<commit_before>var Spinner = require('../widgets/spinner.js');
var Dice = require('../widgets/dice.js');
var Initiative = require('../core/initiative.js');
var increment = require('../core/increment.js');
var config = require('../config.js');
var log = require('../core/log.js');

var british = 0;
var american = 0;

function create(battle) {
	var composite = tabris.create("Composite", {
    	layoutData: {centerX: 0, top: config.PAGE_MARGIN},
        background: config.background,
        textColor: config.textColor,
        highlightOnTouch: true
	});

    var diceView = Dice.create([
    	{num: 1, low: 0, high: 9, color: 'red'},
    	{num: 1, low: 0, high: 9, color: 'blue'}
    ], {left: 50, top: 2}, function(dice) {
    	log.debug('Determine initiative');
        var result = Initiative.calc(battle, dice[0].value, spinBritish.getValue(), dice[1].value, spinAmerican.getValue());
        resultView.set('text', result)
	}).appendTo(composite);

    var resultView = tabris.create("TextView", {
    	text: "",
    	layoutData: {left: [diceView, 20], top: 15},
        background: config.background,
        textColor: config.textColor,
        font: 'bold 24px'
	}).appendTo(composite);

    var labelView = tabris.create("TextView", {
    	text: "Momentum",
        background: config.background,
        textColor: config.textColor,
    	layoutData: {centerX: 20, top: [diceView, 10]}
	}).appendTo(composite);

    var spinBritish = Spinner.create('British', british, true, {left: 0, right: [0,3], top: [labelView,5]}, function(valueView, incr) {
    	british = increment(british, incr, 0, 5);
    	valueView.set("text", british);
	}).appendTo(composite);

    var spinAmerican = Spinner.create('American', american, true, {left: 0, right: [0,3], top: [spinBritish,5]}, function(valueView, incr) {
    	american = increment(american, incr, 0, 5);
    	valueView.set("text", american);
	}).appendTo(composite);

	return composite;
}

module.exports = {
	create: function(battle) {
    	log.debug('Creating Initiative for ' + battle.name);
    	return create(battle);
    }
};
<commit_msg>use images for nationality on initiative view<commit_after>var Spinner = require('../widgets/spinner.js');
var Dice = require('../widgets/dice.js');
var Initiative = require('../core/initiative.js');
var increment = require('../core/increment.js');
var config = require('../config.js');
var log = require('../core/log.js');

var british = 0;
var american = 0;

function create(battle) {
	var composite = tabris.create("Composite", {
    	layoutData: {centerX: 0, top: config.PAGE_MARGIN},
        background: config.background,
        textColor: config.textColor,
        highlightOnTouch: true
	});

    var diceView = Dice.create([
    	{num: 1, low: 0, high: 9, color: 'red'},
    	{num: 1, low: 0, high: 9, color: 'blue'}
    ], {left: 50, top: 2}, function(dice) {
    	log.debug('Determine initiative');
        var result = Initiative.calc(battle, dice[0].value, spinBritish.getValue(), dice[1].value, spinAmerican.getValue());
        resultView.set('text', result)
	}).appendTo(composite);

    var resultView = tabris.create("TextView", {
    	text: "",
    	layoutData: {left: [diceView, 20], top: 15},
        background: config.background,
        textColor: config.textColor,
        font: 'bold 24px'
	}).appendTo(composite);

    var labelView = tabris.create("TextView", {
    	text: "Momentum",
        background: config.background,
        textColor: config.textColor,
    	layoutData: {centerX: 20, top: [diceView, 10]}
	}).appendTo(composite);

    var spinBritish = Spinner.create({src: 'images/british-flag-sm.png'}, british, true, {left: 0, right: [0,3], top: [labelView,5]}, function(valueView, incr) {
    	british = increment(british, incr, 0, 5);
    	valueView.set("text", british);
	}).appendTo(composite);

    var spinAmerican = Spinner.create({src: 'images/american-flag-sm.png'}, american, true, {left: 0, right: [0,3], top: [spinBritish,5]}, function(valueView, incr) {
    	american = increment(american, incr, 0, 5);
    	valueView.set("text", american);
	}).appendTo(composite);

	return composite;
}

module.exports = {
	create: function(battle) {
    	log.debug('Creating Initiative for ' + battle.name);
    	return create(battle);
    }
};
<|endoftext|>


<commit_before>module.exports = function(karma) {
  karma.configure({
    // base path, that will be used to resolve files and exclude
    basePath: '../..',

    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
        'lib/jquery/jquery-2.0.3.min.js',
        'lib/angular/1.1.5/angular.js',
        'lib/angular/1.1.5/angular-cookies.min.js',
        'lib/angular/1.1.5/angular-mocks.js',
        'lib/angular/angular-ui-sortable.js',

        /*
        For angular 1.2:
         'lib/angular/1.2/angular.js',
         'lib/angular/1.2/angular-route.min.js',
         'lib/angular/1.2/angular-touch.min.js',
         'lib/angular/1.2/angular-cookies.min.js',
         'lib/angular/1.2/angular-animate.min.js',
         'lib/angular/1.2/angular-mocks.js',*/

         'lib/underscore/underscore.js',
         'lib/umbraco/Extensions.js',
         'lib/yepnope/yepnope.min.js',

         'test/config/app.unit.js',
         'src/common/mocks/umbraco.servervariables.js',

         'src/common/directives/*.js',
         'src/common/filters/*.js',
         'src/common/services/*.js',
         'src/common/security/*.js',
         'src/common/resources/*.js',
         'src/common/mocks/**/*.js',
         'src/views/**/*.controller.js',
         'test/unit/**/*.spec.js',
        {pattern: 'lib/umbraco/namespacemanager.js', watched: true, served: true}
    ],

    // list of files to exclude
    exclude: [],

    // use dolts reporter, as travis terminal does not support escaping sequences
    // possible values: 'dots', 'progress', 'junit', 'teamcity'
    // CLI --reporters progress
    reporters: ['progress'],

    // web server port
    // CLI --port 9876
    port: 9876,

    // cli runner port
    // CLI --runner-port 9100
    runnerPort: 9100,

    // enable / disable colors in the output (reporters and logs)
    // CLI --colors --no-colors
    colors: true,

    // level of logging
    // possible values: karma.LOG_DISABLE || karma.LOG_ERROR || karma.LOG_WARN || karma.LOG_INFO || karma.LOG_DEBUG
    // CLI --log-level debug
    logLevel: karma.LOG_DEBUG,

    // enable / disable watching file and executing tests whenever any file changes
    // CLI --auto-watch --no-auto-watch
    autoWatch: false,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    // CLI --browsers Chrome,Firefox,Safari
    browsers: ['PhantomJS'],

    // If browser does not capture in given timeout [ms], kill it
    // CLI --capture-timeout 5000
    captureTimeout: 5000,

    // Auto run tests on start (when browsers are captured) and exit
    // CLI --single-run --no-single-run
    singleRun: true,

    // report which specs are slower than 500ms
    // CLI --report-slower-than 500
    reportSlowerThan: 500,

    // compile coffee scripts
    preprocessors: {
      '**/*.coffee': 'coffee'
    },

    plugins: [
      'karma-jasmine',
      'karma-chrome-launcher',
      'karma-firefox-launcher',
      'karma-phantomjs-launcher'
    ]
  });
};<commit_msg>updated testrunner config<commit_after>module.exports = function(karma) {
  karma.configure({
    // base path, that will be used to resolve files and exclude
    basePath: '../..',

    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
        'lib/jquery/jquery-2.0.3.min.js',
        'lib/angular/1.1.5/angular.js',
        'lib/angular/1.1.5/angular-cookies.min.js',
        'lib/angular/1.1.5/angular-mocks.js',
        'lib/angular/angular-ui-sortable.js',

        /*
        For angular 1.2:
         'lib/angular/1.2/angular.js',
         'lib/angular/1.2/angular-route.min.js',
         'lib/angular/1.2/angular-touch.min.js',
         'lib/angular/1.2/angular-cookies.min.js',
         'lib/angular/1.2/angular-animate.min.js',
         'lib/angular/1.2/angular-mocks.js',*/

         'lib/underscore/underscore.js',
         'lib/umbraco/Extensions.js',
         'lib/yepnope/yepnope.min.js',

         'test/config/app.unit.js',
         'src/common/mocks/umbraco.servervariables.js',

         'src/common/directives/*.js',
         'src/common/filters/*.js',
         'src/common/services/*.js',
         'src/common/security/*.js',
         'src/common/resources/*.js',
         'src/common/mocks/**/*.js',
         'src/views/**/*.controller.js',
         'test/unit/**/*.spec.js',
        {pattern: 'lib/**/*.js', watched: true, served: true, included: false}
    ],

    // list of files to exclude
    exclude: [],

    // use dolts reporter, as travis terminal does not support escaping sequences
    // possible values: 'dots', 'progress', 'junit', 'teamcity'
    // CLI --reporters progress
    reporters: ['progress'],

    // web server port
    // CLI --port 9876
    port: 9876,

    // cli runner port
    // CLI --runner-port 9100
    runnerPort: 9100,

    // enable / disable colors in the output (reporters and logs)
    // CLI --colors --no-colors
    colors: true,

    // level of logging
    // possible values: karma.LOG_DISABLE || karma.LOG_ERROR || karma.LOG_WARN || karma.LOG_INFO || karma.LOG_DEBUG
    // CLI --log-level debug
    logLevel: karma.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    // CLI --auto-watch --no-auto-watch
    autoWatch: false,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    // CLI --browsers Chrome,Firefox,Safari
    browsers: ['PhantomJS'],

    // If browser does not capture in given timeout [ms], kill it
    // CLI --capture-timeout 5000
    captureTimeout: 5000,

    // Auto run tests on start (when browsers are captured) and exit
    // CLI --single-run --no-single-run
    singleRun: true,

    // report which specs are slower than 500ms
    // CLI --report-slower-than 500
    reportSlowerThan: 500,

    // compile coffee scripts
    preprocessors: {
      '**/*.coffee': 'coffee'
    },

    plugins: [
      'karma-jasmine',
      'karma-chrome-launcher',
      'karma-firefox-launcher',
      'karma-phantomjs-launcher'
    ]
  });
};<|endoftext|>


<commit_before>var mysql       = require("mysql");

exports.Driver = Driver;

function Driver(config, connection, opts) {
	this.config = config || {};
	this.opts   = opts || {};

	if (!this.config.timezone) {
		// force UTC if not defined, UTC is always better..
		this.config.timezone = "Z";
	}
	this.db = (connection ? connection : mysql.createConnection(config.href || config));

	var escapes = {
		escape   : this.db.escape,
		escapeId : escapeId
	};

	this.QuerySelect = new (require("../sql/Select"))(escapes);
	this.QueryInsert = new (require("../sql/Insert"))(escapes);
	this.QueryUpdate = new (require("../sql/Update"))(escapes);
	this.QueryRemove = new (require("../sql/Remove"))(escapes);
}

Driver.prototype.connect = function (cb) {
	this.db.connect(cb);
};

Driver.prototype.close = function (cb) {
	this.db.end(cb);
};

Driver.prototype.find = function (fields, table, conditions, opts, cb) {
	this.QuerySelect
		.clear()
		.fields(fields)
		.table(table);
	if (opts.fields) {
		this.QuerySelect.fields(opts.fields);
	}
	if (opts.merge) {
		this.QuerySelect.merge(opts.merge.from, opts.merge.to);
	}
	if (opts.offset) {
		this.QuerySelect.offset(opts.offset);
	}
	if (typeof opts.limit == "number") {
		this.QuerySelect.limit(opts.limit);
	} else if (opts.offset) {
		// OFFSET cannot be used without LIMIT so we use the biggest BIGINT number possible
		this.QuerySelect.limit('18446744073709551615');
	}
	if (opts.order) {
		this.QuerySelect.order(opts.order[0], opts.order[1]);
	}
	for (var k in conditions) {
		this.QuerySelect.where(k, conditions[k]);
	}

	this.db.query(this.QuerySelect.build(), cb);
	if (this.opts.debug) {
		require("../Debug").sql('mysql', this.QuerySelect.build());
	}
};

Driver.prototype.insert = function (table, data, cb) {
	this.QueryInsert
		.clear()
		.table(table);
	for (var k in data) {
		this.QueryInsert.set(k, data[k]);
	}

	if (this.opts.debug) {
		require("../Debug").sql('mysql', this.QueryInsert.build());
	}
	this.db.query(this.QueryInsert.build(), function (err, info) {
		if (err) {
			return cb(err);
		}
		return cb(null, {
			id: info.insertId
		});
	});
};

Driver.prototype.update = function (table, changes, conditions, cb) {
	this.QueryUpdate
		.clear()
		.table(table);
	for (var k in conditions) {
		this.QueryUpdate.where(k, conditions[k]);
	}
	for (k in changes) {
		this.QueryUpdate.set(k, changes[k]);
	}

	if (this.opts.debug) {
		require("../Debug").sql('mysql', this.QueryUpdate.build());
	}
	this.db.query(this.QueryUpdate.build(), cb);
};

Driver.prototype.remove = function (table, conditions, cb) {
	this.QueryRemove
		.clear()
		.table(table);
	for (var k in conditions) {
		this.QueryRemove.where(k, conditions[k]);
	}

	if (this.opts.debug) {
		require("../Debug").sql('mysql', this.QueryRemove.build());
	}
	this.db.query(this.QueryRemove.build(), cb);
};

Driver.prototype.clear = function (table, cb) {
	var query = "TRUNCATE TABLE " + escapeId(table);
	if (this.opts.debug) {
		require("../Debug").sql('mysql', query);
	}
	this.db.query(query, cb);
};

Driver.prototype.valueToProperty = function (value, property) {
	switch (property.type) {
		case "boolean":
			return !!value;
		case "object":
			try {
				return JSON.parse(value);
			} catch (e) {
				return null;
			}
			break;
		default:
			return value;
	}
};

Driver.prototype.propertyToValue = function (value, property) {
	switch (property.type) {
		case "boolean":
			return (value) ? 1 : 0;
		case "object":
			return JSON.stringify(value);
		default:
			return value;
	}
};

function escapeId(id) {
	var m = id.match(/^(.+)\.\*$/);
	if (m) {
		return '`' + m[1].replace(/\`/g, '``') + '`.*';
	}
	return '`' + id.replace(/\`/g, '``').replace(/\./g, '`.`') + '`';
}
<commit_msg>Fixes mysql escape (fixes #10)<commit_after>var mysql       = require("mysql");

exports.Driver = Driver;

function Driver(config, connection, opts) {
	this.config = config || {};
	this.opts   = opts || {};

	if (!this.config.timezone) {
		// force UTC if not defined, UTC is always better..
		this.config.timezone = "Z";
	}
	this.db = (connection ? connection : mysql.createConnection(config.href || config));

	var escapes = {
		escape   : this.db.escape.bind(this.db),
		escapeId : escapeId
	};

	this.QuerySelect = new (require("../sql/Select"))(escapes);
	this.QueryInsert = new (require("../sql/Insert"))(escapes);
	this.QueryUpdate = new (require("../sql/Update"))(escapes);
	this.QueryRemove = new (require("../sql/Remove"))(escapes);
}

Driver.prototype.connect = function (cb) {
	this.db.connect(cb);
};

Driver.prototype.close = function (cb) {
	this.db.end(cb);
};

Driver.prototype.find = function (fields, table, conditions, opts, cb) {
	this.QuerySelect
		.clear()
		.fields(fields)
		.table(table);
	if (opts.fields) {
		this.QuerySelect.fields(opts.fields);
	}
	if (opts.merge) {
		this.QuerySelect.merge(opts.merge.from, opts.merge.to);
	}
	if (opts.offset) {
		this.QuerySelect.offset(opts.offset);
	}
	if (typeof opts.limit == "number") {
		this.QuerySelect.limit(opts.limit);
	} else if (opts.offset) {
		// OFFSET cannot be used without LIMIT so we use the biggest BIGINT number possible
		this.QuerySelect.limit('18446744073709551615');
	}
	if (opts.order) {
		this.QuerySelect.order(opts.order[0], opts.order[1]);
	}
	for (var k in conditions) {
		this.QuerySelect.where(k, conditions[k]);
	}

	this.db.query(this.QuerySelect.build(), cb);
	if (this.opts.debug) {
		require("../Debug").sql('mysql', this.QuerySelect.build());
	}
};

Driver.prototype.insert = function (table, data, cb) {
	this.QueryInsert
		.clear()
		.table(table);
	for (var k in data) {
		this.QueryInsert.set(k, data[k]);
	}

	if (this.opts.debug) {
		require("../Debug").sql('mysql', this.QueryInsert.build());
	}
	this.db.query(this.QueryInsert.build(), function (err, info) {
		if (err) {
			return cb(err);
		}
		return cb(null, {
			id: info.insertId
		});
	});
};

Driver.prototype.update = function (table, changes, conditions, cb) {
	this.QueryUpdate
		.clear()
		.table(table);
	for (var k in conditions) {
		this.QueryUpdate.where(k, conditions[k]);
	}
	for (k in changes) {
		this.QueryUpdate.set(k, changes[k]);
	}

	if (this.opts.debug) {
		require("../Debug").sql('mysql', this.QueryUpdate.build());
	}
	this.db.query(this.QueryUpdate.build(), cb);
};

Driver.prototype.remove = function (table, conditions, cb) {
	this.QueryRemove
		.clear()
		.table(table);
	for (var k in conditions) {
		this.QueryRemove.where(k, conditions[k]);
	}

	if (this.opts.debug) {
		require("../Debug").sql('mysql', this.QueryRemove.build());
	}
	this.db.query(this.QueryRemove.build(), cb);
};

Driver.prototype.clear = function (table, cb) {
	var query = "TRUNCATE TABLE " + escapeId(table);
	if (this.opts.debug) {
		require("../Debug").sql('mysql', query);
	}
	this.db.query(query, cb);
};

Driver.prototype.valueToProperty = function (value, property) {
	switch (property.type) {
		case "boolean":
			return !!value;
		case "object":
			try {
				return JSON.parse(value);
			} catch (e) {
				return null;
			}
			break;
		default:
			return value;
	}
};

Driver.prototype.propertyToValue = function (value, property) {
	switch (property.type) {
		case "boolean":
			return (value) ? 1 : 0;
		case "object":
			return JSON.stringify(value);
		default:
			return value;
	}
};

function escapeId(id) {
	var m = id.match(/^(.+)\.\*$/);
	if (m) {
		return '`' + m[1].replace(/\`/g, '``') + '`.*';
	}
	return '`' + id.replace(/\`/g, '``').replace(/\./g, '`.`') + '`';
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

var conflictRegExp = require('./lib/conflict'),
    resolution = require('./lib/resolution'),
    ResolutionError = require('./lib/resolution-error');

var help = require('help-version')(usage()).help,
    edit = require('string-editor'),
    byline = require('byline'),
    cloneRegExp = require('clone-regexp'),
    prompt = require('inquirer').prompt,
    chalk = require('chalk'),
    debug = require('debug')('git-conflicts');

var fs = require('fs'),
    spawn = require('child_process').spawn;

function usage() {
  return [
    'Usage:  git conflicts [file]...',
    '',
    'Run conflict resolution for each file in order.',
    'With no arguments, run conflict resolution for each unmerged path.'
  ].join('\n');
}

(function main (argv) {
  var enqueue = newQueue();

  if (argv.length) {
    argv.forEach(enqueue);
  }
  else {
    var git = spawn('git', ['ls-files', '--unmerged'], {
      stdio: ['ignore', 'pipe', process.stderr]
    });

    var resolved = Object.create(null);

    git.stdout
      .pipe(byline())
      .on('data', function (line) {
        var filename = line.toString().split(/\s+/)[3];
        if (resolved[filename]) {
          return;
        }

        resolved[filename] = true;
        enqueue(filename);
      });

    git.on('exit', function (code, signal) {
      if (code !== 0) {
        error(Error('Git terminated abruptly'));
      }
    });
  }
}(process.argv.slice(2)));

// Handle error.
function error (err) {
  if (debug.enabled) {
    throw err;
  }

  console.error(chalk.red(err.name) + ': ' + err.message);
  process.exit(1);
}

// Create new queue for conflicted filenames.
// Calls `resolveConflicts` in sequence on these files.
function newQueue () {
  var queue = [];

  var check = function () {
    if (queue.length) {
      resolveConflicts(queue[0], function (err) {
        if (err) return error(err);
        queue.shift();
        check();
      });
    }
  };

  return function (entry) {
    queue.push(entry);
    if (queue.length == 1) {
      check();
    }
  };
}

// Read the file and resolve the conflicts one by one.
function resolveConflicts (filename, cb) {
  var diff = fs.readFileSync(filename, { encoding: 'utf8' });
  var regexp = cloneRegExp(conflictRegExp, { multiline: true });

  (function resolve (diff, merged) {
    var match = diff.match(regexp);
    if (!match) return cb();

    resolveOne(match[0], function (err, result, retry) {
      if (err) return cb(err);

      if (retry) {
        return resolve(diff, merged);
      }

      merged += diff.slice(0, match.index) + result;
      diff = diff.slice(match.index + match[0].length);

      fs.writeFileSync(filename, merged + diff);
      resolve(diff, merged);
    });
  }(diff, ''));

  function resolveOne (conflict, cb) {
    var tempFileName = Date.now() + '.diff';
    edit(prepareConflictForEditing(filename, conflict), tempFileName,
         function (err, result) {
           if (err) return cb(err);

           resolution(result, function (err, result) {
             return (err instanceof ResolutionError)
               ? onResolutionError(filename, conflict, err, cb)
               : cb(err, result);
           });
         });
  }
}

// Add some comments explaining to user how to proceed with the conflict.
function prepareConflictForEditing (filename, conflict) {
  return conflict + [
    '\n\n',
    '# Conflict in `' + filename + '`.\n',
    '#\n',
    '# Resolve this conflict by changing lines between conflict markers\n',
    '# (`<<<<<<<` and `>>>>>>>`) to the final unified version.\n',
    '#\n',
    '# Empty lines and lines starting with \'#\' will be ignored, unless\n',
    '# they are between conflict markers.\n'
  ].join('');
}

// Ask the user whether we should skip the conflict or abort.
function onResolutionError (filename, conflict, err, cb) {
  prompt({
    type: 'expand',
    name: 'answer',
    message: 'Resolution on `' + filename + '` does not apply',
    choices: [
      { name: 'retry', key: 'r' },
      { name: 'skip', key: 's' },
      { name: 'quit', key: 'q' }
    ]
  }, function (a) {
    switch (a.answer) {
      case 'retry':
        return cb(null, conflict, true);

      case 'skip':
        return cb(null, conflict);

      case 'quit':
        return cb(err);

      default: throw Error('unreachable');
    }
  });
}
<commit_msg>don't emit an error on quit<commit_after>#!/usr/bin/env node
'use strict';

var conflictRegExp = require('./lib/conflict'),
    resolution = require('./lib/resolution'),
    ResolutionError = require('./lib/resolution-error');

var help = require('help-version')(usage()).help,
    edit = require('string-editor'),
    byline = require('byline'),
    cloneRegExp = require('clone-regexp'),
    prompt = require('inquirer').prompt,
    chalk = require('chalk'),
    debug = require('debug')('git-conflicts');

var fs = require('fs'),
    spawn = require('child_process').spawn;

function usage() {
  return [
    'Usage:  git conflicts [file]...',
    '',
    'Run conflict resolution for each file in order.',
    'With no arguments, run conflict resolution for each unmerged path.'
  ].join('\n');
}

(function main (argv) {
  var enqueue = newQueue();

  if (argv.length) {
    argv.forEach(enqueue);
  }
  else {
    var git = spawn('git', ['ls-files', '--unmerged'], {
      stdio: ['ignore', 'pipe', process.stderr]
    });

    var resolved = Object.create(null);

    git.stdout
      .pipe(byline())
      .on('data', function (line) {
        var filename = line.toString().split(/\s+/)[3];
        if (resolved[filename]) {
          return;
        }

        resolved[filename] = true;
        enqueue(filename);
      });

    git.on('exit', function (code, signal) {
      if (code !== 0) {
        error(Error('Git terminated abruptly'));
      }
    });
  }
}(process.argv.slice(2)));

// Handle error.
function error (err) {
  if (debug.enabled) {
    throw err;
  }

  console.error(chalk.red(err.name) + ': ' + err.message);
  process.exit(1);
}

// Create new queue for conflicted filenames.
// Calls `resolveConflicts` in sequence on these files.
function newQueue () {
  var queue = [];

  var check = function () {
    if (queue.length) {
      resolveConflicts(queue[0], function (err) {
        if (err) return error(err);
        queue.shift();
        check();
      });
    }
  };

  return function (entry) {
    queue.push(entry);
    if (queue.length == 1) {
      check();
    }
  };
}

// Read the file and resolve the conflicts one by one.
function resolveConflicts (filename, cb) {
  var diff = fs.readFileSync(filename, { encoding: 'utf8' });
  var regexp = cloneRegExp(conflictRegExp, { multiline: true });

  (function resolve (diff, merged) {
    var match = diff.match(regexp);
    if (!match) return cb();

    resolveOne(match[0], function (err, result, retry) {
      if (err) return cb(err);

      if (retry) {
        return resolve(diff, merged);
      }

      merged += diff.slice(0, match.index) + result;
      diff = diff.slice(match.index + match[0].length);

      fs.writeFileSync(filename, merged + diff);
      resolve(diff, merged);
    });
  }(diff, ''));

  function resolveOne (conflict, cb) {
    var tempFileName = Date.now() + '.diff';
    edit(prepareConflictForEditing(filename, conflict), tempFileName,
         function (err, result) {
           if (err) return cb(err);

           resolution(result, function (err, result) {
             return (err instanceof ResolutionError)
               ? onResolutionError(filename, conflict, err, cb)
               : cb(err, result);
           });
         });
  }
}

// Add some comments explaining to user how to proceed with the conflict.
function prepareConflictForEditing (filename, conflict) {
  return conflict + [
    '\n\n',
    '# Conflict in `' + filename + '`.\n',
    '#\n',
    '# Resolve this conflict by changing lines between conflict markers\n',
    '# (`<<<<<<<` and `>>>>>>>`) to the final unified version.\n',
    '#\n',
    '# Empty lines and lines starting with \'#\' will be ignored, unless\n',
    '# they are between conflict markers.\n'
  ].join('');
}

// Ask the user whether we should skip the conflict or abort.
function onResolutionError (filename, conflict, err, cb) {
  prompt({
    type: 'expand',
    name: 'answer',
    message: 'Resolution on `' + filename + '` does not apply',
    choices: [
      { name: 'retry', key: 'r' },
      { name: 'skip', key: 's' },
      { name: 'quit', key: 'q' }
    ]
  }, function (a) {
    switch (a.answer) {
      case 'retry':
        return cb(null, conflict, true);

      case 'skip':
        return cb(null, conflict);

      case 'quit':
        return process.exit();

      default: throw Error('unreachable');
    }
  });
}
<|endoftext|>


<commit_before>require('enyo');

var
	kind = require('../kind');
	scope = window || global;

var
	Control = require('../Control'),
	Image = require('../Image'),
	StylesheetSupport = require('../StylesheetSupport');

/**
* {@link enyo.SpriteAnimation} is a basic animation [component]{@link enyo.Component}.
* Call `play()` to start the animation. The animation will run for the period
* of time (in milliseconds) specified by its [duration]{@link enyo.SpriteAnimation#duration}.
*
* @class enyo.SpriteAnimation
* @extends enyo.Control
* @ui
* @public
*/
module.exports = kind(
	/** @lends enyo.SpriteAnimation.prototype */ {

	/**
	* @private
	*/
	name: 'enyo.SpriteAnimation',

	/**
	* @private
	*/
	kind: Control,

	/**
	* @private
	*/
	classes: 'enyo-sprite-animation',

	/**
	* @private
	*/
	rtl: false,

	/**
	* @private
	*/
	published:
		/** @lends enyo.SpriteAnimation.prototype */ {

		/**
		* Default value used if the animation has no
		* [duration]{@link enyo.SpriteAnimation#duration} specified.
		*
		* @type {String}
		* @default ''false''
		* @public
		*/
		src: '',

		/**
		* The number of milliseconds the animation will run.
		*
		* @type {Number}
		* @default 5000
		* @public
		*/
		duration: 5000,

		/**
		* The width of a single sprite-cell image.
		*
		* @type {Number}
		* @default 100
		* @public
		*/
		width: 100,

		/**
		* The height of a single sprite-cell image.
		*
		* @type {Number}
		* @default 100
		* @public
		*/
		height: 100,

		/**
		* The number of rows of sprite-cells.
		*
		* @type {Number}
		* @default 1
		* @public
		*/
		rows: 1,

		/**
		* The number of columns of sprite-cells.
		*
		* @type {Number}
		* @default 2
		* @public
		*/
		columns: 2,

		/**
		* Accepts any valid CSS animation-iteration-count value. Default is null, which implies
		* infinite iterations.
		*
		* @type {Number|String}
		* @default null
		* @public
		*/
		iterationCount: null,

		/**
		* Indicates whether the cells are laid out horizontally or vertically. For example:
		* ```
		* Horizontal:
		*	[1][2]
		*	[3][4]
		* Vertical:
		*	[1][3]
		*	[2][4]
		* ```
		*
		* @type {String}
		* @default 'horizontal'
		* @public
		*/
		cellOrientation: 'horizontal',

		/**
		* Applies an offset to the coordinates of the first sprite. Normally this may be left
		* at `0`, but if you have multiple sprites in a single image file, or there's padding
		* around your image, specify the offset in pixels.
		*
		* @type {Number}
		* @default 0
		* @public
		*/
		offsetTop: 0,

		/**
		* Applies an offset to the coordinates of the first sprite. Normally this may be left
		* at `0`, but if you have multiple sprites in a single image file, or there's padding
		* around your image, specify the offset in pixels.
		*
		* @type {Number}
		* @default 0
		* @public
		*/
		offsetLeft: 0,

		/**
		* Boolean property to get or set the `paused`-state of this animation. This is bindable.
		* There's also a [pause()]{@link enyo.SpriteAnimation#pause} method for convenience.
		*
		* @type {Boolean}
		* @default false
		* @public
		*/
		paused: false,

		/**
		* When an animation should run a finite number of times (set
		* [iterationCount]{@link enyo.SpriteAnimation#iterationCount}), and stop at the last
		* frame when it's finished: set this to `true` (default). Setting this to `false` will
		* reset the animation back to the starting frame when the iterations complete. This
		* property has no effect on infinitely iterating animations.
		*
		* @type {Boolean}
		* @default true
		* @public
		*/
		stopAtEnd: true,

		/**
		* A toggle for whether to use high-performance CSS animation keyframes or low
		* performance JavaScript-based timing methods. This may be useful for times when the CSS
		* animation capabilities are lacking or the device is low-powered.
		*
		* @type {Boolean}
		* @default true
		* @public
		*/
		useCssAnimation: true
	},

	/**
	* @private
	*/
	events: {
		onSpriteAnimationEnds: ''
	},

	/**
	* @private
	*/
	handlers: {
		onwebkitAnimationEnd: 'doSpriteAnimationEnds'
	},

	_frameIndex: 0,
	_loopCount: 0,

	/**
	* @private
	*/
	components: [
		{kind: Image, name: 'spriteImage', classes: 'enyo-sprite-animation-image', mixins: [StylesheetSupport], sizing: 'cover'}
	],

	/**
	* @private
	*/
	bindings: [
		{from: '.src', to: '.$.spriteImage.src'}
	],

	/**
	* @private
	*/
	computed: {
		'animationName': ['id'],
		'totalWidth': ['offsetLeft', 'width', 'columns'],
		'totalHeight': ['offsetTop', 'height', 'rows'],
		'steps': ['cellOrientation', 'columns', 'rows'],
		'frameCount': ['columns', 'rows'],
		'frameLength': ['duration', 'frameCount']
	},

	/**
	* @private
	*/
	observers: {
		setSize: ['width', 'height', 'totalWidth', 'totalHeight'],
		setOffset: ['offsetTop', 'offsetLeft'],
		_applyAnimation: ['iterationCount', 'cellOrientation', 'columns', 'rows', 'id'],
		updateKeyframes: ['cellOrientation', 'width', 'height', 'totalWidth', 'totalHeight', 'columns', 'rows', 'offsetTop', 'offsetLeft']
	},

	/**
	* @method
	* @private
	*/
	create: kind.inherit(function (sup) {
		return function() {
			sup.apply(this, arguments);

			this.applyStyle('direction', 'ltr');
			this.setOffset();
			this.setSize();
			this.pausedChanged();
			this.stopAtEndChanged();
			this.updateKeyframes();
			this._applyAnimation();
		};
	}),

	/**
	* @private
	*/
	durationChanged: function () {
		this.$.spriteImage.applyStyle('-webkit-animation-duration', (this.get('duration') / 1000) + 's');
		this.$.spriteImage.applyStyle('animation-duration', (this.get('duration') / 1000) + 's');
		this._forceAnimationReset();
	},

	/**
	* @private
	*/
	setSize: function () {
		this.applyStyle('width', this.get('width') + 'px');
		this.applyStyle('height', this.get('height') + 'px');

		this.$.spriteImage.applyStyle('width', this.get('totalWidth') + 'px');
		this.$.spriteImage.applyStyle('height', this.get('totalHeight') + 'px');
	},

	/**
	* @private
	*/
	setOffset: function () {
		this.$.spriteImage.applyStyle('background-position', (this.get('offsetLeft') * -1) + 'px ' + (this.get('offsetTop') * -1) + 'px');
	},

	/**
	* @private
	*/
	updateKeyframes: function () {
		if (this.useCssAnimation) {
			this.$.spriteImage.set('stylesheetContent', this._generateKeyframes());
		} else {
			this._generatePositionList();
		}
		this._forceAnimationReset();
	},

	/**
	* @private
	*/
	animationName: function () {
		return this.get('id') + '_keyframes';
	},

	/**
	* @private
	*/
	totalWidth: function () {
		return this.get('offsetLeft') + this.get('width') * this.get('columns');
	},

	/**
	* @private
	*/
	totalHeight: function () {
		return this.get('offsetTop') + this.get('height') * this.get('rows');
	},

	/**
	* Retrieves the amount of steps each row or column has.
	*
	* @returns {Number} The amount of rows or columns the animation will step through.
	* @private
	*/
	steps: function () {
		return (this.get('cellOrientation') == 'horizontal') ? this.get('columns') : this.get('rows');
	},

	frameCount: function () {
		return (this.rows * this.columns);
	},

	frameLength: function () {
		return Math.floor(this.get('duration') / this.get('frameCount'));
	},

	/**
	* Starts the animation.
	*
	* @public
	*/
	start: function () {
		if (this.useCssAnimation) {
			this.$.spriteImage.applyStyle('-webkit-animation-name', this.get('animationName'));
			this.$.spriteImage.applyStyle('animation-name', this.get('animationName'));
		} else {
			this._intervalHandle = scope.setInterval(this.bindSafely(this._nextFrame, this), this.get('frameLength'));
		}
		this.set('paused', false);
	},

	/**
	* Stops (and resets) the animation.
	*
	* @public
	*/
	stop: function () {
		this.$.spriteImage.applyStyle('-webkit-animation-name', null);
		this.$.spriteImage.applyStyle('animation-name', null);
		scope.clearInterval(this._intervalHandle);
		this._loopCount = 0;
	},

	/**
	* @private
	*/
	stopAtEndChanged: function() {
		this.$.spriteImage.applyStyle('-webkit-animation-fill-mode', this.get('stopAtEnd') ? 'forwards' : null);
		this.$.spriteImage.applyStyle('animation-fill-mode', this.get('stopAtEnd') ? 'forwards' : null);
	},

	/**
	* Links the pause property to the [pause]{@link enyo.SpriteAnimation#pause} method.
	*
	* @private
	*/
	pausedChanged: function() {
		this.addRemoveClass('paused', this.get('paused'));
		if (!this.get('useCssAnimation')) {
			if (this.get('paused')) {
				this.stop();
			} else {
				this.start();
			}
		}
	},

	/**
	* Pauses the animation. Starting the animation after running this will resume it from where
	* it left off (or paused at).
	*
	* @public
	*/
	pause: function () {
		this.set('paused', true);
	},

	_nextFrame: function () {
		var fi = this._frameIndex * 2,
			x = this._positionList[fi]     * -1 + this.offsetLeft,
			y = this._positionList[fi + 1] * -1 + this.offsetTop,
			iterations = parseInt(this.get('iterationCount'), 10) || null; // strings like "infinite" will be converted to null

		this.$.spriteImage.applyStyle('-webkit-transform', 'translate3d('+ x +'px, '+ y +'px, 0)');
		this.$.spriteImage.applyStyle('transform', 'translate3d('+ x +'px, '+ y +'px, 0)');

		if (fi + 1 >= this._positionList.length - 1) {
			this._frameIndex = 0;
			this._loopCount++;
			if (iterations != null && this._loopCount >= iterations) {
				this.stop();
				this.doSpriteAnimationEnds();
				if (!this.get('stopAtEnd')) {
					// go one additional frame to get us back to the start.
					this._frameIndex++;
					this._nextFrame();
				}
			}
		} else {
			this._frameIndex++;
		}
	},

	/**
	* @private
	*/
	_forceAnimationReset: function () {
		this.stop();
		this.startJob('forceAnimationReset', function() {
			this.start();
		}, 100);	// This long delay is needed to force webkit to un-set and re-set the animation.
	},

	/**
	* @private
	*/
	_applyAnimation: function () {
		var steps = this.get('steps'),
			iterations = this.get('iterationCount');

		iterations = (iterations && iterations !== 0) ? iterations : 'infinite';
		this.$.spriteImage.applyStyle('-webkit-animation-timing-function', 'steps(' + steps + ', start)');
		this.$.spriteImage.applyStyle('animation-timing-function', 'steps(' + steps + ', start)');
		this.$.spriteImage.applyStyle('-webkit-animation-iteration-count', iterations);
		this.$.spriteImage.applyStyle('animation-iteration-count', iterations);
		this.durationChanged();
	},

	/**
	* @private
	*/
	_generateKeyframes: function () {
		var o,
			width = this.get('width'),
			height = this.get('height'),
			rows = this.get('rows'),
			cols = this.get('columns'),
			horiz = this.get('cellOrientation') == 'horizontal' ? true : false,
			kfStr = '',
			outer = (horiz ? rows : cols);

		kfStr += '@-webkit-keyframes '+ this.get('animationName') +' {\n';
		for (o = 0; o < outer; o++) {
			kfStr += this._generateKeyframe(
				// percent
				((o / outer) ? ((o / outer) + 0.000001) : 0),
				// startX
				horiz ? width : (-width * o),
				// startY
				horiz ? (-height * o) : height
			);
			kfStr += this._generateKeyframe(
				// percent
				((o+1) / outer),
				// endX
				horiz ? ((-width * cols) + width) : (-width * o),
				// endY
				horiz ? (-height * o) : ((-height * rows) + height)
			);
		}
		kfStr += '}\n';
		return kfStr;
	},

	/**
	* @private
	*/
	_generateKeyframe: function (percent, x, y) {
		return (Math.ceil(percent*1000000) / 10000) +'%	{ -webkit-transform: translate3d('+ x +'px, '+ y +'px, 0);	transform: translate3d('+ x +'px, '+ y +'px, 0); }\n';
	},

	_generatePositionList: function () {
		// build and store a list of all of the necessary keyframe positions in order
		var o, i,
			width = this.get('width'),
			height = this.get('height'),
			rows = this.get('rows'),
			cols = this.get('columns'),
			horiz = this.get('cellOrientation') == 'horizontal' ? true : false,
			outer = (horiz ? rows : cols),
			inner = (horiz ? cols : rows);

		this._positionList = [];
		for (o = 0; o < outer; o++) {
			for (i = 0; i < inner; i++) {
				this._positionList.push((width * (horiz ? i : o)), (height * (horiz ? o : i)));
			}
		}
		return this._positionList;
	}
});<commit_msg>ENYO-1575: Fix enyo.SpriteAnimation 'paused' property<commit_after>require('enyo');

var
	kind = require('../kind');
	scope = window || global;

var
	Control = require('../Control'),
	Image = require('../Image'),
	StylesheetSupport = require('../StylesheetSupport');

/**
* {@link enyo.SpriteAnimation} is a basic animation [component]{@link enyo.Component}.
* Call `play()` to start the animation. The animation will run for the period
* of time (in milliseconds) specified by its [duration]{@link enyo.SpriteAnimation#duration}.
*
* @class enyo.SpriteAnimation
* @extends enyo.Control
* @ui
* @public
*/
module.exports = kind(
	/** @lends enyo.SpriteAnimation.prototype */ {

	/**
	* @private
	*/
	name: 'enyo.SpriteAnimation',

	/**
	* @private
	*/
	kind: Control,

	/**
	* @private
	*/
	classes: 'enyo-sprite-animation',

	/**
	* @private
	*/
	rtl: false,

	/**
	* @private
	*/
	published:
		/** @lends enyo.SpriteAnimation.prototype */ {

		/**
		* Default value used if the animation has no
		* [duration]{@link enyo.SpriteAnimation#duration} specified.
		*
		* @type {String}
		* @default ''false''
		* @public
		*/
		src: '',

		/**
		* The number of milliseconds the animation will run.
		*
		* @type {Number}
		* @default 5000
		* @public
		*/
		duration: 5000,

		/**
		* The width of a single sprite-cell image.
		*
		* @type {Number}
		* @default 100
		* @public
		*/
		width: 100,

		/**
		* The height of a single sprite-cell image.
		*
		* @type {Number}
		* @default 100
		* @public
		*/
		height: 100,

		/**
		* The number of rows of sprite-cells.
		*
		* @type {Number}
		* @default 1
		* @public
		*/
		rows: 1,

		/**
		* The number of columns of sprite-cells.
		*
		* @type {Number}
		* @default 2
		* @public
		*/
		columns: 2,

		/**
		* Accepts any valid CSS animation-iteration-count value. Default is null, which implies
		* infinite iterations.
		*
		* @type {Number|String}
		* @default null
		* @public
		*/
		iterationCount: null,

		/**
		* Indicates whether the cells are laid out horizontally or vertically. For example:
		* ```
		* Horizontal:
		*	[1][2]
		*	[3][4]
		* Vertical:
		*	[1][3]
		*	[2][4]
		* ```
		*
		* @type {String}
		* @default 'horizontal'
		* @public
		*/
		cellOrientation: 'horizontal',

		/**
		* Applies an offset to the coordinates of the first sprite. Normally this may be left
		* at `0`, but if you have multiple sprites in a single image file, or there's padding
		* around your image, specify the offset in pixels.
		*
		* @type {Number}
		* @default 0
		* @public
		*/
		offsetTop: 0,

		/**
		* Applies an offset to the coordinates of the first sprite. Normally this may be left
		* at `0`, but if you have multiple sprites in a single image file, or there's padding
		* around your image, specify the offset in pixels.
		*
		* @type {Number}
		* @default 0
		* @public
		*/
		offsetLeft: 0,

		/**
		* Boolean property to get or set the `paused`-state of this animation. This is bindable.
		* There's also a [pause()]{@link enyo.SpriteAnimation#pause} method for convenience.
		*
		* @type {Boolean}
		* @default false
		* @public
		*/
		paused: false,

		/**
		* When an animation should run a finite number of times (set
		* [iterationCount]{@link enyo.SpriteAnimation#iterationCount}), and stop at the last
		* frame when it's finished: set this to `true` (default). Setting this to `false` will
		* reset the animation back to the starting frame when the iterations complete. This
		* property has no effect on infinitely iterating animations.
		*
		* @type {Boolean}
		* @default true
		* @public
		*/
		stopAtEnd: true,

		/**
		* A toggle for whether to use high-performance CSS animation keyframes or low
		* performance JavaScript-based timing methods. This may be useful for times when the CSS
		* animation capabilities are lacking or the device is low-powered.
		*
		* @type {Boolean}
		* @default true
		* @public
		*/
		useCssAnimation: true
	},

	/**
	* @private
	*/
	events: {
		onSpriteAnimationEnds: ''
	},

	/**
	* @private
	*/
	handlers: {
		onwebkitAnimationEnd: 'doSpriteAnimationEnds'
	},

	_frameIndex: 0,
	_loopCount: 0,

	/**
	* @private
	*/
	components: [
		{kind: Image, name: 'spriteImage', classes: 'enyo-sprite-animation-image', mixins: [StylesheetSupport], sizing: 'cover'}
	],

	/**
	* @private
	*/
	bindings: [
		{from: '.src', to: '.$.spriteImage.src'}
	],

	/**
	* @private
	*/
	computed: {
		'animationName': ['id'],
		'totalWidth': ['offsetLeft', 'width', 'columns'],
		'totalHeight': ['offsetTop', 'height', 'rows'],
		'steps': ['cellOrientation', 'columns', 'rows'],
		'frameCount': ['columns', 'rows'],
		'frameLength': ['duration', 'frameCount']
	},

	/**
	* @private
	*/
	observers: {
		setSize: ['width', 'height', 'totalWidth', 'totalHeight'],
		setOffset: ['offsetTop', 'offsetLeft'],
		_applyAnimation: ['iterationCount', 'cellOrientation', 'columns', 'rows', 'id'],
		updateKeyframes: ['cellOrientation', 'width', 'height', 'totalWidth', 'totalHeight', 'columns', 'rows', 'offsetTop', 'offsetLeft']
	},

	/**
	* @method
	* @private
	*/
	create: kind.inherit(function (sup) {
		return function() {
			sup.apply(this, arguments);

			this.applyStyle('direction', 'ltr');
			this.setOffset();
			this.setSize();
			this.pausedChanged();
			this.stopAtEndChanged();
			this.updateKeyframes();
			this._applyAnimation();
		};
	}),

	/**
	* @private
	*/
	durationChanged: function () {
		this.$.spriteImage.applyStyle('-webkit-animation-duration', (this.get('duration') / 1000) + 's');
		this.$.spriteImage.applyStyle('animation-duration', (this.get('duration') / 1000) + 's');
		this._forceAnimationReset();
	},

	/**
	* @private
	*/
	setSize: function () {
		this.applyStyle('width', this.get('width') + 'px');
		this.applyStyle('height', this.get('height') + 'px');

		this.$.spriteImage.applyStyle('width', this.get('totalWidth') + 'px');
		this.$.spriteImage.applyStyle('height', this.get('totalHeight') + 'px');
	},

	/**
	* @private
	*/
	setOffset: function () {
		this.$.spriteImage.applyStyle('background-position', (this.get('offsetLeft') * -1) + 'px ' + (this.get('offsetTop') * -1) + 'px');
	},

	/**
	* @private
	*/
	updateKeyframes: function () {
		if (this.useCssAnimation) {
			this.$.spriteImage.set('stylesheetContent', this._generateKeyframes());
		} else {
			this._generatePositionList();
		}
		this._forceAnimationReset();
	},

	/**
	* @private
	*/
	animationName: function () {
		return this.get('id') + '_keyframes';
	},

	/**
	* @private
	*/
	totalWidth: function () {
		return this.get('offsetLeft') + this.get('width') * this.get('columns');
	},

	/**
	* @private
	*/
	totalHeight: function () {
		return this.get('offsetTop') + this.get('height') * this.get('rows');
	},

	/**
	* Retrieves the amount of steps each row or column has.
	*
	* @returns {Number} The amount of rows or columns the animation will step through.
	* @private
	*/
	steps: function () {
		return (this.get('cellOrientation') == 'horizontal') ? this.get('columns') : this.get('rows');
	},

	frameCount: function () {
		return (this.rows * this.columns);
	},

	frameLength: function () {
		return Math.floor(this.get('duration') / this.get('frameCount'));
	},

	/**
	* Starts the animation.
	*
	* @public
	*/
	start: function () {
		if (this.useCssAnimation) {
			this.$.spriteImage.applyStyle('-webkit-animation-name', this.get('animationName'));
			this.$.spriteImage.applyStyle('animation-name', this.get('animationName'));
		} else {
			this._intervalHandle = scope.setInterval(this.bindSafely(this._nextFrame, this), this.get('frameLength'));
		}
		this.set('paused', false);
	},

	/**
	* Stops (and resets) the animation.
	*
	* @public
	*/
	stop: function () {
		this.$.spriteImage.applyStyle('-webkit-animation-name', null);
		this.$.spriteImage.applyStyle('animation-name', null);
		scope.clearInterval(this._intervalHandle);
		this._loopCount = 0;
	},

	/**
	* @private
	*/
	stopAtEndChanged: function() {
		this.$.spriteImage.applyStyle('-webkit-animation-fill-mode', this.get('stopAtEnd') ? 'forwards' : null);
		this.$.spriteImage.applyStyle('animation-fill-mode', this.get('stopAtEnd') ? 'forwards' : null);
	},

	/**
	* Links the pause property to the [pause]{@link enyo.SpriteAnimation#pause} method.
	*
	* @private
	*/
	pausedChanged: function() {
		this.addRemoveClass('paused', this.get('paused'));
		if (!this.get('useCssAnimation')) {
			if (this.get('paused')) {
				this.stop();
			} else {
				this.start();
			}
		}
	},

	/**
	* Pauses the animation. Starting the animation after running this will resume it from where
	* it left off (or paused at).
	*
	* @public
	*/
	pause: function () {
		this.set('paused', true);
	},

	_nextFrame: function () {
		var fi = this._frameIndex * 2,
			x = this._positionList[fi]     * -1 + this.offsetLeft,
			y = this._positionList[fi + 1] * -1 + this.offsetTop,
			iterations = parseInt(this.get('iterationCount'), 10) || null; // strings like "infinite" will be converted to null

		this.$.spriteImage.applyStyle('-webkit-transform', 'translate3d('+ x +'px, '+ y +'px, 0)');
		this.$.spriteImage.applyStyle('transform', 'translate3d('+ x +'px, '+ y +'px, 0)');

		if (fi + 1 >= this._positionList.length - 1) {
			this._frameIndex = 0;
			this._loopCount++;
			if (iterations != null && this._loopCount >= iterations) {
				this.stop();
				this.doSpriteAnimationEnds();
				if (!this.get('stopAtEnd')) {
					// go one additional frame to get us back to the start.
					this._frameIndex++;
					this._nextFrame();
				}
			}
		} else {
			this._frameIndex++;
		}
	},

	/**
	* @private
	*/
	_forceAnimationReset: function () {
		this.stop();
		if (this.get('paused')) return;
		this.startJob('forceAnimationReset', function() {
			this.start();
		}, 100);	// This long delay is needed to force webkit to un-set and re-set the animation.
	},

	/**
	* @private
	*/
	_applyAnimation: function () {
		var steps = this.get('steps'),
			iterations = this.get('iterationCount');

		iterations = (iterations && iterations !== 0) ? iterations : 'infinite';
		this.$.spriteImage.applyStyle('-webkit-animation-timing-function', 'steps(' + steps + ', start)');
		this.$.spriteImage.applyStyle('animation-timing-function', 'steps(' + steps + ', start)');
		this.$.spriteImage.applyStyle('-webkit-animation-iteration-count', iterations);
		this.$.spriteImage.applyStyle('animation-iteration-count', iterations);
		this.durationChanged();
	},

	/**
	* @private
	*/
	_generateKeyframes: function () {
		var o,
			width = this.get('width'),
			height = this.get('height'),
			rows = this.get('rows'),
			cols = this.get('columns'),
			horiz = this.get('cellOrientation') == 'horizontal' ? true : false,
			kfStr = '',
			outer = (horiz ? rows : cols);

		kfStr += '@-webkit-keyframes '+ this.get('animationName') +' {\n';
		for (o = 0; o < outer; o++) {
			kfStr += this._generateKeyframe(
				// percent
				((o / outer) ? ((o / outer) + 0.000001) : 0),
				// startX
				horiz ? width : (-width * o),
				// startY
				horiz ? (-height * o) : height
			);
			kfStr += this._generateKeyframe(
				// percent
				((o+1) / outer),
				// endX
				horiz ? ((-width * cols) + width) : (-width * o),
				// endY
				horiz ? (-height * o) : ((-height * rows) + height)
			);
		}
		kfStr += '}\n';
		return kfStr;
	},

	/**
	* @private
	*/
	_generateKeyframe: function (percent, x, y) {
		return (Math.ceil(percent*1000000) / 10000) +'%	{ -webkit-transform: translate3d('+ x +'px, '+ y +'px, 0);	transform: translate3d('+ x +'px, '+ y +'px, 0); }\n';
	},

	_generatePositionList: function () {
		// build and store a list of all of the necessary keyframe positions in order
		var o, i,
			width = this.get('width'),
			height = this.get('height'),
			rows = this.get('rows'),
			cols = this.get('columns'),
			horiz = this.get('cellOrientation') == 'horizontal' ? true : false,
			outer = (horiz ? rows : cols),
			inner = (horiz ? cols : rows);

		this._positionList = [];
		for (o = 0; o < outer; o++) {
			for (i = 0; i < inner; i++) {
				this._positionList.push((width * (horiz ? i : o)), (height * (horiz ? o : i)));
			}
		}
		return this._positionList;
	}
});<|endoftext|>


<commit_before>//initialize all the things
function init() {

    //game pieces
    leftPaddle = new component(20, 100, "white", 60, 120);
    rightPaddle = new component(20, 100, "white", 1200, 120);
    ball = new component(10, 10, "white", 300, 300);
    player1Score = new scoreNumbers(30, 30, "green", 10, 120);
    player2Score = new scoreNumbers(30, 30, "green", 10, 120);

    //start the game
    game.start();
}

//main game object
var game = {
    canvas : document.getElementById("pong"),
    start : function() {
        this.canvas.width = 1280;
        this.canvas.height = 720;
        this.canvas.style.cursor = "none"; //hide cursor
        this.context = this.canvas.getContext("2d");
        //glorious 60fps (16ms)
        this.interval = setInterval(update, 16);
        //background
        this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);

        //Keyboard
        window.addEventListener('keydown', function (e) {
            e.preventDefault();
            game.keys = (game.keys || []);
            game.keys[e.keyCode] = (e.type == "keydown");
        });
        window.addEventListener('keyup', function (e) {
            game.keys[e.keyCode] = (e.type == "keydown");
        });
        //mouse
        window.addEventListener('mousemove', function (e) {
            game.x = e.pageX;
            game.y = e.pageY;
        });
    },
    stop : function() {
        clearInterval(this.interval);
    },
    clear : function() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}

function scoreNumbers(score,x,y){

}

function net(){
    context = game.context;
    //broken centre line
    context.beginPath();
    context.strokeStyle = 'white';
    context.lineWidth = 5;
    context.setLineDash([20, 20]);
    context.moveTo(640, 10);
    context.lineTo(640, 720);
    context.stroke();
}
//game object
function component(width, height, color, x, y) {
    //object attributes
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    this.x = x;
    this.y = y;

    //functions called by update loop
    this.update = function() {
        context = game.context;
        context.fillStyle = color;
        context.fillRect(this.x, this.y, this.width, this.height);
    }
    this.newPos = function() {
        this.y += this.speedY;
        this.x += this.speedX;
    }

    //check for collison with another object
    this.crashWith = function(otherobj) {

        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);

        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);

        //should maybe re-write this to assume false, rather than assume true and prove wrong - may reduce any possible false positives
        var crash = true;

        if ((mybottom < othertop) ||
               (mytop > otherbottom) ||
               (myright < otherleft) ||
               (myleft > otherright)) {
           crash = false;
        }
        return crash;
    }
}

//update loop
function update(){
    //if collision, stop the game, else, update all the things
    if (rightPaddle.crashWith(ball)) {
        game.stop();
    } else {
        game.clear();

        rightPaddle.speedY = 0;
        leftPaddle.speedY = 0;
        ball.speedX = 5;
        ball.speedY = 5;

        //keyboard movement
        if (game.keys && game.keys[38]) {rightPaddle.speedY = -10; }
        if (game.keys && game.keys[40]) {rightPaddle.speedY = 10; }

        //mouse movement, y axis only
        if (game.y) {
            //DISABLED FOR NOW, testing is easier with the keyboard
            //rightPaddle.y = game.y;
        }
        net();

        ball.newPos();
        ball.update();

        leftPaddle.newPos();
        leftPaddle.update();

        rightPaddle.newPos();
        rightPaddle.update();
    }

}
<commit_msg>adjust net to be centre<commit_after>//initialize all the things
function init() {

    //game pieces
    leftPaddle = new component(20, 100, "white", 60, 120);
    rightPaddle = new component(20, 100, "white", 1200, 120);
    ball = new component(10, 10, "white", 300, 300);
    player1Score = new scoreNumbers(30, 30, "green", 10, 120);
    player2Score = new scoreNumbers(30, 30, "green", 10, 120);

    //start the game
    game.start();
}

//main game object
var game = {
    canvas : document.getElementById("pong"),
    start : function() {
        this.canvas.width = 1280;
        this.canvas.height = 720;
        //this.canvas.style.cursor = "none"; //hide cursor
        this.context = this.canvas.getContext("2d");
        //glorious 60fps (16ms)
        this.interval = setInterval(update, 16);
        //background
        this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);

        //Keyboard
        window.addEventListener('keydown', function (e) {
            e.preventDefault();
            game.keys = (game.keys || []);
            game.keys[e.keyCode] = (e.type == "keydown");
        });
        window.addEventListener('keyup', function (e) {
            game.keys[e.keyCode] = (e.type == "keydown");
        });
        //mouse
        window.addEventListener('mousemove', function (e) {
            game.x = e.pageX;
            game.y = e.pageY;
        });
    },
    stop : function() {
        clearInterval(this.interval);
    },
    clear : function() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
}

function scoreNumbers(score,x,y){

}

function net(){
    context = game.context;
    //broken centre line
    context.beginPath();
    context.strokeStyle = 'white';
    context.lineWidth = 6;
    context.setLineDash([20, 20]);
    context.moveTo(637, 10);
    context.lineTo(637, 720);
    context.stroke();
}
//game object
function component(width, height, color, x, y) {
    //object attributes
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    this.x = x;
    this.y = y;

    //functions called by update loop
    this.update = function() {
        context = game.context;
        context.fillStyle = color;
        context.fillRect(this.x, this.y, this.width, this.height);
    }
    this.newPos = function() {
        this.y += this.speedY;
        this.x += this.speedX;
    }

    //check for collison with another object
    this.crashWith = function(otherobj) {

        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);

        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);

        //should maybe re-write this to assume false, rather than assume true and prove wrong - may reduce any possible false positives
        var crash = true;

        if ((mybottom < othertop) ||
               (mytop > otherbottom) ||
               (myright < otherleft) ||
               (myleft > otherright)) {
           crash = false;
        }
        return crash;
    }
}

//update loop
function update(){
    //if collision, stop the game, else, update all the things
    if (rightPaddle.crashWith(ball)) {
        game.stop();
    } else {
        game.clear();

        rightPaddle.speedY = 0;
        leftPaddle.speedY = 0;
        ball.speedX = 5;
        ball.speedY = 5;

        //keyboard movement
        if (game.keys && game.keys[38]) {rightPaddle.speedY = -10; }
        if (game.keys && game.keys[40]) {rightPaddle.speedY = 10; }

        //mouse movement, y axis only
        if (game.y) {
            //DISABLED FOR NOW, testing is easier with the keyboard
            //rightPaddle.y = game.y;
        }
        net();

        ball.newPos();
        ball.update();

        leftPaddle.newPos();
        leftPaddle.update();

        rightPaddle.newPos();
        rightPaddle.update();
    }

}
<|endoftext|>


<commit_before>import {Observable as O} from 'rx';
import Cycle from '@cycle/core';
import {makeDOMDriver} from '@cycle/dom';
import {div, svg} from '@cycle/dom';

import {preventDefaultDriver} from '../../drivers/prevent-default';
import {keyboardDriver} from '../../drivers/keyboard';
import {globalEventDriver} from '../../drivers/global-events';

const numberCircleApp = (sources) => {
  return {
    DOM:
    // number of bits to generate the number circle for
    O.just(3)
    // convert number of bit's into array of angles
    .map((bits) =>
      Array
        // init array of length 2^bits.
        .apply(Array, {length: Math.pow(2, bits)})
        // map array to angles
        .map((_, index, all) => 2 * Math.PI * index / all.length)
    )
    // convert array of angles into svg
    .map((angles) =>
      div([
        svg('svg', {
          attributes: {
            width: 200,
            height: 200,
            class: 'graphics-root',
            viewBox: `0 0 500 500`,
            preserveAspectRatio: 'xMidYMid meet',
          },
        }, angles.map((angle) =>
          svg('circle', {
            cx: 250 + Math.sin(angle) * 200,
            cy: 250 + Math.cos(angle) * 200,
            r: 50,
          }))
        ),
      ])
    ),
  };
};

const drivers = {
  DOM: makeDOMDriver('#app'),
  preventDefault: preventDefaultDriver,
  keydown: keyboardDriver,
  globalEvents: globalEventDriver,
};

Cycle.run(numberCircleApp, drivers);
<commit_msg>decompose into render function<commit_after>import {Observable as O} from 'rx';
import Cycle from '@cycle/core';
import {makeDOMDriver} from '@cycle/dom';
import {div, svg} from '@cycle/dom';

import {preventDefaultDriver} from '../../drivers/prevent-default';
import {keyboardDriver} from '../../drivers/keyboard';
import {globalEventDriver} from '../../drivers/global-events';

// convert array of angles into svg
const render = (angles) =>
  div([
    svg('svg', {
      attributes: {
        width: 200,
        height: 200,
        class: 'graphics-root',
        viewBox: `0 0 500 500`,
        preserveAspectRatio: 'xMidYMid meet',
      },
    }, angles.map((angle) =>
      svg('circle', {
        cx: 250 + Math.sin(angle) * 200,
        cy: 250 + Math.cos(angle) * 200,
        r: 50,
      }))
    ),
  ])
;

const numberCircleApp = (sources) => {
  const state$ = // number of bits to generate the number circle for
    O.just(3)
    // convert number of bit's into array of angles
    .map((bits) =>
      Array
        // init array of length 2^bits.
        .apply(Array, {length: Math.pow(2, bits)})
        // map array to angles
        .map((_, index, all) => 2 * Math.PI * index / all.length)
    );

  return {
    DOM: state$.map(render),
  };
};

const drivers = {
  DOM: makeDOMDriver('#app'),
  preventDefault: preventDefaultDriver,
  keydown: keyboardDriver,
  globalEvents: globalEventDriver,
};

Cycle.run(numberCircleApp, drivers);
<|endoftext|>


<commit_before>/*
    Rob Holme

    Extract the value of a nominated field from all open HL7 files
*/

// load modules
const vscode = require('vscode');
const common = require('./common.js');
const resultClass = require('./ExtractFieldResult.js');

//----------------------------------------------------
// extract the index of a field location from the hl7 item location string
// @param {string} itemLocation - A string value identifying the field location to extract (e.g. PID-3)
function ExtractAllFields(itemLocation) {
	var results = new resultClass.resultCollection();
	var fieldIndex;
	var segmentName = "";

	// return if no location provided by the user;
	if (!itemLocation) {
		return;
	}

	// test to see if the user has provided a valid location string
	if (!common.IsItemLocationValid(itemLocation))
	{
		vscode.window.showInformationMessage(itemLocation + " is not a recognised HL7 field location");
		console.log(itemLocation + " is not a recognised HL7 field location");
		return;
	}

	// identify the segment name and field index from the location string
	segmentName = common.GetSegmentNameFromLocationString(itemLocation).toUpperCase();
	fieldIndex = parseInt(common.GetFieldIndex(itemLocation), 10);
	// the first field of MSH segments is the field delimiter, adjust index accordingly for MSH fields
	if (segmentName == "MSH") {
		fieldIndex--;
	}

	// extract the field(s) from the current document
	results = common.GetFields(segmentName, fieldIndex);

	// display the results to on output window
	var allResults = results.Results;
	if (allResults.length > 0) {
		var channel = vscode.window.createOutputChannel('HL7 Fields from all messages');
		channel.clear();
		channel.appendLine(common.padRight("Value", results.MaxLength, ' ') + "  Filename");
		channel.appendLine(common.padRight("-----", results.MaxLength, ' ') + "  --------");
		for (i = 0; i < allResults.length; i++) {
			channel.appendLine(common.padRight(allResults[i].Value, results.MaxLength, ' ') + "  " + allResults[i].Filename)
		}
		channel.show(vscode.ViewColumn.Two);
	}
}

exports.ExtractAllFields = ExtractAllFields;<commit_msg>Added return codes<commit_after>/*
    Rob Holme

    Extract the value of a nominated field from all open HL7 files
*/

// load modules
const vscode = require('vscode');
const common = require('./common.js');
const resultClass = require('./ExtractFieldResult.js');

// return codes for ExtractAllFields()
const ExtractReturnCode = {
	ERROR_NO_LOCATION_PROVIDED: 0,
	ERROR_LOCATION_NOT_VALID: 1,
	SUCCESS: 2
};

//----------------------------------------------------
// extract the index of a field location from the hl7 item location string
// @param {string} itemLocation - A string value identifying the field location to extract (e.g. PID-3)
function ExtractAllFields(itemLocation) {
	var results = new resultClass.resultCollection();
	var fieldIndex;
	var segmentName = "";

	// return if no location provided by the user;
	if (!itemLocation) {
		return ExtractReturnCode.ERROR_NO_LOCATION_PROVIDED;
	}

	// test to see if the user has provided a valid location string
	if (!common.IsItemLocationValid(itemLocation))
	{
		vscode.window.showInformationMessage(itemLocation + " is not a recognised HL7 field location");
		console.log(itemLocation + " is not a recognised HL7 field location");
		return ExtractReturnCode.ERROR_LOCATION_NOT_VALID;
	}

	// identify the segment name and field index from the location string
	segmentName = common.GetSegmentNameFromLocationString(itemLocation).toUpperCase();
	fieldIndex = parseInt(common.GetFieldIndex(itemLocation), 10);
	// the first field of MSH segments is the field delimiter, adjust index accordingly for MSH fields
	if (segmentName == "MSH") {
		fieldIndex--;
	}

	// extract the field(s) from the current document
	results = common.GetFields(segmentName, fieldIndex);

	// display the results to on output window
	var allResults = results.Results;
	if (allResults.length > 0) {
		var channel = vscode.window.createOutputChannel('HL7 Fields from all messages');
		channel.clear();
		channel.appendLine(common.padRight("Value", results.MaxLength, ' ') + "  Filename");
		channel.appendLine(common.padRight("-----", results.MaxLength, ' ') + "  --------");
		for (i = 0; i < allResults.length; i++) {
			channel.appendLine(common.padRight(allResults[i].Value, results.MaxLength, ' ') + "  " + allResults[i].Filename)
		}
		channel.show(vscode.ViewColumn.Two);
	}
	return ExtractReturnCode.SUCCESS;
}

exports.ExtractAllFields = ExtractAllFields;
exports.ExtractReturnCode = ExtractReturnCode;<|endoftext|>


<commit_before>#!/usr/bin/env node

"use strict";

const yargs = require("yargs");
const ipt = require("ipt");
const out = require("simple-output");
const pkgInfo = require("pkginfo");

let tasks;
let descriptions;
const sep = require("os").EOL;
const { execSync } = require("child_process");
const { argv } = yargs
	.usage("Usage:\n  ntl [<path>]")
	.alias("a", "all")
	.describe("a", "Includes pre and post scripts on the list")
	.alias("A", "autocomplete")
	.describe("A", "Starts in autocomplete mode")
	.alias("D", "debug")
	.describe("D", "Prints to stderr any internal error")
	.alias("d", "descriptions")
	.describe("d", "Displays the descriptions of each script")
	.alias("o", "descriptions-only")
	.describe("o", "Limits output to scripts with a description")
	.help("h")
	.alias("h", "help")
	.describe("h", "Shows this help message")
	.alias("i", "info")
	.describe("i", "Displays the contents of each script")
	.alias("m", "multiple")
	.describe("m", "Allows the selection of multiple items")
	.alias("s", "size")
	.describe("s", "Amount of lines to display at once")
	.alias("v", "version")
	.boolean(["a", "A", "D", "d", "o", "h", "i", "m", "v"])
	.number(["s"])
	.epilog("Visit https://github.com/ruyadorno/ntl for more info");

const pkg = require("./package");
const cwd = argv._[0] || process.cwd();
const { autocomplete, multiple, size } = argv;

function error(e, msg) {
	out.error(argv.debug ? e : msg);
	process.exit(1);
}

// Exits program execution on ESC
process.stdin.on("keypress", (ch, key) => {
	if (key && key.name === "escape") {
		process.exit(0);
	}
});

// get package.json scripts value
try {
	tasks = { exports: {} };
	pkgInfo(tasks, { dir: cwd, include: ["scripts"] });
	tasks = tasks.exports.scripts;
} catch (e) {
	error(e, "No package.json found");
}

// validates that there are actually npm scripts
if (!tasks || Object.keys(tasks).length < 1) {
	out.info("No npm scripts available in cwd");
	process.exit(0);
}

// get package.json descriptions value
if (argv.descriptions) {
	try {
		descriptions = { exports: {} };
		pkgInfo(descriptions, { dir: cwd, include: ["ntl"] });
		descriptions = descriptions.exports.ntl.descriptions;
	} catch (e) {
		console.warn("No descriptions for your npm scripts found");
	}
}

const longestScriptName = (scripts) => Object.keys(scripts).reduce((acc, curr) => curr.length > acc.length ? curr : acc).length;

// defines the items that will be printed to the user
const input = (argv.info || argv.descriptions
	? Object.keys(tasks).map(i => ({ name: `${i.padStart(longestScriptName(argv.descriptionsOnly ? descriptions : tasks))} › ${argv.descriptions && descriptions[i] ? descriptions[i] : tasks[i]}`, value: i }))
	: Object.keys(tasks)
).filter(
	// filter out prefixed tasks
	i =>
		argv.all
			? true
			: ["pre", "post"].every(prefix => argv.info || argv.descriptions
					? i.name.slice(0, prefix.length) !== prefix
					: i.slice(0, prefix.length) !== prefix
			)
).filter(
	// filter out tasks without a description
	i =>
		argv.descriptions && argv.descriptionsOnly
			? descriptions[i.value] !== undefined
			: true
);

out.success("Npm Task List - v" + pkg.version);

// creates interactive interface using ipt
ipt(input, {
	message: "Select a task to run:",
	autocomplete,
	multiple,
	size
})
	.then(keys => {
		keys.forEach(key => {
			execSync(`npm run ${key}`, {
				cwd,
				stdio: [process.stdin, process.stdout, process.stderr]
			});
		});
	})
	.catch(err => {
		error(err, "Error building interactive interface");
	});
<commit_msg>Do not break on empty package.json "ntl"<commit_after>#!/usr/bin/env node

"use strict";

const yargs = require("yargs");
const ipt = require("ipt");
const out = require("simple-output");
const pkgInfo = require("pkginfo");

let tasks;
let descriptions;
const sep = require("os").EOL;
const { execSync } = require("child_process");
const { argv } = yargs
	.usage("Usage:\n  ntl [<path>]")
	.alias("a", "all")
	.describe("a", "Includes pre and post scripts on the list")
	.alias("A", "autocomplete")
	.describe("A", "Starts in autocomplete mode")
	.alias("D", "debug")
	.describe("D", "Prints to stderr any internal error")
	.alias("d", "descriptions")
	.describe("d", "Displays the descriptions of each script")
	.alias("o", "descriptions-only")
	.describe("o", "Limits output to scripts with a description")
	.help("h")
	.alias("h", "help")
	.describe("h", "Shows this help message")
	.alias("i", "info")
	.describe("i", "Displays the contents of each script")
	.alias("m", "multiple")
	.describe("m", "Allows the selection of multiple items")
	.alias("s", "size")
	.describe("s", "Amount of lines to display at once")
	.alias("v", "version")
	.boolean(["a", "A", "D", "d", "o", "h", "i", "m", "v"])
	.number(["s"])
	.epilog("Visit https://github.com/ruyadorno/ntl for more info");

const pkg = require("./package");
const cwd = argv._[0] || process.cwd();
const { autocomplete, multiple, size } = argv;

function error(e, msg) {
	out.error(argv.debug ? e : msg);
	process.exit(1);
}

// Exits program execution on ESC
process.stdin.on("keypress", (ch, key) => {
	if (key && key.name === "escape") {
		process.exit(0);
	}
});

// get package.json scripts value
try {
	tasks = { exports: {} };
	pkgInfo(tasks, { dir: cwd, include: ["scripts"] });
	tasks = tasks.exports.scripts;
} catch (e) {
	error(e, "No package.json found");
}

// validates that there are actually npm scripts
if (!tasks || Object.keys(tasks).length < 1) {
	out.info("No npm scripts available in cwd");
	process.exit(0);
}

// get package.json descriptions value
if (argv.descriptions) {
	try {
		descriptions = { exports: {} };
		pkgInfo(descriptions, { dir: cwd, include: ["ntl"] });
		descriptions = descriptions.exports.ntl.descriptions || {};
	} catch (e) {
		console.warn("No descriptions for your npm scripts found");
	}
}

const longestScriptName = (scripts) => Object.keys(scripts).reduce((acc, curr) => curr.length > acc.length ? curr : acc).length;

// defines the items that will be printed to the user
const input = (argv.info || argv.descriptions
	? Object.keys(tasks).map(i => ({ name: `${i.padStart(longestScriptName(argv.descriptionsOnly ? descriptions : tasks))} › ${argv.descriptions && descriptions[i] ? descriptions[i] : tasks[i]}`, value: i }))
	: Object.keys(tasks)
).filter(
	// filter out prefixed tasks
	i =>
		argv.all
			? true
			: ["pre", "post"].every(prefix => argv.info || argv.descriptions
					? i.name.slice(0, prefix.length) !== prefix
					: i.slice(0, prefix.length) !== prefix
			)
).filter(
	// filter out tasks without a description
	i =>
		argv.descriptions && argv.descriptionsOnly
			? descriptions[i.value] !== undefined
			: true
);

out.success("Npm Task List - v" + pkg.version);

// creates interactive interface using ipt
ipt(input, {
	message: "Select a task to run:",
	autocomplete,
	multiple,
	size
})
	.then(keys => {
		keys.forEach(key => {
			execSync(`npm run ${key}`, {
				cwd,
				stdio: [process.stdin, process.stdout, process.stderr]
			});
		});
	})
	.catch(err => {
		error(err, "Error building interactive interface");
	});
<|endoftext|>


<commit_before><commit_msg>adds record of set DnsMode and Encodings to NetSimVisualization, so that it can pass the appropriate values on to new VizElements<commit_after><|endoftext|>


<commit_before>(function () {
    'use strict';

    angular
        .module('jass.config')
        .config(config);

    config.$inject = ['$locationProvider'];

    /**
     * @name config
     * @desc Enable HTML5 routing
     * See https://thinkster.io/django-angularjs-tutorial/
     */
    function config($locationProvider) {
        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('!');
    }
})();
<commit_msg>Removed comments<commit_after>(function () {
    'use strict';

    angular
        .module('jass.config')
        .config(config);

    config.$inject = ['$locationProvider'];

    function config($locationProvider) {
        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('!');
    }
})();
<|endoftext|>


<commit_before>import Ember from 'ember';
import TravisRoute from 'travis/routes/basic';
import config from 'travis/config/environment';

export default TravisRoute.extend({
  needsAuth: false,

  titleToken(model) {
    var name = model.name || model.login;
    return name;
  },

  model(params, transition) {
    var options;
    options = {};

    if (this.get('auth.signedIn')) {
      options.headers = {
        Authorization: "token " + (this.auth.token())
      };
    }

    let includes = `?include=owner.repositories,repository.default_branch,build.commit,repository.current_build`;
    let { owner } = transition.params.owner;
    let url = `${config.apiEndpoint}/v3/owner/${owner}${includes}`;
    return Ember.$.get(url, options);
  }
});
<commit_msg>Use $.ajax instead of $.get<commit_after>import Ember from 'ember';
import TravisRoute from 'travis/routes/basic';
import config from 'travis/config/environment';

export default TravisRoute.extend({
  needsAuth: false,

  titleToken(model) {
    var name = model.name || model.login;
    return name;
  },

  model(params, transition) {
    var options;
    options = {};

    if (this.get('auth.signedIn')) {
      options.headers = {
        Authorization: "token " + (this.auth.token())
      };
    }

    let includes = `?include=owner.repositories,repository.default_branch,build.commit,repository.current_build`;
    let { owner } = transition.params.owner;
    let url = `${config.apiEndpoint}/v3/owner/${owner}${includes}`;
    return Ember.$.ajax(url, options);
  }
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';
var meow = require('meow');
var speedtest = require('speedtest-net');
var updateNotifier = require('update-notifier');
var roundTo = require('round-to');
var chalk = require('chalk');
var logUpdate = require('log-update');
var elegantSpinner = require('elegant-spinner');

var cli = meow({
	help: [
		'Usage',
		'  $ speed-test'
	]
});

updateNotifier({pkg: cli.pkg}).notify();

var stats = {
	ping: '',
	download: '',
	upload: ''
};

var state = 'ping';
var frame = elegantSpinner();

function getSpinner(x) {
	return state === x ? chalk.cyan.dim(frame()) : '';
}

function render() {
	logUpdate([
		'',
		'      Ping  ' + stats.ping + getSpinner('ping'),
		'  Download  ' + stats.download + getSpinner('download'),
		'    Upload  ' + stats.upload + getSpinner('upload')
	].join('\n'));
}

var st = speedtest({maxTime: 20000});

setInterval(render, 50);

st.once('testserver', function (server) {
	state = 'download';
	stats.ping = chalk.cyan(Math.round(server.bestPing) + chalk.dim(' ms'));
});

st.once('downloadspeed', function (speed) {
	state = 'upload';
	stats.download = chalk.cyan(roundTo(speed, 1) + chalk.dim(' Mbps'));
});

st.once('uploadspeed', function (speed) {
	state = '';
	stats.upload = chalk.cyan(roundTo(speed, 1) + chalk.dim(' Mbps'));
	render();
	process.exit();
});

st.on('error', function (err) {
	console.error(err);
	process.exit(1);
});
<commit_msg>Make output 'bold' to aid legibility<commit_after>#!/usr/bin/env node
'use strict';
var meow = require('meow');
var speedtest = require('speedtest-net');
var updateNotifier = require('update-notifier');
var roundTo = require('round-to');
var chalk = require('chalk');
var logUpdate = require('log-update');
var elegantSpinner = require('elegant-spinner');

var cli = meow({
	help: [
		'Usage',
		'  $ speed-test'
	]
});

updateNotifier({pkg: cli.pkg}).notify();

var stats = {
	ping: '',
	download: '',
	upload: ''
};

var state = 'ping';
var frame = elegantSpinner();

function getSpinner(x) {
	return state === x ? chalk.cyan.dim(frame()) : '';
}

function render() {
	logUpdate([
		'',
		'      Ping  ' + stats.ping + getSpinner('ping'),
		'  Download  ' + stats.download + getSpinner('download'),
		'    Upload  ' + stats.upload + getSpinner('upload')
	].join('\n'));
}

var st = speedtest({maxTime: 20000});

setInterval(render, 50);

st.once('testserver', function (server) {
	state = 'download';
	stats.ping = chalk.cyan(Math.round(server.bestPing) + chalk.dim(' ms'));
	stats.ping = chalk.bold(stats.ping);
});

st.once('downloadspeed', function (speed) {
	state = 'upload';
	stats.download = chalk.cyan(roundTo(speed, 1) + chalk.dim(' Mbps'));
	stats.download = chalk.bold(stats.download);
});

st.once('uploadspeed', function (speed) {
	state = '';
	stats.upload = chalk.cyan(roundTo(speed, 1) + chalk.dim(' Mbps'));
	stats.upload = chalk.bold(stats.upload);
	render();
	process.exit();
});

st.on('error', function (err) {
	console.error(err);
	process.exit(1);
});
<|endoftext|>