<commit_before>/*jslint devel:true, stupid:true*/
/*global module, require*/

(function () {

    'use strict';

    var path = require('path'),
        fs = require('fs'),
        execSync = require("execSync"),
        mkdirp = require('mkdirp'),
        defaults = require('lodash.defaults'),
        cheerio = require("cheerio"),
        tidy = require('htmltidy').tidy;

    module.exports = function (params) {

        // Default options
        var options = defaults(params || {}, {

            // I/O
            source: 'logo.png',
            dest: 'images',

            // Icon Types
            android: true,
            apple: true,
            coast: true,
            favicons: true,
            firefox: true,
            windows: true,

            // Miscellaneous
            html: null,
            background: '#1d1d1d',
            tileBlackWhite: true,
            manifest: null,
            trueColor: false,
            logging: false,
            callback: null

        }),

            elements = [],
            files = [],
            opts = ["-background", '"' + options.background + '"', "-flatten"];

        // Print to the console.
        function print(message) {
            if (message && options.logging) {
                console.log(message);
            }
        }

        // Determine whether HTML is to be produced
        function writeHTML() {
            return options.html && options.html !== '';
        }

        // Execute external command
        function execute(cmd) {
            return execSync.exec(cmd);
        }

        // Convert image with Imagemagick
        function convert(args, name) {
            args.unshift('convert');
            var ret = execute(args.join(' '));
            if (ret.code === 127) {
                return print('You need to have ImageMagick installed in your PATH for this task to work.');
            }
            if (name) {
                print('Created ' + name);
            }
        }

        // Combine arguments into command
        function combine(src, dest, size, fname, opts) {
            var out = [src, "-resize", size].concat(opts);
            out.push(path.join(dest, fname));
            return out;
        }

        // Delete and rewrite HTML tags
        function writeTags(callback) {
            var $, html = '';
            if (options.html && fs.existsSync(options.source)) {
                $ = cheerio.load(fs.readFileSync(options.html));
                $('link[rel="shortcut icon"]').remove();
                $('link[rel="icon"]').remove();
                $('link[rel="apple-touch-icon"]').remove();
                $('meta').each(function () {
                    var name = $(this).attr('name');
                    if (name && (name === 'msapplication-TileImage' || name === 'msapplication-TileColor' || name.indexOf('msapplication-square') >= 0 || name === 'mobile-web-app-capable')) {
                        $(this).remove();
                    }
                });
                html = $.html().replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, '').replace(/\s+/g, ' ');
                if (html === '') {
                    $ = cheerio.load('');
                }
                if ($('head').length > 0) {
                    $("head").append(elements.join('\n'));
                } else {
                    print("HTML has no <head>.");
                }
                tidy($.html(), { wrap: 0, indent: true }, function (err, data) {
                    if (err) {
                        return print(err);
                    }
                    return callback(data);
                });
            } else {
                return callback(elements.join('\n'));
            }
        }

        // Make regular favicon files
        function makeFavicons() {
            [16, 32, 48].forEach(function (size) {
                var dimensions = size + 'x' + size,
                    ext = path.extname(options.source),
                    basename = path.basename(options.source, ext),
                    dirname = path.dirname(options.source),
                    p = path.join(dirname, basename + "." + dimensions + ext),
                    saveTo = path.join(options.dest, dimensions + '.png'),
                    src = options.source;
                if (fs.existsSync(p)) {
                    src = p;
                }
                convert([src, '-resize', dimensions, saveTo]);
                files.push(saveTo);
            });
            convert(files.concat([
                '-alpha on',
                '-background none',
                options.trueColor ? '' : '-bordercolor white -border 0 -colors 64',
                path.join(options.dest, 'favicon.ico')
            ]), 'favicon.ico');
            convert([options.source, '-resize', "64x64", path.join(options.dest, 'favicon.png')], 'favicon.png');
            elements.push('<link rel="shortcut icon" href="favicon.ico" />', '<link rel="icon" type="image/png" sizes="64x64" href="favicon.png" />');
        }

        // Make Apple touch icons
        function makeApple() {
            [57, 60, 72, 76, 144, 120, 144, 152].forEach(function (size) {
                var dimensions = size + 'x' + size,
                    rule = (size === 57 ? '' : '-' + dimensions),
                    name = 'apple-touch-icon' + rule + '.png',
                    command = combine(options.source, options.dest, dimensions, name, opts);
                convert(command, name);
                elements.push('<link rel="apple-touch-icon" sizes="' + dimensions + '" href="' + name + '" />');
            });
        }

        // Make Coast icon
        function makeCoast() {
            var dimensions = '228x228',
                name = 'coast-icon-' + dimensions + '.png',
                command = combine(options.source, options.dest, dimensions, name, opts);
            convert(command, name);
            elements.push('<link rel="icon" sizes="' + dimensions + '" href="' + name + '" />');
        }

        // Make Android homescreen icon
        function makeAndroid() {
            var dimensions = '196x196',
                name = 'homescreen-' + dimensions + '.png',
                command = combine(options.source, options.dest, dimensions, name, opts);
            convert(command, name);
            elements.push('<meta name="mobile-web-app-capable" value="yes" />', '<link rel="icon" sizes="' + dimensions + '" href="' + name + '" />');
        }

        // Make Firefox icons
        function makeFirefox() {
            var updateManifest = (options.manifest && options.manifest !== ''),
                contentsFirefox,
                contentFirefox;
            if (updateManifest) {
                contentsFirefox = (fs.existsSync(options.manifest)) ? fs.readFileSync(options.manifest) : '{}';
                contentFirefox = JSON.parse(contentsFirefox);
                contentFirefox.icons = {};
            }
            [16, 30, 32, 48, 60, 64, 90, 120, 128, 256].forEach(function (size) {
                var dimensions = size + 'x' + size,
                    name = "firefox-icon-" + dimensions + ".png";
                convert(combine(options.source, options.dest, dimensions, name, []), name);
                if (updateManifest) {
                    contentFirefox.icons[size] = name;
                }
            });
            if (updateManifest) {
                print('Updating Firefox manifest... ');
                fs.writeFileSync(options.manifest, JSON.stringify(contentFirefox, null, 2));
            }
        }

        // Make Windows 8 tile icons
        function makeWindows() {
            if (writeHTML()) {
                opts = [];
            }
            elements.push('<meta name="msapplication-TileColor" content="' + options.background + '" />');
            if (options.tileBlackWhite) {
                opts.push('-fuzz 100%', '-fill black', '-opaque red', '-fuzz 100%', '-fill black', '-opaque blue', '-fuzz 100%', '-fill white', '-opaque green');
            }
            [70, 144, 150, 310].forEach(function (size) {
                var dimensions = size + 'x' + size,
                    name = 'windows-tile-' + dimensions + '.png',
                    command = combine(options.source, options.dest, dimensions, name, opts);
                convert(command, name);
                if (size === 144) {
                    elements.push('<meta name="msapplication-TileImage" content="' + name + '" />');
                } else {
                    elements.push('<meta name="msapplication-square' + dimensions + 'logo" content="' + name + '" />');
                }
            });
        }

        // Delete temporary images
        function clean() {
            [16, 32, 48].forEach(function (size) {
                fs.unlinkSync(path.join(options.dest, size + 'x' + size + '.png'));
            });
        }

        // Create the appropriate icons
        function makeIcons() {
            if (options.favicons) { makeFavicons(); clean(); }
            if (options.apple) { makeApple(); }
            if (options.coast) { makeCoast(); }
            if (options.android) { makeAndroid(); }
            if (options.firefox) { makeFirefox(); }
            if (options.windows) { makeWindows(); }
        }

        // Initialise
        function init() {
            var html;
            if (!fs.existsSync(options.dest) || !fs.lstatSync(options.dest).isDirectory()) {
                mkdirp(options.dest);
            }
            makeIcons();
            writeTags(function (data) {
                html = data;
            });
            if (writeHTML()) {
                print('Updating HTML... ');
                fs.writeFileSync(options.html, html);
            }
            if (options.callback) {
                return options.callback('Generated favions', html);
            }
        }

        init();

    };

}());
<commit_msg>Check if temp files exist before removing<commit_after>/*jslint devel:true, stupid:true*/
/*global module, require*/

(function () {

    'use strict';

    var path = require('path'),
        fs = require('fs'),
        execSync = require("execSync"),
        mkdirp = require('mkdirp'),
        defaults = require('lodash.defaults'),
        cheerio = require("cheerio"),
        tidy = require('htmltidy').tidy;

    module.exports = function (params) {

        // Default options
        var options = defaults(params || {}, {

            // I/O
            source: 'logo.png',
            dest: 'images',

            // Icon Types
            android: true,
            apple: true,
            coast: true,
            favicons: true,
            firefox: true,
            windows: true,

            // Miscellaneous
            html: null,
            background: '#1d1d1d',
            tileBlackWhite: true,
            manifest: null,
            trueColor: false,
            logging: false,
            callback: null

        }),

            elements = [],
            files = [],
            opts = ["-background", '"' + options.background + '"', "-flatten"];

        // Print to the console.
        function print(message) {
            if (message && options.logging) {
                console.log(message);
            }
        }

        // Determine whether HTML is to be produced
        function writeHTML() {
            return options.html && options.html !== '';
        }

        // Execute external command
        function execute(cmd) {
            return execSync.exec(cmd);
        }

        // Convert image with Imagemagick
        function convert(args, name) {
            args.unshift('convert');
            var ret = execute(args.join(' '));
            if (ret.code === 127) {
                return print('You need to have ImageMagick installed in your PATH for this task to work.');
            }
            if (name) {
                print('Created ' + name);
            }
        }

        // Combine arguments into command
        function combine(src, dest, size, fname, opts) {
            var out = [src, "-resize", size].concat(opts);
            out.push(path.join(dest, fname));
            return out;
        }

        // Delete and rewrite HTML tags
        function writeTags(callback) {
            var $, html = '';
            if (options.html && fs.existsSync(options.source)) {
                $ = cheerio.load(fs.readFileSync(options.html));
                $('link[rel="shortcut icon"]').remove();
                $('link[rel="icon"]').remove();
                $('link[rel="apple-touch-icon"]').remove();
                $('meta').each(function () {
                    var name = $(this).attr('name');
                    if (name && (name === 'msapplication-TileImage' || name === 'msapplication-TileColor' || name.indexOf('msapplication-square') >= 0 || name === 'mobile-web-app-capable')) {
                        $(this).remove();
                    }
                });
                html = $.html().replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, '').replace(/\s+/g, ' ');
                if (html === '') {
                    $ = cheerio.load('');
                }
                if ($('head').length > 0) {
                    $("head").append(elements.join('\n'));
                } else {
                    print("HTML has no <head>.");
                }
                tidy($.html(), { wrap: 0, indent: true }, function (err, data) {
                    if (err) {
                        return print(err);
                    }
                    return callback(data);
                });
            } else {
                return callback(elements.join('\n'));
            }
        }

        // Make regular favicon files
        function makeFavicons() {
            [16, 32, 48].forEach(function (size) {
                var dimensions = size + 'x' + size,
                    ext = path.extname(options.source),
                    basename = path.basename(options.source, ext),
                    dirname = path.dirname(options.source),
                    p = path.join(dirname, basename + "." + dimensions + ext),
                    saveTo = path.join(options.dest, dimensions + '.png'),
                    src = options.source;
                if (fs.existsSync(p)) {
                    src = p;
                }
                convert([src, '-resize', dimensions, saveTo]);
                files.push(saveTo);
            });
            convert(files.concat([
                '-alpha on',
                '-background none',
                options.trueColor ? '' : '-bordercolor white -border 0 -colors 64',
                path.join(options.dest, 'favicon.ico')
            ]), 'favicon.ico');
            convert([options.source, '-resize', "64x64", path.join(options.dest, 'favicon.png')], 'favicon.png');
            elements.push('<link rel="shortcut icon" href="favicon.ico" />', '<link rel="icon" type="image/png" sizes="64x64" href="favicon.png" />');
        }

        // Make Apple touch icons
        function makeApple() {
            [57, 60, 72, 76, 144, 120, 144, 152].forEach(function (size) {
                var dimensions = size + 'x' + size,
                    rule = (size === 57 ? '' : '-' + dimensions),
                    name = 'apple-touch-icon' + rule + '.png',
                    command = combine(options.source, options.dest, dimensions, name, opts);
                convert(command, name);
                elements.push('<link rel="apple-touch-icon" sizes="' + dimensions + '" href="' + name + '" />');
            });
        }

        // Make Coast icon
        function makeCoast() {
            var dimensions = '228x228',
                name = 'coast-icon-' + dimensions + '.png',
                command = combine(options.source, options.dest, dimensions, name, opts);
            convert(command, name);
            elements.push('<link rel="icon" sizes="' + dimensions + '" href="' + name + '" />');
        }

        // Make Android homescreen icon
        function makeAndroid() {
            var dimensions = '196x196',
                name = 'homescreen-' + dimensions + '.png',
                command = combine(options.source, options.dest, dimensions, name, opts);
            convert(command, name);
            elements.push('<meta name="mobile-web-app-capable" value="yes" />', '<link rel="icon" sizes="' + dimensions + '" href="' + name + '" />');
        }

        // Make Firefox icons
        function makeFirefox() {
            var updateManifest = (options.manifest && options.manifest !== ''),
                contentsFirefox,
                contentFirefox;
            if (updateManifest) {
                contentsFirefox = (fs.existsSync(options.manifest)) ? fs.readFileSync(options.manifest) : '{}';
                contentFirefox = JSON.parse(contentsFirefox);
                contentFirefox.icons = {};
            }
            [16, 30, 32, 48, 60, 64, 90, 120, 128, 256].forEach(function (size) {
                var dimensions = size + 'x' + size,
                    name = "firefox-icon-" + dimensions + ".png";
                convert(combine(options.source, options.dest, dimensions, name, []), name);
                if (updateManifest) {
                    contentFirefox.icons[size] = name;
                }
            });
            if (updateManifest) {
                print('Updating Firefox manifest... ');
                fs.writeFileSync(options.manifest, JSON.stringify(contentFirefox, null, 2));
            }
        }

        // Make Windows 8 tile icons
        function makeWindows() {
            if (writeHTML()) {
                opts = [];
            }
            elements.push('<meta name="msapplication-TileColor" content="' + options.background + '" />');
            if (options.tileBlackWhite) {
                opts.push('-fuzz 100%', '-fill black', '-opaque red', '-fuzz 100%', '-fill black', '-opaque blue', '-fuzz 100%', '-fill white', '-opaque green');
            }
            [70, 144, 150, 310].forEach(function (size) {
                var dimensions = size + 'x' + size,
                    name = 'windows-tile-' + dimensions + '.png',
                    command = combine(options.source, options.dest, dimensions, name, opts);
                convert(command, name);
                if (size === 144) {
                    elements.push('<meta name="msapplication-TileImage" content="' + name + '" />');
                } else {
                    elements.push('<meta name="msapplication-square' + dimensions + 'logo" content="' + name + '" />');
                }
            });
        }

        // Delete temporary images
        function clean() {
            [16, 32, 48].forEach(function (size) {
                var file = path.join(options.dest, size + 'x' + size + '.png');
                if (fs.existsSync(file)) {
                    fs.unlinkSync(file);
                }
            });
        }

        // Create the appropriate icons
        function makeIcons() {
            if (options.favicons) { makeFavicons(); clean(); }
            if (options.apple) { makeApple(); }
            if (options.coast) { makeCoast(); }
            if (options.android) { makeAndroid(); }
            if (options.firefox) { makeFirefox(); }
            if (options.windows) { makeWindows(); }
        }

        // Initialise
        function init() {
            var html;
            if (!fs.existsSync(options.dest) || !fs.lstatSync(options.dest).isDirectory()) {
                mkdirp(options.dest);
            }
            makeIcons();
            writeTags(function (data) {
                html = data;
            });
            if (writeHTML()) {
                print('Updating HTML... ');
                fs.writeFileSync(options.html, html);
            }
            if (options.callback) {
                return options.callback('Generated favions', html);
            }
        }

        init();

    };

}());
<|endoftext|>


<commit_before>app.controller("SigninController", ["$scope", "$uibModal", "$window", "AlertService", "SigninService", "GetCurrentService", function($scope, $uibModal, $window, AlertService, SigninService, GetCurrentService) {
	$scope.signinData = {};
	$scope.alerts = [];

	$scope.openSigninModal = function() {
		var signinModalInstance = $uibModal.open({
			templateUrl: "../../js/views/signin-modal.php",
			controller: "SigninModal",
			resolve: {
				signinData: function() {
					return ($scope.signinData);
				}
			}
		});
		signinModalInstance.result.then(function(signinData) {
			$scope.signinData = signinData;
			SigninService.signin(signinData)
				.then(function(result) {
					if(result.status === 200) {
						AlertService.addAlert({type: "success", msg: result.message});
						//three potential cases here: receiving volunteer, receiving admin, giving admin
						//Receiving volunteer redirects to the listing page, the other two go to their respective landing pages
						GetCurrentService.fetchVolCurrent()
							.then(function(result) {
								if(result.data.status === 200) {
									if(result.data.data.volIsAdmin === true) {
										GetCurrentService.fetchOrgCurrent()
											.then(function(result) {
												if(result.data.status === 200) {
													if(result.data.data.orgType === "G") {
														//giving admin
														$window.location.assign("../../php/template/login-landing-giver.php")
													} else if(result.data.data.orgType === "R") {
														//receiving admin
														$window.location.assign("../../php/template/login-landing-page.php")
													}
												} else {
													AlertService.addAlert({type: "danger", msg: result.message});
												}
											});
									} else {
										//receiving volunteer
										$window.location.assign("../../php/template/listing-receive-view.php")
									}
								} else {
									AlertService.addAlert({type: "danger", msg: result.message});
								}
							});

					} else {
						AlertService.addAlert({type: "danger", msg: result.message});
					}
				});
		}, function() {
			$scope.signinData = {};
		});
	};
}]);<commit_msg>signin-controller all replys to results https://app.asana.com/0/60993780339172/70723740973486<commit_after>app.controller("SigninController", ["$scope", "$uibModal", "$window", "AlertService", "SigninService", "GetCurrentService", function($scope, $uibModal, $window, AlertService, SigninService, GetCurrentService) {
	$scope.signinData = {};
	$scope.alerts = [];

	$scope.openSigninModal = function() {
		var signinModalInstance = $uibModal.open({
			templateUrl: "../../js/views/signin-modal.php",
			controller: "SigninModal",
			resolve: {
				signinData: function() {
					return ($scope.signinData);
				}
			}
		});
		signinModalInstance.result.then(function(signinData) {
			$scope.signinData = signinData;
			SigninService.signin(signinData)
				.then(function(result) {
					if(result.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
						//three potential cases here: receiving volunteer, receiving admin, giving admin
						//Receiving volunteer redirects to the listing page, the other two go to their respective landing pages
						GetCurrentService.fetchVolCurrent()
							.then(function(result) {
								if(result.data.status === 200) {
									if(result.data.data.volIsAdmin === true) {
										GetCurrentService.fetchOrgCurrent()
											.then(function(result) {
												if(result.data.status === 200) {
													if(result.data.data.orgType === "G") {
														//giving admin
														$window.location.assign("../../php/template/login-landing-giver.php")
													} else if(result.data.data.orgType === "R") {
														//receiving admin
														$window.location.assign("../../php/template/login-landing-page.php")
													}
												} else {
													$scope.alerts[0] = {type: "danger", msg: result.data.message};
												}
											});
									} else {
										//receiving volunteer
										$window.location.assign("../../php/template/listing-receive-view.php")
									}
								} else {
									$scope.alerts[0] = {type: "danger", msg: result.data.message};
								}
							});

					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});
		}, function() {
			$scope.signinData = {};
		});
	};
}]);<|endoftext|>


<commit_before>/*jshint node: true, -W106 */
'use strict';

/*
* Name : filterConditionModel.js
* Module : Lib::DataTier::FilterConditionModel
* Location : /lib/dataTier/flow
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-14   Matteo Furlan    Initial code
* =========================================================
*/

var HF = require('../helpers/functionHelper.js');

function FilterConditionModel(cond) {
	if(cond===undefined || typeof cond !== 'string' || cond.trim().length<3){
		return 611;
	}
	var parsed=HF.parseCondition(cond);
	if(typeof parsed === 'number'){
		return 612;
	}
	this._key=parsed.key;
	this._operator=parsed.operator;
	this._value=parsed.value;
}
/*
FilterConditionModel.prototype={
	validateRecord: function(record){
		switch (this._operator) {
			case ">":
				return record[this._key]>this._value;
				break;
			case ">=":
				//
				break;
		}
		return false;

};}*/
module.exports = FilterConditionModel;<commit_msg>test again<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : filterConditionModel.js
* Module : Lib::DataTier::FilterConditionModel
* Location : /lib/dataTier/flow
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-14   Matteo Furlan    Initial code
* =========================================================
*/

var HF = require('../helpers/functionHelper.js');

function FilterConditionModel(cond) {
	if(cond===undefined || typeof cond !== 'string' || cond.trim().length<3){
		return 611;
	}
	var parsed=HF.parseCondition(cond);
	if(typeof parsed === 'number'){
		return 612;
	}
	this._key=parsed.key;
	this._operator=parsed.operator;
	this._value=parsed.value;
}
/*
FilterConditionModel.prototype={
	validateRecord: function(record){
		switch (this._operator) {
			case ">":
				return record[this._key]>this._value;
				break;
			case ">=":
				//
				break;
		}
		return false;

};}*/
module.exports = FilterConditionModel;<|endoftext|>


<commit_before>'use strict';

var redis = require('redis'),
    coRedis = require('co-redis'),
    koa = require('koa');

var app = koa(),
    client  = redis.createClient(
      process.env.REDIS_PORT,
      process.env.REDIS_HOST
    ),
    dbCo = coRedis(client);

if (process.env.REDIS_SECRET) {
  client.auth(process.env.REDIS_SECRET);
}

client.on('error', function (err) {
  console.log('Redis client error: ' + err);
});

app.use(function* () {

  var indexkey;

  if (this.request.query.index_key) {
    indexkey = process.env.APP_NAME +':'+ this.request.query.index_key;
  } else {
    indexkey = yield dbCo.get(process.env.APP_NAME +':current');
  }
  var index = yield dbCo.get(indexkey);

  if (index) {
    this.body = index;
  } else {
    this.status = 404;
  }
});

app.listen(process.env.PORT || 3000);
<commit_msg>Fix ember-cli-deploy-redis v 0.5 bug<commit_after>'use strict';

var redis = require('redis'),
    coRedis = require('co-redis'),
    koa = require('koa');

var app = koa(),
    client  = redis.createClient(
      process.env.REDIS_PORT,
      process.env.REDIS_HOST
    ),
    dbCo = coRedis(client);

if (process.env.REDIS_SECRET) {
  client.auth(process.env.REDIS_SECRET);
}

client.on('error', function (err) {
  console.log('Redis client error: ' + err);
});

app.use(function* () {

  var indexkey;

  if (this.request.query.index_key) {
    indexkey = process.env.APP_NAME +':'+ this.request.query.index_key;
  } else {
    indexkey = yield dbCo.get(process.env.APP_NAME +':current');
    indexkey = process.env.APP_NAME + ':' + indexkey;
  }
  var index = yield dbCo.get(indexkey);

  if (index) {
    this.body = index;
  } else {
    this.status = 404;
  }
});

app.listen(process.env.PORT || 3000);
<|endoftext|>


<commit_before>var request = require('request');
var events = require('events');
var address = require('network-address');
var qs = require('querystring');
var roundround = require('roundround');

request = request.defaults({
	timeout: 10000
});

var noop = function() {};

var registry = function(url) {
	if (!url) url = '127.0.0.1';

	var parsed = url.match(/^([^:]+:\/\/)?([^\/]+)(?:\/([^\?]+))?(?:\?(.+))?$/);
	if (!parsed) throw new Error('Invalid connection string');

	var protocol = parsed[1] || 'http://';
	var ns = (parsed[3] || '').replace(/^\//, '').replace(/([^\/])$/, '$1/');
	var urls = parsed[2].split(/,\s*/).map(function(url) {
		if (url.indexOf(':') === -1) url += ':4001';
		return protocol+url;
	});

	var that = new events.EventEmitter();
	var services = [];
	var prev = urls.join(', ');

	var req = function(path, opts, cb) {
		var tries = urls.length;
		var offset = (Math.random() * urls.length) | 0;
		var next = roundround(urls, offset);

		var loop = function() {
			request(opts.location || (next()+path), opts, function onresponse(err, response) {
				if (err) {
					if (opts.location) delete opts.location;
					if (--tries <= 0) return cb(err);
					return setTimeout(loop, 1000);
				}

				if (response.statusCode === 307) return request(opts.location = response.headers.location, opts, onresponse);
				if (response.statusCode === 404) return cb();
				if (response.statusCode > 299) return cb(new Error('bad status code ('+response.statusCode+')'));

				cb(null, response.body);
			});
		};

		loop();
	};

	var refresh = function() {
		req('/v2/machines', {}, function(err, body) {
			if (err || !body || prev === body) return setTimeout(refresh, 60000).unref();
			prev = body;
			urls = body.split(/,\s*/);
			that.emit('machines', urls);
			setTimeout(refresh, 60000).unref();
		});
	};

	refresh();

	that.join = function(name, service, cb) {
		if (typeof service === 'number') service = {port:service};
		if (typeof service === 'function') return that.join(name, null, service);
		if (!service) service = {};

		service.name = name;
		service.hostname = service.hostname || address();
		service.host = service.port ? service.hostname+':'+service.port : service.hostname;
		service.url = service.url || (service.protocol || 'http')+'://'+service.host;

		var path = '/v2/keys/services/'+ns+name+'/'+service.url.replace(/[:\/]+/g, '-');
		var body = qs.stringify({
			value:JSON.stringify(service),
			ttl:10
		});

		service.key = path;
		services.push(service);

		var opts = {
			method: 'PUT',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
			},
			body: body
		};

		var ping = function(cb) {
			req(path, opts, function(err, body) {
				cb(err);
			});
		};

		var keepAlive = function() {
			ping(function(err) {
				service.timeout = setTimeout(keepAlive, err ? 15000 : 5000);
				service.timeout.unref();
			});
		};

		ping(function(err) {
			service.timeout = setTimeout(keepAlive, 5000);
			service.timeout.unref();
			if (cb) cb(err, service);
		});
	};

	that.leave = function(name, cb) {
		if (typeof name === 'function') return that.leave(null, name);
		if (!cb) cb = noop;

		var list = services.filter(function(service) {
			return !name || service.name === name;
		});

		if (!list.length) return cb();

		var loop = function() {
			if (!list.length) return cb();
			req(list.shift().key, {method:'DELETE'}, loop);
		};

		loop();
	};

	var flatten = function(nodes) {
		var result = [];
		nodes.forEach(function visit(node) {
			if (node.nodes) return node.nodes.forEach(visit);
			if (node.value) result.push(node.value);
		});
		return result;
	};

	that.list = function(name, cb) {
		if (typeof name === 'function') return that.list(null, name);
		req('/v2/keys/services/'+ns+(name || ''), {json:true, qs:{recursive:true}}, function(err, body) {
			if (err) return cb(err);
			if (!body || !body.node || !body.node.nodes) return cb(null, []);

			var vals = [];
			flatten(body.node.nodes).forEach(function(node) {
				try {
					vals.push(JSON.parse(node));
				} catch (err) {
					// do nothing ...
				}
			});

			cb(null, vals);
		});
	};

	that.lookup = function(name, cb) {
		if (typeof name === 'function') return that.lookup(null, name);
		req('/v2/keys/services/'+ns+(name || ''), {json:true, qs:{recursive:true}}, function(err, body) {
			if (err) return cb(err);
			if (!body || !body.node || !body.node.nodes) return cb();

			var nodes = flatten(body.node.nodes);
			if (!nodes.length) return cb();

			var node = nodes[(Math.random() * nodes.length) | 0];
			if (!node) return cb();

			try {
				node = JSON.parse(node);
			} catch (err) {
				return cb(err);
			}

			cb(null, node);
		});
	};

	return that;
};

module.exports = registry;<commit_msg>forwarding clone instead<commit_after>var request = require('request');
var events = require('events');
var address = require('network-address');
var qs = require('querystring');
var roundround = require('roundround');

request = request.defaults({
	timeout: 10000
});

var noop = function() {};

var registry = function(url) {
	if (!url) url = '127.0.0.1';

	var parsed = url.match(/^([^:]+:\/\/)?([^\/]+)(?:\/([^\?]+))?(?:\?(.+))?$/);
	if (!parsed) throw new Error('Invalid connection string');

	var protocol = parsed[1] || 'http://';
	var ns = (parsed[3] || '').replace(/^\//, '').replace(/([^\/])$/, '$1/');
	var urls = parsed[2].split(/,\s*/).map(function(url) {
		if (url.indexOf(':') === -1) url += ':4001';
		return protocol+url;
	});

	var that = new events.EventEmitter();
	var services = [];
	var prev = urls.join(', ');

	var req = function(path, opts, cb) {
		var tries = urls.length;
		var offset = (Math.random() * urls.length) | 0;
		var next = roundround(urls, offset);

		var loop = function() {
			request(opts.location || (next()+path), opts, function onresponse(err, response) {
				if (err) {
					if (opts.location) delete opts.location;
					if (--tries <= 0) return cb(err);
					return setTimeout(loop, 1000);
				}

				if (response.statusCode === 307) return request(opts.location = response.headers.location, opts, onresponse);
				if (response.statusCode === 404) return cb();
				if (response.statusCode > 299) return cb(new Error('bad status code ('+response.statusCode+')'));

				cb(null, response.body);
			});
		};

		loop();
	};

	var refresh = function() {
		req('/v2/machines', {}, function(err, body) {
			if (err || !body || prev === body) return setTimeout(refresh, 60000).unref();
			prev = body;
			urls = body.split(/,\s*/);
			that.emit('machines', urls);
			setTimeout(refresh, 60000).unref();
		});
	};

	refresh();

	that.join = function(name, service, cb) {
		if (typeof service === 'number') service = {port:service};
		if (typeof service === 'function') return that.join(name, null, service);
		if (!service) service = {};

		service.name = name;
		service.hostname = service.hostname || address();
		service.host = service.port ? service.hostname+':'+service.port : service.hostname;
		service.url = service.url || (service.protocol || 'http')+'://'+service.host;

		var path = '/v2/keys/services/'+ns+name+'/'+service.url.replace(/[:\/]+/g, '-');
		var body = qs.stringify({
			value:JSON.stringify(service),
			ttl:10
		});

		var clone = {};
		Object.keys(service).forEach(function(key) {
			clone[key] = service[key];
		});

		service.key = path;
		services.push(service);

		var opts = {
			method: 'PUT',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
			},
			body: body
		};

		var ping = function(cb) {
			req(path, opts, function(err, body) {
				cb(err);
			});
		};

		var keepAlive = function() {
			ping(function(err) {
				service.timeout = setTimeout(keepAlive, err ? 15000 : 5000);
				service.timeout.unref();
			});
		};

		ping(function(err) {
			service.timeout = setTimeout(keepAlive, 5000);
			service.timeout.unref();
			if (cb) cb(err, clone);
		});
	};

	that.leave = function(name, cb) {
		if (typeof name === 'function') return that.leave(null, name);
		if (!cb) cb = noop;

		var list = services.filter(function(service) {
			return !name || service.name === name;
		});

		if (!list.length) return cb();

		var loop = function() {
			if (!list.length) return cb();
			req(list.shift().key, {method:'DELETE'}, loop);
		};

		loop();
	};

	var flatten = function(nodes) {
		var result = [];
		nodes.forEach(function visit(node) {
			if (node.nodes) return node.nodes.forEach(visit);
			if (node.value) result.push(node.value);
		});
		return result;
	};

	that.list = function(name, cb) {
		if (typeof name === 'function') return that.list(null, name);
		req('/v2/keys/services/'+ns+(name || ''), {json:true, qs:{recursive:true}}, function(err, body) {
			if (err) return cb(err);
			if (!body || !body.node || !body.node.nodes) return cb(null, []);

			var vals = [];
			flatten(body.node.nodes).forEach(function(node) {
				try {
					vals.push(JSON.parse(node));
				} catch (err) {
					// do nothing ...
				}
			});

			cb(null, vals);
		});
	};

	that.lookup = function(name, cb) {
		if (typeof name === 'function') return that.lookup(null, name);
		req('/v2/keys/services/'+ns+(name || ''), {json:true, qs:{recursive:true}}, function(err, body) {
			if (err) return cb(err);
			if (!body || !body.node || !body.node.nodes) return cb();

			var nodes = flatten(body.node.nodes);
			if (!nodes.length) return cb();

			var node = nodes[(Math.random() * nodes.length) | 0];
			if (!node) return cb();

			try {
				node = JSON.parse(node);
			} catch (err) {
				return cb(err);
			}

			cb(null, node);
		});
	};

	return that;
};

module.exports = registry;<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
const childProcess = require('child_process');

function createFolder(logger, folder) {
  return new Promise((resolve, reject) => {
    logger.debug({ folder }, 'Create folder');
    fs.mkdir(folder, error => (error ? reject(error) : resolve()));
  });
}

function cloneRepo(logger, cwd, repo) {
  return new Promise((resolve, reject) => {
    logger.info({ cwd, repo }, 'Git clone repo start');

    const clone = childProcess.spawn('git', ['clone', repo], { cwd });
    clone.on('error', reject);
    clone.on('exit', (code) => {
      if (code) {
        logger.error({ code }, 'Git clone failed');
        reject(`Clone ${repo} exit code with ${code}`);
      } else {
        logger.info('Git clone successfully');
        resolve();
      }
    });
  });
}

function cloneRepos(logger, workingFolder, repos) {
  return cloneRepo(logger.child({ _cloneRepos: ['cloneRepo', 0] }), workingFolder, repos[0]); // TODO multiple repos
}

function runScript(logger, cwd, script) {
  return new Promise((resolve, reject) => {
    logger.info({ cwd, script }, 'Start to run script under working directory');
    const exec = childProcess.exec(script, { cwd });
    exec.stdout.pipe(process.stdout);
    exec.stderr.pipe(process.stderr);
    exec.on('error', reject);
    exec.on('exit', (code) => {
      if (code) {
        logger.error('Run script failed');
        reject(`Execute script exit with ${code}`);
      } else {
        logger.info('Run script successfully');
        resolve();
      }
    });
  });
}

function runScripts(logger, workingFolder, scripts) {
  let lastScript = Promise.resolve();

  scripts.forEach((script, index) => {
    const childLogger = logger.child({ _runScripts: ['runScript', index] });
    const patchedScript = script.replace(/\$\{HOST_DIR\}/g, JSON.stringify(process.cwd()));
    lastScript = lastScript.then(() => runScript(childLogger, workingFolder, patchedScript));
  });

  return lastScript;
}

function runBatch(logger, workingFolder, packageName, batch) {
  const repo = batch.repo;
  logger.info({ repo }, 'Run batch for repo');

  const scripts = batch.scripts;
  logger.debug({ scripts }, 'Scripts from batch');

  const fullScripts = [`npm link ${packageName}`, 'npm install'].concat(scripts);
  logger.trace({ fullScripts }, 'Full scripts after patch');

  const repoName = path.basename(repo);
  const cwd = path.resolve(workingFolder, repoName);
  logger.info({ cwd }, 'Working directory for batch');

  return runScripts(logger.child({ _runBatch: 'runScripts' }), cwd, fullScripts);
}

function runBatches(logger, workingFolder, packageName, batches) {
  return runBatch(logger.child({ _runBatches: ['runBatch', 0] }), workingFolder, packageName, batches[0]); // TODO multiple repos
}

function npmLink(logger, cwd) {
  return runScript(logger.child({ _npmLink: 'runScript' }), cwd, 'npm link');
}

function npmUnlink(logger, cwd) {
  return runScript(logger.child({ _npmUnlink: 'runScript' }), cwd, 'npm unlink');
}

function dependentBuild(logger, folderPath) {
  const cwd = process.cwd();
  logger.info({ cwd }, 'Current working directory');

  const rootFolder = path.resolve(cwd, folderPath);
  logger.debug({ rootFolder }, 'Resolved root directory');

  // TODO optimize on readFileSync
  const packageFilePath = path.resolve(rootFolder, 'package.json');
  const packageName = JSON.parse(fs.readFileSync(packageFilePath)).name;
  logger.info({ packageName }, 'Package name');

  const workingFolder = path.resolve(rootFolder, 'dependent-build');
  logger.debug({ workingFolder }, 'Dependent-build folder');

  const configPath = path.resolve(rootFolder, 'dependent-build.yml');
  logger.info({ configPath }, 'Dependent-build configuration path');

  const configContent = fs.readFileSync(configPath, 'utf-8');
  logger.trace({ configContent }, 'Dependent-build configuration file content');

  const config = yaml.safeLoad(configContent);
  logger.debug({ config }, 'Dependent-build configuration');

  const repos = Object.keys(config);
  logger.trace({ repos }, 'Got dependent repos');

  const batches = repos.map(repo => ({ repo, scripts: config[repo] }));
  logger.trace({ batches }, 'Arrange config to batches (repo-scripts pairs)');

  return createFolder(logger.child({ _dependentBuild: 'createFolder' }), workingFolder)
    .then(() => npmLink(logger.child({ _dependentBuild: 'npmLink' }), workingFolder))
    .then(() => cloneRepos(logger.child({ _dependentBuild: 'cloneRepos' }), workingFolder, repos))
    .then(() => runBatches(logger.child({ _dependentBuild: 'runBatches' }), workingFolder, packageName, batches))
    .then(() => npmUnlink(logger.child({ _dependentBuild: 'npmUnlink' }), workingFolder),
      e => npmUnlink(logger.child({ _dependentBuild: 'npmUnlink' }), workingFolder).then(() => { throw e; }));
}

module.exports = dependentBuild;
<commit_msg>Use `var` instead of `let` for one case.<commit_after>const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
const childProcess = require('child_process');

function createFolder(logger, folder) {
  return new Promise((resolve, reject) => {
    logger.debug({ folder }, 'Create folder');
    fs.mkdir(folder, error => (error ? reject(error) : resolve()));
  });
}

function cloneRepo(logger, cwd, repo) {
  return new Promise((resolve, reject) => {
    logger.info({ cwd, repo }, 'Git clone repo start');

    const clone = childProcess.spawn('git', ['clone', repo], { cwd });
    clone.on('error', reject);
    clone.on('exit', (code) => {
      if (code) {
        logger.error({ code }, 'Git clone failed');
        reject(`Clone ${repo} exit code with ${code}`);
      } else {
        logger.info('Git clone successfully');
        resolve();
      }
    });
  });
}

function cloneRepos(logger, workingFolder, repos) {
  return cloneRepo(logger.child({ _cloneRepos: ['cloneRepo', 0] }), workingFolder, repos[0]); // TODO multiple repos
}

function runScript(logger, cwd, script) {
  return new Promise((resolve, reject) => {
    logger.info({ cwd, script }, 'Start to run script under working directory');
    const exec = childProcess.exec(script, { cwd });
    exec.stdout.pipe(process.stdout);
    exec.stderr.pipe(process.stderr);
    exec.on('error', reject);
    exec.on('exit', (code) => {
      if (code) {
        logger.error('Run script failed');
        reject(`Execute script exit with ${code}`);
      } else {
        logger.info('Run script successfully');
        resolve();
      }
    });
  });
}

function runScripts(logger, workingFolder, scripts) {
  var lastScript = Promise.resolve(); // eslint-disable-line no-var

  scripts.forEach((script, index) => {
    const childLogger = logger.child({ _runScripts: ['runScript', index] });
    const patchedScript = script.replace(/\$\{HOST_DIR\}/g, JSON.stringify(process.cwd()));
    lastScript = lastScript.then(() => runScript(childLogger, workingFolder, patchedScript));
  });

  return lastScript;
}

function runBatch(logger, workingFolder, packageName, batch) {
  const repo = batch.repo;
  logger.info({ repo }, 'Run batch for repo');

  const scripts = batch.scripts;
  logger.debug({ scripts }, 'Scripts from batch');

  const fullScripts = [`npm link ${packageName}`, 'npm install'].concat(scripts);
  logger.trace({ fullScripts }, 'Full scripts after patch');

  const repoName = path.basename(repo);
  const cwd = path.resolve(workingFolder, repoName);
  logger.info({ cwd }, 'Working directory for batch');

  return runScripts(logger.child({ _runBatch: 'runScripts' }), cwd, fullScripts);
}

function runBatches(logger, workingFolder, packageName, batches) {
  return runBatch(logger.child({ _runBatches: ['runBatch', 0] }), workingFolder, packageName, batches[0]); // TODO multiple repos
}

function npmLink(logger, cwd) {
  return runScript(logger.child({ _npmLink: 'runScript' }), cwd, 'npm link');
}

function npmUnlink(logger, cwd) {
  return runScript(logger.child({ _npmUnlink: 'runScript' }), cwd, 'npm unlink');
}

function dependentBuild(logger, folderPath) {
  const cwd = process.cwd();
  logger.info({ cwd }, 'Current working directory');

  const rootFolder = path.resolve(cwd, folderPath);
  logger.debug({ rootFolder }, 'Resolved root directory');

  // TODO optimize on readFileSync
  const packageFilePath = path.resolve(rootFolder, 'package.json');
  const packageName = JSON.parse(fs.readFileSync(packageFilePath)).name;
  logger.info({ packageName }, 'Package name');

  const workingFolder = path.resolve(rootFolder, 'dependent-build');
  logger.debug({ workingFolder }, 'Dependent-build folder');

  const configPath = path.resolve(rootFolder, 'dependent-build.yml');
  logger.info({ configPath }, 'Dependent-build configuration path');

  const configContent = fs.readFileSync(configPath, 'utf-8');
  logger.trace({ configContent }, 'Dependent-build configuration file content');

  const config = yaml.safeLoad(configContent);
  logger.debug({ config }, 'Dependent-build configuration');

  const repos = Object.keys(config);
  logger.trace({ repos }, 'Got dependent repos');

  const batches = repos.map(repo => ({ repo, scripts: config[repo] }));
  logger.trace({ batches }, 'Arrange config to batches (repo-scripts pairs)');

  return createFolder(logger.child({ _dependentBuild: 'createFolder' }), workingFolder)
    .then(() => npmLink(logger.child({ _dependentBuild: 'npmLink' }), workingFolder))
    .then(() => cloneRepos(logger.child({ _dependentBuild: 'cloneRepos' }), workingFolder, repos))
    .then(() => runBatches(logger.child({ _dependentBuild: 'runBatches' }), workingFolder, packageName, batches))
    .then(() => npmUnlink(logger.child({ _dependentBuild: 'npmUnlink' }), workingFolder),
      e => npmUnlink(logger.child({ _dependentBuild: 'npmUnlink' }), workingFolder).then(() => { throw e; }));
}

module.exports = dependentBuild;
<|endoftext|>


<commit_before>'use strict'

module.exports = [
  '0.0.1'
, '0.0.2'
, '0.0.3'
, '0.0.4'
, '0.0.5'
, '0.0.6'
, '0.1.0'
, '0.1.1'
, '0.1.2'
, '0.1.3'
, '0.1.4'
, '0.1.5'
, '0.1.6'
, '0.1.7'
, '0.1.8'
, '0.1.9'
, '0.1.10'
, '0.1.11'
, '0.1.12'
, '0.1.13'
, '0.1.14'
, '0.1.15'
, '0.1.16'
, '0.1.17'
, '0.1.18'
, '0.1.19'
, '0.1.20'
, '0.1.21'
, '0.1.22'
, '0.1.23'
, '0.1.24'
, '0.1.25'
, '0.1.26'
, '0.1.27'
, '0.1.28'
, '0.1.29'
, '0.1.30'
, '0.1.31'
, '0.1.32'
, '0.1.33'
, '0.1.90'
, '0.1.91'
, '0.1.92'
, '0.1.93'
, '0.1.94'
, '0.1.95'
, '0.1.96'
, '0.1.97'
, '0.1.98'
, '0.1.99'
, '0.1.100'
, '0.1.101'
, '0.1.102'
, '0.1.103'
, '0.1.104'
, '0.2.0'
, '0.2.1'
, '0.2.2'
, '0.2.3'
, '0.2.4'
, '0.2.5'
, '0.2.6'
, '0.3.0'
, '0.3.1'
, '0.3.2'
, '0.3.3'
, '0.3.4'
, '0.3.5'
, '0.3.6'
, '0.3.7'
, '0.3.8'
, '0.4.0'
, '0.4.1'
, '0.4.2'
, '0.4.3'
, '0.4.4'
, '0.4.5'
, '0.4.6'
, '0.4.7'
, '0.4.8'
, '0.4.9'
, '0.4.10'
, '0.4.11'
, '0.4.12'
, '0.5.0'
, '0.5.1'
, '0.5.2'
, '0.5.3'
, '0.5.4'
, '0.5.5'
, '0.5.6'
, '0.5.7'
, '0.5.8'
, '0.5.9'
, '0.5.10'
, '0.6.0'
, '0.6.1'
, '0.6.2'
, '0.6.3'
, '0.6.4'
, '0.6.5'
, '0.6.6'
, '0.6.7'
, '0.6.8'
, '0.6.9'
, '0.6.10'
, '0.6.11'
, '0.6.12'
, '0.6.13'
, '0.6.14'
, '0.6.15'
, '0.6.16'
, '0.6.17'
, '0.6.18'
, '0.6.19'
, '0.6.20'
, '0.6.21'
, '0.7.0'
, '0.7.1'
, '0.7.2'
, '0.7.3'
, '0.7.4'
, '0.7.5'
, '0.7.6'
, '0.7.7'
, '0.7.8'
, '0.7.9'
, '0.7.10'
, '0.7.11'
, '0.7.12'
, '0.8.0'
, '0.8.1'
, '0.8.2'
, '0.8.3'
, '0.8.4'
, '0.8.5'
, '0.8.6'
, '0.8.7'
, '0.8.8'
, '0.8.9'
, '0.8.10'
, '0.8.11'
, '0.8.12'
, '0.8.13'
, '0.8.14'
, '0.8.15'
, '0.8.16'
, '0.8.17'
, '0.8.18'
, '0.8.19'
, '0.8.20'
, '0.8.21'
, '0.8.22'
, '0.8.23'
, '0.8.24'
, '0.8.25'
, '0.8.26'
, '0.8.27'
, '0.8.28'
, '0.9.0'
, '0.9.1'
, '0.9.2'
, '0.9.3'
, '0.9.4'
, '0.9.5'
, '0.9.6'
, '0.9.7'
, '0.9.8'
, '0.9.9'
, '0.9.10'
, '0.9.11'
, '0.9.12'
, '0.10.0'
, '0.10.1'
, '0.10.2'
, '0.10.3'
, '0.10.4'
, '0.10.5'
, '0.10.6'
, '0.10.7'
, '0.10.8'
, '0.10.9'
, '0.10.10'
, '0.10.11'
, '0.10.12'
, '0.10.13'
, '0.10.14'
, '0.10.15'
, '0.10.16'
, '0.10.17'
, '0.10.18'
, '0.10.19'
, '0.10.20'
, '0.10.21'
, '0.10.22'
, '0.10.23'
, '0.10.24'
, '0.10.25'
, '0.10.26'
, '0.10.27'
, '0.10.28'
, '0.10.29'
, '0.10.30'
, '0.10.31'
, '0.10.32'
, '0.10.33'
, '0.10.34'
, '0.10.35'
, '0.10.36'
, '0.10.37'
, '0.10.38'
, '0.10.39'
, '0.10.40'
, '0.11.0'
, '0.11.1'
, '0.11.2'
, '0.11.3'
, '0.11.4'
, '0.11.5'
, '0.11.6'
, '0.11.7'
, '0.11.8'
, '0.11.9'
, '0.11.10'
, '0.11.11'
, '0.11.12'
, '0.11.13'
, '0.11.14'
, '0.11.15'
, '0.11.16'
, '0.12.0'
, '0.12.1'
, '0.12.2'
, '0.12.3'
, '0.12.4'
, '0.12.5'
, '0.12.6'
, '0.12.7'
, '1.0.0'
, '1.0.1'
, '1.0.2'
, '1.0.3'
, '1.0.4'
, '1.1.0'
, '1.2.0'
, '1.3.0'
, '1.4.1'
, '1.4.2'
, '1.4.3'
, '1.5.0'
, '1.5.1'
, '1.6.0'
, '1.6.1'
, '1.6.2'
, '1.6.3'
, '1.6.4'
, '1.7.0'
, '1.7.1'
, '1.8.1'
, '1.8.2'
, '1.8.3'
, '1.8.4'
, '2.0.0'
, '2.0.1'
, '2.0.2'
, '2.1.0'
, '2.2.0'
, '2.2.1'
, '2.3.0'
, '2.3.1'
, '2.3.2'
, '2.3.3'
, '2.3.4'
, '2.4.0'
, '2.5.0'
, '3.0.0'
, '3.1.0'
, '3.2.0'
, '3.3.0'
, '3.3.1'
, '4.0.0'
, '4.1.0'
, '4.1.1'
, '4.1.2'
, '4.2.0'
, '4.2.1'
, '4.2.2'
, '5.0.0'
]
<commit_msg>add v5.1.0<commit_after>'use strict'

module.exports = [
  '0.0.1'
, '0.0.2'
, '0.0.3'
, '0.0.4'
, '0.0.5'
, '0.0.6'
, '0.1.0'
, '0.1.1'
, '0.1.2'
, '0.1.3'
, '0.1.4'
, '0.1.5'
, '0.1.6'
, '0.1.7'
, '0.1.8'
, '0.1.9'
, '0.1.10'
, '0.1.11'
, '0.1.12'
, '0.1.13'
, '0.1.14'
, '0.1.15'
, '0.1.16'
, '0.1.17'
, '0.1.18'
, '0.1.19'
, '0.1.20'
, '0.1.21'
, '0.1.22'
, '0.1.23'
, '0.1.24'
, '0.1.25'
, '0.1.26'
, '0.1.27'
, '0.1.28'
, '0.1.29'
, '0.1.30'
, '0.1.31'
, '0.1.32'
, '0.1.33'
, '0.1.90'
, '0.1.91'
, '0.1.92'
, '0.1.93'
, '0.1.94'
, '0.1.95'
, '0.1.96'
, '0.1.97'
, '0.1.98'
, '0.1.99'
, '0.1.100'
, '0.1.101'
, '0.1.102'
, '0.1.103'
, '0.1.104'
, '0.2.0'
, '0.2.1'
, '0.2.2'
, '0.2.3'
, '0.2.4'
, '0.2.5'
, '0.2.6'
, '0.3.0'
, '0.3.1'
, '0.3.2'
, '0.3.3'
, '0.3.4'
, '0.3.5'
, '0.3.6'
, '0.3.7'
, '0.3.8'
, '0.4.0'
, '0.4.1'
, '0.4.2'
, '0.4.3'
, '0.4.4'
, '0.4.5'
, '0.4.6'
, '0.4.7'
, '0.4.8'
, '0.4.9'
, '0.4.10'
, '0.4.11'
, '0.4.12'
, '0.5.0'
, '0.5.1'
, '0.5.2'
, '0.5.3'
, '0.5.4'
, '0.5.5'
, '0.5.6'
, '0.5.7'
, '0.5.8'
, '0.5.9'
, '0.5.10'
, '0.6.0'
, '0.6.1'
, '0.6.2'
, '0.6.3'
, '0.6.4'
, '0.6.5'
, '0.6.6'
, '0.6.7'
, '0.6.8'
, '0.6.9'
, '0.6.10'
, '0.6.11'
, '0.6.12'
, '0.6.13'
, '0.6.14'
, '0.6.15'
, '0.6.16'
, '0.6.17'
, '0.6.18'
, '0.6.19'
, '0.6.20'
, '0.6.21'
, '0.7.0'
, '0.7.1'
, '0.7.2'
, '0.7.3'
, '0.7.4'
, '0.7.5'
, '0.7.6'
, '0.7.7'
, '0.7.8'
, '0.7.9'
, '0.7.10'
, '0.7.11'
, '0.7.12'
, '0.8.0'
, '0.8.1'
, '0.8.2'
, '0.8.3'
, '0.8.4'
, '0.8.5'
, '0.8.6'
, '0.8.7'
, '0.8.8'
, '0.8.9'
, '0.8.10'
, '0.8.11'
, '0.8.12'
, '0.8.13'
, '0.8.14'
, '0.8.15'
, '0.8.16'
, '0.8.17'
, '0.8.18'
, '0.8.19'
, '0.8.20'
, '0.8.21'
, '0.8.22'
, '0.8.23'
, '0.8.24'
, '0.8.25'
, '0.8.26'
, '0.8.27'
, '0.8.28'
, '0.9.0'
, '0.9.1'
, '0.9.2'
, '0.9.3'
, '0.9.4'
, '0.9.5'
, '0.9.6'
, '0.9.7'
, '0.9.8'
, '0.9.9'
, '0.9.10'
, '0.9.11'
, '0.9.12'
, '0.10.0'
, '0.10.1'
, '0.10.2'
, '0.10.3'
, '0.10.4'
, '0.10.5'
, '0.10.6'
, '0.10.7'
, '0.10.8'
, '0.10.9'
, '0.10.10'
, '0.10.11'
, '0.10.12'
, '0.10.13'
, '0.10.14'
, '0.10.15'
, '0.10.16'
, '0.10.17'
, '0.10.18'
, '0.10.19'
, '0.10.20'
, '0.10.21'
, '0.10.22'
, '0.10.23'
, '0.10.24'
, '0.10.25'
, '0.10.26'
, '0.10.27'
, '0.10.28'
, '0.10.29'
, '0.10.30'
, '0.10.31'
, '0.10.32'
, '0.10.33'
, '0.10.34'
, '0.10.35'
, '0.10.36'
, '0.10.37'
, '0.10.38'
, '0.10.39'
, '0.10.40'
, '0.11.0'
, '0.11.1'
, '0.11.2'
, '0.11.3'
, '0.11.4'
, '0.11.5'
, '0.11.6'
, '0.11.7'
, '0.11.8'
, '0.11.9'
, '0.11.10'
, '0.11.11'
, '0.11.12'
, '0.11.13'
, '0.11.14'
, '0.11.15'
, '0.11.16'
, '0.12.0'
, '0.12.1'
, '0.12.2'
, '0.12.3'
, '0.12.4'
, '0.12.5'
, '0.12.6'
, '0.12.7'
, '1.0.0'
, '1.0.1'
, '1.0.2'
, '1.0.3'
, '1.0.4'
, '1.1.0'
, '1.2.0'
, '1.3.0'
, '1.4.1'
, '1.4.2'
, '1.4.3'
, '1.5.0'
, '1.5.1'
, '1.6.0'
, '1.6.1'
, '1.6.2'
, '1.6.3'
, '1.6.4'
, '1.7.0'
, '1.7.1'
, '1.8.1'
, '1.8.2'
, '1.8.3'
, '1.8.4'
, '2.0.0'
, '2.0.1'
, '2.0.2'
, '2.1.0'
, '2.2.0'
, '2.2.1'
, '2.3.0'
, '2.3.1'
, '2.3.2'
, '2.3.3'
, '2.3.4'
, '2.4.0'
, '2.5.0'
, '3.0.0'
, '3.1.0'
, '3.2.0'
, '3.3.0'
, '3.3.1'
, '4.0.0'
, '4.1.0'
, '4.1.1'
, '4.1.2'
, '4.2.0'
, '4.2.1'
, '4.2.2'
, '5.0.0'
, '5.1.0'
]
<|endoftext|>


<commit_before>module.exports = SupinBot = {};

var EventEmitter = require('events').EventEmitter;
var path = require('path');
var fs = require('fs');

var extend = require('extend');
var winston = require('winston');
var SlackBot = require('slackbots');
var CommandManager = require(path.resolve('libs/command-manager'));
var config = require(path.resolve('libs/config'));

SupinBot.config = config;
SupinBot.bot = new SlackBot(config.get('slack'));
SupinBot.CommandManager = new CommandManager();
SupinBot.events = new EventEmitter();
SupinBot.log = new winston.Logger({
	level: config.get('log.level'),
	transports: [
		new winston.transports.Console(),
		new winston.transports.File({
			filename: config.get('log.filename'),
			handleExceptions: true
		})
	]
});

SupinBot.PARAMS = config.get('slack.params');

SupinBot.bot.on('message', function (data) {
	SupinBot.log.debug('WS Event', data);

	if (data.type == 'message') {
		if (data.subtype != 'bot_message' && data.text) {
			var channel = SupinBot.getChannelByID(data.channel);
			var user = SupinBot.getUserByID(data.user);
			var command = SupinBot.CommandManager.parseMessage(data.text);

			if (command) {
				command.exec(this, user, channel, data.text);
			}
		}
	}

	process.nextTick(function() {
		SupinBot.events.emit('message', data);
	});
});

SupinBot.postMessage = function(channel, message, params) {
	return SupinBot.bot.postMessage(channel, message, extend(SupinBot.PARAMS, params));
};

SupinBot.getChannelByID = function(channelID) {
	for (var channel in SupinBot.bot.channels) {
		if (SupinBot.bot.channels[channel].id == channelID) {
			return SupinBot.bot.channels[channel];
		}
	}

	for (var group in SupinBot.bot.groups) {
		if (SupinBot.bot.groups[group].id == channelID) {
			return SupinBot.bot.groups[group];
		}
	}
};

SupinBot.getUserByID = function(userID) {
	for (var user in SupinBot.bot.users) {
		if (SupinBot.bot.users[user].id == userID) {
			return SupinBot.bot.users[user];
		}
	}
};

SupinBot.loadScripts = function() {
	fs.readdirSync(path.resolve('scripts')).sort().forEach(function(file) {
		SupinBot.loadScript(path.resolve('scripts', file));
	});

	config.get('scripts').forEach(function(script) {
		SupinBot.loadScript(script);
	});
};

SupinBot.loadScript = function(filePath) {
	try {
		var script = require(filePath);

		if (typeof script === 'function') {
			return script(SupinBot);
		}

		SupinBot.log.error('Cannot load ' + filePath + ', module.exports is not a function.');
	} catch (e) {
		SupinBot.log.error('An uncaught error occured while loading ' + filePath);
		SupinBot.log.error(e);
	}
};

SupinBot.loadScripts();
<commit_msg>Fixed attachments overwriting the bot PARAMS property<commit_after>module.exports = SupinBot = {};

var EventEmitter = require('events').EventEmitter;
var path = require('path');
var fs = require('fs');

var extend = require('extend');
var winston = require('winston');
var SlackBot = require('slackbots');
var CommandManager = require(path.resolve('libs/command-manager'));
var config = require(path.resolve('libs/config'));

SupinBot.config = config;
SupinBot.bot = new SlackBot(config.get('slack'));
SupinBot.CommandManager = new CommandManager();
SupinBot.events = new EventEmitter();
SupinBot.log = new winston.Logger({
	level: config.get('log.level'),
	transports: [
		new winston.transports.Console(),
		new winston.transports.File({
			filename: config.get('log.filename'),
			handleExceptions: true
		})
	]
});

SupinBot.PARAMS = config.get('slack.params');

SupinBot.bot.on('message', function (data) {
	SupinBot.log.debug('WS Event', data);

	if (data.type == 'message') {
		if (data.subtype != 'bot_message' && data.text) {
			var channel = SupinBot.getChannelByID(data.channel);
			var user = SupinBot.getUserByID(data.user);
			var command = SupinBot.CommandManager.parseMessage(data.text);

			if (command) {
				command.exec(this, user, channel, data.text);
			}
		}
	}

	process.nextTick(function() {
		SupinBot.events.emit('message', data);
	});
});

SupinBot.postMessage = function(channel, message, params) {
	return SupinBot.bot.postMessage(channel, message, extend({}, SupinBot.PARAMS, params));
};

SupinBot.getChannelByID = function(channelID) {
	for (var channel in SupinBot.bot.channels) {
		if (SupinBot.bot.channels[channel].id == channelID) {
			return SupinBot.bot.channels[channel];
		}
	}

	for (var group in SupinBot.bot.groups) {
		if (SupinBot.bot.groups[group].id == channelID) {
			return SupinBot.bot.groups[group];
		}
	}
};

SupinBot.getUserByID = function(userID) {
	for (var user in SupinBot.bot.users) {
		if (SupinBot.bot.users[user].id == userID) {
			return SupinBot.bot.users[user];
		}
	}
};

SupinBot.loadScripts = function() {
	fs.readdirSync(path.resolve('scripts')).sort().forEach(function(file) {
		SupinBot.loadScript(path.resolve('scripts', file));
	});

	config.get('scripts').forEach(function(script) {
		SupinBot.loadScript(script);
	});
};

SupinBot.loadScript = function(filePath) {
	try {
		var script = require(filePath);

		if (typeof script === 'function') {
			return script(SupinBot);
		}

		SupinBot.log.error('Cannot load ' + filePath + ', module.exports is not a function.');
	} catch (e) {
		SupinBot.log.error('An uncaught error occured while loading ' + filePath);
		SupinBot.log.error(e);
	}
};

SupinBot.loadScripts();
<|endoftext|>


<commit_before>'use strict';
// Reference: https://projectpokemon.org/wiki/Pokemon_X/Y_3DS_Structure
function stripNullChars (str) {
  return str.replace(/\0.*/, '');
}

function parseMap (data, map) {
  const parsedData = [];
  for (let i = 0; i < map.length; i++, data = Math.floor(data / 2)) {
    if (map[i] && data % 2) {
      parsedData.push(map[i]);
    }
  }
  return parsedData;
}

function checksumIsValid (buf) {
  let sum = 0;
  for (let i = 8; i < 232; i += 2) {
    sum += buf.readUInt16LE(i);
  }
  return (sum & 0xffff) === buf.readUInt16LE(0x06);
}

exports.parseBuffer = buf => {
  const data = {};
  if (buf.readUInt16LE(0x04)) {
    throw new Error('The provided buffer is not valid pk6 data');
  }
  data.checksumIsValid = checksumIsValid(buf);
  data.encryptionConstant = buf.readUInt32LE(0x00);
  data.dexNo = buf.readUInt16LE(0x08);
  data.heldItemId = buf.readUInt16LE(0x0a);
  data.tid = buf.readUInt16LE(0x0c);
  data.sid = buf.readUInt16LE(0x0e);
  data.exp = buf.readUInt32LE(0x10);
  data.abilityId = buf.readUInt8(0x14);
  data.abilityNum = buf.readUInt8(0x15);
  data.superTrainingHitsRemaining = buf.readUInt8(0x16);
  data.superTrainingBag = buf.readUInt8(0x17);
  data.pid = buf.readUInt32LE(0x18);
  data.natureId = buf.readUInt8(0x1c); // TODO: Parse

  const genderByte = buf.readUInt8(0x1d);
  data.isFatefulEncounter = !!(genderByte & 0x01);
  const isFemale = genderByte & 0x02;
  const isGenderless = genderByte & 0x04;
  data.gender = isFemale ? 'F' : isGenderless ? '' : 'M';
  data.formId = genderByte >> 3;

  data.evHp = buf.readUInt8(0x1e);
  data.evAtk = buf.readUInt8(0x1f);
  data.evDef = buf.readUInt8(0x20);
  data.evSpe = buf.readUInt8(0x21);
  data.evSpAtk = buf.readUInt8(0x22);
  data.evSpDef = buf.readUInt8(0x23);

  data.contestStatCool = buf.readUInt8(0x24);
  data.contestStatBeauty = buf.readUInt8(0x25);
  data.contestStatCute = buf.readUInt8(0x26);
  data.contestStatSmart = buf.readUInt8(0x27);
  data.contestStatTough = buf.readUInt8(0x28);
  data.contestStatSheen = buf.readUInt8(0x29);

  const markingByte = buf.readUInt8(0x2a);
  data.hasCircleMarking = !!(markingByte & 0x01);
  data.hasTriangleMarking = !!(markingByte & 0x02);
  data.hasSquareMarking = !!(markingByte & 0x04);
  data.hasHeartMarking = !!(markingByte & 0x08);
  data.hasStarMarking = !!(markingByte & 0x10);
  data.hasDiamondMarking = !!(markingByte & 0x20);

  const pokerusByte = buf.readUInt8(0x2b);
  data.pokerusDuration = pokerusByte & 16;
  data.pokerusStrain = pokerusByte >> 4;

  data.medalData = buf.readUInt32LE(0x2c);
  data.ribbonData = buf.readUIntLE(0x30, 6);
  data.distributionSuperTrainingFlags = buf.readUInt8(0x3a); // Not sure what these are
  data.nickname = stripNullChars(buf.toString('utf16le', 0x40, 0x58));

  data.move1Id = buf.readUInt16LE(0x5a);
  data.move2Id = buf.readUInt16LE(0x5c);
  data.move3Id = buf.readUInt16LE(0x5e);
  data.move4Id = buf.readUInt16LE(0x60);
  data.move1Pp = buf.readUInt8(0x62);
  data.move2Pp = buf.readUInt8(0x63);
  data.move3Pp = buf.readUInt8(0x64);
  data.move4Pp = buf.readUInt8(0x65);
  data.move1Ppu = buf.readUInt8(0x66);
  data.move2Ppu = buf.readUInt8(0x67);
  data.move3Ppu = buf.readUInt8(0x68);
  data.move4Ppu = buf.readUInt8(0x69);
  data.eggMove1Id = buf.readUInt16LE(0x6a);
  data.eggMove2Id = buf.readUInt16LE(0x6c);
  data.eggMove3Id = buf.readUInt16LE(0x6e);
  data.eggMove4Id = buf.readUInt16LE(0x70);

  data.canDoSecretSuperTraining = !!(buf.readUInt8(0x72));

  const ivBytes = buf.readUInt32LE(0x74);
  data.ivHp = ivBytes & 0x1f;
  data.ivAtk = ivBytes >> 5 & 0x1f;
  data.ivDef = ivBytes >> 10 & 0x1f;
  data.ivSpe = ivBytes >> 15 & 0x1f;
  data.ivSpAtk = ivBytes >> 20 & 0x1f;
  data.ivSpDef = ivBytes >> 25 & 0x1f;
  data.isEgg = (ivBytes >> 30) % 2 !== 0;
  data.isNicknamed = (ivBytes >> 31) % 2 !== 0;

  data.notOt = stripNullChars(buf.toString('utf16le', 0x78, 0x90));
  data.notOtGender = buf.readUInt8(0x92) ? 'F' : 'M';

  data.currentHandlerIsOt = !buf.readUInt8(0x93);

  data.geoLocation1 = buf.readUInt16LE(0x94); // TODO: Figure out how to parse these
  data.geoLocation2 = buf.readUInt16LE(0x96);
  data.geoLocation3 = buf.readUInt16LE(0x98);
  data.geoLocation4 = buf.readUInt16LE(0x9a);
  data.geoLocation5 = buf.readUInt16LE(0x9c);

  data.notOtFriendship = buf.readUInt8(0xa2);
  data.notOtAffection = buf.readUInt8(0xa3);
  data.notOtMemoryIntensity = buf.readUInt8(0xa4); // TODO: Parse
  data.notOtMemoryLine = buf.readUInt8(0xa5);
  data.notOtMemoryFeeling = buf.readUInt8(0xa6);
  data.notOtMemoryTextVar = buf.readUInt16LE(0xa8);

  data.fullness = buf.readUInt8(0xae);
  data.enjoyment = buf.readUInt8(0xaf);

  data.ot = stripNullChars(buf.toString('utf16le', 0xb0, 0xc8));
  data.otFriendship = buf.readUInt8(0xca);
  data.otAffection = buf.readUInt8(0xcb);
  data.otMemoryIntensity = buf.readUInt8(0xcc); // TODO: Parse
  data.otMemoryLine = buf.readUInt8(0xcd);
  data.otMemoryTextVar = buf.readUInt16LE(0xce);
  data.otMemoryFeeling = buf.readUInt8(0xd0);

  data.eggDate = Date.UTC(buf.readUInt8(0xd1) + 2000, (buf.readUInt8(0xd2) || NaN) - 1, buf.readUInt8(0xd3));
  data.metDate = Date.UTC(buf.readUInt8(0xd4) + 2000, (buf.readUInt8(0xd5) || NaN) - 1, buf.readUInt8(0xd6));

  data.eggLocationId = buf.readUInt16LE(0xd8); // TODO: Parse
  data.metLocationId = buf.readUInt32LE(0xda);
  data.ballId = buf.readUInt8(0xdc);

  const encounterLevelByte = buf.readUInt8(0xdd);
  data.levelMet = encounterLevelByte & 0x7f;
  data.otGender = encounterLevelByte >> 7 ? 'F' : 'M';

  data.encounterTypeId = buf.readUInt8(0xde); // TODO: Parse
  data.otGameId = buf.readUInt8(0xdf); // TODO: Parse
  data.countryId = buf.readUInt8(0xe0); // TODO: Parse
  data.regionId = buf.readUInt8(0xe1); // TODO: Parse
  data.consoleRegion = ['J', 'U', 'E', 'K'][buf.readUInt8(0xe2)]; // Japan, Americas, PAL, Korea
  data.language = ['JPN', 'ENG', 'FRE', 'ITA', 'GER', 'SPA', 'KOR'][buf.readUInt8(0xe3) - 1];
  data.rawPk6 = buf.toString('base64');

  return data;
};

exports.parseFile = path => {
  return exports.parseBuffer(require('fs').readFileSync(path));
};

exports.getPokemonData = dexNo => {
  try {
    return require(`./pokemon_data/${dexNo}.json`);
  } catch (e) {
    throw new Error(`Invalid dex number: ${dexNo}`);
  }
};

exports.getItemData = itemId => {
  if (itemId === 0) {
    return null;
  }
  try {
    return require(`./item_data_gen6/${itemId}.json`);
  } catch (e) {
    throw new Error(`Invalid item ID: ${itemId}`);
  }
};

exports.getMoveData = moveId => {
  if (moveId === 0) {
    return null;
  }
  try {
    return require(`./move_data/${moveId}.json`);
  } catch (e) {
    throw new Error(`Invalid move ID: ${moveId}`);
  }
};

exports.getAbilityData = abilityId => {
  if (abilityId === 0) {
    return null;
  }
  try {
    return require(`./ability_data/${abilityId}.json`);
  } catch (e) {
    throw `Invalid ability ID: ${abilityId}`;
  }
};

exports.getRibbonData = ribbonData => {
  return parseMap(ribbonData, require('./ribbonsByOrder'));
};

exports.getMedalData = medalData => {
  return parseMap(medalData, require('./medalsByOrder'));
};
<commit_msg>Fixed date parsing<commit_after>'use strict';
// Reference: https://projectpokemon.org/wiki/Pokemon_X/Y_3DS_Structure
function stripNullChars (str) {
  return str.replace(/\0.*/, '');
}

function parseMap (data, map) {
  const parsedData = [];
  for (let i = 0; i < map.length; i++, data = Math.floor(data / 2)) {
    if (map[i] && data % 2) {
      parsedData.push(map[i]);
    }
  }
  return parsedData;
}

function checksumIsValid (buf) {
  let sum = 0;
  for (let i = 8; i < 232; i += 2) {
    sum += buf.readUInt16LE(i);
  }
  return (sum & 0xffff) === buf.readUInt16LE(0x06);
}

function getDateFromInt (dateStorage) {
  if (!dateStorage) {
    return null;
  }
  return Date.UTC((dateStorage & 0xff) + 2000, (dateStorage >> 8 & 0xff) - 1, (dateStorage >> 16 & 0xff));
}

exports.parseBuffer = buf => {
  const data = {};
  if (buf.readUInt16LE(0x04)) {
    throw new Error('The provided buffer is not valid pk6 data');
  }
  data.checksumIsValid = checksumIsValid(buf);
  data.encryptionConstant = buf.readUInt32LE(0x00);
  data.dexNo = buf.readUInt16LE(0x08);
  data.heldItemId = buf.readUInt16LE(0x0a);
  data.tid = buf.readUInt16LE(0x0c);
  data.sid = buf.readUInt16LE(0x0e);
  data.exp = buf.readUInt32LE(0x10);
  data.abilityId = buf.readUInt8(0x14);
  data.abilityNum = buf.readUInt8(0x15);
  data.superTrainingHitsRemaining = buf.readUInt8(0x16);
  data.superTrainingBag = buf.readUInt8(0x17);
  data.pid = buf.readUInt32LE(0x18);
  data.natureId = buf.readUInt8(0x1c); // TODO: Parse

  const genderByte = buf.readUInt8(0x1d);
  data.isFatefulEncounter = !!(genderByte & 0x01);
  const isFemale = genderByte & 0x02;
  const isGenderless = genderByte & 0x04;
  data.gender = isFemale ? 'F' : isGenderless ? '' : 'M';
  data.formId = genderByte >> 3;

  data.evHp = buf.readUInt8(0x1e);
  data.evAtk = buf.readUInt8(0x1f);
  data.evDef = buf.readUInt8(0x20);
  data.evSpe = buf.readUInt8(0x21);
  data.evSpAtk = buf.readUInt8(0x22);
  data.evSpDef = buf.readUInt8(0x23);

  data.contestStatCool = buf.readUInt8(0x24);
  data.contestStatBeauty = buf.readUInt8(0x25);
  data.contestStatCute = buf.readUInt8(0x26);
  data.contestStatSmart = buf.readUInt8(0x27);
  data.contestStatTough = buf.readUInt8(0x28);
  data.contestStatSheen = buf.readUInt8(0x29);

  const markingByte = buf.readUInt8(0x2a);
  data.hasCircleMarking = !!(markingByte & 0x01);
  data.hasTriangleMarking = !!(markingByte & 0x02);
  data.hasSquareMarking = !!(markingByte & 0x04);
  data.hasHeartMarking = !!(markingByte & 0x08);
  data.hasStarMarking = !!(markingByte & 0x10);
  data.hasDiamondMarking = !!(markingByte & 0x20);

  const pokerusByte = buf.readUInt8(0x2b);
  data.pokerusDuration = pokerusByte & 16;
  data.pokerusStrain = pokerusByte >> 4;

  data.medalData = buf.readUInt32LE(0x2c);
  data.ribbonData = buf.readUIntLE(0x30, 6);
  data.distributionSuperTrainingFlags = buf.readUInt8(0x3a); // Not sure what these are
  data.nickname = stripNullChars(buf.toString('utf16le', 0x40, 0x58));

  data.move1Id = buf.readUInt16LE(0x5a);
  data.move2Id = buf.readUInt16LE(0x5c);
  data.move3Id = buf.readUInt16LE(0x5e);
  data.move4Id = buf.readUInt16LE(0x60);
  data.move1Pp = buf.readUInt8(0x62);
  data.move2Pp = buf.readUInt8(0x63);
  data.move3Pp = buf.readUInt8(0x64);
  data.move4Pp = buf.readUInt8(0x65);
  data.move1Ppu = buf.readUInt8(0x66);
  data.move2Ppu = buf.readUInt8(0x67);
  data.move3Ppu = buf.readUInt8(0x68);
  data.move4Ppu = buf.readUInt8(0x69);
  data.eggMove1Id = buf.readUInt16LE(0x6a);
  data.eggMove2Id = buf.readUInt16LE(0x6c);
  data.eggMove3Id = buf.readUInt16LE(0x6e);
  data.eggMove4Id = buf.readUInt16LE(0x70);

  data.canDoSecretSuperTraining = !!(buf.readUInt8(0x72));

  const ivBytes = buf.readUInt32LE(0x74);
  data.ivHp = ivBytes & 0x1f;
  data.ivAtk = ivBytes >> 5 & 0x1f;
  data.ivDef = ivBytes >> 10 & 0x1f;
  data.ivSpe = ivBytes >> 15 & 0x1f;
  data.ivSpAtk = ivBytes >> 20 & 0x1f;
  data.ivSpDef = ivBytes >> 25 & 0x1f;
  data.isEgg = (ivBytes >> 30) % 2 !== 0;
  data.isNicknamed = (ivBytes >> 31) % 2 !== 0;

  data.notOt = stripNullChars(buf.toString('utf16le', 0x78, 0x90));
  data.notOtGender = buf.readUInt8(0x92) ? 'F' : 'M';

  data.currentHandlerIsOt = !buf.readUInt8(0x93);

  data.geoLocation1 = buf.readUInt16LE(0x94); // TODO: Figure out how to parse these
  data.geoLocation2 = buf.readUInt16LE(0x96);
  data.geoLocation3 = buf.readUInt16LE(0x98);
  data.geoLocation4 = buf.readUInt16LE(0x9a);
  data.geoLocation5 = buf.readUInt16LE(0x9c);

  data.notOtFriendship = buf.readUInt8(0xa2);
  data.notOtAffection = buf.readUInt8(0xa3);
  data.notOtMemoryIntensity = buf.readUInt8(0xa4); // TODO: Parse
  data.notOtMemoryLine = buf.readUInt8(0xa5);
  data.notOtMemoryFeeling = buf.readUInt8(0xa6);
  data.notOtMemoryTextVar = buf.readUInt16LE(0xa8);

  data.fullness = buf.readUInt8(0xae);
  data.enjoyment = buf.readUInt8(0xaf);

  data.ot = stripNullChars(buf.toString('utf16le', 0xb0, 0xc8));
  data.otFriendship = buf.readUInt8(0xca);
  data.otAffection = buf.readUInt8(0xcb);
  data.otMemoryIntensity = buf.readUInt8(0xcc); // TODO: Parse
  data.otMemoryLine = buf.readUInt8(0xcd);
  data.otMemoryTextVar = buf.readUInt16LE(0xce);
  data.otMemoryFeeling = buf.readUInt8(0xd0);

  data.eggDate = getDateFromInt(buf.readUIntLE(0xd1, 3));
  data.metDate = getDateFromInt(buf.readUIntLE(0xd4, 3));

  data.eggLocationId = buf.readUInt16LE(0xd8); // TODO: Parse
  data.metLocationId = buf.readUInt32LE(0xda);
  data.ballId = buf.readUInt8(0xdc);

  const encounterLevelByte = buf.readUInt8(0xdd);
  data.levelMet = encounterLevelByte & 0x7f;
  data.otGender = encounterLevelByte >> 7 ? 'F' : 'M';

  data.encounterTypeId = buf.readUInt8(0xde); // TODO: Parse
  data.otGameId = buf.readUInt8(0xdf); // TODO: Parse
  data.countryId = buf.readUInt8(0xe0); // TODO: Parse
  data.regionId = buf.readUInt8(0xe1); // TODO: Parse
  data.consoleRegion = ['J', 'U', 'E', 'K'][buf.readUInt8(0xe2)]; // Japan, Americas, PAL, Korea
  data.language = ['JPN', 'ENG', 'FRE', 'ITA', 'GER', 'SPA', 'KOR'][buf.readUInt8(0xe3) - 1];
  data.rawPk6 = buf.toString('base64');

  return data;
};

exports.parseFile = path => {
  return exports.parseBuffer(require('fs').readFileSync(path));
};

exports.getPokemonData = dexNo => {
  try {
    return require(`./pokemon_data/${dexNo}.json`);
  } catch (e) {
    throw new Error(`Invalid dex number: ${dexNo}`);
  }
};

exports.getItemData = itemId => {
  if (itemId === 0) {
    return null;
  }
  try {
    return require(`./item_data_gen6/${itemId}.json`);
  } catch (e) {
    throw new Error(`Invalid item ID: ${itemId}`);
  }
};

exports.getMoveData = moveId => {
  if (moveId === 0) {
    return null;
  }
  try {
    return require(`./move_data/${moveId}.json`);
  } catch (e) {
    throw new Error(`Invalid move ID: ${moveId}`);
  }
};

exports.getAbilityData = abilityId => {
  if (abilityId === 0) {
    return null;
  }
  try {
    return require(`./ability_data/${abilityId}.json`);
  } catch (e) {
    throw `Invalid ability ID: ${abilityId}`;
  }
};

exports.getRibbonData = ribbonData => {
  return parseMap(ribbonData, require('./ribbonsByOrder'));
};

exports.getMedalData = medalData => {
  return parseMap(medalData, require('./medalsByOrder'));
};
<|endoftext|>


<commit_before>'use strict';

var param = require('jquery-param');
var STATE_DONE = 4;
var CONTENT_TYPE = 'Content-type';

var ajax = {};

ajax.x = function() {
  return new XMLHttpRequest();
};

ajax.send = function(url, opts) {
  var x = ajax.x();
  x.open(opts.method, url);
  x.onreadystatechange = function() {
    if (x.readyState !== STATE_DONE) {
      return;
    }
    if (x.status >= 200 && x.status < 300) {
      opts.success(x.responseText);
      return;
    }
    opts.error(x.responseText);
  };
  if (opts.method === 'POST') {
    x.setRequestHeader(CONTENT_TYPE, 'application/x-www-form-urlencoded');
  }
  if (opts.contentType) {
    x.setRequestHeader(CONTENT_TYPE, opts.contentType);
  }
  x.setRequestHeader('Accept', '*/*');
  if (opts.mimeType && x.overrideMimeType) {
    x.overrideMimeType(opts.mimeType);
  }
  x.send(opts.data);
};

ajax.get = function(url, opts) {
  opts = opts || {};
  opts.method = 'GET';

  var query = param(opts.data);
  var fullUrl = url + (query.length ? '?' + query : '');
  opts.data = null;
  ajax.send(fullUrl, opts);
};

ajax.post = function(url, opts) {
  opts = opts || {};
  opts.method = 'POST';

  opts.data = param(opts.data);
  ajax.send(url, opts);
};

module.exports = ajax;
<commit_msg>Success and error properties made optional<commit_after>'use strict';

var param = require('jquery-param');
var STATE_DONE = 4;
var CONTENT_TYPE = 'Content-type';
var noop = function() {};

var ajax = {};

ajax.x = function() {
  return new XMLHttpRequest();
};

ajax.send = function(url, opts) {
  opts = opts || {};
  opts.success = opts.success || noop;
  opts.error = opts.error || noop;

  var x = ajax.x();
  x.open(opts.method, url);
  x.onreadystatechange = function() {
    if (x.readyState !== STATE_DONE) {
      return;
    }
    if (x.status >= 200 && x.status < 300) {
      opts.success(x.responseText);
      return;
    }
    opts.error(x.responseText);
  };
  if (opts.method === 'POST') {
    x.setRequestHeader(CONTENT_TYPE, 'application/x-www-form-urlencoded');
  }
  if (opts.contentType) {
    x.setRequestHeader(CONTENT_TYPE, opts.contentType);
  }
  x.setRequestHeader('Accept', '*/*');
  if (opts.mimeType && x.overrideMimeType) {
    x.overrideMimeType(opts.mimeType);
  }
  x.send(opts.data);
};

ajax.get = function(url, opts) {
  opts = opts || {};
  opts.method = 'GET';

  var query = param(opts.data);
  var fullUrl = url + (query.length ? '?' + query : '');
  opts.data = null;
  ajax.send(fullUrl, opts);
};

ajax.post = function(url, opts) {
  opts = opts || {};
  opts.method = 'POST';

  opts.data = param(opts.data);
  ajax.send(url, opts);
};

module.exports = ajax;
<|endoftext|>


<commit_before>const express = require("express");
const graphqlHTTP = require("express-graphql");
const bundlerSchema = require("./schemas/bundler");
const BundlerService = require("./services/Bundler");

const storage = require("./storage/provider");
const registry = require("./registries/provider");

// Configure storage provider for caching bundles
const StorageProvider = require("./storage/connectors/" + (process.env.BUNDLER_STORAGE || "nedb"));
storage.setProvider(new StorageProvider());

// Configure registry provider to pull npm modules with.
const RegistryProvider = require("./registries/installers/" + (process.env.BUNDLER_INSTALLER || "yarn"));
registry.setProvider(new RegistryProvider());

const app = express();

app
  .use(express.static("cache"))
  .use("/graphql", graphqlHTTP({
    schema: bundlerSchema,
    graphiql: process.env.DEBUG,
    rootValue: {
      bundler: function (options) {
        return new BundlerService(options);
      }
    }
  }));

app.listen(process.env.PORT || 4000);
<commit_msg>refactored how a few of the envrionment variables are processed<commit_after>const express = require("express");
const graphqlHTTP = require("express-graphql");
const bundlerSchema = require("./schemas/bundler");
const BundlerService = require("./services/Bundler");

const storage = require("./storage/provider");
const registry = require("./registries/provider");

// Configure storage provider for caching bundles
const StorageProvider = require("./storage/connectors/" + (process.env.BUNDLER_STORAGE || "nedb"));
storage.setProvider(new StorageProvider());

// Configure registry provider to pull npm modules with.
const RegistryProvider = require("./registries/installers/" + (process.env.BUNDLER_INSTALLER || "yarn"));
registry.setProvider(new RegistryProvider());

const app = express();
const port = process.env.PORT || 4000;
const debug = !!process.env.DEBUG;

app
  .use(express.static("cache"))
  .use("/graphql", graphqlHTTP({
    schema: bundlerSchema,
    graphiql: debug,
    rootValue: {
      bundler: function (options) {
        return new BundlerService(options);
      }
    }
  }));

app.listen(port);

console.log("Listening on", port);
<|endoftext|>


<commit_before>var loaderUtils = require("loader-utils");

module.exports = function (content) {
  this.cacheable();
  var cb = this.async();
  var languages = {};
  var output = '';
  var vueUrl = loaderUtils.getRemainingRequest(this);
  var loaders = {
    html: 'html',
    css: 'style!css',
    js: ''
  };
  var loaderPrefix = {
    template: '',
    style: 'style!css!',
    script: ''
  };
  var defaultLang = {
    template: 'html',
    style: 'css',
    script: 'js'
  };

  function loader(part, lang) {
    lang = lang || defaultLang[part];
    var loader = loaders[lang] !== undefined ? loaders[lang] : loaderPrefix[part] + lang;
    return loader ? loader + '!' : '';
  }

  function getRequire(part, lang) {
    return 'require(' + loaderUtils.stringifyRequest(this, '-!' + loader(part, lang) + require.resolve('./selector.js') + '?' + part + '/' + lang + '!' + vueUrl) + ')';
  }

  var me = this;
  var url = "!!" + require.resolve("./parser.js") + "!" + vueUrl;
  this.loadModule(url, function(err, source, map, module) {
    if (err) return cb(err);

    var parts = me.exec(source, url);

    for (var i = 0; i < parts.includes.length; i++)
      output += 'require(' + loaderUtils.stringifyRequest(this, loaderUtils.urlToRequest(parts.includes[i])) + ')\n';

    for (var lang in parts.style)
      output += getRequire('style', lang) + '\n';

    for (var lang in parts.script)
      output += 'module.exports = ' + getRequire('script', lang) + '\n';

    var hasTemplate = false;
    for (var lang in parts.template) {
      if (hasTemplate)
        return cb(new Error('Only one template element allowed per vue component!'));
      output += 'module.exports.template = ' + getRequire('template', lang);
      output += '\nif (module.exports.template instanceof Function) module.exports.template = module.exports.template({})';
      hasTemplate = true;
    }

    cb(null, output);
  })
}
<commit_msg>Fix bug<commit_after>var loaderUtils = require("loader-utils");

module.exports = function (content) {
  this.cacheable();
  var cb = this.async();
  var languages = {};
  var output = '';
  var vueUrl = loaderUtils.getRemainingRequest(this);
  var loaders = {
    html: 'html',
    css: 'style!css',
    js: ''
  };
  var loaderPrefix = {
    template: '',
    style: 'style!css!',
    script: ''
  };
  var defaultLang = {
    template: 'html',
    style: 'css',
    script: 'js'
  };

  function loader(part, lang) {
    lang = lang || defaultLang[part];
    var loader = loaders[lang] !== undefined ? loaders[lang] : loaderPrefix[part] + lang;
    return loader ? loader + '!' : '';
  }

  var me = this;
  function getRequire(part, lang) {
    return 'require(' + loaderUtils.stringifyRequest(me, '-!' + loader(part, lang) + require.resolve('./selector.js') + '?' + part + '/' + lang + '!' + vueUrl) + ')';
  }

  var me = this;
  var url = "!!" + require.resolve("./parser.js") + "!" + vueUrl;
  this.loadModule(url, function(err, source, map, module) {
    if (err) return cb(err);

    var parts = me.exec(source, url);

    for (var i = 0; i < parts.includes.length; i++)
      output += 'require(' + loaderUtils.stringifyRequest(this, loaderUtils.urlToRequest(parts.includes[i])) + ')\n';

    for (var lang in parts.style)
      output += getRequire('style', lang) + '\n';

    for (var lang in parts.script)
      output += 'module.exports = ' + getRequire('script', lang) + '\n';

    var hasTemplate = false;
    for (var lang in parts.template) {
      if (hasTemplate)
        return cb(new Error('Only one template element allowed per vue component!'));
      output += 'module.exports.template = ' + getRequire('template', lang);
      output += '\nif (module.exports.template instanceof Function) module.exports.template = module.exports.template({})';
      hasTemplate = true;
    }

    cb(null, output);
  })
}
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var _ = require('@sailshq/lodash');
var flaverr = require('flaverr');
var includeAll = require('include-all');
var Machine = require('machine');

/**
 * loadHelpers()
 *
 * Load helper definitions from disk, build them into Callables, then attach
 * them to the `sails.helpers` dictionary.
 *
 * @param {SailsApp} sails
 * @param {Function} done
 *        @param {Error?} err
 */
module.exports = function loadHelpers(sails, done) {

  // Load helper defs out of the specified folder
  includeAll.optional({
    dirname: sails.config.paths.helpers,
    filter: /^([^.]+)\.(?:(?!md|txt).)+$/,
    flatten: true,
    keepDirectoryPath: true
  }, function(err, helperDefs) {
    if (err) { return done(err); }

    try {
      // If any helpers were specified when loading Sails, add those on
      // top of the ones loaded from disk.  (Experimental)
      if (sails.config.helpers && sails.config.helpers.moduleDefinitions) {
        // TODO: Reconsider how this is done to allow more flexibility in configuration.d
        _.extend(helperDefs, sails.config.helpers.moduleDefinitions);
      }

      // Loop through each helper def, attempting to build each one as
      // a Callable (a.k.a. "wet machine")
      _.each(helperDefs, function(helperDef, identity) {
        try {
          // Camel-case every part of the file path, and join with dots
          // e.g. /user-helpers/foo/my-helper => userHelpers.foo.myHelper
          var keyPath = _.map(identity.split('/'), _.camelCase).join('.');

          // Use filename-derived `identity` if no other, better identity can be derived.
          // (Otherwise, as of machine@v15, this fails with an ImplementationError.)
          if (!helperDef.identity && !helperDef.friendlyName && !helperDef.description) {
            helperDef.identity = identity;
          }

          // Use _.set to set the (possibly nested) property of sails.helpers
          // e.g. sails.helpers.userHelpers.foo.myHelper
          _.set(sails.helpers, keyPath, Machine.build(helperDef));
        } catch (err) {
          // If an error occurs building the callable, throw here to bust
          // out of the _.each loop early
          throw flaverr({
            code: 'E_FAILED_TO_BUILD_MACHINE',
            identity: identity
          }, err);
        }
      });//∞

    } catch (err) {

      // Handle any errors building Callables for our helpers by sending the
      // errors through the hook callback, which will cause Sails to halt lifting.
      if (flaverr.taste('E_FAILED_TO_BUILD_MACHINE', err)) {
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        // FUTURE: Instead of this additional log, consider modifying the error itself.
        // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
        sails.log.error('Failed to load helper `' + err.identity +'` into a Callable!');
        return done(err);
      } else {
        return done(err);
      }

    }//</ caught >

    // --• Everthing worked!
    return done();

  });

};
<commit_msg>Take care of modifying error message instead of using a separate log.<commit_after>/**
 * Module dependencies
 */

var _ = require('@sailshq/lodash');
var flaverr = require('flaverr');
var includeAll = require('include-all');
var Machine = require('machine');

/**
 * loadHelpers()
 *
 * Load helper definitions from disk, build them into Callables, then attach
 * them to the `sails.helpers` dictionary.
 *
 * @param {SailsApp} sails
 * @param {Function} done
 *        @param {Error?} err
 */
module.exports = function loadHelpers(sails, done) {

  // Load helper defs out of the specified folder
  includeAll.optional({
    dirname: sails.config.paths.helpers,
    filter: /^([^.]+)\.(?:(?!md|txt).)+$/,
    flatten: true,
    keepDirectoryPath: true
  }, function(err, helperDefs) {
    if (err) { return done(err); }

    // If any helpers were specified when loading Sails, add those on
    // top of the ones loaded from disk.  (Experimental)
    if (sails.config.helpers && sails.config.helpers.moduleDefinitions) {
      // TODO: Reconsider how this is done to allow more flexibility in configuration.d
      _.extend(helperDefs, sails.config.helpers.moduleDefinitions);
    }

    try {
      // Loop through each helper def, attempting to build each one as
      // a Callable (a.k.a. "wet machine")
      _.each(helperDefs, function(helperDef, identity) {
        try {
          // Camel-case every part of the file path, and join with dots
          // e.g. /user-helpers/foo/my-helper => userHelpers.foo.myHelper
          var keyPath = _.map(identity.split('/'), _.camelCase).join('.');

          // Use filename-derived `identity` if no other, better identity can be derived.
          // (Otherwise, as of machine@v15, this fails with an ImplementationError.)
          if (!helperDef.identity && !helperDef.friendlyName && !helperDef.description) {
            helperDef.identity = identity;
          }

          // Use _.set to set the (possibly nested) property of sails.helpers
          // e.g. sails.helpers.userHelpers.foo.myHelper
          _.set(sails.helpers, keyPath, Machine.build(helperDef));
        } catch (err) {
          // If an error occurs building the callable, throw here to bust
          // out of the _.each loop early
          throw flaverr({
            code: 'E_FAILED_TO_BUILD_CALLABLE',
            identity: identity,
            raw: err
          }, err);
        }
      });//∞

    } catch (err) {

      // Handle any errors building Callables for our helpers by sending the
      // errors through the hook callback, which will cause Sails to halt lifting.
      if (flaverr.taste('E_FAILED_TO_BUILD_CALLABLE', err)) {
        return done(flaverr({
          message: 'Failed to load helper `' + err.identity +'` into a Callable!  '+err.message
        }, err));
      } else {
        return done(err);
      }

    }//</ caught >

    // --• Everthing worked!
    return done();

  });

};
<|endoftext|>