<commit_before>function app_events(_args) {
	var win = Titanium.UI.createWindow({
		title:_args.title,
		navBarHidden:true
	});

	var label = Ti.UI.createLabel({
		text:'No app event received. Make call while running app',
		textAlign:'center',
		width:'auto'
	});

	win.add(label);

	var paused = false;

	Titanium.App.addEventListener('pause',function(e)
	{
		Ti.API.info("PAUSED");
		paused = true;
		label.text = "App has been paused";
	});

	Titanium.App.addEventListener('resume',function(e)
	{
		Ti.API.info("RESUMED");
		if (paused)
		{
			label.text = "App has resumed";
		}
		else
		{
			label.text = "App has resumed (w/o pause)";
		}
	});

	if (Titanium.Platform.name == 'android') {
		win.addEventListener('open', function() {
			win.activity.addEventListener('pause', function(e) {
				Ti.API.info("pause event received");
				paused = true;
				label.text = "App has been paused";
			});
			win.activity.addEventListener('resume', function(e) {
				Ti.API.info("resume event received");
				if (paused) {
					label.text = "App has resumed";
				} else {
					label.text = "App has resumed (w/o pause)";
				}
			});
		});
	}

	return win;
};

module.exports = app_events;

<commit_msg>[TIMOB-12218]Adding test case for `significanttimechange` event. <commit_after>function app_events(_args) {
	var win = Titanium.UI.createWindow({
		title:_args.title,
		navBarHidden:true
	});

	var view = Titanium.UI.createView({
	  top: 20,
	  width:Ti.UI.FILL,
	  height: Ti.UI.FILL,
	  layout:'vertical'
	});
	win.add(view);

	var label = Ti.UI.createLabel({
		text:'No app event received. Make call while running app',
		textAlign:'center',
		width:'auto'
	});

	view.add(label);

	var paused = false;

	function pauseResponse(e){
		Ti.API.info("PAUSED");
		paused = true;
		label.text = "App has been paused";
	}
	Titanium.App.addEventListener('pause', pauseResponse);

	function resumeResponse(e){
		Titanium.API.info("RESUMED");
		if (paused)
		{
			label.text = "App has resumed";
		}
		else
		{
			label.text = "App has resumed (w/o pause)";
		}
	}

	Titanium.App.addEventListener('resume', resumeResponse);

	win.addEventListener('close', function(e){
		Titanium.API.info('Removing `paused` and `resume` events.');
		Titanium.App.removeEventListener('pause',pauseResponse);
		Titanium.App.removeEventListener('resume',resumeResponse);
	});

	if(Titanium.Platform.name == 'iPhone OS'){
		var timeLabel = Ti.UI.createLabel({
			top:50,
			text:'No Time Change event, received. Try Changing the devices time zone (Setting > General > Date & Time> TimeZone',
			textAlign:'center',
			width:'auto'
		});
		view.add(timeLabel)

		function timeChanged(){
			Ti.API.info("Time Change Event Received !! ");
			timeLabel.text = "Time Change event received.";
		}

		Titanium.App.addEventListener('significanttimechange', timeChanged);

		win.addEventListener('close',function(){
			Titanium.API.info('Removing `significanttimechange` event.');
			Titanium.App.removeEventListener('significanttimechange',timeChanged);
		});
	 }

	if (Titanium.Platform.name == 'android') {
		win.addEventListener('open', function() {
			win.activity.addEventListener('pause', function(e) {
				Ti.API.info("pause event received");
				paused = true;
				label.text = "App has been paused";
			});
			win.activity.addEventListener('resume', function(e) {
				Ti.API.info("resume event received");
				if (paused) {
					label.text = "App has resumed";
				} else {
					label.text = "App has resumed (w/o pause)";
				}
			});
		});
	}

	return win;
};

module.exports = app_events;<|endoftext|>


<commit_before>var fs = require('fs');
var exec = require('child_process').exec;
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var async = require('async');
var debug = require('debug')('rpi-gpio');
var Epoll = require('epoll').Epoll;

var PINS = {
    v1: {
        // 1: 3.3v
        // 2: 5v
        '3': 0,
        // 4: 5v
        '5': 1,
        // 6: ground
        '7': 4,
        '8': 14,
        // 9: ground
        '10': 15,
        '11': 17,
        '12': 18,
        '13': 21,
        // 14: ground
        '15': 22,
        '16': 23,
        // 17: 3.3v
        '18': 24,
        '19': 10,
        // 20: ground
        '21': 9,
        '22': 25,
        '23': 11,
        '24': 8,
        // 25: ground
        '26': 7
    },
    v2: {
        // 1: 3.3v
        // 2: 5v
        '3': 2,
        // 4: 5v
        '5': 3,
        // 6: ground
        '7': 4,
        '8': 14,
        // 9: ground
        '10': 15,
        '11': 17,
        '12': 18,
        '13': 27,
        // 14: ground
        '15': 22,
        '16': 23,
        // 17: 3.3v
        '18': 24,
        '19': 10,
        // 20: ground
        '21': 9,
        '22': 25,
        '23': 11,
        '24': 8,
        // 25: ground
        '26': 7,

        // Model B+ pins
        // 27: ID_SD
        // 28: ID_SC
        '29': 5,
        // 30: ground
        '31': 6,
        '32': 12,
        '33': 13,
        // 34: ground
        '35': 19,
        '36': 16,
        '37': 26,
        '38': 20,
        // 39: ground
        '40': 21
    }
};

// OPTIONS:
// gpioAdmin: true|false - whether to use gpioAdmin or not. If not, must be run as root.
// mode: 'BCM'|'RPI' - Sets pin numbering scheme. Defaults to RPI;
function Gpio(options) {

    options = options || {};

    var currentPins;
    var exportedInputPins = {};
    var exportedOutputPins = {};
    var poller;

    var getPin;
    if(options.mode && options.mode == 'BCM'){
        debug('Setting mode to BCM.');
        getPin = getPinBcm;
    } else {
        debug('Setting mode to RPI.');
        getPin = getPinRpi;
    }
    var path = options.gpioAdmin === true ? '/sys/devices/virtual/gpio' : '/sys/class/gpio';

    this.DIR_IN = 'in';
    this.DIR_OUT = 'out';
    this.PULL_UP = 'pullup';
    this.PULL_DOWN = 'pulldown';
    this.MODE_RPI = 'mode_rpi';
    this.MODE_BCM = 'mode_bcm';

    /**
     * Setup a channel for use as an input or output
     *
     * @param {number}   channel   Reference to the pin in the current mode's schema
     * @param {string}   direction The pin direction, either 'in' or 'out'
     * @param {string}   pullupdown Optional whether to enable pull up or down resistors, either 'pullup' or 'pulldown'.
     * Currently only available in gpio-admin.
     * @param {function} onSetup   Optional callback
     */
    /*
    setup(channel, onSetup)
    setup(channel, direction, onSetup)
    setup(channel, direction, pullupdown, onSetup)
     */
    this.setup = function(channel, direction, pullupdown, onSetup /*err*/) {
        if (arguments.length === 2 && typeof direction == 'function') {
            onSetup = direction;
            direction = this.DIR_OUT;
        }

        if (arguments.length === 3 && typeof pullupdown == 'function') {
            onSetup = pullupdown;
        }

        direction = direction || this.DIR_OUT;
        onSetup = onSetup || function() {};

        if (!channel) {
            return process.nextTick(function() {
                onSetup(new Error('Channel must be a number'));
            });
        }

        if (direction !== this.DIR_IN && direction !== this.DIR_OUT) {
            return process.nextTick(function() {
                onSetup(new Error('Cannot set invalid direction'));
            });
        }

        if (pullupdown !== this.PULL_UP && pullupdown !== this.PULL_DOWN) {
            return process.nextTick(function() {
                onSetup(new Error('Cannot set invalid pullup/pulldown value'));
            });
        }

        var pinForSetup;
        async.waterfall([
            setRaspberryVersion,
            function(next) {
                pinForSetup = getPin(channel);
                if (!pinForSetup) {
                    return next(new Error('Channel ' + channel + ' does not map to a GPIO pin'));
                }
                debug('set up pin %d', pinForSetup);
                isExported(pinForSetup, next);
            },
            function(isExported, next) {
                if (isExported) {
                    return unexportPin(pinForSetup, next);
                }
                return next(null);
            },
            function(next) {
                exportPin(pinForSetup, pullupdown, next);
            },
            function(next) {
                this.emit('export', channel);
                createListener.call(this, channel, pinForSetup);

                if (direction === this.DIR_IN) {
                    exportedInputPins[pinForSetup] = true;
                } else {
                    exportedOutputPins[pinForSetup] = true;
                }

                setDirection(pinForSetup, direction, next);
            }.bind(this)
        ], onSetup);
    };

    /**
     * Write a value to a channel
     *
     * @param {number}   channel The channel to write to
     * @param {boolean}  value   If true, turns the channel on, else turns off
     * @param {function} cb      Optional callback
     */
    this.write = this.output = function(channel, value, cb /*err*/) {
        var pin = getPin(channel);

        if (!exportedOutputPins[pin]) {
            var message;
            if (exportedInputPins[pin]) {
                message = 'Pin has been exported for input so cannot be written to';
            } else {
                message = 'Pin has not been exported';
            }

            return process.nextTick(function() {
                cb(new Error(message));
            });
        }

        value = (!!value && value !== '0') ? '1' : '0';
        fs.writeFile(path + '/gpio' + pin + '/value', value, cb || function() {});
    };

    /**
     * Read a value from a channel
     *
     * @param {number}   channel The channel to read from
     * @param {function} cb      Callback which receives the channel's boolean value
     */
    this.read = this.input = function(channel, cb /*err,value*/) {
        var pin = getPin(channel);

        if (!exportedInputPins[pin]) {
            return process.nextTick(function() {
                cb(new Error('Pin has not been exported'));
            });
        }

        var buffer = new Buffer(1);
        var fd = fs.openSync(path + '/gpio' + pin + '/value', 'r');
        fs.read(fd, buffer, 0, 1, 0, function(err, bytesRead, buffer) {
            return cb(err, buffer.toString() === '1');
        });
    };

    /**
     * Unexport any pins setup by this module
     *
     * @param {function} cb Optional callback
     */
    this.destroy = function(cb) {
        poller.close();
        var tasks = Object.keys(exportedOutputPins)
            .concat(Object.keys(exportedInputPins))
            .map(function(pin) {
                return function(done) {
                    unexportPin(pin, done);
                }
            });

        async.parallel(tasks, cb);
    };

    /**
     * Reset the state of the module
     */
    this.reset = function() {
        exportedOutputPins = {};
        exportedInputPins = {};
        this.removeAllListeners();

        currentPins = undefined;
        getPin = getPinRpi;
    };

    // Init
    EventEmitter.call(this);
    this.reset();

    // Private functions requring access to state
    function setRaspberryVersion(cb) {
        if (currentPins) {
            return cb(null);
        }

        fs.readFile('/proc/cpuinfo', 'utf8', function(err, data) {
            if (err) {return cb(err);}

            // Match the last 4 digits of the number following "Revision:"
            var match = data.match(/Revision\s*:\s*[0-9a-f]*([0-9a-f]{4})/);
            var revisionNumber = parseInt(match[1], 16);
            var pinVersion = (revisionNumber < 4) ? 'v1' : 'v2';

            debug(
                'seen hardware revision %d; using pin mode %s',
                revisionNumber,
                pinVersion
            );

            currentPins = PINS[pinVersion];

            return cb(null);
        });
    };

    function getPinRpi(channel) {
        return currentPins[channel] + '';
    };

    function getPinBcm(channel) {
        channel = parseInt(channel, 10);
        return [
            3,
            5,
            7,
            8,
            10,
            11,
            12,
            13,
            15,
            16,
            18,
            19,
            21,
            22,
            23,
            24,
            26,
            29,
            31,
            32,
            33,
            35,
            36,
            37,
            38,
            40
        ].indexOf(channel) !== -1 ? (channel + '') : null;
    };

    function createListener(channel, pin) {
        debug('listen for pin %d', pin);
        var Gpio = this;

        // only initialize poller on first use
        if(!poller){
            poller = new Epoll(function (err, fd, events) {
                // Read GPIO value file. Reading also clears the interrupt.
                Gpio.read(channel, function(err, value){
                    Gpio.emit('change', channel, value);
                });
            });
        }

        var fd = fs.openSync(path + '/gpio' + pin + '/value', 'r');

        // Read the GPIO value file before watching to prevent an initial unauthentic interrupt.
        fs.readSync(fd, new Buffer(1), 0, 1, 0);

        // Start watching for interrupts.
        poller.add(fd, Epoll.EPOLLPRI);
    };

    var baseCommand = 'gpio-admin';

    function setDirection(pin, direction, cb) {
        debug('set direction %s on pin %d', direction.toUpperCase(), pin);
        fs.writeFile(path + '/gpio' + pin + '/direction', direction, function(err) {
            if (cb) {
                return cb(err);
            }
        });
    }

    function exportPin(pin, pullupdown, cb) {
        debug('export pin %d with pullup/down mode %s', pin, pullupdown);
        if (options.gpioAdmin) {
            if(pullupdown){
                execCommand(baseCommand + ' export ' + pin + ' ' + pullupdown, cb);
            } else {
                execCommand(baseCommand + ' export ' + pin, cb);
            }
        } else {
            fs.writeFile(path + '/export', pin, cb);
        }
    }

    function unexportPin(pin, cb) {
        debug('unexport pin %d', pin);
        var fd = fs.openSync(path + '/gpio' + pin + '/value', 'r');
        poller.remove(fd);
        if (options.gpioAdmin) {
            execCommand(baseCommand + ' unexport ' + pin, cb);
        } else {
            fs.writeFile(path + '/unexport', pin, cb);
        }
    }

    function isExported(pin, cb) {
        fs.exists(path + '/gpio' + pin, function(exists) {
            return cb(null, exists);
        });
    }

}
util.inherits(Gpio, EventEmitter);

function execCommand(command, cb) {

    exec(command,
        function(error, stdout, stderr) {
            if (error) {
                debug('command: ' + command);
                debug('exec error: ' + error);
                debug('stderr: ' + stderr);
                debug('stdout: ' + stdout);
            }
            return cb(error);
        });
}

module.exports = new Gpio;<commit_msg>quick fix for pullupdown<commit_after>var fs = require('fs');
var exec = require('child_process').exec;
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var async = require('async');
var debug = require('debug')('rpi-gpio');
var Epoll = require('epoll').Epoll;

var PINS = {
    v1: {
        // 1: 3.3v
        // 2: 5v
        '3': 0,
        // 4: 5v
        '5': 1,
        // 6: ground
        '7': 4,
        '8': 14,
        // 9: ground
        '10': 15,
        '11': 17,
        '12': 18,
        '13': 21,
        // 14: ground
        '15': 22,
        '16': 23,
        // 17: 3.3v
        '18': 24,
        '19': 10,
        // 20: ground
        '21': 9,
        '22': 25,
        '23': 11,
        '24': 8,
        // 25: ground
        '26': 7
    },
    v2: {
        // 1: 3.3v
        // 2: 5v
        '3': 2,
        // 4: 5v
        '5': 3,
        // 6: ground
        '7': 4,
        '8': 14,
        // 9: ground
        '10': 15,
        '11': 17,
        '12': 18,
        '13': 27,
        // 14: ground
        '15': 22,
        '16': 23,
        // 17: 3.3v
        '18': 24,
        '19': 10,
        // 20: ground
        '21': 9,
        '22': 25,
        '23': 11,
        '24': 8,
        // 25: ground
        '26': 7,

        // Model B+ pins
        // 27: ID_SD
        // 28: ID_SC
        '29': 5,
        // 30: ground
        '31': 6,
        '32': 12,
        '33': 13,
        // 34: ground
        '35': 19,
        '36': 16,
        '37': 26,
        '38': 20,
        // 39: ground
        '40': 21
    }
};

// OPTIONS:
// gpioAdmin: true|false - whether to use gpioAdmin or not. If not, must be run as root.
// mode: 'BCM'|'RPI' - Sets pin numbering scheme. Defaults to RPI;
function Gpio(options) {

    options = options || {};

    var currentPins;
    var exportedInputPins = {};
    var exportedOutputPins = {};
    var poller;

    var getPin;
    if(options.mode && options.mode == 'BCM'){
        debug('Setting mode to BCM.');
        getPin = getPinBcm;
    } else {
        debug('Setting mode to RPI.');
        getPin = getPinRpi;
    }
    var path = options.gpioAdmin === true ? '/sys/devices/virtual/gpio' : '/sys/class/gpio';

    this.DIR_IN = 'in';
    this.DIR_OUT = 'out';
    this.PULL_UP = 'pullup';
    this.PULL_DOWN = 'pulldown';
    this.MODE_RPI = 'mode_rpi';
    this.MODE_BCM = 'mode_bcm';

    /**
     * Setup a channel for use as an input or output
     *
     * @param {number}   channel   Reference to the pin in the current mode's schema
     * @param {string}   direction The pin direction, either 'in' or 'out'
     * @param {string}   pullupdown Optional whether to enable pull up or down resistors, either 'pullup' or 'pulldown'.
     * Currently only available in gpio-admin.
     * @param {function} onSetup   Optional callback
     */
    /*
    setup(channel, onSetup)
    setup(channel, direction, onSetup)
    setup(channel, direction, pullupdown, onSetup)
     */
    this.setup = function(channel, direction, pullupdown, onSetup /*err*/) {
        if (arguments.length === 2 && typeof direction == 'function') {
            onSetup = direction;
            direction = this.DIR_OUT;
        }

        if (arguments.length === 3 && typeof pullupdown == 'function') {
            onSetup = pullupdown;
            pullupdown = null;
        }

        direction = direction || this.DIR_OUT;
        onSetup = onSetup || function() {};

        if (!channel) {
            return process.nextTick(function() {
                onSetup(new Error('Channel must be a number'));
            });
        }

        if (direction !== this.DIR_IN && direction !== this.DIR_OUT) {
            return process.nextTick(function() {
                onSetup(new Error('Cannot set invalid direction'));
            });
        }

        if (pullupdown !== this.PULL_UP && pullupdown !== this.PULL_DOWN) {
            return process.nextTick(function() {
                onSetup(new Error('Cannot set invalid pullup/pulldown value'));
            });
        }

        var pinForSetup;
        async.waterfall([
            setRaspberryVersion,
            function(next) {
                pinForSetup = getPin(channel);
                if (!pinForSetup) {
                    return next(new Error('Channel ' + channel + ' does not map to a GPIO pin'));
                }
                debug('set up pin %d', pinForSetup);
                isExported(pinForSetup, next);
            },
            function(isExported, next) {
                if (isExported) {
                    return unexportPin(pinForSetup, next);
                }
                return next(null);
            },
            function(next) {
                exportPin(pinForSetup, pullupdown, next);
            },
            function(next) {
                this.emit('export', channel);
                createListener.call(this, channel, pinForSetup);

                if (direction === this.DIR_IN) {
                    exportedInputPins[pinForSetup] = true;
                } else {
                    exportedOutputPins[pinForSetup] = true;
                }

                setDirection(pinForSetup, direction, next);
            }.bind(this)
        ], onSetup);
    };

    /**
     * Write a value to a channel
     *
     * @param {number}   channel The channel to write to
     * @param {boolean}  value   If true, turns the channel on, else turns off
     * @param {function} cb      Optional callback
     */
    this.write = this.output = function(channel, value, cb /*err*/) {
        var pin = getPin(channel);

        if (!exportedOutputPins[pin]) {
            var message;
            if (exportedInputPins[pin]) {
                message = 'Pin has been exported for input so cannot be written to';
            } else {
                message = 'Pin has not been exported';
            }

            return process.nextTick(function() {
                cb(new Error(message));
            });
        }

        value = (!!value && value !== '0') ? '1' : '0';
        fs.writeFile(path + '/gpio' + pin + '/value', value, cb || function() {});
    };

    /**
     * Read a value from a channel
     *
     * @param {number}   channel The channel to read from
     * @param {function} cb      Callback which receives the channel's boolean value
     */
    this.read = this.input = function(channel, cb /*err,value*/) {
        var pin = getPin(channel);

        if (!exportedInputPins[pin]) {
            return process.nextTick(function() {
                cb(new Error('Pin has not been exported'));
            });
        }

        var buffer = new Buffer(1);
        var fd = fs.openSync(path + '/gpio' + pin + '/value', 'r');
        fs.read(fd, buffer, 0, 1, 0, function(err, bytesRead, buffer) {
            return cb(err, buffer.toString() === '1');
        });
    };

    /**
     * Unexport any pins setup by this module
     *
     * @param {function} cb Optional callback
     */
    this.destroy = function(cb) {
        poller.close();
        var tasks = Object.keys(exportedOutputPins)
            .concat(Object.keys(exportedInputPins))
            .map(function(pin) {
                return function(done) {
                    unexportPin(pin, done);
                }
            });

        async.parallel(tasks, cb);
    };

    /**
     * Reset the state of the module
     */
    this.reset = function() {
        exportedOutputPins = {};
        exportedInputPins = {};
        this.removeAllListeners();

        currentPins = undefined;
        getPin = getPinRpi;
    };

    // Init
    EventEmitter.call(this);
    this.reset();

    // Private functions requring access to state
    function setRaspberryVersion(cb) {
        if (currentPins) {
            return cb(null);
        }

        fs.readFile('/proc/cpuinfo', 'utf8', function(err, data) {
            if (err) {return cb(err);}

            // Match the last 4 digits of the number following "Revision:"
            var match = data.match(/Revision\s*:\s*[0-9a-f]*([0-9a-f]{4})/);
            var revisionNumber = parseInt(match[1], 16);
            var pinVersion = (revisionNumber < 4) ? 'v1' : 'v2';

            debug(
                'seen hardware revision %d; using pin mode %s',
                revisionNumber,
                pinVersion
            );

            currentPins = PINS[pinVersion];

            return cb(null);
        });
    };

    function getPinRpi(channel) {
        return currentPins[channel] + '';
    };

    function getPinBcm(channel) {
        channel = parseInt(channel, 10);
        return [
            3,
            5,
            7,
            8,
            10,
            11,
            12,
            13,
            15,
            16,
            18,
            19,
            21,
            22,
            23,
            24,
            26,
            29,
            31,
            32,
            33,
            35,
            36,
            37,
            38,
            40
        ].indexOf(channel) !== -1 ? (channel + '') : null;
    };

    function createListener(channel, pin) {
        debug('listen for pin %d', pin);
        var Gpio = this;

        // only initialize poller on first use
        if(!poller){
            poller = new Epoll(function (err, fd, events) {
                // Read GPIO value file. Reading also clears the interrupt.
                Gpio.read(channel, function(err, value){
                    Gpio.emit('change', channel, value);
                });
            });
        }

        var fd = fs.openSync(path + '/gpio' + pin + '/value', 'r');

        // Read the GPIO value file before watching to prevent an initial unauthentic interrupt.
        fs.readSync(fd, new Buffer(1), 0, 1, 0);

        // Start watching for interrupts.
        poller.add(fd, Epoll.EPOLLPRI);
    };

    var baseCommand = 'gpio-admin';

    function setDirection(pin, direction, cb) {
        debug('set direction %s on pin %d', direction.toUpperCase(), pin);
        fs.writeFile(path + '/gpio' + pin + '/direction', direction, function(err) {
            if (cb) {
                return cb(err);
            }
        });
    }

    function exportPin(pin, pullupdown, cb) {
        debug('export pin %d with pullup/down mode %s', pin, pullupdown);
        if (options.gpioAdmin) {
            if(pullupdown){
                execCommand(baseCommand + ' export ' + pin + ' ' + pullupdown, cb);
            } else {
                execCommand(baseCommand + ' export ' + pin, cb);
            }
        } else {
            fs.writeFile(path + '/export', pin, cb);
        }
    }

    function unexportPin(pin, cb) {
        debug('unexport pin %d', pin);
        var fd = fs.openSync(path + '/gpio' + pin + '/value', 'r');
        poller.remove(fd);
        if (options.gpioAdmin) {
            execCommand(baseCommand + ' unexport ' + pin, cb);
        } else {
            fs.writeFile(path + '/unexport', pin, cb);
        }
    }

    function isExported(pin, cb) {
        fs.exists(path + '/gpio' + pin, function(exists) {
            return cb(null, exists);
        });
    }

}
util.inherits(Gpio, EventEmitter);

function execCommand(command, cb) {

    exec(command,
        function(error, stdout, stderr) {
            if (error) {
                debug('command: ' + command);
                debug('exec error: ' + error);
                debug('stderr: ' + stderr);
                debug('stdout: ' + stdout);
            }
            return cb(error);
        });
}

module.exports = new Gpio;<|endoftext|>


<commit_before>const fs = require("fs");
const path = require("path");
const Discord = require("discord.js");
const logger = require("../logger");
const DiscordWinstonTransport = require("../DiscordWinstonTransport");

const client = new Discord.Client();

const handlers = {
  help: handleHelp,
};

const commands = fs
  .readdirSync(path.resolve(__dirname, "./commands"))
  .filter((file) => file.endsWith(".js"))
  .map((file) => {
    return require(`./commands/${file}`);
  });

for (const command of commands) {
  handlers[command.command] = command.handler;
}

async function handleHelp(message) {
  const commandHelp = commands
    .map((command) => {
      return `\`!${command.command} ${command.usage || ""}\` -- ${
        command.description
      }`;
    })
    .join("\n");

  const help = `
I am a helpful bot that can do things with Winamp skins. Here are the commands I know:

${commandHelp}
\`!help\` Show this message

You can issue these commands in a DM to me or in any channel. For tasks relating to approving skins, I will respond in the #tweet-bot channel.
`.trim();
  message.channel.send(help);
}

client.on("message", async (message) => {
  if (message.author.bot) {
    return;
  }
  const [rawCommand, ...args] = message.content.split(" ");
  if (!rawCommand.startsWith("!")) {
    return;
  }
  const command = rawCommand.slice(1);
  logger.info(`User triggered WebampBot command`, {
    command,
    user: message.author.username,
    args,
    channel: message.channel.name || "DM",
  });
  const handler = handlers[command];
  if (handler == null) {
    logger.warn("Unknown command", {
      command,
      user: message.author.username,
      args,
      alert: true,
    });
    return;
  }
  handler(message, args);
});

client.on("error", (e) => {
  logger.error("The WebSocket encountered an error:", e);
});

async function main() {
  DiscordWinstonTransport.addToLogger(client, logger);
}

main();
<commit_msg>Await handler<commit_after>const fs = require("fs");
const path = require("path");
const Discord = require("discord.js");
const logger = require("../logger");
const DiscordWinstonTransport = require("../DiscordWinstonTransport");

const client = new Discord.Client();

const handlers = {
  help: handleHelp,
};

const commands = fs
  .readdirSync(path.resolve(__dirname, "./commands"))
  .filter((file) => file.endsWith(".js"))
  .map((file) => {
    return require(`./commands/${file}`);
  });

for (const command of commands) {
  handlers[command.command] = command.handler;
}

async function handleHelp(message) {
  const commandHelp = commands
    .map((command) => {
      return `\`!${command.command} ${command.usage || ""}\` -- ${
        command.description
      }`;
    })
    .join("\n");

  const help = `
I am a helpful bot that can do things with Winamp skins. Here are the commands I know:

${commandHelp}
\`!help\` Show this message

You can issue these commands in a DM to me or in any channel. For tasks relating to approving skins, I will respond in the #tweet-bot channel.
`.trim();
  message.channel.send(help);
}

client.on("message", async (message) => {
  if (message.author.bot) {
    return;
  }
  const [rawCommand, ...args] = message.content.split(" ");
  if (!rawCommand.startsWith("!")) {
    return;
  }
  const command = rawCommand.slice(1);
  logger.info(`User triggered WebampBot command`, {
    command,
    user: message.author.username,
    args,
    channel: message.channel.name || "DM",
  });
  const handler = handlers[command];
  if (handler == null) {
    logger.warn("Unknown command", {
      command,
      user: message.author.username,
      args,
      alert: true,
    });
    return;
  }
  await handler(message, args);
});

client.on("error", (e) => {
  logger.error("The WebSocket encountered an error:", e);
});

async function main() {
  DiscordWinstonTransport.addToLogger(client, logger);
}

main();
<|endoftext|>


<commit_before>require('sugar')

var googlePlus = require('./google-plus'),
    express = require('express'),
    errors = require('./errors'),
    connect = require('connect')

var app = express()

app.configure(function() {
    app.use(express.static(__dirname + '/../public'))
    app.set('views', __dirname + '/../views')
    app.set('view engine', 'ejs')
    app.set('view options', {layout: false})
    app.use(connect.compress());
    app.use(function(request, response, next) {
        response.header('Cache-Control', 'max-age=0')
        next()
    })
})

app.get('/', function(request, response) {
    response.render('home')
})

app.get('/:id', function(request, response, next) {
    var userId = request.params.id
    if (! /^[0-9]+$/.test(userId)) return next()
    var plus = new googlePlus.GooglePlus(process.env.GOOGLE_API_KEY)
    var styles = {
        title: request.query.title || 'cut'
    }

    /**
     * @returns {number} In seconds
     */
    var getLapseSinceLastUpdate = function(posts) {
        return posts.length ? Math.round((new Date - posts[0].updated) / 1000) : Infinity
    }

    var getCacheMaxAge = function(posts) {
        var minAge = 10 /* mins */ * 60
        var maxAge = 120 /* mins */ * 60
        return Math.max(minAge, Math.min(maxAge, getLapseSinceLastUpdate(posts)))
    }

    plus.userPosts(userId, styles, function(error, posts) {
        if (error) return next(error)
        response.header('Content-Type', 'text/xml; charset=utf-8')
        response.header('Cache-Control', 'max-age=' + getCacheMaxAge(posts))
        response.render('feed', {
            profileUrl: 'https://plus.google.com/' + userId,
            posts: posts,
        })
    })
})

app.get('/feed.xsl', function(request, response) {
    response.render('feed-xsl')
})

app.get('/*', function(request, response, next) {
    next(new errors.NotFoundError)
})

app.use(function(error, request, response, next) {
    response.header('Content-Type', 'text/plain; charset=utf-8')
    if (error instanceof errors.UserError) {
        var code = error instanceof errors.NotFoundError ? 404 : 400
        response.send(error.message, code)
    } else {
        console.error(error.message)
        response.send(error.publicMessage || "Internal Error", 500)
    }
})

app.listen(process.env.PORT || 8080)
<commit_msg>2 -> 3 hours<commit_after>require('sugar')

var googlePlus = require('./google-plus'),
    express = require('express'),
    errors = require('./errors'),
    connect = require('connect')

var app = express()

app.configure(function() {
    app.use(express.static(__dirname + '/../public'))
    app.set('views', __dirname + '/../views')
    app.set('view engine', 'ejs')
    app.set('view options', {layout: false})
    app.use(connect.compress());
    app.use(function(request, response, next) {
        response.header('Cache-Control', 'max-age=0')
        next()
    })
})

app.get('/', function(request, response) {
    response.render('home')
})

app.get('/:id', function(request, response, next) {
    var userId = request.params.id
    if (! /^[0-9]+$/.test(userId)) return next()
    var plus = new googlePlus.GooglePlus(process.env.GOOGLE_API_KEY)
    var styles = {
        title: request.query.title || 'cut'
    }

    /**
     * @returns {number} In seconds
     */
    var getLapseSinceLastUpdate = function(posts) {
        return posts.length ? Math.round((new Date - posts[0].updated) / 1000) : Infinity
    }

    var getCacheMaxAge = function(posts) {
        var minAge = 10 /* mins */ * 60
        var maxAge = 3 /* hours */ * 60 * 60
        return Math.max(minAge, Math.min(maxAge, getLapseSinceLastUpdate(posts)))
    }

    plus.userPosts(userId, styles, function(error, posts) {
        if (error) return next(error)
        response.header('Content-Type', 'text/xml; charset=utf-8')
        response.header('Cache-Control', 'max-age=' + getCacheMaxAge(posts))
        response.render('feed', {
            profileUrl: 'https://plus.google.com/' + userId,
            posts: posts,
        })
    })
})

app.get('/feed.xsl', function(request, response) {
    response.render('feed-xsl')
})

app.get('/*', function(request, response, next) {
    next(new errors.NotFoundError)
})

app.use(function(error, request, response, next) {
    response.header('Content-Type', 'text/plain; charset=utf-8')
    if (error instanceof errors.UserError) {
        var code = error instanceof errors.NotFoundError ? 404 : 400
        response.send(error.message, code)
    } else {
        console.error(error.message)
        response.send(error.publicMessage || "Internal Error", 500)
    }
})

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


<commit_before>'use strict';

import angular from 'angular';
import uiRouter from '@uirouter/angularjs';

import angularMaterial from 'angular-material';
import 'angular-material/angular-material.css';

import ngMdIcons from 'angular-material-icons';

import MoviesService from './services/movies/movies';
import EventsService from './services/events/events';
import UserService from './services/user/user';

import Routes from './config/routes';
import Middlewares from './config/middlewares';

import AppContent from './components/app-content/app-content';
import ViewMovies from './components/view-movies/view-movies';
import ViewMovie from './components/view-movie/view-movie';
import ViewMovieEdit from './components/view-movie-edit/view-movie-edit';
import ViewMovieCreate from './components/view-movie-create/view-movie-create';
import ViewEvents from './components/view-events/view-events';
import ViewEvent from './components/view-event/view-event';
import ViewEventEdit from './components/view-event-edit/view-event-edit';
import ViewEventCreate from './components/view-event-create/view-event-create';
import ViewLogin from './components/view-login/view-login';
import ViewRegister from './components/view-register/view-register';

let app = angular.module('app', [
    uiRouter,
    angularMaterial,
    ngMdIcons,
    UserService.name,
    MoviesService.name,
    EventsService.name,
    AppContent.name,
    ViewMovies.name,
    ViewMovie.name,
    ViewMovieEdit.name,
    ViewMovieCreate.name,
    ViewEvents.name,
    ViewEvent.name,
    ViewEventEdit.name,
    ViewEventCreate.name,
    ViewRegister.name,
    ViewLogin.name
]);

app.constant('API_URL', 'http://5aee6f28.ngrok.io/api');
app.config(Routes);
app.config(Middlewares);

angular.element(document).ready(function() {
    return angular.bootstrap(document.body, [app.name], {
        strictDi: true
    });
});

export default app;<commit_msg>Added ViewProfile.name to the modules<commit_after>'use strict';

import angular from 'angular';
import uiRouter from '@uirouter/angularjs';

import angularMaterial from 'angular-material';
import 'angular-material/angular-material.css';

import ngMdIcons from 'angular-material-icons';

import MoviesService from './services/movies/movies';
import EventsService from './services/events/events';
import UserService from './services/user/user';

import Routes from './config/routes';
import Middlewares from './config/middlewares';

import AppContent from './components/app-content/app-content';
import ViewMovies from './components/view-movies/view-movies';
import ViewMovie from './components/view-movie/view-movie';
import ViewMovieEdit from './components/view-movie-edit/view-movie-edit';
import ViewMovieCreate from './components/view-movie-create/view-movie-create';
import ViewEvents from './components/view-events/view-events';
import ViewEvent from './components/view-event/view-event';
import ViewEventEdit from './components/view-event-edit/view-event-edit';
import ViewEventCreate from './components/view-event-create/view-event-create';
import ViewLogin from './components/view-login/view-login';
import ViewRegister from './components/view-register/view-register';
import ViewProfile from './components/view-profile/view-profile';

let app = angular.module('app', [
    uiRouter,
    angularMaterial,
    ngMdIcons,
    UserService.name,
    MoviesService.name,
    EventsService.name,
    AppContent.name,
    ViewMovies.name,
    ViewMovie.name,
    ViewMovieEdit.name,
    ViewMovieCreate.name,
    ViewEvents.name,
    ViewEvent.name,
    ViewEventEdit.name,
    ViewEventCreate.name,
    ViewRegister.name,
    ViewLogin.name,
    ViewProfile.name
]);

app.constant('API_URL', 'http://5aee6f28.ngrok.io/api');
app.config(Routes);
app.config(Middlewares);

angular.element(document).ready(function() {
    return angular.bootstrap(document.body, [app.name], {
        strictDi: true
    });
});

export default app;<|endoftext|>


<commit_before>(function(document, window){

    window['CropResize'] = CropResize;

    function CropResize(element, attributes){

        var _cropResize         = this,
            _eventQueues = {
                mousedown:new EventObject(window, onMouseMove),
                mouseup:new EventObject(window, onMouseUp),
                mousemove:new EventObject(window, onMouseMove),
                resize:new EventObject(window, onWindowResize),
                change:new EventObject(element, onFileInputChange)
            };

        this.remove = remove;
        this.images = {};

        for(var eventName in _eventQueues){
            (function(eventName, eventObj){
                eventObj.element.addEventListener(eventName, eventObj.fn);
            })(eventName, _eventQueues[eventName]);
        }

        function remove(){
            for(var eventName in _eventQueues){
                (function(eventName, eventObj){
                    eventObj.element.removeEventListener(eventName, eventObj.fn);
                    eventObj.events = [];
                })(eventName, _eventQueues[eventName]);
            }

        }

        function EventObject(target, fn){
            return {
                events:[],
                element:target,
                fn:fn
            }
        }

        function onMouseDown(e){
            onSubscription(e, 'mousedown');
        }

        function onMouseUp(e){
            onSubscription(e, 'mouseup');
        }

        function onMouseMove(e){
            onSubscription(e, 'mousemove');
        }

        function onWindowResize(e){
            onSubscription(e, 'resize');
        }

        function onSubscription(e, key){
            var events = _eventQueues[key];
            for(var i = 0; i < events.length; i++){
                events[i](e);
            }
        }

        function onFileInputChange(e, scope){

            var files       = this.files,
                parsedFiles = [];

            for(var file in files){
                parsedFiles.push(new FileHandler(files[file]));
            }
        }

        function FileHandler(file){

            var fileHandler = {};

            fileHandler.original    = {};
            fileHandler.cropped     = {};

            if(typeof file === 'object' && file.type.match('image.*')){
                var reader = new FileReader();

                reader.onload = onReaderLoad;

                reader.readAsDataURL(file);

                function onReaderLoad(e){
                    fileHandler.original['url'] = e.target.result;
                    fileHandler.original['size'] = bytesToSize(file.size);
                    bindCanvas.call(fileHandler);
                }
            }
        }

        function bindCanvas(){
            var self = this;

            self['canvas'] = {};
            self.canvas['element'] = document.createElement('canvas');
            self.canvas['context'] = self.canvas.element.getContext('2d');

            var parent  = element.parentElement,
                image   = new Image();

            image.onload    =   onCanvasImageLoad;
            image.src       =   self.original.url;

            function onCanvasImageLoad(){
                self.original['width']  =   this.width;
                self.original['height'] =   this.height;

                self.canvas['width']    =   self['canvas'].element.width;
                self.canvas['height']   =   self['canvas'].element.height;

                var canvasParams = measurements(self.original, self.canvas);

                if(attributes['target']){
                    attributes['target'].appendChild(self.canvas.element)
                }else{
                    parent.insertBefore(self.canvas.element, element);
                }

                self.canvas.context.clearRect(0, 0, self.canvas['width'], self.canvas['height']);
                self.canvas.context.drawImage(image,
                    canvasParams.sx,
                    canvasParams.sy,
                    canvasParams.sWidth,
                    canvasParams.sHeight,
                    canvasParams.dx,
                    canvasParams.dy,
                    canvasParams.dWidth,
                    canvasParams.dHeight
                );

                cropWindow((attributes['target'] || parent), self.canvas);

                function measurements(image, canvas){
                    var hRatio      =   canvas.width  / image.width,
                        vRatio      =   canvas.height  / image.height,
                        ratio       =   Math.min ( hRatio, vRatio);

                    return {
                        sx:         0,
                        sy:         0,
                        sWidth:     image.width,
                        sHeight:    image.height,
                        dx:         (canvas['width'] - image['width'] * ratio ) / 2,
                        dy:         (canvas['height'] - image['height'] * ratio ) / 2,
                        dWidth:     image.width * ratio,
                        dHeight:    image.height * ratio
                    }
                }

            }
        }

        function createImgInstance(croppedImageData,croppedImageElement, target){
            var buffer = document.createElement('canvas'),
                bufferCtx = buffer.getContext("2d");

            buffer.width    =   500;
            buffer.height   =   500;
            bufferCtx.putImageData(croppedImageData, 0, 0);

            croppedImageElement.src = buffer.toDataURL('image/png');

            if(target && !target.contains(croppedImageElement)){
                target.appendChild(croppedImageElement);
            }
            return croppedImageElement;
        }

        function cropWindow(target, canvas, croppedSrc){

            var croppedImage = document.createElement('img');

            var isHeld              = false,
                mouseStart          = {},
                cropWindowElement   = document.createElement('div'),
                childNames = [
                    'handle-top-left',
                    'handle-top-center',
                    'handle-top-right',
                    'handle-right-middle',
                    'handle-bottom-right',
                    'handle-bottom-center',
                    'handle-bottom-left',
                    'handle-left-middle',
                    'center-point'
                ];

            cropWindowElement.className = 'cr-crop-window';

            for(var i = 0; i < childNames.length; i++){
                (function(){
                    var cropHandle = document.createElement('div');
                    cropHandle.className = "cr-crop-handle cr-" + childNames[i];
                    cropWindowElement.appendChild(cropHandle);
                })();
            }

            target.appendChild(cropWindowElement);

            _eventQueues.mousemove.push(onCropMove);
            _eventQueues.mousedown.push(onCropMouseDown);
            _eventQueues.mouseup.push(onCropMouseUp);

            function onCropMove(e){
                if(isHeld){

                    //TODO:Add Boundaries
                    //TODO:Add functionality for handles clicked
                    //TODO:Keep previous translate
                    cropWindowElement.style.transform = "translate(" + ((e.x - mouseStart.x)) + "px, " + ((e.y - mouseStart.y)) + "px)";

                    var canvasBoundingRect = canvas.element.getBoundingClientRect(),
                        canvasWidth     =   canvas.element.clientWidth,
                        canvasHeight    =   canvas.element.clientHeight;

                    var heightPercent   =   cropWindowElement.clientHeight / canvasHeight,
                        widthPercent    =   cropWindowElement.clientWidth / canvasWidth,
                        leftPercent = (cropWindowElement.getBoundingClientRect().left - canvasBoundingRect.left) / canvasWidth,
                        topPercent = (cropWindowElement.getBoundingClientRect().top - canvasBoundingRect.top) / canvasHeight;

                    var newImgData = canvas.context.getImageData(
                            canvas.width * leftPercent,
                            canvas.height * topPercent,
                            canvas.width * widthPercent,
                            canvas.height * heightPercent);

                    createImgInstance(newImgData, croppedImage, _element.parentNode);
                }
            }

            function onCropMouseDown(e){
                if(e.target.className.match("-crop-")){
                    isHeld = true;
                    mouseStart['x'] = e.x;
                    mouseStart['y'] = e.y;
                }
            }

            function onCropMouseUp(e){
                isHeld = false;
            }

        }

        function bytesToSize(bytes) {
            var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            if (bytes == 0) return '0 Byte';
            var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
            return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
        }

    }

})(document, window);<commit_msg>Updated the cropped image height and with to be dynamic.<commit_after>(function(document, window){

    window['CropResize'] = CropResize;

    function CropResize(element, attributes){

        var _cropResize         = this,
            _eventQueues = {
                mousedown:new EventObject(window, onMouseMove),
                mouseup:new EventObject(window, onMouseUp),
                mousemove:new EventObject(window, onMouseMove),
                resize:new EventObject(window, onWindowResize),
                change:new EventObject(element, onFileInputChange)
            };

        this.remove = remove;
        this.images = {};

        for(var eventName in _eventQueues){
            (function(eventName, eventObj){
                eventObj.element.addEventListener(eventName, eventObj.fn);
            })(eventName, _eventQueues[eventName]);
        }

        function remove(){
            for(var eventName in _eventQueues){
                (function(eventName, eventObj){
                    eventObj.element.removeEventListener(eventName, eventObj.fn);
                    eventObj.events = [];
                })(eventName, _eventQueues[eventName]);
            }
        }

        function EventObject(target, fn){
            return {
                events:[],
                element:target,
                fn:fn
            }
        }

        function onMouseDown(e){
            onSubscription(e, 'mousedown');
        }

        function onMouseUp(e){
            onSubscription(e, 'mouseup');
        }

        function onMouseMove(e){
            onSubscription(e, 'mousemove');
        }

        function onWindowResize(e){
            onSubscription(e, 'resize');
        }

        function onSubscription(e, key){
            var events = _eventQueues[key];
            for(var i = 0; i < events.length; i++){
                events[i](e);
            }
        }

        function onFileInputChange(e, scope){
            var files       = this.files,
                parsedFiles = [];

            for(var file in files){
                parsedFiles.push(new FileHandler(files[file]));
            }
        }

        function FileHandler(file){

            var fileHandler = {};

            fileHandler.original    = {};
            fileHandler.cropped     = {};

            if(typeof file === 'object' && file.type.match('image.*')){
                var reader = new FileReader();

                reader.onload = onReaderLoad;

                reader.readAsDataURL(file);

                function onReaderLoad(e){
                    fileHandler.original['url'] = e.target.result;
                    fileHandler.original['size'] = bytesToSize(file.size);
                    bindCanvas.call(fileHandler);
                }
            }
        }

        function bindCanvas(){
            var self = this;

            self['canvas'] = {};
            self.canvas['element'] = document.createElement('canvas');
            self.canvas['context'] = self.canvas.element.getContext('2d');

            var parent  = element.parentElement,
                image   = new Image();

            image.onload    =   onCanvasImageLoad;
            image.src       =   self.original.url;

            function onCanvasImageLoad(){
                self.original['width']  =   this.width;
                self.original['height'] =   this.height;

                self.canvas['width']    =   self['canvas'].element.width;
                self.canvas['height']   =   self['canvas'].element.height;

                var canvasParams = measurements(self.original, self.canvas);

                if(attributes['target']){
                    attributes['target'].appendChild(self.canvas.element)
                }else{
                    parent.insertBefore(self.canvas.element, element);
                }

                self.canvas.context.clearRect(0, 0, self.canvas['width'], self.canvas['height']);
                self.canvas.context.drawImage(image,
                    canvasParams.sx,
                    canvasParams.sy,
                    canvasParams.sWidth,
                    canvasParams.sHeight,
                    canvasParams.dx,
                    canvasParams.dy,
                    canvasParams.dWidth,
                    canvasParams.dHeight
                );

                cropWindow((attributes['target'] || parent), self.canvas);

                function measurements(image, canvas){
                    var hRatio      =   canvas.width  / image.width,
                        vRatio      =   canvas.height  / image.height,
                        ratio       =   Math.min ( hRatio, vRatio);

                    return {
                        sx:         0,
                        sy:         0,
                        sWidth:     image.width,
                        sHeight:    image.height,
                        dx:         (canvas['width'] - image['width'] * ratio ) / 2,
                        dy:         (canvas['height'] - image['height'] * ratio ) / 2,
                        dWidth:     image.width * ratio,
                        dHeight:    image.height * ratio
                    }
                }

            }
        }

        function createImgInstance(croppedImageData, croppedImageElement, target, width, height){
            var buffer = document.createElement('canvas'),
                bufferCtx = buffer.getContext("2d");

            buffer.width    =   width;
            buffer.height   =   height;
            bufferCtx.putImageData(croppedImageData, 0, 0);

            croppedImageElement.src = buffer.toDataURL('image/png');

            if(target && !target.contains(croppedImageElement)){
                target.appendChild(croppedImageElement);
            }
            return croppedImageElement;
        }

        function cropWindow(target, canvas, croppedSrc){

            var croppedImage = document.createElement('img');

            var isHeld              = false,
                mouseStart          = {},
                cropWindowElement   = document.createElement('div'),
                childNames = [
                    'handle-top-left',
                    'handle-top-center',
                    'handle-top-right',
                    'handle-right-middle',
                    'handle-bottom-right',
                    'handle-bottom-center',
                    'handle-bottom-left',
                    'handle-left-middle',
                    'center-point'
                ];

            cropWindowElement.className = 'cr-crop-window';

            for(var i = 0; i < childNames.length; i++){
                (function(){
                    var cropHandle = document.createElement('div');
                    cropHandle.className = "cr-crop-handle cr-" + childNames[i];
                    cropWindowElement.appendChild(cropHandle);
                })();
            }

            target.appendChild(cropWindowElement);

            _eventQueues.mousemove.push(onCropMove);
            _eventQueues.mousedown.push(onCropMouseDown);
            _eventQueues.mouseup.push(onCropMouseUp);

            function onCropMove(e){
                if(isHeld){

                    //TODO:Add Boundaries
                    //TODO:Add functionality for handles clicked
                    //TODO:Keep previous translate
                    cropWindowElement.style.transform = "translate(" + ((e.x - mouseStart.x)) + "px, " + ((e.y - mouseStart.y)) + "px)";

                    var canvasBoundingRect = canvas.element.getBoundingClientRect(),
                        canvasWidth     =   canvas.element.clientWidth,
                        canvasHeight    =   canvas.element.clientHeight;

                    var heightPercent   =   cropWindowElement.clientHeight / canvasHeight,
                        widthPercent    =   cropWindowElement.clientWidth / canvasWidth,
                        leftPercent = (cropWindowElement.getBoundingClientRect().left - canvasBoundingRect.left) / canvasWidth,
                        topPercent = (cropWindowElement.getBoundingClientRect().top - canvasBoundingRect.top) / canvasHeight;

                    var newWidth = canvas.width * widthPercent,
                        newHeight = canvas.height * heightPercent;

                    var newImgData = canvas.context.getImageData(
                            canvas.width * leftPercent,
                            canvas.height * topPercent,
                            newWidth,
                            newHeight);

                    createImgInstance(newImgData, croppedImage, _element.parentNode, newWidth, newHeight);
                }
            }

            function onCropMouseDown(e){
                if(e.target.className.match("-crop-")){
                    isHeld = true;
                    mouseStart['x'] = e.x;
                    mouseStart['y'] = e.y;
                }
            }

            function onCropMouseUp(e){
                isHeld = false;
            }

        }

        function bytesToSize(bytes) {
            var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            if (bytes == 0) return '0 Byte';
            var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
            return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
        }

    }

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


<commit_before>import {run} from '@cycle/core'
import {makeDOMDriver} from '@cycle/dom'
import {makeHistoryDriver} from 'cyclic-history'
import {makeHTTPDriver} from '@cycle/http'
import {makeRouterDriver} from 'cyclic-router'
import {createHashHistory} from 'history'
import {makeStateDriver} from './state-driver'
import {makeHistoricalDataDriver} from './historical-data-driver'
import Main from './main'
import Pol from './polymer'

// This is the Cycle run. first argument is our mainApp then an object:
// DOM is the ID or class we want the cycle to render onto our page.
// History is using our makeHistoryDriver to deal with routing.
console.log("Initializing Cycle...")

const sources = {
  DOM: makeDOMDriver(`#application`),
  HTTP: makeHTTPDriver(),
  historicalData: makeHistoricalDataDriver(),
  router: makeRouterDriver(createHashHistory()),
  state$: makeStateDriver(),
}

run(Main, sources)
<commit_msg>Dummy commit<commit_after>import {run} from '@cycle/core'
import {makeDOMDriver} from '@cycle/dom'
import {makeHistoryDriver} from 'cyclic-history'
import {makeHTTPDriver} from '@cycle/http'
import {makeRouterDriver} from 'cyclic-router'
import {createHashHistory} from 'history'
import {makeStateDriver} from './state-driver'
import {makeHistoricalDataDriver} from './historical-data-driver'
import Main from './main'
import Pol from './polymer'

// This is the Cycle run. first argument is our mainApp then an object:
// DOM is the ID or class we want the cycle to render onto our page.
// History is using our makeHistoryDriver to deal with routing.

console.log("Initializing Cycle...")

const sources = {
  DOM: makeDOMDriver(`#application`),
  HTTP: makeHTTPDriver(),
  historicalData: makeHistoricalDataDriver(),
  router: makeRouterDriver(createHashHistory()),
  state$: makeStateDriver(),
}

run(Main, sources)
<|endoftext|>


<commit_before>var googleImages = require('google-images');
var exif = require('exif2');
var request = require('request');
var fs = require('fs');
var md5 = require('MD5');
var shredfile = require('shredfile')({});
var gui = require('nw.gui');
var exec = require('child_process').exec;
var csv = require('csv-to-json');

// TODO: Check for internet availability.

// Mouse positions; see readMouseMove().
var x;
var y;

function imageSearch(query) {
  var resultsCount = 0;
  var imagesDiv = document.getElementById('images');
  var endOfResults = document.getElementById('eor');
  var eorBreak = document.getElementById('eor-break');

  // The deprecated Google Images API only allows us to recieve a maximum
  // of 60 results.
  for (var i = 0; i < 57; i = i +4) {
    // NOTE: Eventually this should be refactored, but I'm not overly
    // concerned about it at this time.

    /* jshint loopfunc: true */
    googleImages.search(query, { page: i, callback: function(err, images) {
      var resultsDiv = document.getElementById('results');
      if (images[0]) {
      results.className = 'page-header';
      images.forEach(function(image) {
        // NOTE: This is a little hack I implemented to replace imgur
        // thumbnails with the full image.
        if (image.url.substring(0, 19) === 'http://i.imgur.com/') {
          image.url = image.url.replace('b.jpg', '.jpg');
        }

        resultsCount++;
        var file = fs.createWriteStream('./tmp/' + md5(image.url));
        var req = request({url: image.url, proxy: 'http://127.0.0.1:8118'});
        req.pipe(file);

        req.on('end', function() {
          exif ('./tmp/' + md5(image.url), function(err, obj) {
            var exifData = '';
            if (err === null) {
              for(var key in obj) {
                if (obj.hasOwnProperty(key) &&
                    key !== 'exiftool version number' &&
                    key !== 'file name' &&
                    key !== 'directory' &&
                    key !== 'file inode change date time' &&
                    key !== 'file modification date time' &&
                    key !== 'file access date time' &&
                    key !== 'file permissions') {
                    exifData += ucwords(key) + ': ' + obj[key] + '
';
                }
              }
            } else {
              exifData = err;
            }
            shredfile.shred('./tmp/' + md5(image.url), function(err, file) {

            });
            results.innerHTML = '
' + resultsCount + ' Results
';
            // Let's pretend I never wrote this...
            /* jshint maxlen: false */
            imagesDiv.innerHTML += '

';
            eorBreak.className = '';
            endOfResults.className = 'lead text-center text-muted';
          });
        });
      });
      } else {
        eorBreak.className = 'hidden';
        endOfResults.className = 'lead text-center text-muted hidden';
        results.className = 'page-header';
        results.innerHTML = '
No images found.
';
        return false;
      }
    }});
  }
}

/**
 * Uppercase Words
 * @param string str
 */
function ucwords(str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function($1) {
        return $1.toUpperCase();
    });
}

// Stolen! Credits go to this chap: http://stackoverflow.com/users/1219011/twist
// Original: http://stackoverflow.com/a/11840120
// Modified to remove non-webkit CSS rules.
function getRotationDegrees(obj) {
  var angle;
  var matrix = obj.css('-webkit-transform') ||
  obj.css('transform');
  if (matrix !== 'none') {
    var values = matrix.split('(')[1].split(')')[0].split(',');
    var a = values[0];
    var b = values[1];
    angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
  } else {
    angle = 0;
  }
  return (angle < 0) ? angle +=360 : angle;
}

function showExifData(data) {
  var exifData = document.getElementById('exif-data');
  exifData.innerHTML = window.atob(data);
  $('#exif-data-modal').modal('show');
}

function showContextMenu(url, from) {
  // TODO: Reduce the amount of statements. Yeah, this is a pile of fuck.
  /* jshint maxstatements:25 */
  var menu = new gui.Menu();
  var clipboard = gui.Clipboard.get();

  // FIXME: Cannot rotate image if flipped.

  var flipImageItem = new gui.MenuItem(
    { label: 'Toggle Flip Image',
      click: function() {
        var image = $('img[src="' + url + '"]');
        if (image.hasClass('flipped')) {
          image.removeClass('flipped');
        } else {
          image.addClass('flipped');
        }
      }
    });

  // TODO: Shred images.
  // TODO: Show confidence?
  var genderAgeItem = new gui.MenuItem(
    { label: 'Age/Gender (Experimental)',
      click: function() {
        var file = fs.createWriteStream('./tmp/br/' + md5(url) + '.image');
        var req = request({url: url, proxy: 'http://127.0.0.1:8118'});
        req.pipe(file);

        req.on('end', function() {
          exec('br -algorithm GenderEstimation -enroll ' + process.cwd() +
               '/tmp/br/' + md5(url) + '.image ' + process.cwd() +
               '/tmp/br/gender_' + md5(url) + '.csv', function(err, result) {
            if (err) {
              alert(err);
              return;
            }
            var genderResult = csv.parse('./tmp/br/gender_' + md5(url) +
                                         '.csv');

            var gender = genderResult[0].Gender;
            if (typeof(gender) === 'undefined') {
              gender = 'Unknown';
            }
            var genderSpan = document.getElementById('gender');
            genderSpan.innerHTML = gender;
          });

          exec('br -algorithm AgeEstimation -enroll ' + process.cwd() +
               '/tmp/br/' + md5(url) + '.image ' + process.cwd() +
               '/tmp/br/age_' + md5(url) + '.csv', function(err, result) {
            if (err) {
              alert(err);
              return;
            }
            var ageResult = csv.parse('./tmp/br/age_' + md5(url) + '.csv');

            var age = ageResult[0].Age;
            var ageSpan = document.getElementById('age');
            if (typeof(age) === 'undefined') {
              ageSpan.innerHTML = 'Unknown';
            } else {
              ageSpan.innerHTML = Math.round(age);
            }
          });
          $('#age-gender-modal').modal('show');
        });
      }
    });

  var previewPageItem = new gui.MenuItem(
    { label: 'Preview Page (No Proxy)',
      click: function() {
        // Let's pretend I never wrote this...
        /* jshint maxlen: false */
        var pwin = open('private.html');
        pwin.document.write('');
      }
    });

  var rotateRightItem = new gui.MenuItem(
    { label: 'Rotate Right',
      click: function() {
        var degrees = getRotationDegrees($('img[src="' + url + '"]'));
        $('img[src="' + url + '"]').rotate(degrees + 90);
      }
    });

  var rotateLeftItem = new gui.MenuItem(
    { label: 'Rotate Left',
      click: function() {
        var degrees = getRotationDegrees($('img[src="' + url + '"]'));
        $('img[src="' + url + '"]').rotate(degrees - 90);
      }
    });

  var copyImageUrlItem = new gui.MenuItem(
    { label: 'Copy Image URL',
      click: function() {
        clipboard.set(url, 'text');
      }
    });

  var copyPageUrlItem = new gui.MenuItem(
    { label: 'Copy Page URL',
      click: function() {
        clipboard.set(from, 'text');
      }
    });

  // It's my party and I'll cry if I want to.
  menu.append(previewPageItem);
  menu.append(new gui.MenuItem({ type: 'separator' }));
  menu.append(rotateLeftItem);
  menu.append(rotateRightItem);
  menu.append(flipImageItem);
  menu.append(genderAgeItem);
  menu.append(new gui.MenuItem({ type: 'separator' }));
  menu.append(copyImageUrlItem);
  menu.append(copyPageUrlItem);
  // TODO: Implement these functions.
  menu.append(new gui.MenuItem({ label: 'Save Image' }));
  menu.append(new gui.MenuItem({ label: 'Save Exif Data' }));
  menu.popup(x, y);
}

function readMouseMove(e) {
  x = e.clientX;
  y = e.clientY;
}

$(document).ready(function() {
  document.onmousemove = readMouseMove;

  document.onkeydown = function(e) {
    // Debug console (` key)
    if (e.keyCode === 192) {
      e.preventDefault();
      gui.Window.get().showDevTools();
      return false;
    }
  };

  // We need to reset the age and gender otherwise we're left with
  // stale data.
  $('#age-gender-modal').on('hidden.bs.modal', function () {
      $('#age').html('Waiting...');
      $('#gender').html('Waiting...');
  });

  $('a[href="#settings"]').click(function() {
    $('#settings-modal').modal('show');
    return false;
  });

  $('a[href="#top"]').click(function() {
    $('html, body').animate({ scrollTop: 0 }, 'slow');
    return false;
  });

  $('#eor').click(function() {
    $('html, body').animate({ scrollTop: 100 }, 'slow');
    return false;
  });

  $('#search-form').on('submit', function() {
    $('#images').html('');
    imageSearch($('#query').val());
    return false;
  });

});
<commit_msg>Remove FIXME comment "Cannot rotate image if flipped."<commit_after>var googleImages = require('google-images');
var exif = require('exif2');
var request = require('request');
var fs = require('fs');
var md5 = require('MD5');
var shredfile = require('shredfile')({});
var gui = require('nw.gui');
var exec = require('child_process').exec;
var csv = require('csv-to-json');

// TODO: Check for internet availability.

// Mouse positions; see readMouseMove().
var x;
var y;

function imageSearch(query) {
  var resultsCount = 0;
  var imagesDiv = document.getElementById('images');
  var endOfResults = document.getElementById('eor');
  var eorBreak = document.getElementById('eor-break');

  // The deprecated Google Images API only allows us to recieve a maximum
  // of 60 results.
  for (var i = 0; i < 57; i = i +4) {
    // NOTE: Eventually this should be refactored, but I'm not overly
    // concerned about it at this time.

    /* jshint loopfunc: true */
    googleImages.search(query, { page: i, callback: function(err, images) {
      var resultsDiv = document.getElementById('results');
      if (images[0]) {
      results.className = 'page-header';
      images.forEach(function(image) {
        // NOTE: This is a little hack I implemented to replace imgur
        // thumbnails with the full image.
        if (image.url.substring(0, 19) === 'http://i.imgur.com/') {
          image.url = image.url.replace('b.jpg', '.jpg');
        }

        resultsCount++;
        var file = fs.createWriteStream('./tmp/' + md5(image.url));
        var req = request({url: image.url, proxy: 'http://127.0.0.1:8118'});
        req.pipe(file);

        req.on('end', function() {
          exif ('./tmp/' + md5(image.url), function(err, obj) {
            var exifData = '';
            if (err === null) {
              for(var key in obj) {
                if (obj.hasOwnProperty(key) &&
                    key !== 'exiftool version number' &&
                    key !== 'file name' &&
                    key !== 'directory' &&
                    key !== 'file inode change date time' &&
                    key !== 'file modification date time' &&
                    key !== 'file access date time' &&
                    key !== 'file permissions') {
                    exifData += ucwords(key) + ': ' + obj[key] + '
';
                }
              }
            } else {
              exifData = err;
            }
            shredfile.shred('./tmp/' + md5(image.url), function(err, file) {

            });
            results.innerHTML = '
' + resultsCount + ' Results
';
            // Let's pretend I never wrote this...
            /* jshint maxlen: false */
            imagesDiv.innerHTML += '

';
            eorBreak.className = '';
            endOfResults.className = 'lead text-center text-muted';
          });
        });
      });
      } else {
        eorBreak.className = 'hidden';
        endOfResults.className = 'lead text-center text-muted hidden';
        results.className = 'page-header';
        results.innerHTML = '
No images found.
';
        return false;
      }
    }});
  }
}

/**
 * Uppercase Words
 * @param string str
 */
function ucwords(str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function($1) {
        return $1.toUpperCase();
    });
}

// Stolen! Credits go to this chap: http://stackoverflow.com/users/1219011/twist
// Original: http://stackoverflow.com/a/11840120
// Modified to remove non-webkit CSS rules.
function getRotationDegrees(obj) {
  var angle;
  var matrix = obj.css('-webkit-transform') ||
  obj.css('transform');
  if (matrix !== 'none') {
    var values = matrix.split('(')[1].split(')')[0].split(',');
    var a = values[0];
    var b = values[1];
    angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
  } else {
    angle = 0;
  }
  return (angle < 0) ? angle +=360 : angle;
}

function showExifData(data) {
  var exifData = document.getElementById('exif-data');
  exifData.innerHTML = window.atob(data);
  $('#exif-data-modal').modal('show');
}

function showContextMenu(url, from) {
  // TODO: Reduce the amount of statements. Yeah, this is a pile of fuck.
  /* jshint maxstatements:25 */
  var menu = new gui.Menu();
  var clipboard = gui.Clipboard.get();

  var flipImageItem = new gui.MenuItem(
    { label: 'Toggle Flip Image',
      click: function() {
        var image = $('img[src="' + url + '"]');
        if (image.hasClass('flipped')) {
          image.removeClass('flipped');
        } else {
          image.addClass('flipped');
        }
      }
    });

  // TODO: Shred images.
  // TODO: Show confidence?
  var genderAgeItem = new gui.MenuItem(
    { label: 'Age/Gender (Experimental)',
      click: function() {
        var file = fs.createWriteStream('./tmp/br/' + md5(url) + '.image');
        var req = request({url: url, proxy: 'http://127.0.0.1:8118'});
        req.pipe(file);

        req.on('end', function() {
          exec('br -algorithm GenderEstimation -enroll ' + process.cwd() +
               '/tmp/br/' + md5(url) + '.image ' + process.cwd() +
               '/tmp/br/gender_' + md5(url) + '.csv', function(err, result) {
            if (err) {
              alert(err);
              return;
            }
            var genderResult = csv.parse('./tmp/br/gender_' + md5(url) +
                                         '.csv');

            var gender = genderResult[0].Gender;
            if (typeof(gender) === 'undefined') {
              gender = 'Unknown';
            }
            var genderSpan = document.getElementById('gender');
            genderSpan.innerHTML = gender;
          });

          exec('br -algorithm AgeEstimation -enroll ' + process.cwd() +
               '/tmp/br/' + md5(url) + '.image ' + process.cwd() +
               '/tmp/br/age_' + md5(url) + '.csv', function(err, result) {
            if (err) {
              alert(err);
              return;
            }
            var ageResult = csv.parse('./tmp/br/age_' + md5(url) + '.csv');

            var age = ageResult[0].Age;
            var ageSpan = document.getElementById('age');
            if (typeof(age) === 'undefined') {
              ageSpan.innerHTML = 'Unknown';
            } else {
              ageSpan.innerHTML = Math.round(age);
            }
          });
          $('#age-gender-modal').modal('show');
        });
      }
    });

  var previewPageItem = new gui.MenuItem(
    { label: 'Preview Page (No Proxy)',
      click: function() {
        // Let's pretend I never wrote this...
        /* jshint maxlen: false */
        var pwin = open('private.html');
        pwin.document.write('');
      }
    });

  var rotateRightItem = new gui.MenuItem(
    { label: 'Rotate Right',
      click: function() {
        var degrees = getRotationDegrees($('img[src="' + url + '"]'));
        $('img[src="' + url + '"]').rotate(degrees + 90);
      }
    });

  var rotateLeftItem = new gui.MenuItem(
    { label: 'Rotate Left',
      click: function() {
        var degrees = getRotationDegrees($('img[src="' + url + '"]'));
        $('img[src="' + url + '"]').rotate(degrees - 90);
      }
    });

  var copyImageUrlItem = new gui.MenuItem(
    { label: 'Copy Image URL',
      click: function() {
        clipboard.set(url, 'text');
      }
    });

  var copyPageUrlItem = new gui.MenuItem(
    { label: 'Copy Page URL',
      click: function() {
        clipboard.set(from, 'text');
      }
    });

  // It's my party and I'll cry if I want to.
  menu.append(previewPageItem);
  menu.append(new gui.MenuItem({ type: 'separator' }));
  menu.append(rotateLeftItem);
  menu.append(rotateRightItem);
  menu.append(flipImageItem);
  menu.append(genderAgeItem);
  menu.append(new gui.MenuItem({ type: 'separator' }));
  menu.append(copyImageUrlItem);
  menu.append(copyPageUrlItem);
  // TODO: Implement these functions.
  menu.append(new gui.MenuItem({ label: 'Save Image' }));
  menu.append(new gui.MenuItem({ label: 'Save Exif Data' }));
  menu.popup(x, y);
}

function readMouseMove(e) {
  x = e.clientX;
  y = e.clientY;
}

$(document).ready(function() {
  document.onmousemove = readMouseMove;

  document.onkeydown = function(e) {
    // Debug console (` key)
    if (e.keyCode === 192) {
      e.preventDefault();
      gui.Window.get().showDevTools();
      return false;
    }
  };

  // We need to reset the age and gender otherwise we're left with
  // stale data.
  $('#age-gender-modal').on('hidden.bs.modal', function () {
      $('#age').html('Waiting...');
      $('#gender').html('Waiting...');
  });

  $('a[href="#settings"]').click(function() {
    $('#settings-modal').modal('show');
    return false;
  });

  $('a[href="#top"]').click(function() {
    $('html, body').animate({ scrollTop: 0 }, 'slow');
    return false;
  });

  $('#eor').click(function() {
    $('html, body').animate({ scrollTop: 100 }, 'slow');
    return false;
  });

  $('#search-form').on('submit', function() {
    $('#images').html('');
    imageSearch($('#query').val());
    return false;
  });

});
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser');
var lessMiddleware = require('less-middleware');
var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

var url = 'mongodb://localhost:27017/accumulator';
var db;
var index = require('./routes/index');

process.title = "ca-app";

var environment = process.env.NODE_ENV ? process.env.NODE_ENV : 'development';
environment = environment.trim();
console.log('NODE_ENV: ' + environment);

var app = express();

MongoClient.connect(url, function (err, mongoDb) {
  assert.equal(null, err);
  console.log("Connected correctly to server");

  db = mongoDb;
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
if (environment === 'development') {
  app.locals.pretty = true;
}

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(lessMiddleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);

var insertDocument = function (db, document, callback) {
  var collection = db.collection('documents');
  collection.insertOne(document, function (err, result) {
    callback(err, JSON.stringify(result.ops[0]));
  });
};

var findAllDocuments = function (db, callback) {
  var collection = db.collection('documents');
  collection.find({}).toArray(function (err, result) {
    callback(err, result);
  });
}

// Insert message
app.post('/api', function (req, res) {
  var data = req.body;
  insertDocument(db, data, function (err, result) {
    res.status(201).send(result)
  })
});

// Get messages
app.get('/api', function (req, res) {
  findAllDocuments(db, function (err, result) {
    res.send(result);
  });
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = environment === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
<commit_msg>database connection log message<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser');
var lessMiddleware = require('less-middleware');
var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

var url = 'mongodb://localhost:27017/accumulator';
var db;
var index = require('./routes/index');

process.title = "ca-app";

var environment = process.env.NODE_ENV ? process.env.NODE_ENV : 'development';
environment = environment.trim();
console.log('NODE_ENV: ' + environment);

var app = express();

MongoClient.connect(url, function (err, mongoDb) {
  assert.equal(null, err);
  console.log("Connected to database");

  db = mongoDb;
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
if (environment === 'development') {
  app.locals.pretty = true;
}

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(lessMiddleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);

var insertDocument = function (db, document, callback) {
  var collection = db.collection('documents');
  collection.insertOne(document, function (err, result) {
    callback(err, JSON.stringify(result.ops[0]));
  });
};

var findAllDocuments = function (db, callback) {
  var collection = db.collection('documents');
  collection.find({}).toArray(function (err, result) {
    callback(err, result);
  });
}

// Insert message
app.post('/api', function (req, res) {
  var data = req.body;
  insertDocument(db, data, function (err, result) {
    res.status(201).send(result)
  })
});

// Get messages
app.get('/api', function (req, res) {
  findAllDocuments(db, function (err, result) {
    res.send(result);
  });
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = environment === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
<|endoftext|>


<commit_before>var ui = require('ui');
var ajax = require('ajax');

// Check for local activity data
var activityData = localStorage.getItem('activity_data');

if(activityData)
{
	console.log('Old data');
	console.log(activityData);
}
else
{
	AjaxWait();
	setTimeout(function(){
		ajax({
			url: 'http://www.bungie.net/Platform/Destiny/Advisors/',
			type: 'json'
		}, function(data){
			activityData = data;
			localStorage.setItem('activity_data', data);
			console.log('Fresh data');
			console.log(data);
			ClearWait();
		}, function(error){
			console.log('Error! ' + error);
			ClearWait();
		});
	}, 2000);
}

var MainMenu = new ui.Menu({
	sections: [{
		title: 'Activities',
		items: [{
			title: 'Weekly Nightfall',
			subtitle: ['NF', 'E', 'AB', 'A', 'LS'].join('*')
	},{
			title: 'Weekly Heroic',
			subtitle: ['H', 'LS'].join('*')
		}]
	}]
});

MainMenu.show();

var waitCard = new UI.Card();
var waitInterval;
var waitTick = 1;

function AjaxWait()
{
	waitCard.title = 'Loading';

	waitInterval = setInterval(function() {
		var sub = '.';

		if(i == 10)
			i = 1;

		for(var i = 0; i < waitTick; i++)
			sub += '.';

		waitTick++;

		waitCard.subtitle = sub;
	}, 500);
}

function ClearWait()
{
	clearInterval(waitInterval);
}
<commit_msg>Waiting intensifies<commit_after>var ui = require('ui');
var ajax = require('ajax');

// Check for local activity data
var activityData = localStorage.getItem('activity_data');

if(activityData)
{
	console.log('Old data');
	console.log(activityData);
}
else
{
	AjaxWait();
	setTimeout(function(){
		ajax({
			url: 'http://www.bungie.net/Platform/Destiny/Advisors/',
			type: 'json'
		}, function(data){
			activityData = data;
			localStorage.setItem('activity_data', data);
			console.log('Fresh data');
			console.log(data);
			ClearWait();
		}, function(error){
			console.log('Error! ' + error);
			ClearWait();
		});
	}, 2000);
}

var MainMenu = new ui.Menu({
	sections: [{
		title: 'Activities',
		items: [{
			title: 'Weekly Nightfall',
			subtitle: ['NF', 'E', 'AB', 'A', 'LS'].join('*')
	},{
			title: 'Weekly Heroic',
			subtitle: ['H', 'LS'].join('*')
		}]
	}]
});

MainMenu.show();

var waitCard = new UI.Card();
var waitInterval;
var waitTick = 1;

function AjaxWait()
{
	waitCard.title('Loading');
	waitCard.subtitle('.');
	waitCard.show();

	waitInterval = setInterval(function() {
		var sub = '.';

		if(i == 10)
			i = 1;

		for(var i = 0; i < waitTick; i++)
			sub += '.';

		waitTick++;

		waitCard.subtitle(sub);
	}, 500);
}

function ClearWait()
{
	clearInterval(waitInterval);
}
<|endoftext|>


<commit_before>/**
 * Welcome to Pebble.js!
 * Test
 * This is where you write your app.
 */

// Calls in required stuff
var UI = require('ui');
var Vibe = require('ui/vibe');
var Vector2 = require('vector2');

// A for loop to make array of hours
var hours = [];
for (var i = 0; i < 24; i++) {
    hours.push(i + 1);
}

// Creates a loop to make an array of hours
/*
var createItems = function() {
  var items = [];
  for (var i = 0; i < hours.length; i++) {
    items.push({
      title: hours[i]
    });
  }
  return items;
};
*/

/*
var main = new UI.Menu({
   sections:[{
     items: createItems()
  }]
});

main.show();
*/

/*
 * var main = new UI.Card({
 *   title: 'Pebble.js',
 *     icon: 'images/menu_icon.png',
 *       subtitle: 'Hello World!',
 *         body: 'Press any button.'
 *         });
 */

// Makes a menu with New Alarms
var main = new UI.Menu({
    sections: [{
        items: [{
            title: 'Add New Alarm',
            subtitle: 'New Alarm'
        }, {
            // Dr. Seuss
            title: 'One Alarm'
        }, {
            title: 'Two Alarm'
        }, {
            title: 'Red Alarm'
        }, {
            title: 'Blue Alarm'
        }]
    }]
});

main.show();

main.on('click', 'select', function(e) {
    item = menu.items(0);
    if (item.title == "Add New Alarm") {
        var card = new UI.Card();
        card.title('A Card');
        card.subtitle('Is a Window');
        card.body('The simplest window type in Pebble.js.');
        card.show();
    }
});

/*
main.on('click', 'up', function(e) {
    var menu = new UI.Menu({
        sections: [{
            items: [{
                title: 'Pebble.js',
                icon: 'images/menu_icon.png',
                subtitle: 'Can do Menus'
            }, {
                title: 'Second Item',
                subtitle: 'Subtitle Text'
            }]
        }]
    });
    */
    menu.on('select', function(e) {
        console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
        console.log('The item is titled "' + e.item.title + '"');
    });
    menu.show();
});
*/

// When click middle button
/*
main.on('click', 'up', function(e) {
    //test vibrqtion and date fubction
    console.log("foo");
    if (new Date() == new Date()) {
        Vibe.vibrate('long');
    }
    var wind = new UI.Window();
    //var time = new UI.TimeText();
    // Time in Text form
    var textfield = new UI.TimeText({
        position: new Vector2(0, 50),
        size: new Vector2(144, 30),
        font: 'gothic-24-bold',
        text: '%M:%S, %a',
        textAlign: 'center'
    });
    wind.add(textfield);
    wind.show();
});
*/

/*
main.on('click', 'down', function(e) {
    var card = new UI.Card();
    card.title('A Card');
    card.subtitle('Is a Window');
    card.body('The simplest window type in Pebble.js.');
    card.show();
});
*/
<commit_msg>vibrate<commit_after>/**
 * Welcome to Pebble.js!
 * Test
 * This is where you write your app.
 */

// Calls in required stuff
var UI = require('ui');
var Vibe = require('ui/vibe');
var Vector2 = require('vector2');

// A for loop to make array of hours
var hours = [];
for (var i = 0; i < 24; i++) {
    hours.push(i + 1);
}

// Creates a loop to make an array of hours
/*
var createItems = function() {
  var items = [];
  for (var i = 0; i < hours.length; i++) {
    items.push({
      title: hours[i]
    });
  }
  return items;
};
*/

/*
var main = new UI.Menu({
   sections:[{
     items: createItems()
  }]
});

main.show();
*/

/*
 * var main = new UI.Card({
 *   title: 'Pebble.js',
 *     icon: 'images/menu_icon.png',
 *       subtitle: 'Hello World!',
 *         body: 'Press any button.'
 *         });
 */

// Makes a menu with New Alarms
var main = new UI.Menu({
    sections: [{
        items: [{
            title: 'Add New Alarm',
            subtitle: 'New Alarm'
        }, {
            // Dr. Seuss
            title: 'One Alarm'
        }, {
            title: 'Two Alarm'
        }, {
            title: 'Red Alarm'
        }, {
            title: 'Blue Alarm'
        }]
    }]
});

main.show();

main.on('click', 'select', function(e) {
    item = menu.items(0);
    if (item.title == "Add New Alarm") {
        Vibe.vibrate('long');
        var card = new UI.Card();
        card.title('A Card');
        card.subtitle('Is a Window');
        card.body('The simplest window type in Pebble.js.');
        card.show();
    }
});

/*
main.on('click', 'up', function(e) {
    var menu = new UI.Menu({
        sections: [{
            items: [{
                title: 'Pebble.js',
                icon: 'images/menu_icon.png',
                subtitle: 'Can do Menus'
            }, {
                title: 'Second Item',
                subtitle: 'Subtitle Text'
            }]
        }]
    });
    */
    menu.on('select', function(e) {
        console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
        console.log('The item is titled "' + e.item.title + '"');
    });
    menu.show();
});
*/

// When click middle button
/*
main.on('click', 'up', function(e) {
    //test vibrqtion and date fubction
    console.log("foo");
    if (new Date() == new Date()) {
        Vibe.vibrate('long');
    }
    var wind = new UI.Window();
    //var time = new UI.TimeText();
    // Time in Text form
    var textfield = new UI.TimeText({
        position: new Vector2(0, 50),
        size: new Vector2(144, 30),
        font: 'gothic-24-bold',
        text: '%M:%S, %a',
        textAlign: 'center'
    });
    wind.add(textfield);
    wind.show();
});
*/

/*
main.on('click', 'down', function(e) {
    var card = new UI.Card();
    card.title('A Card');
    card.subtitle('Is a Window');
    card.body('The simplest window type in Pebble.js.');
    card.show();
});
*/
<|endoftext|>