<commit_before>"use strict";
let gulp = require('gulp');
let paths = {
	styles: './sass/**/*.scss',
	scripts: './js/**/*.js'
}

/*gulp.task('scripts', () => {
	let changed = require('gulp-changed'),
		babel = require('gulp-babel');

	return gulp.src(paths.scripts)
		.pipe(changed('js'))
		.pipe(babel({
			modules: 'common',
			stage: 0
		}).on('error', e => console.error(e)))
		.pipe(gulp.dest('js'));
});

gulp.task('scripts:watch', () => {
	gulp.start('scripts');
	gulp.watch(paths.scripts, ['scripts']);
});*/

gulp.task('scripts:bundle' /*, ['scripts']*/ , cb => {
	let path = require("path");
	let Builder = require('systemjs-builder');
	let builder = new Builder();

	builder.loadConfig('js/config.js').then(() => {
		builder.config({
			transpiler: 'babel',
			babelOptions: {
				stage: 0
			}
		});
		builder.buildStatic('app/app.js', 'dist/js/app.js')
			.then(() => {
				console.log('Build complete');
				cb();
			})
			.catch(err => {
				console.log('Build error');
				console.log(err);
				cb();
			});
	}).catch(e => console.error(e));
});

gulp.task('scripts:build', ['scripts:bundle'], cb => {
	let concat = require('gulp-concat'),
		uglify = require('gulp-uglify'),
		sourcemaps = require('gulp-sourcemaps'),
		rename = require('gulp-rename');

	return gulp.src('./dist/js/app.js')
		.pipe(concat('app.js'))
		.pipe(gulp.dest('./dist/js'))
		.pipe(sourcemaps.init())
		.pipe(uglify())
		.pipe(rename('app.min.js'))
		.pipe(sourcemaps.write('.'))
		.pipe(gulp.dest('./dist/js'));
});

gulp.task('styles', function() {
	let postcss = require('gulp-postcss');
	return gulp.src('postcss/style.css')
		.pipe(postcss([
			require('postcss-import'),
			require('postcss-nested'),
			require('postcss-cssnext'),
			require('postcss-calc'),
			require('postcss-clearfix'),
			require('autoprefixer')({
				browsers: ['last 3 versions']
			})
		]).on('error', e => console.error(e)))
		.pipe(gulp.dest('css'));
});

gulp.task('styles:watch', function() {
	gulp.start('styles');
	gulp.watch('postcss/**/*.css', ['styles']);
});

gulp.task('scripts:lint', function() {
	let jshint = require('gulp-jshint');

	return gulp.src(['js/app/**/*.js'])
		.pipe(jshint({
			globals: {},
			curly: true,
			eqnull: true,
			undef: true,
			unused: true,
			strict: true,
			shadow: true,
			browser: true,
			'-W030': 'Expected an assignment or function call and instead saw an expression',
			'-W093': 'Did you mean to return a conditional instead of an assignment?'
		}))
		.pipe(jshint.reporter('jshint-stylish'))
		.pipe(jshint.reporter('fail'));
});

gulp.task('html', () => {
	let htmlprocessor = require('gulp-htmlprocessor');
	return gulp.src('index.html')
		.pipe(htmlprocessor({}))
		.pipe(gulp.dest('dist'));
});

gulp.task('deploy:beta', () => {
	let sftp = require("gulp-sftp");
	gulp.src('dist/**/*')
		.pipe(sftp({
			host: 'beta.jsonlint.com',
			user: 'root',
			remotePath: '/var/www/beta.jsonlint.com/site/public_html/'
		}));
});

gulp.task('default', ['scripts:lint', 'scripts:build', 'html'], () => {
	gulp.src('./css/*').pipe(gulp.dest('./dist/css'));
	gulp.src('./img/*').pipe(gulp.dest('./dist/img'));
	gulp.src(['./proxy.php', './*.appcache']).pipe(gulp.dest('./dist'));
});
<commit_msg>minor change in gulpfile<commit_after>"use strict";
let gulp = require('gulp');
let paths = {
	styles: './sass/**/*.scss',
	scripts: './js/**/*.js'
}

/*gulp.task('scripts', () => {
	let changed = require('gulp-changed'),
		babel = require('gulp-babel');

	return gulp.src(paths.scripts)
		.pipe(changed('js'))
		.pipe(babel({
			modules: 'common',
			stage: 0
		}).on('error', e => console.error(e)))
		.pipe(gulp.dest('js'));
});

gulp.task('scripts:watch', () => {
	gulp.start('scripts');
	gulp.watch(paths.scripts, ['scripts']);
});*/

gulp.task('scripts:bundle' /*, ['scripts']*/ , cb => {
	let path = require("path");
	let Builder = require('systemjs-builder');
	let builder = new Builder();

	builder.loadConfig('js/config.js').then(() => {
		builder.config({
			transpiler: 'babel',
			babelOptions: {
				stage: 0
			}
		});
		builder.buildStatic('app/app.js', 'dist/js/app.js')
			.then(() => {
				console.log('Build complete');
				cb();
			})
			.catch(err => {
				console.log('Build error');
				console.log(err);
				cb();
			});
	}).catch(e => console.error(e));
});

gulp.task('scripts:build', ['scripts:bundle'], cb => {
	let concat = require('gulp-concat'),
		uglify = require('gulp-uglify'),
		sourcemaps = require('gulp-sourcemaps'),
		rename = require('gulp-rename');

	return gulp.src('./dist/js/app.js')
		.pipe(concat('app.js'))
		.pipe(gulp.dest('./dist/js'))
		.pipe(sourcemaps.init())
		.pipe(uglify())
		.pipe(rename('app.min.js'))
		.pipe(sourcemaps.write('.'))
		.pipe(gulp.dest('./dist/js'));
});

gulp.task('styles', function() {
	let postcss = require('gulp-postcss');
	return gulp.src('postcss/style.css')
		.pipe(postcss([
			require('postcss-import'),
			require('postcss-nested'),
			require('postcss-cssnext'),
			require('postcss-calc'),
			require('postcss-clearfix'),
			require('autoprefixer')({
				browsers: ['last 3 versions']
			})
		]).on('error', e => console.error(e)))
		.pipe(gulp.dest('css'));
});

gulp.task('styles:watch', function() {
	gulp.start('styles');
	gulp.watch('postcss/**/*.css', ['styles']);
});

gulp.task('scripts:lint', function() {
	let jshint = require('gulp-jshint');

	return gulp.src(['js/app/**/*.js'])
		.pipe(jshint({
			globals: {},
			curly: true,
			eqnull: true,
			undef: true,
			unused: true,
			strict: true,
			shadow: true,
			browser: true,
			'-W093': 'Did you mean to return a conditional instead of an assignment?'
		}))
		.pipe(jshint.reporter('jshint-stylish'))
		.pipe(jshint.reporter('fail'));
});

gulp.task('html', () => {
	let htmlprocessor = require('gulp-htmlprocessor');
	return gulp.src('index.html')
		.pipe(htmlprocessor({}))
		.pipe(gulp.dest('dist'));
});

gulp.task('deploy:beta', () => {
	let sftp = require("gulp-sftp");
	gulp.src('dist/**/*')
		.pipe(sftp({
			host: 'beta.jsonlint.com',
			user: 'root',
			remotePath: '/var/www/beta.jsonlint.com/site/public_html/'
		}));
});

gulp.task('default', ['scripts:lint', 'scripts:build', 'html'], () => {
	gulp.src('./css/*').pipe(gulp.dest('./dist/css'));
	gulp.src('./img/*').pipe(gulp.dest('./dist/img'));
	gulp.src(['./proxy.php', './*.appcache']).pipe(gulp.dest('./dist'));
});
<|endoftext|>


<commit_before>Unison = (function() {

  "use strict";

  // get breakpoint object
  var getBreakpoints = function(allBreakpoints) {
    var allBP, currentBP, usnBP = {}, i = 0, doc = document, head = doc.head, win = window, title = head.getElementsByTagName('title')[0];
    // check if css is passing breakpoints properly, if not return null for getBreakpoint()
    var unisonReady = ( win.getComputedStyle(head, null).getPropertyValue('clear') === 'none' ) ? false : true ;
    function cleanMQstr(el) {
      if(!el) { return; }
      var str = win.getComputedStyle(el, null).getPropertyValue('font-family');
      return str.replace(/"/g, '').replace(/'/g, '');
    }
    currentBP = cleanMQstr(head).split(' ');
    allBP = title ? cleanMQstr(title).split(',') : usnBP;
    usnBP.currentBP = {
      name : currentBP[0],
      width : currentBP[1]
    };
    usnBP.allBP = {};
    for ( ; i < allBP.length; i++ ) {
      var mq = allBP[i].trim().split(' ');
      usnBP.allBP[mq[0]] = mq[1];
    }
    if ( unisonReady ) {
      return ( typeof allBreakpoints === 'boolean' ) ? usnBP.allBP : usnBP ;
    } else {
      return null;
    }
  };

  // return some stuff because people like to see stuff in the console
  return {
    getBreakpoints : getBreakpoints
  };

})();<commit_msg>use getElementsByTagName to get head and title elements<commit_after>Unison = (function() {

  "use strict";

  // get breakpoint object
  var getBreakpoints = function(allBreakpoints) {
    var allBP,
        currentBP,
        usnBP = {},
        i = 0,
        win = window,
        doc = document,
        head = doc.getElementsByTagName('head')[0],
        title = doc.getElementsByTagName('title')[0];

    // check if css is passing breakpoints properly, if not return null for getBreakpoint()
    var unisonReady = ( win.getComputedStyle(head, null).getPropertyValue('clear') === 'none' ) ? false : true ;
    function cleanMQstr(el) {
      if(!el) { return; }
      var str = win.getComputedStyle(el, null).getPropertyValue('font-family');
      return str.replace(/"/g, '').replace(/'/g, '');
    }
    currentBP = cleanMQstr(head).split(' ');
    allBP = title ? cleanMQstr(title).split(',') : usnBP;
    usnBP.currentBP = {
      name : currentBP[0],
      width : currentBP[1]
    };
    usnBP.allBP = {};
    for ( ; i < allBP.length; i++ ) {
      var mq = allBP[i].trim().split(' ');
      usnBP.allBP[mq[0]] = mq[1];
    }
    if ( unisonReady ) {
      return ( typeof allBreakpoints === 'boolean' ) ? usnBP.allBP : usnBP ;
    } else {
      return null;
    }
  };

  // return some stuff because people like to see stuff in the console
  return {
    getBreakpoints : getBreakpoints
  };

})();<|endoftext|>


<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)
		{
			// inherit options from defineOptions (except defineOptions.fields)
			var fields = definition.fields = definition.fields || {},
				options = definition.options = definition.options || {};

			utils.defaultsNoUndef(options, defineOptions);
			delete options.fields;

			// add additional fields
			if (defineOptions.fields && !options.skipFields) {
				_.forIn(defineOptions.fields, function(field, fieldName) {
					if (fields[fieldName] !== undefined) return;
					fields[fieldName] = utils.functionValue(_.clone(field), modelName, definition, definitions);
				});
			}

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

			// find primary key
			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) {
				if (!options.primaryKey) throw new Sequelize.SequelizeDefinerError("Model '" + modelName + "' has no primary key defined");

				key = utils.functionValue(options.primaryKey, modelName, definition, definitions);
				var keyField = {type: options.primaryKeyType, allowNull: false, primaryKey: true, autoIncrement: true, _autoGenerated: true};

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

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

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

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

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

				// process oneToMany associations
				var reference = params.reference;
				if (reference !== undefined && !reference) {
					delete params.reference;
				} else if (reference || (options.autoAssociate && primaryKeys[fieldName])) {
					// field references another model
					var referencesKey;
					if (reference) {
						if (!definitions[reference]) throw new Sequelize.SequelizeDefinerError("Referenced model '" + reference + "' in field '" + fieldName + "' does not exist");

						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: options.onDelete,
						onUpdate: options.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 : options.primaryKeyType;

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

				// create label
				if (options.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,
					foreignKey1 = modelName1 + Utils.uppercaseFirst(key1),
					foreignKey2 = modelName2 + Utils.uppercaseFirst(key2);

				utils.defaultsNoUndef(options, {
					associate: defineOptions.associateThrough,
					skipFields: defineOptions.skipFieldsOnThrough,
					labels: defineOptions.labels,
					freezeTableName: defineOptions.freezeTableName,
					camel: defineOptions.camelThrough,
					onDelete: defineOptions.onDelete,
					onUpdate: defineOptions.onUpdate
				});

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

					if (options.labels) {
						fields[foreignKey1].label = utils.camelToHuman(modelName1);
						fields[foreignKey2].label = utils.camelToHuman(modelName2);
					}

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

					var throughOptions = {
						tableName: tableName,
						labels: false,
						skipFields: options.skipFields
					};

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

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

				var joinOptions = _.clone(options);
				joinOptions.foreignKey = foreignKey1;
				model1.hasMany(model2, joinOptions);

				joinOptions = _.clone(options);
				utils.setNoUndef(joinOptions, 'as', asReverse);
				joinOptions.foreignKey = foreignKey2;
				model2.hasMany(model1, joinOptions);
			});
		}
	};

	Sequelize.prototype.defineFromFolder = function(path, options) {
		options = _.clone(options || {});

		var loadOptions = _.clone(utils.pop(options, 'loadOptions') || {});
		loadOptions.flatten = true;

		var definitions = requireFolderTree(path, loadOptions);

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

	return Sequelize;
};
<commit_msg>Refactor fields parsing<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)
		{
			// inherit options from defineOptions (except defineOptions.fields)
			var fields = definition.fields = definition.fields || {},
				options = definition.options = definition.options || {};

			utils.defaultsNoUndef(options, defineOptions);
			delete options.fields;

			// add additional fields
			if (defineOptions.fields && !options.skipFields) {
				_.forIn(defineOptions.fields, function(field, fieldName) {
					if (fields[fieldName] !== undefined) return;
					fields[fieldName] = utils.functionValue(_.clone(field), modelName, definition, definitions);
				});
			}

			// delete empty fields and set field type where shorthand definition used
			_.forIn(fields, function(field, fieldName) {
				if (!field) {
					delete fields[fieldName];
				} else if (!_.isPlainObject(field)) {
					fields[fieldName] = {type: field};
				}
			});

			// find primary key
			var key;
			_.forIn(fields, function(field, fieldName) {
				if (field.primaryKey) {
					key = fieldName;
					return false;
				}
			});

			// if no primary key, create primary key column
			if (!key) {
				if (!options.primaryKey) throw new Sequelize.SequelizeDefinerError("Model '" + modelName + "' has no primary key defined");

				key = utils.functionValue(options.primaryKey, modelName, definition, definitions);
				var keyField = {type: options.primaryKeyType, allowNull: false, primaryKey: true, autoIncrement: true, _autoGenerated: true};

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

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

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

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

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

				// process oneToMany associations
				var reference = params.reference;
				if (reference !== undefined && !reference) {
					delete params.reference;
				} else if (reference || (options.autoAssociate && primaryKeys[fieldName])) {
					// field references another model
					var referencesKey;
					if (reference) {
						if (!definitions[reference]) throw new Sequelize.SequelizeDefinerError("Referenced model '" + reference + "' in field '" + fieldName + "' does not exist");

						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: options.onDelete,
						onUpdate: options.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 : options.primaryKeyType;

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

				// create label
				if (options.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,
					foreignKey1 = modelName1 + Utils.uppercaseFirst(key1),
					foreignKey2 = modelName2 + Utils.uppercaseFirst(key2);

				utils.defaultsNoUndef(options, {
					associate: defineOptions.associateThrough,
					skipFields: defineOptions.skipFieldsOnThrough,
					labels: defineOptions.labels,
					freezeTableName: defineOptions.freezeTableName,
					camel: defineOptions.camelThrough,
					onDelete: defineOptions.onDelete,
					onUpdate: defineOptions.onUpdate
				});

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

					if (options.labels) {
						fields[foreignKey1].label = utils.camelToHuman(modelName1);
						fields[foreignKey2].label = utils.camelToHuman(modelName2);
					}

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

					var throughOptions = {
						tableName: tableName,
						labels: false,
						skipFields: options.skipFields
					};

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

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

				var joinOptions = _.clone(options);
				joinOptions.foreignKey = foreignKey1;
				model1.hasMany(model2, joinOptions);

				joinOptions = _.clone(options);
				utils.setNoUndef(joinOptions, 'as', asReverse);
				joinOptions.foreignKey = foreignKey2;
				model2.hasMany(model1, joinOptions);
			});
		}
	};

	Sequelize.prototype.defineFromFolder = function(path, options) {
		options = _.clone(options || {});

		var loadOptions = _.clone(utils.pop(options, 'loadOptions') || {});
		loadOptions.flatten = true;

		var definitions = requireFolderTree(path, loadOptions);

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

	return Sequelize;
};
<|endoftext|>


<commit_before>var fs = require('fs');
var xml2js = require('xml2js');
var request = require('request');
var express = require('express');
var _ = require('lodash');
var cors = require('cors');
var app = express();

var parser = new xml2js.Parser();

app.use(cors());

app.get('/', function(req, res){
  res.redirect(301, '/exhibits');
 });

app.get('/pretty', function(req, res){
  request('http://www.norfolkva.gov/cultural_affairs/public_art_downtown.xml',
    function (error, response, body) {
      if (!error && response.statusCode == 200) {
        parser.parseString(body, function (err, result) {
        var converted = JSON.stringify(result, undefined, 2);
        //print pretty
        console.log(converted);
        res.set('Content-Type', 'application/json');
        res.send( "
" + converted + "
");
        });
      }
      else {
        res.send(404,"Not found");
      }
    });
});

//exhibits
/* Query Strings to search for ...
    id: DS.attr('number'),
    title: DS.attr('string'),
    location: DS.attr('string'),
    artists: DS.attr('string'),
    latitude: DS.attr('number'),
    longitude: DS.attr('number'),
*/
app.get('/exhibits', function(req, res){
  request('http://www.norfolkva.gov/cultural_affairs/public_art_downtown.xml',
    function (error, response, body) {
      if (!error && response.statusCode == 200) {
        var obj = [];
        parser.parseString(body, function (err, result) {
        _.each(result.parks.parkz, function (data) {
          obj.push(data.$);
        });
          res.set('Content-Type', 'application/json');
          res.send(obj);
        });
      }
      else {
        res.send(404,"Not found");
      }
    });
});

var port = Number(process.env.PORT || 3000);
console.log("Listening on Port " + port);
app.listen(port);
<commit_msg>created api id route<commit_after>var fs = require('fs');
var xml2js = require('xml2js');
var request = require('request');
var express = require('express');
var _ = require('lodash');
var cors = require('cors');
var app = express();

var parser = new xml2js.Parser();

app.use(cors());

app.get('/', function(req, res){
  res.redirect(301, '/exhibits');
 });

app.get('/pretty', function(req, res){
  request('http://www.norfolkva.gov/cultural_affairs/public_art_downtown.xml',
    function (error, response, body) {
      if (!error && response.statusCode == 200) {
        parser.parseString(body, function (err, result) {
        var converted = JSON.stringify(result, undefined, 2);
        //print pretty
        console.log(converted);
        res.set('Content-Type', 'application/json');
        res.send( "
" + converted + "
");
        });
      }
      else {
        res.send(404,"Not found");
      }
    });
});

//exhibits
/* Query Strings to search for ...
    id: DS.attr('number'),
    title: DS.attr('string'),
    location: DS.attr('string'),
    artists: DS.attr('string'),
    latitude: DS.attr('number'),
    longitude: DS.attr('number'),
*/
app.get('/exhibits', function(req, res){
  request('http://www.norfolkva.gov/cultural_affairs/public_art_downtown.xml',
    function (error, response, body) {
      if (!error && response.statusCode == 200) {
        var obj = [];
        parser.parseString(body, function (err, result) {
        _.each(result.parks.parkz, function (data) {
          obj.push(data.$);
        });
          res.set('Content-Type', 'application/json');
          res.send(obj);
        });
      }
      else {
        res.send(404,"Not found");
      }
    });
});

app.get('/exhibits/:id', function(req, res){
  //parm id
  var id = req.params.id;
  request('http://www.norfolkva.gov/cultural_affairs/public_art_downtown.xml',
    function (error, response, body) {
      if (!error && response.statusCode == 200) {
          var obj;
          parser.parseString(body, function (err, result) {
          console.log(result.parks.parkz);
          obj = result.parks.parkz[id].$;
          res.set('Content-Type', 'application/json');
          res.send(obj);
        });
      }
      else {
        res.send(404,"Not found");
      }
    });
});

var port = Number(process.env.PORT || 3000);
console.log("Listening on Port " + port);
app.listen(port);
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['comm<commit_msg>Re-updating the readme.<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commi<|endoftext|>


<commit_before>/* global __REDIAL_PROPS__ */

import React, { Component } from 'react';
import PropTypes from 'prop-types';

import triggerHooks from './triggerHooks';
import createMap from './createMap';
import createMapKeys from './util/mapKeys';
import getAllComponents from './getAllComponents';

function hydrate(renderProps) {
  if (typeof __REDIAL_PROPS__ !== 'undefined' && Array.isArray(__REDIAL_PROPS__)) {
    const getMapKeyForComponent = createMapKeys(renderProps.routes, renderProps.components);
    const components = getAllComponents(renderProps.components);
    const componentKeys = components.map(getMapKeyForComponent);
    return createMap(componentKeys, __REDIAL_PROPS__);
  }

  return createMap();
}

export default class RedialContext extends Component {
  static displayName = 'RedialContext';

  static propTypes = {
    children: PropTypes.node.isRequired,

    // RouterContext default
    renderProps: PropTypes.object.isRequired,

    // Custom
    locals: PropTypes.object,
    beforeTransition: PropTypes.array,
    afterTransition: PropTypes.array,
    parallel: PropTypes.bool,
    initialLoading: PropTypes.func,
    onError: PropTypes.func,
    onAborted: PropTypes.func,
    onStarted: PropTypes.func,
    onCompleted: PropTypes.func,

    // Server
    redialMap: PropTypes.object,
  };

  static defaultProps = {
    beforeTransition: [],
    afterTransition: [],
    parallel: false,

    onError(err, { beforeTransition }) {
      if (process.env.NODE_ENV !== 'production') {
        const type = beforeTransition ? 'beforeTransition' : 'afterTransition';
        console.error(type, err);
      }
    },

    onAborted(becauseError) {
      if (process.env.NODE_ENV !== 'production') {
        if (becauseError) {
          console.warn('Loading was aborted from an error');
        } else {
          console.warn('Loading was aborted manually');
        }
      }
    },

    onStarted(force) {
      if (process.env.NODE_ENV !== 'production') {
        console.info('Loading started. Force:', force);
      }
    },

    onCompleted(type) {
      if (process.env.NODE_ENV !== 'production') {
        console.info('Loading completed. Type:', type);
      }
    },
  };

  static childContextTypes = {
    redialContext: PropTypes.object,
  };

  constructor(props, context) {
    super(props, context);
    this.state = {
      loading: false,
      afterTransitionLoading: false,
      aborted: () => false,
      abort: () => {},
      prevRenderProps: undefined,
      redialMap: props.redialMap || hydrate(props.renderProps),
      initial: props.beforeTransition.length > 0,
    };
    this.completed = {
      beforeTransition: false,
      afterTransition: false,
      error: null,
    };
  }

  getChildContext() {
    const { loading, afterTransitionLoading, redialMap } = this.state;
    return {
      redialContext: {
        loading,
        afterTransitionLoading,
        redialMap,
        reloadComponent: (component) => {
          this.reloadComponent(component);
        },
        abortLoading: () => {
          this.abort();
        },
      },
    };
  }

  componentDidMount() {
    this.load(this.props.renderProps.components, this.props.renderProps);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.renderProps.location === this.props.renderProps.location) {
      return;
    }

    this.load(nextProps.renderProps.components, nextProps.renderProps);
  }

  componentWillUnmount() {
    this.unmounted = true;
  }

  reloadComponent(component) {
    this.load(component, this.props.renderProps, true);
  }

  abort(becauseError, abort) {
    // Make sure we only cancel if it is the correct ongoing request
    if (!abort || this.state.abort === abort) {
      // We need to be in a loading state for it to make sense
      // to abort something
      if (this.state.loading || this.state.afterTransitionLoading) {
        this.state.abort();

        this.setState({
          loading: false,
          afterTransitionLoading: false,
        });

        if (this.props.onAborted) {
          this.props.onAborted(becauseError);
        }
      }
    }
  }

  load(components, renderProps, force = false) {
    let isAborted = false;
    const abort = () => {
      isAborted = true;
    };
    const aborted = () => isAborted;

    const bail = () => {
      const currentLocation = this.props.renderProps.location;
      if (aborted()) {
        return 'aborted';
      } else if (currentLocation !== renderProps.location) {
        return 'location-changed';
      }

      return false;
    };

    if (this.props.onStarted) {
      this.props.onStarted(force);
    }

    this.completed.beforeTransition = false;

    this.setState({
      aborted,
      abort,
      loading: true,
      prevRenderProps: this.state.aborted() ? this.state.prevRenderProps : this.props.renderProps,
    });

    if (this.props.parallel) {
      this.runAfterTransition(
        this.props.afterTransition,
        components,
        renderProps,
        force,
        bail
      )
      .then(() => {
        if (this.completed.afterTransition) {
          this.props.onCompleted('afterTransition');
        }
      })
      .catch((err) => {
        // We will only propagate this error if beforeTransition have been completed
        // This because the beforeTransition error is more critical
        const error = () => this.props.onError(err, {
          reason: bail() || 'other',
          beforeTransition: false,
          router: this.props.renderProps.router,
          abort: () => this.abort(true, abort),
        });

        if (this.completed.beforeTransition) {
          error();
        } else {
          this.completed.error = error;
        }
      });
    }

    this.runBeforeTransition(
      this.props.beforeTransition,
      components,
      renderProps,
      force,
      bail
    )
    .catch((error) => {
      let afterTransition = false;
      if (error && error.afterTransition !== undefined) {
        afterTransition = error.afterTransition;
        error = error.error; // eslint-disable-line
      }

      this.props.onError(error, {
        reason: bail() || 'other',
        // If not defined before it's a beforeTransition error
        beforeTransition: !afterTransition,
        router: this.props.renderProps.router,
        abort: () => this.abort(true, abort),
      });
    });
  }

  runAfterTransition(hooks, components, renderProps, force = false, bail) {
    // Get afterTransition data, will not block route transitions
    this.completed.afterTransition = false;
    this.completed.error = null;

    this.setState({
      afterTransitionLoading: true,
    });

    return triggerHooks({
      hooks,
      components,
      renderProps,
      redialMap: this.state.redialMap,
      locals: this.props.locals,
      force,
      bail,
    }).then(({ redialMap }) => {
      this.completed.afterTransition = true;
      this.setState({
        afterTransitionLoading: false,
        redialMap,
      });
    });
  }

  runBeforeTransition(hooks, components, renderProps, force = false, bail) {
    const completeRouteTransition = (redialMap) => {
      if (!bail() && !this.unmounted) {
        this.setState({
          loading: false,
          redialMap,
          prevRenderProps: undefined,
          initial: false,
        });

        this.props.onCompleted('beforeTransition');

        this.completed.beforeTransition = true;

        // Start afterTransition if we are not in parallel
        if (!this.props.parallel) {
          return this.runAfterTransition(
            this.props.afterTransition,
            components,
            renderProps,
            force,
            bail
          )
          .then(() => {
            this.props.onCompleted('afterTransition');
          })
          .catch((error) => Promise.reject({ error, afterTransition: true }));
        } else if (this.completed.afterTransition) {
          this.completed.afterTransition = false;
          this.props.onCompleted('afterTransition');
        } else if (this.completed.error) {
          this.completed.error();
        }
      }

      return Promise.resolve();
    };

    return triggerHooks({
      hooks,
      components,
      renderProps,
      redialMap: this.state.redialMap,
      locals: this.props.locals,
      force,
      bail,
    }).then(({ redialMap }) =>
      completeRouteTransition(redialMap)
    );
  }

  render() {
    if (this.props.initialLoading && this.state.initial && this.state.redialMap.size() === 0) {
      return this.props.initialLoading();
    }

    const props = (this.state.loading || this.state.aborted()) && this.state.prevRenderProps;
    if (props) {
      /* eslint-disable no-unused-vars */
      // Omit `createElement`. Otherwise we might skip `renderRouteContext` in `applyMiddleware`.
      const { createElement, ...prevProps } = props;
      /* eslint-enable no-unused-vars */
      return React.cloneElement(
        this.props.children,
        prevProps,
      );
    }

    return this.props.children;
  }
}
<commit_msg>fix: Make sure we don't show a components for a aborted path<commit_after>/* global __REDIAL_PROPS__ */

import React, { Component } from 'react';
import PropTypes from 'prop-types';

import triggerHooks from './triggerHooks';
import createMap from './createMap';
import createMapKeys from './util/mapKeys';
import getAllComponents from './getAllComponents';

function hydrate(renderProps) {
  if (typeof __REDIAL_PROPS__ !== 'undefined' && Array.isArray(__REDIAL_PROPS__)) {
    const getMapKeyForComponent = createMapKeys(renderProps.routes, renderProps.components);
    const components = getAllComponents(renderProps.components);
    const componentKeys = components.map(getMapKeyForComponent);
    return createMap(componentKeys, __REDIAL_PROPS__);
  }

  return createMap();
}

export default class RedialContext extends Component {
  static displayName = 'RedialContext';

  static propTypes = {
    children: PropTypes.node.isRequired,

    // RouterContext default
    renderProps: PropTypes.object.isRequired,

    // Custom
    locals: PropTypes.object,
    beforeTransition: PropTypes.array,
    afterTransition: PropTypes.array,
    parallel: PropTypes.bool,
    initialLoading: PropTypes.func,
    onError: PropTypes.func,
    onAborted: PropTypes.func,
    onStarted: PropTypes.func,
    onCompleted: PropTypes.func,

    // Server
    redialMap: PropTypes.object,
  };

  static defaultProps = {
    beforeTransition: [],
    afterTransition: [],
    parallel: false,

    onError(err, { beforeTransition }) {
      if (process.env.NODE_ENV !== 'production') {
        const type = beforeTransition ? 'beforeTransition' : 'afterTransition';
        console.error(type, err);
      }
    },

    onAborted(becauseError) {
      if (process.env.NODE_ENV !== 'production') {
        if (becauseError) {
          console.warn('Loading was aborted from an error');
        } else {
          console.warn('Loading was aborted manually');
        }
      }
    },

    onStarted(force) {
      if (process.env.NODE_ENV !== 'production') {
        console.info('Loading started. Force:', force);
      }
    },

    onCompleted(type) {
      if (process.env.NODE_ENV !== 'production') {
        console.info('Loading completed. Type:', type);
      }
    },
  };

  static childContextTypes = {
    redialContext: PropTypes.object,
  };

  constructor(props, context) {
    super(props, context);
    this.state = {
      loading: false,
      afterTransitionLoading: false,
      aborted: () => false,
      abort: () => {},
      prevRenderProps: undefined,
      redialMap: props.redialMap || hydrate(props.renderProps),
      initial: props.beforeTransition.length > 0,
    };
    this.completed = {
      beforeTransition: false,
      afterTransition: false,
      error: null,
    };
  }

  getChildContext() {
    const { loading, afterTransitionLoading, redialMap } = this.state;
    return {
      redialContext: {
        loading,
        afterTransitionLoading,
        redialMap,
        reloadComponent: (component) => {
          this.reloadComponent(component);
        },
        abortLoading: () => {
          this.abort();
        },
      },
    };
  }

  componentDidMount() {
    this.load(this.props.renderProps.components, this.props.renderProps);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.renderProps.location === this.props.renderProps.location) {
      return;
    }

    this.load(nextProps.renderProps.components, nextProps.renderProps);
  }

  componentWillUnmount() {
    this.unmounted = true;
  }

  reloadComponent(component) {
    this.load(component, this.props.renderProps, true);
  }

  abort(becauseError, abort) {
    // Make sure we only cancel if it is the correct ongoing request
    if (!abort || this.state.abort === abort) {
      // We need to be in a loading state for it to make sense
      // to abort something
      if (this.state.loading || this.state.afterTransitionLoading) {
        this.state.abort();

        this.setState({
          loading: false,
          afterTransitionLoading: false,
        });

        if (this.props.onAborted) {
          this.props.onAborted(becauseError);
        }
      }
    }
  }

  load(components, renderProps, force = false) {
    let isAborted = false;
    const abort = () => {
      isAborted = true;
    };
    const aborted = () => isAborted;

    const bail = () => {
      const currentLocation = this.props.renderProps.location;
      if (aborted()) {
        return 'aborted';
      } else if (currentLocation !== renderProps.location) {
        return 'location-changed';
      }

      return false;
    };

    if (this.props.onStarted) {
      this.props.onStarted(force);
    }

    this.completed.beforeTransition = false;

    this.setState({
      aborted,
      abort,
      loading: true,
      prevRenderProps: this.state.loading || this.state.aborted()
        ? this.state.prevRenderProps
        : this.props.renderProps,
    });

    if (this.props.parallel) {
      this.runAfterTransition(
        this.props.afterTransition,
        components,
        renderProps,
        force,
        bail
      )
      .then(() => {
        if (this.completed.afterTransition) {
          this.props.onCompleted('afterTransition');
        }
      })
      .catch((err) => {
        // We will only propagate this error if beforeTransition have been completed
        // This because the beforeTransition error is more critical
        const error = () => this.props.onError(err, {
          reason: bail() || 'other',
          beforeTransition: false,
          router: this.props.renderProps.router,
          abort: () => this.abort(true, abort),
        });

        if (this.completed.beforeTransition) {
          error();
        } else {
          this.completed.error = error;
        }
      });
    }

    this.runBeforeTransition(
      this.props.beforeTransition,
      components,
      renderProps,
      force,
      bail
    )
    .catch((error) => {
      let afterTransition = false;
      if (error && error.afterTransition !== undefined) {
        afterTransition = error.afterTransition;
        error = error.error; // eslint-disable-line
      }

      this.props.onError(error, {
        reason: bail() || 'other',
        // If not defined before it's a beforeTransition error
        beforeTransition: !afterTransition,
        router: this.props.renderProps.router,
        abort: () => this.abort(true, abort),
      });
    });
  }

  runAfterTransition(hooks, components, renderProps, force = false, bail) {
    // Get afterTransition data, will not block route transitions
    this.completed.afterTransition = false;
    this.completed.error = null;

    this.setState({
      afterTransitionLoading: true,
    });

    return triggerHooks({
      hooks,
      components,
      renderProps,
      redialMap: this.state.redialMap,
      locals: this.props.locals,
      force,
      bail,
    }).then(({ redialMap }) => {
      this.completed.afterTransition = true;
      this.setState({
        afterTransitionLoading: false,
        redialMap,
      });
    });
  }

  runBeforeTransition(hooks, components, renderProps, force = false, bail) {
    const completeRouteTransition = (redialMap) => {
      if (!bail() && !this.unmounted) {
        this.setState({
          loading: false,
          redialMap,
          prevRenderProps: undefined,
          initial: false,
        });

        this.props.onCompleted('beforeTransition');

        this.completed.beforeTransition = true;

        // Start afterTransition if we are not in parallel
        if (!this.props.parallel) {
          return this.runAfterTransition(
            this.props.afterTransition,
            components,
            renderProps,
            force,
            bail
          )
          .then(() => {
            this.props.onCompleted('afterTransition');
          })
          .catch((error) => Promise.reject({ error, afterTransition: true }));
        } else if (this.completed.afterTransition) {
          this.completed.afterTransition = false;
          this.props.onCompleted('afterTransition');
        } else if (this.completed.error) {
          this.completed.error();
        }
      }

      return Promise.resolve();
    };

    return triggerHooks({
      hooks,
      components,
      renderProps,
      redialMap: this.state.redialMap,
      locals: this.props.locals,
      force,
      bail,
    }).then(({ redialMap }) =>
      completeRouteTransition(redialMap)
    );
  }

  render() {
    if (this.props.initialLoading && this.state.initial && this.state.redialMap.size() === 0) {
      return this.props.initialLoading();
    }

    const props = (this.state.loading || this.state.aborted()) && this.state.prevRenderProps;
    if (props) {
      /* eslint-disable no-unused-vars */
      // Omit `createElement`. Otherwise we might skip `renderRouteContext` in `applyMiddleware`.
      const { createElement, ...prevProps } = props;
      /* eslint-enable no-unused-vars */
      return React.cloneElement(
        this.props.children,
        prevProps,
      );
    }

    return this.props.children;
  }
}
<|endoftext|>


<commit_before>(function() {
  slBarogram = function(placeholder) {
    // Private attributes

    var baro = this;

    var flot = null;

    var active = [];
    var passive = [];
    var enls = [];
    var contests = [];
    var time_highlight = null;

    // Public attributes and functions

    /**
     * @expose
     * Draws the barogram onto the underlying canvas
     */
    baro.draw = function() {
      update();
      flot.setupGrid();
      flot.draw();
    };

    /**
     * @expose
     * Clears the active traces from the barogram
     */
    baro.clearActiveTraces = function() {
      active = [];
    };

    /**
     * @expose
     * Sets the active traces for the barogram
     */
    baro.setActiveTraces = function(data) {
      active = data;
    };

    /**
     * @expose
     * Clears the passive traces from the barogram
     */
    baro.clearPassiveTraces = function() {
      passive = [];
    };

    /**
     * @expose
     * Sets the passive traces for the barogram
     */
    baro.setPassiveTraces = function(data) {
      passive = data;
    };

    /**
     * @expose
     * Clears the ENL data
     */
    baro.clearENLData = function() {
      enls = [];
    };

    /**
     * @expose
     * Sets the ENL data
     */
    baro.setENLData = function(data) {
      enls = data;
    };

    /**
     * @expose
     * Clears the contest markers
     */
    baro.clearContests = function() {
      contests = [];
    };

    /**
     * @expose
     * Sets the contest markers
     */
    baro.setContests = function(data) {
      contests = data;
    };

    /**
     * @expose
     * Clears the crosshair from the barogram
     */
    baro.clearTime = function() {
      baro.setTime(null);
    };

    /**
     * @expose
     * Set the crosshair to the given time
     *
     * @param {?number} time If null the crosshair is removed,
     *   if -1 the crosshair is moved to the end of the barogram,
     *   else the crosshair is moved to the given time.
     */
    baro.setTime = function(time) {
      if (time === null)
        flot.clearCrosshair();
      else if (time == -1)
        flot.lockCrosshair({x: 999999999});
      else
        flot.lockCrosshair({x: global_time * 1000});
    };

    /**
     * @expose
     * Clears the time interval limits from the barogram
     */
    baro.clearTimeInterval = function() {
      var opt = flot.getOptions();
      opt.xaxes[0].min = opt.xaxes[0].max = null;
    };

    /**
     * @expose
     * Sets the time interval that should be shown on the barogram
     *
     * @param {number} start The earliest time that should be shown.
     * @param {number} end The latest time that should be shown.
     */
    baro.setTimeInterval = function(start, end) {
      var opt = flot.getOptions();
      opt.xaxes[0].min = start * 1000;
      opt.xaxes[0].max = end * 1000;
    };

    /**
     * @expose
     * Clears the highlight of a certain time interval from the barogram
     */
    baro.clearTimeHighlight = function() {
      time_highlight = null;
    };

    /**
     * @expose
     * Highlights a certain time interval on the barogram
     *
     * @param {number} start The earliest time that should be highlighted.
     * @param {number} end The latest time that should be highlighted.
     */
    baro.setTimeHighlight = function(start, end) {
      time_highlight = {
        start: start,
        end: end
      };
    };

    // Initialization

    setupFlot();
    attachEventHandlers();

    function setupFlot() {
      flot = $.plot(placeholder, [], {
        grid: {
          borderWidth: 0,
          hoverable: true,
          autoHighlight: false,
          margin: 5
        },
        xaxis: {
          mode: 'time',
          timeformat: '%H:%M'
        },
        yaxes: [
          {
            tickFormatter: slUnits.addAltitudeUnit
          },
          {
            show: false,
            min: 0,
            max: 1000
          }
        ],
        crosshair: {
          mode: 'x'
        }
      });
    }

    function attachEventHandlers() {
      placeholder.on('plothover', function(event, pos) {
        $(baro).trigger('barohover', [pos.x / 1000.]);
      }).on('mouseout', function(event) {
        $(baro).trigger('mouseout');
      });
    }

    function update() {
      var data = [];
      addActiveTraces(data);
      addPassiveTraces(data);
      addENLData(data);
      addContests(data);
      updateTimeHighlight();

      flot.setData(data);
    }

    function addActiveTraces(data) {
      var active_length = active.length;
      for (var i = 0; i < active_length; ++i) {
        var trace = active[i];

        data.push({
          data: trace.data,
          color: trace.color
        });
      }
    }

    function addPassiveTraces(data) {
      var passive_length = passive.length;
      for (var i = 0; i < passive_length; ++i) {
        var trace = passive[i];

        var color = $.color.parse(trace.color).add('a', -0.6).toString();

        data.push({
          data: trace.data,
          color: color,
          shadowSize: 0,
          lines: {
            lineWidth: 1
          }
        });
      }
    }

    function addENLData(data) {
      var enls_length = enls.length;
      for (var i = 0; i < enls_length; ++i) {
        var enl = enls[i];

        data.push({
          data: enl.data,
          color: enl.color,
          lines: {
            lineWidth: 0,
            fill: 0.2
          },
          yaxis: 2
        });
      }
    }

    /**
     * Adds the current contest markers to the data array
     *
     * @param {Array} data The data array that will be passed to flot.
     */
    function addContests(data) {
      // Skip the function if there are no contest markers
      if (contests === null)
        return;

      // Iterate through the contests
      var contests_length = contests.length;
      for (var i = 0; i < contests_length; ++i) {
        var contest = contests[i];

        var times = contest.times;
        var times_length = times.length;
        if (times_length < 1)
          continue;

        var color = contest.color;

        // Add the turnpoint markers to the markings array
        var markings = [];
        for (var j = 0; j < times_length; ++j) {
          var time = times[j] * 1000;

          markings.push({
            position: time
          });
        }

        // Add the chart series for this contest to the data array
        data.push({
          marks: {
            show: true,
            lineWidth: 1,
            toothSize: 6,
            color: color,
            fillColor: color
          },
          data: [],
          markdata: markings
        });
      }
    }

    /**
     * Adds the time highlight area to the flot options if available
     */
    function updateTimeHighlight() {
      // There is no flot.setOptions(), so we modify them in-place.
      var options = flot.getOptions();

      // Clear the markings if there is no time highlight
      if (time_highlight === null) {
        options.grid.markings = [];
        return;
      }

      // Add time highlight as flot markings
      options.grid.markings = [{
        color: '#fff083',
        xaxis: {
          from: time_highlight.start * 1000,
          to: time_highlight.end * 1000
        }
      }];
    }
  };
})();
<commit_msg>baro.js: Added elevations support<commit_after>(function() {
  slBarogram = function(placeholder) {
    // Private attributes

    var baro = this;

    var flot = null;

    var active = [];
    var passive = [];
    var enls = [];
    var contests = [];
    var elevations = [];
    var time_highlight = null;

    // Public attributes and functions

    /**
     * @expose
     * Draws the barogram onto the underlying canvas
     */
    baro.draw = function() {
      update();
      flot.setupGrid();
      flot.draw();
    };

    /**
     * @expose
     * Clears the active traces from the barogram
     */
    baro.clearActiveTraces = function() {
      active = [];
    };

    /**
     * @expose
     * Sets the active traces for the barogram
     */
    baro.setActiveTraces = function(data) {
      active = data;
    };

    /**
     * @expose
     * Clears the passive traces from the barogram
     */
    baro.clearPassiveTraces = function() {
      passive = [];
    };

    /**
     * @expose
     * Sets the passive traces for the barogram
     */
    baro.setPassiveTraces = function(data) {
      passive = data;
    };

    /**
     * @expose
     * Clears the ENL data
     */
    baro.clearENLData = function() {
      enls = [];
    };

    /**
     * @expose
     * Sets the ENL data
     */
    baro.setENLData = function(data) {
      enls = data;
    };

    /**
     * @expose
     * Clears the contest markers
     */
    baro.clearContests = function() {
      contests = [];
    };

    /**
     * @expose
     * Sets the contest markers
     */
    baro.setContests = function(data) {
      contests = data;
    };

    /**
     * @expose
     * Clears the elevation data
     */
    baro.clearElevations = function() {
      elevations = [];
    };

    /**
     * @expose
     * Sets the elevation data
     */
    baro.setElevations = function(data) {
      elevations = data;
    };

    /**
     * @expose
     * Clears the crosshair from the barogram
     */
    baro.clearTime = function() {
      baro.setTime(null);
    };

    /**
     * @expose
     * Set the crosshair to the given time
     *
     * @param {?number} time If null the crosshair is removed,
     *   if -1 the crosshair is moved to the end of the barogram,
     *   else the crosshair is moved to the given time.
     */
    baro.setTime = function(time) {
      if (time === null)
        flot.clearCrosshair();
      else if (time == -1)
        flot.lockCrosshair({x: 999999999});
      else
        flot.lockCrosshair({x: global_time * 1000});
    };

    /**
     * @expose
     * Clears the time interval limits from the barogram
     */
    baro.clearTimeInterval = function() {
      var opt = flot.getOptions();
      opt.xaxes[0].min = opt.xaxes[0].max = null;
    };

    /**
     * @expose
     * Sets the time interval that should be shown on the barogram
     *
     * @param {number} start The earliest time that should be shown.
     * @param {number} end The latest time that should be shown.
     */
    baro.setTimeInterval = function(start, end) {
      var opt = flot.getOptions();
      opt.xaxes[0].min = start * 1000;
      opt.xaxes[0].max = end * 1000;
    };

    /**
     * @expose
     * Clears the highlight of a certain time interval from the barogram
     */
    baro.clearTimeHighlight = function() {
      time_highlight = null;
    };

    /**
     * @expose
     * Highlights a certain time interval on the barogram
     *
     * @param {number} start The earliest time that should be highlighted.
     * @param {number} end The latest time that should be highlighted.
     */
    baro.setTimeHighlight = function(start, end) {
      time_highlight = {
        start: start,
        end: end
      };
    };

    // Initialization

    setupFlot();
    attachEventHandlers();

    function setupFlot() {
      flot = $.plot(placeholder, [], {
        grid: {
          borderWidth: 0,
          hoverable: true,
          autoHighlight: false,
          margin: 5
        },
        xaxis: {
          mode: 'time',
          timeformat: '%H:%M'
        },
        yaxes: [
          {
            tickFormatter: slUnits.addAltitudeUnit
          },
          {
            show: false,
            min: 0,
            max: 1000
          }
        ],
        crosshair: {
          mode: 'x'
        }
      });
    }

    function attachEventHandlers() {
      placeholder.on('plothover', function(event, pos) {
        $(baro).trigger('barohover', [pos.x / 1000.]);
      }).on('mouseout', function(event) {
        $(baro).trigger('mouseout');
      });
    }

    function update() {
      var data = [];
      addActiveTraces(data);
      addPassiveTraces(data);
      addENLData(data);
      addContests(data);
      addElevations(data);
      updateTimeHighlight();

      flot.setData(data);
    }

    function addActiveTraces(data) {
      var active_length = active.length;
      for (var i = 0; i < active_length; ++i) {
        var trace = active[i];

        data.push({
          data: trace.data,
          color: trace.color
        });
      }
    }

    function addPassiveTraces(data) {
      var passive_length = passive.length;
      for (var i = 0; i < passive_length; ++i) {
        var trace = passive[i];

        var color = $.color.parse(trace.color).add('a', -0.6).toString();

        data.push({
          data: trace.data,
          color: color,
          shadowSize: 0,
          lines: {
            lineWidth: 1
          }
        });
      }
    }

    function addENLData(data) {
      var enls_length = enls.length;
      for (var i = 0; i < enls_length; ++i) {
        var enl = enls[i];

        data.push({
          data: enl.data,
          color: enl.color,
          lines: {
            lineWidth: 0,
            fill: 0.2
          },
          yaxis: 2
        });
      }
    }

    /**
     * Adds the current contest markers to the data array
     *
     * @param {Array} data The data array that will be passed to flot.
     */
    function addContests(data) {
      // Skip the function if there are no contest markers
      if (contests === null)
        return;

      // Iterate through the contests
      var contests_length = contests.length;
      for (var i = 0; i < contests_length; ++i) {
        var contest = contests[i];

        var times = contest.times;
        var times_length = times.length;
        if (times_length < 1)
          continue;

        var color = contest.color;

        // Add the turnpoint markers to the markings array
        var markings = [];
        for (var j = 0; j < times_length; ++j) {
          var time = times[j] * 1000;

          markings.push({
            position: time
          });
        }

        // Add the chart series for this contest to the data array
        data.push({
          marks: {
            show: true,
            lineWidth: 1,
            toothSize: 6,
            color: color,
            fillColor: color
          },
          data: [],
          markdata: markings
        });
      }
    }

    function addElevations(data) {
      data.push({
        data: elevations,
        color: 'rgb(235, 155, 98)',
        lines: {
          lineWidth: 0,
          fill: 0.8
        }
      });
    }

    /**
     * Adds the time highlight area to the flot options if available
     */
    function updateTimeHighlight() {
      // There is no flot.setOptions(), so we modify them in-place.
      var options = flot.getOptions();

      // Clear the markings if there is no time highlight
      if (time_highlight === null) {
        options.grid.markings = [];
        return;
      }

      // Add time highlight as flot markings
      options.grid.markings = [{
        color: '#fff083',
        xaxis: {
          from: time_highlight.start * 1000,
          to: time_highlight.end * 1000
        }
      }];
    }
  };
})();
<|endoftext|>


<commit_before>var express = require('express'),
  ffmpeg = require('../index');

var app = express.createServer();

app.use(express.static(__dirname + '/flowplayer'));

app.get('/', function(req, res) {
  res.send('index.html');
});

app.get('/video/:filename', function(req, res) {
  res.contentType('flv');
  // make sure you set the correct path to your video file storage
  var pathToMovie = '/path/to/storage/' + req.params.filename;
  var proc = new ffmpeg({ source: pathToMovie, nolog: true })
    // use the 'flashvideo' preset (located in /lib/presets/flashvideo.js)
    .usingPreset('flashvideo')
    // save to stream
    .writeToStream(res, function(retcode, error){
      console.log('file has been converted succesfully');
    });
});

app.listen(4000);
<commit_msg>Fixed this warning in newer versions of express.js: Warning: express.createServer() is deprecated, express applications no longer inherit from http.Server, please use:<commit_after>var express = require('express'),
  ffmpeg = require('../index');

var app = express();

app.use(express.static(__dirname + '/flowplayer'));

app.get('/', function(req, res) {
  res.send('index.html');
});

app.get('/video/:filename', function(req, res) {
  res.contentType('flv');
  // make sure you set the correct path to your video file storage
  var pathToMovie = '/path/to/storage/' + req.params.filename;
  var proc = new ffmpeg({ source: pathToMovie, nolog: true })
    // use the 'flashvideo' preset (located in /lib/presets/flashvideo.js)
    .usingPreset('flashvideo')
    // save to stream
    .writeToStream(res, function(retcode, error){
      console.log('file has been converted succesfully');
    });
});

app.listen(4000);
<|endoftext|>


<commit_before>import {defaultSchema} from "../model"

import {defaultKeymap} from "./commands"

class Option {
  constructor(defaultValue, update, updateOnInit) {
    this.defaultValue = defaultValue
    this.update = update
    this.updateOnInit = updateOnInit !== false
  }
}

const options = {
  __proto__: null,

  // :: Schema #path=schema #kind=option
  // The [schema](#Schema) that the editor's document should use.
  schema: new Option(defaultSchema, false, false),

  // :: any #path=doc #kind=option
  // The starting document. Usually a `Node`, but can be in another
  // format when the `docFormat` option is also specified.
  doc: new Option(null, function(pm, value) {
    pm.setDoc(value)
  }, false),

  // :: ?string #path=docFormat #kind=option
  // The format in which the `doc` option is given. Defaults to `null`
  // (a raw `Node`).
  docFormat: new Option(null),

  // :: ?union<DOMNode, (DOMNode)> #path=place #kind=option
  // Determines the placement of the editor in the page. When `null`,
  // the editor is not placed. When a DOM node is given, the editor is
  // appended to that node. When a function is given, it is called
  // with the editor's wrapping DOM node, and is expected to place it
  // into the document.
  place: new Option(null),

  // :: Keymap #path=keymap #kind=option
  // The base [keymap](#Keymap). When not given, a default keymap is
  // synthesized from the default key bindings provided by the
  // [commands](#Command) that are in scope for the editor.
  keymap: new Option(null, (pm, value) => {
    if (!value) pm.options.keymap = defaultKeymap(pm)
  }),

  // :: number #path=historyDepth #kind=option
  // The amount of history events that are collected before the oldest
  // events are discarded. Defaults to 100.
  historyDepth: new Option(100),

  // :: number #path=historyEventDelay #kind=option
  // The amount of milliseconds that must pass between changes to
  // start a new history event. Defaults to 500.
  historyEventDelay: new Option(500),

  // :: string #path=commandParamHandler #kind=option
  // The name of the handler used to prompt the user for [command
  // parameters](#CommandParam). Only relevant when multiple such
  // handlers are loaded, and you want to choose between them.
  commandParamHandler: new Option("default"),

  // :: ?string #path=label #kind=option
  // The label of the editor. When set, the editable DOM node gets an
  // `aria-label` attribute with this value.
  label: new Option(null)
}

// :: (string, any, (pm: ProseMirror, newValue: any, oldValue: any, init: bool), bool)
// Define a new option. The `update` handler will be called with the
// option's old and new value every time the option is
// [changed](#ProseMirror.setOption). When `updateOnInit` is true, it
// is also called on editor init, with null as the old value, and a fourth
// argument of true.
export function defineOption(name, defaultValue, update, updateOnInit) {
  options[name] = new Option(defaultValue, update, updateOnInit)
}

export function parseOptions(obj) {
  let result = Object.create(null)
  let given = obj ? [obj].concat(obj.use || []) : []
  outer: for (let opt in options) {
    for (let i = 0; i < given.length; i++) {
      if (opt in given[i]) {
        result[opt] = given[i][opt]
        continue outer
      }
    }
    result[opt] = options[opt].defaultValue
  }
  return result
}

export function initOptions(pm) {
  for (var opt in options) {
    let desc = options[opt]
    if (desc.update && desc.updateOnInit)
      desc.update(pm, pm.options[opt], null, true)
  }
}

export function setOption(pm, name, value) {
  let desc = options[name]
  if (desc.update === false) throw new Error("Option '" + name + "' can not be changed")
  let old = pm.options[name]
  pm.options[name] = value
  if (desc.update) desc.update(pm, value, old, false)
}
<commit_msg>Use defineOption to define built-in options<commit_after>import {defaultSchema} from "../model"

import {defaultKeymap} from "./commands"

class Option {
  constructor(defaultValue, update, updateOnInit) {
    this.defaultValue = defaultValue
    this.update = update
    this.updateOnInit = updateOnInit !== false
  }
}

const options = Object.create(null)

// :: (string, any, (pm: ProseMirror, newValue: any, oldValue: any, init: bool), bool)
// Define a new option. The `update` handler will be called with the
// option's old and new value every time the option is
// [changed](#ProseMirror.setOption). When `updateOnInit` is true, it
// is also called on editor init, with null as the old value, and a fourth
// argument of true.
export function defineOption(name, defaultValue, update, updateOnInit) {
  options[name] = new Option(defaultValue, update, updateOnInit)
}

// :: Schema #path=schema #kind=option
// The [schema](#Schema) that the editor's document should use.
defineOption("schema", defaultSchema, false)

// :: any #path=doc #kind=option
// The starting document. Usually a `Node`, but can be in another
// format when the `docFormat` option is also specified.
defineOption("doc", null, (pm, value) => pm.setDoc(value), false)

// :: ?string #path=docFormat #kind=option
// The format in which the `doc` option is given. Defaults to `null`
// (a raw `Node`).
defineOption("docFormat", null)

// :: ?union<DOMNode, (DOMNode)> #path=place #kind=option
// Determines the placement of the editor in the page. When `null`,
// the editor is not placed. When a DOM node is given, the editor is
// appended to that node. When a function is given, it is called
// with the editor's wrapping DOM node, and is expected to place it
// into the document.
defineOption("place", null)

// :: Keymap #path=keymap #kind=option
// The base [keymap](#Keymap). When not given, a default keymap is
// synthesized from the default key bindings provided by the
// [commands](#Command) that are in scope for the editor.
defineOption("keymap", null, (pm, value) => {
  if (!value) pm.options.keymap = defaultKeymap(pm)
})

// :: number #path=historyDepth #kind=option
// The amount of history events that are collected before the oldest
// events are discarded. Defaults to 100.
defineOption("historyDepth", 100)

// :: number #path=historyEventDelay #kind=option
// The amount of milliseconds that must pass between changes to
// start a new history event. Defaults to 500.
defineOption("historyEventDelay", 500)

// :: string #path=commandParamHandler #kind=option
// The name of the handler used to prompt the user for [command
// parameters](#CommandParam). Only relevant when multiple such
// handlers are loaded, and you want to choose between them.
defineOption("commandParamHandler", "default")

// :: ?string #path=label #kind=option
// The label of the editor. When set, the editable DOM node gets an
// `aria-label` attribute with this value.
defineOption("label", null)

export function parseOptions(obj) {
  let result = Object.create(null)
  let given = obj ? [obj].concat(obj.use || []) : []
  outer: for (let opt in options) {
    for (let i = 0; i < given.length; i++) {
      if (opt in given[i]) {
        result[opt] = given[i][opt]
        continue outer
      }
    }
    result[opt] = options[opt].defaultValue
  }
  return result
}

export function initOptions(pm) {
  for (var opt in options) {
    let desc = options[opt]
    if (desc.update && desc.updateOnInit)
      desc.update(pm, pm.options[opt], null, true)
  }
}

export function setOption(pm, name, value) {
  let desc = options[name]
  if (desc.update === false) throw new Error("Option '" + name + "' can not be changed")
  let old = pm.options[name]
  pm.options[name] = value
  if (desc.update) desc.update(pm, value, old, false)
}
<|endoftext|>


<commit_before>define(['ash',
    'game/GameGlobals',
	'game/constants/ItemConstants',
	'game/constants/PerkConstants',
	'game/constants/LocaleConstants',
	'game/constants/PositionConstants',
	'game/constants/UpgradeConstants',
	'game/constants/WorldConstants',
	'game/vos/ResourcesVO'],
function (Ash, GameGlobals, ItemConstants, PerkConstants, LocaleConstants, PositionConstants, UpgradeConstants, WorldConstants, ResourcesVO) {

    var FightConstants = {

		FIGHT_PLAYER_BASE_ATT: 3,
		FIGHT_PLAYER_BASE_DEF: 1,
		MAX_FOLLOWER_MAX: 3,

        HIT_STUN_TIME: 0.25,

        // applies both to enemy and player damage and makes fights to faster (with fewer hits)
        FIGHT_DAMAGE_BASE: 16,
        // applies to both enemy and player and makes fights go faster (less time between hits)
        FIGHT_SPEED_FACTOR: 1.2,

        PARTICIPANT_TYPE_FRIENDLY: 0,
        PARTICIPANT_TYPE_ENEMY: 1,

        getStrength: function (att, def, hp) {
             var str = (att + def) / 100 * hp;
             return Math.round(str);
        },

        getDamagePerSec: function (att, def) {
            var ratio = att / (att + def);
            // damage is part determined by attack, part by a static value
            // -> increases with att but tends to be around reasonable numbers relative to max hp which is around 100
            var result =  ratio * att / 2 + ratio * this.FIGHT_DAMAGE_BASE / 2;
            result = Math.max(1, result);
            return result;
        },

        getPlayerAttackTime: function (itemsComponent) {
            var weapons = itemsComponent.getEquipped(ItemConstants.itemTypes.weapon);
            var weapon = weapons.length > 0 ? weapons[0] : null;
            var weaponSpeedBonus = weapon ? weapon.getBonus(ItemConstants.itemBonusTypes.fight_speed) || 1 : 1;
            return 1 / weaponSpeedBonus / this.FIGHT_SPEED_FACTOR;
        },

		getPlayerAtt: function (playerStamina, itemsComponent) {
			var itemBonus = itemsComponent.getCurrentBonus(ItemConstants.itemBonusTypes.fight_att, ItemConstants.itemTypes.weapon);
			var playerAtt = Math.floor(this.FIGHT_PLAYER_BASE_ATT + itemBonus);
			var followerBonus = itemsComponent.getCurrentBonus(ItemConstants.itemBonusTypes.fight_att, ItemConstants.itemTypes.follower);
            return playerAtt + followerBonus;
        },

        getPlayerAttDesc: function (playerStamina, itemsComponent) {
            var itemBonus = itemsComponent.getCurrentBonus(ItemConstants.itemBonusTypes.fight_att, ItemConstants.itemTypes.weapon);
            var healthFactor = (playerStamina.health/100);
            var followerBonus = itemsComponent.getCurrentBonus(ItemConstants.itemBonusTypes.fight_att, ItemConstants.itemTypes.follower);
            var desc = "player: " + this.FIGHT_PLAYER_BASE_ATT;
            if (itemBonus > 0) desc += "
equipment: " + itemBonus;
            if (healthFactor < 1) desc += "
health: -" + Math.round((1-healthFactor) * 1000) / 10 + "%";
            if (followerBonus > 0) desc += "
followers: " + followerBonus;
            return desc;
        },

        getPlayerDef: function (playerStamina, itemsComponent) {
            var itemBonus = itemsComponent.getCurrentBonus(ItemConstants.itemBonusTypes.fight_def);
            return this.FIGHT_PLAYER_BASE_DEF + itemBonus;
        },

        getPlayerDefDesc: function (playerStamina, itemsComponent) {
            var itemBonus = itemsComponent.getCurrentBonus(ItemConstants.itemBonusTypes.fight_def);
            var desc = "player: " + this.FIGHT_PLAYER_BASE_DEF;
            if (itemBonus > 0) desc += "
equipment: " + itemBonus;
            return desc;
        },

        getPlayerStrength: function (playerStamina, itemsComponent) {
            var att = this.getPlayerAtt(playerStamina, itemsComponent);
            var def = this.getPlayerDef(playerStamina, itemsComponent);
            return this.getStrength(att, def, playerStamina.maxHP);
        },

        getMaxFollowers: function (numCamps) {
			var firstFollowerCamp = UpgradeConstants.getMinimumCampOrdinalForUpgrade("unlock_building_inn");
			var numFollowerCamps = numCamps - firstFollowerCamp + 1;
			var totalFollowerCamps = (WorldConstants.CAMPS_TOTAL - firstFollowerCamp + 1);
			var maxFollowers = Math.ceil(numFollowerCamps / totalFollowerCamps * this.MAX_FOLLOWER_MAX);
			return Math.max(0, maxFollowers);
        },

        getTypicalFollowers: function (numCamps) {
			var firstFollowerCamp = UpgradeConstants.getMinimumCampOrdinalForUpgrade("unlock_building_inn");
            if (numCamps <= firstFollowerCamp) return 0;
            return this.getMaxFollowers(numCamps);
        },

        getEnemyAttackTime: function (enemy) {
            var enemySpeed = enemy.speed || 1;
            return 1 / enemySpeed / this.FIGHT_SPEED_FACTOR;
        },

        // Damage done by player to an enemy per sec
        getEnemyDamagePerSec: function (enemy, playerStamina, itemsComponent) {
            if (!enemy) return 0;
            var playerAtt = FightConstants.getPlayerAtt(playerStamina, itemsComponent);
            return this.getDamagePerSec(playerAtt, enemy.def);
        },

        getEnemyDamagePerAttack: function (enemy, playerStamina, itemsComponent) {
            var dps = this.getEnemyDamagePerSec(enemy, playerStamina, itemsComponent);
            var attackTime = this.getPlayerAttackTime(itemsComponent);
            return dps * attackTime;
        },

        // Damage done by the enemy to the player per sec
        getPlayerDamagePerSec: function (enemy, playerStamina, itemsComponent) {
            if (!enemy) return 0;
            var playerDef = FightConstants.getPlayerDef(playerStamina, itemsComponent);
            return this.getDamagePerSec(enemy.att, playerDef);
        },

        getPlayerDamagePerAttack: function (enemy, playerStamina, itemsComponent) {
            var dps = this.getPlayerDamagePerSec(enemy, playerStamina, itemsComponent);
            var attacktTime = this.getEnemyAttackTime(enemy);
            return dps * attacktTime;
        },

        getRandomDamagePerSec: function (enemy, playerStamina, itemsComponent) {
            var playerDamage = this.getPlayerDamagePerSec(enemy, playerStamina, itemsComponent);
            return enemy.attRandomFactor * playerDamage;
        },

        getRandomDamagePerAttack: function (enemy, playerStamina, itemsComponent) {
            var dps = this.getRandomDamagePerSec(enemy, playerStamina, itemsComponent);
            var attacktTime = this.getEnemyAttackTime(enemy);
            return dps * attacktTime;
        },

        getMissChance: function (participantType) {
            if (participantType == this.PARTICIPANT_TYPE_FRIENDLY)
                return 0.03;
            return 0.06;
        },

        getPoorHitChance: function (participantType) {
            if (participantType == this.PARTICIPANT_TYPE_FRIENDLY)
                return 0.07;
            return 0.09;
        },

        getGoodHitChance: function (participantType) {
            if (participantType == this.PARTICIPANT_TYPE_FRIENDLY)
                return 0.07;
            return 0.09;
        },

        getCriticalHitChance: function (participantType) {
            if (participantType == this.PARTICIPANT_TYPE_FRIENDLY)
                return 0.07;
            return 0.05;
        },

        getFightWinProbability: function(enemy, playerStamina, itemsComponent) {
            if (!enemy) return 1;
            var enemyDamage = this.getEnemyDamagePerSec(enemy, playerStamina, itemsComponent);
            var playerDamage = this.getPlayerDamagePerSec(enemy, playerStamina, itemsComponent);

            var playerDamageRandomMin = playerDamage * -0.5;
            var playerDamageRandomMax = playerDamage * 0.5;

            var timeAliveEnemy = enemy.maxHP / enemyDamage * 1.05;
            var timeAlivePlayerMin = playerStamina.maxHP / (playerDamage + playerDamageRandomMax) * 0.95;
            var timeAlivePlayerMax = playerStamina.maxHP / (playerDamage + playerDamageRandomMin) * 1.05;

            var ratio =  (timeAlivePlayerMax - timeAliveEnemy) / (timeAlivePlayerMax - timeAlivePlayerMin);
            if (ratio < 0.05) ratio = 0.05;
            if (ratio > 0.95) ratio = 0.95;

            return ratio;
        },

		getEnemyLocaleId: function (baseActionID, action, isNeighbour) {
			switch (baseActionID) {
				case "clear_workshop": return LocaleConstants.LOCALE_ID_WORKSHOP;
				default: return null;
			}
		},

		getRelatedSectorDirection: function (baseActionID, action) {
			switch (baseActionID) {
				case "fight_gang": return parseInt(action.split("_")[2]);
				default: return PositionConstants.DIRECTION_NONE;
			}
		},

    };

    return FightConstants;

});
<commit_msg>[ui] adjust fight speed<commit_after>define(['ash',
    'game/GameGlobals',
	'game/constants/ItemConstants',
	'game/constants/PerkConstants',
	'game/constants/LocaleConstants',
	'game/constants/PositionConstants',
	'game/constants/UpgradeConstants',
	'game/constants/WorldConstants',
	'game/vos/ResourcesVO'],
function (Ash, GameGlobals, ItemConstants, PerkConstants, LocaleConstants, PositionConstants, UpgradeConstants, WorldConstants, ResourcesVO) {

    var FightConstants = {

		FIGHT_PLAYER_BASE_ATT: 3,
		FIGHT_PLAYER_BASE_DEF: 1,
		MAX_FOLLOWER_MAX: 3,

        HIT_STUN_TIME: 0.25,

        // applies both to enemy and player damage and makes fights to faster (with fewer hits)
        FIGHT_DAMAGE_BASE: 18,
        // applies to both enemy and player and makes fights go faster (less time between hits)
        FIGHT_SPEED_FACTOR: 1.25,

        PARTICIPANT_TYPE_FRIENDLY: 0,
        PARTICIPANT_TYPE_ENEMY: 1,

        getStrength: function (att, def, hp) {
             var str = (att + def) / 100 * hp;
             return Math.round(str);
        },

        getDamagePerSec: function (att, def) {
            var ratio = att / (att + def);
            // damage is part determined by attack, part by a static value
            // -> increases with att but tends to be around reasonable numbers relative to max hp which is around 100
            var result =  ratio * att / 2 + ratio * this.FIGHT_DAMAGE_BASE / 2;
            result = Math.max(1, result);
            return result;
        },

        getPlayerAttackTime: function (itemsComponent) {
            var weapons = itemsComponent.getEquipped(ItemConstants.itemTypes.weapon);
            var weapon = weapons.length > 0 ? weapons[0] : null;
            var weaponSpeedBonus = weapon ? weapon.getBonus(ItemConstants.itemBonusTypes.fight_speed) || 1 : 1;
            return 1 / weaponSpeedBonus / this.FIGHT_SPEED_FACTOR;
        },

		getPlayerAtt: function (playerStamina, itemsComponent) {
			var itemBonus = itemsComponent.getCurrentBonus(ItemConstants.itemBonusTypes.fight_att, ItemConstants.itemTypes.weapon);
			var playerAtt = Math.floor(this.FIGHT_PLAYER_BASE_ATT + itemBonus);
			var followerBonus = itemsComponent.getCurrentBonus(ItemConstants.itemBonusTypes.fight_att, ItemConstants.itemTypes.follower);
            return playerAtt + followerBonus;
        },

        getPlayerAttDesc: function (playerStamina, itemsComponent) {
            var itemBonus = itemsComponent.getCurrentBonus(ItemConstants.itemBonusTypes.fight_att, ItemConstants.itemTypes.weapon);
            var healthFactor = (playerStamina.health/100);
            var followerBonus = itemsComponent.getCurrentBonus(ItemConstants.itemBonusTypes.fight_att, ItemConstants.itemTypes.follower);
            var desc = "player: " + this.FIGHT_PLAYER_BASE_ATT;
            if (itemBonus > 0) desc += "
equipment: " + itemBonus;
            if (healthFactor < 1) desc += "
health: -" + Math.round((1-healthFactor) * 1000) / 10 + "%";
            if (followerBonus > 0) desc += "
followers: " + followerBonus;
            return desc;
        },

        getPlayerDef: function (playerStamina, itemsComponent) {
            var itemBonus = itemsComponent.getCurrentBonus(ItemConstants.itemBonusTypes.fight_def);
            return this.FIGHT_PLAYER_BASE_DEF + itemBonus;
        },

        getPlayerDefDesc: function (playerStamina, itemsComponent) {
            var itemBonus = itemsComponent.getCurrentBonus(ItemConstants.itemBonusTypes.fight_def);
            var desc = "player: " + this.FIGHT_PLAYER_BASE_DEF;
            if (itemBonus > 0) desc += "
equipment: " + itemBonus;
            return desc;
        },

        getPlayerStrength: function (playerStamina, itemsComponent) {
            var att = this.getPlayerAtt(playerStamina, itemsComponent);
            var def = this.getPlayerDef(playerStamina, itemsComponent);
            return this.getStrength(att, def, playerStamina.maxHP);
        },

        getMaxFollowers: function (numCamps) {
			var firstFollowerCamp = UpgradeConstants.getMinimumCampOrdinalForUpgrade("unlock_building_inn");
			var numFollowerCamps = numCamps - firstFollowerCamp + 1;
			var totalFollowerCamps = (WorldConstants.CAMPS_TOTAL - firstFollowerCamp + 1);
			var maxFollowers = Math.ceil(numFollowerCamps / totalFollowerCamps * this.MAX_FOLLOWER_MAX);
			return Math.max(0, maxFollowers);
        },

        getTypicalFollowers: function (numCamps) {
			var firstFollowerCamp = UpgradeConstants.getMinimumCampOrdinalForUpgrade("unlock_building_inn");
            if (numCamps <= firstFollowerCamp) return 0;
            return this.getMaxFollowers(numCamps);
        },

        getEnemyAttackTime: function (enemy) {
            var enemySpeed = enemy.speed || 1;
            return 1 / enemySpeed / this.FIGHT_SPEED_FACTOR;
        },

        // Damage done by player to an enemy per sec
        getEnemyDamagePerSec: function (enemy, playerStamina, itemsComponent) {
            if (!enemy) return 0;
            var playerAtt = FightConstants.getPlayerAtt(playerStamina, itemsComponent);
            return this.getDamagePerSec(playerAtt, enemy.def);
        },

        getEnemyDamagePerAttack: function (enemy, playerStamina, itemsComponent) {
            var dps = this.getEnemyDamagePerSec(enemy, playerStamina, itemsComponent);
            var attackTime = this.getPlayerAttackTime(itemsComponent);
            return dps * attackTime;
        },

        // Damage done by the enemy to the player per sec
        getPlayerDamagePerSec: function (enemy, playerStamina, itemsComponent) {
            if (!enemy) return 0;
            var playerDef = FightConstants.getPlayerDef(playerStamina, itemsComponent);
            return this.getDamagePerSec(enemy.att, playerDef);
        },

        getPlayerDamagePerAttack: function (enemy, playerStamina, itemsComponent) {
            var dps = this.getPlayerDamagePerSec(enemy, playerStamina, itemsComponent);
            var attacktTime = this.getEnemyAttackTime(enemy);
            return dps * attacktTime;
        },

        getRandomDamagePerSec: function (enemy, playerStamina, itemsComponent) {
            var playerDamage = this.getPlayerDamagePerSec(enemy, playerStamina, itemsComponent);
            return enemy.attRandomFactor * playerDamage;
        },

        getRandomDamagePerAttack: function (enemy, playerStamina, itemsComponent) {
            var dps = this.getRandomDamagePerSec(enemy, playerStamina, itemsComponent);
            var attacktTime = this.getEnemyAttackTime(enemy);
            return dps * attacktTime;
        },

        getMissChance: function (participantType) {
            if (participantType == this.PARTICIPANT_TYPE_FRIENDLY)
                return 0.03;
            return 0.06;
        },

        getPoorHitChance: function (participantType) {
            if (participantType == this.PARTICIPANT_TYPE_FRIENDLY)
                return 0.07;
            return 0.09;
        },

        getGoodHitChance: function (participantType) {
            if (participantType == this.PARTICIPANT_TYPE_FRIENDLY)
                return 0.07;
            return 0.09;
        },

        getCriticalHitChance: function (participantType) {
            if (participantType == this.PARTICIPANT_TYPE_FRIENDLY)
                return 0.07;
            return 0.05;
        },

        getFightWinProbability: function(enemy, playerStamina, itemsComponent) {
            if (!enemy) return 1;
            var enemyDamage = this.getEnemyDamagePerSec(enemy, playerStamina, itemsComponent);
            var playerDamage = this.getPlayerDamagePerSec(enemy, playerStamina, itemsComponent);

            var playerDamageRandomMin = playerDamage * -0.5;
            var playerDamageRandomMax = playerDamage * 0.5;

            var timeAliveEnemy = enemy.maxHP / enemyDamage * 1.05;
            var timeAlivePlayerMin = playerStamina.maxHP / (playerDamage + playerDamageRandomMax) * 0.95;
            var timeAlivePlayerMax = playerStamina.maxHP / (playerDamage + playerDamageRandomMin) * 1.05;

            var ratio =  (timeAlivePlayerMax - timeAliveEnemy) / (timeAlivePlayerMax - timeAlivePlayerMin);
            if (ratio < 0.05) ratio = 0.05;
            if (ratio > 0.95) ratio = 0.95;

            return ratio;
        },

		getEnemyLocaleId: function (baseActionID, action, isNeighbour) {
			switch (baseActionID) {
				case "clear_workshop": return LocaleConstants.LOCALE_ID_WORKSHOP;
				default: return null;
			}
		},

		getRelatedSectorDirection: function (baseActionID, action) {
			switch (baseActionID) {
				case "fight_gang": return parseInt(action.split("_")[2]);
				default: return PositionConstants.DIRECTION_NONE;
			}
		},

    };

    return FightConstants;

});
<|endoftext|>