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

    var EventEmitter= require('events').EventEmitter,

        versionio   = require('version-io'),
        changelog   = require('changelog-io'),
        rendy       = require('rendy'),
        spawnify    = require('spawnify'),
        async       = require('async'),
        minor       = require('minor'),
        prepend     = require('prepend'),
        grizzly     = require('grizzly'),
        readjson    = require('readjson'),
        jessy       = require('jessy'),

        Cmd         = [
            'git add --all',
            'git commit -m "chore(package) v{{ version }}"',
            'git pull --rebase',
            'git push origin {{ branch }}',
        ].join('&&'),

        CmdTag      = [
            'git tag v{{ version }}',
            'git push origin v{{ version }}'
        ].join('&&'),

        MSG         = [ 'publish <version>',
                        'package: {{ name }} v{{ version }}'
                    ].join('\n');

    module.exports  = function(version) {
        var emitter = new EventEmitter(),
            name    = process.cwd() + '/package.json';

        readjson(name, function(error, info) {
            var msg;

            if (error) {
                msg             = error.message;
                error.message   = 'Error reading package.json: ' + msg;
                emitter.emit('error', error);
            } else if (!version) {
                emitter.emit('data', rendy(MSG, {
                    name    : info.name,
                    version : info.version
                }));
            } else {
                publish(version, info, emitter);
            }
        });

        return emitter;
    };

    function publish(version, info, emitter) {
        var cmd,
            cmdTag,
            type        = '--',
            chlog       = '';

        if (!version.indexOf('v')) {
            version  = version.slice(1);
            type    += 'v' + version;
        } else if (/major|minor|patch/.test(version)) {
            type    += version;
            version  = minor(version, info.version);
        }

        cmd = rendy(Cmd, {
            version: version,
            branch: info.branch || 'master'
        });

        cmdTag = rendy(CmdTag, {
            version: version
        });

        async.series([
            function beforePublish(callback) {
                var cmd     = jessy('scripts.wisdom', info);

                if (!cmd)
                    callback();
                else
                    runWisdom(type, emitter, callback);
            },

            function(callback) {
                var isUndefined = typeof info.changelog === 'undefined';

                if (!isUndefined && !info.changelog) {
                    emitter.emit('data', 'changelog: false');
                    callback();
                } else {
                    changelog(version, function(error, data) {
                        if (error) {
                            callback(error);
                        } else {
                            prepend('ChangeLog', data, callback);

                            chlog = rmLines(data, 2);
                            chlog = markdown(chlog);
                        }
                    });
                }
            },

            function(callback) {
                versionio(version, callback);
            },

            function(callback) {
                versionio(version, {name: 'bower'}, function(error) {
                    if (error && error.code !== 'ENOENT')
                        emitter.emit('error', error);

                    callback();
                });
            },

            function(callback) {
               execute(cmd, emitter, callback);
            },

            function release(callback) {
                var isUndefined = typeof info.release === 'undefined';

                if (!isUndefined && !info.release) {
                    emitter.emit('data', 'release: false\n');
                    npmPublish(info, emitter, callback);
                } else {
                    execute(cmdTag, emitter, callback);
                }
            },

            function publish(callback) {
                var v       = 'v' + version,
                    repo    = getRepoName(info),
                    owner   = getOwner(info),
                    data    = {
                        owner       : owner,
                        repo        : repo,
                        tag_name    : v,
                        name        : info.name + ' ' + v,
                        body        : chlog
                    };

                grizzly(null, data, function(error) {
                    if (!error) {
                        emitter.emit('data', 'release: ok\n');
                        callback();
                    } else {
                        emitter.emit('data', 'Error releasing on github. Trying again.\n');
                        publish(callback);
                    }
                });
            },

            npmPublish.bind(null, info, emitter),

        ], function(error) {
            if (error)
                emitter.emit('error', error);

            emitter.emit('exit');
        });

        return emitter;
    }

    function npmPublish(info, emitter, callback) {
        if (!info.private)
            execute('npm publish', emitter, callback);
    }

    function execute(cmd, emitter, callback) {
        var rejected,
            spawn = spawnify(cmd);

        spawn.on('error', function(error) {
            rejected = ~error.message.indexOf('rejected');

            emitter.emit('error', error);

            if (rejected)
                callback(error);
        });

        spawn.on('data', function(data) {
            emitter.emit('data', data);
        });

        spawn.on('exit', function() {
            spawn = null;

            if (!rejected)
                callback();
        });
    }

    function runWisdom(type, emitter, callback) {
        var isError,
            spawn = spawnify('npm run wisdom -- ' + type);

        spawn.on('error', function(error) {
            isError = true;
            emitter.emit('error', error);
        });

        spawn.on('data', function(data) {
            emitter.emit('data', data);
        });

        spawn.on('close', function() {
            callback();
        });
    }

    function rmLines(str, count) {
        return str
            .split('\n')
            .slice(count)
            .join('\n');
    }

    function markdown(str) {
        return str
            .replace(/fix:/g, '## fix')
            .replace(/feature:/g, '## feature');
    }

    function getRepoName(json) {
        return json.repository.url
            .split('/')
            .pop()
            .replace('.git', '');
    }

    function getOwner(json) {
        var FROM_OWNER   = 3,
            WITHOUT_REPO = -1;

        return json.repository.url
            .split('/')
            .slice(FROM_OWNER, WITHOUT_REPO)
            .pop();
    }
})();
<commit_msg>feature(wisdom) add "\n"<commit_after>(function() {
    'use strict';

    var EventEmitter= require('events').EventEmitter,

        versionio   = require('version-io'),
        changelog   = require('changelog-io'),
        rendy       = require('rendy'),
        spawnify    = require('spawnify'),
        async       = require('async'),
        minor       = require('minor'),
        prepend     = require('prepend'),
        grizzly     = require('grizzly'),
        readjson    = require('readjson'),
        jessy       = require('jessy'),

        Cmd         = [
            'git add --all',
            'git commit -m "chore(package) v{{ version }}"',
            'git pull --rebase',
            'git push origin {{ branch }}',
        ].join('&&'),

        CmdTag      = [
            'git tag v{{ version }}',
            'git push origin v{{ version }}'
        ].join('&&'),

        MSG         = [ 'publish <version>',
                        'package: {{ name }} v{{ version }}'
                    ].join('\n');

    module.exports  = function(version) {
        var emitter = new EventEmitter(),
            name    = process.cwd() + '/package.json';

        readjson(name, function(error, info) {
            var msg;

            if (error) {
                msg             = error.message;
                error.message   = 'Error reading package.json: ' + msg;
                emitter.emit('error', error);
            } else if (!version) {
                emitter.emit('data', rendy(MSG, {
                    name    : info.name,
                    version : info.version
                }));
            } else {
                publish(version, info, emitter);
            }
        });

        return emitter;
    };

    function publish(version, info, emitter) {
        var cmd,
            cmdTag,
            type        = '--',
            chlog       = '';

        if (!version.indexOf('v')) {
            version  = version.slice(1);
            type    += 'v' + version;
        } else if (/major|minor|patch/.test(version)) {
            type    += version;
            version  = minor(version, info.version);
        }

        cmd = rendy(Cmd, {
            version: version,
            branch: info.branch || 'master'
        });

        cmdTag = rendy(CmdTag, {
            version: version
        });

        async.series([
            function beforePublish(callback) {
                var cmd     = jessy('scripts.wisdom', info);

                if (!cmd)
                    callback();
                else
                    runWisdom(type, emitter, callback);
            },

            function(callback) {
                var isUndefined = typeof info.changelog === 'undefined';

                if (!isUndefined && !info.changelog) {
                    emitter.emit('data', 'changelog: false\n');
                    callback();
                } else {
                    changelog(version, function(error, data) {
                        if (error) {
                            callback(error);
                        } else {
                            prepend('ChangeLog', data, callback);

                            chlog = rmLines(data, 2);
                            chlog = markdown(chlog);
                        }
                    });
                }
            },

            function(callback) {
                versionio(version, callback);
            },

            function(callback) {
                versionio(version, {name: 'bower'}, function(error) {
                    if (error && error.code !== 'ENOENT')
                        emitter.emit('error', error);

                    callback();
                });
            },

            function(callback) {
               execute(cmd, emitter, callback);
            },

            function release(callback) {
                var isUndefined = typeof info.release === 'undefined';

                if (!isUndefined && !info.release) {
                    emitter.emit('data', 'release: false\n');
                    npmPublish(info, emitter, callback);
                } else {
                    execute(cmdTag, emitter, callback);
                }
            },

            function publish(callback) {
                var v       = 'v' + version,
                    repo    = getRepoName(info),
                    owner   = getOwner(info),
                    data    = {
                        owner       : owner,
                        repo        : repo,
                        tag_name    : v,
                        name        : info.name + ' ' + v,
                        body        : chlog
                    };

                grizzly(null, data, function(error) {
                    if (!error) {
                        emitter.emit('data', 'release: ok\n');
                        callback();
                    } else {
                        emitter.emit('data', 'Error releasing on github. Trying again.\n');
                        publish(callback);
                    }
                });
            },

            npmPublish.bind(null, info, emitter),

        ], function(error) {
            if (error)
                emitter.emit('error', error);

            emitter.emit('exit');
        });

        return emitter;
    }

    function npmPublish(info, emitter, callback) {
        if (!info.private)
            execute('npm publish', emitter, callback);
    }

    function execute(cmd, emitter, callback) {
        var rejected,
            spawn = spawnify(cmd);

        spawn.on('error', function(error) {
            rejected = ~error.message.indexOf('rejected');

            emitter.emit('error', error);

            if (rejected)
                callback(error);
        });

        spawn.on('data', function(data) {
            emitter.emit('data', data);
        });

        spawn.on('exit', function() {
            spawn = null;

            if (!rejected)
                callback();
        });
    }

    function runWisdom(type, emitter, callback) {
        var isError,
            spawn = spawnify('npm run wisdom -- ' + type);

        spawn.on('error', function(error) {
            isError = true;
            emitter.emit('error', error);
        });

        spawn.on('data', function(data) {
            emitter.emit('data', data);
        });

        spawn.on('close', function() {
            callback();
        });
    }

    function rmLines(str, count) {
        return str
            .split('\n')
            .slice(count)
            .join('\n');
    }

    function markdown(str) {
        return str
            .replace(/fix:/g, '## fix')
            .replace(/feature:/g, '## feature');
    }

    function getRepoName(json) {
        return json.repository.url
            .split('/')
            .pop()
            .replace('.git', '');
    }

    function getOwner(json) {
        var FROM_OWNER   = 3,
            WITHOUT_REPO = -1;

        return json.repository.url
            .split('/')
            .slice(FROM_OWNER, WITHOUT_REPO)
            .pop();
    }
})();
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var _				= require( 'lodash' ),
	EventEmitter	= require('events').EventEmitter,
	async			= require('async'),
	util			= require( '../util'),
	loadSails		= require('./load'),
	exposeGlobals	= require('./exposeGlobals'),
	runBootstrap	= require('./bootstrap');

/**
 * Expose `Sails` constructor
 */

module.exports = Sails;

/**
 * Sails constructor
 *
 * @api private
 */

function Sails () {

	/**
	 * Expose utilities
	 *
	 * @api private
	 */

	this.util = util;

	/**
	 * Load the pieces of a Sails app
	 *
	 * @api private
	 */

	this.load = loadSails(this);

	/**
	 * Start the Sails server
	 *
	 * @api private
	 */

	this.initialize = function (cb) {

		var sails = this;

		// Indicate that server is starting
		sails.log('Starting app at ' + sails.config.appPath + '...');

		// Used to warn about possible issues if starting the server is taking a very long time
		var liftAbortTimer;

		async.auto({

			// Optionally expose services, models, sails, _, async, etc.
			exposeGlobals: exposeGlobals(sails),

			// Run the app bootstrap
			bootstrap: [ 'exposeGlobals' , runBootstrap(sails) ],

			bindBeforeShutdown: function (cb) {

				// Add beforeShutdown event
				var exiting;
				process.on('SIGINT', function() {
					beforeShutdown(process.exit);
				});
				process.on('SIGTERM', function() {
					beforeShutdown(process.exit);
				});
				process.on('exit', function() {
					if (!exiting) beforeShutdown();
				});
				function beforeShutdown(cb) {
					exiting = true;
					if(_.isFunction(sails.config.beforeShutdown)) {
						sails.config.beforeShutdown(cb);
					}
					else cb && cb();
				}

				cb();
			},

			startServer: function (cb) {

				// Start Express server (implicitly starts socket.io)
				// If host is explicitly declared, include it in express's listen() call
				if (sails.explicitHost) {
					sails.log.verbose('Restricting access to explicit host: '+sails.explicitHost);
					sails.express.server.listen(sails.config.port, sails.explicitHost, cb);
				}
				else {
					sails.express.server.listen(sails.config.port, cb);
				}

				// Start timer in case this takes suspiciously long...
				liftAbortTimer = setTimeout(function failedToStart() {
					sails.log.warn('');
					sails.log.warn('Server doesn\'t seem to be starting.');
					sails.log.warn('Perhaps something else is already running on port '+sails.config.port+ ' with hostname ' + sails.explicitHost + '?');
				}, 2500);
			},

			verifyServerStartedSuccessfully: ['startServer', function (cb) {

				// Check for port conflicts
				// Ignore this check if explicit host is set
				if(!sails.explicitHost && !sails.express.server.address()) {
					sails.log.error('Trying to start server on port ' + sails.config.port + '...');
					sails.log.error('But something else is already running on that port!');
					sails.log.error('Please disable the other server, or choose a different port, and try again.');
					process.exit(1);
				}

				cb();
			}]

		}, function (err) {
			clearTimeout(liftAbortTimer);
			return cb && cb(err);
		});

	};

	/**
	 * Factory method to generate a sails instance,
	 * lift() is also the entry point for the Sails.js runtime
	 * Loads the app, then starts the server.
	 *
	 * @api public
	 */

	this.lift = function (configOverride, cb) {

		var sails = this;

		// Stow CLI/env override
		this.config = _.clone(configOverride || {});

		async.series([

			this.load,

			this.initialize

		], function sailsReady (err, results) {

			sails.log();
			sails.log.ship();
			sails.log('Sails (v'+sails.version +')');
			sails.log('Sails lifted on port ' + sails.config.port + ' in ' + sails.config.environment + ' mode.');

			if (sails.config.environment === 'development') {
				var usingSSL = ( ( sails.config.serverOptions && sails.config.serverOptions.key && sails.config.serverOptions.cert ) ||
					( sails.config.express && sails.config.express.serverOptions && sails.config.express.serverOptions.key && sails.config.express.serverOptions.cert ));

				sails.log();
				sails.log('( to see your app, visit: ' + ( usingSSL ? 'https' : 'http' ) + '://' + sails.config.host + ':' + sails.config.port + ' )');
			}

			return cb && cb(err, sails);
		});
	};

	/**
	 * Kill the server
	 * ( Socket.io server is stopped automatically when Express server is closed )
	 *
	 * @api public
	 */

	this.lower = function (cb) {
		sails.express.server.close();
	};

	/**
	 * Run the grunt build task
	 *
	 * @api public
	 */

	this.build = function (taskName, cb) {

		// Default to 'build' task
		taskName = taskName || 'build';

		var log = this.log;
		log.info('Building assets into directory...');

		var startGrunt = require('../automation')(this);
		startGrunt(taskName, function (err) {
			if (err) return cb && cb(err);

			log.info('Successfully built \'www\' directory in the application root.');
			cb && cb();
		});
	};

	_.bindAll(this);
}

/**
 * Extend from EventEmitter to allow hooks to listen to stuff
 *
 * @api private
 */

Sails.prototype = new EventEmitter();
Sails.prototype.constructor = Sails;
Sails.prototype.after = function ( id, handler ) {

	// Make sure the object to track handlers exists
	this.__after_bindings = this.__after_bindings || {};

	// If the event handler has already fired, just fire it again
	if (this.__after_bindings[id]) {
		handler.apply(this, this.__after_bindings[id].toArray());
	}

	// Otherwise listen for when the event fires
	else {
		this.on(id, function () {

			// Fire the event handler only once
			if (!sails.__after_bindings[id]) {
				handler.apply(this, arguments.toArray());
			}

			// But remember that it's happened, so if after() is called afterwards,
			// the handler will be triggered each time
			else sails.__after_bindings[id] = arguments;
		});
	}
};

<commit_msg>Fixed bad path causing grunt to complain.<commit_after>/**
 * Module dependencies.
 */

var _				= require( 'lodash' ),
	EventEmitter	= require('events').EventEmitter,
	async			= require('async'),
	util			= require( '../util'),
	loadSails		= require('./load'),
	exposeGlobals	= require('./exposeGlobals'),
	runBootstrap	= require('./bootstrap');

/**
 * Expose `Sails` constructor
 */

module.exports = Sails;

/**
 * Sails constructor
 *
 * @api private
 */

function Sails () {

	/**
	 * Expose utilities
	 *
	 * @api private
	 */

	this.util = util;

	/**
	 * Load the pieces of a Sails app
	 *
	 * @api private
	 */

	this.load = loadSails(this);

	/**
	 * Start the Sails server
	 *
	 * @api private
	 */

	this.initialize = function (cb) {

		var sails = this;

		// Indicate that server is starting
		sails.log('Starting app at ' + sails.config.appPath + '...');

		// Used to warn about possible issues if starting the server is taking a very long time
		var liftAbortTimer;

		async.auto({

			// Optionally expose services, models, sails, _, async, etc.
			exposeGlobals: exposeGlobals(sails),

			// Run the app bootstrap
			bootstrap: [ 'exposeGlobals' , runBootstrap(sails) ],

			bindBeforeShutdown: function (cb) {

				// Add beforeShutdown event
				var exiting;
				process.on('SIGINT', function() {
					beforeShutdown(process.exit);
				});
				process.on('SIGTERM', function() {
					beforeShutdown(process.exit);
				});
				process.on('exit', function() {
					if (!exiting) beforeShutdown();
				});
				function beforeShutdown(cb) {
					exiting = true;
					if(_.isFunction(sails.config.beforeShutdown)) {
						sails.config.beforeShutdown(cb);
					}
					else cb && cb();
				}

				cb();
			},

			startServer: function (cb) {

				// Start Express server (implicitly starts socket.io)
				// If host is explicitly declared, include it in express's listen() call
				if (sails.explicitHost) {
					sails.log.verbose('Restricting access to explicit host: '+sails.explicitHost);
					sails.express.server.listen(sails.config.port, sails.explicitHost, cb);
				}
				else {
					sails.express.server.listen(sails.config.port, cb);
				}

				// Start timer in case this takes suspiciously long...
				liftAbortTimer = setTimeout(function failedToStart() {
					sails.log.warn('');
					sails.log.warn('Server doesn\'t seem to be starting.');
					sails.log.warn('Perhaps something else is already running on port '+sails.config.port+ ' with hostname ' + sails.explicitHost + '?');
				}, 2500);
			},

			verifyServerStartedSuccessfully: ['startServer', function (cb) {

				// Check for port conflicts
				// Ignore this check if explicit host is set
				if(!sails.explicitHost && !sails.express.server.address()) {
					sails.log.error('Trying to start server on port ' + sails.config.port + '...');
					sails.log.error('But something else is already running on that port!');
					sails.log.error('Please disable the other server, or choose a different port, and try again.');
					process.exit(1);
				}

				cb();
			}]

		}, function (err) {
			clearTimeout(liftAbortTimer);
			return cb && cb(err);
		});

	};

	/**
	 * Factory method to generate a sails instance,
	 * lift() is also the entry point for the Sails.js runtime
	 * Loads the app, then starts the server.
	 *
	 * @api public
	 */

	this.lift = function (configOverride, cb) {

		var sails = this;

		// Stow CLI/env override
		this.config = _.clone(configOverride || {});

		async.series([

			this.load,

			this.initialize

		], function sailsReady (err, results) {

			sails.log();
			sails.log.ship();
			sails.log('Sails (v'+sails.version +')');
			sails.log('Sails lifted on port ' + sails.config.port + ' in ' + sails.config.environment + ' mode.');

			if (sails.config.environment === 'development') {
				var usingSSL = ( ( sails.config.serverOptions && sails.config.serverOptions.key && sails.config.serverOptions.cert ) ||
					( sails.config.express && sails.config.express.serverOptions && sails.config.express.serverOptions.key && sails.config.express.serverOptions.cert ));

				sails.log();
				sails.log('( to see your app, visit: ' + ( usingSSL ? 'https' : 'http' ) + '://' + sails.config.host + ':' + sails.config.port + ' )');
			}

			return cb && cb(err, sails);
		});
	};

	/**
	 * Kill the server
	 * ( Socket.io server is stopped automatically when Express server is closed )
	 *
	 * @api public
	 */

	this.lower = function (cb) {
		sails.express.server.close();
	};

	/**
	 * Run the grunt build task
	 *
	 * @api public
	 */

	this.build = function (taskName, cb) {

		// Default to 'build' task
		taskName = taskName || 'build';

		var log = this.log;
		log.info('Building assets into directory...');

		var startGrunt = require('../grunt')(this);
		startGrunt(taskName, function (err) {
			if (err) return cb && cb(err);

			log.info('Successfully built \'www\' directory in the application root.');
			cb && cb();
		});
	};

	_.bindAll(this);
}

/**
 * Extend from EventEmitter to allow hooks to listen to stuff
 *
 * @api private
 */

Sails.prototype = new EventEmitter();
Sails.prototype.constructor = Sails;
Sails.prototype.after = function ( id, handler ) {

	// Make sure the object to track handlers exists
	this.__after_bindings = this.__after_bindings || {};

	// If the event handler has already fired, just fire it again
	if (this.__after_bindings[id]) {
		handler.apply(this, this.__after_bindings[id].toArray());
	}

	// Otherwise listen for when the event fires
	else {
		this.on(id, function () {

			// Fire the event handler only once
			if (!sails.__after_bindings[id]) {
				handler.apply(this, arguments.toArray());
			}

			// But remember that it's happened, so if after() is called afterwards,
			// the handler will be triggered each time
			else sails.__after_bindings[id] = arguments;
		});
	}
};

<|endoftext|>


<commit_before>var express           = require('express')
  , bodyParser        = require('body-parser')
  , _                 = require('underscore')
  , stringify         = require('json-stringify-safe')
  ;

var io_core           = require('./io/core')
  , io_exec           = require('./io/exec')
  , io_socket         = require('./io/socket')
  ;

function Worker() {
  var app             = express()
    , http            = require('http').Server(app)
    , io              = require('socket.io')(http)
  ;

  io.on('connection', io_socket.connection.bind(this));

  app.all('/execute', function(req, res, next){
    var id        = req.headers['$execution-id']
      , execution = this.reqs[id]
      ;

    // console.log('concurrently running', _.keys(this.reqs).length);
    delete this.reqs[id];

    (io_exec.exec.bind(this))(execution, req, res, next);
  }.bind(this));

  app.get('/stats', io_exec.stats);

  app.post('/SIGKILL', io_core.sigkill);

  app.use(io_core.catchall);

  this.http = http;
  this.io = io;
}

Worker.prototype.reqs = {};

function toString(buf) {
  var ret = buf;

  if (_.isError(buf) || _.isNaN(buf) || _.isNumber(buf) || _.isFunction(buf) || _.isRegExp(buf) || !_.isFinite(buf)) {
    ret = buf.toString();
  }

  if (_.isObject(buf) || _.isArray(buf) || _.isArguments(buf) || _.isBoolean(buf) || _.isDate(buf) || _.isNull(buf)) {
    ret = stringify(buf);
  }

  if (_.isUndefined(buf)) {
    ret = 'undefined';
  }

  return ret;
}

Worker.prototype.stdout = function(id, buf){
  this.io.to(id).emit('stdout', id, toString(buf));
};

Worker.prototype.stderr = function(id, buf){
  this.io.to(id).emit('stderr', id, toString(buf));
};

Worker.prototype.listen = function(options, cb) {
  this.http.listen(options.port, function(err, res){
    cb && cb(err, res);
  });
};

module.exports = Worker;<commit_msg>optemize<commit_after>var express           = require('express')
  , bodyParser        = require('body-parser')
  , _                 = require('underscore')
  , stringify         = require('json-stringify-safe')
  ;

var io_core           = require('./io/core')
  , io_exec           = require('./io/exec')
  , io_socket         = require('./io/socket')
  ;

function Worker() {
  var app             = express()
    , http            = require('http').Server(app)
    , io              = require('socket.io')(http)
  ;

  io.on('connection', io_socket.connection.bind(this));

  app.all('/execute', function(req, res, next){
    var id        = req.headers['$execution-id']
      , execution = this.reqs[id]
      ;

    // console.log('concurrently running', _.keys(this.reqs).length);
    delete this.reqs[id];

    (io_exec.exec.bind(this))(execution, req, res, next);
  }.bind(this));

  app.get('/stats', io_exec.stats);

  app.post('/SIGKILL', io_core.sigkill);

  app.use(io_core.catchall);

  this.http = http;
  this.io = io;
}

Worker.prototype.reqs = {};

function toString(buf) {
  var ret = buf;

  if (_.isString(buf)) {
    // nothing
  } else if (_.isError(buf) || _.isNaN(buf) || _.isNumber(buf) || _.isFunction(buf) || _.isRegExp(buf) || !_.isFinite(buf)) {
    ret = buf.toString();
  } else if (_.isObject(buf) || _.isArray(buf) || _.isArguments(buf) || _.isBoolean(buf) || _.isDate(buf) || _.isNull(buf)) {
    ret = stringify(buf);
  } else if (_.isUndefined(buf)) {
    ret = 'undefined';
  }

  return ret;
}

Worker.prototype.stdout = function(id, buf){
  this.io.to(id).emit('stdout', id, toString(buf));
};

Worker.prototype.stderr = function(id, buf){
  this.io.to(id).emit('stderr', id, toString(buf));
};

Worker.prototype.listen = function(options, cb) {
  this.http.listen(options.port, function(err, res){
    cb && cb(err, res);
  });
};

module.exports = Worker;<|endoftext|>


<commit_before>/*
 * array-zip
 * https://github.com/frozzare/array-pluck
 *
 * Copyright (c) 2014 Fredrik Forsmo
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function () {
	var args = Array.prototype.slice.call(arguments, 0);
	return args.reduce(function (a, b) {
		return a.length > b.length ? a : b;
	}, []).map(function (_, i) {
		return args.map(function (arr) {
			return arr[i];
		});
	});
};
<commit_msg>Spaces<commit_after>/*
 * array-zip
 * https://github.com/frozzare/array-pluck
 *
 * Copyright (c) 2014 Fredrik Forsmo
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function () {
  var args = Array.prototype.slice.call(arguments, 0);
  return args.reduce(function (a, b) {
    return a.length > b.length ? a : b;
  }, []).map(function (_, i) {
    return args.map(function (arr) {
      return arr[i];
    });
  });
};
<|endoftext|>


<commit_before>'use babel';

//import AtomSassView from './atom-sass-view';
import { CompositeDisposable } from 'atom';

var Compiler = require('./compiler')

export default {

  subscriptions: null,

  activate(state) {
    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();
    // Register command that toggles this view
    console.log("start");
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'atom-sass:compile': () => this.compile()
    }));
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  compile() {
    console.log('AtomSass Compile Started!');
    var compiler = new Compiler();
    //var currentView     = atom.workspace.getActiveTextEditor();
  }

};
<commit_msg>Update atom-sass.js<commit_after>'use babel';

//import AtomSassView from './atom-sass-view';
import { CompositeDisposable } from 'atom';

var Compiler = require('./compiler')

export default {

  subscriptions: null,

  activate(state) {
    // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
    this.subscriptions = new CompositeDisposable();
    // Register command that toggles this view
    this.subscriptions.add(atom.commands.add('atom-workspace', {
      'atom-sass:compile': () => this.compile()
    }));
  },

  deactivate() {
    this.subscriptions.dispose();
  },

  compile() {
    console.log('AtomSass Compile Started!');
    var compiler = new Compiler();
  }
};
<|endoftext|>


<commit_before>// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * This script is called by generate_devtools_ui_strings.py as part of the build process. It
 * parses DevTools frontend .js and module.json files, collects localizable strings, checks
 * if frontend strings are in .grd/.grdp files and reports error if present, and generates
 * {jsonKey, IDS_KEY} mappings if there is no error.
 *
 * Usage:
 *   --root_gen_dir      The root directory of the output .h and .cc files
 *   --output_header     Absolute path of the output .h file for the id mappings
 *   --output_cc         Absolute path of the output .cc file for the id mappings
 */

const checkLocalizedStrings = require('../localization_utils/check_localized_strings');
const localizationUtils = require('../localization_utils/localization_utils');

const fs = require('fs');
const path = require('path');
const {promisify} = require('util');
const writeFileAsync = promisify(fs.writeFile);

class Arguments {
  constructor(rootGenDir, outputHeaderFilePath, outputCCFilePath) {
    this.rootGenDir = rootGenDir;
    this.outputHeaderFilePath = outputHeaderFilePath;
    this.outputCCFilePath = outputCCFilePath;
  }
}

function parseArguments(args) {
  const rootGenDirIndex = args.indexOf('--root_gen_dir');
  const outputHeaderIndex = args.indexOf('--output_header');
  const outputCCIndex = args.indexOf('--output_cc');
  return new Arguments(args[rootGenDirIndex + 1], args[outputHeaderIndex + 1], args[outputCCIndex + 1]);
}

async function main() {
  const args = parseArguments(process.argv);
  let frontendStrings;
  try {
    [frontendStrings, _] = await checkLocalizedStrings.parseLocalizableResourceMaps();
  } catch (e) {
    console.log(e);
    process.exit(1);
  }

  const toAddError = checkLocalizedStrings.getAndReportResourcesToAdd();
  const toModifyError = checkLocalizedStrings.getAndReportIDSKeysToModify();
  const toRemoveError = checkLocalizedStrings.getAndReportResourcesToRemove();
  let error = `${toAddError ? `${toAddError}\n` : ''}${toModifyError ? `${toModifyError}\n` : ''}${
      toRemoveError ? `${toRemoveError}\n` : ''}`;
  if (error !== '') {
    error +=
        '\nThe errors are potentially fixable with `node third_party/devtools-frontend/src/scripts/check_localizable_resources.js --autofix`'
    console.log(error);
  }

  // Since it's part of the build system, only fail if there are strings to be added to GRD/GRDP files
  // or if there are wrong IDS_ keys.
  if (toAddError || toModifyError)
    process.exit(1);

  try {
    await generateDevToolsLocalizedStrings(args, frontendStrings);
  } catch (e) {
    console.log('Error generating id map files:');
    console.log(e.stack);
    process.exit(1);
  }
}

// Generates {jsonKey, IDS_KEY} mappings according to frontendStrings
async function generateDevToolsLocalizedStrings(args, frontendStrings) {
  const promises = [];
  const outputAbsoluteHeaderFilePath = path.join(args.rootGenDir, args.outputHeaderFilePath);
  const outputAbsoluteCCFilePath = path.join(args.rootGenDir, args.outputCCFilePath);
  const doNotEditStr =
      `// This file is automatically generated by //third_party/devtools-frontend/src/scripts/build/generate_devtools_ui_strings.js. Do not edit.`;
  const outputHeaderFileContent = `${doNotEditStr}

#ifndef CHROME_BROWSER_UI_WEBUI_DEVTOOLS_UI_STRINGS_H_
#define CHROME_BROWSER_UI_WEBUI_DEVTOOLS_UI_STRINGS_H_

#include "chrome/browser/ui/webui/localized_string.h"

namespace devtools {

constexpr unsigned int kLocalizedStringsSize = ${frontendStrings.size};
extern const LocalizedString kLocalizedStrings[kLocalizedStringsSize];

} // namespace devtools

#endif // CHROME_BROWSER_UI_WEBUI_DEVTOOLS_UI_STRINGS_H_
`;

  promises.push(writeFileAsync(outputAbsoluteHeaderFilePath, outputHeaderFileContent));

  let mappingsStr = '';
  frontendStrings.forEach((frontendString, idsKey) => {
    mappingsStr += `  {"${localizationUtils.sanitizeStringIntoCppFormat(frontendString.string)}", ${idsKey}},\n`;
  });

  const outputCCFileContent = `${doNotEditStr}

#include "${args.outputHeaderFilePath}"

#include "third_party/devtools-frontend/src/front_end/langpacks/devtools_ui_strings.h"

namespace devtools {

const LocalizedString kLocalizedStrings[] = {
${mappingsStr}};

} // namespace devtools
`;

  promises.push(writeFileAsync(outputAbsoluteCCFilePath, outputCCFileContent));
  return Promise.all(promises);
}

main();
<commit_msg>Updating paths on generate_devtools_ui_strings.js<commit_after>// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * This script is called by generate_devtools_ui_strings.py as part of the build process. It
 * parses DevTools frontend .js and module.json files, collects localizable strings, checks
 * if frontend strings are in .grd/.grdp files and reports error if present, and generates
 * {jsonKey, IDS_KEY} mappings if there is no error.
 *
 * Usage:
 *   --root_gen_dir      The root directory of the output .h and .cc files
 *   --output_header     Absolute path of the output .h file for the id mappings
 *   --output_cc         Absolute path of the output .cc file for the id mappings
 */

const checkLocalizedStrings = require('../localization/utils/check_localized_strings');
const localizationUtils = require('../localization/utils/localization_utils');

const fs = require('fs');
const path = require('path');
const {promisify} = require('util');
const writeFileAsync = promisify(fs.writeFile);

class Arguments {
  constructor(rootGenDir, outputHeaderFilePath, outputCCFilePath) {
    this.rootGenDir = rootGenDir;
    this.outputHeaderFilePath = outputHeaderFilePath;
    this.outputCCFilePath = outputCCFilePath;
  }
}

function parseArguments(args) {
  const rootGenDirIndex = args.indexOf('--root_gen_dir');
  const outputHeaderIndex = args.indexOf('--output_header');
  const outputCCIndex = args.indexOf('--output_cc');
  return new Arguments(args[rootGenDirIndex + 1], args[outputHeaderIndex + 1], args[outputCCIndex + 1]);
}

async function main() {
  const args = parseArguments(process.argv);
  let frontendStrings;
  try {
    [frontendStrings, _] = await checkLocalizedStrings.parseLocalizableResourceMaps();
  } catch (e) {
    console.log(e);
    process.exit(1);
  }

  const toAddError = checkLocalizedStrings.getAndReportResourcesToAdd();
  const toModifyError = checkLocalizedStrings.getAndReportIDSKeysToModify();
  const toRemoveError = checkLocalizedStrings.getAndReportResourcesToRemove();
  let error = `${toAddError ? `${toAddError}\n` : ''}${toModifyError ? `${toModifyError}\n` : ''}${
      toRemoveError ? `${toRemoveError}\n` : ''}`;
  if (error !== '') {
    error +=
        '\nThe errors are potentially fixable with `node third_party/devtools-frontend/src/scripts/check_localizable_resources.js --autofix`'
    console.log(error);
  }

  // Since it's part of the build system, only fail if there are strings to be added to GRD/GRDP files
  // or if there are wrong IDS_ keys.
  if (toAddError || toModifyError)
    process.exit(1);

  try {
    await generateDevToolsLocalizedStrings(args, frontendStrings);
  } catch (e) {
    console.log('Error generating id map files:');
    console.log(e.stack);
    process.exit(1);
  }
}

// Generates {jsonKey, IDS_KEY} mappings according to frontendStrings
async function generateDevToolsLocalizedStrings(args, frontendStrings) {
  const promises = [];
  const outputAbsoluteHeaderFilePath = path.join(args.rootGenDir, args.outputHeaderFilePath);
  const outputAbsoluteCCFilePath = path.join(args.rootGenDir, args.outputCCFilePath);
  const doNotEditStr =
      `// This file is automatically generated by //third_party/devtools-frontend/src/scripts/build/generate_devtools_ui_strings.js. Do not edit.`;
  const outputHeaderFileContent = `${doNotEditStr}

#ifndef CHROME_BROWSER_UI_WEBUI_DEVTOOLS_UI_STRINGS_H_
#define CHROME_BROWSER_UI_WEBUI_DEVTOOLS_UI_STRINGS_H_

#include "chrome/browser/ui/webui/localized_string.h"

namespace devtools {

constexpr unsigned int kLocalizedStringsSize = ${frontendStrings.size};
extern const LocalizedString kLocalizedStrings[kLocalizedStringsSize];

} // namespace devtools

#endif // CHROME_BROWSER_UI_WEBUI_DEVTOOLS_UI_STRINGS_H_
`;

  promises.push(writeFileAsync(outputAbsoluteHeaderFilePath, outputHeaderFileContent));

  let mappingsStr = '';
  frontendStrings.forEach((frontendString, idsKey) => {
    mappingsStr += `  {"${localizationUtils.sanitizeStringIntoCppFormat(frontendString.string)}", ${idsKey}},\n`;
  });

  const outputCCFileContent = `${doNotEditStr}

#include "${args.outputHeaderFilePath}"

#include "third_party/devtools-frontend/src/front_end/langpacks/devtools_ui_strings.h"

namespace devtools {

const LocalizedString kLocalizedStrings[] = {
${mappingsStr}};

} // namespace devtools
`;

  promises.push(writeFileAsync(outputAbsoluteCCFilePath, outputCCFileContent));
  return Promise.all(promises);
}

main();
<|endoftext|>


<commit_before>/**
 * required to include: classification-selector-modal.html
 *
 * availiable option :
 * {
 *    selector: 'classifications'
 *    use: 'name', 'id'
 * }
 *
 * $('.js_lazy-selector-attractions').classificationSelector({selector:'classifications', use:'name'});
 * $('.js_lazy-selector-venues').classificationSelector({selector:'classifications', use:'id'});
 */

(function ($) {

  $.fn.classificationSelector = function (options) {
    var defaults = {},
        settings = $.extend({}, $.fn.lazySelector.defaults, options),
        $iconButton = $('');

    var $input = $(this),
			$modal = $('#js_ls-modal-classification'),
      $form = $('#js_lazy-sel_form', $modal),
      $btnGET = $modal.find('#js_classification-modal_btn'),
      cssValidationClass = 'get-eventId_form-validation',
      modalContent = $('.modal-content', $modal),
      $jstree = $('#classification-jstree')
      ;
    var keyword = $form.find('#keyword'),
      apikey = apiKeyService.checkApiKeyCookie('tk-api-key') || $('#w-tm-api-key').val() || apiKeyService.getApiExploreKey(),
      selector = options.selector,
      use = options.use,
      eventUrl = 'https://app.ticketmaster.com/discovery/v2/' + selector + '.json';

    function  initTree(json) {
      json = setChildren(json['_embedded']['classifications']);

      $jstree.jstree({
        "core" : {
          'check_callback': true,
          'data' : json
        } ,
        "plugins" : [ "search" ] ,
        "search": {
          "show_only_matches" : true,
          /**
           * Indicates if all nodes opened to reveal the search result, should be closed when the search is cleared or a new search is performed. Default is `true`.
           * @name $.jstree.defaults.search.close_opened_onclear
           * @plugin search
           */
          "case_sensitive" : false
        }
      }).on('select_node.jstree', function (e, data) {
        data.instance.toggle_node(data.node); //set open on one click
        var i, j, r = [];
        for (i = 0, j = data.selected.length; i < j; i++) {
          r.push(
            {
              text: data.instance.get_node(data.selected[i]).text,
              id: data.instance.get_node(data.selected[i]).id
            }
          );
        }

        $('button',$jstree).off('click', setIdListener).remove();

        $('<button/>')
          .addClass('btn btn-submit btn-small')
          .text('Use')
          .attr('data-classificationId',(use === 'name') ? r[0].text : r[0].id)
          .insertAfter($('#'+r[0].id +' .jstree-clicked', $jstree))
          .on('click', setIdListener);
      });

    }

    function  updateTree(json) {
      var newJson = (json['_embedded'] && json['_embedded']['classifications']) ? setChildren(json['_embedded']['classifications']) : null;
      $jstree.jstree(true).settings.core.data = newJson;
      $jstree.jstree(true).refresh();

      if(newJson && newJson.length && newJson[0].children.length === 0){
        setTimeout(function() {
            $('.jstree-icon').hide();
          },100 );
      };
    }

    /**
     *
     * @param data {Array} - recived classifications array
     * @returns {Array}
     */
    function setChildren(data) {
      var newArrObj =[];
      data = rename(data);

      //rename parent(genres)
      data.map(function(item){
        newArrObj.push( {
          children:(item.segment._embedded && item.segment._embedded.genres)? item.segment._embedded.genres :[],
          text : item.segment.text || '',
          id : item.segment.id
        } );
      });
      //rename/copy child(subgenres) field
      newArrObj.map(function(item){
        item.children.map(function(item) {
          if(item._embedded && item._embedded.subgenres){
            item['children'] = item._embedded.subgenres ;
            delete item._embedded;
          }
        });
      });

      return newArrObj;
    }

    /**
     * Rename fields
     * @param json
     */
    function rename(json) {
      var opt ={
        root: {fieldName:['segment'], val:'text', to:'name' },
        parent: {fieldName:['genres'],'_embedded':true ,  val:'text', to:'name' },
        child: {fieldName:['subgenres'],'_embedded':true,   val:'text', to:'name'}
      };
      var arr = JSON.stringify(json);//convert array to string
      arr = JSON.parse(arr);

      function replaceAtoB(arr,opt) {
        var genresArr = [],
            subgenresArr = [];
        for (var i = 0; i<arr.length; i++) {
          arr[i][opt.root.fieldName][opt.root.val] = arr[i][opt.root.fieldName][opt.root.to];
          delete arr[i][opt.root.fieldName][opt.root.to];

          if( arr[i][opt.root.fieldName]['_embedded'] && opt.parent.fieldName in arr[i][opt.root.fieldName]['_embedded']) {
            genresArr = arr[i][opt.root.fieldName]['_embedded'][opt.parent.fieldName];
          }
          if( 0<genresArr.length ) {
            for (var ii = 0; ii < genresArr.length; ii++) {
              genresArr[ii][opt.parent.val] = genresArr[ii][opt.parent.to];
              delete genresArr[ii][opt.parent.to];

              if(genresArr[ii]['_embedded'] && genresArr[ii]['_embedded'][opt.child.fieldName]){
                subgenresArr = genresArr[ii]['_embedded'][opt.child.fieldName];
              }
              if( 0<subgenresArr.length ) {
                for (var j = 0; j < subgenresArr.length; j++) {
                  subgenresArr[j][opt.child.val] = subgenresArr[j][opt.child.to];
                  delete subgenresArr[j][opt.child.to];
                }
              }

            }
          }

        }
      }
      replaceAtoB(arr,opt);
      return arr;
    }

    /**
     * set data-selector for "GET" button
     */
    function changeModalTextListener() {
      $btnGET.attr('data-selector', selector);
      submitForm(true);
    }

    /**
     * show/hide loader
     * @param action - string ('on' or 'off')
     */
    var loading = function (action) {
      var spinner = $('#spinner-ls', $modal);
      // add the overlay with loading image to the page
      if (action == "on") {
        spinner.show();
      }
      else if (action == "off") {
        spinner.hide();
      }

    };

    function resetForm() {
      $jstree
        .jstree("destroy")
        .removeAttr('class')
        .removeAttr('role')
        .removeAttr('aria-activedescendant')
      ;
      // Clear highlight
      $form.removeClass(cssValidationClass);
    }

    /**
     * Handler for 'GET' button
     * @param pageNumero - int. used for pagination
     * @param eventUrl - url of request
     * @returns {boolean} - done/fail
     */
    function submitForm(isInit) {
      var url = ( isInit )
        ? eventUrl + '?apikey=' + apikey
        : eventUrl + '?apikey=' + apikey + '&keyword=' + keyword.val();

      $.ajax({
        dataType: 'json',
        async: true,
        url: url,
        data: $form.serialize()
      }).done(function (result) {
        if (result) {
          if (result.page.totalElements < 1) {
            loading('off');
            renderResults(null, $jstree); //add message at bottom of list
            return false;
          };

          (isInit) ? initTree(result) : updateTree(result);
          loading('off');
          $btnGET.attr('disabled', false);
        } else {
          console.log('no result found');
        }
      }).fail(function (e, textStatus, errorThrown) {
        console.log('There was an fail status - ' , e.status , errorThrown);
        loading('off');
        renderResults('FAIL', $jstree , e);
        $btnGET.attr('disabled', false);
      });

    }

    function hasScrollBar(element) {
      return element.get(0).scrollHeight > element.parent().innerHeight();
    }

    var renderResults = function (data, ulElement, errorMsg) {
      function showMessage(element, message, /*optional*/clearList) {
        if (clearList) {
          $('li', element).remove();
          $('.error-box').remove();
        }

        $('
')
          .addClass( 'error-box text-center ')
          .addClass( (data === 'FAIL')?' error-fail ': '')
            .append($('
').text(message.msg))
            .append($('
').text(message.explanation))
          .appendTo(ulElement);
      }

      $btnGET.attr('disabled', false);

      //show fail msg
      if (data === 'FAIL') {
        var msgErr = (errorMsg.responseJSON !== null )?errorMsg.responseJSON.errors[0].status : 'unknown',
          statusText = (errorMsg.responseJSON !== null )?errorMsg.responseJSON.errors[0].statusText  : errorMsg.statusText  || '',
          explanation = (errorMsg.responseJSON !== null )?errorMsg.responseJSON.errors[0].detail : 'unknown';

        showMessage($jstree, {
          msg: 'Error ' + msgErr + ': ' + statusText,
          explanation: explanation
        }, true);
        return false;
      }

      //show No results found msg
      if (data === null || !data._embedded) {
        showMessage(ulElement, {msg: 'No results found.' , explanation: 'Please try to get another keyword.'}, true);
        modalContent.removeClass('narrow');
        return false;
      }
    };

    function setIdListener(e){
      var selectedID = e.target.getAttribute('data-classificationId');
      $input.val(selectedID)
            .attr('value', selectedID)
            .trigger('change');  //update widget:

      // Close dialog
      $modal.modal('hide');
    }

    // EVENTS
    $btnGET.on('click', function (e) {
      e.preventDefault();
      if ($btnGET.attr('data-selector') !== $iconButton.attr('data-selector')) return false; //stop request

      var form = $form.get(0);
      if (!$btnGET.is(':disabled')) {
        if (form.checkValidity()) {
          $btnGET.attr('disabled', true);
          loading('on'); //show loading-spinner
          submitForm();
          //resetForm(); //clear
        } else {
          // Highlight errors
          if (form.reportValidity) form.reportValidity();
          $form.addClass(cssValidationClass);
        }
      }
    });

    $form.on("keyup", function (e) {
      var input = $(e.target);
      if (e.target.tagName === "INPUT"){
        if (e.keyCode == 13){
          input.blur();

          modalContent.removeClass('narrow');
          if ($btnGET.attr('data-selector') !== $iconButton.attr('data-selector')) return false;

          if ($form.get(0).checkValidity()) {
            loading('on');
            submitForm();
          }
        }
      }
      return false;
    });

    // Mobile devices. Force 'change' by 'Go' press
    $form.on("submit", function (e) {
      e.preventDefault();
    });

    $modal.on('hidden.bs.modal', function () {
      resetForm();
      keyword.val('');//clear search input
    });

    return this.each(function (i) {
      init($(this));

      function init(input) {
        input.wrap('

');
        input.after($iconButton);
        $iconButton.attr('data-selector', selector);

        $('#get-'+options.selector+'-'+options.use).on('click', changeModalTextListener);

      }
    });

  };

})(jQuery);

<commit_msg>mod: condition of inner check<commit_after>/**
 * required to include: classification-selector-modal.html
 *
 * availiable option :
 * {
 *    selector: 'classifications'
 *    use: 'name', 'id'
 * }
 *
 * $('.js_lazy-selector-attractions').classificationSelector({selector:'classifications', use:'name'});
 * $('.js_lazy-selector-venues').classificationSelector({selector:'classifications', use:'id'});
 */

(function ($) {

  $.fn.classificationSelector = function (options) {
    var defaults = {},
        settings = $.extend({}, $.fn.lazySelector.defaults, options),
        $iconButton = $('');

    var $input = $(this),
			$modal = $('#js_ls-modal-classification'),
      $form = $('#js_lazy-sel_form', $modal),
      $btnGET = $modal.find('#js_classification-modal_btn'),
      cssValidationClass = 'get-eventId_form-validation',
      modalContent = $('.modal-content', $modal),
      $jstree = $('#classification-jstree')
      ;
    var keyword = $form.find('#keyword'),
      apikey = apiKeyService.checkApiKeyCookie('tk-api-key') || $('#w-tm-api-key').val() || apiKeyService.getApiExploreKey(),
      selector = options.selector,
      use = options.use,
      eventUrl = 'https://app.ticketmaster.com/discovery/v2/' + selector + '.json';

    function  initTree(json) {
      json = setChildren(json['_embedded']['classifications']);

      $jstree.jstree({
        "core" : {
          'check_callback': true,
          'data' : json
        } ,
        "plugins" : [ "search" ] ,
        "search": {
          "show_only_matches" : true,
          /**
           * Indicates if all nodes opened to reveal the search result, should be closed when the search is cleared or a new search is performed. Default is `true`.
           * @name $.jstree.defaults.search.close_opened_onclear
           * @plugin search
           */
          "case_sensitive" : false
        }
      }).on('select_node.jstree', function (e, data) {
        data.instance.toggle_node(data.node); //set open on one click
        var i, j, r = [];
        for (i = 0, j = data.selected.length; i < j; i++) {
          r.push(
            {
              text: data.instance.get_node(data.selected[i]).text,
              id: data.instance.get_node(data.selected[i]).id
            }
          );
        }

        $('button',$jstree).off('click', setIdListener).remove();

        $('<button/>')
          .addClass('btn btn-submit btn-small')
          .text('Use')
          .attr('data-classificationId',(use === 'name') ? r[0].text : r[0].id)
          .insertAfter($('#'+r[0].id +' .jstree-clicked', $jstree))
          .on('click', setIdListener);
      });

    }

    function  updateTree(json) {
      var newJson = (json['_embedded'] && json['_embedded']['classifications']) ? setChildren(json['_embedded']['classifications']) : null;
      $jstree.jstree(true).settings.core.data = newJson;
      $jstree.jstree(true).refresh();

      if(newJson && newJson.length && newJson[0].children.length === 0){
        setTimeout(function() {
            $('.jstree-icon').hide();
          },100 );
      };
    }

    /**
     *
     * @param data {Array} - recived classifications array
     * @returns {Array}
     */
    function setChildren(data) {
      var newArrObj =[];
      data = rename(data);

      //rename parent(genres)
      data.map(function(item){
        newArrObj.push( {
          children:(item.segment._embedded && item.segment._embedded.genres)? item.segment._embedded.genres :[],
          text : item.segment.text || '',
          id : item.segment.id
        } );
      });
      //rename/copy child(subgenres) field
      newArrObj.map(function(item){
        item.children.map(function(item) {
          if(item._embedded && item._embedded.subgenres){
            item['children'] = item._embedded.subgenres ;
            delete item._embedded;
          }
        });
      });

      return newArrObj;
    }

    /**
     * Rename fields
     * @param json
     */
    function rename(json) {
      var opt ={
        root: {fieldName:['segment'], val:'text', to:'name' },
        parent: {fieldName:['genres'],'_embedded':true ,  val:'text', to:'name' },
        child: {fieldName:['subgenres'],'_embedded':true,   val:'text', to:'name'}
      };
      var arr = JSON.stringify(json);//convert array to string
      arr = JSON.parse(arr);

      function replaceAtoB(arr,opt) {
        var genresArr = [],
            subgenresArr = [];
        for (var i = 0; i<arr.length; i++) {
          arr[i][opt.root.fieldName][opt.root.val] = arr[i][opt.root.fieldName][opt.root.to];
          delete arr[i][opt.root.fieldName][opt.root.to];

          if( arr[i][opt.root.fieldName]['_embedded'] && opt.parent.fieldName in arr[i][opt.root.fieldName]['_embedded']) {
            genresArr = arr[i][opt.root.fieldName]['_embedded'][opt.parent.fieldName];
          }
          if( 0<genresArr.length ) {
            for (var ii = 0; ii < genresArr.length; ii++) {
              genresArr[ii][opt.parent.val] = genresArr[ii][opt.parent.to];
              delete genresArr[ii][opt.parent.to];

              if(genresArr[ii]['_embedded'] && genresArr[ii]['_embedded'][opt.child.fieldName]){
                subgenresArr = genresArr[ii]['_embedded'][opt.child.fieldName];
              }
              if( 0<subgenresArr.length ) {
                for (var j = 0; j < subgenresArr.length; j++) {
                  subgenresArr[j][opt.child.val] = subgenresArr[j][opt.child.to];
                  if(j>0) delete subgenresArr[j][opt.child.to];//skip zero item
                }
              }

            }
          }

        }
      }
      replaceAtoB(arr,opt);
      return arr;
    }

    /**
     * set data-selector for "GET" button
     */
    function changeModalTextListener() {
      $btnGET.attr('data-selector', selector);
      submitForm(true);
    }

    /**
     * show/hide loader
     * @param action - string ('on' or 'off')
     */
    var loading = function (action) {
      var spinner = $('#spinner-ls', $modal);
      // add the overlay with loading image to the page
      if (action == "on") {
        spinner.show();
      }
      else if (action == "off") {
        spinner.hide();
      }

    };

    function resetForm() {
      $jstree
        .jstree("destroy")
        .removeAttr('class')
        .removeAttr('role')
        .removeAttr('aria-activedescendant')
      ;
      // Clear highlight
      $form.removeClass(cssValidationClass);
    }

    /**
     * Handler for 'GET' button
     * @param pageNumero - int. used for pagination
     * @param eventUrl - url of request
     * @returns {boolean} - done/fail
     */
    function submitForm(isInit) {
      var url = ( isInit )
        ? eventUrl + '?apikey=' + apikey
        : eventUrl + '?apikey=' + apikey + '&keyword=' + keyword.val();

      $.ajax({
        dataType: 'json',
        async: true,
        url: url,
        data: $form.serialize()
      }).done(function (result) {
        if (result) {
          if (result.page.totalElements < 1) {
            loading('off');
            renderResults(null, $jstree); //add message at bottom of list
            return false;
          };

          (isInit) ? initTree(result) : updateTree(result);
          loading('off');
          $btnGET.attr('disabled', false);
        } else {
          console.log('no result found');
        }
      }).fail(function (e, textStatus, errorThrown) {
        console.log('There was an fail status - ' , e.status , errorThrown);
        loading('off');
        renderResults('FAIL', $jstree , e);
        $btnGET.attr('disabled', false);
      });

    }

    function hasScrollBar(element) {
      return element.get(0).scrollHeight > element.parent().innerHeight();
    }

    var renderResults = function (data, ulElement, errorMsg) {
      function showMessage(element, message, /*optional*/clearList) {
        if (clearList) {
          $('li', element).remove();
          $('.error-box').remove();
        }

        $('
')
          .addClass( 'error-box text-center ')
          .addClass( (data === 'FAIL')?' error-fail ': '')
            .append($('
').text(message.msg))
            .append($('
').text(message.explanation))
          .appendTo(ulElement);
      }

      $btnGET.attr('disabled', false);

      //show fail msg
      if (data === 'FAIL') {
        var msgErr = (errorMsg.responseJSON !== null )?errorMsg.responseJSON.errors[0].status : 'unknown',
          statusText = (errorMsg.responseJSON !== null )?errorMsg.responseJSON.errors[0].statusText  : errorMsg.statusText  || '',
          explanation = (errorMsg.responseJSON !== null )?errorMsg.responseJSON.errors[0].detail : 'unknown';

        showMessage($jstree, {
          msg: 'Error ' + msgErr + ': ' + statusText,
          explanation: explanation
        }, true);
        return false;
      }

      //show No results found msg
      if (data === null || !data._embedded) {
        showMessage(ulElement, {msg: 'No results found.' , explanation: 'Please try to get another keyword.'}, true);
        modalContent.removeClass('narrow');
        return false;
      }
    };

    function setIdListener(e){
      var selectedID = e.target.getAttribute('data-classificationId');
      $input.val(selectedID)
            .attr('value', selectedID)
            .trigger('change');  //update widget:

      // Close dialog
      $modal.modal('hide');
    }

    // EVENTS
    $btnGET.on('click', function (e) {
      e.preventDefault();
      if ($btnGET.attr('data-selector') !== $iconButton.attr('data-selector')) return false; //stop request

      var form = $form.get(0);
      if (!$btnGET.is(':disabled')) {
        if (form.checkValidity()) {
          $btnGET.attr('disabled', true);
          loading('on'); //show loading-spinner
          submitForm();
          //resetForm(); //clear
        } else {
          // Highlight errors
          if (form.reportValidity) form.reportValidity();
          $form.addClass(cssValidationClass);
        }
      }
    });

    $form.on("keyup", function (e) {
      var input = $(e.target);
      if (e.target.tagName === "INPUT"){
        if (e.keyCode == 13){
          input.blur();

          modalContent.removeClass('narrow');
          if ($btnGET.attr('data-selector') !== $iconButton.attr('data-selector')) return false;

          if ($form.get(0).checkValidity()) {
            loading('on');
            submitForm();
          }
        }
      }
      return false;
    });

    // Mobile devices. Force 'change' by 'Go' press
    $form.on("submit", function (e) {
      e.preventDefault();
    });

    $modal.on('hidden.bs.modal', function () {
      resetForm();
      keyword.val('');//clear search input
    });

    return this.each(function (i) {
      init($(this));

      function init(input) {
        input.wrap('

');
        input.after($iconButton);
        $iconButton.attr('data-selector', selector);

        $('#get-'+options.selector+'-'+options.use).on('click', changeModalTextListener);

      }
    });

  };

})(jQuery);

<|endoftext|>


<commit_before>var PayPalController = require('../PayPal/PayPalController');

var Orders = function(data){

    function createOrder (req, res){
        var validatedData = validateData(req);

        console.log('asd');
        PayPalController.pay({paymentInfo:''}).then(function (data) {
           res.json({
               payment:data
           });
        }, function (error) {
           res.json({
               error:error
           });
        });

        //if(!data){
        //    return false;
        //}
        //
        //data.orders.create(validatedData)
        //    .then(function (createdOrder){
        //        res.json({
        //            success: true,
        //            data: createdOrder
        //        });
        //    }, function (error){
        //        res.render('error', {
        //            message: 'Cannot create order!',
        //            error: error
        //        });
        //    })
    }

    function validateData (req){
        var data = req.body,
            user = req.user,
            validatedData = {};

        //Validate User
        if (user.ID) {
            validatedData.userId = user.ID;
        } else {
            return false;
        }

        //Validated order items
        if (data.items) {
            validatedData.items = data.items;
        } else {
            return false;
        }

        //Validate payment method
        if (data.paymentMethod) {
            if(data.paymentMethod == 'credit-card'){
                //Validate billing address
                if (data.creditCardInfo) {
                    validatedData.creditCardInfo = data.creditCardInfo;
                } else {
                    return false;
                }
            }
            validatedData.paymentMethod = data.paymentMethod;
        } else {
            return false;
        }

        //Validate delivery address
        if (data.deliveryAddress) {
            validatedData.deliveryAddress = data.deliveryAddress;
        } else {
            return false;
        }

        //Validate billing address
        if (data.billingAddress) {
            validatedData.billingAddress = data.billingAddress;
        } else {
            return false;
        }

        //Add comment if available
        if (data.comment) {
            validatedData.comment = data.comment;
        }
    }

    return {
        createOrder: createOrder
    };
};

module.exports = Orders;
<commit_msg>Orders backend controller make credit card payment functionality. More data validation and connected to use paypal controller.<commit_after>var PayPalController = require('../PayPal/PayPalController'),
    Q = require('Q'),
    config = require('../../../config/config');

var Orders = function(data){

    function validateData (req){
        var data = req.body,
            user = req.user,
            validatedData = {};

        //Validate Registered user User
        if (user) {
            validatedData.relatedRegisteredUserId = user.ID;
        };

        //Validate user info
        if(data.firstname && data.lastname && data.email && data.phoneNumber){
            validatedData.userInfo = {
                firstName: data.firstname,
                lastName: data.lastname,
                email: data.email,
                phoneNumber: data.phoneNumber
            }
        }else{
            return {error:'Wrong User info!'};
        }

        //Validated order items
        if (data.items) {
            validatedData.items = data.items;
        } else {
            return {error:'No Items!'};
        }

        //Validate payment method and related info
        if (data.paymentMethod) {
            if(data.paymentMethod == 'credit-card'){
                //Validate billing address
                if (data.cardNumber && data.cardOwnerName &&
                    data.cardCvv &&
                    data.cardExpiresMonth &&
                    data.cardExpiresYear
            ) {
                    var userNames = data.cardOwnerName.split(' ');
                    validatedData.paymentInfo = {
                        creditCardNumber: data.cardNumber,
                        creditCardType: data.cardType,
                        creditCardExpireMonth: data.cardExpiresMonth,
                        creditCardExpireYear: data.cardExpiresYear,
                        creditCardCCV: data.cardCvv,
                        creditCardFirstName: userNames[0],
                        creditCardLastName: userNames[1]
                    };
                } else {
                    return {error:'No Credit Card info!'};
                }
            }
            validatedData.paymentMethod = data.paymentMethod;
        } else {
            return {error:'No Payment Method!'};
        }

        //Validate delivery address
        if (data.country && data.city && data.address && data.postalCode) {
            validatedData.deliveryAddress = {
                country: data.country,
                city: data.city,
                address: data.address,
                zip: data.postalCode
            };
            validatedData.billingAddress = {
                country: data.country,
                city: data.city,
                address: data.address,
                zip: data.postalCode
            };
        } else {
            return {error:'Incorrect delivery info!'};;
        }

        //Add comment if available
        if (data.comment) {
            validatedData.comment = data.comment;
        }

        //If no problems
        return validatedData;
    };

    function createOrder (req, res){
        var validatedData = validateData(req);
        //TODO save userId to order if logged in
        if(validatedData.error){
            res.json({
                success: false,
                message: validatedData.error
            });
            return;
        };

        //Adjust order status to awaiting payment
        validatedData.status = 'awaiting_payment';

        //Save order
        data.orders.createOrder(validatedData)
            .then(function (createdOrder){
            //Process payment
                console.log('1');
                //Credit Card
                if(validatedData.paymentMethod == 'credit-card'){

                    payOrderWithCreditCard(validatedData.paymentInfo, createdOrder).then(function (paymentData) {
                        console.log('6');
                        //Update the order with the payment data on success
                        var paymentDataToUpdate = {
                            payment: {
                                method: 'creditCard',
                                creditCard : paymentData,
                                paypal: {}
                            },
                            status: 'paid'
                        };
                        updateOrderPayment(createdOrder._id, paymentDataToUpdate).then(function (updatedOrderWithPayment) {
                            console.log('8');
                            res.json({
                                success: true,
                                message: 'Order payed with credit card and updated successfully!'
                            });
                        }, function (error) {
                            res.json({
                                success: false,
                                message: 'Updating order with payment failed, but payment with credit card was successful!',
                                error:error
                            });
                        });

                    }, function (error) {

                        res.json({
                            success: false,
                            message: 'Payment for order failed!',
                            error:error
                        });

                    });

                }else if (validatedData.paymentMethod == 'paypal'){
                    //TODO call paypal payment here

                }

            },
            //Error creating order
            function (error){
                res.render('error', {
                    success: false,
                    message: 'Cannot create order!',
                    error: error
                });
            });
    };

    function payOrderWithCreditCard (orderFormData, orderData) {
        var deferred = Q.defer(),
            amountTotal = 10;
        //TODO Calculate total amount of items in order

        //Create payment info object
        var paymentInfo = {
            creditCardNumber : orderFormData.creditCardNumber,
            creditCardType: orderFormData.creditCardType,
            creditCardExpireMonth: orderFormData.creditCardExpireMonth,
            creditCardExpireYear: orderFormData.creditCardExpireYear,
            creditCardCCV: orderFormData.creditCardCCV,
            creditCardFirstName: orderFormData.creditCardFirstName,
            creditCardLastName: orderFormData.creditCardLastName,
            amountTotal: amountTotal,
            currency: 'USD',
            description: 'Payment for order' + orderData._id
        };
        console.log('2');
        PayPalController.makeCreditCardPayment(paymentInfo).then(function (data) {
                console.log('5');
                //Payment is complete.
                deferred.resolve(data);

            },
            //Error from creditCard payment
            function (error) {
                deferred.reject(error);
                return deferred.promise;
            });
        return deferred.promise;
    };

    function payOrderWithPayPal (paymentData) {
        var deferred = Q.defer();
        //Create payment info object
        var paymentInfo = {
            "intent": "sale",
            "payer": {
                "payment_method": 'paypal'
            },
            "redirect_urls": {
                "return_url": "http://localhost:3310/execute",
                "cancel_url": "http://localhost:3310/cancel"
            },
            "transactions": [{
                "amount": {
                    "total": "5.00",
                    "currency": "USD"
                },
                "description": "My awesome payment"
            }]
        };

        PayPalController.pay(paymentInfo).then(function (data) {
                //Payment is complete. Update order
                var paymentInfo = data;

                updateOrderPayment(paymentInfo).then(function (updatedOrder) {
                    deferred.resolve(updatedOrder);
                }, function (error) {
                    deferred.reject(error);
                    return deferred.promise;
                });

                return deferred.promise;
            },
            //Error from paypal payment
            function (error) {
                res.json({
                    error:error
                });
            });
    }

    function updateOrderPayment (orderId , paymentInfoData) {
        var deferred = Q.defer();
        console.log('8',data.orders);
        data.orders.updateById(orderId , paymentInfoData).then(function (updatedOrder) {
                console.log('9');
                deferred.resolve(updatedOrder);
            },
            //Error updating order with payment info
            function (error) {
                deferred.reject(error);
                return deferred.promise;
            });
        return deferred.promise;
    };

    return {
        createOrder: createOrder
    };
};

module.exports = Orders;
<|endoftext|>


<commit_before>//# sourceURL=workflowControls.js

'use strict';

window.smartRApp.directive('workflowControls', [
    '$rootScope',
    function($rootScope) {
        return {
            restrict: 'E',
            transclude: true,
            templateUrl: $rootScope.smartRPath + '/js/smartR/_angular/templates/workflowControls.html',
            link: function(scope, element) {
                var templateHider = element.children()[0],
                    templateControls = element.children()[1];
                scope.hidden = false;
                templateHider.style.bottom = templateControls.clientHeight + 'px';
                templateHider.addEventListener('click', function() {
                    if (scope.hidden) {
                        templateControls.style.visibility = 'visible';
                        templateHider.style.bottom = templateControls.clientHeight + 'px';
                        $(templateHider).text('Hide');
                        scope.hidden = false;
                    } else {
                        templateControls.style.visibility = 'hidden';
                        templateHider.style.bottom = 0;
                        $(templateHider).text('Show');
                        scope.hidden = true;
                    }
                });
            }
        };
    }
]);
<commit_msg>fixed minor issue in workflow controls<commit_after>//# sourceURL=workflowControls.js

'use strict';

window.smartRApp.directive('workflowControls', [
    '$rootScope',
    function($rootScope) {
        return {
            restrict: 'E',
            transclude: true,
            templateUrl: $rootScope.smartRPath + '/js/smartR/_angular/templates/workflowControls.html',
            link: function(scope, element) {
                scope.$evalAsync(function() {
                    var templateHider = element.children()[0],
                        templateControls = element.children()[1];
                    scope.hidden = false;
                    templateHider.style.bottom = templateControls.clientHeight + 'px';
                    templateHider.addEventListener('click', function() {
                        if (scope.hidden) {
                            templateControls.style.visibility = 'visible';
                            templateHider.style.bottom = templateControls.clientHeight + 'px';
                            $(templateHider).text('Hide');
                            scope.hidden = false;
                        } else {
                            templateControls.style.visibility = 'hidden';
                            templateHider.style.bottom = 0;
                            $(templateHider).text('Show');
                            scope.hidden = true;
                        }
                    });
                });
            }
        };
    }
]);
<|endoftext|>


<commit_before>import mongoose from 'mongoose'
import logger from './logger'
import config from '../config'

mongoose.Promise = global.Promise

export default function connectMongoDB () {
  mongoose.connect(config.mongoDB.uri, config.mongoDB.options)

  mongoose.connection
    .on('connected', () => logger.verbose(`Mongoose connection open to ${config.mongoDB.uri}`))
    .on('disconnected', () => logger.verbose('Mongoose connection disconnected'))
    .on('error', (err) => logger.error(`Mongoose connection error: ${err}`))

  process.on('SIGINT', () => {
    mongoose.connection.close(() => {
      logger.verbose('Mongoose connection disconnected through app termination')
      process.exit(0)
    })
  })
}
<commit_msg>refactor: remove logger<commit_after>import mongoose from 'mongoose'
import config from '../config'

mongoose.Promise = global.Promise

export default function connectMongoDB () {
  mongoose.connect(config.mongoDB.uri, config.mongoDB.options)

  mongoose.connection
    .on('connected', () => console.log(`Mongoose connection open to ${config.mongoDB.uri}`))
    .on('disconnected', () => console.log('Mongoose connection disconnected'))
    .on('error', (err) => console.error(`Mongoose connection error: ${err}`))

  process.on('SIGINT', () => {
    mongoose.connection.close(() => {
      console.log('Mongoose connection disconnected through app termination')
      process.exit(0)
    })
  })
}
<|endoftext|>


<commit_before>// export your constants
const types = {
    LOGIN_REQUEST: 'LOGIN_REQUEST',
    LOGIN_SUCCESS: 'LOGIN_SUCCESS',
    LOGIN_FAILURE: 'LOGIN_FAILURE',
    LOGOUT_REQUEST: 'LOGOUT_REQUEST',
    LOGOUT_SUCCESS: 'LOGOUT_SUCCESS',
    ADD_SHIPPING: 'ADD_SHIPPING',
    ADD_PAYMENT: 'ADD_PAYMENT',
    SAME_AS_SHIPPING: 'SAME_AS_SHIPPING',
    SUBMIT_REQUEST: 'SUBMIT_REQUEST',
    SUBMIT_SUCCESS: 'SUBMIT_SUCCESS',
    SUBMIT_FAILURE: 'SUBMIT_FAILURE',
    CREATE_PAGE: 'CREATE_PAGE',
    READ_PAGE: 'READ_PAGE',
    EDIT_PAGE: 'EDIT_PAGE',
    SAVE_PAGE_REQUEST: 'SAVE_PAGE_REQUEST',
    SAVE_PAGE_SUCCESS: 'SAVE_PAGE_SUCCESS',
    SAVE_PAGE_FAILURE: 'SAVE_PAGE_FAILURE',
    FETCH_PAGE_REQUEST: 'FETCH_PAGE_REQUEST',
    FETCH_PAGE_SUCCESS: 'FETCH_PAGE_SUCCESS',
    FETCH_PAGE_FAILURE: 'FETCH_PAGE_FAILURE',
    DELETE_PAGE: 'DELETE_PAGE',
    AVAILABILITY_FETCH_REQUEST: 'AVAILABILITY_FETCH_REQUEST',
    AVAILABILITY_FETCH_SUCCESS: 'AVAILABILITY_FETCH_SUCCESS',
    AVAILABILITY_FETCH_FAILURE: 'AVAILABILITY_FETCH_FAILURE',
    ADD_TO_CART: 'ADD_TO_CART'
}

export default types
<commit_msg>new types for fetching strain list<commit_after>// export your constants
const types = {
    LOGIN_REQUEST: 'LOGIN_REQUEST',
    LOGIN_SUCCESS: 'LOGIN_SUCCESS',
    LOGIN_FAILURE: 'LOGIN_FAILURE',
    LOGOUT_REQUEST: 'LOGOUT_REQUEST',
    LOGOUT_SUCCESS: 'LOGOUT_SUCCESS',
    ADD_SHIPPING: 'ADD_SHIPPING',
    ADD_PAYMENT: 'ADD_PAYMENT',
    SAME_AS_SHIPPING: 'SAME_AS_SHIPPING',
    SUBMIT_REQUEST: 'SUBMIT_REQUEST',
    SUBMIT_SUCCESS: 'SUBMIT_SUCCESS',
    SUBMIT_FAILURE: 'SUBMIT_FAILURE',
    CREATE_PAGE: 'CREATE_PAGE',
    READ_PAGE: 'READ_PAGE',
    EDIT_PAGE: 'EDIT_PAGE',
    SAVE_PAGE_REQUEST: 'SAVE_PAGE_REQUEST',
    SAVE_PAGE_SUCCESS: 'SAVE_PAGE_SUCCESS',
    SAVE_PAGE_FAILURE: 'SAVE_PAGE_FAILURE',
    FETCH_PAGE_REQUEST: 'FETCH_PAGE_REQUEST',
    FETCH_PAGE_SUCCESS: 'FETCH_PAGE_SUCCESS',
    FETCH_PAGE_FAILURE: 'FETCH_PAGE_FAILURE',
    DELETE_PAGE: 'DELETE_PAGE',
    AVAILABILITY_FETCH_REQUEST: 'AVAILABILITY_FETCH_REQUEST',
    AVAILABILITY_FETCH_SUCCESS: 'AVAILABILITY_FETCH_SUCCESS',
    AVAILABILITY_FETCH_FAILURE: 'AVAILABILITY_FETCH_FAILURE',
    ADD_TO_CART: 'ADD_TO_CART',
    STRAINS_FETCH_REQUEST: 'STRAINS_FETCH_REQUEST',
    STRAINS_FETCH_SUCCESS: 'STRAINS_FETCH_SUCCESS',
    STRAINS_FETCH_FAILURE: 'STRAINS_FETCH_FAILURE'
}

export default types
<|endoftext|>


<commit_before>// @flow
import React from 'react'
import ClickableBox from './clickable-box'
import Text from './text'
import glamorous from 'glamorous-native'
import {globalStyles, globalColors} from '../styles'

import type {Props} from './radio-button'

export const RADIOBUTTON_SIZE = 22
export const RADIOBUTTON_MARGIN = 8

const RadioOuterBox = glamorous(ClickableBox)({
  backgroundColor: globalColors.white,
  borderRadius: 100,
  borderWidth: 1,
  height: RADIOBUTTON_SIZE,
  marginRight: RADIOBUTTON_MARGIN,
  position: 'relative',
  width: RADIOBUTTON_SIZE,
}, ({disabled, selected}) => ({
  borderColor: selected ? globalColors.blue : globalColors.black_10,
  opacity: disabled ? 0.4 : 1,
}))

const RadioInnerBox = glamorous(ClickableBox)({
  borderColor: globalColors.white,
  borderRadius: 10,
  borderWidth: 5,
  left: 5,
  position: 'absolute',
  top: 5,
}, ({selected}) => ({
  borderColor: selected ? globalColors.blue : globalColors.white
}))

const RadioButton = ({disabled, label, onSelect, selected, style}: Props) => {
  return (
  <ClickableBox
    style={{...styleContainer, ...style}}
    onClick={disabled ? undefined : () => onSelect(!selected)}
  >
    <RadioOuterBox disabled={disabled} selected={selected}>
      <RadioInnerBox selected={selected} />
    </RadioOuterBox>

    <Text type="Body" style={{color: globalColors.black_75}}>{label}</Text>
  </ClickableBox>
)
}

const styleContainer = {
  ...globalStyles.flexBoxRow,
  alignItems: 'center',
}

export default RadioButton
<commit_msg>prettier<commit_after>// @flow
import React from 'react'
import ClickableBox from './clickable-box'
import Text from './text'
import glamorous from 'glamorous-native'
import {globalStyles, globalColors} from '../styles'

import type {Props} from './radio-button'

export const RADIOBUTTON_SIZE = 22
export const RADIOBUTTON_MARGIN = 8

const RadioOuterCircle = glamorous(ClickableBox)(
  {
    backgroundColor: globalColors.white,
    borderRadius: 100,
    borderWidth: 1,
    height: RADIOBUTTON_SIZE,
    marginRight: RADIOBUTTON_MARGIN,
    position: 'relative',
    width: RADIOBUTTON_SIZE,
  },
  ({disabled, selected}) => ({
    borderColor: selected ? globalColors.blue : globalColors.black_10,
    opacity: disabled ? 0.4 : 1,
  })
)

const RadioInnerCircle = glamorous(ClickableBox)(
  {
    borderColor: globalColors.white,
    borderRadius: 10,
    borderWidth: 5,
    left: 5,
    position: 'absolute',
    top: 5,
  },
  ({selected}) => ({
    borderColor: selected ? globalColors.blue : globalColors.white,
  })
)

const RadioButton = ({disabled, label, onSelect, selected, style}: Props) => (
  <ClickableBox
    style={{...styleContainer, ...style}}
    onClick={disabled ? undefined : () => onSelect(!selected)}
  >
    <RadioOuterCircle disabled={disabled} selected={selected}>
      <RadioInnerCircle selected={selected} />
    </RadioOuterCircle>

    <Text type="Body" style={{color: globalColors.black_75}}>{label}</Text>
  </ClickableBox>
)

const styleContainer = {
  ...globalStyles.flexBoxRow,
  alignItems: 'center',
}

export default RadioButton
<|endoftext|>


<commit_before>/**
 * Group是一个容器，可以插入子节点，Group的变换也会被应用到子节点上
 * @module zrender/graphic/Group
 * @example
 *     var Group = require('zrender/graphic/Group');
 *     var Circle = require('zrender/graphic/shape/Circle');
 *     var g = new Group();
 *     g.position[0] = 100;
 *     g.position[1] = 100;
 *     g.addChild(new Circle({
 *         style: {
 *             x: 100,
 *             y: 100,
 *             r: 20,
 *         }
 *     }));
 *     zr.addGroup(g);
 */
define(function (require) {

    var zrUtil = require('../core/util');
    var Element = require('../Element');
    var BoundingRect = require('../core/BoundingRect');

    var tmpMat = [];

    /**
     * @alias module:zrender/graphic/Group
     * @constructor
     * @extends module:zrender/mixin/Transformable
     * @extends module:zrender/mixin/Eventful
     */
    var Group = function (opts) {

        opts = opts || {};

        Element.call(this, opts);

        for (var key in opts) {
            this[key] = opts[key];
        }

        this._children = [];

        this.__storage = null;

        this.__dirty = true;
    };

    Group.prototype = {

        constructor: Group,

        /**
         * @type {string}
         */
        type: 'group',

        /**
         * 复制并返回一份新的包含所有儿子节点的数组
         * @return {Array.<module:zrender/Element>}
         */
        children: function () {
            return this._children.slice();
        },

        /**
         * 获取指定 index 的儿子节点
         * @param  {number} idx
         * @return {module:zrender/Element}
         */
        childAt: function (idx) {
            return this._children[idx];
        },

        /**
         * 添加子节点
         * @param {module:zrender/Element} child
         */
        // TODO Type Check
        add: function (child) {
            if (child == this) {
                return;
            }

            if (child.parent == this) {
                return;
            }
            if (child.parent) {
                child.parent.removeChild(child);
            }

            this._children.push(child);
            child.parent = this;

            var storage = this.__storage;
            if (storage && storage !== child.__storage) {

                storage.addToMap(child);

                if (child instanceof Group) {
                    child.addChildrenToStorage(storage);
                }
            }

            this.__zr && this.__zr.refresh();

            return this;
        },

        /**
         * 移除子节点
         * @param {module:zrender/Element} child
         */
        // TODO Type Check
        remove: function (child) {
            var idx = zrUtil.indexOf(this._children, child);

            if (idx >= 0) {
                this._children.splice(idx, 1);
            }
            child.parent = null;

            var storage = this.__storage;
            if (storage) {

                storage.delFromMap(child.id);

                if (child instanceof Group) {
                    child.delChildrenFromStorage(storage);
                }
            }

            this.__zr && this.__zr.refresh();

            return this;
        },

        /**
         * 移除所有子节点
         */
        removeAll: function () {
            var children = this._children;
            var storage = this.__storage;
            var child;
            var i;
            for (i = 0; i < children.length; i++) {
                child = children[i];
                if (storage) {
                    storage.delFromMap(child.id);
                    if (child instanceof Group) {
                        child.delChildrenFromStorage(storage);
                    }
                }
                child.parent = null;
            }
            children.length = 0;

            return this;
        },

        /**
         * 遍历所有子节点
         * @param  {Function} cb
         * @param  {}   context
         */
        eachChild: function (cb, context) {
            var haveContext = !!context;
            for (var i = 0; i < this._children.length; i++) {
                var child = this._children[i];
                if (haveContext) {
                    cb.call(context, child);
                } else {
                    cb(child);
                }
            }
            return this;
        },

        /**
         * 深度优先遍历所有子孙节点
         * @param  {Function} cb
         * @param  {}   context
         */
        traverse: function (cb, context) {
            var haveContext = !!context;
            for (var i = 0; i < this._children.length; i++) {
                var child = this._children[i];
                if (haveContext) {
                    cb.call(context, child);
                } else {
                    cb(child);
                }

                if (child.type === 'group') {
                    child.traverse(cb, context);
                }
            }
            return this;
        },

        addChildrenToStorage: function (storage) {
            for (var i = 0; i < this._children.length; i++) {
                var child = this._children[i];
                storage.addToMap(child);
                if (child instanceof Group) {
                    child.addChildrenToStorage(storage);
                }
            }
        },

        delChildrenFromStorage: function (storage) {
            for (var i = 0; i < this._children.length; i++) {
                var child = this._children[i];
                storage.delFromMap(child.id);
                if (child instanceof Group) {
                    child.delChildrenFromStorage(storage);
                }
            }
        },

        dirty: function () {
            this.__dirty = true;
            this.__zr && this.__zr.refresh();
            return this;
        },

        /**
         * @return {module:zrender/core/BoundingRect}
         */
        getBoundingRect: function () {
            // TODO Caching
            // TODO Transform
            var rect;
            var tmpRect = new BoundingRect(0, 0, 0, 0);
            var children = this._children;
            for (var i = 0; i < children.length; i++) {
                var child = children[i];
                var childRect = child.getBoundingRect();
                var transform = child.getLocalTransform(tmpMat);
                rect = rect || childRect.clone();
                if (transform) {
                    tmpRect.copy(childRect);
                    tmpRect.applyTransform(transform);
                    rect.union(tmpRect);
                }
                else {
                    rect.union(childRect);
                }
            }
            return rect || new BoundingRect(0, 0, 0, 0);
        },

        update: function () {
            this.updateTransform();
            return this;
        }
    };

    zrUtil.inherits(Group, Element);

    return Group;
});<commit_msg>Group#add, Group#remove is more robust<commit_after>/**
 * Group是一个容器，可以插入子节点，Group的变换也会被应用到子节点上
 * @module zrender/graphic/Group
 * @example
 *     var Group = require('zrender/graphic/Group');
 *     var Circle = require('zrender/graphic/shape/Circle');
 *     var g = new Group();
 *     g.position[0] = 100;
 *     g.position[1] = 100;
 *     g.addChild(new Circle({
 *         style: {
 *             x: 100,
 *             y: 100,
 *             r: 20,
 *         }
 *     }));
 *     zr.addGroup(g);
 */
define(function (require) {

    var zrUtil = require('../core/util');
    var Element = require('../Element');
    var BoundingRect = require('../core/BoundingRect');

    var tmpMat = [];

    /**
     * @alias module:zrender/graphic/Group
     * @constructor
     * @extends module:zrender/mixin/Transformable
     * @extends module:zrender/mixin/Eventful
     */
    var Group = function (opts) {

        opts = opts || {};

        Element.call(this, opts);

        for (var key in opts) {
            this[key] = opts[key];
        }

        this._children = [];

        this.__storage = null;

        this.__dirty = true;
    };

    Group.prototype = {

        constructor: Group,

        /**
         * @type {string}
         */
        type: 'group',

        /**
         * 复制并返回一份新的包含所有儿子节点的数组
         * @return {Array.<module:zrender/Element>}
         */
        children: function () {
            return this._children.slice();
        },

        /**
         * 获取指定 index 的儿子节点
         * @param  {number} idx
         * @return {module:zrender/Element}
         */
        childAt: function (idx) {
            return this._children[idx];
        },

        /**
         * 添加子节点
         * @param {module:zrender/Element} child
         */
        add: function (child) {
            // Validate
            if (!child || child === this || child.parent === this) {
                return;
            }

            if (child.parent) {
                child.parent.removeChild(child);
            }

            this._children.push(child);
            child.parent = this;

            var storage = this.__storage;
            if (storage && storage !== child.__storage) {

                storage.addToMap(child);

                if (child instanceof Group) {
                    child.addChildrenToStorage(storage);
                }
            }

            this.__zr && this.__zr.refresh();

            return this;
        },

        /**
         * 移除子节点
         * @param {module:zrender/Element} child
         */
        remove: function (child) {
            var zr = this.__zr;
            var storage = this.__storage;
            var children = this._children;

            var idx = zrUtil.indexOf(children, child);
            if (idx < 0) {
                return;
            }
            children.splice(idx, 1);

            child.parent = null;

            if (storage) {

                storage.delFromMap(child.id);

                if (child instanceof Group) {
                    child.delChildrenFromStorage(storage);
                }
            }

            zr && zr.refresh();

            return this;
        },

        /**
         * 移除所有子节点
         */
        removeAll: function () {
            var children = this._children;
            var storage = this.__storage;
            var child;
            var i;
            for (i = 0; i < children.length; i++) {
                child = children[i];
                if (storage) {
                    storage.delFromMap(child.id);
                    if (child instanceof Group) {
                        child.delChildrenFromStorage(storage);
                    }
                }
                child.parent = null;
            }
            children.length = 0;

            return this;
        },

        /**
         * 遍历所有子节点
         * @param  {Function} cb
         * @param  {}   context
         */
        eachChild: function (cb, context) {
            var haveContext = !!context;
            for (var i = 0; i < this._children.length; i++) {
                var child = this._children[i];
                if (haveContext) {
                    cb.call(context, child);
                } else {
                    cb(child);
                }
            }
            return this;
        },

        /**
         * 深度优先遍历所有子孙节点
         * @param  {Function} cb
         * @param  {}   context
         */
        traverse: function (cb, context) {
            var haveContext = !!context;
            for (var i = 0; i < this._children.length; i++) {
                var child = this._children[i];
                if (haveContext) {
                    cb.call(context, child);
                } else {
                    cb(child);
                }

                if (child.type === 'group') {
                    child.traverse(cb, context);
                }
            }
            return this;
        },

        addChildrenToStorage: function (storage) {
            for (var i = 0; i < this._children.length; i++) {
                var child = this._children[i];
                storage.addToMap(child);
                if (child instanceof Group) {
                    child.addChildrenToStorage(storage);
                }
            }
        },

        delChildrenFromStorage: function (storage) {
            for (var i = 0; i < this._children.length; i++) {
                var child = this._children[i];
                storage.delFromMap(child.id);
                if (child instanceof Group) {
                    child.delChildrenFromStorage(storage);
                }
            }
        },

        dirty: function () {
            this.__dirty = true;
            this.__zr && this.__zr.refresh();
            return this;
        },

        /**
         * @return {module:zrender/core/BoundingRect}
         */
        getBoundingRect: function () {
            // TODO Caching
            // TODO Transform
            var rect;
            var tmpRect = new BoundingRect(0, 0, 0, 0);
            var children = this._children;
            for (var i = 0; i < children.length; i++) {
                var child = children[i];
                var childRect = child.getBoundingRect();
                var transform = child.getLocalTransform(tmpMat);
                rect = rect || childRect.clone();
                if (transform) {
                    tmpRect.copy(childRect);
                    tmpRect.applyTransform(transform);
                    rect.union(tmpRect);
                }
                else {
                    rect.union(childRect);
                }
            }
            return rect || new BoundingRect(0, 0, 0, 0);
        },

        update: function () {
            this.updateTransform();
            return this;
        }
    };

    zrUtil.inherits(Group, Element);

    return Group;
});<|endoftext|>