<commit_before>'use strict';

const logger = require('../logger');
const { FEATURE_CREATED, FEATURE_UPDATED, FEATURE_ARCHIVED } = require('../event-type');
const NameExistsError = require('../error/name-exists-error');
const NotFoundError = require('../error/notfound-error');
const ValidationError = require('../error/validation-error.js');
const validateRequest = require('../error/validate-request');
const extractUser = require('../extract-user');

const legacyFeatureMapper = require('../data-helper/legacy-feature-mapper');
const version = 1;

const handleErrors = (req, res, error) => {
    switch (error.constructor) {
        case NotFoundError:
            return res
                .status(404)
                .end();
        case NameExistsError:
            return res
                .status(403)
                .json([{ msg: 'A feature with this name already exists. Try re-activating it from the archive.' }])
                .end();
        case ValidationError:
            return res
                .status(400)
                .json(req.validationErrors())
                .end();
        default:
            logger.error('Server failed executing request', error);
            return res
                .status(500)
                .end();
    }
};

module.exports = function (app, config) {
    const { featureToggleStore, eventStore } = config.stores;

    app.get('/features', (req, res) => {
        featureToggleStore.getFeatures()
            .then((features) => features.map(legacyFeatureMapper.addOldFields))
            .then(features => res.json({ version, features }));
    });

    app.get('/features/:featureName', (req, res) => {
        featureToggleStore.getFeature(req.params.featureName)
            .then(legacyFeatureMapper.addOldFields)
            .then(feature => res.json(feature).end())
            .catch(() => res.status(404).json({ error: 'Could not find feature' }));
    });

    app.post('/features-validate', (req, res) => {
        req.checkBody('name', 'Name is required').notEmpty();
        req.checkBody('name', 'Name must match format ^[0-9a-zA-Z\\.\\-]+$').matches(/^[0-9a-zA-Z\\.\\-]+$/i);

        validateRequest(req)
            .then(validateFormat)
            .then(validateUniqueName)
            .then(() => res.status(201).end())
            .catch(error => handleErrors(req, res, error));
    });

    app.post('/features', (req, res) => {
        req.checkBody('name', 'Name is required').notEmpty();
        req.checkBody('name', 'Name must match format ^[0-9a-zA-Z\\.\\-]+$').matches(/^[0-9a-zA-Z\\.\\-]+$/i);
        const userName = extractUser(req);

        validateRequest(req)
            .then(validateFormat)
            .then(validateUniqueName)
            .then((_req) => legacyFeatureMapper.toNewFormat(_req.body))
            .then(validateStrategy)
            .then((featureToggle) => eventStore.store({
                type: FEATURE_CREATED,
                createdBy: userName,
                data: featureToggle,
            }))
            .then(() => res.status(201).end())
            .catch(error => handleErrors(req, res, error));
    });

    app.put('/features/:featureName', (req, res) => {
        const featureName = req.params.featureName;
        const userName = extractUser(req);
        const updatedFeature = legacyFeatureMapper.toNewFormat(req.body);

        updatedFeature.name = featureName;

        featureToggleStore.getFeature(featureName)
            .then(() => validateStrategy(updatedFeature))
            .then(() => eventStore.store({
                type: FEATURE_UPDATED,
                createdBy: userName,
                data: updatedFeature,
            }))
            .then(() => res.status(200).end())
            .catch(error => handleErrors(req, res, error));
    });

    app.post('/features/:featureName/toggle', (req, res) => {
        const featureName = req.params.featureName;
        const userName = extractUser(req);

        featureToggleStore.getFeature(featureName)
            .then((feature) => {
                feature.enabled = !feature.enabled;
                return eventStore.store({
                    type: FEATURE_UPDATED,
                    createdBy: userName,
                    data: feature,
                });
            })
            .then(() => res.status(200).end())
            .catch(error => handleErrors(req, res, error));
    });

    app.delete('/features/:featureName', (req, res) => {
        const featureName = req.params.featureName;
        const userName = extractUser(req);

        featureToggleStore.getFeature(featureName)
            .then(() => eventStore.store({
                type: FEATURE_ARCHIVED,
                createdBy: userName,
                data: {
                    name: featureName,
                },
            }))
            .then(() => res.status(200).end())
            .catch(error => handleErrors(req, res, error));
    });

    function validateUniqueName (req) {
        return new Promise((resolve, reject) => {
            featureToggleStore.getFeature(req.body.name)
                .then(() => reject(new NameExistsError('Feature name already exist')))
                .catch(() => resolve(req));
        });
    }

    function validateFormat (req) {
        if (req.body.strategy && req.body.strategies) {
            return Promise.reject(new ValidationError('Cannot use both "strategy" and "strategies".'));
        }

        return Promise.resolve(req);
    }

    function validateStrategy (featureToggle) {
        if (!featureToggle.strategies || featureToggle.strategies.length === 0) {
            return Promise.reject(new ValidationError('You must define at least one strategy'));
        }

        return Promise.resolve(featureToggle);
    }
};
<commit_msg>validate configures strategy shape<commit_after>'use strict';

const joi = require('joi');
const logger = require('../logger');
const { FEATURE_CREATED, FEATURE_UPDATED, FEATURE_ARCHIVED } = require('../event-type');
const NameExistsError = require('../error/name-exists-error');
const NotFoundError = require('../error/notfound-error');
const ValidationError = require('../error/validation-error.js');
const validateRequest = require('../error/validate-request');
const extractUser = require('../extract-user');

const legacyFeatureMapper = require('../data-helper/legacy-feature-mapper');
const version = 1;

const handleErrors = (req, res, error) => {
    switch (error.constructor) {
        case NotFoundError:
            return res
                .status(404)
                .end();
        case NameExistsError:
            return res
                .status(403)
                .json([{ msg: 'A feature with this name already exists. Try re-activating it from the archive.' }])
                .end();
        case ValidationError:
            return res
                .status(400)
                .json(req.validationErrors())
                .end();
        default:
            logger.error('Server failed executing request', error);
            return res
                .status(500)
                .end();
    }
};

module.exports = function (app, config) {
    const { featureToggleStore, eventStore } = config.stores;

    app.get('/features', (req, res) => {
        featureToggleStore.getFeatures()
            .then((features) => features.map(legacyFeatureMapper.addOldFields))
            .then(features => res.json({ version, features }));
    });

    app.get('/features/:featureName', (req, res) => {
        featureToggleStore.getFeature(req.params.featureName)
            .then(legacyFeatureMapper.addOldFields)
            .then(feature => res.json(feature).end())
            .catch(() => res.status(404).json({ error: 'Could not find feature' }));
    });

    app.post('/features-validate', (req, res) => {
        req.checkBody('name', 'Name is required').notEmpty();
        req.checkBody('name', 'Name must match format ^[0-9a-zA-Z\\.\\-]+$').matches(/^[0-9a-zA-Z\\.\\-]+$/i);

        validateRequest(req)
            .then(validateFormat)
            .then(validateUniqueName)
            .then(() => res.status(201).end())
            .catch(error => handleErrors(req, res, error));
    });

    app.post('/features', (req, res) => {
        req.checkBody('name', 'Name is required').notEmpty();
        req.checkBody('name', 'Name must match format ^[0-9a-zA-Z\\.\\-]+$').matches(/^[0-9a-zA-Z\\.\\-]+$/i);
        const userName = extractUser(req);

        validateRequest(req)
            .then(validateFormat)
            .then(validateUniqueName)
            .then((_req) => legacyFeatureMapper.toNewFormat(_req.body))
            .then(validateStrategy)
            .then((featureToggle) => eventStore.store({
                type: FEATURE_CREATED,
                createdBy: userName,
                data: featureToggle,
            }))
            .then(() => res.status(201).end())
            .catch(error => handleErrors(req, res, error));
    });

    app.put('/features/:featureName', (req, res) => {
        const featureName = req.params.featureName;
        const userName = extractUser(req);
        const updatedFeature = legacyFeatureMapper.toNewFormat(req.body);

        updatedFeature.name = featureName;

        featureToggleStore.getFeature(featureName)
            .then(() => validateStrategy(updatedFeature))
            .then(() => eventStore.store({
                type: FEATURE_UPDATED,
                createdBy: userName,
                data: updatedFeature,
            }))
            .then(() => res.status(200).end())
            .catch(error => handleErrors(req, res, error));
    });

    app.post('/features/:featureName/toggle', (req, res) => {
        const featureName = req.params.featureName;
        const userName = extractUser(req);

        featureToggleStore.getFeature(featureName)
            .then((feature) => {
                feature.enabled = !feature.enabled;
                return eventStore.store({
                    type: FEATURE_UPDATED,
                    createdBy: userName,
                    data: feature,
                });
            })
            .then(() => res.status(200).end())
            .catch(error => handleErrors(req, res, error));
    });

    app.delete('/features/:featureName', (req, res) => {
        const featureName = req.params.featureName;
        const userName = extractUser(req);

        featureToggleStore.getFeature(featureName)
            .then(() => eventStore.store({
                type: FEATURE_ARCHIVED,
                createdBy: userName,
                data: {
                    name: featureName,
                },
            }))
            .then(() => res.status(200).end())
            .catch(error => handleErrors(req, res, error));
    });

    function validateUniqueName (req) {
        return new Promise((resolve, reject) => {
            featureToggleStore.getFeature(req.body.name)
                .then(() => reject(new NameExistsError('Feature name already exist')))
                .catch(() => resolve(req));
        });
    }

    function validateFormat (req) {
        if (req.body.strategy && req.body.strategies) {
            return Promise.reject(new ValidationError('Cannot use both "strategy" and "strategies".'));
        }

        return Promise.resolve(req);
    }

    const strategiesSchema = joi.object().keys({
        name: joi.string()
            .regex(/^[a-zA-Z0-9\\.\\-]{3,100}$/)
            .required(),
        parameters: joi.object(),
    });

    function validateStrategy (featureToggle) {
        return new Promise((resolve, reject) => {
            if (!featureToggle.strategies || featureToggle.strategies.length === 0) {
                return reject(new ValidationError('You must define at least one strategy'));
            }

            featureToggle.strategies = featureToggle.strategies.map((strategyConfig) => {
                const result = joi.validate(strategyConfig, strategiesSchema);
                if (result.error) {
                    throw result.error;
                }
                return result.value;
            });

            return resolve(featureToggle);
        });
    }
};
<|endoftext|>


<commit_before>if (process.argv.indexOf('--help') > 0 || process.argv.length < 8) {
	console.log("Run\n" +
		"node build.js --path [my_app_directory] --name [my_app_main] --out [out_name] [[--closure]]\n" +
		"\n" +
		"Arguments\n" +
		"--path	Path to js entry-point.\n" +
		"--name	Name of entry-point.\n" +
		"--out Optimized file output name.\n" +
		"[[--closure]] Optional argument to optimize with closure instead of uglify.\n"
		);
	process.exit();
}

// Parse command line arguments
var i = process.argv.indexOf('--path');
if (i > 0 && process.argv[i + 1] && process.argv[i + 1][0] !== '-') {
	appPath = process.argv[i + 1];
	console.log('Path to entry-point: ' + appPath);
} else {
	console.log('Not valid input: ' + process.argv[i + 1]);
	process.exit();
}

i = process.argv.indexOf('--name');
if (i > 0 && process.argv[i + 1] && process.argv[i + 1][0] !== '-') {
	appName = process.argv[i + 1];
	console.log('Name of entry-point: ' + appName);
} else {
	console.log('Not valid input: ' + process.argv[i + 1]);
	process.exit();
}

i = process.argv.indexOf('--out');
if (i > 0 && process.argv[i + 1] && process.argv[i + 1][0] !== '-') {
	appOut = process.argv[i + 1];
	console.log('Optimized file output name: ' + appOut);
} else {
	console.log('Not valid input: ' + process.argv[i + 1]);
	process.exit();
}

var doClosureStep = false;
i = process.argv.indexOf('--closure');
if (i > 0) {
	optimizer = 'none';
	doClosureStep = true;
	console.log('Using closure');
} else {
	optimizer = 'uglify';
	console.log('Using uglify');
}

var requirejs = require('requirejs');
var workingDir = process.cwd();

var config = {
	baseUrl : appPath,
	paths : {
		goo : workingDir+'/../src/goo',
		almond : workingDir+'/../build/almond'
	},
	name : 'almond',
	include : [appName],
	insertRequire : [appName],
	out : doClosureStep ? 'extracted.js' : appOut,
	useStrict : true,
	uglify : {
		toplevel : false,
		ascii_only : false,
		beautify: true,
//		max_line_length: 120,
//		no_mangle: true
	},
	optimize : optimizer,
	wrap : true,
};

// console.log(config);

requirejs.optimize(config, function(buildResponse) {
	// buildResponse is just a text output of the modules
	// included. Load the built file for the contents.
	// Use config.out to get the optimized file contents.
//	var contents = fs.readFileSync(config.out, 'utf8');

	console.log(buildResponse);

	if (doClosureStep) {
		var command = 'java -jar compiler.jar --compilation_level=SIMPLE_OPTIMIZATIONS --language_in ECMASCRIPT5_STRICT --jscomp_off=internetExplorerChecks --js extracted.js --js_output_file '
			+ appOut;
		var exec = require('child_process').exec;
		exec(command, function callback(error, stdout, stderr) {
			console.log('stdout: ' + stdout);
			console.log('stderr: ' + stderr);
			if (error !== null) {
				console.log('closure error: ' + error);
			}
		});
	}
}, function(error) {
	console.log('optimize error: ' + error);
});
<commit_msg>Added more settings for the optimizer<commit_after>if (process.argv.indexOf('--help') > 0 || process.argv.length < 8) {
	console.log("Run\n" +
		"node build.js --path [my_app_directory] --name [my_app_main] --out [out_name] [[--closure]]\n" +
		"\n" +
		"Arguments\n" +
		"--path	Path to js entry-point.\n" +
		"--name	Name of entry-point.\n" +
		"--out Optimized file output name.\n" +
		"[[--closure]] Optional argument to optimize with closure instead of uglify.\n",
		"[[--simple]] Optional argument to not mangle the code, needed for angularjs atm.\n"
		);
	process.exit();
}

// Parse command line arguments
var i = process.argv.indexOf('--path');
if (i > 0 && process.argv[i + 1] && process.argv[i + 1][0] !== '-') {
	appPath = process.argv[i + 1];
	console.log('Path to entry-point: ' + appPath);
} else {
	console.log('Not valid input: ' + process.argv[i + 1]);
	process.exit();
}

i = process.argv.indexOf('--name');
if (i > 0 && process.argv[i + 1] && process.argv[i + 1][0] !== '-') {
	appName = process.argv[i + 1];
	console.log('Name of entry-point: ' + appName);
} else {
	console.log('Not valid input: ' + process.argv[i + 1]);
	process.exit();
}

i = process.argv.indexOf('--out');
if (i > 0 && process.argv[i + 1] && process.argv[i + 1][0] !== '-') {
	appOut = process.argv[i + 1];
	console.log('Optimized file output name: ' + appOut);
} else {
	console.log('Not valid input: ' + process.argv[i + 1]);
	process.exit();
}

var doClosureStep = false;
i = process.argv.indexOf('--closure');
if (i > 0) {
	optimizer = 'none';
	doClosureStep = true;
	console.log('Using closure');
} else {
	optimizer = 'uglify';
	console.log('Using uglify');
}

var doSimple = false;
i = process.argv.indexOf('--simple');
if (i > 0) {
	doSimple = true;
	console.log('Not mangling code');
}

var requirejs = require('requirejs');
var workingDir = process.cwd();

var config = {
	baseUrl : appPath,
	paths : {
		goo : workingDir+'/../src/goo',
		almond : workingDir+'/../build/almond'
	},
	name : 'almond',
	include : [appName],
	insertRequire : [appName],
	out : doClosureStep ? 'extracted.js' : appOut,
	useStrict : true,
	uglify : doSimple ? {
		no_mangle: true,
		no_copyright: true
	} : {},
	optimize : optimizer,
	wrap : true,
};

// console.log(config);

requirejs.optimize(config, function(buildResponse) {
	// buildResponse is just a text output of the modules
	// included. Load the built file for the contents.
	// Use config.out to get the optimized file contents.
//	var contents = fs.readFileSync(config.out, 'utf8');

	console.log(buildResponse);

	if (doClosureStep) {
		var command = 'java -jar compiler.jar --compilation_level=SIMPLE_OPTIMIZATIONS --language_in ECMASCRIPT5_STRICT --jscomp_off=internetExplorerChecks --js extracted.js --js_output_file '
			+ appOut;
		var exec = require('child_process').exec;
		exec(command, function callback(error, stdout, stderr) {
			console.log('stdout: ' + stdout);
			console.log('stderr: ' + stderr);
			if (error !== null) {
				console.log('closure error: ' + error);
			}
		});
	}
}, function(error) {
	console.log('optimize error: ' + error);
});
<|endoftext|>


<commit_before>/* @flow */

const Promise = require('bluebird')
const async = require('async')
const crypto = require('crypto')
const fs = require('fs')
const measureTime = require('../perftools')

/*::
import type { Callback } from '../utils/func'
*/

module.exports = {
  init
}

// Get checksum for given file
const computeChecksum = (filePath /*: string */, callback /*: Callback */) => {
  const stopMeasure = measureTime('LocalWatcher#checksumer')
  const stream = fs.createReadStream(filePath)
  const checksum = crypto.createHash('md5')
  checksum.setEncoding('base64')
  stream.on('end', function () {
    stopMeasure()
    checksum.end()
    callback(null, checksum.read())
  })
  stream.on('error', function (err) {
    stopMeasure()
    checksum.end()
    callback(err)
  })
  stream.pipe(checksum)
}

const retryComputeChecksum = (filePath /*: string */, callback /*: Callback */) => {
  async.retry({
    times: 5,
    // retry after 1, 2, 4, 8, 16 seconds
    interval: (count) => 500 * Math.pow(2, count),
    errorFilter: err => err.code === 'EBUSY'
  }, (cb) => { computeChecksum(filePath, cb) }, callback)
}

/*::
export type Checksumer = {
  push: (filePath: string) => Promise<string>,
  kill: () => void
}
*/

function init () /*: Checksumer */ {
  // Use a queue for checksums to avoid computing many checksums at the
  // same time. It's better for performance (hard disk are faster with
  // linear readings).
  const queue = Promise.promisifyAll(async.queue(retryComputeChecksum))

  return {
    push (filePath /*: string */) /*: Promise<string> */ {
      return queue.pushAsync(filePath)
    },

    kill: queue.kill
  }
}
<commit_msg>core/local/checksumer: Expose computeChecksum<commit_after>/* @flow */

const Promise = require('bluebird')
const async = require('async')
const crypto = require('crypto')
const fs = require('fs')
const measureTime = require('../perftools')

/*::
import type { Callback } from '../utils/func'
*/

module.exports = {
  computeChecksum,
  init
}

// Get checksum for given file
function computeChecksum (filePath /*: string */, callback /*: Callback */) {
  const stopMeasure = measureTime('LocalWatcher#checksumer')
  const stream = fs.createReadStream(filePath)
  const checksum = crypto.createHash('md5')
  checksum.setEncoding('base64')
  stream.on('end', function () {
    stopMeasure()
    checksum.end()
    callback(null, checksum.read())
  })
  stream.on('error', function (err) {
    stopMeasure()
    checksum.end()
    callback(err)
  })
  stream.pipe(checksum)
}

const retryComputeChecksum = (filePath /*: string */, callback /*: Callback */) => {
  async.retry({
    times: 5,
    // retry after 1, 2, 4, 8, 16 seconds
    interval: (count) => 500 * Math.pow(2, count),
    errorFilter: err => err.code === 'EBUSY'
  }, (cb) => { computeChecksum(filePath, cb) }, callback)
}

/*::
export type Checksumer = {
  push: (filePath: string) => Promise<string>,
  kill: () => void
}
*/

function init () /*: Checksumer */ {
  // Use a queue for checksums to avoid computing many checksums at the
  // same time. It's better for performance (hard disk are faster with
  // linear readings).
  const queue = Promise.promisifyAll(async.queue(retryComputeChecksum))

  return {
    push (filePath /*: string */) /*: Promise<string> */ {
      return queue.pushAsync(filePath)
    },

    kill: queue.kill
  }
}
<|endoftext|>


<commit_before>var keystone = require('keystone');

exports = module.exports = function(req, res) {

	var view = new keystone.View(req, res),
		locals = res.locals;

	locals.section = 'scoreboard';
	locals.current.sortOrder = req.query.sort || 'name.first';

	// LOAD the Players

	view.on('init', function(next) {
		keystone.list('User').model.find()
			.where('state', 'active')
			.sort(locals.current.sortOrder)
			.exec(function(err, players) {
				locals.players = players;
				next();
			});
	});

	view.render('index');

};
<commit_msg>Handle game creation<commit_after>var keystone = require('keystone'),
	User = keystone.list('User'),
	Game = keystone.list('Game');

exports = module.exports = function(req, res) {

	var view = new keystone.View(req, res),
		locals = res.locals;

	locals.section = 'scoreboard';
	locals.current.sortOrder = req.query.sort || 'rank';

	// CREATE a Game

	view.on('post', { action: 'game.create' }, function(next) {

		var newGame = new Game.model();

		var updater = newGame.getUpdateHandler(req);

		updater.process(req.body, {
			fields: 'player1, player2, player1Score, player2Score',
			required: 'player1, player2, player1Score, player2Score',
			errorMessage: 'There was an error creating the game:',
			flashErrors: true,
			logErrors: true
		}, function(err) {

			if (err) {
				locals.validationErrors = err.errors;
				return next();
			} else {
				req.flash('success', 'New game ' + newGame.name + ' saved successfully.');

				// redirect so we load the new game
				res.redirect('/');
			}

		});

	});

	// LOAD the Players after post so we get the latest data

	view.on('render', function(next) {
		User.model.find()
			.where('state', 'active')
			.sort(locals.current.sortOrder)
			.exec(function(err, players) {
				locals.players = players;
				next();
			});
	});

	view.render('index');

};
<|endoftext|>


<commit_before><commit_msg>Add map for section distribuição<commit_after><|endoftext|>


<commit_before>var gcm = require('node-gcm');

exports.sendNotification = function(db, title, messageNotif) {
    db.connect(process.env.DATABASE_URL ,function(err, client, done) {
        client.query("SELECT notification_id from notification_client", function(err, results){
            if(err) {
                console.log('Error while getting notifications clients : ' + err);
                return;
            }

            if(results.rows.length > 0) {
                // create a message with default values
                var message = new gcm.Message();

                // or with object values
                var message = new gcm.Message({
                    collapseKey: 'demo',
                    delayWhileIdle: true,
                    timeToLive: 3,
                    data: {
                        title: title,
                        message: messageNotif
                    }
                });

                var sender = new gcm.Sender(process.env.ANDROID_SERVER_KEY);
                var notificationIds = [];
                for(var notif in results.rows) {
                    notificationIds.push(results.rows[notif].notification_id);
                }

                /**
                 * Params: message-literal, registrationIds-array, No. of retries, callback-function
                 **/
                sender.send(message, notificationIds, notificationIds.length, function (err, result) {
                    if(process.env.NODE_ENV == 'DEV') {
                        console.log('sending notification with result : ' + JSON.stringify(result));
                    }
                });
            } else {
                console.log('No notification clients found');
            }
            done();
        })
    })
}
<commit_msg>Add logs<commit_after>var gcm = require('node-gcm');

exports.sendNotification = function(db, title, messageNotif) {
    if(process.env.NODE_ENV == 'DEV') {
        console.log('Ready to send notification with params :[' +db+ ', ' +title+', '+ messageNotif + ']');
    }
    db.connect(process.env.DATABASE_URL ,function(err, client, done) {
        if(err) {
            console.log('Error while contacting database ' + err);
        }
        client.query("SELECT notification_id from notification_client", function(error, results){
            if(err) {
                console.log('Error while getting notifications clients : ' + error);
                return;
            }

            if(results.rows.length > 0) {
                // create a message with default values
                var message = new gcm.Message();

                // or with object values
                var message = new gcm.Message({
                    collapseKey: 'demo',
                    delayWhileIdle: true,
                    timeToLive: 3,
                    data: {
                        title: title,
                        message: messageNotif
                    }
                });

                var sender = new gcm.Sender(process.env.ANDROID_SERVER_KEY);
                var notificationIds = [];
                for(var notif in results.rows) {
                    notificationIds.push(results.rows[notif].notification_id);
                }

                /**
                 * Params: message-literal, registrationIds-array, No. of retries, callback-function
                 **/
                sender.send(message, notificationIds, notificationIds.length, function (err, result) {
                    if(process.env.NODE_ENV == 'DEV') {
                        console.log('sending notification with result : ' + JSON.stringify(result));
                    }
                });
            } else {
                console.log('No notification clients found');
            }
            done();
        })
    })
}
<|endoftext|>


<commit_before>const through = require('through')
const Docker = require('../docker')
const { owner, repo } = require('../apiDelegate')

exports.get = async ctx => {
  const { branch, commit_id: commitId } = ctx.query
  await ctx.render('preview', {
    owner, repo, branch, commitId
  })
}

exports.post = async ctx => {
  const { branch, commit_id: commitId } = ctx.request.body

  const docker = new Docker({
    owner, repo, branch, commitId
  })
  const status = await docker.getContainerStatus()
  const getURL = port => ctx.env !== 'production'
    ? `http://${owner}.${repo}.${branch}.${commitId}.127.0.0.1.xip.io`
    : `http://localhost:${port}`
  if(!status) { // doen't exist container
    const t = through()
    ctx.body = await t

    docker.on('progress', progress => {
      t.write(progress)
    })

    docker.run()
      .then(docker.getPort)
      .then(getURL)
      .then(url => {
        t.write('\nFinished. Redirect...\n')
        t.write(url)
        t.end()
      }).catch(err => {
        if(err) {
          if(typeof err === 'string') {
            t.write(err)
          } else {
            t.write(err.message)
          }
        }
        t.end()
      })
  } else { //exist container
    if(status === 'exited')
      await docker.container.start()
    const url = await Promise.resolve(docker.getPort).then(getURL)
    ctx.body = { url }
  }
}
<commit_msg>Fix require<commit_after>const through = require('through')
const Docker = require('../docker')
const ApiDelegate = require('../apiDelegate')

const { owner, repo } = new ApiDelegate()

exports.get = async ctx => {
  const { branch, commit_id: commitId } = ctx.query
  await ctx.render('preview', {
    owner, repo, branch, commitId
  })
}

exports.post = async ctx => {
  const { branch, commit_id: commitId } = ctx.request.body

  const docker = new Docker({
    owner, repo, branch, commitId
  })
  const status = await docker.getContainerStatus()
  const getURL = port => ctx.env !== 'production'
    ? `http://${owner}.${repo}.${branch}.${commitId}.127.0.0.1.xip.io`
    : `http://localhost:${port}`
  if(!status) { // doen't exist container
    const t = through()
    ctx.body = await t

    docker.on('progress', progress => {
      t.write(progress)
    })

    docker.run()
      .then(docker.getPort)
      .then(getURL)
      .then(url => {
        t.write('\nFinished. Redirect...\n')
        t.write(url)
        t.end()
      }).catch(err => {
        if(err) {
          if(typeof err === 'string') {
            t.write(err)
          } else {
            t.write(err.message)
          }
        }
        t.end()
      })
  } else { //exist container
    if(status === 'exited')
      await docker.container.start()
    const url = await Promise.resolve(docker.getPort).then(getURL)
    ctx.body = { url }
  }
}
<|endoftext|>


<commit_before>const Promise = require("bluebird")
const _ = require('lodash')
const fs = Promise.promisifyAll(require('fs'))
const mustache = require('mustache')

module.exports = function(grunt) {

    grunt.registerMultiTask('mustache_compile', function(){

        // Get Grunt Options
        let task_options = this.options()
        let output_array = this.files

        // Generator Coroutine function
        let variables_coroutine = Promise.coroutine(function*(){

            // Merge all variables
            let dynamic_variables = yield task_options.dynamic_variables()
            let variables = _.merge(task_options.variables, dynamic_variables)

            // Define result array
            let result_destinations = []

            for (mapping of output_array){
                for (source of mapping.src){

                    // Start rendering the file to a stream
                    let template_raw = yield fs.readFileAsync(source, {encoding:'utf-8'})
                    let text = mustache.render(template_raw, variables)

                    let destination_array = _.isString(mapping.dest) ?
                        [mapping.dest] : mapping.dest;

                    for (destination of destination_array){
                        // Output the stream
                        grunt.file.write(destination, text)

                        // Logs
                        grunt.log.ok(destination)
                        result_destinations.push(destination)
                    }

                }
            }

            // Result
            return result_destinations
        })

        /*
            Main Execution Chain
        */
        let done = this.async()
        Promise
            // Execute the Generator as a Coroutine
            .try(variables_coroutine)
            // finalize
            .then(done)
            // Catch any error
            .catch( error => {
                grunt.log.error(error)
                done(error)
            })
    })

}
<commit_msg>More Async/Await<commit_after>const Promise = require("bluebird")
const _ = require('lodash')
const fs = Promise.promisifyAll(require('fs'))
const mustache = require('mustache')

module.exports = function(grunt) {

    grunt.registerMultiTask('mustache_compile', function(){

        // Get Grunt Options
        let task_options = this.options()
        let output_array = this.files

        // Generator Coroutine function
        let variables_coroutine = async function(){

            // Merge all variables
            let dynamic_variables = await task_options.dynamic_variables()
            let variables = _.merge(task_options.variables, dynamic_variables)

            // Define result array
            let result_destinations = []

            for (mapping of output_array){
                for (source of mapping.src){

                    // Start rendering the file to a stream
                    let template_raw = await fs.readFileAsync(source, {encoding:'utf-8'})
                    let text = mustache.render(template_raw, variables)

                    let destination_array = _.isString(mapping.dest) ?
                        [mapping.dest] : mapping.dest;

                    for (destination of destination_array){
                        // Output the stream
                        grunt.file.write(destination, text)

                        // Logs
                        grunt.log.ok(destination)
                        result_destinations.push(destination)
                    }

                }
            }

            // Result
            return result_destinations
        }

        /*
            Main Execution Chain
        */
        let done = this.async()
        Promise
            // Execute the Generator as a Coroutine
            .try(variables_coroutine)
            // finalize
            .then(done)
            // Catch any error
            .catch( error => {
                grunt.log.error(error)
                done(error)
            })
    })

}
<|endoftext|>


<commit_before>var shell = require('shelljs')

shell.exec('node-sass -r src/themes -o dist/themes')
shell.cp('-r', 'src/themes/assets', 'dist/themes/assets')
shell.exec('rollup -c build/rollup.config.js')
<commit_msg>Remove dist directory before building<commit_after>var shell = require('shelljs')

shell.rm('-r', 'dist')

shell.exec('node-sass -r src/themes -o dist/themes')
shell.cp('-r', 'src/themes/assets', 'dist/themes/assets')
shell.exec('rollup -c build/rollup.config.js')
<|endoftext|>


<commit_before>// Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.ui.form");

frappe.ui.form.Review = class Review {
	constructor({parent, frm}) {
		this.parent = parent;
		this.frm = frm;
		this.fetch_energy_points()
			.then(() => {
				this.make_review_container();
				this.add_review_button();
				this.update_reviewers();
			});
	}
	fetch_energy_points() {
		return frappe.xcall('frappe.social.doctype.energy_point_log.energy_point_log.get_energy_points', {
			user: frappe.session.user
		}).then(data => {
			this.points = data;
		});
	}
	make_review_container() {
		this.$wrapper = this.parent.append(`

${__('Reviews')}

		`);
		this.review_list_wrapper = this.$wrapper.find('.review-list');
	}
	add_review_button() {

		this.review_list_wrapper.append(`

		`);

		const review_button = this.review_list_wrapper.find('.btn-add-review');

		if (!this.points.review_points) {
			review_button.click(false);
			review_button.popover({
				trigger: 'hover',
				content: () => {
					return `

						${__('You do not have enough review points')}

`;
				},
				html: true
			});
		} else {
			review_button.click(() => this.show_review_dialog());
		}
	}
	get_involved_users() {
		const user_fields = this.frm.meta.fields
			.filter(d => d.fieldtype === 'Link' && d.options === 'User')
			.map(d => d.fieldname);

		user_fields.push('owner');
		let involved_users = user_fields.map(field => this.frm.doc[field]);

		const docinfo = this.frm.get_docinfo();

		involved_users = involved_users.concat(
			docinfo.communications.map(d => d.sender && d.delivery_status==='sent'),
			docinfo.comments.map(d => d.owner),
			docinfo.versions.map(d => d.owner),
			docinfo.assignments.map(d => d.owner)
		);

		return involved_users
			.uniqBy(u => u)
			.filter(user => user !== frappe.session.user)
			.filter(Boolean);
	}
	show_review_dialog() {
		const user_options = this.get_involved_users();
		const doc_owner = this.frm.doc.owner;
		const review_dialog = new frappe.ui.Dialog({
			'title': __('Add Review'),
			'fields': [{
				fieldname: 'to_user',
				fieldtype: 'Autocomplete',
				label: __('To User'),
				options: user_options,
				default: user_options.includes(doc_owner) ? doc_owner : user_options[0],
				description: __('Only users involved in the document are listed')
			}, {
				fieldname: 'review_type',
				fieldtype: 'Select',
				label: __('Action'),
				options: [{
					'label': __('Appreciate'),
					'value': 'Appreciation'
				}, {
					'label': __('Criticize'),
					'value': 'Criticism'
				}],
				default: 'Appreciation'
			}, {
				fieldname: 'points',
				fieldtype: 'Int',
				label: __('Points'),
				reqd: 1,
				description: __(`Currently you have ${this.points.review_points} review points`)
			}, {
				fieldtype: 'Small Text',
				fieldname: 'reason',
				reqd: 1,
				label: __('Reason')
			}],
			primary_action: (values) => {
				if (values.points > this.points.review_points) {
					return frappe.msgprint(__('You do not have enough points'));
				}
				frappe.xcall('frappe.social.doctype.energy_point_log.energy_point_log.review', {
					doc: {
						doctype: this.frm.doc.doctype,
						name: this.frm.doc.name,
					},
					to_user: values.to_user,
					points: values.points,
					review_type: values.review_type,
					reason: values.reason
				}).then(review => {
					review_dialog.hide();
					review_dialog.clear();
					this.frm.get_docinfo().energy_point_logs.unshift(review);
					this.update_reviewers();
				});
			},
			primary_action_label: __('Submit')
		});
		review_dialog.show();
	}
	update_reviewers() {
		const review_logs = this.frm.get_docinfo().energy_point_logs
			.filter(log => log.type !== 'Auto');

		this.review_list_wrapper.find('.review-pill').remove();
		review_logs.forEach(log => {
			let review_pill = $(`

					${frappe.avatar(log.owner)}
					${frappe.energy_points.get_points(log.points)}

			`);
			this.review_list_wrapper.prepend(review_pill);
			this.setup_detail_popover(review_pill, log);
		});
	}
	setup_detail_popover(el, data) {
		let subject = '';
		let fullname = frappe.user.full_name(data.user);
		let timestamp = `<span class="text-muted">${frappe.datetime.comment_when(data.creation)}</span>`;
		let message_parts = [Math.abs(data.points), fullname, timestamp];
		if (data.type === 'Appreciation') {
			if (data.points == 1) {
				subject = __('{0} appreciation point for {1} {2}', message_parts);
			} else {
				subject = __('{0} appreciation points for {1} {2}', message_parts);
			}
		} else {
			if (data.points == -1) {
				subject = __('{0} criticism point for {1} {2}', message_parts);
			} else {
				subject = __('{0} criticism points for {1} {2}', message_parts);
			}
		}
		el.popover({
			animation: true,
			trigger: 'hover',
			delay: 500,
			placement: 'top',
			template:`

			`,
			content: () => {
				return `

							${subject}

${data.reason}

				`;
			},
			html: true,
			container: 'body'
		});
		return el;
	}
};
<commit_msg>fix: Remove Administrator from involved users<commit_after>// Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and Contributors
// MIT License. See license.txt

frappe.provide("frappe.ui.form");

frappe.ui.form.Review = class Review {
	constructor({parent, frm}) {
		this.parent = parent;
		this.frm = frm;
		this.fetch_energy_points()
			.then(() => {
				this.make_review_container();
				this.add_review_button();
				this.update_reviewers();
			});
	}
	fetch_energy_points() {
		return frappe.xcall('frappe.social.doctype.energy_point_log.energy_point_log.get_energy_points', {
			user: frappe.session.user
		}).then(data => {
			this.points = data;
		});
	}
	make_review_container() {
		this.$wrapper = this.parent.append(`

${__('Reviews')}

		`);
		this.review_list_wrapper = this.$wrapper.find('.review-list');
	}
	add_review_button() {

		this.review_list_wrapper.append(`

		`);

		const review_button = this.review_list_wrapper.find('.btn-add-review');

		if (!this.points.review_points) {
			review_button.click(false);
			review_button.popover({
				trigger: 'hover',
				content: () => {
					return `

						${__('You do not have enough review points')}

`;
				},
				html: true
			});
		} else {
			review_button.click(() => this.show_review_dialog());
		}
	}
	get_involved_users() {
		const user_fields = this.frm.meta.fields
			.filter(d => d.fieldtype === 'Link' && d.options === 'User')
			.map(d => d.fieldname);

		user_fields.push('owner');
		let involved_users = user_fields.map(field => this.frm.doc[field]);

		const docinfo = this.frm.get_docinfo();

		involved_users = involved_users.concat(
			docinfo.communications.map(d => d.sender && d.delivery_status==='sent'),
			docinfo.comments.map(d => d.owner),
			docinfo.versions.map(d => d.owner),
			docinfo.assignments.map(d => d.owner)
		);

		return involved_users
			.uniqBy(u => u)
			.filter(user => !['Administrator', frappe.session.user].includes(user))
			.filter(Boolean);
	}
	show_review_dialog() {
		const user_options = this.get_involved_users();
		const doc_owner = this.frm.doc.owner;
		const review_dialog = new frappe.ui.Dialog({
			'title': __('Add Review'),
			'fields': [{
				fieldname: 'to_user',
				fieldtype: 'Autocomplete',
				label: __('To User'),
				options: user_options,
				default: user_options.includes(doc_owner) ? doc_owner : user_options[0],
				description: __('Only users involved in the document are listed')
			}, {
				fieldname: 'review_type',
				fieldtype: 'Select',
				label: __('Action'),
				options: [{
					'label': __('Appreciate'),
					'value': 'Appreciation'
				}, {
					'label': __('Criticize'),
					'value': 'Criticism'
				}],
				default: 'Appreciation'
			}, {
				fieldname: 'points',
				fieldtype: 'Int',
				label: __('Points'),
				reqd: 1,
				description: __(`Currently you have ${this.points.review_points} review points`)
			}, {
				fieldtype: 'Small Text',
				fieldname: 'reason',
				reqd: 1,
				label: __('Reason')
			}],
			primary_action: (values) => {
				if (values.points > this.points.review_points) {
					return frappe.msgprint(__('You do not have enough points'));
				}
				frappe.xcall('frappe.social.doctype.energy_point_log.energy_point_log.review', {
					doc: {
						doctype: this.frm.doc.doctype,
						name: this.frm.doc.name,
					},
					to_user: values.to_user,
					points: values.points,
					review_type: values.review_type,
					reason: values.reason
				}).then(review => {
					review_dialog.hide();
					review_dialog.clear();
					this.frm.get_docinfo().energy_point_logs.unshift(review);
					this.update_reviewers();
				});
			},
			primary_action_label: __('Submit')
		});
		review_dialog.show();
	}
	update_reviewers() {
		const review_logs = this.frm.get_docinfo().energy_point_logs
			.filter(log => log.type !== 'Auto');

		this.review_list_wrapper.find('.review-pill').remove();
		review_logs.forEach(log => {
			let review_pill = $(`

					${frappe.avatar(log.owner)}
					${frappe.energy_points.get_points(log.points)}

			`);
			this.review_list_wrapper.prepend(review_pill);
			this.setup_detail_popover(review_pill, log);
		});
	}
	setup_detail_popover(el, data) {
		let subject = '';
		let fullname = frappe.user.full_name(data.user);
		let timestamp = `<span class="text-muted">${frappe.datetime.comment_when(data.creation)}</span>`;
		let message_parts = [Math.abs(data.points), fullname, timestamp];
		if (data.type === 'Appreciation') {
			if (data.points == 1) {
				subject = __('{0} appreciation point for {1} {2}', message_parts);
			} else {
				subject = __('{0} appreciation points for {1} {2}', message_parts);
			}
		} else {
			if (data.points == -1) {
				subject = __('{0} criticism point for {1} {2}', message_parts);
			} else {
				subject = __('{0} criticism points for {1} {2}', message_parts);
			}
		}
		el.popover({
			animation: true,
			trigger: 'hover',
			delay: 500,
			placement: 'top',
			template:`

			`,
			content: () => {
				return `

							${subject}

${data.reason}

				`;
			},
			html: true,
			container: 'body'
		});
		return el;
	}
};
<|endoftext|>


<commit_before>define(function() {

  'use strict';

  var _BYTESOURCE = Symbol('byteSource');

  var itemObjectModel = {
    createItem: function(title) {
      var itemElement = document.createElement('SECTION');
      itemElement.classList.add('item');

      itemElement.appendChild(itemElement.titleElement = document.createElement('HEADER'));

      itemElement.titleTextElement = itemElement.titleElement;

      Object.defineProperties(itemElement, this.itemProperties);

      if (title) itemElement.itemTitle = title;

      itemElement.addEventListener('click', clickItem);

      return itemElement;
    },
    itemProperties: {
      itemTitle: {
        get: function() {
          return this.titleTextElement.innerText;
        },
        set: function(text) {
          this.titleTextElement.innerText = text;
        },
        enumerable: true,
      },
      byteSource: {
        get: function() {
          return this[_BYTESOURCE];
        },
        set: function(byteSource) {
          this[_BYTESOURCE] = byteSource;
          if (!byteSource) {
            this.titleElement.innerText = this.titleTextElement.innerText;
            this.titleTextElement = this.titleElement;
          }
          else {
            var link = document.createElement('A');
            link.href = '#';
            link.classList.add('item-download');
            link.download = this.itemTitle.replace(/[\\\/:"<>\*\?\|]/g, '_');
            link.innerText = this.titleTextElement.innerText;
            this.titleElement.innerHTML = '';
            this.titleElement.appendChild(this.titleTextElement = link);
          }
        },
      },
      startAddingItems: {
        value: function() {
          if (!this.classList.contains('has-subitems')) {
            this.classList.add('has-subitems');
            this.appendChild(this.subitemsElement = document.createElement('SECTION'));
            this.subitemsElement.classList.add('subitems');
          }
        },
      },
      addItem: {
        value: function(item) {
          this.startAddingItems();
          this.classList.add('itemizing');
          this.subitemsElement.appendChild(item);
        },
      },
      confirmAllItemsAdded: {
        value: function() {
          this.classList.remove('itemizing');
          this.classList.add('itemized');
        },
      },
    },
  };

  function clickItem(e) {
    e.stopPropagation();
    if (e.target.classList.contains('item-download')) {
      if (!e.target.classList.contains('prepared')) {
        e.preventDefault();
        if (!e.target.classList.contains('preparing')) {
          e.target.classList.add('preparing');
          this.byteSource.getURL().then(function(url) {
            e.target.classList.remove('preparing');
            e.target.classList.add('prepared');
            e.target.href = url;
            e.target.click();
          });
        }
      }
      return;
    }
    if (this.classList.contains('has-subitems')) {
      if (this.classList.toggle('open')) {
        this.dispatchEvent(new Event(itemObjectModel.EVT_POPULATE));
      }
    }
  }

  Object.defineProperties(itemObjectModel, {
    EVT_POPULATE: {value:'item-populate'},
  });

  return itemObjectModel;

});
<commit_msg>Setting text property adds element<commit_after>define(function() {

  'use strict';

  var _BYTESOURCE = Symbol('byteSource');

  var itemObjectModel = {
    createItem: function(title) {
      var itemElement = document.createElement('SECTION');
      itemElement.classList.add('item');

      itemElement.appendChild(itemElement.titleElement = document.createElement('HEADER'));

      itemElement.titleTextElement = itemElement.titleElement;

      Object.defineProperties(itemElement, this.itemProperties);

      if (title) itemElement.itemTitle = title;

      itemElement.addEventListener('click', clickItem);

      return itemElement;
    },
    itemProperties: {
      itemTitle: {
        get: function() {
          return this.titleTextElement.innerText;
        },
        set: function(text) {
          this.titleTextElement.innerText = text;
        },
        enumerable: true,
      },
      byteSource: {
        get: function() {
          return this[_BYTESOURCE];
        },
        set: function(byteSource) {
          this[_BYTESOURCE] = byteSource;
          if (!byteSource) {
            this.titleElement.innerText = this.titleTextElement.innerText;
            this.titleTextElement = this.titleElement;
          }
          else {
            var link = document.createElement('A');
            link.href = '#';
            link.classList.add('item-download');
            link.download = this.itemTitle.replace(/[\\\/:"<>\*\?\|]/g, '_');
            link.innerText = this.titleTextElement.innerText;
            this.titleElement.innerHTML = '';
            this.titleElement.appendChild(this.titleTextElement = link);
          }
        },
      },
      startAddingItems: {
        value: function() {
          if (!this.classList.contains('has-subitems')) {
            this.classList.add('has-subitems');
            this.appendChild(this.subitemsElement = document.createElement('SECTION'));
            this.subitemsElement.classList.add('subitems');
          }
        },
      },
      addItem: {
        value: function(item) {
          this.startAddingItems();
          this.classList.add('itemizing');
          this.subitemsElement.appendChild(item);
        },
      },
      confirmAllItemsAdded: {
        value: function() {
          this.classList.remove('itemizing');
          this.classList.add('itemized');
        },
      },
      text: {
        set: function(text) {
          var textContainer = document.createElement('PRE');
          textContainer.appendChild(document.createTextNode(text));
          this.addItem(textContainer);
        },
      },
    },
  };

  function clickItem(e) {
    e.stopPropagation();
    if (e.target.classList.contains('item-download')) {
      if (!e.target.classList.contains('prepared')) {
        e.preventDefault();
        if (!e.target.classList.contains('preparing')) {
          e.target.classList.add('preparing');
          this.byteSource.getURL().then(function(url) {
            e.target.classList.remove('preparing');
            e.target.classList.add('prepared');
            e.target.href = url;
            e.target.click();
          });
        }
      }
      return;
    }
    if (this.classList.contains('has-subitems')) {
      if (this.classList.toggle('open')) {
        this.dispatchEvent(new Event(itemObjectModel.EVT_POPULATE));
      }
    }
  }

  Object.defineProperties(itemObjectModel, {
    EVT_POPULATE: {value:'item-populate'},
  });

  return itemObjectModel;

});
<|endoftext|>


<commit_before>/*
 * HomePage
 *
 * This is the first thing users see of our App, at the '/' route
 */

import React from 'react'
import { connect } from 'react-redux'
import { compose, withContext, getContext, withHandlers } from 'recompose'
import { bindActionCreators } from 'redux'
import { createStructuredSelector } from 'reselect'

import { makeSelectLoading } from 'containers/App/selectors'
import { selectUsername } from './selectors'
import * as actions from './actions'
import ImmutableForm from './immutableForm'

const HomePage = ({ username, onChangeUsernameCreator }) => (

    <input value={username} onChange={onChangeUsernameCreator} />
    <ImmutableForm />

)

HomePage.propTypes = {
  username: React.PropTypes.stringss,
  onChangeUsernameCreator: React.PropTypes.func,
}

const mapStateToProps = createStructuredSelector({
  username: selectUsername(),
  loading: makeSelectLoading(),
})

export default compose(
  connect(mapStateToProps, dispatch => ({
    actions: bindActionCreators(actions, dispatch),
  })),
  withContext({
    actions: React.PropTypes.object.isRequired,
  }, props => ({
    actions: props.actions,
  })),
  getContext({
    actions: React.PropTypes.object.isRequired,
  }),
  withHandlers({
    onChangeUsernameCreator: props => event => {
      props.actions.changeUsername(event.target.value)
    },
  }),
)(HomePage)
<commit_msg>feat: Remove unexpected chars<commit_after>/*
 * HomePage
 *
 * This is the first thing users see of our App, at the '/' route
 */

import React from 'react'
import { connect } from 'react-redux'
import { compose, withContext, getContext, withHandlers } from 'recompose'
import { bindActionCreators } from 'redux'
import { createStructuredSelector } from 'reselect'

import { makeSelectLoading } from 'containers/App/selectors'
import { selectUsername } from './selectors'
import * as actions from './actions'
import ImmutableForm from './immutableForm'

const HomePage = ({ username, onChangeUsernameCreator }) => (

    <input value={username} onChange={onChangeUsernameCreator} />
    <ImmutableForm />

)

HomePage.propTypes = {
  username: React.PropTypes.string,
  onChangeUsernameCreator: React.PropTypes.func,
}

const mapStateToProps = createStructuredSelector({
  username: selectUsername(),
  loading: makeSelectLoading(),
})

export default compose(
  connect(mapStateToProps, dispatch => ({
    actions: bindActionCreators(actions, dispatch),
  })),
  withContext({
    actions: React.PropTypes.object.isRequired,
  }, props => ({
    actions: props.actions,
  })),
  getContext({
    actions: React.PropTypes.object.isRequired,
  }),
  withHandlers({
    onChangeUsernameCreator: props => event => {
      props.actions.changeUsername(event.target.value)
    },
  }),
)(HomePage)
<|endoftext|>


<commit_before>'use strict';
const l10nFile = __dirname + '/../l10n/commands/drop.yml';
const l10n = require('../src/l10n')(l10nFile);
const CommandUtil = require('../src/command_util').CommandUtil;
const util = require('util');

exports.command = (rooms, items, players, npcs, Commands) => {
  return (args, player, isDead) => {
    const room = rooms.getAt(player.getLocation());

    args = args.toLowerCase();

    if (args === 'all') {
      dropAll();
      return;
    }

    let item = CommandUtil.findItemInInventory(args, player, true);

    if (!item && !isDead) {
      return player.sayL10n(l10n, 'ITEM_NOT_FOUND');
    }

    if (item.isEquipped()) {
      item = CommandUtil.findItemInInventory('2.' + args, player, true) || item;
      if (item.isEquipped() && !isDead) {
        return player.sayL10n(l10n, 'ITEM_WORN');
      }
    }

    drop(item);

    function dropAll() {
      player.getInventory().forEach(item => drop(item));
    }

    function drop(item) {
      let playerName = player.getName();

      players.eachIf(
        p => CommandUtil.inSameRoom(p, player),
        p => p.sayL10n(l10n, 'OTHER_DROPS', playerName, item.getShortDesc(p.getLocale()))
      );

      let itemName = item.getShortDesc('en');
      if (!isDead) { player.sayL10n(l10n, 'ITEM_DROP', itemName, false); }
      util.log(playerName + " drops " + itemName + " at " + room.getLocation() + ".");

      room.getNpcs().forEach( id => {
        let npc = npcs.get(id);
        npc.emit('playerDropItem', room, player, players, item);
      });

      player.removeItem(item);
      room.addItem(item.getUuid());
      item.setInventory(null);
      item.setRoom(room.getLocation());
    }
  };
};
<commit_msg>Add check in drop all so you don't drop what you have equipped.<commit_after>'use strict';
const l10nFile = __dirname + '/../l10n/commands/drop.yml';
const l10n = require('../src/l10n')(l10nFile);
const CommandUtil = require('../src/command_util').CommandUtil;
const util = require('util');

exports.command = (rooms, items, players, npcs, Commands) => {
  return (args, player, isDead) => {
    const room = rooms.getAt(player.getLocation());

    args = args.toLowerCase();

    if (args === 'all') {
      dropAll();
      return;
    }

    let item = CommandUtil.findItemInInventory(args, player, true);

    if (!item && !isDead) {
      return player.sayL10n(l10n, 'ITEM_NOT_FOUND');
    }

    if (item.isEquipped()) {
      item = CommandUtil.findItemInInventory('2.' + args, player, true) || item;
      if (item.isEquipped() && !isDead) {
        return player.sayL10n(l10n, 'ITEM_WORN');
      }
    }

    drop(item);

    function dropAll() {
      player.getInventory()
        .forEach(item => item.isEquipped() ?
          drop(item) :
          () => {});
    }

    function drop(item) {
      let playerName = player.getName();

      players.eachIf(
        p => CommandUtil.inSameRoom(p, player),
        p => p.sayL10n(l10n, 'OTHER_DROPS', playerName, item.getShortDesc(p.getLocale()))
      );

      let itemName = item.getShortDesc('en');
      if (!isDead) { player.sayL10n(l10n, 'ITEM_DROP', itemName, false); }
      util.log(playerName + " drops " + itemName + " at " + room.getLocation() + ".");

      room.getNpcs().forEach( id => {
        let npc = npcs.get(id);
        npc.emit('playerDropItem', room, player, players, item);
      });

      player.removeItem(item);
      room.addItem(item.getUuid());
      item.setInventory(null);
      item.setRoom(room.getLocation());
    }
  };
};
<|endoftext|>


<commit_before>"use strict";
var gulp = require('gulp');
var runSequence = require('run-sequence').use(gulp);
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var environments = require('gulp-environments');
var gutil = require('gulp-util');

var config = require('./config');

var build = function(callback) {
  runSequence(
    'clean--all',
    'scripts',
    'styles',
    'markup',
    'assets',
    'styleguide',
    'lab',
    'robots',
    callback
  );
}

gulp.task('build', function(callback) {
  environments.current(environments.development);
  build(callback);
});

gulp.task('production', function(callback) {
  environments.current(environments.production);
  build(callback);
});

gulp.task('watch', function() {
  //gulp.watch(['gulpfile.js', 'build/**/*.js'], ['build']);
  gulp.watch(config.paths.styles.src + '**/*.scss', ['styles', 'assets', reload]);
  gulp.watch(config.paths.scripts.src + '**/*.js', ['scripts', reload]);
  gulp.watch([
    config.paths.lab.src + '**/*',
    config.paths.views.src + '**/*',
    config.paths.data.src + '**/*',
    config.paths.styleguide.src + '**/*'
  ], ['build', reload]);
});

gulp.task('serve', ['build', 'watch'], function(callback) {
  var http = require('http');
  var serveStatic = require('serve-static');
  var finalhandler = require('finalhandler');
  var ngrok = require('ngrok');
  var open = require('open');

  var serve = serveStatic(config.basePaths.dist, {
    "index": ['index.html', 'index.htm']
  });

  var server = http.createServer(function(req, res) {
    var done = finalhandler(req, res);
    serve(req, res, done);
  })

  var serverPort = config.serverPort ? config.serverPort : Math.floor((Math.random() * 1000) + 3000);
  var localhost = 'http://localhost:' + serverPort;

  server.listen(serverPort, function() {
    gutil.log(gutil.colors.green('Local URL'), 'http://localhost:' + serverPort);
    ngrok.connect(serverPort, function(error, url) {
      gutil.log(gutil.colors.green('External URL:'), url);
      open(localhost, 'google chrome');
      callback();
    });
  });

});

gulp.task('default', ['build']);
<commit_msg>Add colon to logged URL<commit_after>"use strict";
var gulp = require('gulp');
var runSequence = require('run-sequence').use(gulp);
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var environments = require('gulp-environments');
var gutil = require('gulp-util');

var config = require('./config');

var build = function(callback) {
  runSequence(
    'clean--all',
    'scripts',
    'styles',
    'markup',
    'assets',
    'styleguide',
    'lab',
    'robots',
    callback
  );
}

gulp.task('build', function(callback) {
  environments.current(environments.development);
  build(callback);
});

gulp.task('production', function(callback) {
  environments.current(environments.production);
  build(callback);
});

gulp.task('watch', function() {
  //gulp.watch(['gulpfile.js', 'build/**/*.js'], ['build']);
  gulp.watch(config.paths.styles.src + '**/*.scss', ['styles', 'assets', reload]);
  gulp.watch(config.paths.scripts.src + '**/*.js', ['scripts', reload]);
  gulp.watch([
    config.paths.lab.src + '**/*',
    config.paths.views.src + '**/*',
    config.paths.data.src + '**/*',
    config.paths.styleguide.src + '**/*'
  ], ['build', reload]);
});

gulp.task('serve', ['build', 'watch'], function(callback) {
  var http = require('http');
  var serveStatic = require('serve-static');
  var finalhandler = require('finalhandler');
  var ngrok = require('ngrok');
  var open = require('open');

  var serve = serveStatic(config.basePaths.dist, {
    "index": ['index.html', 'index.htm']
  });

  var server = http.createServer(function(req, res) {
    var done = finalhandler(req, res);
    serve(req, res, done);
  })

  var serverPort = config.serverPort ? config.serverPort : Math.floor((Math.random() * 1000) + 3000);
  var localhost = 'http://localhost:' + serverPort;

  server.listen(serverPort, function() {
    gutil.log(gutil.colors.green('Local URL:'), 'http://localhost:' + serverPort);
    ngrok.connect(serverPort, function(error, url) {
      gutil.log(gutil.colors.green('External URL:'), url);
      open(localhost, 'google chrome');
      callback();
    });
  });

});

gulp.task('default', ['build']);
<|endoftext|>


<commit_before>const u = require('../styles/utils');
const c = require('../styles/config');
const colors = require('material-colors');

const dashboardPadding = 20;
const halfCategorySpacing = 10;
const categoryBorderWidth = 5;
const transitionDuration = '200ms';
const transitionFunction = 'cubic-bezier(0, 0.8, 0, 1)';

module.exports = {
  '.dashboard': {
    'padding': u.inRem(dashboardPadding),
    'width': u.inRem(c.navBarWidth),
    'height': '100%',
    'overflow': 'auto',
  },

  '.dashboard::-webkit-scrollbar': {
    'display': 'none',
  },

  '.dashboard’s-title': {
    'font-size': u.inRem(40),
    'line-height': u.inRem(40),
  },

  '.dashboard’s-subtitle': {
    'font-size': u.inRem(12),
    'text-transform': 'uppercase',
    'letter-spacing': '0.2em',
  },

  '.dashboard’s-categories': {
    'list-style-type': 'none',
    'padding-top': u.inRem(40),
  },

  '.dashboard’s-category': {
    'line-height': u.inRem(40),
    'position': 'relative',
    'margin': [
      '0',
      u.inRem(-dashboardPadding),
      u.inRem(halfCategorySpacing * 2),
    ].join(' '),
  },

  [[
    '.dashboard’s-button',
    '.dashboard’s-button:focus',
  ].join(', ')]: {
    'display': 'block',
    'width': '100%',
    'padding': [
      '0',
      u.inRem(dashboardPadding),
      '0',
      u.inRem(dashboardPadding - categoryBorderWidth),
    ].join(' '),
    'border-left': [
      u.inRem(categoryBorderWidth),
      'solid',
      u.primaryColorOpacity(0.7),
    ].join(' '),
  },

  '.dashboard’s-button:hover': {
    'background': u.primaryColorOpacity(0.1),
  },

  '.dashboard’s-button:active': {
    'background': u.primaryColorOpacity(0.2),
  },

  '.dashboard’s-button:focus': {
    'outline': 'none',
    'border-left-color': colors.cyan[700],
  },

  '.dashboard’s-category-title': {
    'line-height': u.inRem(60),
    'font-size': u.inRem(14),
    'text-transform': 'uppercase',
    'letter-spacing': '0.07em',
  },

  '.dashboard’s-song': {
    'display': 'block',
    'overflow': 'hidden',
    'color': u.primaryColorOpacity(1),
    'transition': [
      `line-height ${transitionDuration} ${transitionFunction}`,
      `color ${transitionDuration} ${transitionFunction}`,
      `visibility ${transitionDuration} step-start`,
    ].join(', '),
  },

  [
    '.dashboard’s-category:not(.dashboard’s-category·unfolded)'
    + ' .dashboard’s-song'
  ]: {
    'line-height': '0rem',
    'visibility': 'hidden',
    'color': u.primaryColorOpacity(0),
    'transition-timing-function': [
      transitionFunction,
      transitionFunction,
      'step-end',
    ].join(', '),
  },
};
<commit_msg>Smoother animation finish<commit_after>const u = require('../styles/utils');
const c = require('../styles/config');
const colors = require('material-colors');

const dashboardPadding = 20;
const halfCategorySpacing = 10;
const categoryBorderWidth = 5;
const transitionDuration = '167ms';
const transitionFunction = 'cubic-bezier(0, 0.6, 0, 0.8)';

module.exports = {
  '.dashboard': {
    'padding': u.inRem(dashboardPadding),
    'width': u.inRem(c.navBarWidth),
    'height': '100%',
    'overflow': 'auto',
  },

  '.dashboard::-webkit-scrollbar': {
    'display': 'none',
  },

  '.dashboard’s-title': {
    'font-size': u.inRem(40),
    'line-height': u.inRem(40),
  },

  '.dashboard’s-subtitle': {
    'font-size': u.inRem(12),
    'text-transform': 'uppercase',
    'letter-spacing': '0.2em',
  },

  '.dashboard’s-categories': {
    'list-style-type': 'none',
    'padding-top': u.inRem(40),
  },

  '.dashboard’s-category': {
    'line-height': u.inRem(40),
    'position': 'relative',
    'margin': [
      '0',
      u.inRem(-dashboardPadding),
      u.inRem(halfCategorySpacing * 2),
    ].join(' '),
  },

  [[
    '.dashboard’s-button',
    '.dashboard’s-button:focus',
  ].join(', ')]: {
    'display': 'block',
    'width': '100%',
    'padding': [
      '0',
      u.inRem(dashboardPadding),
      '0',
      u.inRem(dashboardPadding - categoryBorderWidth),
    ].join(' '),
    'border-left': [
      u.inRem(categoryBorderWidth),
      'solid',
      u.primaryColorOpacity(0.7),
    ].join(' '),
  },

  '.dashboard’s-button:hover': {
    'background': u.primaryColorOpacity(0.1),
  },

  '.dashboard’s-button:active': {
    'background': u.primaryColorOpacity(0.2),
  },

  '.dashboard’s-button:focus': {
    'outline': 'none',
    'border-left-color': colors.cyan[700],
  },

  '.dashboard’s-category-title': {
    'line-height': u.inRem(60),
    'font-size': u.inRem(14),
    'text-transform': 'uppercase',
    'letter-spacing': '0.07em',
  },

  '.dashboard’s-song': {
    'display': 'block',
    'overflow': 'hidden',
    'color': u.primaryColorOpacity(1),
    'transition': [
      `line-height ${transitionDuration} ${transitionFunction}`,
      `color ${transitionDuration} ${transitionFunction}`,
      `visibility ${transitionDuration} step-start`,
    ].join(', '),
  },

  [
    '.dashboard’s-category:not(.dashboard’s-category·unfolded)'
    + ' .dashboard’s-song'
  ]: {
    'line-height': '0rem',
    'visibility': 'hidden',
    'color': u.primaryColorOpacity(0),
    'transition-timing-function': [
      transitionFunction,
      transitionFunction,
      'step-end',
    ].join(', '),
  },
};
<|endoftext|>


<commit_before>exports.run = (bot, message, args) => {
  var safeEval = require('safe-eval');
  let Discord = require('discord.js');
  if(args.length == 0) throw err;
  var id = message.author.id;
  var output;
  var safe;
  try {
    if (id == 223321546872193024 || id == 232885456172220416 ||
    	id == 266249580058902528 || id == 310505417891381249) {
      safe = `Owner ${message.author.tag}`;
      var output = eval(args.join(" "));
    } else {
      safe = `User ${message.author.tag}`;
      var output = safeEval(args.join(" "));
    }
    const embed = new Discord.RichEmbed()
      .setAuthor(safe, message.author.displayAvatarURL)
      .setColor([188, 123, 55])
      .addField(":inbox_tray: -- Input", "```" + args.join(" ") + "```")
      .addField(":outbox_tray: -- Output", "```" + output + "```");
    message.channel.send({embed});
    message.delete();
  } catch (err) {
    const embed = new Discord.RichEmbed()
      .setAuthor(safe, message.author.displayAvatarURL)
      .setColor([188, 123, 55])
      .addField(":inbox_tray: -- Input", "```" + args.join(" ") + "```")
      .addField(":outbox_tray: -- Output", "```" + err.message + "```");
		message.channel.send({embed});
    message.delete();
  }
}

exports.help = () => {
  return [":floppy_disk:", "eval <Expression>", "Processes the Expression in Node.js."];
}
<commit_msg>Rewrote eval.js<commit_after>exports.run = (bot, message, args) => {
  var safeEval = require('safe-eval');
  let Discord = require('discord.js');
  if(args.length == 0) throw err;
  var id = message.author.id;

  var safe;
  try {
    var output;
    if (id == 223321546872193024 || id == 232885456172220416 ||
    	id == 266249580058902528 || id == 310505417891381249) {
      safe = `Owner ${message.author.tag}`;
      var output = eval(args.join(" "));
    } else {
      safe = `User ${message.author.tag}`;
      var output = safeEval(args.join(" "));
    }
    outputToChannel(message, output, safe);
  } catch (err) {
    outputToChannel(message, err.message, safe);
  }
}

function outputToChannel(message, output, safe) {
  const embed = new Discord.RichEmbed()
    .setAuthor(safe, message.author.displayAvatarURL)
    .setColor([188, 123, 55])
    .addField(":inbox_tray: -- Input", "```" + args.join(" ") + "```")
    .addField(":outbox_tray: -- Output", "```" + output + "```");
  message.channel.send({embed});
  message.delete();
}

exports.help = () => {
  return [":floppy_disk:", "eval <Expression>", "Processes the Expression in Node.js."];
}
<|endoftext|>


<commit_before>'use strict'

// 启动服务
let http = require('http')
let https = require('https')
let fs = require('fs')
let path = require('path')
let express = require('express')
let bodyParser = require('body-parser')
let morgan = require('morgan')
let rfs = require('rotating-file-stream')
let db = require('./models')
let log4js = require('log4js')
let configLog = require('./config-log')
let favicon = require('serve-favicon')

// 处理日志
log4js.configure(configLog)
let sysLog = log4js.getLogger('sys')

// 启动缓存链接
db.redisct()
// 启动数据库链接
db.connect()

// 启动路由及端口处理
let reapp = express()
let app = express()
app.use(log4js.connectLogger(log4js.getLogger('http'), { level: 'auto' }))

// http转发
let httpServer = http.createServer(reapp)
const httpPORT = process.env.HTTPPORT || 8080
reapp.all('*', function(req, res) {
  try {
    return res.redirect("https://" + req.headers["host"].replace('8080', '443') + req.url)
  } catch (e) {
    sysLog.error(e)
  }
})

//https-ssl
let httpsServer = https.createServer({
  key: fs.readFileSync(path.join(__dirname, '../../ssl-key/ssl-fs.rhinel.xyz/ssl-key.key'), 'utf8'),
  cert: fs.readFileSync(path.join(__dirname, '../../ssl-key/ssl-fs.rhinel.xyz/ssl-key.pem'), 'utf8'),
  ciphers: 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4',
  honorCipherOrder: true
}, app)
const httpsPORT = process.env.HTTPSPORT || 443
app.use(favicon(path.join(__dirname, '../static', 'icon-cloud.png')))

// 路由
app.use(express.static(__dirname + '/'))
// 使用post&json
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
// 处理路由
require('./routes')(app, express)

// 启动监听
sysLog.info('--------------------------------------')
sysLog.info(new Date().toLocaleString())
httpServer.listen(httpPORT, ()=>{
  sysLog.info('TechNode http is on port ' + httpPORT + '!')
})

httpsServer.listen(httpsPORT, ()=>{
  sysLog.info('TechNode https is on port ' + httpsPORT + '!')
})
<commit_msg>显示错误来源header<commit_after>'use strict'

// 启动服务
let http = require('http')
let https = require('https')
let fs = require('fs')
let path = require('path')
let express = require('express')
let bodyParser = require('body-parser')
let morgan = require('morgan')
let rfs = require('rotating-file-stream')
let db = require('./models')
let log4js = require('log4js')
let configLog = require('./config-log')
let favicon = require('serve-favicon')

// 处理日志
log4js.configure(configLog)
let sysLog = log4js.getLogger('sys')

// 启动缓存链接
db.redisct()
// 启动数据库链接
db.connect()

// 启动路由及端口处理
let reapp = express()
let app = express()
app.use(log4js.connectLogger(log4js.getLogger('http'), { level: 'auto' }))

// http转发
let httpServer = http.createServer(reapp)
const httpPORT = process.env.HTTPPORT || 8080
reapp.all('*', function(req, res) {
  try {
    return res.redirect("https://" + req.headers["host"].replace('8080', '443') + req.url)
  } catch (e) {
    sysLog.error(req.headers + req.url)
    sysLog.error(e)
  }
})

//https-ssl
let httpsServer = https.createServer({
  key: fs.readFileSync(path.join(__dirname, '../../ssl-key/ssl-fs.rhinel.xyz/ssl-key.key'), 'utf8'),
  cert: fs.readFileSync(path.join(__dirname, '../../ssl-key/ssl-fs.rhinel.xyz/ssl-key.pem'), 'utf8'),
  ciphers: 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4',
  honorCipherOrder: true
}, app)
const httpsPORT = process.env.HTTPSPORT || 443
app.use(favicon(path.join(__dirname, '../static', 'icon-cloud.png')))

// 路由
app.use(express.static(__dirname + '/'))
// 使用post&json
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
// 处理路由
require('./routes')(app, express)

// 启动监听
sysLog.info('--------------------------------------')
sysLog.info(new Date().toLocaleString())
httpServer.listen(httpPORT, ()=>{
  sysLog.info('TechNode http is on port ' + httpPORT + '!')
})

httpsServer.listen(httpsPORT, ()=>{
  sysLog.info('TechNode https is on port ' + httpsPORT + '!')
})
<|endoftext|>


<commit_before>/*
 * grunt-remove-usestrict
 *
 *
 * Copyright (c) 2014 HAKASHUN
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {
  var path = require('path');
  var chalk = require('chalk');

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('remove_usestrict', 'A task to remove usestrict', function () {

    // Iterate over all specified file groups.
    this.files.forEach(function (file) {
      var src = filterExistFile(file);
      if(src.length === 0) {
        grunt.log.warn( 'Destination (' + file.dest + ') not written because src files were empty.' );
        return;
      }
      var dest;
      var isExpandedPair;
      try {
        src.forEach(function(s){
          isExpandedPair = file.orig.expand || false;
          if (detectDestType(file.dest) === 'directory') {
            dest = (isExpandedPair) ? file.dest : unixifyPath(path.join(file.dest, s));
          } else {
            dest = file.dest;
          }
          if(!grunt.file.isDir(s)) {
            grunt.log.writeln('Removing "use strict" from ' + chalk.cyan(s) + ' to ' + chalk.cyan(dest));
            var sourceCode = '' + grunt.file.read(s, {encoding: 'utf8'});
            sourceCode = sourceCode.replace(/("|')use strict\1;?/g, '');
            grunt.file.write(dest, sourceCode, {encoding: 'utf8'});
          }
        });
      } catch(e) {
        outputError(e);
      }
    });
  });

  /**
   * filtering file array only exist file
   * @param file
   * @returns {array}
   */
  var filterExistFile = function(file) {
    return file.src.filter(function (filepath) {
      // Warn on and remove invalid source files (if nonull was set).
      if (!grunt.file.exists(filepath)) {
        grunt.log.warn('Source file "' + filepath + '" not found.');
        return false;
      } else {
        return true;
      }
    });
  };

  /**
   * output error
   * @param e
   */
  var outputError = function(e) {
    var err = new Error( 'Removing "use strict" is failed.' );
    if ( e.msg ) {
      err.message += ', ' + e.msg + '.';
    }
    err.origError = e;
    grunt.fail.warn( err );
  };

  /**
   * detectDestType
   * @param dest
   * @returns {string}
   */
  var detectDestType = function(dest) {
    if (grunt.util._.endsWith(dest, '/')) {
      return 'directory';
    } else {
      return 'file';
    }
  };

  /**
   * unixifyPath
   * @param filepath
   * @returns {*}
   */
  var unixifyPath = function(filepath) {
    if (process.platform === 'win32') {
      return filepath.replace(/\\/g, '/');
    } else {
      return filepath;
    }
  };
};
<commit_msg>Remove the entire line<commit_after>/*
 * grunt-remove-usestrict
 *
 *
 * Copyright (c) 2014 HAKASHUN
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function (grunt) {
  var path = require('path');
  var chalk = require('chalk');

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('remove_usestrict', 'A task to remove usestrict', function () {

    // Iterate over all specified file groups.
    this.files.forEach(function (file) {
      var src = filterExistFile(file);
      if(src.length === 0) {
        grunt.log.warn( 'Destination (' + file.dest + ') not written because src files were empty.' );
        return;
      }
      var dest;
      var isExpandedPair;
      try {
        src.forEach(function(s){
          isExpandedPair = file.orig.expand || false;
          if (detectDestType(file.dest) === 'directory') {
            dest = (isExpandedPair) ? file.dest : unixifyPath(path.join(file.dest, s));
          } else {
            dest = file.dest;
          }
          if(!grunt.file.isDir(s)) {
            grunt.log.writeln('Removing "use strict" from ' + chalk.cyan(s) + ' to ' + chalk.cyan(dest));
            var sourceCode = '' + grunt.file.read(s, {encoding: 'utf8'});
            sourceCode = sourceCode.replace(/("|')use strict\1;?\s*/g, '');
            grunt.file.write(dest, sourceCode, {encoding: 'utf8'});
          }
        });
      } catch(e) {
        outputError(e);
      }
    });
  });

  /**
   * filtering file array only exist file
   * @param file
   * @returns {array}
   */
  var filterExistFile = function(file) {
    return file.src.filter(function (filepath) {
      // Warn on and remove invalid source files (if nonull was set).
      if (!grunt.file.exists(filepath)) {
        grunt.log.warn('Source file "' + filepath + '" not found.');
        return false;
      } else {
        return true;
      }
    });
  };

  /**
   * output error
   * @param e
   */
  var outputError = function(e) {
    var err = new Error( 'Removing "use strict" is failed.' );
    if ( e.msg ) {
      err.message += ', ' + e.msg + '.';
    }
    err.origError = e;
    grunt.fail.warn( err );
  };

  /**
   * detectDestType
   * @param dest
   * @returns {string}
   */
  var detectDestType = function(dest) {
    if (grunt.util._.endsWith(dest, '/')) {
      return 'directory';
    } else {
      return 'file';
    }
  };

  /**
   * unixifyPath
   * @param filepath
   * @returns {*}
   */
  var unixifyPath = function(filepath) {
    if (process.platform === 'win32') {
      return filepath.replace(/\\/g, '/');
    } else {
      return filepath;
    }
  };
};
<|endoftext|>


<commit_before>const config = require("../settings.json");

exports.run = function(client, message, args){
  args = message.content.split(" ").slice(1).join(" ");
  if(args === "") { args = null; }

  console.log("Game status changed.");
  client.user.setGame(args);
};

exports.conf = {
  enabled: true,
  guildOnly: false,
  aliases: ["game"],
  permLevel: 5
};

exports.help = {
  name: "Game",
  description: "Set the game status.",
  usage: "game <args>"
};
<commit_msg>Update game.js<commit_after>const config = require("../settings.json");
const moment = require("moment");

exports.run = function(client, message, args){
  args = message.content.split(" ").slice(1).join(" ");
  if(!args) { args = null; }

  console.log(`[${moment().format("YYYY-MM-DD HH:mm")}] Game status changed to ${args}.`);
  client.user.setGame(args);
}

exports.conf = {
  enabled: true,
  guildOnly: false,
  aliases: ["game"],
  permLevel: 5
};

exports.help = {
  name: "Game",
  description: "Set the game status.",
  usage: "game <args>"
};
<|endoftext|>


<commit_before>'use strict';

// Third party dependencies
var moment = require('moment');

// Local dependencies
var command = require('../lib/command');
var fs      = require('../lib/fs');

/**
 * Returns the last modified timestamp of the remote file as a decimal number.
 * @param {!string} pathname
 * @param {!object} commandChannel
 * @param {!object} session
 */
command.add('MDTM', 'MDTM <sp> pathname', function (pathname, commandChannel, session) {
  var absolutePath = fs.toAbsolute(pathname, session.cwd);

  fs.stat(pathname, function (err, stats) {
    if (err) {
      commandChannel.write(550, fs.errorMessage(err, pathname));
    } else {
      commandChannel.write(213, moment(stats.mtime).format('YYYYMMDDHHmmss'));
    }
  });
});
<commit_msg>Fixed wrong path bug with MDTM<commit_after>'use strict';

// Third party dependencies
var moment = require('moment');

// Local dependencies
var command = require('../lib/command');
var fs      = require('../lib/fs');

/**
 * Returns the last modified timestamp of the remote file as a decimal number.
 * @param {!string} pathname
 * @param {!object} commandChannel
 * @param {!object} session
 */
command.add('MDTM', 'MDTM <sp> pathname', function (pathname, commandChannel, session) {
  var absolutePath = fs.toAbsolute(pathname, session.cwd);

  fs.stat(absolutePath, function (err, stats) {
    if (err) {
      commandChannel.write(550, fs.errorMessage(err, pathname));
    } else {
      commandChannel.write(213, moment(stats.mtime).format('YYYYMMDDHHmmss'));
    }
  });
});
<|endoftext|>


<commit_before><commit_msg>Modal Service<commit_after><|endoftext|>


<commit_before>KadiraDebug = KadiraDebug || {};
var LRUCache = Npm.require('lru-cache');
var UAParser = Npm.require('ua-parser-js');

AppConfig = {
  // app environment. Either `production` or `development`.
  env: Utils.getAppEnv(),

  // auth key taken from enviornment variables
  authKey: Utils.getDebugAuthKey(),

  // This is a set of token passed from the client, these token will be used to
  // authorize a browser session in the production mode.
  // It's possible for a single accessToken to be used in multiple times.

  // XXX: We need to store these inside a DB
  accessTokens: new LRUCache({max: 1000}),

  // XXX: We need to store these in a DB
  // These maps hold authorized Kadira Debug DDP sessionIds
  authorizedSessions: {
    // sessions made from the app's client
    client: {},
    // sessions made from the Kadira Debug UI
    remote: {}
  }
};

var traceStore = new TraceStore();
traceStore.start();

SubHandlers = {
  // Keep DDP sessions of the remote admin's subscription for timeline
  timeline: [],
  // Keep DDP sessions of the client app's subscription for sending the
  // count of remote admins
  listeners: []
};
var uniqueId = 0;
var serverId = Random.id();

// publications

Meteor.publish('kadira.debug.remote.auth', function(authKey) {
  check(authKey, Match.Any);

  // We need to check authentication of a production app only.
  // For other development apps, we can use KD without any authentication
  if(AppConfig.env === 'production') {
    if(authKey !== AppConfig.authKey) {
      throw new Meteor.Error('401', 'Unauthorized.');
    }

    var kadiraInfo = Kadira._getInfo();
    var sessionId = kadiraInfo.session;
    AppConfig.authorizedSessions.remote[sessionId] = true;
  }

  this.onStop(function() {
    delete AppConfig.authorizedSessions.remote[sessionId];
  });

  this.ready();
});

Meteor.publish('kadira.debug.remote.timeline', function() {
  KadiraDebug._authorize('remote');

  this.ready();
  var sub = this;

  SubHandlers.timeline.push(sub);
  updateListenersCount();

  sub.onStop(function() {
    var index = SubHandlers.timeline.indexOf(sub);
    SubHandlers.timeline.splice(index, 1);
    updateListenersCount();
  });
});

Meteor.publish('kadira.debug.client.auth', function(accessToken) {
  check(accessToken, Match.Any);

  // We need to check the accessToken in the production mode only.
  // On development mode we don't need these checks.
  if(AppConfig.env === 'production') {
    if(!AppConfig.accessTokens.has(accessToken)) {
      throw new Meteor.Error('401', 'Unauthorized.');
    }

    var kadiraInfo = Kadira._getInfo();
    var sessionId = kadiraInfo.session;

    AppConfig.authorizedSessions.client[sessionId] = true;
  }

  this.onStop(function() {
    delete AppConfig.authorizedSessions.client[sessionId];
  });

  this.ready();
});

Meteor.publish('kadira.debug.client.listeners', function() {
  KadiraDebug._authorize('client');

  var sub = this;
  var timelineCount = SubHandlers.timeline.length;

  // XXX: We need to get this count from the DB
  sub.added('kdInfo', 'listeners-count', {count: timelineCount});
  sub.ready();

  SubHandlers.listeners.push(sub);
  sub.onStop(function() {
    var index = SubHandlers.listeners.indexOf(sub);
    SubHandlers.listeners.splice(index, 1);
  });
});

Meteor.publish('kadira.debug.client.init', function(browserId, clientId) {
  check(browserId, String);
  check(clientId, String);

  KadiraDebug._authorize('client');

  var kadiraInfo = Kadira._getInfo();
  if(kadiraInfo) {
    var sessionId = kadiraInfo.session;

    traceStore.registerSession(sessionId, browserId, clientId);

    this.onStop(function() {
      traceStore.unregisterSession(browserId, clientId);
    });
  }

  this.ready();
});

// methods
Meteor.methods({
  'kadira.debug.client.updateTimeline': function(browserId, clientId, data) {
    check(browserId, String);
    check(clientId, String);
    check(data, Object);

    KadiraDebug._authorize('client');

    // Pick tracked server time events and push them to the
    // client's payload
    // So, we can send them back to the server
    // XXX: We need to update these to the DB.
    var serverTimeEvents = traceStore.pickTimeEvents(browserId, clientId);
    serverTimeEvents.forEach(function(ev) {
      data.times.push(ev);
    });

    // set unique id for each server sessions
    data.serverId = serverId;

    // update timeline
    // XXX: Try to send these to timeline which monitor the given access token
    // XXX: We need to get these from the DB
    SubHandlers.timeline.forEach(function(sub) {
      var id = 'id' + ++uniqueId;
      sub.added('kdTimeline', id, {
        browserId: browserId,
        clientId: clientId,
        data: data
      });
      sub.removed('kdTimeline', id);
    });
  },

  'kadira.debug.client.getBrowserName': function(userAgent) {
    check(userAgent, String);

    KadiraDebug._authorize('client');

    var parser = new UAParser(userAgent);
    return parser.getResult().browser.name;
  },

  'kadira.debug.remote.getTrace': function(browserId, clientId, type, id) {
    check(browserId, String);
    check(clientId, String);
    check(type, String);
    check(id, String);

    KadiraDebug._authorize('remote');

    // We need to get traces from the DB
    return traceStore.getTrace(browserId, clientId, type, id);
  },

  'kadira.debug.remote.getAppEnv': function() {
    return AppConfig.env;
  },

  'kadira.debug.remote.createAccessToken': function() {
    KadiraDebug._authorize('remote');

    var kadiraInfo = Kadira._getInfo();

    // XXX: We need to update the DB
    var accessToken = Random.id(4);
    AppConfig.accessTokens.set(accessToken, kadiraInfo.session);

    return accessToken;
  },

  'kadira.debug.remote.reset': function() {
    KadiraDebug._authorize('remote');

    // XXX: We need to reset the DB
    AppConfig.accessTokens.reset();
    AppConfig.authorizedSessions = {
      client: {},
      remote: {}
    };
  }
});

function updateListenersCount() {
  SubHandlers.listeners.forEach(function(sub) {
    // XXX: Somehow we need to get this from DB
    // Need to increment the DB.
    var timelineCount = SubHandlers.timeline.length;
    sub.changed('kdInfo', 'listeners-count', {count: timelineCount});
  });
}

KadiraDebug._authorize = function(type, sessionId) {
  if(AppConfig.env === 'development') {
    return true;
  }

  if(!sessionId) {
    var kadiraInfo = Kadira._getInfo();
    var sessionId = kadiraInfo.session;
  }

  // XXX: Here we need to hit the DB
  if(AppConfig.authorizedSessions[type][sessionId]) {
    return true;
  } else {
    throw new Meteor.Error('401', 'Unauthorized.');
  }
};<commit_msg>authorize/authenticate accessToken and the sessions with stored in a localCollection<commit_after>KadiraDebug = KadiraDebug || {};
var UAParser = Npm.require('ua-parser-js');

// This keep number of appConfigs
// such as; accessTokens, clientAuthorizedSessions, remoteAuthorizedSessions etc.
// as documents in a local colletion for authentication purposes
KdConfig = new Mongo.Collection('kDebugConfig');

// accessTokens:
// This is a set of token passed from the client, these token will be used to
// authorize a browser session in the production mode.
// It's possible for a single accessToken to be used in multiple times.

// clientAuthorizedSessions, remoteAuthorizedSessions:
// These are hold authorized Kadira Debug DDP sessionIds

AppConfig = {
  // app environment. Either `production` or `development`.
  env: Utils.getAppEnv(),

  // auth key taken from enviornment variables
  authKey: Utils.getDebugAuthKey(),
};

var traceStore = new TraceStore();
traceStore.start();

SubHandlers = {
  // Keep DDP sessions of the remote admin's subscription for timeline
  timeline: [],
  // Keep DDP sessions of the client app's subscription for sending the
  // count of remote admins
  listeners: []
};
var uniqueId = 0;
var serverId = Random.id();

// publications

Meteor.publish('kadira.debug.remote.auth', function(authKey) {
  check(authKey, Match.Any);

  // We need to check authentication of a production app only.
  // For other development apps, we can use KD without any authentication
  if(AppConfig.env === 'production') {
    if(authKey !== AppConfig.authKey) {
      throw new Meteor.Error('401', 'Unauthorized.');
    }

    // authorize the remote session
    var kadiraInfo = Kadira._getInfo();
    var sessionId = kadiraInfo.session;

    var authObj = {};
    authObj[sessionId] = true;

    KdConfig.update(
      { _id: 'remoteAuthorizedSessions' },
      { $set: authObj },
      { upsert: true }
    );
  }

  this.onStop(function() {
    KdConfig.update(
      {_id: 'remoteAuthorizedSessions'},
      {$unset: authObj}
    );
  });

  this.ready();
});

Meteor.publish('kadira.debug.remote.timeline', function() {
  KadiraDebug._authorize('remote');

  this.ready();
  var sub = this;

  SubHandlers.timeline.push(sub);
  updateListenersCount();

  sub.onStop(function() {
    var index = SubHandlers.timeline.indexOf(sub);
    SubHandlers.timeline.splice(index, 1);
    updateListenersCount();
  });
});

Meteor.publish('kadira.debug.client.auth', function(accessToken) {
  check(accessToken, Match.Any);

  // We need to check the accessToken in the production mode only.
  // On development mode we don't need these checks.
  if(AppConfig.env === 'production') {

    // authenticate accessToken
    var query = {};
    query._id = 'accessTokens';
    query[accessToken] = true;

    if(!KdConfig.findOne(query)) {
      throw new Meteor.Error('401', 'Unauthorized.');
    }

    // authorize client session
    var kadiraInfo = Kadira._getInfo();
    var sessionId = kadiraInfo.session;

    var authObj = {};
    authObj[sessionId] = true;

    KdConfig.update(
      {_id: 'clientAuthorizedSessions'},
      {$set: authObj},
      { upsert: true }
    );
  }

  this.onStop(function() {
    KdConfig.update(
      {_id: 'remoteAuthorizedSessions'},
      {$unset: authObj}
    );
  });

  this.ready();
});

Meteor.publish('kadira.debug.client.listeners', function() {
  KadiraDebug._authorize('client');

  var sub = this;
  var timelineCount = SubHandlers.timeline.length;

  // XXX: We need to get this count from the DB
  sub.added('kdInfo', 'listeners-count', {count: timelineCount});
  sub.ready();

  SubHandlers.listeners.push(sub);
  sub.onStop(function() {
    var index = SubHandlers.listeners.indexOf(sub);
    SubHandlers.listeners.splice(index, 1);
  });
});

Meteor.publish('kadira.debug.client.init', function(browserId, clientId) {
  check(browserId, String);
  check(clientId, String);

  KadiraDebug._authorize('client');

  var kadiraInfo = Kadira._getInfo();
  if(kadiraInfo) {
    var sessionId = kadiraInfo.session;

    traceStore.registerSession(sessionId, browserId, clientId);

    this.onStop(function() {
      traceStore.unregisterSession(browserId, clientId);
    });
  }

  this.ready();
});

// methods
Meteor.methods({
  'kadira.debug.client.updateTimeline': function(browserId, clientId, data) {
    check(browserId, String);
    check(clientId, String);
    check(data, Object);

    KadiraDebug._authorize('client');

    // Pick tracked server time events and push them to the
    // client's payload
    // So, we can send them back to the server
    // XXX: We need to update these to the DB.
    var serverTimeEvents = traceStore.pickTimeEvents(browserId, clientId);
    serverTimeEvents.forEach(function(ev) {
      data.times.push(ev);
    });

    // set unique id for each server sessions
    data.serverId = serverId;

    // update timeline
    // XXX: Try to send these to timeline which monitor the given access token
    // XXX: We need to get these from the DB
    SubHandlers.timeline.forEach(function(sub) {
      var id = 'id' + ++uniqueId;
      sub.added('kdTimeline', id, {
        browserId: browserId,
        clientId: clientId,
        data: data
      });
      sub.removed('kdTimeline', id);
    });
  },

  'kadira.debug.client.getBrowserName': function(userAgent) {
    check(userAgent, String);

    KadiraDebug._authorize('client');

    var parser = new UAParser(userAgent);
    return parser.getResult().browser.name;
  },

  'kadira.debug.remote.getTrace': function(browserId, clientId, type, id) {
    check(browserId, String);
    check(clientId, String);
    check(type, String);
    check(id, String);

    KadiraDebug._authorize('remote');

    // XXX: We need to get traces from the DB
    return traceStore.getTrace(browserId, clientId, type, id);
  },

  'kadira.debug.remote.getAppEnv': function() {
    return AppConfig.env;
  },

  'kadira.debug.remote.createAccessToken': function() {
    KadiraDebug._authorize('remote');

    var kadiraInfo = Kadira._getInfo();

    // authorize accessToken
    var accessToken = Random.id(4);

    var tokenObj = {};
    tokenObj[accessToken] = true;

    KdConfig.update(
      { _id: 'accessTokens' },
      { $set: tokenObj },
      { upsert: true }
    );

    return accessToken;
  },

  'kadira.debug.remote.reset': function() {
    KadiraDebug._authorize('remote');
    resetKdDbConfig();
  }
});

function updateListenersCount() {
  SubHandlers.listeners.forEach(function(sub) {
    // XXX: Somehow we need to get this from DB
    // Need to increment the DB.
    var timelineCount = SubHandlers.timeline.length;
    sub.changed('kdInfo', 'listeners-count', {count: timelineCount});
  });
}

KadiraDebug._authorize = function(type, sessionId) {
  if(AppConfig.env === 'development') {
    return true;
  }

  if(!sessionId) {
    var kadiraInfo = Kadira._getInfo();
    var sessionId = kadiraInfo.session;
  }

  // authenticate the current session
  var query = {};
  query._id = type + 'AuthorizedSessions';
  query[sessionId] = true;

  if(KdConfig.findOne(query)) {
    return true;
  } else {
    throw new Meteor.Error('401', 'Unauthorized.');
  }
};

function resetKdDbConfig() {
  KdConfig.remove({_id: 'accessTokens'});
  KdConfig.remove({_id: 'clientAuthorizedSessions'});
  KdConfig.remove({_id: 'remoteAuthorizedSessions'});
}<|endoftext|>