<commit_before>var fs = require('fs'),
    path = require('path'),
    https = require('https'),
    crypto = require('crypto'),
    chakram = require('chakram'),
    expect = chakram.expect,
    txf = require('..');

var port = 8700;

var secrets = {
    foo: {
        sender: '',
        receiver: ''
    },
    prot: {
        sender: 'foobar',
        receiver: 'fred bloggs'
    },
    no_keys: {}
};

function make_server(protocol, cb)
{
    var opts;
    if (protocol === 'https')
    {
        opts = {
            key: fs.readFileSync(path.join(__dirname, 'server.key')),
            cert: fs.readFileSync(path.join(__dirname, 'server.pem'))
        };
    }
    var server = require(protocol).createServer(opts);
    server.listen(port, cb);
    return server;
}

function stest(protocol, agent)
{
    var url = protocol + '://localhost:' + port + '/';
describe(protocol, function ()
{

describe('txf', function ()
{
    var server, senders_and_receivers;

    before(function (cb)
    {
        server = make_server(protocol, cb);
        senders_and_receivers = txf(server, secrets);
    });

    after(function (cb)
    {
        server.close(function (err)
        {
            expect(senders_and_receivers.senders.size === 0);
            expect(senders_and_receivers.receivers.size === 0);
            cb(err);
        });
    });

    function test(description, make_put_url, make_get_url)
    {
    describe(description, function ()
    {
        it('should transfer data', function ()
        {
            var get_response = chakram.get(make_get_url('bar'),
                                           { agent: agent });
            expect(get_response).to.have.status(200);
            expect(get_response).to.have.json('hello');
            expect(get_response).to.have.header('content-type', 'application/json');

            var put_response = chakram.put(make_put_url('bar'),
                                           'hello',
                                           { agent: agent });
            expect(put_response).to.have.status(200);

            return chakram.wait();
        });

        it('should support multiple transfers at the same time', function ()
        {
            this.timeout(60 * 1000);

            for (var i = 0; i < 10; i += 1)
            {
                var get_response = chakram.get(make_get_url('bar' + i),
                                               { agent: agent });
                expect(get_response).to.have.status(200);
                expect(get_response).to.have.json('hello' + i);

                var put_response = chakram.put(make_put_url('bar' + i),
                                               'hello' + i,
                                               { agent: agent });
                expect(put_response).to.have.status(200);
            }

            return chakram.wait();
        });

        it('should error if get request is in progress', function ()
        {
            var get_response = chakram.get(make_get_url('bar'),
                                           { agent: agent });
            expect(get_response).to.have.status(200);
            expect(get_response).to.have.json('hello');

            expect(chakram.get(make_get_url('bar'),
                               { agent: agent })).to.have.status(409);

            var put_response = chakram.put(make_put_url('bar'),
                                           'hello',
                                           { agent: agent });
            expect(put_response).to.have.status(200);

            return chakram.wait();
        });

        it('should error if put request is in progress', function ()
        {
            var put_response = chakram.put(make_put_url('bar'),
                                           'hello',
                                           { agent: agent });
            expect(put_response).to.have.status(200);

            expect(chakram.put(make_put_url('bar'),
                               'hello',
                               { agent: agent })).to.have.status(409);

            var get_response = chakram.get(make_get_url('bar'),
                                           { agent: agent });
            expect(get_response).to.have.status(200);
            expect(get_response).to.have.json('hello');

            return chakram.wait();
        });

        it('should support large transfers', function ()
        {
            var buf = crypto.randomBytes(1024 * 1024);

            var put_response = chakram.put(make_put_url('bar'),
                                           buf,
                                           { json: false, agent: agent });
            expect(put_response).to.have.status(200);

            return chakram.all([

            chakram.get(make_get_url('bar'),
                        { encoding: null, agent: agent })
            .then(function (get_response)
            {
                expect(get_response).to.have.status(200);
                expect(get_response).to.have.header('content-type', 'application/octet-stream');
                expect(get_response.body.equals(buf)).to.equal(true);
            }),

            chakram.wait()]);
        });

        it('should error if too many levels in path', function ()
        {
            var get_response = chakram.get(make_get_url('bar/dummy1/dummy2'),
                                           { agent: agent });
            expect(get_response).to.have.status(400);
            return chakram.wait();
        });

        it('should error if namespace unknown', function ()
        {
            var get_response = chakram.get(make_get_url('bar', 'dummy'),
                                           { agent: agent });
            expect(get_response).to.have.status(403);
            return chakram.wait();
        });

        if (description === 'auth')
        {
            it('should error if receiver digest is wrong', function ()
            {
                var get_response = chakram.get(make_put_url('bar'),
                                               { agent: agent });
                expect(get_response).to.have.status(404);
                return chakram.wait();
            });

            it('should error if sender digest is wrong', function ()
            {
                var put_response = chakram.put(make_get_url('bar'),
                                               'hello',
                                               { agent: agent });
                expect(put_response).to.have.status(404);
                return chakram.wait();
            });
        }

        it('should error if namespace has no receiver key', function ()
        {
            var get_response = chakram.get(make_get_url('bar', 'no_keys'),
                                           { agent: agent });
            expect(get_response).to.have.status(403);
            return chakram.wait();
        });

        it('should error if namespace has no sender key', function ()
        {
            var put_response = chakram.put(make_put_url('bar', 'no_keys'),
                                           'hello',
                                           { agent: agent });
            expect(put_response).to.have.status(403);
            return chakram.wait();
        });

        it('should error if request is not put or get', function ()
        {
            var head_response = chakram.head(make_get_url('bar'),
                                             { agent: agent });
            expect(head_response).to.have.status(405);
            return chakram.wait();
        });

        it('should cope with close and end events occurring on request', function ()
        {
            server.on('request', function (request, response)
            {
                request.on('end', function ()
                {
                    this.emit('close');
                });

                response.on('finish', function ()
                {
                    this.emit('close');
                });
            });

            var get_response = chakram.get(make_get_url('bar'),
                                           { agent: agent });
            expect(get_response).to.have.status(200);
            expect(get_response).to.have.json('hello');

            var put_response = chakram.put(make_put_url('bar'),
                                           'hello',
                                           { agent: agent });
            expect(put_response).to.have.status(200);

            return chakram.wait();
        });

        it('should pass on content-type', function ()
        {
            var buf = crypto.randomBytes(1024);

            var put_response = chakram.put(make_put_url('bar'), buf,
            {
                json: false,
                headers: { 'Content-Type': 'dummy1/dummy2' },
                agent: agent
            });
            expect(put_response).to.have.status(200);

            return chakram.all([

            chakram.get(make_get_url('bar'),
                        { encoding: null, agent: agent })
            .then(function (get_response)
            {
                expect(get_response).to.have.status(200);
                expect(get_response).to.have.header('content-type', 'dummy1/dummy2');
                expect(get_response.body.equals(buf)).to.equal(true);
            }),

            chakram.wait()]);
        });
    });
    }

    function make_url_no_auth(path, namespace)
    {
        return url + (namespace || 'foo') + '/' + path;
    }

    test('no auth', make_url_no_auth, make_url_no_auth);

    test('auth', function (path, namespace)
    {
        return url +
               (namespace || 'prot') + '/' +
               crypto.createHmac('sha256', secrets.prot.sender)
                   .update(path)
                   .digest('hex') + '/' +
               path;
    }, function (path, namespace)
    {
        return url +
               (namespace || 'prot') + '/' +
               crypto.createHmac('sha256', secrets.prot.receiver)
                   .update(path)
                   .digest('hex') + '/' +
               path;
    });
});

describe('txf-no-secerts', function ()
{
    var server;

    before(function (cb)
    {
        server = make_server(protocol, cb);
        txf(server);
    });

    after(function (cb)
    {
        server.close(cb);
    });

    it('should error when no secrets have been supplied', function ()
    {
        var get_response = chakram.get(url + 'foo/bar', { agent: agent });
        return expect(get_response).to.have.status(403);
    });
});

});
}

stest('http');
stest('https', new https.Agent(
{
    ca: fs.readFileSync(path.join(__dirname, 'ca.pem'))
}));
<commit_msg>Put num requests back<commit_after>var fs = require('fs'),
    path = require('path'),
    https = require('https'),
    crypto = require('crypto'),
    chakram = require('chakram'),
    expect = chakram.expect,
    txf = require('..');

var port = 8700;

var secrets = {
    foo: {
        sender: '',
        receiver: ''
    },
    prot: {
        sender: 'foobar',
        receiver: 'fred bloggs'
    },
    no_keys: {}
};

function make_server(protocol, cb)
{
    var opts;
    if (protocol === 'https')
    {
        opts = {
            key: fs.readFileSync(path.join(__dirname, 'server.key')),
            cert: fs.readFileSync(path.join(__dirname, 'server.pem'))
        };
    }
    var server = require(protocol).createServer(opts);
    server.listen(port, cb);
    return server;
}

function stest(protocol, agent)
{
    var url = protocol + '://localhost:' + port + '/';
describe(protocol, function ()
{

describe('txf', function ()
{
    var server, senders_and_receivers;

    before(function (cb)
    {
        server = make_server(protocol, cb);
        senders_and_receivers = txf(server, secrets);
    });

    after(function (cb)
    {
        server.close(function (err)
        {
            expect(senders_and_receivers.senders.size === 0);
            expect(senders_and_receivers.receivers.size === 0);
            cb(err);
        });
    });

    function test(description, make_put_url, make_get_url)
    {
    describe(description, function ()
    {
        it('should transfer data', function ()
        {
            var get_response = chakram.get(make_get_url('bar'),
                                           { agent: agent });
            expect(get_response).to.have.status(200);
            expect(get_response).to.have.json('hello');
            expect(get_response).to.have.header('content-type', 'application/json');

            var put_response = chakram.put(make_put_url('bar'),
                                           'hello',
                                           { agent: agent });
            expect(put_response).to.have.status(200);

            return chakram.wait();
        });

        it('should support multiple transfers at the same time', function ()
        {
            this.timeout(60 * 1000);

            for (var i = 0; i < 1000; i += 1)
            {
                var get_response = chakram.get(make_get_url('bar' + i),
                                               { agent: agent });
                expect(get_response).to.have.status(200);
                expect(get_response).to.have.json('hello' + i);

                var put_response = chakram.put(make_put_url('bar' + i),
                                               'hello' + i,
                                               { agent: agent });
                expect(put_response).to.have.status(200);
            }

            return chakram.wait();
        });

        it('should error if get request is in progress', function ()
        {
            var get_response = chakram.get(make_get_url('bar'),
                                           { agent: agent });
            expect(get_response).to.have.status(200);
            expect(get_response).to.have.json('hello');

            expect(chakram.get(make_get_url('bar'),
                               { agent: agent })).to.have.status(409);

            var put_response = chakram.put(make_put_url('bar'),
                                           'hello',
                                           { agent: agent });
            expect(put_response).to.have.status(200);

            return chakram.wait();
        });

        it('should error if put request is in progress', function ()
        {
            var put_response = chakram.put(make_put_url('bar'),
                                           'hello',
                                           { agent: agent });
            expect(put_response).to.have.status(200);

            expect(chakram.put(make_put_url('bar'),
                               'hello',
                               { agent: agent })).to.have.status(409);

            var get_response = chakram.get(make_get_url('bar'),
                                           { agent: agent });
            expect(get_response).to.have.status(200);
            expect(get_response).to.have.json('hello');

            return chakram.wait();
        });

        it('should support large transfers', function ()
        {
            var buf = crypto.randomBytes(1024 * 1024);

            var put_response = chakram.put(make_put_url('bar'),
                                           buf,
                                           { json: false, agent: agent });
            expect(put_response).to.have.status(200);

            return chakram.all([

            chakram.get(make_get_url('bar'),
                        { encoding: null, agent: agent })
            .then(function (get_response)
            {
                expect(get_response).to.have.status(200);
                expect(get_response).to.have.header('content-type', 'application/octet-stream');
                expect(get_response.body.equals(buf)).to.equal(true);
            }),

            chakram.wait()]);
        });

        it('should error if too many levels in path', function ()
        {
            var get_response = chakram.get(make_get_url('bar/dummy1/dummy2'),
                                           { agent: agent });
            expect(get_response).to.have.status(400);
            return chakram.wait();
        });

        it('should error if namespace unknown', function ()
        {
            var get_response = chakram.get(make_get_url('bar', 'dummy'),
                                           { agent: agent });
            expect(get_response).to.have.status(403);
            return chakram.wait();
        });

        if (description === 'auth')
        {
            it('should error if receiver digest is wrong', function ()
            {
                var get_response = chakram.get(make_put_url('bar'),
                                               { agent: agent });
                expect(get_response).to.have.status(404);
                return chakram.wait();
            });

            it('should error if sender digest is wrong', function ()
            {
                var put_response = chakram.put(make_get_url('bar'),
                                               'hello',
                                               { agent: agent });
                expect(put_response).to.have.status(404);
                return chakram.wait();
            });
        }

        it('should error if namespace has no receiver key', function ()
        {
            var get_response = chakram.get(make_get_url('bar', 'no_keys'),
                                           { agent: agent });
            expect(get_response).to.have.status(403);
            return chakram.wait();
        });

        it('should error if namespace has no sender key', function ()
        {
            var put_response = chakram.put(make_put_url('bar', 'no_keys'),
                                           'hello',
                                           { agent: agent });
            expect(put_response).to.have.status(403);
            return chakram.wait();
        });

        it('should error if request is not put or get', function ()
        {
            var head_response = chakram.head(make_get_url('bar'),
                                             { agent: agent });
            expect(head_response).to.have.status(405);
            return chakram.wait();
        });

        it('should cope with close and end events occurring on request', function ()
        {
            server.on('request', function (request, response)
            {
                request.on('end', function ()
                {
                    this.emit('close');
                });

                response.on('finish', function ()
                {
                    this.emit('close');
                });
            });

            var get_response = chakram.get(make_get_url('bar'),
                                           { agent: agent });
            expect(get_response).to.have.status(200);
            expect(get_response).to.have.json('hello');

            var put_response = chakram.put(make_put_url('bar'),
                                           'hello',
                                           { agent: agent });
            expect(put_response).to.have.status(200);

            return chakram.wait();
        });

        it('should pass on content-type', function ()
        {
            var buf = crypto.randomBytes(1024);

            var put_response = chakram.put(make_put_url('bar'), buf,
            {
                json: false,
                headers: { 'Content-Type': 'dummy1/dummy2' },
                agent: agent
            });
            expect(put_response).to.have.status(200);

            return chakram.all([

            chakram.get(make_get_url('bar'),
                        { encoding: null, agent: agent })
            .then(function (get_response)
            {
                expect(get_response).to.have.status(200);
                expect(get_response).to.have.header('content-type', 'dummy1/dummy2');
                expect(get_response.body.equals(buf)).to.equal(true);
            }),

            chakram.wait()]);
        });
    });
    }

    function make_url_no_auth(path, namespace)
    {
        return url + (namespace || 'foo') + '/' + path;
    }

    test('no auth', make_url_no_auth, make_url_no_auth);

    test('auth', function (path, namespace)
    {
        return url +
               (namespace || 'prot') + '/' +
               crypto.createHmac('sha256', secrets.prot.sender)
                   .update(path)
                   .digest('hex') + '/' +
               path;
    }, function (path, namespace)
    {
        return url +
               (namespace || 'prot') + '/' +
               crypto.createHmac('sha256', secrets.prot.receiver)
                   .update(path)
                   .digest('hex') + '/' +
               path;
    });
});

describe('txf-no-secerts', function ()
{
    var server;

    before(function (cb)
    {
        server = make_server(protocol, cb);
        txf(server);
    });

    after(function (cb)
    {
        server.close(cb);
    });

    it('should error when no secrets have been supplied', function ()
    {
        var get_response = chakram.get(url + 'foo/bar', { agent: agent });
        return expect(get_response).to.have.status(403);
    });
});

});
}

stest('http');
stest('https', new https.Agent(
{
    ca: fs.readFileSync(path.join(__dirname, 'ca.pem'))
}));
<|endoftext|>


<commit_before>module.exports = function(grunt) {

	require('load-grunt-tasks')(grunt);

	grunt.initConfig({
		sass: {
			compile: {
				options: {
					style: 'compressed'
				},
				files: {
					'styles/screen.css': 'styles/screen.scss'
				}
			}
		},
		autoprefixer: {
			prefix: {
				src: 'styles/screen.css'
			}
		},
		jekyll: {
			full: {},
			limit: {
				options: {
					limit_posts: 150
				}
			}
		},
		htmlmin: {
			site: {
				options: {
					removeComments: true,
					collapseWhitespace: true
				},
				expand: true,
				cwd: '_site/',
				src: '**/*.html',
				dest: '_site/'
			}
		},
		imagemin: {
			options: {
				cache: false
			},
			site: {
				expand: true,
				cwd: '_site/',
				src: '**/*.{png,jpg,gif}',
				dest: '_site/'
			}
		},
		watch: {
			styles: {
				files: 'styles/*.scss',
				tasks: ['sass', 'autoprefixer', 'copy']
			},
			limit: {
				files: [
					'**',
					'!_site/**',
					'!node_modules/**',
					'!.sass-cache/**',
					'!styles/*',
					'!Gruntfile.js',
					'!README.md',
					'!package.json',
					'!.git/**'
				],
				tasks: ['jekyll:limit', 'htmlmin']
			}
		},
		copy: {
			css: {
				files: {
					'_site/styles/screen.css' : 'styles/screen.css'
				}
			}
		},
		rsync: {
			options: {
				args: [
					'--delete', // delete extraneous files on the receiving side
					'--times', // preserve modification times…
					'--omit-dir-times', // …except for directories
					'--compress', // compress data during the transfer
					'--verbose' // increase verbosity
				],
				exclude: ['.DS_Store'],
				recursive: true
			},
			deploy: {
				options: {
					src: '_site/',
					dest: '/var/www/html/',
					host: '54.213.240.91'
				}
			}
		}
	});

	grunt.registerTask('default', function() {
		grunt.log.subhead('Please use following commangs');
		grunt.log.writeln('• grunt watch  — for quick dev build');
		grunt.log.writeln('• grunt build  — for full site build');
		grunt.log.writeln('• grunt deploy — for build & deploy');
	});

	grunt.registerTask('build', [
		'sass',
		'autoprefixer',
		'jekyll:full',
		'htmlmin',
		'imagemin'
	]);

	grunt.registerTask('deploy', ['build', 'rsync']);

};
<commit_msg>Making it harder to build & deploy without testing<commit_after>module.exports = function(grunt) {

	require('load-grunt-tasks')(grunt);

	grunt.initConfig({
		sass: {
			compile: {
				options: {
					style: 'compressed'
				},
				files: {
					'styles/screen.css': 'styles/screen.scss'
				}
			}
		},
		autoprefixer: {
			prefix: {
				src: 'styles/screen.css'
			}
		},
		jekyll: {
			full: {},
			limit: {
				options: {
					limit_posts: 150
				}
			}
		},
		htmlmin: {
			site: {
				options: {
					removeComments: true,
					collapseWhitespace: true
				},
				expand: true,
				cwd: '_site/',
				src: '**/*.html',
				dest: '_site/'
			}
		},
		imagemin: {
			options: {
				cache: false
			},
			site: {
				expand: true,
				cwd: '_site/',
				src: '**/*.{png,jpg,gif}',
				dest: '_site/'
			}
		},
		watch: {
			styles: {
				files: 'styles/*.scss',
				tasks: ['sass', 'autoprefixer', 'copy']
			},
			limit: {
				files: [
					'**',
					'!_site/**',
					'!node_modules/**',
					'!.sass-cache/**',
					'!styles/*',
					'!Gruntfile.js',
					'!README.md',
					'!package.json',
					'!.git/**'
				],
				tasks: ['jekyll:limit', 'htmlmin']
			}
		},
		copy: {
			css: {
				files: {
					'_site/styles/screen.css' : 'styles/screen.css'
				}
			}
		},
		rsync: {
			options: {
				args: [
					'--delete', // delete extraneous files on the receiving side
					'--times', // preserve modification times…
					'--omit-dir-times', // …except for directories
					'--compress', // compress data during the transfer
					'--verbose' // increase verbosity
				],
				exclude: ['.DS_Store'],
				recursive: true
			},
			deploy: {
				options: {
					src: '_site/',
					dest: '/var/www/html/',
					host: '54.213.240.91'
				}
			}
		}
	});

	grunt.registerTask('default', function() {
		grunt.log.subhead('Please use following commangs');
		grunt.log.writeln('• grunt watch  — for quick dev build');
		grunt.log.writeln('• grunt build  — for full site build');
		grunt.log.writeln('• grunt deploy — for build & deploy');
	});

	grunt.registerTask('build', [
		'sass',
		'autoprefixer',
		'jekyll:full',
		'htmlmin',
		'imagemin'
	]);

	grunt.registerTask('deploy', ['rsync']);

};
<|endoftext|>


<commit_before>(function() {
  'use strict';
  angular.module('civic.events.variants')
    .controller('MyVariantInfoController', MyVariantInfoController)
    .directive('myVariantInfo', function () {
      return {
        restrict: 'E',
        scope: {
          variantInfo: '='
        },
        controller: 'MyVariantInfoController',
        templateUrl: 'app/views/events/variants/summary/myVariantInfo.tpl.html'
      };
    });

  // @ngInject
  function MyVariantInfoController($scope, ngDialog, _) {
    var ctrl = $scope.ctrl = {};
    ctrl.variantInfo = $scope.variantInfo;

    // MyVariant.info returns some fields as strings OR arrays, this
    // converts strings to a single-element array
    var multiTypeFields = [
      'cadd.consdetail',
      'cadd.consequence',
      'clinvar.hgvs.coding',
      'clinvar.hgvs.genomic',
      'clinvar.hgvs.non-coding',
      'emv.hgvs'
    ];
    _.each(multiTypeFields, function(field) {
      var val = _.get(ctrl.variantInfo,field);
      if (_.isString(val)) { _.set(ctrl.variantInfo, field, [val]); }
    });

    // calculate adjusted allele frequency
    if(!_.isUndefined(ctrl.variantInfo.exac)) {
      if(!_.isUndefined(ctrl.variantInfo.exac.an) && !_.isUndefined(ctrl.variantInfo.exac.ac)) {
        ctrl.variantInfo.exac.adj_allele_freq = _.round(ctrl.variantInfo.exac.ac.ac_adj / ctrl.variantInfo.exac.an.an_adj, 5);
      }
    }

    // replace ampersands with commas in SnpEff Effect strings
    if(!_.isUndefined(ctrl.variantInfo.snpeff) && !_.isUndefined(ctrl.variantInfo.snpeff.ann[0])) {
      if(!_.isUndefined(ctrl.variantInfo.snpeff.ann[0])) {
        ctrl.variantInfo.snpeff.ann[0].effect = ctrl.variantInfo.snpeff.ann[0].effect.replace(/_/g, ' ');
        ctrl.variantInfo.snpeff.ann[0].effect = ctrl.variantInfo.snpeff.ann[0].effect.replace(/&/g, ', ');
      }
    }

    ctrl.popupOptions = {
      template: 'app/views/events/variants/summary/myVariantInfoDialog.tpl.html',
      scope: $scope
    };

    ctrl.openDialog = function() {
      if(_.has(ctrl.dialog, 'id')) {
        ctrl.closeDialog().then(function() {
          ctrl.dialog = ngDialog.open(ctrl.popupOptions);
        });
      } else {
        ctrl.dialog = ngDialog.open(ctrl.popupOptions);
      }
      return ctrl.dialog;
    };

    ctrl.closeDialog = function() {
      ctrl.dialog.close();
      return ctrl.dialog.closePromise.then(function() { _.omit(ctrl, 'dialog'); } );
    };
  }

})();
<commit_msg>MyVariantInfo now handles ambiguity in the return type from database<commit_after>(function() {
  'use strict';
  angular.module('civic.events.variants')
    .controller('MyVariantInfoController', MyVariantInfoController)
    .directive('myVariantInfo', function () {
      return {
        restrict: 'E',
        scope: {
          variantInfo: '='
        },
        controller: 'MyVariantInfoController',
        templateUrl: 'app/views/events/variants/summary/myVariantInfo.tpl.html'
      };
    });

  // @ngInject
  function MyVariantInfoController($scope, ngDialog, _) {
    var ctrl = $scope.ctrl = {};
    ctrl.variantInfo = $scope.variantInfo;

    // MyVariant.info returns some fields as strings OR arrays, this
    // converts strings to a single-element array
    var multiTypeFields = [
      'cadd.consdetail',
      'cadd.consequence',
      'clinvar.hgvs.coding',
      'clinvar.hgvs.genomic',
      'clinvar.hgvs.non-coding',
      'emv.hgvs'
    ];
    _.each(multiTypeFields, function(field) {
      var val = _.get(ctrl.variantInfo,field);
      if (_.isString(val)) { _.set(ctrl.variantInfo, field, [val]); }
    });

    // calculate adjusted allele frequency
    if(!_.isUndefined(ctrl.variantInfo.exac)) {
      if(!_.isUndefined(ctrl.variantInfo.exac.an) && !_.isUndefined(ctrl.variantInfo.exac.ac)) {
        //ctrl.variantInfo.exac.adj_allele_freq = _.round(ctrl.variantInfo.exac.ac.ac_adj / ctrl.variantInfo.exac.an.an_adj, 5);
        ctrl.variantInfo.exac.adj_allele_freq = _.round(
          _.last(_.flatten(_.values(ctrl.variantInfo.exac.ac))) / _.last(_.flatten(_.values(ctrl.variantInfo.exac.an))),
          5
        );
      }
    }

    // replace ampersands with commas in SnpEff Effect strings
    if(!_.isUndefined(ctrl.variantInfo.snpeff) && !_.isUndefined(ctrl.variantInfo.snpeff.ann[0])) {
      if(!_.isUndefined(ctrl.variantInfo.snpeff.ann[0])) {
        ctrl.variantInfo.snpeff.ann[0].effect = ctrl.variantInfo.snpeff.ann[0].effect.replace(/_/g, ' ');
        ctrl.variantInfo.snpeff.ann[0].effect = ctrl.variantInfo.snpeff.ann[0].effect.replace(/&/g, ', ');
      }
    }

    ctrl.popupOptions = {
      template: 'app/views/events/variants/summary/myVariantInfoDialog.tpl.html',
      scope: $scope
    };

    ctrl.openDialog = function() {
      if(_.has(ctrl.dialog, 'id')) {
        ctrl.closeDialog().then(function() {
          ctrl.dialog = ngDialog.open(ctrl.popupOptions);
        });
      } else {
        ctrl.dialog = ngDialog.open(ctrl.popupOptions);
      }
      return ctrl.dialog;
    };

    ctrl.closeDialog = function() {
      ctrl.dialog.close();
      return ctrl.dialog.closePromise.then(function() { _.omit(ctrl, 'dialog'); } );
    };
  }

})();
<|endoftext|>


<commit_before>module.exports = function (grunt) {
    'use strict';

    var config = {
        app: 'app',
        dist: 'dist'
    };

    require('load-grunt-tasks')(grunt);
    require('time-grunt')(grunt);
    grunt.task.loadTasks('tasks');

    var LIVERELOAD_PORT = 35729;
    var lrSnippet = require('connect-livereload')({
        port: LIVERELOAD_PORT
    });
    var mountFolder = function (connect, dir) {
        return connect.static(require('path').resolve(dir));
    };
    var modRewrite = require('connect-modrewrite');

    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        config: config,
        watch: {
            less: {
                files:  ['<%= config.app %>/styles/{,*/}*.less'],
                tasks: ['less']
            },
            livereload: {
                options: {
                    livereload: LIVERELOAD_PORT
                },
                files: [
                    '<%= config.app %>/{,*/}*.html',
                    '{.tmp,<%= config.app %>}/styles/{,*/}*.css',
                    '{.tmp,<%= config.app %>}/scripts/{,*/}*.js',
                    '<%= config.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
                ]
            }
        },
        //Connect
        connect: {
            options: {
                port: 9000,
                hostname: '0.0.0.0'
            },
            livereload: {
                options: {
                    middleware: function (connect) {
                        return [
                            lrSnippet,
                            modRewrite([
                                '!\\.html|\\.xml|\\images|\\.js|\\.css|\\.png|\\.jpg|\\.woff|\\.ttf|\\.svg|\\.ico /index.html [L]'
                            ]),
                            mountFolder(connect, '.tmp'),
                            mountFolder(connect, config.app)
                        ];
                    }
                }
            },
            test: {
                options: {
                    middleware: function (connect) {
                        return [
                            mountFolder(connect, '.tmp'),
                            mountFolder(connect, 'test')
                        ];
                    }
                }
            }
        },
        open: {
            server: {
                url: 'http://localhost:<%= connect.options.port %>'
            }
        },
        less: {
            dist: {
                options: {
                },
                files: {
                    '<%= config.app %>/styles/index.css': ['<%= config.app %>/styles/index.less']
                }
            }
        },
        peg: {
            options: { trackLineAndColumn: true },
            excelGrammar : {
                src: 'pegjs/excelGrammar.pegjs',
                dest: '<%= config.app %>/modules/excel-parser.js',
                angular: {
                    module: 'excel-parser',
                    factory: 'ExcelParser'
                }
            },
            formulaGrammar : {
                src: 'pegjs/formulaGrammar.pegjs',
                dest: '<%= config.app %>/modules/formula-parser.js',
                angular: {
                    module: 'formula-parser',
                    factory: 'FormulaParser'
                }
            }
        },
        swagger: {
            options: {
                apis: [
                    {
                        swagger: 'swagger/reports.json',
                        module: 'report-api',
                        newModule: true,
                        service: 'report-api'
                    }
                ],
                dest: '<%= config.app %>/modules'
            },
            all: {}
        },
        clean: {
            pre: ['dist/', 'coverage/', 'out/'],
            post: []
        },
        jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            src: ['Gruntfile.js', '<%= config.app %>/modules/**/*.js', 'tests/*.js', 'tasks/*.js'],
        },
        karma: {
            options: {
                configFile: './karma.conf.js'
            },
            dev: {
                browsers: ['Chrome'],
                autoWatch: true,
                singleRun: false
            },
            '1.2.9': {
                options: {
                    files: [
                        '<%= config.app %>/bower_components/angular/angular.js',
                        '<%= config.app %>/bower_components/angular-mocks-1.2.9/angular-mocks.js',
                        '<%= config.app %>/modules/excel-parser.js',
                        '<%= config.app %>/modules/formula-parser.js',
                        '<%= config.app %>/modules/report-api.js',
                        '<%= config.app %>/modules/report-model.js',
                        'tests/unit/karma.start.js',
                        'tests/unit/*.js'
                    ]
                }
            }
        },
        coveralls: {
            options: {
                'coverage_dir': 'coverage'
            }
        },
        protractor: {
            options: {
                configFile: 'node_modules/protractor/referenceConf.js', // Default config file
                keepAlive: true, // If false, the grunt process stops when the test fails.
                noColor: false, // If true, protractor will not use colors in its output.
                args: {}
            },
            all: {
                options: {
                    //configFile: "e2e.conf.js", // Target-specific config file
                    args: {
                        'specs': ['node_modules/protractor/example/example_spec.js']
                    } // Target-specific arguments
                }
            }
        }
    });

    grunt.registerTask('server', function () {
        grunt.task.run([
            'peg',
            'swagger',
            'less',
            'connect:livereload',
            'open',
            'watch'
        ]);
    });

    grunt.registerTask('test', ['clean:pre', 'less', 'karma:1.2.9', 'clean:post', 'protractor']);
    grunt.registerTask('build', ['clean:pre', 'peg', 'swagger']);
    grunt.registerTask('default', ['jshint', 'build', 'test']);
};
<commit_msg>Fix protractor configuration location<commit_after>module.exports = function (grunt) {
    'use strict';

    var config = {
        app: 'app',
        dist: 'dist'
    };

    require('load-grunt-tasks')(grunt);
    require('time-grunt')(grunt);
    grunt.task.loadTasks('tasks');

    var LIVERELOAD_PORT = 35729;
    var lrSnippet = require('connect-livereload')({
        port: LIVERELOAD_PORT
    });
    var mountFolder = function (connect, dir) {
        return connect.static(require('path').resolve(dir));
    };
    var modRewrite = require('connect-modrewrite');

    // Project configuration.
    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),
        config: config,
        watch: {
            less: {
                files:  ['<%= config.app %>/styles/{,*/}*.less'],
                tasks: ['less']
            },
            livereload: {
                options: {
                    livereload: LIVERELOAD_PORT
                },
                files: [
                    '<%= config.app %>/{,*/}*.html',
                    '{.tmp,<%= config.app %>}/styles/{,*/}*.css',
                    '{.tmp,<%= config.app %>}/scripts/{,*/}*.js',
                    '<%= config.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
                ]
            }
        },
        //Connect
        connect: {
            options: {
                port: 9000,
                hostname: '0.0.0.0'
            },
            livereload: {
                options: {
                    middleware: function (connect) {
                        return [
                            lrSnippet,
                            modRewrite([
                                '!\\.html|\\.xml|\\images|\\.js|\\.css|\\.png|\\.jpg|\\.woff|\\.ttf|\\.svg|\\.ico /index.html [L]'
                            ]),
                            mountFolder(connect, '.tmp'),
                            mountFolder(connect, config.app)
                        ];
                    }
                }
            },
            test: {
                options: {
                    middleware: function (connect) {
                        return [
                            mountFolder(connect, '.tmp'),
                            mountFolder(connect, 'test')
                        ];
                    }
                }
            }
        },
        open: {
            server: {
                url: 'http://localhost:<%= connect.options.port %>'
            }
        },
        less: {
            dist: {
                options: {
                },
                files: {
                    '<%= config.app %>/styles/index.css': ['<%= config.app %>/styles/index.less']
                }
            }
        },
        peg: {
            options: { trackLineAndColumn: true },
            excelGrammar : {
                src: 'pegjs/excelGrammar.pegjs',
                dest: '<%= config.app %>/modules/excel-parser.js',
                angular: {
                    module: 'excel-parser',
                    factory: 'ExcelParser'
                }
            },
            formulaGrammar : {
                src: 'pegjs/formulaGrammar.pegjs',
                dest: '<%= config.app %>/modules/formula-parser.js',
                angular: {
                    module: 'formula-parser',
                    factory: 'FormulaParser'
                }
            }
        },
        swagger: {
            options: {
                apis: [
                    {
                        swagger: 'swagger/reports.json',
                        module: 'report-api',
                        newModule: true,
                        service: 'report-api'
                    }
                ],
                dest: '<%= config.app %>/modules'
            },
            all: {}
        },
        clean: {
            pre: ['dist/', 'coverage/', 'out/'],
            post: []
        },
        jshint: {
            options: {
                jshintrc: '.jshintrc'
            },
            src: ['Gruntfile.js', '<%= config.app %>/modules/**/*.js', 'tests/*.js', 'tasks/*.js'],
        },
        karma: {
            options: {
                configFile: './karma.conf.js'
            },
            dev: {
                browsers: ['Chrome'],
                autoWatch: true,
                singleRun: false
            },
            '1.2.9': {
                options: {
                    files: [
                        '<%= config.app %>/bower_components/angular/angular.js',
                        '<%= config.app %>/bower_components/angular-mocks-1.2.9/angular-mocks.js',
                        '<%= config.app %>/modules/excel-parser.js',
                        '<%= config.app %>/modules/formula-parser.js',
                        '<%= config.app %>/modules/report-api.js',
                        '<%= config.app %>/modules/report-model.js',
                        'tests/unit/karma.start.js',
                        'tests/unit/*.js'
                    ]
                }
            }
        },
        coveralls: {
            options: {
                'coverage_dir': 'coverage'
            }
        },
        protractor: {
            options: {
                configFile: 'node_modules/grunt-protractor-runner/node_modules/protractor/referenceConf.js', // Default config file
                keepAlive: true, // If false, the grunt process stops when the test fails.
                noColor: false, // If true, protractor will not use colors in its output.
                args: {}
            },
            all: {
                options: {
                    //configFile: "e2e.conf.js", // Target-specific config file
                    args: {
                        'specs': ['node_modules/protractor/example/example_spec.js']
                    } // Target-specific arguments
                }
            }
        }
    });

    grunt.registerTask('server', function () {
        grunt.task.run([
            'peg',
            'swagger',
            'less',
            'connect:livereload',
            'open',
            'watch'
        ]);
    });

    grunt.registerTask('test', ['clean:pre', 'less', 'karma:1.2.9', 'clean:post', 'protractor']);
    grunt.registerTask('build', ['clean:pre', 'peg', 'swagger']);
    grunt.registerTask('default', ['jshint', 'build', 'test']);
};
<|endoftext|>


<commit_before>GV.helpers = _.extend(GV.helpers, {
  parseURL: function(url) {
    var partials;

    if(url)
      partials = url.split('/')[2].split(':');

    return {
      ip: partials && partials[0] || null,
      port: partials && partials[1] || null
    };
  },

  /**
   * Returns Meteor user id if present, else the offline users id
   */
  userId: function(id) {
    var offlineUser = GV.collections.OfflineUsers.find({}).fetch()[0];
    var offlineUserId = offlineUser && offlineUser._id;

    return id || _.defaults({ _id: offlineUserId }, { _id: "offlineuser" })._id;
  },

  // TODO: fix this

  /**
   * Renders a page if logged in, else rendering another page
   * @param {String} page - the page to render if logged in
   * @param {String} elsePage - the page to render if not logged in
   */
  redirectIfLoggedIn: function(page, elsePage) {

    var parsedURL = GV.helpers.parseURL(Router.current().router.url(page));
    var constructedURL = "http://" + parsedURL.ip + ":" + parsedURL.port + "/";

    if(constructedURL === "http://localhost:3000/") {
      console.log("Local mode...");
      this.render(page);
    } else {
      console.log("Remote mode...");
      if(Meteor.user()) {
        this.render(page);
      } else {
        this.render(elsePage);
      }
    }
  },

  /**
   * Redirects to a page if not logged in
   * @param {String} page - the page to redirect to
   */
  redirectIfNotLoggedIn: function(page) {
    var parsedURL = GV.helpers.parseURL(Router.current().router.url(page));
    var constructedURL = "http://" + parsedURL.ip + ":" + parsedURL.port + "/";

    if(constructedURL === "http://localhost:3000/") {
      this.render();
    } else {
      if(!Meteor.user()) {
        this.render(page);
      } else {
        this.render();
      }
    }
  }

});
<commit_msg>Fixes subscription problem.<commit_after>GV.helpers = _.extend(GV.helpers, {
  parseURL: function(url) {
    var partials;

    if(url)
      partials = url.split('/')[2].split(':');

    return {
      ip: partials && partials[0] || null,
      port: partials && partials[1] || null
    };
  },

  /**
   * Returns Meteor user id if present, else the offline users id
   */
  userId: function(id) {
    var offlineUser = GV.collections.OfflineUsers.find({}).fetch()[0];
    var offlineUserId = offlineUser && offlineUser._id;

    return id || _.defaults({ _id: offlineUserId }, { _id: "offlineuser" })._id;
  },

  // TODO: fix this

  /**
   * Renders a page if logged in, else rendering another page
   * @param {String} page - the page to render if logged in
   * @param {String} elsePage - the page to render if not logged in
   */
  redirectIfLoggedIn: function(page, elsePage) {

    var parsedURL = GV.helpers.parseURL(Router.current().router.url(page));
    var constructedURL = "http://" + parsedURL.ip + ":" + parsedURL.port + "/";

    if(constructedURL === "http://localhost:3000/") {
      console.log("Local mode...");
      this.redirect(page);
    } else {
      console.log("Remote mode...");
      if(Meteor.user()) {
        this.redirect(page);
      } else {
        this.render(elsePage);
      }
    }
  },

  /**
   * Redirects to a page if not logged in
   * @param {String} page - the page to redirect to
   */
  redirectIfNotLoggedIn: function(page) {
    var parsedURL = GV.helpers.parseURL(Router.current().router.url(page));
    var constructedURL = "http://" + parsedURL.ip + ":" + parsedURL.port + "/";

    if(constructedURL === "http://localhost:3000/") {
      this.render();
    } else {
      if(!Meteor.user()) {
        this.redirect(page);
      } else {
        this.render();
      }
    }
  }

});
<|endoftext|>


<commit_before>'use strict';
/**
 * Base prompt implementation
 * Should be extended by prompt types.
 */
const _ = {
  assign: require('lodash/assign'),
  defaults: require('lodash/defaults'),
  clone: require('lodash/clone'),
};
const chalk = require('chalk');
const runAsync = require('run-async');
const { filter, flatMap, share, take, takeUntil } = require('rxjs/operators');
const Choices = require('../objects/choices');
const ScreenManager = require('../utils/screen-manager');

class Prompt {
  constructor(question, rl, answers) {
    // Setup instance defaults property
    _.assign(this, {
      answers,
      status: 'pending',
    });

    // Set defaults prompt options
    this.opt = _.defaults(_.clone(question), {
      validate: () => true,
      validatingText: '',
      filter: (val) => val,
      filteringText: '',
      when: () => true,
      suffix: '',
      prefix: chalk.green('?'),
    });

    // Make sure name is present
    if (!this.opt.name) {
      this.throwParamError('name');
    }

    // Set default message if no message defined
    if (!this.opt.message) {
      this.opt.message = this.opt.name + ':';
    }

    // Normalize choices
    if (Array.isArray(this.opt.choices)) {
      this.opt.choices = new Choices(this.opt.choices, answers);
    }

    this.rl = rl;
    this.screen = new ScreenManager(this.rl);
  }

  /**
   * Start the Inquiry session and manage output value filtering
   * @return {Promise}
   */

  run() {
    return new Promise((resolve, reject) => {
      this._run(
        (value) => resolve(value),
        (error) => reject(error)
      );
    });
  }

  // Default noop (this one should be overwritten in prompts)
  _run(cb) {
    cb();
  }

  /**
   * Throw an error telling a required parameter is missing
   * @param  {String} name Name of the missing param
   * @return {Throw Error}
   */

  throwParamError(name) {
    throw new Error('You must provide a `' + name + '` parameter');
  }

  /**
   * Called when the UI closes. Override to do any specific cleanup necessary
   */
  close() {
    this.screen.releaseCursor();
  }

  /**
   * Run the provided validation method each time a submit event occur.
   * @param  {Rx.Observable} submit - submit event flow
   * @return {Object}        Object containing two observables: `success` and `error`
   */
  handleSubmitEvents(submit) {
    const self = this;
    const validate = runAsync(this.opt.validate);
    const asyncFilter = runAsync(this.opt.filter);
    const validation = submit.pipe(
      flatMap((value) => {
        this.startSpinner(value, this.opt.filteringText);
        return asyncFilter(value, self.answers).then(
          (filteredValue) => {
            this.startSpinner(filteredValue, this.opt.validatingText);
            return validate(filteredValue, self.answers).then(
              (isValid) => ({ isValid, value: filteredValue }),
              (err) => ({ isValid: err, value: filteredValue })
            );
          },
          (err) => ({ isValid: err })
        );
      }),
      share()
    );

    const success = validation.pipe(
      filter((state) => state.isValid === true),
      take(1)
    );
    const error = validation.pipe(
      filter((state) => state.isValid !== true),
      takeUntil(success)
    );

    return {
      success,
      error,
    };
  }

  startSpinner(value, bottomContent) {
    value = this.getSpinningValue(value);
    // If the question will spin, cut off the prefix (for layout purposes)
    const content = bottomContent
      ? this.getQuestion() + value
      : this.getQuestion().slice(this.opt.prefix.length + 1) + value;

    this.screen.renderWithSpinner(content, bottomContent);
  }

  /**
   * Allow override, e.g. for password prompts
   * See: https://github.com/SBoudrias/Inquirer.js/issues/1022
   *
   * @return {String} value to display while spinning
   */
  getSpinningValue(value) {
    return value;
  }

  /**
   * Generate the prompt question string
   * @return {String} prompt question string
   */
  getQuestion() {
    let message =
      this.opt.prefix +
      ' ' +
      chalk.bold(this.opt.message) +
      this.opt.suffix +
      chalk.reset(' ');

    // Append the default if available, and if question isn't touched/answered
    if (
      this.opt.default != null &&
      this.status !== 'touched' &&
      this.status !== 'answered'
    ) {
      // If default password is supplied, hide it
      if (this.opt.type === 'password') {
        message += chalk.italic.dim('[hidden] ');
      } else {
        message += chalk.dim('(' + this.opt.default + ') ');
      }
    }

    return message;
  }
}

module.exports = Prompt;
<commit_msg>Add prefix extra space only when not empty (#1033)<commit_after>'use strict';
/**
 * Base prompt implementation
 * Should be extended by prompt types.
 */
const _ = {
  assign: require('lodash/assign'),
  defaults: require('lodash/defaults'),
  clone: require('lodash/clone'),
};
const chalk = require('chalk');
const runAsync = require('run-async');
const { filter, flatMap, share, take, takeUntil } = require('rxjs/operators');
const Choices = require('../objects/choices');
const ScreenManager = require('../utils/screen-manager');

class Prompt {
  constructor(question, rl, answers) {
    // Setup instance defaults property
    _.assign(this, {
      answers,
      status: 'pending',
    });

    // Set defaults prompt options
    this.opt = _.defaults(_.clone(question), {
      validate: () => true,
      validatingText: '',
      filter: (val) => val,
      filteringText: '',
      when: () => true,
      suffix: '',
      prefix: chalk.green('?'),
    });

    // Make sure name is present
    if (!this.opt.name) {
      this.throwParamError('name');
    }

    // Set default message if no message defined
    if (!this.opt.message) {
      this.opt.message = this.opt.name + ':';
    }

    // Normalize choices
    if (Array.isArray(this.opt.choices)) {
      this.opt.choices = new Choices(this.opt.choices, answers);
    }

    this.rl = rl;
    this.screen = new ScreenManager(this.rl);
  }

  /**
   * Start the Inquiry session and manage output value filtering
   * @return {Promise}
   */

  run() {
    return new Promise((resolve, reject) => {
      this._run(
        (value) => resolve(value),
        (error) => reject(error)
      );
    });
  }

  // Default noop (this one should be overwritten in prompts)
  _run(cb) {
    cb();
  }

  /**
   * Throw an error telling a required parameter is missing
   * @param  {String} name Name of the missing param
   * @return {Throw Error}
   */

  throwParamError(name) {
    throw new Error('You must provide a `' + name + '` parameter');
  }

  /**
   * Called when the UI closes. Override to do any specific cleanup necessary
   */
  close() {
    this.screen.releaseCursor();
  }

  /**
   * Run the provided validation method each time a submit event occur.
   * @param  {Rx.Observable} submit - submit event flow
   * @return {Object}        Object containing two observables: `success` and `error`
   */
  handleSubmitEvents(submit) {
    const self = this;
    const validate = runAsync(this.opt.validate);
    const asyncFilter = runAsync(this.opt.filter);
    const validation = submit.pipe(
      flatMap((value) => {
        this.startSpinner(value, this.opt.filteringText);
        return asyncFilter(value, self.answers).then(
          (filteredValue) => {
            this.startSpinner(filteredValue, this.opt.validatingText);
            return validate(filteredValue, self.answers).then(
              (isValid) => ({ isValid, value: filteredValue }),
              (err) => ({ isValid: err, value: filteredValue })
            );
          },
          (err) => ({ isValid: err })
        );
      }),
      share()
    );

    const success = validation.pipe(
      filter((state) => state.isValid === true),
      take(1)
    );
    const error = validation.pipe(
      filter((state) => state.isValid !== true),
      takeUntil(success)
    );

    return {
      success,
      error,
    };
  }

  startSpinner(value, bottomContent) {
    value = this.getSpinningValue(value);
    // If the question will spin, cut off the prefix (for layout purposes)
    const content = bottomContent
      ? this.getQuestion() + value
      : this.getQuestion().slice(this.opt.prefix.length + 1) + value;

    this.screen.renderWithSpinner(content, bottomContent);
  }

  /**
   * Allow override, e.g. for password prompts
   * See: https://github.com/SBoudrias/Inquirer.js/issues/1022
   *
   * @return {String} value to display while spinning
   */
  getSpinningValue(value) {
    return value;
  }

  /**
   * Generate the prompt question string
   * @return {String} prompt question string
   */
  getQuestion() {
    let message =
      (this.opt.prefix ? this.opt.prefix + ' ' : '') +
      chalk.bold(this.opt.message) +
      this.opt.suffix +
      chalk.reset(' ');

    // Append the default if available, and if question isn't touched/answered
    if (
      this.opt.default != null &&
      this.status !== 'touched' &&
      this.status !== 'answered'
    ) {
      // If default password is supplied, hide it
      if (this.opt.type === 'password') {
        message += chalk.italic.dim('[hidden] ');
      } else {
        message += chalk.dim('(' + this.opt.default + ') ');
      }
    }

    return message;
  }
}

module.exports = Prompt;
<|endoftext|>


<commit_before>var hiredis = require("./build/default/hiredis"),
    net = require("net");

exports.Reader = hiredis.Reader;
exports.createConnection = function(port, host) {
    var s = new net.Stream();
    var r = new hiredis.Reader();
    var _write = s.write;
    s.connect(port || 6379, host);

    s.write = function() {
        var i, args = arguments;
        _write.call(s, "*" + args.length + "\r\n");
        for (i = 0; i < args.length; i++) {
            var arg = args[i];
            _write.call(s, "$" + arg.length + "\r\n" + arg + "\r\n");
        }
    }

    s.on("data", function(data) {
        var reply;
        r.feed(data);
        try {
            while(reply = r.get())
                s.emit("reply", reply);
        } catch(err) {
            r = null;
            s.emit("error", err);
            s.destroy();
        }
    });

    return s;
}

<commit_msg>Explicitly check if reply is undefined<commit_after>var hiredis = require("./build/default/hiredis"),
    net = require("net");

exports.Reader = hiredis.Reader;
exports.createConnection = function(port, host) {
    var s = new net.Stream();
    var r = new hiredis.Reader();
    var _write = s.write;
    s.connect(port || 6379, host);

    s.write = function() {
        var i, args = arguments;
        _write.call(s, "*" + args.length + "\r\n");
        for (i = 0; i < args.length; i++) {
            var arg = args[i];
            _write.call(s, "$" + arg.length + "\r\n" + arg + "\r\n");
        }
    }

    s.on("data", function(data) {
        var reply;
        r.feed(data);
        try {
            while((reply = r.get()) !== undefined)
                s.emit("reply", reply);
        } catch(err) {
            r = null;
            s.emit("error", err);
            s.destroy();
        }
    });

    return s;
}

<|endoftext|>


<commit_before>var path = require('path');

module.exports = function(grunt) {
  grunt.initConfig({
    jscs: {
      src: ["tasks/nunjucks.js", "tests/compare.js"],
      options: {
        config: ".jscsrc"
      }
    },
    nunjucks: {
      options: {
        data: grunt.file.readJSON('tests/data.json'),
        preprocessData: function(data) {
          data.page = path.basename(this.src[0], '.html');
          return data;
        },
        configureEnvironment: function(env) {
          env.addGlobal('foo', 'bar');
        }
      },
      render: {
        files: {
          'tests/_output.html' : ['tests/input.html']
        }
      }
    }
  });

  grunt.loadNpmTasks("grunt-jscs");
  grunt.loadTasks("tasks/");

  grunt.registerTask("jscs", ["jscs"]);
  grunt.registerTask("test", ["nunjucks"]);
}<commit_msg>update gruntfile with new targets for leaking vars tests<commit_after>var path = require('path');

module.exports = function(grunt) {
  grunt.initConfig({
    jscs: {
      src: ["tasks/nunjucks.js", "tests/compare.js"],
      options: {
        config: ".jscsrc"
      }
    },
    nunjucks: {
      options: {
        data: grunt.file.readJSON('tests/data.json'),
        preprocessData: function(data) {
          data.page = path.basename(this.src[0], '.html');
          return data;
        },
        configureEnvironment: function(env) {
          env.addGlobal('foo', 'bar');
        }
      },
      render: {
        files: {
          'tests/_output.html' : ['tests/input.html'],
          'tests/_output.html' : ['tests/input.html'],
          'tests/leaking-vars/_output1.html' : ['tests/leaking-vars/input1.html'],
          'tests/leaking-vars/_output2.html' : ['tests/leaking-vars/input2.html']
        }
      }
    }
  });

  grunt.loadNpmTasks("grunt-jscs");
  grunt.loadTasks("tasks/");

  grunt.registerTask("jscs", ["jscs"]);
  grunt.registerTask("test", ["nunjucks"]);
}<|endoftext|>


<commit_before>//settings
var settings = {
  stepTime: 50,
  eveCount: 20,
  width: window.innerWidth - 40,
  height: window.innerHeight - 40,
}

Eves = [];

//helpful things
var random = Math.random;
var max = Math.max;
var min = Math.min;
var floor = Math.floor;
var sqrt = Math.sqrt;
var pow = Math.pow;
var sin = Math.sin;
var cos = Math.cos;
var atan = Math.atan;
var log10 = Math.log10;
var findDistance = function(pos1, pos2) {
  return sqrt(pow(pos2.x - pos1.x, 2) + pow(pos2.y - pos1.y, 2));
}
var limitPositions = function(x,y,r) {
  x = max(r, min(x, (settings.width - r)));
  y = max(r, min(y, (settings.height - r)));
  return [x,y];
}

//INIT:

createBoard();
populateData();
generateEves();
setTimeout(animate, 1000);

//FUNCTIONS:

function drawEve(data) {
  //draws Eve with data
  //return element
  console.log(data);
  var eve = document.createElementNS('http://www.w3.org/2000/svg','g');

  d3.select(eve)
    .attr('class','eve')
    .attr('id', data.id)
    .append('circle')
    .attr('cx', data.bodyParts[0].pos.x).attr('cy', data.bodyParts[0].pos.y)
    .attr('r', data.bodyParts[0].mass)
    .attr('id', data.id + 'b0');
  //if distance between starting x and wall are less than 50,
    //draw it on oneside,
  // else,
    //draw it on the otehr
  for(var i = 0; i < data.limbs.length; i++) {
    //tack on body part
    var b0 = data.bodyParts[i];
    var b1 = data.bodyParts[i + 1];
    d3.select(eve)
      .append('line')
      .attr('x1', b0.pos.x).attr('y1', b0.pos.y)
      .attr('x2', b1.pos.x).attr('y2', b1.pos.y)
      .attr('id', data.id + 'l' + i);
    d3.select(eve)
      .append('circle')
      .attr('cx', b1.pos.x).attr('cy', b1.pos.y)
      .attr('r', b1.mass)
      .attr('id', data.id + 'b' + (i + 1));
  }
  return eve;
};

function createBoard() {
  d3.select('body').selectAll('svg')
    .data([{width:settings.width, height:settings.height}])
    .enter()
    .append('svg')
    .attr('class', 'board')
    .attr('width', settings.width)
    .attr('height', settings.height);
}

function createEveData(proto) {
  var data = {};
  data.id = 'eve' + floor(random() * 10000000000);

  if(proto) {
    //build off existing
    //select a quality
    //if relevant, select a subquality
  } else {
    data.bodyParts = [];
    data.limbs = [];
    var firstPart = {
      mass: floor(random() * 10) + 3,
      pos: {x:floor(random() * settings.width), y:floor(random() * settings.height)},
      vel: {x:0, y:0}
    }
    data.bodyParts.push(firstPart);
    //count of limbs? Can they be freely attached without two nodes?

    var bodyPartCount = floor(random() * 4) + 2;
    var yPos = firstPart.pos.y;
    var currentXPos = firstPart.pos.x;
    for(var i = 1; i < bodyPartCount; i++) {

      var limb = {
        connections: [i-1, i],
        currentLength: floor(random() * 20) + 10,
        growing: false,
        //angle of connection?
        //phase of movement?
        //magnitude of movement? (springiness)
        //speed of movement?
        //color?
      };
      limb.initialLength = limb.currentLength;
      limb.maxLength = limb.initialLength + floor(random() * 5);

      currentXPos = currentXPos + limb.initialLength;

      var bodyPart = {
        mass: floor(random() * 10) + 3,
        pos: {x:currentXPos, y:yPos},
        vel: {x:0, y:0}
        //color
        //spikes/plates if i'm into that
      }

      data.limbs.push(limb);
      data.bodyParts.push(bodyPart);
    }
    //speed?
    //color?
    //total mass?
  }
  return data;
}

function generateEves() {
  var d3Eves = d3.select('.board').selectAll('.eve')
    .data(Eves, function(d) { return d.id });
  //new ones:
  d3Eves.enter()
    .append(drawEve);
    //click handler for stats
}

function populateData() {
  for(var i = 0; i < settings.eveCount; i ++) {
    Eves.push(createEveData());
  }
}

function animate() {
  setInterval( function() {
    applyLimbForces();
    updateBodyPartPositions();
  }, settings.stepTime);
}

function applyLimbForces() {
  for(var i = 0; i < Eves.length; i++) {
    var eve = Eves[i];
    for(var j = 0; j < eve.limbs.length; j++) {
      var limb = eve.limbs[j];
      var b0 = eve.bodyParts[limb.connections[0]];
      var b1 = eve.bodyParts[limb.connections[1]];
      var displacement, force;
      limb.currentLength = findDistance(b0.pos, b1.pos)
      if(limb.growing) {
        displacement = limb.maxLength - limb.currentLength;
        force = displacement * 0.1;
        if(limb.currentLength >= limb.maxLength) {
          limb.growing = false;
        }
      } else {
        displacement = limb.initialLength - limb.currentLength;
        force = displacement * 0.1;
        if(limb.currentLength <= limb.initialLength) {
          limb.growing = true;
        }
      }
      var xPosDiff = b1.pos.x - b0.pos.x;
      var yPosDiff = b1.pos.y - b0.pos.y;
      if(xPosDiff === 0) {
        var theta = Math.PI;
      }
      else {
        var theta = atan(yPosDiff / xPosDiff);
      }
      if (xPosDiff >= 0) {
        force *= -1;
      }
      var movementFactor = 1;
      if(limb.growing) {
        movementFactor = 0.9;
      }
      var dVx0 = force / b0.mass * cos(theta);
      var dVy0 = force / b0.mass * sin(theta);
      var dVx1 = -force / b1.mass * cos(theta) * movementFactor;
      var dVy1 = -force / b1.mass * sin(theta) * movementFactor;
      b0.vel.x = min( 20, max( b0.vel.x + dVx0, -20 ));
      b0.vel.y = min( 20, max( b0.vel.y + dVy0, -20 ));
      b1.vel.x = min( 20, max( b1.vel.x + dVx1, -20 ));
      b1.vel.y = min( 20, max( b1.vel.y + dVy1, -20 ));
    }
  }
}

function updateBodyPartPositions() {
  for(var i = 0; i < Eves.length; i++) {
    var eve = Eves[i];
    for(var j = 0; j < eve.bodyParts.length; j++) {
      var bodyPart = eve.bodyParts[j];
      bodyPart.pos.x += bodyPart.vel.x;
      //check if offscreen
      bodyPart.pos.y += bodyPart.vel.y;
      //check if offscreen
      d3.select('#' + eve.id + 'b' + j)
        .attr('cx', bodyPart.pos.x).attr('cy', bodyPart.pos.y);
      d3.select('#' + eve.id + 'l' + j)
        .attr('x1', bodyPart.pos.x).attr('y1', bodyPart.pos.y);
      if(j > 0) {
        d3.select('#' + eve.id + 'l' + (j-1))
          .attr('x2', bodyPart.pos.x).attr('y2', bodyPart.pos.y);
      }
    }
  }
}

<commit_msg>Reverse velocity when eve hits wall<commit_after>//settings
var settings = {
  stepTime: 50,
  eveCount: 20,
  width: window.innerWidth - 40,
  height: window.innerHeight - 40,
}

Eves = [];

//helpful things
var random = Math.random;
var max = Math.max;
var min = Math.min;
var floor = Math.floor;
var sqrt = Math.sqrt;
var pow = Math.pow;
var sin = Math.sin;
var cos = Math.cos;
var atan = Math.atan;
var log10 = Math.log10;
var findDistance = function(pos1, pos2) {
  return sqrt(pow(pos2.x - pos1.x, 2) + pow(pos2.y - pos1.y, 2));
}
var limitPositions = function(x,y,r) {
  x = max(r, min(x, (settings.width - r)));
  y = max(r, min(y, (settings.height - r)));
  return [x,y];
}

//INIT:

createBoard();
populateData();
generateEves();
setTimeout(animate, 1000);

//FUNCTIONS:

function drawEve(data) {
  //draws Eve with data
  //return element
  console.log(data);
  var eve = document.createElementNS('http://www.w3.org/2000/svg','g');

  d3.select(eve)
    .attr('class','eve')
    .attr('id', data.id)
    .append('circle')
    .attr('cx', data.bodyParts[0].pos.x).attr('cy', data.bodyParts[0].pos.y)
    .attr('r', data.bodyParts[0].mass)
    .attr('id', data.id + 'b0');
  //if distance between starting x and wall are less than 50,
    //draw it on oneside,
  // else,
    //draw it on the otehr
  for(var i = 0; i < data.limbs.length; i++) {
    //tack on body part
    var b0 = data.bodyParts[i];
    var b1 = data.bodyParts[i + 1];
    d3.select(eve)
      .append('line')
      .attr('x1', b0.pos.x).attr('y1', b0.pos.y)
      .attr('x2', b1.pos.x).attr('y2', b1.pos.y)
      .attr('id', data.id + 'l' + i);
    d3.select(eve)
      .append('circle')
      .attr('cx', b1.pos.x).attr('cy', b1.pos.y)
      .attr('r', b1.mass)
      .attr('id', data.id + 'b' + (i + 1));
  }
  return eve;
};

function createBoard() {
  d3.select('body').selectAll('svg')
    .data([{width:settings.width, height:settings.height}])
    .enter()
    .append('svg')
    .attr('class', 'board')
    .attr('width', settings.width)
    .attr('height', settings.height);
}

function createEveData(proto) {
  var data = {};
  data.id = 'eve' + floor(random() * 10000000000);

  if(proto) {
    //build off existing
    //select a quality
    //if relevant, select a subquality
  } else {
    data.bodyParts = [];
    data.limbs = [];
    var firstPart = {
      mass: floor(random() * 10) + 3,
      pos: {x:floor(random() * settings.width), y:floor(random() * settings.height)},
      vel: {x:0, y:0}
    }
    data.bodyParts.push(firstPart);
    //count of limbs? Can they be freely attached without two nodes?

    var bodyPartCount = floor(random() * 4) + 2;
    var yPos = firstPart.pos.y;
    var currentXPos = firstPart.pos.x;
    for(var i = 1; i < bodyPartCount; i++) {

      var limb = {
        connections: [i-1, i],
        currentLength: floor(random() * 20) + 10,
        growing: false,
        //angle of connection?
        //phase of movement?
        //magnitude of movement? (springiness)
        //speed of movement?
        //color?
      };
      limb.initialLength = limb.currentLength;
      limb.maxLength = limb.initialLength + floor(random() * 5);

      currentXPos = currentXPos + limb.initialLength;

      var bodyPart = {
        mass: floor(random() * 10) + 3,
        pos: {x:currentXPos, y:yPos},
        vel: {x:0, y:0}
        //color
        //spikes/plates if i'm into that
      }

      data.limbs.push(limb);
      data.bodyParts.push(bodyPart);
    }
    //speed?
    //color?
    //total mass?
  }
  return data;
}

function generateEves() {
  var d3Eves = d3.select('.board').selectAll('.eve')
    .data(Eves, function(d) { return d.id });
  //new ones:
  d3Eves.enter()
    .append(drawEve);
    //click handler for stats
}

function populateData() {
  for(var i = 0; i < settings.eveCount; i ++) {
    Eves.push(createEveData());
  }
}

function animate() {
  setInterval( function() {
    applyLimbForces();
    updateBodyPartPositions();
  }, settings.stepTime);
}

function applyLimbForces() {
  for(var i = 0; i < Eves.length; i++) {
    var eve = Eves[i];
    for(var j = 0; j < eve.limbs.length; j++) {
      var limb = eve.limbs[j];
      var b0 = eve.bodyParts[limb.connections[0]];
      var b1 = eve.bodyParts[limb.connections[1]];
      var displacement, force;
      limb.currentLength = findDistance(b0.pos, b1.pos)
      if(limb.growing) {
        displacement = limb.maxLength - limb.currentLength;
        force = displacement * 0.1;
        if(limb.currentLength >= limb.maxLength) {
          limb.growing = false;
        }
      } else {
        displacement = limb.initialLength - limb.currentLength;
        force = displacement * 0.1;
        if(limb.currentLength <= limb.initialLength) {
          limb.growing = true;
        }
      }
      var xPosDiff = b1.pos.x - b0.pos.x;
      var yPosDiff = b1.pos.y - b0.pos.y;
      if(xPosDiff === 0) {
        var theta = Math.PI;
      }
      else {
        var theta = atan(yPosDiff / xPosDiff);
      }
      if (xPosDiff >= 0) {
        force *= -1;
      }
      var movementFactor = 1;
      if(limb.growing) {
        movementFactor = 0.9;
      }
      var dVx0 = force / b0.mass * cos(theta);
      var dVy0 = force / b0.mass * sin(theta);
      var dVx1 = -force / b1.mass * cos(theta) * movementFactor;
      var dVy1 = -force / b1.mass * sin(theta) * movementFactor;
      b0.vel.x = min( 20, max( b0.vel.x + dVx0, -20 ));
      b0.vel.y = min( 20, max( b0.vel.y + dVy0, -20 ));
      b1.vel.x = min( 20, max( b1.vel.x + dVx1, -20 ));
      b1.vel.y = min( 20, max( b1.vel.y + dVy1, -20 ));
    }
  }
}

function updateBodyPartPositions() {
  for(var i = 0; i < Eves.length; i++) {
    var eve = Eves[i];
    for(var j = 0; j < eve.bodyParts.length; j++) {
      var bodyPart = eve.bodyParts[j];
      bodyPart.pos.x += bodyPart.vel.x;
      //check if offscreen
      if(bodyPart.pos.x <= bodyPart.mass || bodyPart.pos.x >= settings.width - bodyPart.mass) {
        bodyPart.pos.x = limitPositions(bodyPart.pos.x, 1, bodyPart.mass)[0];
        bodyPart.vel.x = -1 * bodyPart.vel.x;
      }
      bodyPart.pos.y += bodyPart.vel.y;
      if(bodyPart.pos.y <= bodyPart.mass || bodyPart.pos.y >= settings.height - bodyPart.mass) {
        bodyPart.pos.y = limitPositions(1, bodyPart.pos.y, bodyPart.mass)[1];
        bodyPart.vel.y = -1 * bodyPart.vel.y;
      }
      //check if offscreen
      d3.select('#' + eve.id + 'b' + j)
        .attr('cx', bodyPart.pos.x).attr('cy', bodyPart.pos.y);
      d3.select('#' + eve.id + 'l' + j)
        .attr('x1', bodyPart.pos.x).attr('y1', bodyPart.pos.y);
      if(j > 0) {
        d3.select('#' + eve.id + 'l' + (j-1))
          .attr('x2', bodyPart.pos.x).attr('y2', bodyPart.pos.y);
      }
    }
  }
}

<|endoftext|>


<commit_before>module.exports = (grunt) => {
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    eslint: {
      gruntfile: {
        src: [ 'Gruntfile.js' ]
      },
      tasks: {
        src: [ 'tasks/*.js', 'lib/*.js' ]
      },
      tests: {
        src: [ 'test/*.js' ]
      }
    },

    jsonlint: {
      sample: {
        src: [ 'test/valid.json' ]
      },
      packageJson: {
        src: [ 'package.json' ]
      },
      schema: {
        src: [ 'test/3.json' ],
        options: {
          schema: {
            src: 'test/3.schema.json'
          }
        }
      },
      singleQuotes: {
        src: [ 'test/single-quotes.json' ],
        options: {
          allowSingleQuotedStrings: true
        }
      },
      comments: {
        src: [ 'test/cjson.json' ],
        options: {
          ignoreComments: true
        }
      },
      trailingCommas: {
        src: [ 'test/trailing-commas.json' ],
        options: {
          ignoreTrailingCommas: true
        }
      },
      json5: {
        src: [ 'test/json5.json' ],
        options: {
          mode: 'json5'
        }
      },
      overflowTest: {
        src: [ 'test/issue13/**/*.json' ]
      },
      invalid: {
        src: [ 'test/invalid.json' ]
      },
      invalidVisualStudio: {
        src: [ 'test/invalid.json' ],
        options: {
          formatter: 'msbuild'
        }
      },
      invalidJshintStyle: {
        src: [ 'test/invalid.json' ],
        options: {
          reporter: 'jshint'
        }
      }
    },

    mochaTest: {
      options: {
        reporter: 'spec'
      },
      unitTests: {
        src: [ 'test/unit-tests.js' ]
      },
      issue13Tests: {
        src: [ 'test/issue13-tests.js' ]
      }
    }
  });

  grunt.loadNpmTasks('grunt-eslint');
  grunt.loadNpmTasks('grunt-mocha-test');

  require('./tasks/jsonlint')(grunt); // eslint-disable-line global-require

  grunt.registerTask('test', [
    'eslint', 'jsonlint:sample', 'jsonlint:packageJson', 'jsonlint:comments', 'jsonlint:singleQuotes',
    'jsonlint:trailingCommas', 'jsonlint:json5', 'mochaTest'
  ]);

  // Default task(s).
  grunt.registerTask('default', [ 'test' ]);
};
<commit_msg>Regression test for allowing duplicate keys by default.<commit_after>module.exports = (grunt) => {
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    eslint: {
      gruntfile: {
        src: [ 'Gruntfile.js' ]
      },
      tasks: {
        src: [ 'tasks/*.js', 'lib/*.js' ]
      },
      tests: {
        src: [ 'test/*.js' ]
      }
    },

    jsonlint: {
      sample: {
        src: [ 'test/valid.json' ]
      },
      packageJson: {
        src: [ 'package.json' ]
      },
      schema: {
        src: [ 'test/3.json' ],
        options: {
          schema: {
            src: 'test/3.schema.json'
          }
        }
      },
      singleQuotes: {
        src: [ 'test/single-quotes.json' ],
        options: {
          allowSingleQuotedStrings: true
        }
      },
      comments: {
        src: [ 'test/cjson.json' ],
        options: {
          ignoreComments: true
        }
      },
      trailingCommas: {
        src: [ 'test/trailing-commas.json' ],
        options: {
          ignoreTrailingCommas: true
        }
      },
      json5: {
        src: [ 'test/json5.json' ],
        options: {
          mode: 'json5'
        }
      },
      duplicateKeys: {
        src: [ 'test/duplicate-keys.json' ]
      },
      overflowTest: {
        src: [ 'test/issue13/**/*.json' ]
      },
      invalid: {
        src: [ 'test/invalid.json' ]
      },
      invalidVisualStudio: {
        src: [ 'test/invalid.json' ],
        options: {
          formatter: 'msbuild'
        }
      },
      invalidJshintStyle: {
        src: [ 'test/invalid.json' ],
        options: {
          reporter: 'jshint'
        }
      }
    },

    mochaTest: {
      options: {
        reporter: 'spec'
      },
      unitTests: {
        src: [ 'test/unit-tests.js' ]
      },
      issue13Tests: {
        src: [ 'test/issue13-tests.js' ]
      }
    }
  });

  grunt.loadNpmTasks('grunt-eslint');
  grunt.loadNpmTasks('grunt-mocha-test');

  require('./tasks/jsonlint')(grunt); // eslint-disable-line global-require

  grunt.registerTask('test', [
    'eslint',
    'jsonlint:sample', 'jsonlint:packageJson', 'jsonlint:comments', 'jsonlint:singleQuotes',
    'jsonlint:trailingCommas', 'jsonlint:json5', 'jsonlint:duplicateKeys',
    'mochaTest'
  ]);

  // Default task(s).
  grunt.registerTask('default', [ 'test' ]);
};
<|endoftext|>


<commit_before>const path = require('path');

const { chunkNameClientRunFirst } = require('../../defaults/before-build');
const defaultEntrypoints = require('../../defaults/entrypoints');
const readClientFile = require('../../utils/read-client-file');
const getClientFilePath = require('../../utils/get-client-file-path');

/**
 * 注入: JavaScript 代码
 * @param {Object} options
 * @param {Boolean} [options.needInjectCritical]
 * @param {Object} [options.injectCache]
 * @param {Object} [options.entrypoints]
 * @param {String} [options.localeId]
 * @param {String} [options.reduxHtml]
 * @param {Object} [options.compilation]
 * @param {Object} [options.SSRState]
 * @returns {String}
 */
module.exports = ({
    needInjectCritical,
    injectCache,
    entrypoints,
    localeId,
    reduxHtml,
    SSRState = {},
    compilation
}) => {
    const ENV = process.env.WEBPACK_BUILD_ENV;
    const isDev = Boolean(
        ENV === 'dev' || (typeof __DEV__ !== 'undefined' && __DEV__)
    );
    const isProd = !isDev;

    if (isDev || typeof injectCache.scriptsInBody === 'undefined') {
        let r = '';

        // 入口: critical
        if (needInjectCritical && Array.isArray(entrypoints.critical)) {
            r += entrypoints.critical
                .filter(file => path.extname(file) === '.js')
                .map(file => {
                    if (isDev) {
                        // return `<script type="text/javascript" src="${getClientFilePath(true, file)}"></script>`;
                        return combineFilePaths(true, file);
                    }
                    return `<script type="text/javascript">${readClientFile(
                        true,
                        file
                    )}</script>`;
                })
                .join('');
        }

        // 其他默认入口
        // console.log('defaultEntrypoints', defaultEntrypoints)
        // console.log('entrypoints', entrypoints)
        defaultEntrypoints.forEach(key => {
            if (Array.isArray(entrypoints[key])) {
                r += entrypoints[key]
                    .filter(file => /\.(js|jsx|mjs|ejs)$/.test(file))
                    .map(file => {
                        // console.log(file)
                        // if (isDev)
                        // return `<script type="text/javascript" src="${getClientFilePath(true, file)}" defer></script>`
                        // return `<script type="text/javascript" src="${getClientFilePath(
                        //     true,
                        //     file
                        // )}" defer></script>`;
                        return combineFilePaths(true, file);
                    })
                    .join('');
            }
        });

        // 如果设置了 PWA 自动注册 Service-Worker，在此注册
        const pwaAuto =
            typeof process.env.KOOT_PWA_AUTO_REGISTER === 'string'
                ? JSON.parse(process.env.KOOT_PWA_AUTO_REGISTER)
                : false;
        if (
            pwaAuto &&
            (process.env.WEBPACK_BUILD_TYPE === 'spa' ||
                typeof injectCache.pathnameSW === 'string')
        ) {
            r += `<script id="__koot-pwa-register-sw" type="text/javascript">`;
            if (isProd) {
                r +=
                    `if ('serviceWorker' in navigator) {` +
                    `window.addEventListener('load', function() {` +
                    // + `navigator.serviceWorker.register("${injectCache.pathnameSW}?koot=${process.env.KOOT_VERSION}",`
                    `navigator.serviceWorker.register("${injectCache.pathnameSW ||
                        JSON.parse(process.env.KOOT_PWA_PATHNAME)}?koot=0.8",` +
                    `{scope: '/'}` +
                    `)` +
                    `.catch(err => {console.log('👩💻 Service Worker SUPPORTED. ERROR', err)})` +
                    `});` +
                    `}else{console.log('👩💻 Service Worker not supported!')}`;
            } else if (isDev) {
                r += `console.log('👩💻 No Service Worker for DEV mode.')`;
            }
            r += `</script>`;
        }

        injectCache.scriptsInBody = r;
    }

    return (
        `<script type="text/javascript">` +
        (reduxHtml ? reduxHtml : `window.__REDUX_STATE__ = {};`) +
        `window.__KOOT_LOCALEID__ = "${SSRState.localeId || ''}";` +
        `window.__KOOT_SSR_STATE__ = ${JSON.stringify(SSRState)};` +
        `</script>` +
        getClientRunFirstJS(localeId, compilation) +
        `${injectCache.scriptsInBody}`
    );
};

/**
 * 客户端预先执行 JS 的代码
 * @param {*} localeId
 * @param {*} compilation
 * @returns {String}
 */
const getClientRunFirstJS = (localeId, compilation) => {
    const filename = `${chunkNameClientRunFirst}.js`;

    if (process.env.WEBPACK_BUILD_ENV === 'dev') {
        return combineFilePaths(filename, localeId);
        // return `<script type="text/javascript" src="${getClientFilePath(
        //     filename,
        //     localeId
        // )}"></script>`;
    }

    return `<script type="text/javascript">${readClientFile(
        filename,
        localeId,
        compilation
    )}</script>`;
};

/**
 * 返回 script 标签
 * 如果有多个结果，会返回包含多个标签的 HTML 结果
 * @param {...any} args `utils/get-client-file-path` 对应的参数
 * @returns {String} 整合的 HTML 结果
 */
const combineFilePaths = (...args) => {
    let pathnames = getClientFilePath(...args);
    if (!Array.isArray(pathnames)) pathnames = [pathnames];
    return pathnames
        .map(
            pathname =>
                `<script type="text/javascript" src="${pathname}" defer></script>`
        )
        .join('');
};
<commit_msg>update sw base version to 0.11<commit_after>const path = require('path');

const { chunkNameClientRunFirst } = require('../../defaults/before-build');
const defaultEntrypoints = require('../../defaults/entrypoints');
const readClientFile = require('../../utils/read-client-file');
const getClientFilePath = require('../../utils/get-client-file-path');

/**
 * 注入: JavaScript 代码
 * @param {Object} options
 * @param {Boolean} [options.needInjectCritical]
 * @param {Object} [options.injectCache]
 * @param {Object} [options.entrypoints]
 * @param {String} [options.localeId]
 * @param {String} [options.reduxHtml]
 * @param {Object} [options.compilation]
 * @param {Object} [options.SSRState]
 * @returns {String}
 */
module.exports = ({
    needInjectCritical,
    injectCache,
    entrypoints,
    localeId,
    reduxHtml,
    SSRState = {},
    compilation
}) => {
    const ENV = process.env.WEBPACK_BUILD_ENV;
    const isDev = Boolean(
        ENV === 'dev' || (typeof __DEV__ !== 'undefined' && __DEV__)
    );
    const isProd = !isDev;

    if (isDev || typeof injectCache.scriptsInBody === 'undefined') {
        let r = '';

        // 入口: critical
        if (needInjectCritical && Array.isArray(entrypoints.critical)) {
            r += entrypoints.critical
                .filter(file => path.extname(file) === '.js')
                .map(file => {
                    if (isDev) {
                        // return `<script type="text/javascript" src="${getClientFilePath(true, file)}"></script>`;
                        return combineFilePaths(true, file);
                    }
                    return `<script type="text/javascript">${readClientFile(
                        true,
                        file
                    )}</script>`;
                })
                .join('');
        }

        // 其他默认入口
        // console.log('defaultEntrypoints', defaultEntrypoints)
        // console.log('entrypoints', entrypoints)
        defaultEntrypoints.forEach(key => {
            if (Array.isArray(entrypoints[key])) {
                r += entrypoints[key]
                    .filter(file => /\.(js|jsx|mjs|ejs)$/.test(file))
                    .map(file => {
                        // console.log(file)
                        // if (isDev)
                        // return `<script type="text/javascript" src="${getClientFilePath(true, file)}" defer></script>`
                        // return `<script type="text/javascript" src="${getClientFilePath(
                        //     true,
                        //     file
                        // )}" defer></script>`;
                        return combineFilePaths(true, file);
                    })
                    .join('');
            }
        });

        // 如果设置了 PWA 自动注册 Service-Worker，在此注册
        const pwaAuto =
            typeof process.env.KOOT_PWA_AUTO_REGISTER === 'string'
                ? JSON.parse(process.env.KOOT_PWA_AUTO_REGISTER)
                : false;
        if (
            pwaAuto &&
            (process.env.WEBPACK_BUILD_TYPE === 'spa' ||
                typeof injectCache.pathnameSW === 'string')
        ) {
            r += `<script id="__koot-pwa-register-sw" type="text/javascript">`;
            if (isProd) {
                r +=
                    `if ('serviceWorker' in navigator) {` +
                    `window.addEventListener('load', function() {` +
                    // + `navigator.serviceWorker.register("${injectCache.pathnameSW}?koot=${process.env.KOOT_VERSION}",`
                    `navigator.serviceWorker.register("${injectCache.pathnameSW ||
                        JSON.parse(process.env.KOOT_PWA_PATHNAME)}?koot=0.11",` +
                    `{scope: '/'}` +
                    `)` +
                    `.catch(err => {console.log('👩💻 Service Worker SUPPORTED. ERROR', err)})` +
                    `});` +
                    `}else{console.log('👩💻 Service Worker not supported!')}`;
            } else if (isDev) {
                r += `console.log('👩💻 No Service Worker for DEV mode.')`;
            }
            r += `</script>`;
        }

        injectCache.scriptsInBody = r;
    }

    return (
        `<script type="text/javascript">` +
        (reduxHtml ? reduxHtml : `window.__REDUX_STATE__ = {};`) +
        `window.__KOOT_LOCALEID__ = "${SSRState.localeId || ''}";` +
        `window.__KOOT_SSR_STATE__ = ${JSON.stringify(SSRState)};` +
        `</script>` +
        getClientRunFirstJS(localeId, compilation) +
        `${injectCache.scriptsInBody}`
    );
};

/**
 * 客户端预先执行 JS 的代码
 * @param {*} localeId
 * @param {*} compilation
 * @returns {String}
 */
const getClientRunFirstJS = (localeId, compilation) => {
    const filename = `${chunkNameClientRunFirst}.js`;

    if (process.env.WEBPACK_BUILD_ENV === 'dev') {
        return combineFilePaths(filename, localeId);
        // return `<script type="text/javascript" src="${getClientFilePath(
        //     filename,
        //     localeId
        // )}"></script>`;
    }

    return `<script type="text/javascript">${readClientFile(
        filename,
        localeId,
        compilation
    )}</script>`;
};

/**
 * 返回 script 标签
 * 如果有多个结果，会返回包含多个标签的 HTML 结果
 * @param {...any} args `utils/get-client-file-path` 对应的参数
 * @returns {String} 整合的 HTML 结果
 */
const combineFilePaths = (...args) => {
    let pathnames = getClientFilePath(...args);
    if (!Array.isArray(pathnames)) pathnames = [pathnames];
    return pathnames
        .map(
            pathname =>
                `<script type="text/javascript" src="${pathname}" defer></script>`
        )
        .join('');
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
    path = require('path'),
    mongoose = require('mongoose'),
  users = require('../../controllers/users.server.controller');
  var User = mongoose.model('User');
  var FB = require('fb');
 var _ = require('underscore');
  var errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;

      console.log('profile:::'+JSON.stringify(profile));

      providerData.accessToken = accessToken;

      providerData.refreshToken = refreshToken;

        FB.setAccessToken(accessToken);

        var Friendslists ='';

        var parents='';

        var picture='';

        var boss='';

        FB.api('/me/friends', function (res) {
            if (!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                return;
            }

            show_results(res);

        });

        function show_results(results) {

            Friendslists = JSON.stringify(results.data,['name']).replace(/'name'/g,'displayName');

            var names = _.pluck(results.data,'name');

            var parents = User.find({ displayName: { $in: names } },null, {sort: {created: 1}}, function(err, cursor) {

                console.log('results::'+ cursor);

                boss = _.pluck(cursor,'email');

                picture = _.pluck(cursor.providerData.picture.data,'url');

                console.log('parent::'+ boss[0]);

                console.log('parents::'+ boss);

            }).stream();

            console.log('FriendsList:' + Friendslists);

        }

    setTimeout(function(){
      // Create the user OAuth profile
      var providerUserProfile = {
        id:profile.id,
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
        parents: boss,
        Boss:boss[0],
        friends:Friendslists,
        providerIdentifierField:'id',
        providerData: providerData
      };

      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

    },Math.random() * 2000);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<commit_msg>global declaration<commit_after>'use strict';

/**
 * Module dependencies.
 */
var passport = require('passport'),
  FacebookStrategy = require('passport-facebook').Strategy,
    path = require('path'),
    mongoose = require('mongoose'),
  users = require('../../controllers/users.server.controller');
  var User = mongoose.model('User');
  var FB = require('fb');
 var _ = require('underscore');
  var errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

module.exports = function (config) {
  // Use facebook strategy
  passport.use(new FacebookStrategy({
      clientID: config.facebook.clientID,
      clientSecret: config.facebook.clientSecret,
      callbackURL: config.facebook.callbackURL,
      profileFields: ['id', 'name', 'displayName', 'emails', 'photos'],
      passReqToCallback: true
    },
    function (req, accessToken, refreshToken, profile, done) {
      // Set the provider data and include tokens
      var providerData = profile._json;

      console.log('profile:::'+JSON.stringify(profile));

      providerData.accessToken = accessToken;

      providerData.refreshToken = refreshToken;

        FB.setAccessToken(accessToken);

        var Friendslists ='';

        var parents='';

        var picture='';

        var boss='';

        FB.api('/me/friends', function (res) {
            if (!res || res.error) {
                console.log(!res ? 'error occurred' : res.error);
                return;
            }

            show_results(res);

        });

        function show_results(results) {

            Friendslists = JSON.stringify(results.data,['name']).replace(/'name'/g,'displayName');

            var names = _.pluck(results.data,'name');

            var parents = User.find({ displayName: { $in: names } },null, {sort: {created: 1}}, function(err, cursor) {

                console.log('results::'+ cursor);

                boss = _.pluck(cursor,'email');

                picture = _.pluck(cursor,'profileImageURL');

                console.log('parent::'+ boss[0]);

                console.log('picture::'+ picture);

                console.log('parents::'+ boss);

            }).stream();

            console.log('FriendsList:' + Friendslists);

        }

    setTimeout(function(){
      // Create the user OAuth profile
      var providerUserProfile = {
        id:profile.id,
        firstName: profile.name.givenName,
        lastName: profile.name.familyName,
        displayName: profile.displayName,
        email: profile.emails ? profile.emails[0].value : undefined,
        username: profile.username || generateUsername(profile),
        profileImageURL: (profile.id) ? '//graph.facebook.com/' + profile.id + '/picture?type=large' : undefined,
        provider: 'facebook',
        parents: boss,
        Boss:boss[0],
        friends:Friendslists,
        providerIdentifierField:'id',
        providerData: providerData
      };

      // Save the user OAuth profile
      users.saveOAuthUserProfile(req, providerUserProfile, done);

    },Math.random() * 2000);

      function generateUsername(profile) {
        var username = '';

        if (profile.emails) {
          username = profile.emails[0].value.split('@')[0];
        } else if (profile.name) {
          username = profile.name.givenName[0] + profile.name.familyName;
        }

        return username.toLowerCase() || undefined;
      }
    }
  ));
};
<|endoftext|>