<commit_before>// --------------------
// Sequelize definer
// --------------------

// modules
var requireFolderTree = require('require-folder-tree');

// imports
var utils = require('./utils'),
	errors = require('./errors');

// exports
module.exports = function(Sequelize) {
	if (!Sequelize) Sequelize = require('sequelize');

	var Utils = Sequelize.Utils,
		_ = Utils._;

	utils = utils(Sequelize);

	// add custom errors to Sequelize
	errors = errors(Sequelize);
	_.extend(Sequelize, errors);
	_.extend(Sequelize.prototype, errors);

	// define a set of models at once
	// input expected in form of a Javascript object with names of the models as keys
	Sequelize.prototype.defineAll = function(definitions, defineOptions) {
		var sequelize = this;

		var globalOptions = sequelize.options.define || {};

		defineOptions = _.extend({
			primaryKey: 'id',
			primaryKeyType: Sequelize.INTEGER,
			primaryKeyFirst: false,
			autoAssociate: false,
			//onDelete: undefined,
			//onUpdate: undefined,
			//fields: undefined,
			skipFieldsOnThrough: false,
			labels: false,
			freezeTableName: globalOptions.freezeTableName,
			camelThrough: globalOptions.camelThrough
		}, defineOptions || {});

		_.defaults(defineOptions, {
			freezeTableName: false,
			camelThrough: false
		});

		// prep definitions
		var primaryKeys = {};

		_.forIn(definitions, function(definition, modelName) {
			prepOne(modelName, definition);
		});

		// process definitions
		var relationshipsOne = [];
		var relationshipsMany = [];

		_.forIn(definitions, function(definition, modelName) {
			defineOne(modelName, definition);
		});

		// create relationships
		defineRelationships();

		// functions

		function prepOne(modelName, definition)
		{
			// find primary key
			var fields = definition.fields = definition.fields || {},
				options = definition.options = definition.options || {};

			var key;
			_.forIn(fields, function(field, fieldName) {
				if (!_.isPlainObject(field)) field = fields[fieldName] = {type: field};

				if (field.primaryKey && !key) key = fieldName;
			});

			// if no primary key, create primary key column
			if (!key && defineOptions.primaryKey) {
				key = utils.functionValue(defineOptions.primaryKey, modelName, definition, definitions);
				var keyField = {type: defineOptions.primaryKeyType, allowNull: false, primaryKey: true, autoIncrement: true};

				if (defineOptions.primaryKeyFirst) {
					utils.unshift(fields, key, keyField);
				} else {
					fields[key] = keyField;
				}
			}

			if (key) {
				definition.primaryKey = key;
				primaryKeys[modelName + Utils.uppercaseFirst(key)] = {model: modelName, field: key};
			} else {
				delete definition.primaryKey;
			}

			// get table name
			utils.defaultNoUndef(options, 'freezeTableName', defineOptions.freezeTableName);
			utils.defaultNoUndef(options, 'tableName', options.freezeTableName ? modelName : Utils.pluralize(modelName));
		}

		function defineOne(modelName, definition)
		{
			// add additional fields
			var fields = definition.fields,
				options = definition.options;

			if (defineOptions.fields && !options.skipFields) {
				_.forIn(defineOptions.fields, function(field, fieldName) {
					if (fields[fieldName] || fields[fieldName] === false || fields[fieldName] === null) return;
					fields[fieldName] = utils.functionValue(field, modelName, definition, definitions);
				});
			}

			_.forIn(fields, function(field, fieldName) {
				if (!field) delete fields[fieldName];
			});

			// populate details of fields
			_.forIn(fields, function(params, fieldName) {
				var label = fieldName;

				// process oneToMany associations
				var reference = params.reference;
				if (reference === false) {
					delete params.reference;
				} else if (reference || (defineOptions.autoAssociate && primaryKeys[fieldName])) {
					// field references another model
					var referencesKey;
					if (reference) {
						if (!definitions[reference]) throw new Sequelize.SequelizeDefinerError('Reference \'' + reference + '\' in field \'' + fieldName + '\' is invalid');

						if (!params.referencesKey) params.referencesKey = definitions[reference].primaryKey;

						if (utils.endsWith(fieldName, Utils.uppercaseFirst(params.referencesKey))) {
							var as = fieldName.slice(0, -params.referencesKey.length);
							if (!params.as && as != reference) params.as = as;
							label = params.as || as;
						} else {
							label = reference;
						}
					} else {
						reference = primaryKeys[fieldName].model;
						params.referencesKey = primaryKeys[fieldName].field;
						label = reference;
					}

					params.references = definitions[reference].options.tableName;

					var referenceType = utils.pop(params, 'referenceType') || 'many';
					if (['one', 'many'].indexOf(referenceType) == -1) throw new Sequelize.SequelizeDefinerError("referenceType must be either 'one' or 'many' in " + modelName + '.' + fieldName);

					utils.defaultsNoUndef(params, {
						onDelete: defineOptions.onDelete,
						onUpdate: defineOptions.onUpdate
					});

					var relationshipOptions = {
						modelName1: modelName,
						modelName2: reference,
						foreignKey: fieldName,
						referenceType: 'has' + Utils.uppercaseFirst(referenceType)
					};

					utils.extendNoUndef(relationshipOptions, {
						as: params.as,
						asReverse: params.asReverse,
						onDelete: params.onDelete,
						onUpdate: params.onUpdate
					});

					// set field type according to referred to field
					var referenceField = definitions[reference].fields[params.referencesKey];
					params.type = referenceField ? referenceField.type : defineOptions.primaryKeyType;

					// store details in relationships array
					relationshipsOne.push(relationshipOptions);
				}

				// create label
				if (defineOptions.labels && !params.label) params.label = (label == 'id' ? 'ID' : utils.camelToHuman(label));
			});

			// process manyToMany relationships
			if (definition.manyToMany) {
				_.forIn(definition.manyToMany, function(options, modelName2) {
					if (options === true) options = {};
					relationshipsMany.push(_.extend(options, {modelName1: modelName, modelName2: modelName2}));
				});
			}

			// define model in sequelize
			var model = sequelize.define(modelName, fields, options);

			// done
			return model;
		}

		function defineRelationships()
		{
			// define relationships
			var models = sequelize.models;

			// define one-to-one/one-to-many relationships
			_.forEach(relationshipsOne, function(options) {
				var model1 = models[utils.pop(options, 'modelName1')],
					model2 = models[utils.pop(options, 'modelName2')];

				var asReverse = utils.pop(options, 'asReverse');

				var joinOptions = _.clone(options);
				utils.setNoUndef(joinOptions, 'as', asReverse);
				model2[options.referenceType](model1, joinOptions); // NB referenceType = 'hasOne' or 'hasMany'

				joinOptions = _.clone(options);
				model1.belongsTo(model2, options);
			});

			// define many-to-many relationships
			_.forEach(relationshipsMany, function(options) {
				var modelName1 = utils.pop(options, 'modelName1'),
					modelName2 = utils.pop(options, 'modelName2'),
					model1 = models[modelName1],
					model2 = models[modelName2],
					key1 = definitions[modelName1].primaryKey,
					key2 = definitions[modelName2].primaryKey;

				if (options.through) {
					// use defined through table
					options.through = models[options.through];
				} else {
					// make through table
					var fields = {};
					fields[modelName1 + Utils.uppercaseFirst(key1)] = {type: definitions[modelName1].fields[key1].type, allowNull: false};
					fields[modelName2 + Utils.uppercaseFirst(key2)] = {type: definitions[modelName2].fields[key2].type, allowNull: false};

					var modelName = modelName1 + (defineOptions.camelThrough ? Utils.uppercaseFirst(modelName2) : modelName2);
					var tableName = defineOptions.freezeTableName ? modelName : (Utils.pluralize(modelName1) + Utils.pluralize(defineOptions.camelThrough ? Utils.uppercaseFirst(modelName2) : modelName2));

					var throughOptions = {tableName: tableName};
					throughOptions.skipFields = (options.skipFields !== undefined) ? options.skipFields : defineOptions.skipFieldsOnThrough;

					options.through = defineOne(modelName, {fields: fields, options: throughOptions});
				}

				utils.defaultsNoUndef(options, {
					onDelete: defineOptions.onDelete,
					onUpdate: defineOptions.onUpdate
				});

				var asReverse = utils.pop(options, 'asReverse');

				var joinOptions = _.clone(options);
				joinOptions.foreignKey = modelName1 + Utils.uppercaseFirst(key1);
				model1.hasMany(model2, joinOptions);

				joinOptions = _.clone(options);
				utils.setNoUndef(joinOptions, 'as', asReverse);
				joinOptions.foreignKey = modelName2 + Utils.uppercaseFirst(key2);
				model2.hasMany(model1, joinOptions);
			});
		}
	};

	Sequelize.prototype.defineFromFolder = function(path, options) {
		var loadOptions = (options || {}).loadOptions || {};
		loadOptions.flatten = true;

		var definitions = requireFolderTree(path, loadOptions);

		return this.defineAll(definitions, options);
	};

	return Sequelize;
};
<commit_msg>Set _autoGenerated on primary/through ID fields<commit_after>// --------------------
// Sequelize definer
// --------------------

// modules
var requireFolderTree = require('require-folder-tree');

// imports
var utils = require('./utils'),
	errors = require('./errors');

// exports
module.exports = function(Sequelize) {
	if (!Sequelize) Sequelize = require('sequelize');

	var Utils = Sequelize.Utils,
		_ = Utils._;

	utils = utils(Sequelize);

	// add custom errors to Sequelize
	errors = errors(Sequelize);
	_.extend(Sequelize, errors);
	_.extend(Sequelize.prototype, errors);

	// define a set of models at once
	// input expected in form of a Javascript object with names of the models as keys
	Sequelize.prototype.defineAll = function(definitions, defineOptions) {
		var sequelize = this;

		var globalOptions = sequelize.options.define || {};

		defineOptions = _.extend({
			primaryKey: 'id',
			primaryKeyType: Sequelize.INTEGER,
			primaryKeyFirst: false,
			autoAssociate: false,
			//onDelete: undefined,
			//onUpdate: undefined,
			//fields: undefined,
			skipFieldsOnThrough: false,
			labels: false,
			freezeTableName: globalOptions.freezeTableName,
			camelThrough: globalOptions.camelThrough
		}, defineOptions || {});

		_.defaults(defineOptions, {
			freezeTableName: false,
			camelThrough: false
		});

		// prep definitions
		var primaryKeys = {};

		_.forIn(definitions, function(definition, modelName) {
			prepOne(modelName, definition);
		});

		// process definitions
		var relationshipsOne = [];
		var relationshipsMany = [];

		_.forIn(definitions, function(definition, modelName) {
			defineOne(modelName, definition);
		});

		// create relationships
		defineRelationships();

		// functions

		function prepOne(modelName, definition)
		{
			// find primary key
			var fields = definition.fields = definition.fields || {},
				options = definition.options = definition.options || {};

			var key;
			_.forIn(fields, function(field, fieldName) {
				if (!_.isPlainObject(field)) field = fields[fieldName] = {type: field};

				if (field.primaryKey && !key) key = fieldName;
			});

			// if no primary key, create primary key column
			if (!key && defineOptions.primaryKey) {
				key = utils.functionValue(defineOptions.primaryKey, modelName, definition, definitions);
				var keyField = {type: defineOptions.primaryKeyType, allowNull: false, primaryKey: true, autoIncrement: true, _autoGenerated: true};

				if (defineOptions.primaryKeyFirst) {
					utils.unshift(fields, key, keyField);
				} else {
					fields[key] = keyField;
				}
			}

			if (key) {
				definition.primaryKey = key;
				primaryKeys[modelName + Utils.uppercaseFirst(key)] = {model: modelName, field: key};
			} else {
				delete definition.primaryKey;
			}

			// get table name
			utils.defaultNoUndef(options, 'freezeTableName', defineOptions.freezeTableName);
			utils.defaultNoUndef(options, 'tableName', options.freezeTableName ? modelName : Utils.pluralize(modelName));
		}

		function defineOne(modelName, definition)
		{
			// add additional fields
			var fields = definition.fields,
				options = definition.options;

			if (defineOptions.fields && !options.skipFields) {
				_.forIn(defineOptions.fields, function(field, fieldName) {
					if (fields[fieldName] || fields[fieldName] === false || fields[fieldName] === null) return;
					fields[fieldName] = utils.functionValue(field, modelName, definition, definitions);
				});
			}

			_.forIn(fields, function(field, fieldName) {
				if (!field) delete fields[fieldName];
			});

			// populate details of fields
			_.forIn(fields, function(params, fieldName) {
				var label = fieldName;

				// process oneToMany associations
				var reference = params.reference;
				if (reference === false) {
					delete params.reference;
				} else if (reference || (defineOptions.autoAssociate && primaryKeys[fieldName])) {
					// field references another model
					var referencesKey;
					if (reference) {
						if (!definitions[reference]) throw new Sequelize.SequelizeDefinerError('Reference \'' + reference + '\' in field \'' + fieldName + '\' is invalid');

						if (!params.referencesKey) params.referencesKey = definitions[reference].primaryKey;

						if (utils.endsWith(fieldName, Utils.uppercaseFirst(params.referencesKey))) {
							var as = fieldName.slice(0, -params.referencesKey.length);
							if (!params.as && as != reference) params.as = as;
							label = params.as || as;
						} else {
							label = reference;
						}
					} else {
						reference = primaryKeys[fieldName].model;
						params.referencesKey = primaryKeys[fieldName].field;
						label = reference;
					}

					params.references = definitions[reference].options.tableName;

					var referenceType = utils.pop(params, 'referenceType') || 'many';
					if (['one', 'many'].indexOf(referenceType) == -1) throw new Sequelize.SequelizeDefinerError("referenceType must be either 'one' or 'many' in " + modelName + '.' + fieldName);

					utils.defaultsNoUndef(params, {
						onDelete: defineOptions.onDelete,
						onUpdate: defineOptions.onUpdate
					});

					var relationshipOptions = {
						modelName1: modelName,
						modelName2: reference,
						foreignKey: fieldName,
						referenceType: 'has' + Utils.uppercaseFirst(referenceType)
					};

					utils.extendNoUndef(relationshipOptions, {
						as: params.as,
						asReverse: params.asReverse,
						onDelete: params.onDelete,
						onUpdate: params.onUpdate
					});

					// set field type according to referred to field
					var referenceField = definitions[reference].fields[params.referencesKey];
					params.type = referenceField ? referenceField.type : defineOptions.primaryKeyType;

					// store details in relationships array
					relationshipsOne.push(relationshipOptions);
				}

				// create label
				if (defineOptions.labels && !params.label) params.label = (label == 'id' ? 'ID' : utils.camelToHuman(label));
			});

			// process manyToMany relationships
			if (definition.manyToMany) {
				_.forIn(definition.manyToMany, function(options, modelName2) {
					if (options === true) options = {};
					relationshipsMany.push(_.extend(options, {modelName1: modelName, modelName2: modelName2}));
				});
			}

			// define model in sequelize
			var model = sequelize.define(modelName, fields, options);

			// done
			return model;
		}

		function defineRelationships()
		{
			// define relationships
			var models = sequelize.models;

			// define one-to-one/one-to-many relationships
			_.forEach(relationshipsOne, function(options) {
				var model1 = models[utils.pop(options, 'modelName1')],
					model2 = models[utils.pop(options, 'modelName2')];

				var asReverse = utils.pop(options, 'asReverse');

				var joinOptions = _.clone(options);
				utils.setNoUndef(joinOptions, 'as', asReverse);
				model2[options.referenceType](model1, joinOptions); // NB referenceType = 'hasOne' or 'hasMany'

				joinOptions = _.clone(options);
				model1.belongsTo(model2, options);
			});

			// define many-to-many relationships
			_.forEach(relationshipsMany, function(options) {
				var modelName1 = utils.pop(options, 'modelName1'),
					modelName2 = utils.pop(options, 'modelName2'),
					model1 = models[modelName1],
					model2 = models[modelName2],
					key1 = definitions[modelName1].primaryKey,
					key2 = definitions[modelName2].primaryKey;

				if (options.through) {
					// use defined through table
					options.through = models[options.through];
				} else {
					// make through table
					var fields = {};
					fields[modelName1 + Utils.uppercaseFirst(key1)] = {type: definitions[modelName1].fields[key1].type, allowNull: false, _autoGenerated: true};
					fields[modelName2 + Utils.uppercaseFirst(key2)] = {type: definitions[modelName2].fields[key2].type, allowNull: false, _autoGenerated: true};

					var modelName = modelName1 + (defineOptions.camelThrough ? Utils.uppercaseFirst(modelName2) : modelName2);
					var tableName = defineOptions.freezeTableName ? modelName : (Utils.pluralize(modelName1) + Utils.pluralize(defineOptions.camelThrough ? Utils.uppercaseFirst(modelName2) : modelName2));

					var throughOptions = {tableName: tableName};
					throughOptions.skipFields = (options.skipFields !== undefined) ? options.skipFields : defineOptions.skipFieldsOnThrough;

					options.through = defineOne(modelName, {fields: fields, options: throughOptions});
				}

				utils.defaultsNoUndef(options, {
					onDelete: defineOptions.onDelete,
					onUpdate: defineOptions.onUpdate
				});

				var asReverse = utils.pop(options, 'asReverse');

				var joinOptions = _.clone(options);
				joinOptions.foreignKey = modelName1 + Utils.uppercaseFirst(key1);
				model1.hasMany(model2, joinOptions);

				joinOptions = _.clone(options);
				utils.setNoUndef(joinOptions, 'as', asReverse);
				joinOptions.foreignKey = modelName2 + Utils.uppercaseFirst(key2);
				model2.hasMany(model1, joinOptions);
			});
		}
	};

	Sequelize.prototype.defineFromFolder = function(path, options) {
		var loadOptions = (options || {}).loadOptions || {};
		loadOptions.flatten = true;

		var definitions = requireFolderTree(path, loadOptions);

		return this.defineAll(definitions, options);
	};

	return Sequelize;
};
<|endoftext|>


<commit_before>require('./global');
var path = require('path');
var log4js = require('log4js');
var serviceLocator = require('./service-locator');
var Logger = require('./logger');
var CMApiClient = require('./cm-api-client');
var JanusHttpClient = require('./janus/http-client');
var Streams = require('./streams');
var CmApplication = require('./cm-application');
var Context = require('./context');

var HttpServer = require('./http-server');
var JanusProxy = require('./janus/proxy');
var JobManager = require('./job/manager');
var Promise = require('bluebird');

/**
 * @param {Config} config
 * @param {Array} roles
 * @constructor
 */
function Application(config, roles) {
  this.config = config;
  this.roles = roles;
}

Application.prototype.registerServices = function() {
  serviceLocator.register('logger', function() {
    var logFilePath = path.resolve(path.dirname(__dirname), this.config['logPath']);
    log4js.configure({
      "appenders": [
        {
          "type": "logLevelFilter",
          "level": "DEBUG",
          "appender": {
            "type": "console",
            "layout": {
              "type": "colored"
            }
          }
        },
        {
          "type": "logLevelFilter",
          "level": "INFO",
          "appender": {
            "type": "file",
            "filename": logFilePath,
            "layout": {
              "type": "json"
            }
          }
        }
      ]
    });
    return new Logger(log4js.getLogger());
  }.bind(this));

  serviceLocator.register('cm-api-client', function() {
    return new CMApiClient(this.config['cmApi']['baseUrl'], this.config['cmApi']['apiKey']);
  }.bind(this));

  serviceLocator.register('http-client', function() {
    return new JanusHttpClient(this.config['janus']['httpAddress']);
  }.bind(this));

  serviceLocator.register('streams', function() {
    return new Streams();
  });

  serviceLocator.register('cm-application', function() {
    return new CmApplication(this.config['cmApplication']['path']);
  }.bind(this));
};

Application.prototype.start = function() {
  var services = [];

  if (_.contains(this.roles, 'server')) {
    var proxy = new JanusProxy(this.config['webSocketServer']['port'], this.config['janus']['webSocketAddress']);
    var httpServer = new HttpServer(this.config['httpServer']['port'], this.config['httpServer']['apiKey']);
    services.push(proxy);
    services.push(httpServer);
  }

  if (_.contains(this.roles, 'jobs')) {
    var jobManager = new JobManager(this.config['jobManager']['jobsPath'], this.config['jobManager']['tempFilesPath']);
    jobManager.handlerRegistry.registerFromConfiguration(this.config['jobManager']['handlersConfiguration']);
    services.push(jobManager);
  }

  Promise.map(services, function(service) {
    return service.start();
  }).catch(function(error) {
    serviceLocator.get('logger').fatal('Process failed. Exiting.', new Context({exception: error}));
    process.emit('close');
  });

  process.on('unhandledRejection', function(reason) {
    if ('This socket has been ended by the other party' == reason.message) {
      serviceLocator.get('logger').warn('Expected rejection error', new Context({exception: reason}));
    } else {
      serviceLocator.get('logger').fatal('Unexpected rejection error', new Context({exception: reason}));
    }
  });

  process.on('uncaughtException', function(error) {
    serviceLocator.get('logger').fatal('Unexpected runtime error. Shutdown the process.', new Context({exception: error}));
    process.emit('close');
  });

  process.on('SIGINT', function() {
    process.emit('close');
  });

  process.on('SIGTERM', function() {
    process.emit('close');
  });

  process.on('close', function() {
    serviceLocator.get('logger').info('Closing application');
    Promise.map(services, function(service) {
      return service.stop();
    }).finally(function() {
      process.nextTick(process.exit(1));
    });
  });
};

module.exports = Application;
<commit_msg>Revert "Formatting"<commit_after>require('./global');
var path = require('path');
var log4js = require('log4js');
var serviceLocator = require('./service-locator');
var Logger = require('./logger');
var CMApiClient = require('./cm-api-client');
var JanusHttpClient = require('./janus/http-client');
var Streams = require('./streams');
var CmApplication = require('./cm-application');
var Context = require('./context');

var HttpServer = require('./http-server');
var JanusProxy = require('./janus/proxy');
var JobManager = require('./job/manager');
var Promise = require('bluebird');

/**
 * @param {Config} config
 * @param {Array} roles
 * @constructor
 */
function Application(config, roles) {
  this.config = config;
  this.roles = roles;
}

Application.prototype.registerServices = function() {
  serviceLocator.register('logger', function() {
    var logFilePath = path.resolve(path.dirname(__dirname), this.config['logPath']);
    log4js.configure({
      "appenders": [
        {
          "type": "logLevelFilter",
          "level": "DEBUG",
          "appender": {
            "type": "console",
            "layout": {
              "type": "colored"
            }
          }
        },
        {
          "type": "logLevelFilter",
          "level": "INFO",
          "appender": {
            "type": "file",
            "filename": logFilePath,
            "layout": {
              "type": "json"
            }
          }
        }
      ]
    });
    return new Logger(log4js.getLogger());
  }.bind(this));

  serviceLocator.register('cm-api-client', function() {
    return new CMApiClient(this.config['cmApi']['baseUrl'], this.config['cmApi']['apiKey']);
  }.bind(this));

  serviceLocator.register('http-client', function() {
    return new JanusHttpClient(this.config['janus']['httpAddress']);
  }.bind(this));

  serviceLocator.register('streams', function() {
    return new Streams();
  });

  serviceLocator.register('cm-application', function() {
    return new CmApplication(this.config['cmApplication']['path']);
  }.bind(this));
};

Application.prototype.start = function() {
  var services = [];

  if (_.contains(this.roles, 'server')) {
    var proxy = new JanusProxy(this.config['webSocketServer']['port'], this.config['janus']['webSocketAddress']);
    var httpServer = new HttpServer(this.config['httpServer']['port'], this.config['httpServer']['apiKey']);
    services.push(proxy);
    services.push(httpServer);
  }

  if (_.contains(this.roles, 'jobs')) {
    var jobManager = new JobManager(this.config['jobManager']['jobsPath'], this.config['jobManager']['tempFilesPath']);
    jobManager.handlerRegistry.registerFromConfiguration(this.config['jobManager']['handlersConfiguration']);
    services.push(jobManager);
  }

  Promise.map(services, function(service) {
    return service.start();
  }).catch(function(error) {
    serviceLocator.get('logger').fatal('Process failed. Exiting.', new Context({exception: error}));
    process.emit('close');
  });

  process.on('unhandledRejection', function(reason) {
    if ('This socket has been ended by the other party' == reason.message) {
      serviceLocator.get('logger').warn('Expected rejection error.', new Context({exception: reason}));
    } else {
      serviceLocator.get('logger').fatal('Unexpected rejection error.', new Context({exception: reason}));
    }
  });

  process.on('uncaughtException', function(error) {
    serviceLocator.get('logger').fatal('Unexpected runtime error. Shutdown the process.', new Context({exception: error}));
    process.emit('close');
  });

  process.on('SIGINT', function() {
    process.emit('close');
  });

  process.on('SIGTERM', function() {
    process.emit('close');
  });

  process.on('close', function() {
    serviceLocator.get('logger').info('Closing application');
    Promise.map(services, function(service) {
      return service.stop();
    }).finally(function() {
      process.nextTick(process.exit(1));
    });
  });
};

module.exports = Application;
<|endoftext|>


<commit_before>'use strict';

// Transparently support JSX
require('node-jsx').install({extension: '.jsx'});

var tollan = require('tollan-client');
var serveStatic = require('serve-static');

tollan.React = require('react');
tollan.Router = require('react-router');
tollan.newforms = require('newforms');
tollan.BootstrapForm = require('newforms-bootstrap');

// Tollan configuration
tollan.config = {
	apiPrefix: '/api',
	routes: require('./routes')(tollan),
	defaultPageTitle: 'Tollan Example',
	port: 3001
};

// Serve our front-end files
tollan.app.use(serveStatic('build'));

// Use our API
// Could also have the API on a separate server/process, so it could be on a
// separate physical machine, for scalability.
// TODO: should be able to have the API on a separate process
var api = require('./api')(tollan);
var actionRoutes = require('./actionRoutes')(tollan);
var modelRoutes = require('./modelRoutes')(tollan);

tollan.app.use(config.apiPrefix+'/action', actionRoutes);
tollan.app.use(config.apiPrefix+'/model', modelRoutes);
tollan.app.use(config.apiPrefix, api);

var eventStreamer = require('./eventStreamer');
var dynamicItemAddedProjection = require('./projections/dynamicItemAdded');
dynamicItemAddedProjection.then(function(projection) {
	eventStreamer.on('dynamic/itemAdded', projection);
	eventStreamer.start();
});

// Start Tollan
tollan.start();
<commit_msg>Bugfix from previous<commit_after>'use strict';

// Transparently support JSX
require('node-jsx').install({extension: '.jsx'});

var tollan = require('tollan-client');
var serveStatic = require('serve-static');

tollan.React = require('react');
tollan.Router = require('react-router');
tollan.newforms = require('newforms');
tollan.BootstrapForm = require('newforms-bootstrap');

// Tollan configuration
tollan.config = {
	apiPrefix: '/api',
	routes: require('./routes')(tollan),
	defaultPageTitle: 'Tollan Example',
	port: 3001
};

// Serve our front-end files
tollan.app.use(serveStatic('build'));

// Use our API
// Could also have the API on a separate server/process, so it could be on a
// separate physical machine, for scalability.
// TODO: should be able to have the API on a separate process
var api = require('./api')(tollan);
var actionRoutes = require('./actionRoutes')(tollan);
var modelRoutes = require('./modelRoutes')(tollan);

tollan.app.use(tollan.config.apiPrefix+'/action', actionRoutes);
tollan.app.use(tollan.config.apiPrefix+'/model', modelRoutes);
tollan.app.use(tollan.config.apiPrefix, api);

var eventStreamer = require('./eventStreamer');
var dynamicItemAddedProjection = require('./projections/dynamicItemAdded');
dynamicItemAddedProjection.then(function(projection) {
	eventStreamer.on('dynamic/itemAdded', projection);
	eventStreamer.start();
});

// Start Tollan
tollan.start();
<|endoftext|>


<commit_before>/**
 * Randy is a country singer that sends notifications, drives a Trans Am, and is one serious bad ass.
 *
 * @package randy
 * @author Andrew Sliwinski <andrew@diy.org>
 */

/**
 * Dependencies
 */
var _       = require('underscore'),
    async   = require('async'),
    redis   = require('redis'),
    sio     = require('socket.io'),
    uuid    = require('node-uuid');

var Util    = require('./util'),
    Storage = require('./storage');

/**
 * Generic socket emitter.
 *
 * @param {Object} Socket
 * @param {Object} Notice
 *
 * @return {void}
 */
function emit (socket, notice) {
    socket.emit('notice', notice);
}

// --------------------------------

/**
 * Constructor
 */
function Randy () {
    var self = this;

    // Setup
    self.ns         = 'randy';
    self.pub        = null;
    self.sub        = null;
    self.store      = null;
    self.io         = null;
    self.sockets    = new Object(null);

    /**
     * Gets the socket (if available) for the specified target.
     *
     * @param {String} Target
     *
     * @return {Object}
     */
    function getSocket (target, callback) {
        if (target === null || target === '') {
            callback(null, self.io.sockets);
        } else {
            try {
                callback(null, self.sockets[target].socket);
            } catch (err) {
                Util.stdout(err);
            }
        }
    };

    /**
     * Subscription "message" event handler.
     *
     * @param {String} Channel
     * @param {String} Notice (JSON String)
     *
     * @return {void}
     */
    self.listener   = function (channel, data) {
        async.auto({
            decode:      function (callback) {
                Util.parse(data, callback);
            },

            socket:     ['decode', function (callback, obj) {
                getSocket(obj.decode.target, callback);
            }],

            emit:       ['socket', function (callback, obj) {
                emit(obj.socket, obj.decode);
            }]
        }, Util.stdout);
    };

    /**
     * Socket.io "connection" event handler.
     *
     * @param {Object} Socket
     *
     * @return {void}
     */
    self.connection = function (socket) {

        /**
         * Registers a socket to begin recieving notifications.
         *
         * @param {String} Unique user id
         *
         * @return {void}
         */
        socket.on('register', function (id) {
            // Check if exists
            if (typeof self.sockets[id] === 'undefined') {
                self.sockets[id] = {
                    id:         socket.id,
                    socket:     socket,
                    storage:    {}
                };
            } else {
                self.sockets[id].id     = socket.id;
                self.sockets[id].socket = socket;
            }

            // Emit from storage
            var storage = self.sockets[id].storage;
            async.forEach(Object.keys(storage), function (obj, callback) {
                emit(socket, storage[obj]);
                callback();
            }, Util.stdout);
        });

        /**
         * Dismisses a persistent notification.
         *
         * @param {Object} Identity
         *                      - id {String, Required}
         *                      - uid {String, Required}
         *
         * @return {void}
         */
        socket.on('dismiss', function (data) {
            try {
                delete self.sockets[data.uid].storage[id];
            } catch (err) {
                Util.stdout(err);
            }
        });

        /**
         * Submits a new event via the loopback interface.
         *
         * @param {Object} Notification object (see "register" method).
         *
         * @return {void}
         */
        socket.on('loopback', function (data) {
            self.submit(data, Util.stdout);
        });
    };
};

/**
 * Start listening for connections on the specified port.
 *
 * @param {Number} Port
 *
 * @return {Error}
 */
Randy.prototype.listen = function (port, arg, callback) {
    var self = this;

    // Detect argument list
    if (_.isUndefined(callback)) {
        callback    = arg;
        arg         = {
            port:       null,
            host:       null,
            options:    null
        };
    };

    try {
        // Storage
        self.store  = new Storage(redis.createClient(arg.port, arg.host, arg.options));

        // Pub / Sub
        self.pub    = redis.createClient(arg.port, arg.host, arg.options);
        self.sub    = redis.createClient(arg.port, arg.host, arg.options);
        self.sub.subscribe(self.ns);
        self.sub.on('message', self.listener);

        // Socket.io
        self.io     = sio.listen(port);
        self.io.set('log level', 1);
        self.io.sockets.on('connection', self.connection);
        callback(null);
    } catch (err) {
        Util.stdout(err);
    }
};

/**
 * Submits a new notification.
 *
 * @param {Object} Notification
 *                  - persist {Boolean, Default=false}
 *                  - target {String, Default=null}
 *                  - message {String, Required}
 *
 * @return {Error}
 */
Randy.prototype.submit = function (notice, callback) {
    var self = this;

    _.defaults(notice, {
        id:         uuid.v4(),                  // Assign uuid
        stamp:      new Date().toJSON(),        // Timestamp
        persist:    false,
        target:     null,
        message:    null
    });

    // Normalize typing
    notice.persist  = (notice.persist.toLowerCase() === 'true' || notice.persist === true) ? true : false;
    notice.target   = (notice.target === '') ? null : notice.target;

    // Persist
    // @note Incorrect... pending data storage
    if (notice.persist) {
        try {
            self.sockets[notice.target].storage[notice.id] = notice;
        } catch (err) {
            Util.stdout('Can not persist notifications without a valid target.');
        }
    }

    // If no message is specified, drop the request
    if (notice.message === null || notice.message === '') {
        return callback('No message was specified.');
    }

    // Hash notice and publish to redis store
    async.auto({
        encode:     function (callback) {
            Util.stringify(notice, callback);
        },

        publish:    ['encode', function (callback, obj) {
            self.pub.publish(self.ns, obj.encode);
            callback(null);
        }]
    }, callback);
};

/**
 * Destroy the socket.io connection and redis subscription(s).
 *
 * @return {Error}
 */
Randy.prototype.destroy = function (callback) {
    var self = this;

    try {
        self.sub.unsubscribe();
        self.pub.end();
        self.sub.end();
        callback(null);
    } catch (err) {
        Util.stdout(err);
    }
};

// --------------------------------
// --------------------------------

/**
 * Export
 */
module.exports = new Randy();
<commit_msg>Migrate to persistent data store<commit_after>/**
 * Randy is a country singer that sends notifications, drives a Trans Am, and is one serious bad ass.
 *
 * @package randy
 * @author Andrew Sliwinski <andrew@diy.org>
 */

/**
 * Dependencies
 */
var _       = require('underscore'),
    async   = require('async'),
    redis   = require('redis'),
    sio     = require('socket.io'),
    uuid    = require('node-uuid');

var Util    = require('./util'),
    Storage = require('./storage');

/**
 * Generic socket emitter.
 *
 * @param {Object} Socket
 * @param {Object} Notice
 *
 * @return {void}
 */
function emit (socket, notice) {
    socket.emit('notice', notice);
}

// --------------------------------

/**
 * Constructor
 */
function Randy () {
    var self = this;

    // Setup
    self.ns         = 'randy';
    self.pub        = null;
    self.sub        = null;
    self.store      = null;
    self.io         = null;
    self.sockets    = new Object(null);

    /**
     * Gets the socket (if available) for the specified target.
     *
     * @param {String} Target
     *
     * @return {Object}
     */
    function getSocket (target, callback) {
        if (target === null || target === '') {
            callback(null, self.io.sockets);
        } else {
            try {
                callback(null, self.sockets[target].socket);
            } catch (err) {
                Util.stdout(err);
            }
        }
    };

    /**
     * Subscription "message" event handler.
     *
     * @param {String} Channel
     * @param {String} Notice (JSON String)
     *
     * @return {void}
     */
    self.listener   = function (channel, data) {
        async.auto({
            decode:      function (callback) {
                Util.parse(data, callback);
            },

            socket:     ['decode', function (callback, obj) {
                getSocket(obj.decode.target, callback);
            }],

            emit:       ['socket', function (callback, obj) {
                emit(obj.socket, obj.decode);
            }]
        }, Util.stdout);
    };

    /**
     * Socket.io "connection" event handler.
     *
     * @param {Object} Socket
     *
     * @return {void}
     */
    self.connection = function (socket) {

        /**
         * Registers a socket to begin recieving notifications.
         *
         * @param {String} Unique user id
         *
         * @return {void}
         */
        socket.on('register', function (id) {
            // Check if exists
            if (typeof self.sockets[id] === 'undefined') {
                self.sockets[id] = {
                    id:         socket.id,
                    socket:     socket
                };
            } else {
                self.sockets[id].id     = socket.id;
                self.sockets[id].socket = socket;
            }

            // Emit from storage
            self.store.all(id, function (err, obj) {
                if (err) {
                    callback(err);
                } else {
                    async.forEach(obj, function (a, callback) {
                        emit(socket, a);
                        callback();
                    }, Util.stdout);
                }
            });
        });

        /**
         * Dismisses a persistent notification.
         *
         * @param {Object} Identity
         *                      - id {String, Required}
         *                      - uid {String, Required}
         *
         * @return {void}
         */
        socket.on('dismiss', function (data) {
            self.store.del(data.uid, data.id, Util.stdout);
        });

        /**
         * Submits a new event via the loopback interface.
         *
         * @param {Object} Notification object (see "register" method).
         *
         * @return {void}
         */
        socket.on('loopback', function (data) {
            self.submit(data, Util.stdout);
        });
    };
};

/**
 * Start listening for connections on the specified port.
 *
 * @param {Number} Port
 *
 * @return {Error}
 */
Randy.prototype.listen = function (port, arg, callback) {
    var self = this;

    // Detect argument list
    if (_.isUndefined(callback)) {
        callback    = arg;
        arg         = {
            port:       null,
            host:       null,
            options:    null
        };
    };

    try {
        // Storage
        self.store  = new Storage(redis.createClient(arg.port, arg.host, arg.options));

        // Pub / Sub
        self.pub    = redis.createClient(arg.port, arg.host, arg.options);
        self.sub    = redis.createClient(arg.port, arg.host, arg.options);
        self.sub.subscribe(self.ns);
        self.sub.on('message', self.listener);

        // Socket.io
        self.io     = sio.listen(port);
        self.io.set('log level', 1);
        self.io.sockets.on('connection', self.connection);
        callback(null);
    } catch (err) {
        Util.stdout(err);
    }
};

/**
 * Submits a new notification.
 *
 * @param {Object} Notification
 *                  - persist {Boolean, Default=false}
 *                  - target {String, Default=null}
 *                  - message {String, Required}
 *
 * @return {Error}
 */
Randy.prototype.submit = function (notice, callback) {
    var self = this;

    _.defaults(notice, {
        id:         uuid.v4(),                  // Assign uuid
        stamp:      new Date().toJSON(),        // Timestamp
        persist:    false,
        target:     null,
        message:    null
    });

    // Normalize typing
    notice.persist  = (notice.persist.toLowerCase() === 'true' || notice.persist === true) ? true : false;
    notice.target   = (notice.target === '') ? null : notice.target;

    // Persist
    if (notice.persist && notice.target !== null) {
        self.store.set(notice.target, notice.id, notice, Util.stdout);
    }

    // If no message is specified, drop the request
    if (notice.message === null || notice.message === '') {
        return callback('No message was specified.');
    }

    // Hash notice and publish to redis store
    async.auto({
        encode:     function (callback) {
            Util.stringify(notice, callback);
        },

        publish:    ['encode', function (callback, obj) {
            self.pub.publish(self.ns, obj.encode);
            callback(null);
        }]
    }, callback);
};

/**
 * Destroy the socket.io connection and redis subscription(s).
 *
 * @return {Error}
 */
Randy.prototype.destroy = function (callback) {
    var self = this;

    try {
        self.sub.unsubscribe();
        self.pub.end();
        self.sub.end();
        callback(null);
    } catch (err) {
        Util.stdout(err);
    }
};

// --------------------------------
// --------------------------------

/**
 * Export
 */
module.exports = new Randy();
<|endoftext|>


<commit_before>'use strict'

const Github = require('github')
    , pkg = require('../package')

module.exports = GetReviewers

const users = {
  // TSC
  'bnoordhuis': 'Ben Noordhuis <info@bnoordhuis.nl>'
, 'chrisdickinson': 'Chris Dickinson <christopher.s.dickinson@gmail.com>'
, 'cjihrig': 'Colin Ihrig <cjihrig@gmail.com>'
, 'Fishrock123': 'Jeremiah Senkpiel <fishrock123@rocketmail.com>'
, 'indutny': 'Fedor Indutny <fedor.indutny@gmail.com>'
, 'jasnell': 'James M Snell <jasnell@gmail.com>'
, 'misterdjules': 'Julien Gilli <jgilli@nodejs.org>'
, 'mscdex': 'Brian White <mscdex@mscdex.net>'
, 'orangemocha': 'Alexis Campailla <orangemocha@nodejs.org>'
, 'piscisaureus': 'Bert Belder <bertbelder@gmail.com>'
, 'rvagg': 'Rod Vagg <rod@vagg.org>'
, 'shigeki': 'Shigeki Ohtsu <ohtsu@iij.ad.jp>'
, 'trevnorris': 'Trevor Norris <trev.norris@gmail.com>'
  // Collaborators
, 'addaleax': 'Anna Henningsen <anna@addaleax.net>'
, 'ak239': 'Aleksei Koziatinskii <ak239spb@gmail.com>'
, 'andrasq': 'Andras <andras@kinvey.com>'
, 'bengl': 'Bryan English <bryan@bryanenglish.com>'
, 'bmeck': 'Bradley Farias <bradley.meck@gmail.com>'
, 'AndreasMadsen': 'Andreas Madsen <amwebdk@gmail.com>'
, 'benjamingr': 'Benjamin Gruenbaum <benjamingr@gmail.com>'
, 'brendanashworth': 'Brendan Ashworth <brendan.ashworth@me.com>'
, 'bzoz': 'Bartosz Sosnowski <bartosz@janeasystems.com>'
, 'calvinmetcalf': 'Calvin Metcalf <calvin.metcalf@gmail.com>'
, 'ChALkeR': 'Сковорода Никита Андреевич <chalkerx@gmail.com>'
, 'claudiorodriguez': 'Claudio Rodriguez <cjrodr@yahoo.com>'
, 'danbev': 'Daniel Bevenius <daniel.bevenius@gmail.com>'
, 'domenic': 'Domenic Denicola <d@domenic.me>'
, 'eljefedelrodeodeljefe': 'Robert Lindstaedt <robert.lindstaedt@gmail.com>'
, 'estliberitas': 'Alexander Makarenko <estliberitas@gmail.com>'
, 'eugeneo': 'Eugene Ostroukhov <eostroukhov@google.com>'
, 'evanlucas': 'Evan Lucas <evanlucas@me.com>'
, 'fhinkel': 'Franziska Hinkelmann <franziska.hinkelmann@gmail.com>'
, 'firedfox': 'Daniel Wang <wangyang0123@gmail.com>'
, 'geek': 'Wyatt Preul <wpreul@gmail.com>'
, 'gibfahn': 'Gibson Fahnestock <gibfahn@gmail.com>'
, 'iarna': 'Rebecca Turner <me@re-becca.org>'
, 'imyller': 'Ilkka Myller <ilkka.myller@nodefield.com>'
, 'isaacs': 'Isaac Z. Schlueter <i@izs.me>'
, 'iWuzHere': 'Imran Iqbal <imran@imraniqbal.org>'
, 'JacksonTian': 'Jackson Tian <shvyo1987@gmail.com>'
, 'jbergstroem': 'Johan Bergström <bugs@bergstroem.nu>'
, 'jhamhader': 'Yuval Brik <yuval@brik.org.il>'
, 'joaocgreis': 'João Reis <reis@janeasystems.com>'
, 'joshgav': 'Josh Gavant <josh.gavant@outlook.com>'
, 'julianduque': 'Julian Duque <julianduquej@gmail.com>'
, 'JungMinu': 'Minwoo Jung <jmwsoft@gmail.com>'
, 'lance': 'Lance Ball <lball@redhat.com>'
, 'lpinca': 'Luigi Pinca <luigipinca@gmail.com>'
, 'lxe': 'Aleksey Smolenchuk <lxe@lxe.co>'
, 'matthewloring': 'Matthew Loring <mattloring@google.com>'
, 'mcollina': 'Matteo Collina <matteo.collina@gmail.com>'
, 'mhdawson': 'Michael Dawson <michael_dawson@ca.ibm.com>'
, 'micnic': 'Nicu Micleușanu <micnic90@gmail.com>'
, 'mikeal': 'Mikeal Rogers <mikeal.rogers@gmail.com>'
, 'monsanto': 'Christopher Monsanto <chris@monsan.to>'
, 'not-an-aardvark': 'Teddy Katz <teddy.katz@gmail.com>'
, 'ofrobots': 'Ali Ijaz Sheikh <ofrobots@google.com>'
, 'Olegas': 'Oleg Elifantiev <oleg@elifantiev.ru>'
, 'othiym23': 'Forrest L Norvell <ogd@aoaioxxysz.net>'
, 'petkaantonov': 'Petka Antonov <petka_antonov@hotmail.com>'
, 'phillipj': 'Phillip Johnsen <johphi@gmail.com>'
, 'pmq20': 'Minqi Pan <pmq2001@gmail.com>'
, 'princejwesley': 'Prince John Wesley <princejohnwesley@gmail.com>'
, 'Qard': 'Stephen Belanger <admin@stephenbelanger.com>'
, 'rlidwka': 'Alex Kocharin <alex@kocharin.ru>'
, 'rmg': 'Ryan Graham <r.m.graham@gmail.com>'
, 'robertkowalski': 'Robert Kowalski <rok@kowalski.gd>'
, 'romankl': 'Roman Klauke <romaaan.git@gmail.com>'
, 'ronkorving': 'Ron Korving <ron@ronkorving.nl>'
, 'RReverser': 'Ingvar Stepanyan <me@rreverser.com>'
, 'saghul': 'Saúl Ibarra Corretgé <saghul@gmail.com>'
, 'sam-github': 'Sam Roberts <vieuxtech@gmail.com>'
, 'santigimeno': 'Santiago Gimeno <santiago.gimeno@gmail.com>'
, 'seishun': 'Nikolai Vavilov <vvnicholas@gmail.com>'
, 'silverwind': 'Roman Reiss <me@silverwind.io>'
, 'srl295': 'Steven R Loomis <srloomis@us.ibm.com>'
, 'stefanmb': 'Stefan Budeanu <stefan@budeanu.com>'
, 'targos': 'Michaël Zasso <mic.besace@gmail.com>'
, 'tellnes': 'Christian Tellnes <christian@tellnes.no>'
, 'TheAlphaNerd': 'Myles Borins <myles.borins@gmail.com>'
, 'thefourtheye': 'Sakthipriyan Vairamani <thechargingvolcano@gmail.com>'
, 'thekemkid': 'Glen Keane <glenkeane.94@gmail.com>'
, 'thlorenz': 'Thorsten Lorenz <thlorenz@gmx.de>'
, 'Trott': 'Rich Trott <rtrott@gmail.com>'
, 'tunniclm': 'Mike Tunnicliffe <m.j.tunnicliffe@gmail.com>'
, 'vkurchatkin': 'Vladimir Kurchatkin <vladimir.kurchatkin@gmail.com>'
, 'whitlockjc': 'Jeremy Whitlock <jwhitlock@apache.org>'
, 'yorkie': 'Yorkie Liu <yorkiefixer@gmail.com>'
, 'yosuke-furukawa': 'Yosuke Furukawa <yosuke.furukawa@gmail.com>'
, 'zkat': 'Kat Marchán <kzm@sykosomatic.org>'
}

function GetReviewers(opts) {
  if (!(this instanceof GetReviewers))
    return new GetReviewers(opts)

  this.version = pkg.version
  this.opts = opts
  this.github = new Github({
    version: '3.0.0'
  , headers: {
      'User-Agent': `core-get-reviewers v${pkg.version}`
    }
  })

  this.github.authenticate({
    type: 'oauth'
  , token: opts.token
  })
}

GetReviewers.users = users

// the Collaborators team is id 1202829
GetReviewers.prototype.fetchCollabs = function fetchCollabs(cb) {
  this.fetchTeams((err, team) => {
    if (err) return cb(err)
    const id = team.id
    this.github.orgs.getTeamMembers({
      id: team.id
    , page: 0
    , per_page: 100
    }, (err, members) => {
      if (err) return cb(err)
      const out = members.map((item) => {
        return item.login
      })
      cb(null, out)
    })
  })
}

GetReviewers.prototype.fetchTeams = function fetchTeams(cb) {
  this.github.orgs.getTeams({
    org: 'nodejs'
  , page: 0
  , per_page: 50
  }, (err, teams) => {
    if (err) return cb(err)
    for (let i = 0; i < teams.length; i++) {
      const team = teams[i]
      if (team.name === 'Collaborators') {
        return cb(null, team)
      }
    }
    cb(new Error('Unable to find collaborators team'))
  })
}

GetReviewers.prototype.getReviewer = function getReviewer(username) {
  return users[username]
}

GetReviewers.prototype.fetchPR = function fetchPR(number, cb) {
  var self = this
  if (!number) {
    setImmediate(function() {
      cb(new Error('PR number is required'))
    })
    return
  }
  // TODO(evanlucas) handle situations where there are > 100 comments
  self.github.issues.getComments({
    user: 'nodejs'
  , repo: this.opts.nodePrivate ? 'node-private' : 'node'
  , number: number
  , page: 0
  , per_page: 100
  }, function(err, comments) {
    if (err) return cb(err)
    comments = comments.filter(function(comment) {
      return /LGTM/i.test(comment.body)
        && users.hasOwnProperty(comment.user.login)
    }).reduce(function(set, comment) {
      if (!set.hasOwnProperty(comment.user.login)) {
        set[comment.user.login] = {
          username: comment.user.login
        , userId: comment.user.id
        , body: comment.body
        }
      }

      return set
    }, {})

    const keys = Object.keys(comments)
        , len = keys.length
        , out = new Array(len)

    for (var i = 0; i < len; i++) {
      out[i] = comments[keys[i]]
    }
    cb(null, out)
  })
}

GetReviewers.prototype.generate = function generate(pr, reviewers) {
  var str = `\nPR-URL: https://github.com/nodejs/${this.opts.nodePrivate ? 'node-private' : 'node'}/pull/${pr}`
  var len = reviewers.length
  for (var i = 0; i < len; i++) {
    var reviewer = reviewers[i].username
    var email = users[reviewer]
    if (!email) {
      throw new Error(`Cannot find email for reviewer ${reviewer}`)
    }
    str += `\nReviewed-By: ${email}`
  }

  return str
}
<commit_msg>s/thealphanerd/mylesborins (#4)<commit_after>'use strict'

const Github = require('github')
    , pkg = require('../package')

module.exports = GetReviewers

const users = {
  // TSC
  'bnoordhuis': 'Ben Noordhuis <info@bnoordhuis.nl>'
, 'chrisdickinson': 'Chris Dickinson <christopher.s.dickinson@gmail.com>'
, 'cjihrig': 'Colin Ihrig <cjihrig@gmail.com>'
, 'Fishrock123': 'Jeremiah Senkpiel <fishrock123@rocketmail.com>'
, 'indutny': 'Fedor Indutny <fedor.indutny@gmail.com>'
, 'jasnell': 'James M Snell <jasnell@gmail.com>'
, 'misterdjules': 'Julien Gilli <jgilli@nodejs.org>'
, 'mscdex': 'Brian White <mscdex@mscdex.net>'
, 'orangemocha': 'Alexis Campailla <orangemocha@nodejs.org>'
, 'piscisaureus': 'Bert Belder <bertbelder@gmail.com>'
, 'rvagg': 'Rod Vagg <rod@vagg.org>'
, 'shigeki': 'Shigeki Ohtsu <ohtsu@iij.ad.jp>'
, 'trevnorris': 'Trevor Norris <trev.norris@gmail.com>'
  // Collaborators
, 'addaleax': 'Anna Henningsen <anna@addaleax.net>'
, 'ak239': 'Aleksei Koziatinskii <ak239spb@gmail.com>'
, 'andrasq': 'Andras <andras@kinvey.com>'
, 'bengl': 'Bryan English <bryan@bryanenglish.com>'
, 'bmeck': 'Bradley Farias <bradley.meck@gmail.com>'
, 'AndreasMadsen': 'Andreas Madsen <amwebdk@gmail.com>'
, 'benjamingr': 'Benjamin Gruenbaum <benjamingr@gmail.com>'
, 'brendanashworth': 'Brendan Ashworth <brendan.ashworth@me.com>'
, 'bzoz': 'Bartosz Sosnowski <bartosz@janeasystems.com>'
, 'calvinmetcalf': 'Calvin Metcalf <calvin.metcalf@gmail.com>'
, 'ChALkeR': 'Сковорода Никита Андреевич <chalkerx@gmail.com>'
, 'claudiorodriguez': 'Claudio Rodriguez <cjrodr@yahoo.com>'
, 'danbev': 'Daniel Bevenius <daniel.bevenius@gmail.com>'
, 'domenic': 'Domenic Denicola <d@domenic.me>'
, 'eljefedelrodeodeljefe': 'Robert Lindstaedt <robert.lindstaedt@gmail.com>'
, 'estliberitas': 'Alexander Makarenko <estliberitas@gmail.com>'
, 'eugeneo': 'Eugene Ostroukhov <eostroukhov@google.com>'
, 'evanlucas': 'Evan Lucas <evanlucas@me.com>'
, 'fhinkel': 'Franziska Hinkelmann <franziska.hinkelmann@gmail.com>'
, 'firedfox': 'Daniel Wang <wangyang0123@gmail.com>'
, 'geek': 'Wyatt Preul <wpreul@gmail.com>'
, 'gibfahn': 'Gibson Fahnestock <gibfahn@gmail.com>'
, 'iarna': 'Rebecca Turner <me@re-becca.org>'
, 'imyller': 'Ilkka Myller <ilkka.myller@nodefield.com>'
, 'isaacs': 'Isaac Z. Schlueter <i@izs.me>'
, 'iWuzHere': 'Imran Iqbal <imran@imraniqbal.org>'
, 'JacksonTian': 'Jackson Tian <shvyo1987@gmail.com>'
, 'jbergstroem': 'Johan Bergström <bugs@bergstroem.nu>'
, 'jhamhader': 'Yuval Brik <yuval@brik.org.il>'
, 'joaocgreis': 'João Reis <reis@janeasystems.com>'
, 'joshgav': 'Josh Gavant <josh.gavant@outlook.com>'
, 'julianduque': 'Julian Duque <julianduquej@gmail.com>'
, 'JungMinu': 'Minwoo Jung <jmwsoft@gmail.com>'
, 'lance': 'Lance Ball <lball@redhat.com>'
, 'lpinca': 'Luigi Pinca <luigipinca@gmail.com>'
, 'lxe': 'Aleksey Smolenchuk <lxe@lxe.co>'
, 'matthewloring': 'Matthew Loring <mattloring@google.com>'
, 'mcollina': 'Matteo Collina <matteo.collina@gmail.com>'
, 'mhdawson': 'Michael Dawson <michael_dawson@ca.ibm.com>'
, 'micnic': 'Nicu Micleușanu <micnic90@gmail.com>'
, 'mikeal': 'Mikeal Rogers <mikeal.rogers@gmail.com>'
, 'monsanto': 'Christopher Monsanto <chris@monsan.to>'
, 'MylesBorins': 'Myles Borins <myles.borins@gmail.com>'
, 'not-an-aardvark': 'Teddy Katz <teddy.katz@gmail.com>'
, 'ofrobots': 'Ali Ijaz Sheikh <ofrobots@google.com>'
, 'Olegas': 'Oleg Elifantiev <oleg@elifantiev.ru>'
, 'othiym23': 'Forrest L Norvell <ogd@aoaioxxysz.net>'
, 'petkaantonov': 'Petka Antonov <petka_antonov@hotmail.com>'
, 'phillipj': 'Phillip Johnsen <johphi@gmail.com>'
, 'pmq20': 'Minqi Pan <pmq2001@gmail.com>'
, 'princejwesley': 'Prince John Wesley <princejohnwesley@gmail.com>'
, 'Qard': 'Stephen Belanger <admin@stephenbelanger.com>'
, 'rlidwka': 'Alex Kocharin <alex@kocharin.ru>'
, 'rmg': 'Ryan Graham <r.m.graham@gmail.com>'
, 'robertkowalski': 'Robert Kowalski <rok@kowalski.gd>'
, 'romankl': 'Roman Klauke <romaaan.git@gmail.com>'
, 'ronkorving': 'Ron Korving <ron@ronkorving.nl>'
, 'RReverser': 'Ingvar Stepanyan <me@rreverser.com>'
, 'saghul': 'Saúl Ibarra Corretgé <saghul@gmail.com>'
, 'sam-github': 'Sam Roberts <vieuxtech@gmail.com>'
, 'santigimeno': 'Santiago Gimeno <santiago.gimeno@gmail.com>'
, 'seishun': 'Nikolai Vavilov <vvnicholas@gmail.com>'
, 'silverwind': 'Roman Reiss <me@silverwind.io>'
, 'srl295': 'Steven R Loomis <srloomis@us.ibm.com>'
, 'stefanmb': 'Stefan Budeanu <stefan@budeanu.com>'
, 'targos': 'Michaël Zasso <mic.besace@gmail.com>'
, 'tellnes': 'Christian Tellnes <christian@tellnes.no>'
, 'thefourtheye': 'Sakthipriyan Vairamani <thechargingvolcano@gmail.com>'
, 'thekemkid': 'Glen Keane <glenkeane.94@gmail.com>'
, 'thlorenz': 'Thorsten Lorenz <thlorenz@gmx.de>'
, 'Trott': 'Rich Trott <rtrott@gmail.com>'
, 'tunniclm': 'Mike Tunnicliffe <m.j.tunnicliffe@gmail.com>'
, 'vkurchatkin': 'Vladimir Kurchatkin <vladimir.kurchatkin@gmail.com>'
, 'whitlockjc': 'Jeremy Whitlock <jwhitlock@apache.org>'
, 'yorkie': 'Yorkie Liu <yorkiefixer@gmail.com>'
, 'yosuke-furukawa': 'Yosuke Furukawa <yosuke.furukawa@gmail.com>'
, 'zkat': 'Kat Marchán <kzm@sykosomatic.org>'
}

function GetReviewers(opts) {
  if (!(this instanceof GetReviewers))
    return new GetReviewers(opts)

  this.version = pkg.version
  this.opts = opts
  this.github = new Github({
    version: '3.0.0'
  , headers: {
      'User-Agent': `core-get-reviewers v${pkg.version}`
    }
  })

  this.github.authenticate({
    type: 'oauth'
  , token: opts.token
  })
}

GetReviewers.users = users

// the Collaborators team is id 1202829
GetReviewers.prototype.fetchCollabs = function fetchCollabs(cb) {
  this.fetchTeams((err, team) => {
    if (err) return cb(err)
    const id = team.id
    this.github.orgs.getTeamMembers({
      id: team.id
    , page: 0
    , per_page: 100
    }, (err, members) => {
      if (err) return cb(err)
      const out = members.map((item) => {
        return item.login
      })
      cb(null, out)
    })
  })
}

GetReviewers.prototype.fetchTeams = function fetchTeams(cb) {
  this.github.orgs.getTeams({
    org: 'nodejs'
  , page: 0
  , per_page: 50
  }, (err, teams) => {
    if (err) return cb(err)
    for (let i = 0; i < teams.length; i++) {
      const team = teams[i]
      if (team.name === 'Collaborators') {
        return cb(null, team)
      }
    }
    cb(new Error('Unable to find collaborators team'))
  })
}

GetReviewers.prototype.getReviewer = function getReviewer(username) {
  return users[username]
}

GetReviewers.prototype.fetchPR = function fetchPR(number, cb) {
  var self = this
  if (!number) {
    setImmediate(function() {
      cb(new Error('PR number is required'))
    })
    return
  }
  // TODO(evanlucas) handle situations where there are > 100 comments
  self.github.issues.getComments({
    user: 'nodejs'
  , repo: this.opts.nodePrivate ? 'node-private' : 'node'
  , number: number
  , page: 0
  , per_page: 100
  }, function(err, comments) {
    if (err) return cb(err)
    comments = comments.filter(function(comment) {
      return /LGTM/i.test(comment.body)
        && users.hasOwnProperty(comment.user.login)
    }).reduce(function(set, comment) {
      if (!set.hasOwnProperty(comment.user.login)) {
        set[comment.user.login] = {
          username: comment.user.login
        , userId: comment.user.id
        , body: comment.body
        }
      }

      return set
    }, {})

    const keys = Object.keys(comments)
        , len = keys.length
        , out = new Array(len)

    for (var i = 0; i < len; i++) {
      out[i] = comments[keys[i]]
    }
    cb(null, out)
  })
}

GetReviewers.prototype.generate = function generate(pr, reviewers) {
  var str = `\nPR-URL: https://github.com/nodejs/${this.opts.nodePrivate ? 'node-private' : 'node'}/pull/${pr}`
  var len = reviewers.length
  for (var i = 0; i < len; i++) {
    var reviewer = reviewers[i].username
    var email = users[reviewer]
    if (!email) {
      throw new Error(`Cannot find email for reviewer ${reviewer}`)
    }
    str += `\nReviewed-By: ${email}`
  }

  return str
}
<|endoftext|>


<commit_before>var url    = require("url");
var http = require('http');
var https = require('https');

function AtlassianCrowd(options) {
  settings = options || {};

  for (var i in options) {
    if(options.hasOwnProperty(i)) {
      settings[i] = options[i];
    }
  }

  if(settings.crowd.base === undefined) {
    throw new Error("Missing Required Setting Crowd Base URL");
  }

  if(settings.application.name === undefined) {
    throw new Error("Missing Required Setting Application Name");
  }

  if(settings.application.password === undefined) {
    throw new Error("Missing Required Setting Application Password");
  }

  var uri = url.parse(settings.crowd.base);

  settings.protocol   = uri.protocol;
  settings.hostname   = uri.hostname;
  settings.pathname   = uri.pathname;
  settings.apipath    = "rest/usermanagement/1";

  settings.authstring = settings.application.name + ":" + settings.application.password;

  if(!settings.port) {
    settings.port = (uri.port) ? uri.port : (uri.protocol === "https:") ? 443 : 80;
  }
}

AtlassianCrowd.prototype.search = function (type, query, callback) {
  if(type !== "user" && type !== "group" && typeof(query) !== "string") {
    var error = new Error("Invalid Search Type");
    error.type = "BAD_REQUEST";
    callback(error);
  }

  if(query.indexOf('=') !== -1) {
    query = require('querystring').escape(query);
  }

  var options = {
    "method": "GET",
    "path": "/search?entity-type=" + type + "&restriction=" + query
  };

  _doRequest(options, function (err, res) {
    return callback(err, res);
  });
};

AtlassianCrowd.prototype.ping = function (callback) {
  var options = {
    method: "GET",
    path: "/config/cookie"
  };

  _doRequest(options, function(err, res) {
    return callback(err, res);
  });
};

_doRequest = function (options, callback) {
  var data = "", error;

  var opts = {
    hostname: this.settings.hostname,
    port: this.settings.port,
    auth: this.settings.authstring,
    method: options.method,
    path: settings.pathname + settings.apipath + options.path,
    rejectUnauthorized: "rejectUnauthorized" in this.settings ? this.settings.rejectUnauthorized : true,
    headers: {
      "Accept": "application/json"
    }
  };

  if(options.method === "POST" || options.method === "PUT") {
    if(options.data) {
      opts.headers['content-type'] = "application/json; content-type: utf-8";
      opts.headers['content-length'] = Buffer.byteLength(options.data,'utf8');
    }
    else {
      error = new Error("Missing POST Data");
      error.type = "BAD_REQUEST";
      return callback(error);
    }
  }
  else {
    if(options.method === "DELETE") {
      // nginx requires content-length header also for DELETE requests
      opts.headers['content-length'] = '0';
    }
  }

  var protocol = (settings.protocol == "https:") ? https : http;

  var request = protocol.request(opts, function(response) {

    response.on('data', function(chunk) {
      data += chunk.toString();
    });

    if(response.statusCode === 204) {
      return callback(null, response.statusCode);
    }

    if(response.statusCode === 401) {
      error = new Error("Application Authorization Error");
      error.type = "APPLICATION_ACCESS_DENIED";
      return callback(error);
    }

    if(response.statusCode === 403) {
      error = new Error("Application Permission Denied");
      error.type = "APPLICATION_PERMISSION_DENIED";
      return callback(error);
    }

    response.on('end', function () {
      if (response.headers['content-type'] !== "application/json") {
        error = new Error("Invalid Response from Atlassian Crowd");
        error.type = "INVALID_RESPONSE";
        return callback(error);
      }
      else {
        if(data) {
          data = JSON.parse(data);
          if(data.reason || data.message) {
            if(typeof data.reason === "undefined") {
              data.reason = "BAD_REQUEST";
              data.message = "Invalid Request to Atlassian Crowd";
            }
            error = new Error(data.message);
            error.type = data.reason;
            return callback(error);
          }
          else {
            return callback(null, data);
          }
        }
        else {
          return callback(null, response.statusCode);
        }
      }
    });
  });

  //4.25.2014 - added to catch any errors that occur during request (ex. server not responding)
  request.on('error', function(error) {
	console.log('Error sending request: ' + error.message );
	callback(error, null);
  });

  if(options.data) {
    request.end(options.data,'utf8');
  }
  else {
    request.end();
  }
};

AtlassianCrowd.prototype.user = require('./user');
AtlassianCrowd.prototype.groups = require('./groups');
AtlassianCrowd.prototype.session = require('./session');

module.exports = AtlassianCrowd;
<commit_msg>fixed HTTP Content-Type Header to correctly specify application/json; charset=utf-8<commit_after>var url    = require("url");
var http = require('http');
var https = require('https');

function AtlassianCrowd(options) {
  settings = options || {};

  for (var i in options) {
    if(options.hasOwnProperty(i)) {
      settings[i] = options[i];
    }
  }

  if(settings.crowd.base === undefined) {
    throw new Error("Missing Required Setting Crowd Base URL");
  }

  if(settings.application.name === undefined) {
    throw new Error("Missing Required Setting Application Name");
  }

  if(settings.application.password === undefined) {
    throw new Error("Missing Required Setting Application Password");
  }

  var uri = url.parse(settings.crowd.base);

  settings.protocol   = uri.protocol;
  settings.hostname   = uri.hostname;
  settings.pathname   = uri.pathname;
  settings.apipath    = "rest/usermanagement/1";

  settings.authstring = settings.application.name + ":" + settings.application.password;

  if(!settings.port) {
    settings.port = (uri.port) ? uri.port : (uri.protocol === "https:") ? 443 : 80;
  }
}

AtlassianCrowd.prototype.search = function (type, query, callback) {
  if(type !== "user" && type !== "group" && typeof(query) !== "string") {
    var error = new Error("Invalid Search Type");
    error.type = "BAD_REQUEST";
    callback(error);
  }

  if(query.indexOf('=') !== -1) {
    query = require('querystring').escape(query);
  }

  var options = {
    "method": "GET",
    "path": "/search?entity-type=" + type + "&restriction=" + query
  };

  _doRequest(options, function (err, res) {
    return callback(err, res);
  });
};

AtlassianCrowd.prototype.ping = function (callback) {
  var options = {
    method: "GET",
    path: "/config/cookie"
  };

  _doRequest(options, function(err, res) {
    return callback(err, res);
  });
};

_doRequest = function (options, callback) {
  var data = "", error;

  var opts = {
    hostname: this.settings.hostname,
    port: this.settings.port,
    auth: this.settings.authstring,
    method: options.method,
    path: settings.pathname + settings.apipath + options.path,
    rejectUnauthorized: "rejectUnauthorized" in this.settings ? this.settings.rejectUnauthorized : true,
    headers: {
      "Accept": "application/json"
    }
  };

  if(options.method === "POST" || options.method === "PUT") {
    if(options.data) {
      opts.headers['content-type'] = "application/json; charset=utf-8";
      opts.headers['content-length'] = Buffer.byteLength(options.data,'utf8');
    }
    else {
      error = new Error("Missing POST Data");
      error.type = "BAD_REQUEST";
      return callback(error);
    }
  }
  else {
    if(options.method === "DELETE") {
      // nginx requires content-length header also for DELETE requests
      opts.headers['content-length'] = '0';
    }
  }

  var protocol = (settings.protocol == "https:") ? https : http;

  var request = protocol.request(opts, function(response) {

    response.on('data', function(chunk) {
      data += chunk.toString();
    });

    if(response.statusCode === 204) {
      return callback(null, response.statusCode);
    }

    if(response.statusCode === 401) {
      error = new Error("Application Authorization Error");
      error.type = "APPLICATION_ACCESS_DENIED";
      return callback(error);
    }

    if(response.statusCode === 403) {
      error = new Error("Application Permission Denied");
      error.type = "APPLICATION_PERMISSION_DENIED";
      return callback(error);
    }

    response.on('end', function () {
      if (response.headers['content-type'] !== "application/json") {
        error = new Error("Invalid Response from Atlassian Crowd");
        error.type = "INVALID_RESPONSE";
        return callback(error);
      }
      else {
        if(data) {
          data = JSON.parse(data);
          if(data.reason || data.message) {
            if(typeof data.reason === "undefined") {
              data.reason = "BAD_REQUEST";
              data.message = "Invalid Request to Atlassian Crowd";
            }
            error = new Error(data.message);
            error.type = data.reason;
            return callback(error);
          }
          else {
            return callback(null, data);
          }
        }
        else {
          return callback(null, response.statusCode);
        }
      }
    });
  });

  //4.25.2014 - added to catch any errors that occur during request (ex. server not responding)
  request.on('error', function(error) {
	console.log('Error sending request: ' + error.message );
	callback(error, null);
  });

  if(options.data) {
    request.end(options.data,'utf8');
  }
  else {
    request.end();
  }
};

AtlassianCrowd.prototype.user = require('./user');
AtlassianCrowd.prototype.groups = require('./groups');
AtlassianCrowd.prototype.session = require('./session');

module.exports = AtlassianCrowd;
<|endoftext|>


<commit_before>// Find urls within selected domain in posts
//

'use strict';

const _        = require('lodash');
const argparse = require('argparse');
const Promise  = require('bluebird');
const mongoose = require('mongoose');
const pump     = require('pump');
const stream   = require('stream');
const URL      = require('url');

let parser = new argparse.ArgumentParser();

parser.addArgument(
  [ '-d', '--db' ],
  {
    help: 'database name',
    defaultValue: 'nodeca'
  }
);

parser.addArgument(
  [ '-c', '--cutoff' ],
  {
    help: 'cutoff (days)',
    type: 'int'
  }
);

parser.addArgument(
  [ '-l', '--long' ],
  {
    help: 'hide short links (without query)',
    action: 'storeTrue'
  }
);

parser.addArgument(
  'domain',
  {
    help: 'domain name'
  }
);

let args = parser.parseArgs();

mongoose.Promise = Promise;

Promise.coroutine(function* () {
  yield mongoose.connect('mongodb://localhost/' + args.db);

  let Post = mongoose.model('forum.Post', new mongoose.Schema());

  let regexp_search = new RegExp('href="https?:\\/\\/[^\\/]*' + _.escapeRegExp(args.domain));

  let query = { html: regexp_search };

  if (args.cutoff) {
    let ts = Date.now() / 1000 - args.cutoff * 24 * 60 * 60;
    let min_objectid = new mongoose.Types.ObjectId(Math.floor(ts).toString(16) + '0000000000000000');

    query._id = { $gt: min_objectid };
  }

  yield Promise.fromCallback(callback => pump(
    Post.find(query).lean(true).cursor(),

    new stream.Writable({
      objectMode: true,
      write(post, encoding, callback) {
        let urls = post.html.match(/href="[^"]+"/g)
                     .map(href => _.unescape(href.replace(/^href="|"$/g, '')));

        urls.forEach(url => {
          let parsed = URL.parse(url, true, true);

          if (parsed.host && parsed.host.includes(args.domain)) {
            /* eslint-disable no-console */

            if (args.long) {
              if (Object.keys(parsed.query).length || parsed.hash) console.log(url, '\n');
            } else console.log(url, '\n');
          }
        });

        callback();
      }
    }),

    callback
  ));

  yield mongoose.disconnect();
})();
<commit_msg>find_urls: increase mongo timeout<commit_after>// Find urls within selected domain in posts
//

'use strict';

const _        = require('lodash');
const argparse = require('argparse');
const Promise  = require('bluebird');
const mongoose = require('mongoose');
const pump     = require('pump');
const stream   = require('stream');
const URL      = require('url');

let parser = new argparse.ArgumentParser();

parser.addArgument(
  [ '-d', '--db' ],
  {
    help: 'database name',
    defaultValue: 'nodeca'
  }
);

parser.addArgument(
  [ '-c', '--cutoff' ],
  {
    help: 'cutoff (days)',
    type: 'int'
  }
);

parser.addArgument(
  [ '-l', '--long' ],
  {
    help: 'hide short links (without query)',
    action: 'storeTrue'
  }
);

parser.addArgument(
  'domain',
  {
    help: 'domain name'
  }
);

let args = parser.parseArgs();

mongoose.Promise = Promise;

Promise.coroutine(function* () {
  const mongoose_options = {
    promiseLibrary: Promise,
    server: {
      poolSize: 10,
      socketOptions: {
        connectTimeoutMS: 10 * 60 * 1000,
        keepAlive: 1
      }
    },
    replset: {
      poolSize: 10,
      socketOptions: {
        connectTimeoutMS: 10 * 60 * 1000,
        keepAlive: 1
      }
    }
  };

  yield mongoose.connect('mongodb://localhost/' + args.db, mongoose_options);

  let Post = mongoose.model('forum.Post', new mongoose.Schema());

  let regexp_search = new RegExp('href="https?:\\/\\/[^\\/]*' + _.escapeRegExp(args.domain));

  let query = { html: regexp_search };

  if (args.cutoff) {
    let ts = Date.now() / 1000 - args.cutoff * 24 * 60 * 60;
    let min_objectid = new mongoose.Types.ObjectId(Math.floor(ts).toString(16) + '0000000000000000');

    query._id = { $gt: min_objectid };
  }

  yield Promise.fromCallback(callback => pump(
    Post.find(query).lean(true).cursor(),

    new stream.Writable({
      objectMode: true,
      write(post, encoding, callback) {
        let urls = post.html.match(/href="[^"]+"/g)
                     .map(href => _.unescape(href.replace(/^href="|"$/g, '')));

        urls.forEach(url => {
          let parsed = URL.parse(url, true, true);

          if (parsed.host && parsed.host.includes(args.domain)) {
            /* eslint-disable no-console */

            if (args.long) {
              if (Object.keys(parsed.query).length || parsed.hash) console.log(url, '\n');
            } else console.log(url, '\n');
          }
        });

        callback();
      }
    }),

    callback
  ));

  yield mongoose.disconnect();
})();
<|endoftext|>


<commit_before>// var $ = require ('jquery');
const canvas = document.getElementById('arkannoyed-canvas');
const context = canvas.getContext('2d');
const World = require('./world');
const Levels = require('./level');

var world = new World(canvas.width, canvas.height);
world.translateLevel(Levels[0]);
world.renderLevel(world.newLevel);
world.renderCourt(world.newLevel);

function renderWorld(context, world) {

  context.clearRect(0, 0, world.width, world.height);
  context.fillStyle = 'blanchedalmond';
  context.fillRect(0, 0, world.width, world.height);

  function drawPaddle(){
    context.fillStyle = 'blue';
    context.fillRect(world.paddle.x, world.paddle.y, world.paddle.width, world.paddle.height);
  }

  function drawBall(){
    context.fillStyle = 'blue';
    context.fillRect(world.ball.x, world.ball.y, world.ball.height, world.ball.width);
  }

  function drawCurrentLevel(){

    world.court.forEach(function (brick) {
    if (brick.status === 1) {
      context.fillStyle = 'green';
      }
    if (brick.status === 3) {
      context.fillStyle = 'red';
    }
    if (brick.status === 2){
      context.fillStyle = 'yellow';
    }
    if (brick.status < 0){
      context.fillStyle = 'grey';
    }
    context.fillRect(brick.x, brick.y, brick.width, brick.height);
    });
  }

  drawCurrentLevel();
  drawPaddle();
  drawBall();
}

renderWorld(context, world);

function tick(world) {
  world.tick();
}

requestAnimationFrame(function gameLoop() {
  renderWorld(context, world);
  tick(world);
  requestAnimationFrame(gameLoop);
});

document.addEventListener('keydown', function (event) {
  if (event.keyCode === 39) { world.rightArrow(); }
  if (event.keyCode === 37) { world.leftArrow(); }
  // if (event.keyCode === 71) { world.godMode(); }
});

document.addEventListener("mousemove", mouseMoveHandler, false);

function mouseMoveHandler(e) {
    var relativeX = e.clientX;
    if(relativeX - world.paddle.width >= 0 && relativeX <= canvas.width) {
        world.paddle.x = relativeX - world.paddle.width;
    }
}
<commit_msg> refactor<commit_after>// var $ = require ('jquery');
const canvas = document.getElementById('arkannoyed-canvas');
const context = canvas.getContext('2d');
const World = require('./world');
const Levels = require('./level');

var world = new World(canvas.width, canvas.height);
world.translateLevel(Levels[1]);
world.renderLevel(world.newLevel);
world.renderCourt(world.newLevel);

function renderWorld(context, world) {

  context.clearRect(0, 0, world.width, world.height);
  context.fillStyle = 'blanchedalmond';
  context.fillRect(0, 0, world.width, world.height);

  function drawPaddle(){
    context.fillStyle = 'blue';
    context.fillRect(world.paddle.x, world.paddle.y, world.paddle.width, world.paddle.height);
  }

  function drawBall(){
    context.fillStyle = 'blue';
    context.fillRect(world.ball.x, world.ball.y, world.ball.height, world.ball.width);
  }

  function drawCurrentLevel(){

    world.court.forEach(function (brick) {
    if (brick.status === 1) {
      context.fillStyle = 'green';
      }
    if (brick.status === 3) {
      context.fillStyle = 'red';
    }
    if (brick.status === 2){
      context.fillStyle = 'yellow';
    }
    if (brick.status < 0){
      context.fillStyle = 'grey';
    }
    context.fillRect(brick.x, brick.y, brick.width, brick.height);
    });
  }

  drawCurrentLevel();
  drawPaddle();
  drawBall();
}

renderWorld(context, world);

function tick(world) {
  world.tick();
}

requestAnimationFrame(function gameLoop() {
  renderWorld(context, world);
  tick(world);
  requestAnimationFrame(gameLoop);
});

document.addEventListener('keydown', function (event) {
  if (event.keyCode === 39) { world.rightArrow(); }
  if (event.keyCode === 37) { world.leftArrow(); }
  // if (event.keyCode === 71) { world.godMode(); }
});

document.addEventListener("mousemove", mouseMoveHandler, false);

function mouseMoveHandler(e) {
    var relativeX = e.clientX;
    if(relativeX - world.paddle.width >= 0 && relativeX <= canvas.width) {
        world.paddle.x = relativeX - world.paddle.width;
    }
}
<|endoftext|>


<commit_before>'use strict';

const restify = require('restify');
const ws281x = require('rpi-ws281x-native');
const count = require('./count');
const color = require('./color');
const theme = require('./theme');
const pkg = require('../package.json');

process.on('SIGINT', function () {
  ws281x.reset();
  process.nextTick(function () { process.exit(0); });
});

var isRunning = false;

function init () {
  var server = restify.createServer();

  count.init();
  ws281x.init(count.getCount());
  color.init(ws281x);
  theme.init(ws281x);

  server.get('/', (req, res, next) => {
    console.log('get', '/');
    res.send({
      name: pkg.name,
      version: pkg.version,
      theme: theme.getThemeName(),
      count: count.getCount(),
      isRunning: isRunning
    });
    next(false);
  });

  server.put('/theme/:name', (req, res, next) => {
    console.log('put', '/theme/:name', req.params.name);
    if(theme.setTheme(req.params.name, count.getCount())) {
      isRunning = 'theme';
      res.status(200);
    } else {
      res.status(400);
    }
    next(false);
  });

  server.put('/count/:num', (req, res, next) => {
    console.log('put', '/count/:num', req.params.num);
    if (count.setCount(req.params.num)) {
      ws281x.reset();
      ws281x.init(count.getCount());
      if (isRunning === 'theme') {
        setTimeout(function () {
          console.log('theme.getThemeName(), count.getCount())', theme.getThemeName(), count.getCount());
          theme.setTheme(theme.getThemeName(), count.getCount());
        }, 10);
      }
      res.status(200);
    } else {
      res.status(400);
    }
    next(false);
  });

  server.put('/color/:red/:green/:blue', (req, res, next) => {
    if (isRunning) {
      stop();
    }
    color.setColorWithRgb(req.params.red, req.params.green, req.params.blue, count.getCount());
    next(false);
  });

  server.put('/color/:hex', (req, res, next) => {
    if (isRunning) {
      stop();
    }
    color.setColorWithHex(req.params.hex, count.getCount());
    next(false);
  });

  server.put('/stop', (req, res, next) => {
    console.log('put', '/stop');
    stop();
    res.status(200);
    next(false);
  });

  server.listen(8080);
  console.log('server is already started at port %s', 8080);
}

function stop() {
  if (isRunning === 'theme') {
    theme.stop();
  }
  ws281x.reset();
  ws281x.init(count.getCount());
  isRunning = false;
}

module.exports = {
  init: init
};
<commit_msg>add rgb and hex<commit_after>'use strict';

const restify = require('restify');
const ws281x = require('rpi-ws281x-native');
const count = require('./count');
const color = require('./color');
const theme = require('./theme');
const pkg = require('../package.json');

process.on('SIGINT', function () {
  ws281x.reset();
  process.nextTick(function () { process.exit(0); });
});

var isRunning = false;

function init () {
  var server = restify.createServer();

  count.init();
  ws281x.init(count.getCount());
  color.init(ws281x);
  theme.init(ws281x);

  server.get('/', (req, res, next) => {
    console.log('get', '/');
    res.send({
      name: pkg.name,
      version: pkg.version,
      theme: theme.getThemeName(),
      count: count.getCount(),
      color: color.getColorName(),
      isRunning: isRunning
    });
    next(false);
  });

  server.put('/theme/:name', (req, res, next) => {
    console.log('put', '/theme/:name', req.params.name);
    if(theme.setTheme(req.params.name, count.getCount())) {
      isRunning = 'theme';
      res.status(200);
    } else {
      res.status(400);
    }
    next(false);
  });

  server.put('/count/:num', (req, res, next) => {
    console.log('put', '/count/:num', req.params.num);
    if (count.setCount(req.params.num)) {
      ws281x.reset();
      ws281x.init(count.getCount());
      if (isRunning === 'theme') {
        setTimeout(function () {
          console.log('theme.getThemeName(), count.getCount())', theme.getThemeName(), count.getCount());
          theme.setTheme(theme.getThemeName(), count.getCount());
        }, 10);
      }
      res.status(200);
    } else {
      res.status(400);
    }
    next(false);
  });

  server.put('/color/:red/:green/:blue', (req, res, next) => {
    console.log('put', '/color/:red/:green/:blue', req.params);
    if (isRunning) {
      stop();
    }
    color.setColorWithRgb(req.params.red, req.params.green, req.params.blue, count.getCount());
    next(false);
  });

  server.put('/color/:hex', (req, res, next) => {
    console.log('put', '/color/:hex', req.params.hex);
    if (isRunning) {
      stop();
    }
    color.setColorWithHex(req.params.hex, count.getCount());
    next(false);
  });

  server.put('/stop', (req, res, next) => {
    console.log('put', '/stop');
    stop();
    res.status(200);
    next(false);
  });

  server.listen(8080);
  console.log('server is already started at port %s', 8080);
}

function stop() {
  if (isRunning === 'theme') {
    theme.stop();
  }
  ws281x.reset();
  ws281x.init(count.getCount());
  isRunning = false;
}

module.exports = {
  init: init
};
<|endoftext|>


<commit_before>'use strict';

/**
* NOTE: the original C code, the long comment, copyright, license, and the constants are from [Cephes]{@link http://netlib.sandia.gov/cephes/cprob/gamma.c}.
*
* The implementation follows the original, but has been modified for JavaScript.
*/

/**
* tgamma.c
*
* Gamma function
*
*
* SYNOPSIS:
*
*   double x, y, tgamma();
*   extern int signgam;
*
*   y = tgamma( x );
*
*
* DESCRIPTION:
*
*   Returns gamma function of the argument.  The result is correctly signed, and the sign (+1 or -1) is also returned in a global (extern) variable named signgam. This variable is also filled in by the logarithmic gamma function lgamma().
*
*   Arguments |x| <= 34 are reduced by recurrence and the function approximated by a rational function of degree 6/7 in the interval (2,3).
*
*   Large arguments are handled by Stirling's formula.
*
*   Large negative arguments are made positive using a reflection formula.
*
*
* ACCURACY:
*
*                      Relative error:
* arithmetic   domain     # trials      peak         rms
*    DEC      -34, 34      10000       1.3e-16     2.5e-17
*    IEEE    -170,-33      20000       2.3e-15     3.3e-16
*    IEEE     -33,  33     20000       9.4e-16     2.2e-16
*    IEEE      33, 171.6   20000       2.3e-15     3.2e-16
*
* Error for arguments outside the test range will be larger owing to error amplification by the exponential function.
*
*
* COPYRIGHT
*
*   Cephes Math Library Release 2.8:  June, 2000
*   Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
*
*
* LICENSE
*
*   The readme file at http://netlib.sandia.gov/cephes/ reads:
*      > Some software in this archive may be from the book _Methods and Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster International, 1989) or from the Cephes Mathematical Library, a commercial product. In either event, it is copyrighted by the author. What you see here may be used freely but it comes with no support or guarantee.
*      > The two known misprints in the book are repaired here in the source listings for the gamma function and the incomplete beta integral.
*
*      > Stephen L. Moshier
*      > moshier@na-net.ornl.gov
*/

// MODULES //

var abs = require( 'math-abs' );
var floor = require( 'math-floor' );
var sin = require( 'math-sin' );
var evalrational = require( 'math-evalrational' ).factory;
var stirlingApprox = require( './stirling_approximation.js' );
var smallApprox = require( './small_approximation.js' );

// CONSTANTS //

var PINF = require( 'const-pinf-float64' );
var NINF = require( 'const-ninf-float64' );
var PI = require( 'const-pi' );
var P = [
	9.99999999999999996796e-01,
	4.94214826801497100753e-01,
	2.07448227648435975150e-01,
	4.76367800457137231464e-02,
	1.04213797561761569935e-02,
	1.19135147006586384913e-03,
	1.60119522476751861407e-04,
	0
];
var Q = [
	1.00000000000000000320e+00,
	7.14304917030273074085e-02,
	-2.34591795718243348568e-01,
	3.58236398605498653373e-02,
	1.18139785222060435552e-02,
	-4.45641913851797240494e-03,
	5.39605580493303397842e-04,
	-2.31581873324120129819e-05
];

// FUNCTIONS //

// Compile function to evaluate rational function based on the above coefficients...
var rateval = evalrational( P, Q );

// GAMMA //

/**
* FUNCTION: gamma( x )
*	Evaluates the gamma function.
*
* @param {Number} x - input value
* @returns {Number} function value
*/
function gamma( x ) {
	var sign;
	var q;
	var p;
	var z;
	if (
		(x%1 === 0 && x < 0) || // negative integer
		x === NINF ||
		x !== x // NaN
	) {
		return NaN;
	}
	if ( x === 0 ) {
		// Check for negative zero...
		if ( 1/x < 0 ) {
			return NINF;
		}
		return PINF;
	}
	if (
		x < -170.5674972726612 ||
		x > 171.61447887182298
	) {
		return PINF;
	}
	q = abs( x );
	if ( q > 33 ) {
		if ( x >= 0 ) {
			return stirlingApprox( x );
		}
		p = floor( q );

		// Check whether `x` is even...
		if ( (p&1) === 0 ) {
			sign = -1;
		} else {
			sign = 1;
		}
		z = q - p;
		if ( z > 0.5 ) {
			p += 1;
			z = q - p;
		}
		z = q * sin( PI * z );
		return sign * PI / ( abs(z)*stirlingApprox(q) );
	}
	// Reduce `x`...
	z = 1;
	while ( x >= 3 ) {
		x -= 1;
		z *= x;
	}
	while ( x < 0 ) {
		if ( x > -1e-9 ) {
			return smallApprox( x, z );
		}
		z /= x;
		x += 1;
	}
	while ( x < 2 ) {
		if ( x < 1e-9 ) {
			return smallApprox( x, z );
		}
		z /= x;
		x += 1;
	}
	if ( x === 2 ) {
		return z;
	}
	x -= 2;
	return z * rateval( x );
} // end FUNCTION gamma()

// EXPORTS //

module.exports = gamma;
<commit_msg>Add articles in code comment<commit_after>'use strict';

/**
* NOTE: the original C code, the long comment, copyright, license, and the constants are from [Cephes]{@link http://netlib.sandia.gov/cephes/cprob/gamma.c}.
*
* The implementation follows the original, but has been modified for JavaScript.
*/

/**
* tgamma.c
*
* Gamma function
*
*
* SYNOPSIS:
*
*   double x, y, tgamma();
*   extern int signgam;
*
*   y = tgamma( x );
*
*
* DESCRIPTION:
*
*   Returns gamma function of the argument.  The result is correctly signed, and the sign (+1 or -1) is also returned in a global (extern) variable named signgam. This variable is also filled in by the logarithmic gamma function lgamma().
*
*   Arguments |x| <= 34 are reduced by recurrence and the function approximated by a rational function of degree 6/7 in the interval (2,3).
*
*   Large arguments are handled by Stirling's formula.
*
*   Large negative arguments are made positive using a reflection formula.
*
*
* ACCURACY:
*
*                      Relative error:
* arithmetic   domain     # trials      peak         rms
*    DEC      -34, 34      10000       1.3e-16     2.5e-17
*    IEEE    -170,-33      20000       2.3e-15     3.3e-16
*    IEEE     -33,  33     20000       9.4e-16     2.2e-16
*    IEEE      33, 171.6   20000       2.3e-15     3.2e-16
*
* Error for arguments outside the test range will be larger owing to error amplification by the exponential function.
*
*
* COPYRIGHT
*
*   Cephes Math Library Release 2.8:  June, 2000
*   Copyright 1984, 1987, 1989, 1992, 2000 by Stephen L. Moshier
*
*
* LICENSE
*
*   The readme file at http://netlib.sandia.gov/cephes/ reads:
*      > Some software in this archive may be from the book _Methods and Programs for Mathematical Functions_ (Prentice-Hall or Simon & Schuster International, 1989) or from the Cephes Mathematical Library, a commercial product. In either event, it is copyrighted by the author. What you see here may be used freely but it comes with no support or guarantee.
*      > The two known misprints in the book are repaired here in the source listings for the gamma function and the incomplete beta integral.
*
*      > Stephen L. Moshier
*      > moshier@na-net.ornl.gov
*/

// MODULES //

var abs = require( 'math-abs' );
var floor = require( 'math-floor' );
var sin = require( 'math-sin' );
var evalrational = require( 'math-evalrational' ).factory;
var stirlingApprox = require( './stirling_approximation.js' );
var smallApprox = require( './small_approximation.js' );

// CONSTANTS //

var PINF = require( 'const-pinf-float64' );
var NINF = require( 'const-ninf-float64' );
var PI = require( 'const-pi' );
var P = [
	9.99999999999999996796e-01,
	4.94214826801497100753e-01,
	2.07448227648435975150e-01,
	4.76367800457137231464e-02,
	1.04213797561761569935e-02,
	1.19135147006586384913e-03,
	1.60119522476751861407e-04,
	0
];
var Q = [
	1.00000000000000000320e+00,
	7.14304917030273074085e-02,
	-2.34591795718243348568e-01,
	3.58236398605498653373e-02,
	1.18139785222060435552e-02,
	-4.45641913851797240494e-03,
	5.39605580493303397842e-04,
	-2.31581873324120129819e-05
];

// FUNCTIONS //

// Compile a function to evaluate a rational function based on the above coefficients...
var rateval = evalrational( P, Q );

// GAMMA //

/**
* FUNCTION: gamma( x )
*	Evaluates the gamma function.
*
* @param {Number} x - input value
* @returns {Number} function value
*/
function gamma( x ) {
	var sign;
	var q;
	var p;
	var z;
	if (
		(x%1 === 0 && x < 0) || // negative integer
		x === NINF ||
		x !== x // NaN
	) {
		return NaN;
	}
	if ( x === 0 ) {
		// Check for negative zero...
		if ( 1/x < 0 ) {
			return NINF;
		}
		return PINF;
	}
	if (
		x < -170.5674972726612 ||
		x > 171.61447887182298
	) {
		return PINF;
	}
	q = abs( x );
	if ( q > 33 ) {
		if ( x >= 0 ) {
			return stirlingApprox( x );
		}
		p = floor( q );

		// Check whether `x` is even...
		if ( (p&1) === 0 ) {
			sign = -1;
		} else {
			sign = 1;
		}
		z = q - p;
		if ( z > 0.5 ) {
			p += 1;
			z = q - p;
		}
		z = q * sin( PI * z );
		return sign * PI / ( abs(z)*stirlingApprox(q) );
	}
	// Reduce `x`...
	z = 1;
	while ( x >= 3 ) {
		x -= 1;
		z *= x;
	}
	while ( x < 0 ) {
		if ( x > -1e-9 ) {
			return smallApprox( x, z );
		}
		z /= x;
		x += 1;
	}
	while ( x < 2 ) {
		if ( x < 1e-9 ) {
			return smallApprox( x, z );
		}
		z /= x;
		x += 1;
	}
	if ( x === 2 ) {
		return z;
	}
	x -= 2;
	return z * rateval( x );
} // end FUNCTION gamma()

// EXPORTS //

module.exports = gamma;
<|endoftext|>