<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

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",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (ne<commit_msg>Reverting changes<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

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",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new<|endoftext|>


<commit_before>(function(){

  'use strict';

  angular
    .module('resourceGenerator', ['ngResource'])
    .provider('ResourceGenerator', ResourceGenerator);

    /**
     * ResourceGenerator provider
     */
    function ResourceGenerator() {

      var _this = this;
      _this.$get = $get;
      _this.defaults = {
        'baseUrl' : null,
        'extensions': null,
        'statics': null,
        'params': {},
        'methods': {
          'getWithChildren' : getWithChildren
        }
      };

      $get.$inject = ['$resource', '$q', '$injector'];

      function $get($resource, $q, $injector){

        /**
         * ResourceGenerator Factory: Creates a resource definition with a few add-on methods to expand on $resource functionality.
         * @param {string} endpoint - the URL for this endpoint
         * @param {Object=} params - $resource like params for this endpoint
         * @param {Object=} subendpoints - an array of objects - each object containing:
         *                        {'name': (string), name for this subendpoint,
         *                        'endpoint': (string) url for this endpoint,
         *                        'params': standard $resource params,
         *                        'link':  {query_param_name: variable_on_parent}
         * @returns {*}
         */
        return function(endpoint, params, subendpoints) {

          var ready = $q.defer();
          var api = _this.defaults.baseUrl || '';

          function resolveParameters () {

            var funcParams = [].slice.call(arguments);
            var params = {};

            angular.forEach(funcParams, function (funcParam) {
              return angular.extend(params, (typeof funcParam === 'function') ? $injector.invoke(funcParam) : funcParam);
            });

            return params;
          }

          function subResourceGenerator(endpoint, parent) {

            var connectingQuery = {};
            var params = resolveParameters(endpoint.params);

            angular.forEach(endpoint.link, function(value, key){
              connectingQuery[key] = parent[value];
            });

            angular.extend(params, connectingQuery);

            return $resource(api + endpoint.url, params, {
              'update': {
                'method': 'PATCH'
              }
            });

          }

          function getResponseTransformer(subendpoints){
            return function(response){
              response = angular.fromJson(response);

              if(!response){
                return response;
              }

              if(angular.isArray(response)) {

                for(var i = 0; i < response.length; i++){

                  angular.forEach(subendpoints, function (endpoint){
                    var subEndpointName = (endpoint.name ? endpoint.name : endpoint.url.replace('/', ''));
                    response[i]['$'+subEndpointName] = subResourceGenerator(endpoint, response[i]);
                  });

                }
              }

              else{
                angular.forEach(subendpoints, function (endpoint){
                  var subEndpointName = (endpoint.name ? endpoint.name : endpoint.url.replace('/', ''));
                  response['$'+subEndpointName] = subResourceGenerator(endpoint, response);
                });
              }

              response.$ready = ready.promise;
              ready.resolve(response);
              return response;
            }

          }

          function extender(src, arg1, func){
            if(angular.isString(arg1)){
              src[arg1] = func;
            }
            else if(angular.isObject(arg1)){
              angular.extend(src, arg1);
            }
            else if(angular.isArray(arg1)){
              angular.forEach(arg1, function(method){
                angular.extend(src, method);
              });
            }
          }

          //combine default parameters with what the user passes in
          var parameters = resolveParameters(_this.defaults.params||{}, params);

          /**
           * Creates a $resource wrapped with extra functionality
           * @param  {string} URL of endpoint to create the resource for. Is parsed by $resource's parser.
           * @param {Object=} Hash of parameters to pass onto each request (or link with the URL router)
           * @param {Object=} Subendpoint hash, containing a list of models that will get attached to $resource using a "link"
           *                  query that will query subendpoints with a variable belonging to this endpoint.
           * @return {$resource}
           */

          var resource = $resource(api + endpoint, parameters, {
            'update': {
              'method': 'PATCH',
              'transformResponse': getResponseTransformer(subendpoints)
            },
            'get': {
              'method': 'GET',
              'transformResponse': getResponseTransformer(subendpoints)
            },
            'query': {
              'isArray': true,
              'method': 'GET',
              'transformResponse': getResponseTransformer(subendpoints)
            },
            'save': {
              'method': 'POST',
              'transformResponse': getResponseTransformer(subendpoints)
            },
            'options': {
              'method': 'OPTIONS'
            }
          });

          resource.$$config = {
            'url': endpoint,
            'params': parameters,
            'children': angular.forEach(subendpoints, function(subendpoint){ return subendpoint.name })
          };

          resource.method = function method(arg1, func){
            extender(resource.prototype, arg1, func);
            return resource;
          };

          resource.static = function method(arg1, func){
            extender(resource, arg1, func);
            return resource;
          };

          resource.extend = function extend(arg1, func){
            resource.method(arg1, func);
            resource.static(arg1, func);
            return resource;
          };

          angular.forEach(_this.defaults.extensions, function(func, key){
            resource.extend(key, func);
          });
          angular.forEach(_this.defaults.methods, function(func, key){
            resource.method(key, func);
          });
          angular.forEach(_this.defaults.statics, function(func, key){
            resource.static(key, func);
          });

          return resource;
        }
      };

      function getWithChildren(getParams, children){

        var ret = new this({'$promise':null, '$resolved':false});
        children = children || this.$$config.children;

        ret.$promise = this.get(getParams).$promise.then(function(result){

          //send out requests for all the children
          return $q.all(angular.forEach(children, function(child){

            return result['$'+child].query().$promise.then(function(childResults){
              //once we fulfill a request, we assign the results back to the parent
              result['_'+child] = childResults;
              return result;
            });

          })).then(function(){
            //all promises resolved
            ret.$resolved = true;
            return angular.extend(ret, result);
            return result;
          }, function(err){
            //there was an issue
            ret.$resolved = true;
            return $q.reject(err);
          });
        });

        return ret;
      }

  }

})(angular);
<commit_msg>restoring resourcegenerator version<commit_after>(function () {

  'use strict';

  angular
    .module('resourceGenerator', ['ngResource'])
    .provider('ResourceGenerator', ResourceGenerator);

  /**
   * ResourceGenerator provider
   */
  function ResourceGenerator() {

    var _this = this;
    _this.$get = $get;
    _this.defaults = {
      'baseUrl': null,
      'extensions': null,
      'statics': null,
      'params': {},
      'methods': {
        'getWithChildren': getWithChildren
      }
    };

    $get.$inject = ['$resource', '$q', '$injector'];

    function $get($resource, $q, $injector) {

      /**
       * ResourceGenerator Factory: Creates a resource definition with a few add-on methods to expand on $resource functionality.
       * @param {string} endpoint - the URL for this endpoint
       * @param {Object=} params - $resource like params for this endpoint
       * @param {Object=} subendpoints - an array of objects - each object containing:
       *                        {'name': (string), name for this subendpoint,
         *                        'endpoint': (string) url for this endpoint,
         *                        'params': standard $resource params,
         *                        'link':  {query_param_name: variable_on_parent}
         * @returns {*}
       */
      return function (endpoint, params, subendpoints) {

        var ready = $q.defer();
        var api = _this.defaults.baseUrl || '';

        function resolveParameters() {

          var funcParams = [].slice.call(arguments);
          var params = {};

          angular.forEach(funcParams, function (funcParam) {
            return angular.extend(params, (typeof funcParam === 'function') ? $injector.invoke(funcParam) : funcParam);
          });

          return params;
        }

        function subResourceGenerator(endpoint, parent) {

          var connectingQuery = {};
          var params = resolveParameters(endpoint.params);

          angular.forEach(endpoint.link, function (value, key) {
            connectingQuery[key] = parent[value];
          });

          angular.extend(params, connectingQuery);

          return $resource(api + endpoint.url, params, {
            'update': {
              'method': 'PATCH'
            }
          });

        }

        function getResponseTransformer(subendpoints) {
          return function (response) {
            response = angular.fromJson(response);

            if (!response) {
              return response;
            }

            if (angular.isArray(response)) {

              for (var i = 0; i < response.length; i++) {

                angular.forEach(subendpoints, function (endpoint) {
                  var subEndpointName = (endpoint.name ? endpoint.name : endpoint.url.replace('/', ''));
                  response[i]['$' + subEndpointName] = subResourceGenerator(endpoint, response[i]);
                });

              }
            }

            else {
              angular.forEach(subendpoints, function (endpoint) {
                var subEndpointName = (endpoint.name ? endpoint.name : endpoint.url.replace('/', ''));
                response['$' + subEndpointName] = subResourceGenerator(endpoint, response);
              });
            }

            response.$ready = ready.promise;
            ready.resolve(response);
            return response;
          }

        }

        function extender(src, arg1, func) {
          if (angular.isString(arg1)) {
            src[arg1] = func;
          }
          else if (angular.isObject(arg1)) {
            angular.extend(src, arg1);
          }
          else if (angular.isArray(arg1)) {
            angular.forEach(arg1, function (method) {
              angular.extend(src, method);
            });
          }
        }

        //combine default parameters with what the user passes in
        var parameters = resolveParameters(_this.defaults.params || {}, params);

        /**
         * Creates a $resource wrapped with extra functionality
         * @param  {string} URL of endpoint to create the resource for. Is parsed by $resource's parser.
         * @param {Object=} Hash of parameters to pass onto each request (or link with the URL router)
         * @param {Object=} Subendpoint hash, containing a list of models that will get attached to $resource using a "link"
         *                  query that will query subendpoints with a variable belonging to this endpoint.
         * @return {$resource}
         */

        var resource = $resource(api + endpoint, parameters, {
          'update': {
            'method': 'PATCH',
            'transformResponse': getResponseTransformer(subendpoints)
          },
          'get': {
            'method': 'GET',
            'transformResponse': getResponseTransformer(subendpoints)
          },
          'query': {
            'isArray': true,
            'method': 'GET',
            'transformResponse': getResponseTransformer(subendpoints)
          },
          'save': {
            'method': 'POST',
            'transformResponse': getResponseTransformer(subendpoints)
          },
          'options': {
            'method': 'OPTIONS'
          }
        });

        resource.$$config = {
          'url': endpoint,
          'params': parameters,
          'children': angular.forEach(subendpoints, function (subendpoint) {
            return subendpoint.name
          })
        };

        resource.method = function method(arg1, func) {
          extender(resource.prototype, arg1, func);
          return resource;
        };

        resource.static = function method(arg1, func) {
          extender(resource, arg1, func);
          return resource;
        };

        resource.extend = function extend(arg1, func) {
          resource.method(arg1, func);
          resource.static(arg1, func);
          return resource;
        };

        angular.forEach(_this.defaults.extensions, function (func, key) {
          resource.extend(key, func);
        });
        angular.forEach(_this.defaults.methods, function (func, key) {
          resource.method(key, func);
        });
        angular.forEach(_this.defaults.statics, function (func, key) {
          resource.static(key, func);
        });

        return resource;
      }
    };

    function getWithChildren(getParams, children) {

      var ret = new this({'$promise': null, '$resolved': false});
      children = children || this.$$config.children;

      ret.$promise = this.get(getParams).$promise.then(function (result) {

        //send out requests for all the children
        return $q.all(angular.forEach(children, function (child) {

          return result['$' + child].query().$promise.then(function (childResults) {
            //once we fulfill a request, we assign the results back to the parent
            result['_' + child] = childResults;
            return result;
          });

        })).then(function () {
          //all promises resolved
          ret.$resolved = true;
          return angular.extend(ret, result);
          return result;
        }, function (err) {
          //there was an issue
          ret.$resolved = true;
          return $q.reject(err);
        });
      });

      return ret;
    }

  }

})(angular);
<|endoftext|>


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

const chalk = require('chalk');
const meow = require('meow');
const redent = require('redent');

const qgen = require('../');

const cli = meow(`
	${chalk.bold('Usage')}
		$ qgen <template name> [dest] [arguments] [options]

	${chalk.bold('Options')}
		-d, --directory <dir>	Templates directory (defaults to ./gqen-templates)
		-c, --config <path>	Path to the JSON config file (defaults to ./qgen.json)

	${chalk.bold('Examples')}
		$ qgen post ${chalk.dim('# generates the post template in the current folder')}
		$ qgen post ./pages ${chalk.dim('# generates the post template inside ./pages')}
		$ qgen post ./pages --page-title "Hello World" ${chalk.dim('# generates the post template in inside ./pages with data field pageTitle="Hello World" to the template rendering engine')}
`, {
	flags: {
		directory: {
			type: 'string',
			alias: 'd'
		},
		config: {
			alias: 'c'
		}
	}
});

/**
 * Displays list of available templates to stdout
 *
 * @param  {Object} options - options for qgen
 * @return {undefined}
 */
const listTemplates = options => {
	try {
		const templates = qgen(options).templates();
		if (Array.isArray(templates) && templates.length > 0) {
			console.log(redent(`	`, 2)); // For one line space
			console.log(redent(`	${chalk.bold('Available Templates')}`, 2));
			templates.forEach(template => {
				console.log(redent(`${template}`, 4));
			});
		}
	} catch (err) {
		console.log(redent(`	`, 2)); // For one line space
		console.error(err.message);
		process.exit(2);
	}
};

if (cli.input.length === 0) {
	console.log(cli.help);
	listTemplates(cli.flags);
} else {
	try {
		qgen(cli.flags).render(cli.input[0], cli.input[1]);
	} catch (err) {
		console.error(err.message);
		process.exit(1);
	}
}
<commit_msg>style(js): lints<commit_after>#!/usr/bin/env node
'use strict';

const chalk = require('chalk');
const meow = require('meow');
const redent = require('redent');

const qgen = require('..');

const cli = meow(`
	${chalk.bold('Usage')}
		$ qgen <template name> [dest] [arguments] [options]

	${chalk.bold('Options')}
		-d, --directory <dir>	Templates directory (defaults to ./gqen-templates)
		-c, --config <path>	Path to the JSON config file (defaults to ./qgen.json)

	${chalk.bold('Examples')}
		$ qgen post ${chalk.dim('# generates the post template in the current folder')}
		$ qgen post ./pages ${chalk.dim('# generates the post template inside ./pages')}
		$ qgen post ./pages --page-title "Hello World" ${chalk.dim('# generates the post template in inside ./pages with data field pageTitle="Hello World" to the template rendering engine')}
`, {
	flags: {
		directory: {
			type: 'string',
			alias: 'd'
		},
		config: {
			alias: 'c'
		}
	}
});

/**
 * Displays list of available templates to stdout
 *
 * @param  {Object} options - options for qgen
 * @return {undefined}
 */
const listTemplates = options => {
	try {
		const templates = qgen(options).templates();
		if (Array.isArray(templates) && templates.length > 0) {
			console.log(redent(`	`, 2)); // For one line space
			console.log(redent(`	${chalk.bold('Available Templates')}`, 2));
			templates.forEach(template => {
				console.log(redent(`${template}`, 4));
			});
		}
	} catch (err) {
		console.log(redent(`	`, 2)); // For one line space
		console.error(err.message);
		process.exit(2);
	}
};

if (cli.input.length === 0) {
	console.log(cli.help);
	listTemplates(cli.flags);
} else {
	try {
		qgen(cli.flags).render(cli.input[0], cli.input[1]);
	} catch (err) {
		console.error(err.message);
		process.exit(1);
	}
}
<|endoftext|>


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

var path = require('path'),
    fs = require('fs'),
    optimist = require('optimist'),
    exec = require('child_process').exec,
    pkg = require(path.join(process.mainModule.paths[0],'..','..','package.json'));

// AVAILABLE CLI OPTIONS
var base = {
  'init': 'Initialize a project directory for use with NGN.',
  'add': 'Add an NGN feature.',
  'remove': 'Remove an NGN feature.',
  'uninstall': 'Remove NGN completely.',
  /*
  'start': 'Start the NGN manager or a process.',
  'stop': 'Stop the manager or a process.',
  'create': 'Create a custom class, API, process, or documentation.',
  */
  'version':'List the version of NGN installed on the system.',
  'help':'View help for a specific command.'
  //'mechanic': 'Open the NGN Mechanic shell.',
  //'repair': 'Repair an existing NGN installation.',
};

var shortcuts = {
  'v': 'version',
  'h': 'help'
};

var opts = {};
for(var o in base){
  opts[o] = base[o];
}

// Optional CLI Options
var opt = {
  'ngn-dev': {
    'develop': 'Auto-restart processes when the file changes. (Dev Tool)',
  }
}

// Add optional CLI options if they're installed.
for (var mod in opt){
  if (fs.existsSync(path.join(__dirname,'..','..','ngn-dev'))){
    for (var m in opt[mod]){
      opts[m] = opt[mod][m];
    }
  }
}

// Placeholder for the selected command
var cmd = null;

// CLI REQUIREMENTS
// Make sure at least one command option is selected.
var minOptions = function(argv){
	if (argv._.length > 0){
		cmd = argv._[0];
		argv[cmd] = argv._[1] || true;
		return true;
	}
	for (var term in opts){
		if (argv.hasOwnProperty(term)){
			cmd = term;
			return true;
		}
	}
	for (var _term in argv){
		if (_term !== '_' && _term !== '$0'){
			cmd = _term;
			break;
		}
	}

	optimist.describe(opts);
	if (cmd == null){
		throw('');
	}

	if (cmd in shortcuts){
	  cmd = shortcuts[cmd];
	  return true;
	}

	throw('"'+cmd+'" is not a valid option.');
};

// Make sure the command option has the appropriate parameters which
// are required to run.
var validOption = function(argv){
	switch (cmd.trim().toLowerCase()){
		case 'uninstall':
		  return true;
		case 'unsupport':
		case 'support':
      if (typeof argv[cmd] == 'boolean'){
        argv[cmd] = '';
      }
			break;

		// Make sure the CLI knows what it needs to create
		case 'create':
			if (argv[cmd] === true || ['class','docs','api'].indexOf(argv[cmd].trim().toLowerCase()) < 0){
				throw('"'+(argv[cmd] === true ? 'Blank' : argv[cmd])+'" is not a valid "create" option. Valid options are:\n  - class\n  - api');
			}
			break;

    case 'start':
    case 'stop':
		  return true;

		// All other options do not require additional parameters, or they
		// are not valid.
		default:
			// If the command options object contains the command, it is
			// recognized and processing continues.
			if (opts.hasOwnProperty(cmd)) {
				return true;
      }

			// If the command is not recognized, the list of valid commands
			// is described and the usage/error is displayed.
			optimist.describe(opts);
			throw('"'+cmd+'" is not a valid option.');
	}
	return true;
};

// ARGUMENTS
var argv = optimist
			.usage('Usage: ngn <option>')
			.wrap(80)
			.check(minOptions)
			.check(validOption)
			.argv,
  p    = require('path'),
  cwd  = process.cwd(),
	root = p.dirname(process.mainModule.filename);

// Include the appropriate command
if (cmd in base){
  require(require('path').join(__dirname,'commands',cmd));
} else {
  for (var pkg in opt){
    if (opt[pkg][cmd] !== undefined){
      require(require('path').join(__dirname,'..','..',pkg))[cmd]();
      break;
    }
  }
}
return;<commit_msg>Added update, modified add<commit_after>#!/usr/bin/env node

var path = require('path'),
    fs = require('fs'),
    optimist = require('optimist'),
    exec = require('child_process').exec,
    pkg = require(path.join(process.mainModule.paths[0],'..','..','package.json'));

// AVAILABLE CLI OPTIONS
var base = {
  'init': 'Initialize a project directory for use with NGN.',
  'add': 'Add an NGN feature.',
  'remove': 'Remove an NGN feature.',
  'update': 'Update the NGN installation',
  'uninstall': 'Remove NGN completely.',
  /*
  'start': 'Start the NGN manager or a process.',
  'stop': 'Stop the manager or a process.',
  'create': 'Create a custom class, API, process, or documentation.',
  */
  'version':'List the version of NGN installed on the system.',
  'help':'View help for a specific command.'
  //'mechanic': 'Open the NGN Mechanic shell.',
  //'repair': 'Repair an existing NGN installation.',
};

var shortcuts = {
  'v': 'version',
  'h': 'help'
};

var opts = {};
for(var o in base){
  opts[o] = base[o];
}

// Optional CLI Options
var opt = {
  'ngn-dev': {
    'develop': 'Auto-restart processes when the file changes. (Dev Tool)',
  }
}

// Add optional CLI options if they're installed.
for (var mod in opt){
  if (fs.existsSync(path.join(__dirname,'..','..','ngn-dev'))){
    for (var m in opt[mod]){
      opts[m] = opt[mod][m];
    }
  }
}

// Placeholder for the selected command
var cmd = null;

// CLI REQUIREMENTS
// Make sure at least one command option is selected.
var minOptions = function(argv){
	if (argv._.length > 0){
		cmd = argv._[0];
		argv[cmd] = argv._[1] || true;
		return true;
	}
	for (var term in opts){
		if (argv.hasOwnProperty(term)){
			cmd = term;
			return true;
		}
	}
	for (var _term in argv){
		if (_term !== '_' && _term !== '$0'){
			cmd = _term;
			break;
		}
	}

	optimist.describe(opts);
	if (cmd == null){
		throw('');
	}

	if (cmd in shortcuts){
	  cmd = shortcuts[cmd];
	  return true;
	}

	throw('"'+cmd+'" is not a valid option.');
};

// Make sure the command option has the appropriate parameters which
// are required to run.
var validOption = function(argv){
	switch (cmd.trim().toLowerCase()){
		case 'uninstall':
		  return true;
		case 'unsupport':
		case 'support':
      if (typeof argv[cmd] == 'boolean'){
        argv[cmd] = '';
      }
			break;

		// Make sure the CLI knows what it needs to create
		case 'create':
			if (argv[cmd] === true || ['class','docs','api'].indexOf(argv[cmd].trim().toLowerCase()) < 0){
				throw('"'+(argv[cmd] === true ? 'Blank' : argv[cmd])+'" is not a valid "create" option. Valid options are:\n  - class\n  - api');
			}
			break;

    case 'start':
    case 'stop':
		  return true;

		// All other options do not require additional parameters, or they
		// are not valid.
		default:
			// If the command options object contains the command, it is
			// recognized and processing continues.
			if (opts.hasOwnProperty(cmd)) {
				return true;
      }

			// If the command is not recognized, the list of valid commands
			// is described and the usage/error is displayed.
			optimist.describe(opts);
			throw('"'+cmd+'" is not a valid option.');
	}
	return true;
};

// ARGUMENTS
var argv = optimist
			.usage('Usage: ngn <option>')
			.wrap(80)
			.check(minOptions)
			.check(validOption)
			.argv,
  p    = require('path'),
  cwd  = process.cwd(),
	root = p.dirname(process.mainModule.filename);

// Include the appropriate command
if (cmd in base){
  require(require('path').join(__dirname,'commands',cmd));
} else {
  for (var pkg in opt){
    if (opt[pkg][cmd] !== undefined){
      require(require('path').join(__dirname,'..','..',pkg))[cmd]();
      break;
    }
  }
}
return;<|endoftext|>


<commit_before>var REQUEST_HEADERS = require("./REQUEST_HEADERS.js").REQUEST_HEADERS;

var router = function(req, res) {
    if (require("./debug.js").debug) {
        res.send("in debug mode, no requests sent");
    } else {
        var request = require("request");
        var x2j = require("xml2js");

        var podcastUrl = req.query.url;

        var podcastData = {};

        request({
            url: podcastUrl,
            headers: REQUEST_HEADERS
        }, function(err, result, body) {
            x2j.parseString(body, function(err, result) {
                if (err) {
                    console.log("error parsing xml");
                    res.sendStatus(500);
                } else {
                    var channel = result.rss.channel[0];
                    // console.log(channel);
                    // title
                    if (channel.title && channel.title[0]) {
                        podcastData.title = channel.title[0];
                    }
                    // publisher
                    if (channel["itunes:author"] && channel["itunes:author"][0]) {
                        podcastData.publisher = channel["itunes:author"][0];
                    }
                    // description
                    if (channel.description && channel.description[0]) {
                        podcastData.description = channel.description[0];
                    }
                    // image
                    if (channel["itunes:image"] && channel["itunes:image"][0]) {
                        podcastData.image = channel["itunes:image"][0].$.href;
                    }
                    if (channel["image"] && channel["image"][0] &&
                        channel["image"][0]["url"] && channel["image"][0]["url"][0]) {
                        podcastData.image = channel["image"][0]["url"][0];
                    }

                    res.send(podcastData);
                }
            });
        });
    }
};

module.exports.router = router;
<commit_msg>Delete already-converted server-side script file<commit_after><|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

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",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_<commit_msg>Should work now<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

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",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_c<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator

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 yo<commit_msg>You feeling lucky punk?<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator

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 <|endoftext|>


<commit_before>import React from 'react';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal'
import Form from 'react-bootstrap/Form'

import createTrip from './create-new-trip.js'

/**
 * Returns a Form.Control element with input type 'text' and other fields
 * specified by the function parameters.
 *
 * @param {string} placeholder Text placehold in the form input
 * @param {React.RefObject} ref Ref attached to the value inputted in the form.
 * @return {JSX.Element} The Form.Control element.
 */
function createTextFormControl(placeholder, ref) {
  return (
    <Form.Control
      type="text"
      placeholder={placeholder}
      ref={ref}
    />
  );
}

/**
 * Returns a Form.Group element with components specified by the input args.
 *
 * @param {string} controlId Prop that accessibly wires the nested label and
 *                           input prop.
 * @param {string} formLabel Label/title for the form input.
 * @param {string} inputType Input type of the form.
 * @param {string} placeholder Text placeholder in the form input.
 * @param {React.RefObject} ref Ref attached to the values inputted in the form.
 * @param {string} subFormText Subtext instructions under a form input.
 * @return {JSX.Element} The Form.Group element.
 */
function createFormGroup(controlId, formLabel, inputType,
                                    placeholder, ref, subFormText = '') {
  let formControl;
  if (inputType === 'text') {
    formControl = createTextFormControl(placeholder, ref)
  } else {
    // TODO(Issue #52): Create diff form inputs for start & end dates
    //                  and collaborator emails.
    console.error('Only text form inputs are implemented as of now');
  }

  return (
    <Form.Group controlId={controlId}>
      <Form.Label>{formLabel}</Form.Label>
        {formControl}
      {/* Temporary instructions until fix Issue #52 */}
      <Form.Text className="text-muted">
        {subFormText}
      </Form.Text>
    </Form.Group>
  )
}

/**
 * Component corresponding to add trips modal.
 *
 * @param {Object} props These are the props for this component:
 * - show: Boolean that determines if the add trips modal should be displayed.
 * - handleClose: The function that handles closing the add trips modal.
 * - userEmail: The current user's email.
 *
 * @extends React.Component
 */
class AddTrip extends React.Component {
  /** @inheritdoc */
  constructor(props) {
    super(props);

    this.nameRef = React.createRef();
    this.descriptionRef = React.createRef();
    this.destinationRef = React.createRef();
    this.startDateRef = React.createRef();
    this.endDateRef = React.createRef();
    this.collaboratorsRef = React.createRef();
  }

  /**
   * Upon submission of the form, a new Trip document is created and the add
   * trip modal is closed.
   *
   * TODO(Merge PR #54): Remove console.log statment.
   */
  handleSubmitNewTrip = () => {
    console.log('New trip submitted.');
    createTrip({name: this.nameRef.current.value,
               description: this.descriptionRef.current.value,
               destination: this.destinationRef.current.value,
               startDate: this.startDateRef.current.value,
               endDate: this.endDateRef.current.value,
               collaborators: this.collaboratorsRef.current.value
    });

    this.props.handleClose();
  }

  /** @inheritdoc */
  render() {
    return (
      <Modal show={this.props.show} onHide={this.props.handleClose}>
        <Modal.Header closeButton>
          <Modal.Title>Add New Trip</Modal.Title>
        </Modal.Header>

        <Form>
          <Modal.Body>
            {createFormGroup('tripNameGroup', 'Trip Name', 'text',
                             'Enter Trip Name', this.nameRef)}
            {createFormGroup('tripDescGroup', 'Trip Description', 'text',
                             'Enter Trip Description', this.descriptionRef)}
            {createFormGroup('tripDestGroup', 'Trip Destination', 'text',
                             'Enter Trip Destination', this.destinationRef)}
            {createFormGroup('tripStartDateGroup', 'Start Date', 'text',
                            'Enter Trip Start Date', this.startDateRef,
                            'Enter date in the form: \'mm/dd/yyy\'')}
            {createFormGroup('tripEndDateGroup', 'End Date', 'text',
                          'Enter Trip End Date', this.endDateRef,
                          'Enter date in the form: \'mm/dd/yyy\'')}
            {createFormGroup('tripCollabsGroup', 'Trip Collaborators', 'text',
                           'Enter Collaborator Emails', this.collaboratorsRef,
                           'Enter emails in the form: \'user1@email.com, ...,' +
                           ' userx@email.com\'')}
          </Modal.Body>

          <Modal.Footer>
            <Button variant='secondary' onClick={this.props.handleClose}>
              Close
            </Button>
            <Button variant='primary' onClick={this.handleSubmitNewTrip}>
              Add Trip
            </Button>
          </Modal.Footer>
        </Form>
      </Modal>
    );
  }
};

export default AddTrip;
<commit_msg>Ensure date placeholder strings contain four 'y's for year.<commit_after>import React from 'react';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal'
import Form from 'react-bootstrap/Form'

import createTrip from './create-new-trip.js'

/**
 * Returns a Form.Control element with input type 'text' and other fields
 * specified by the function parameters.
 *
 * @param {string} placeholder Text placehold in the form input
 * @param {React.RefObject} ref Ref attached to the value inputted in the form.
 * @return {JSX.Element} The Form.Control element.
 */
function createTextFormControl(placeholder, ref) {
  return (
    <Form.Control
      type="text"
      placeholder={placeholder}
      ref={ref}
    />
  );
}

/**
 * Returns a Form.Group element with components specified by the input args.
 *
 * @param {string} controlId Prop that accessibly wires the nested label and
 *                           input prop.
 * @param {string} formLabel Label/title for the form input.
 * @param {string} inputType Input type of the form.
 * @param {string} placeholder Text placeholder in the form input.
 * @param {React.RefObject} ref Ref attached to the values inputted in the form.
 * @param {string} subFormText Subtext instructions under a form input.
 * @return {JSX.Element} The Form.Group element.
 */
function createFormGroup(controlId, formLabel, inputType,
                                    placeholder, ref, subFormText = '') {
  let formControl;
  if (inputType === 'text') {
    formControl = createTextFormControl(placeholder, ref)
  } else {
    // TODO(Issue #52): Create diff form inputs for start & end dates
    //                  and collaborator emails.
    console.error('Only text form inputs are implemented as of now');
  }

  return (
    <Form.Group controlId={controlId}>
      <Form.Label>{formLabel}</Form.Label>
        {formControl}
      {/* Temporary instructions until fix Issue #52 */}
      <Form.Text className="text-muted">
        {subFormText}
      </Form.Text>
    </Form.Group>
  )
}

/**
 * Component corresponding to add trips modal.
 *
 * @param {Object} props These are the props for this component:
 * - show: Boolean that determines if the add trips modal should be displayed.
 * - handleClose: The function that handles closing the add trips modal.
 * - userEmail: The current user's email.
 *
 * @extends React.Component
 */
class AddTrip extends React.Component {
  /** @inheritdoc */
  constructor(props) {
    super(props);

    this.nameRef = React.createRef();
    this.descriptionRef = React.createRef();
    this.destinationRef = React.createRef();
    this.startDateRef = React.createRef();
    this.endDateRef = React.createRef();
    this.collaboratorsRef = React.createRef();
  }

  /**
   * Upon submission of the form, a new Trip document is created and the add
   * trip modal is closed.
   *
   * TODO(Merge PR #54): Remove console.log statment.
   */
  handleSubmitNewTrip = () => {
    console.log('New trip submitted.');
    createTrip({name: this.nameRef.current.value,
               description: this.descriptionRef.current.value,
               destination: this.destinationRef.current.value,
               startDate: this.startDateRef.current.value,
               endDate: this.endDateRef.current.value,
               collaborators: this.collaboratorsRef.current.value
    });

    this.props.handleClose();
  }

  /** @inheritdoc */
  render() {
    return (
      <Modal show={this.props.show} onHide={this.props.handleClose}>
        <Modal.Header closeButton>
          <Modal.Title>Add New Trip</Modal.Title>
        </Modal.Header>

        <Form>
          <Modal.Body>
            {createFormGroup('tripNameGroup', 'Trip Name', 'text',
                             'Enter Trip Name', this.nameRef)}
            {createFormGroup('tripDescGroup', 'Trip Description', 'text',
                             'Enter Trip Description', this.descriptionRef)}
            {createFormGroup('tripDestGroup', 'Trip Destination', 'text',
                             'Enter Trip Destination', this.destinationRef)}
            {createFormGroup('tripStartDateGroup', 'Start Date', 'text',
                            'Enter Trip Start Date', this.startDateRef,
                            'Enter date in the form: \'mm/dd/yyyy\'')}
            {createFormGroup('tripEndDateGroup', 'End Date', 'text',
                          'Enter Trip End Date', this.endDateRef,
                          'Enter date in the form: \'mm/dd/yyyy\'')}
            {createFormGroup('tripCollabsGroup', 'Trip Collaborators', 'text',
                           'Enter Collaborator Emails', this.collaboratorsRef,
                           'Enter emails in the form: \'user1@email.com, ...,' +
                           ' userx@email.com\'')}
          </Modal.Body>

          <Modal.Footer>
            <Button variant='secondary' onClick={this.props.handleClose}>
              Close
            </Button>
            <Button variant='primary' onClick={this.handleSubmitNewTrip}>
              Add Trip
            </Button>
          </Modal.Footer>
        </Form>
      </Modal>
    );
  }
};

export default AddTrip;
<|endoftext|>


<commit_before>import spies from 'chai-spies';

export default function(chai, utils) {
    chai.use(spies);

    utils.addMethod(chai.assert, 'calledOnce', function(actual, expected, msg) {
        new chai.Assertion(actual).to.have.been.called.once(msg);
    });

    utils.addMethod(chai.assert, 'notCalledOnce', function(actual, expected, msg) {
        new chai.Assertion(actual).not.to.have.been.called.once(msg);
    });
}
<commit_msg>remove chai-spies dependency<commit_after>export default function(chai, utils) {
    utils.addMethod(chai.assert, 'calledOnce', function(actual, expected, msg) {
        new chai.Assertion(actual).to.have.been.called.once(msg);
    });

    utils.addMethod(chai.assert, 'notCalledOnce', function(actual, expected, msg) {
        new chai.Assertion(actual).not.to.have.been.called.once(msg);
    });
}
<|endoftext|>


<commit_before>;( function( window, document, undefined ) {

	"use strict";

	var respImgInspector = {};

	var supports = !!document.querySelector &&
		!!window.addEventListener &&
		!!window.MutationObserver;

	var settings, wrapper, items = [], images = [], overlays = [];

	var defaults = {
		selectors: null,
		classNamespace: "respimg-inspector-",
		wrapperId: "respimg-inspector-wrapper"
	};

	var elementsToExclude = [
		"span", "em", "strong", "i", "b", "big", "small", "tt", "abbr",
		"script", "br", "hr", "sub", "sup", "button", "input", "label",
		"select", "textarea", "samp", "var"
	];

	var docBody = document.body;

	var forEach = function( collection, callback, scope ) {
		if ( Object.prototype.toString.call( collection ) === "[object Object]" ) {
			for ( var prop in collection ) {
				if ( Object.prototype.hasOwnProperty.call( collection, prop ) ) {
					callback.call( scope, collection[ prop ], prop, collection );
				}
			}
		} else {
			for ( var i = 0, len = collection.length; i < len; i++ ) {
				callback.call( scope, collection[ i ], i, collection );
			}
		}
	};

	var extend = function( defaults, options ) {
		var extended = {};
		var prop;
		for ( prop in defaults ) {
			if ( Object.prototype.hasOwnProperty.call( defaults, prop ) ) {
				extended[ prop ] = defaults[ prop ];
			}
		}
		for ( prop in options ) {
			if ( Object.prototype.hasOwnProperty.call( options, prop ) ) {
				extended[ prop ] = options[ prop ];
			}
		}
		return extended;
	};

	var throttle = function( type, name, scope ) {
		var obj = scope || window;
		var running = false;
		var func = function() {
			if ( running ) { return; }
			running = true;
			observer.disconnect();
			requestAnimationFrame( function() {
				obj.dispatchEvent ( new CustomEvent( name ) );
				running = false;
			} );
		};
		obj.addEventListener( type, func );
	};

	var getCss = function( element, property ) {
		return window.getComputedStyle( element, null ).getPropertyValue( property );
	};

	var observer = new MutationObserver( function( mutations ) {
		mutations.forEach( function() {
			update();
		} );
	} );

	var update = function() {
		cleanUp();
		var selectors = getSelectors();
		var respImgElements = document.querySelectorAll( selectors );
		forEach( respImgElements, function( respImgElement ) {
			var image = getImage( respImgElement );
			var item = {
				el: respImgElement,
				img: image
			};

			// TODO: Handle more background image usages.
			// Only handle IMG tag and background "cover" for now.
			if ( item.el.nodeName === "IMG" ||
				getCss( item.el, "background-size" ) === "cover"
			) {
				items.push( item );
				images.push( image );
			}
		} );
		window.imagesLoaded( images, function() {
			forEach( items, function( item ) {
				var data = extend( getElementData( item.el ), getImageData( item.img ) );
				overlays.push( getOverlay( data ) );
				observer.observe( item.el, {
					attributes: true
				} );
			} );
			renderWrapper();
			renderOverlays();
			observer.observe( docBody, {
				childList: true
			} );
		} );
	};

	var getSelectors = function() {
		if ( settings.selectors ) {
			return settings.selectors;
		} else {
			var array = elementsToExclude.map( function( element ) {
				return "*:not(" + element + ")";
			} );
			return array.join();
		}
	};

	var getElementData = function( element ) {
		var elRect = element.getBoundingClientRect();
		return {
			elTag: element.nodeName.toLowerCase(),
			elWidth: elRect.width,
			elHeight: elRect.height,
			elTop: elRect.top,
			elBottom: elRect.bottom,
			elLeft: elRect.left,
			elRight: elRect.right
		};
	};

	var getImageData = function( img ) {
		return {
			imgWidth: img.width,
			imgHeight: img.height,
			imgNaturalWidth: img.naturalWidth,
			imgNaturalHeight: img.naturalHeight,
			imgSizes: img.sizes
		};
	};

	var getImage = function( element ) {
		var image;
		if ( element.nodeName === "IMG" ) {
			image = element;
		} else if ( getCss( element, "background-image" ) !== "none" ) {
			var bgUrl = /^url\((['"]?)(.*)\1\)$/.exec( getCss( element, "background-image" ) );
			image = new Image();
			image.src = bgUrl[ 2 ];
		}
		return image;
	};

	var getOverlayClassName = function( data ) {
		var overlayClassName;
		var pixelRatio = window.devicePixelRatio;
		if ( data.elWidth * pixelRatio < data.imgNaturalWidth ||
			data.elHeight * pixelRatio < data.imgNaturalHeight
		) {
			overlayClassName = "warning";
		} else if ( data.elWidth * pixelRatio > data.imgNaturalWidth ||
			data.elHeight * pixelRatio > data.imgNaturalHeight
		) {
			overlayClassName = "bad";
		} else {
			overlayClassName = "good";
		}
		return settings.classNamespace + overlayClassName;
	};

	var getOverlay = function( data ) {
		var marginTop = getCss( docBody, "margin-top" );
		var marginLeft = getCss( docBody, "margin-left" );
		var bodyRect = docBody.getBoundingClientRect();
		var offsetTop = data.elTop - bodyRect.top;
		var offsetLeft = data.elLeft - bodyRect.left;
		var overlay = document.createElement( "div" );
		overlay.classList.add( settings.classNamespace + "overlay" );
		overlay.style.position = "absolute";
		overlay.style.width = data.elWidth + "px";
		overlay.style.height = data.elHeight + "px";
		overlay.style.top = "calc(" + offsetTop + "px + " + marginTop + ")";
		overlay.style.left =	"calc(" + offsetLeft + "px + " + marginLeft + ")";
		overlay.classList.add( getOverlayClassName( data ) );
		forEach( data, function( dataValue, dataKey ) {
			overlay.dataset[ dataKey ] = dataValue;
		} );
		return overlay;
	};

	var renderWrapper = function() {
		wrapper = document.createElement( "div" );
		wrapper.id = settings.wrapperId;
		wrapper.style.position = "absolute";
		wrapper.style.top = 0;
		wrapper.style.bottom = 0;
		wrapper.style.left = 0;
		wrapper.style.right = 0;
		wrapper.style.zIndex = 2147483647;
		docBody.appendChild( wrapper );
	};

	var renderOverlays = function() {
		forEach( overlays, function( overlay ) {
			wrapper.appendChild( overlay );
		} );
	};

	var cleanUp = function() {
		observer.disconnect();
		if ( overlays.length ) {
			forEach( overlays, function( overlay ) {
				overlay.remove();
			} );
		}
		if ( wrapper !== undefined ) {
			wrapper.remove();
		}
		items = [];
		images = [];
		overlays = [];
	};

	respImgInspector.init = function( options ) {
		if ( !supports ) { return; }
		settings = extend( defaults, options || {} );
		throttle( "resize", "optimizedResize" );
		window.addEventListener( "optimizedResize", update );
		window.addEventListener( "load", update );
	};

	if ( typeof define === "function" && define.amd ) {
		define( [], function() {
			return respImgInspector;
		} );
	} else if ( typeof module !== "undefined" && module.exports ) {
		module.exports = respImgInspector;
	} else {
		window.respImgInspector = respImgInspector;
	}

} )( window, document );
<commit_msg>Fix typo<commit_after>;( function( window, document, undefined ) {

	"use strict";

	var respImgInspector = {};

	var supports = !!document.querySelector &&
		!!window.addEventListener &&
		!!window.MutationObserver;

	var settings, wrapper, items = [], images = [], overlays = [];

	var defaults = {
		selectors: null,
		classNamespace: "respimg-inspector-",
		wrapperId: "respimg-inspector-wrapper"
	};

	var elementsToExclude = [
		"span", "em", "strong", "i", "b", "big", "small", "tt", "abbr",
		"script", "br", "hr", "sub", "sup", "button", "input", "label",
		"select", "textarea", "samp", "var"
	];

	var docBody = document.body;

	var forEach = function( collection, callback, scope ) {
		if ( Object.prototype.toString.call( collection ) === "[object Object]" ) {
			for ( var prop in collection ) {
				if ( Object.prototype.hasOwnProperty.call( collection, prop ) ) {
					callback.call( scope, collection[ prop ], prop, collection );
				}
			}
		} else {
			for ( var i = 0, len = collection.length; i < len; i++ ) {
				callback.call( scope, collection[ i ], i, collection );
			}
		}
	};

	var extend = function( defaults, options ) {
		var extended = {};
		var prop;
		for ( prop in defaults ) {
			if ( Object.prototype.hasOwnProperty.call( defaults, prop ) ) {
				extended[ prop ] = defaults[ prop ];
			}
		}
		for ( prop in options ) {
			if ( Object.prototype.hasOwnProperty.call( options, prop ) ) {
				extended[ prop ] = options[ prop ];
			}
		}
		return extended;
	};

	var throttle = function( type, name, scope ) {
		var obj = scope || window;
		var running = false;
		var func = function() {
			if ( running ) { return; }
			running = true;
			observer.disconnect();
			requestAnimationFrame( function() {
				obj.dispatchEvent( new CustomEvent( name ) );
				running = false;
			} );
		};
		obj.addEventListener( type, func );
	};

	var getCss = function( element, property ) {
		return window.getComputedStyle( element, null ).getPropertyValue( property );
	};

	var observer = new MutationObserver( function( mutations ) {
		mutations.forEach( function() {
			update();
		} );
	} );

	var update = function() {
		cleanUp();
		var selectors = getSelectors();
		var respImgElements = document.querySelectorAll( selectors );
		forEach( respImgElements, function( respImgElement ) {
			var image = getImage( respImgElement );
			var item = {
				el: respImgElement,
				img: image
			};

			// TODO: Handle more background image usages.
			// Only handle IMG tag and background "cover" for now.
			if ( item.el.nodeName === "IMG" ||
				getCss( item.el, "background-size" ) === "cover"
			) {
				items.push( item );
				images.push( image );
			}
		} );
		window.imagesLoaded( images, function() {
			forEach( items, function( item ) {
				var data = extend( getElementData( item.el ), getImageData( item.img ) );
				overlays.push( getOverlay( data ) );
				observer.observe( item.el, {
					attributes: true
				} );
			} );
			renderWrapper();
			renderOverlays();
			observer.observe( docBody, {
				childList: true
			} );
		} );
	};

	var getSelectors = function() {
		if ( settings.selectors ) {
			return settings.selectors;
		} else {
			var array = elementsToExclude.map( function( element ) {
				return "*:not(" + element + ")";
			} );
			return array.join();
		}
	};

	var getElementData = function( element ) {
		var elRect = element.getBoundingClientRect();
		return {
			elTag: element.nodeName.toLowerCase(),
			elWidth: elRect.width,
			elHeight: elRect.height,
			elTop: elRect.top,
			elBottom: elRect.bottom,
			elLeft: elRect.left,
			elRight: elRect.right
		};
	};

	var getImageData = function( img ) {
		return {
			imgWidth: img.width,
			imgHeight: img.height,
			imgNaturalWidth: img.naturalWidth,
			imgNaturalHeight: img.naturalHeight,
			imgSizes: img.sizes
		};
	};

	var getImage = function( element ) {
		var image;
		if ( element.nodeName === "IMG" ) {
			image = element;
		} else if ( getCss( element, "background-image" ) !== "none" ) {
			var bgUrl = /^url\((['"]?)(.*)\1\)$/.exec( getCss( element, "background-image" ) );
			image = new Image();
			image.src = bgUrl[ 2 ];
		}
		return image;
	};

	var getOverlayClassName = function( data ) {
		var overlayClassName;
		var pixelRatio = window.devicePixelRatio;
		if ( data.elWidth * pixelRatio < data.imgNaturalWidth ||
			data.elHeight * pixelRatio < data.imgNaturalHeight
		) {
			overlayClassName = "warning";
		} else if ( data.elWidth * pixelRatio > data.imgNaturalWidth ||
			data.elHeight * pixelRatio > data.imgNaturalHeight
		) {
			overlayClassName = "bad";
		} else {
			overlayClassName = "good";
		}
		return settings.classNamespace + overlayClassName;
	};

	var getOverlay = function( data ) {
		var marginTop = getCss( docBody, "margin-top" );
		var marginLeft = getCss( docBody, "margin-left" );
		var bodyRect = docBody.getBoundingClientRect();
		var offsetTop = data.elTop - bodyRect.top;
		var offsetLeft = data.elLeft - bodyRect.left;
		var overlay = document.createElement( "div" );
		overlay.classList.add( settings.classNamespace + "overlay" );
		overlay.style.position = "absolute";
		overlay.style.width = data.elWidth + "px";
		overlay.style.height = data.elHeight + "px";
		overlay.style.top = "calc(" + offsetTop + "px + " + marginTop + ")";
		overlay.style.left =	"calc(" + offsetLeft + "px + " + marginLeft + ")";
		overlay.classList.add( getOverlayClassName( data ) );
		forEach( data, function( dataValue, dataKey ) {
			overlay.dataset[ dataKey ] = dataValue;
		} );
		return overlay;
	};

	var renderWrapper = function() {
		wrapper = document.createElement( "div" );
		wrapper.id = settings.wrapperId;
		wrapper.style.position = "absolute";
		wrapper.style.top = 0;
		wrapper.style.bottom = 0;
		wrapper.style.left = 0;
		wrapper.style.right = 0;
		wrapper.style.zIndex = 2147483647;
		docBody.appendChild( wrapper );
	};

	var renderOverlays = function() {
		forEach( overlays, function( overlay ) {
			wrapper.appendChild( overlay );
		} );
	};

	var cleanUp = function() {
		observer.disconnect();
		if ( overlays.length ) {
			forEach( overlays, function( overlay ) {
				overlay.remove();
			} );
		}
		if ( wrapper !== undefined ) {
			wrapper.remove();
		}
		items = [];
		images = [];
		overlays = [];
	};

	respImgInspector.init = function( options ) {
		if ( !supports ) { return; }
		settings = extend( defaults, options || {} );
		throttle( "resize", "optimizedResize" );
		window.addEventListener( "optimizedResize", update );
		window.addEventListener( "load", update );
	};

	if ( typeof define === "function" && define.amd ) {
		define( [], function() {
			return respImgInspector;
		} );
	} else if ( typeof module !== "undefined" && module.exports ) {
		module.exports = respImgInspector;
	} else {
		window.respImgInspector = respImgInspector;
	}

} )( window, document );
<|endoftext|>


<commit_before>/**
 * Created by Awesome on 2/28/2016.
 */

    // use strict
'use strict';

// require dependencies
var co = require ('co');

// require local dependencies
var model = require (global.appRoot + '/bin/bundles/user/model/acl');

/**
 * build acl class
 */
class acl {
    /**
     * tests acl
     *
     * @param acl
     * @param User
     * @returns {Promise}
     */
    test (acl, User) {
        return new Promise ((resolve, reject) => {
            co (function * () {
                // check if acl required
                if (!User || User === undefined) {
                    User = false;
                }
                // check for acl
                if (!acl) {
                    return resolve (true);
                }
                // check if not user
                if ((!User && acl.test === false) || (User && acl.test === true)) {
                    return resolve (true);
                }
                // check if user
                if ((User && acl.test === false) || (!User && acl.test === true)) {
                    return resolve (acl.fail || false);
                }
                // check if user
                if (!User) {
                    return resolve (acl.fail || false);
                }

                // check get acl
                var userAcl = yield User.model ('acl');
                if (!userAcl) {
                    return resolve (acl.fail || false);
                }

                // check if user
                var can = false;
                // loop acl array
                for (var i = 0; i < userAcl.length; i++) {
                    // run acl test
                    var aclTest = userAcl[i].get ('value');

                    // check if all
                    if (aclTest === true) {
                        return resolve (true);
                    }

                    // loop individual acl
                    for (var x = 0; x < acl.test.length; x++) {
                        if (aclTest.indexOf (acl.test[x]) > -1) {
                            can = true;
                        }
                    }
                }

                // check if acl found
                if (can) {
                    return resolve (true);
                }

                // perform default resolve
                return resolve (acl.fail || false);
            });
        });
    }
}

/**
 * export acl class
 *
 * @type {acl}
 */
module.exports = new acl ();
<commit_msg>lint acl.js for complex functions<commit_after>/**
 * Created by Awesome on 2/28/2016.
 */

    // use strict
'use strict';

// require dependencies
var co = require ('co');

// require local dependencies
var model = require (global.appRoot + '/bin/bundles/user/model/acl');

/**
 * build acl class
 */
class acl {
    /**
     * construct acl class
     */
    constructor() {
        // bind methods
        this.test = this.test.bind (this);
    }

    /**
     * tests acl
     *
     * @param acl
     * @param User
     * @returns {Promise}
     */
    test (acl, User) {
        return new Promise ((resolve, reject) => {
            co (function * () {
                // reset user if undefined
                if (!User || User === undefined) {
                    User = false;
                }
                // check for acl
                if (!acl) {
                    return resolve (true);
                }
                // check logged in specific acl
                if ((!User && acl.test === false) || (User && acl.test === true)) {
                    return resolve (true);
                } else if ((User && acl.test === false) || (!User && acl.test === true)) {
                    return resolve (acl.fail || false);
                } else if (!User) {
                    return resolve (acl.fail || false);
                }

                // check and get user acl
                var userAcl = yield User.model ('acl');
                if (!userAcl) {
                    return resolve (acl.fail || false);
                }

                // check if user
                var can = false;
                // loop acl array
                for (var i = 0; i < userAcl.length; i++) {
                    // run acl test
                    var aclTest = userAcl[i].get ('value');

                    // check if all
                    if (aclTest === true) {
                        return resolve (true);
                    }

                    // loop individual acl
                    for (var x = 0; x < acl.test.length; x++) {
                        if (aclTest.indexOf (acl.test[x]) > -1) {
                            can = true;
                        }
                    }
                }

                // check if acl found
                if (can) {
                    return resolve (true);
                }

                // perform default resolve
                return resolve (acl.fail || false);
            });
        });
    }
}

/**
 * export acl class
 *
 * @type {acl}
 */
module.exports = new acl ();
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

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",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counte<commit_msg>Updated the readme<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

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",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return Math.floor(Math.random()*(max-min+1)+min);
}

function commit(t_offset, outFD, outFile, data, counter, length)
{
  if (counter < length)
  {
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    if (counter + step >= length) step = length - counter
    process.stdout.write("\033[2K Writing " + counter<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

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",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commi<commit_msg>Sprint complete<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

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",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit<|endoftext|>


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

var fs = require('fs');

// checks for available update and returns an instance
var defaults = require('lodash');
var pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json'));

require('update-notifier')({
  pkg: defaults(pkg, { version: '0.0.0' }),
}).notify();

require('./../lib/cli.js');
<commit_msg>fix error in lodash<commit_after>#! /usr/bin/env node
'use strict';

var fs = require('fs');

// checks for available update and returns an instance
var _ = require('lodash');
var pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json'));

require('update-notifier')({
  pkg: _.defaults(pkg, { version: '0.0.0' }),
}).notify();

require('./../lib/cli.js');
<|endoftext|>


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

var opts = require('nomnom').script('cfn-include').options({
    path: {
      position: 0,
      help: 'location of template. Either path to a local file, URL or file on an S3 bucket (e.g. s3://bucket-name/example.template)',
      required: true,
    },
    minimize: {
      help: 'minimize JSON output',
      default: false,
      flag: true,
      abbr: 'm',
    },
    validate: {
      help: 'validate compiled template',
      default: false,
      flag: true,
      abbr: 't',
    },
  }).parse(),
  path = require('path'),
  include = require('cfn-include'),
  Promise = require('bluebird');

var location, protocol = opts.path.match(/^\w+:\/\//);
if (protocol) location = opts.path;
else if (path.isAbsolute(opts.path)) location = 'file://' + opts.path;
else location = 'file://' + path.join(process.cwd(), opts.path);

include({
  url: location
}).then(function(template) {
  var promise = Promise.resolve();
  if (opts.validate) {
    var cfn = new(require('cfn-include/aws-sdk-proxy').CloudFormation)({
      region: 'us-east-1'
    });
    promise = Promise.promisify(cfn.validateTemplate).call(cfn, {
      TemplateBody: JSON.stringify(template),
    });
  }
  promise.then(function(res) {
    console.log(JSON.stringify(template, null, opts.minimize ? null : 2));
  }, function(err) {
    console.error('Validation failed:', err.message);
    process.exit(1);
  });
});
<commit_msg>ref #6, include metadata<commit_after>#!/usr/bin/env node

var _ = require('lodash'),
  exec = require('child_process').execSync,
  opts = require('nomnom').script('cfn-include').options({
    path: {
      position: 0,
      help: 'location of template. Either path to a local file, URL or file on an S3 bucket (e.g. s3://bucket-name/example.template)',
      required: true,
    },
    minimize: {
      help: 'minimize JSON output',
      default: false,
      flag: true,
      abbr: 'm',
    },
    validate: {
      help: 'validate compiled template',
      default: false,
      flag: true,
      abbr: 't',
    },
  }).parse(),
  path = require('path'),
  include = require('cfn-include'),
  Promise = require('bluebird');

var location, protocol = opts.path.match(/^\w+:\/\//);
if (protocol) location = opts.path;
else if (path.isAbsolute(opts.path)) location = 'file://' + opts.path;
else location = 'file://' + path.join(process.cwd(), opts.path);

include({
  url: location
}).then(function(template) {
  var promise = Promise.resolve();
  try {
    var stdout = exec('git log -n 1 --pretty=%H', {
      stdio: [0, 'pipe', 'ignore']
    }).toString().trim();
  } catch (e) {}
  _.defaultsDeep(template, {
    Metadata: {
      CfnInclude: {
        GitCommit: stdout,
        BuildDate: new Date().toISOString()
      }
    }
  });
  if (opts.validate) {
    var cfn = new(require('cfn-include/aws-sdk-proxy').CloudFormation)({
      region: 'us-east-1'
    });
    promise = Promise.promisify(cfn.validateTemplate).call(cfn, {
      TemplateBody: JSON.stringify(template),
    });
  }
  promise.then(function(res) {
    console.log(JSON.stringify(template, null, opts.minimize ? null : 2));
  }, function(err) {
    console.error('Validation failed:', err.message);
    process.exit(1);
  });
});
<|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",
  "AAAAAAAAAA<commit_msg>Fixed a typo<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",
  "AAAAAAAAAAA<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

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",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return <commit_msg>Incompatible dimensions found, Cthuhlu Error 666<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

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",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_time_hour * 3600)
    var commit_time_min = Math.floor(commit_time_rem / 60)
    var commit_time_sec = commit_time_rem - (commit_time_min * 60)
    console.info("Input file is %s Bytes, this will generate %s commits and take approximately %s hours %s minutes %s seconds", length, commit_count, commit_time_hour, commit_time_min, commit_time_sec)
    var t_offset = 0
    if (process.env.FAKETIME) {
      // 20% buffer, to reduce the likelihood of going in to the future
      t_offset = commit_time * -1.2;
      faketime(t_offset);
    }
    try {
      child_process.execFileSync('git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var counter = 0
    process.stdout.write("Queueing up the first commit...\r");
    var timeout;
    if (process.env.FAKETIME) {
      faketime(t_offset);
      timeout = 20;
    } else {
      timeout = randomIntFromInterval(0, max_sleep) * 1000
    }
    setTimeout(commit, timeout, t_offset, outFD, outFile, data, counter, length);
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [max_time_in_seconds] [step]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

function randomIntFromInterval(min,max)
{
   return M<|endoftext|>