<commit_before>import Component from '@ember/component';
import {computed} from '@ember/object';
import {reads} from '@ember/object/computed';
import {inject as service} from '@ember/service';
import {set} from '@ember/object';

const US = {flag: '🇺🇸', name: 'US', baseUrl: 'https://api.mailgun.net/v3'};
const EU = {flag: '🇪🇺', name: 'EU', baseUrl: 'https://api.eu.mailgun.net/v3'};

const CURRENCIES = [
    {
        label: 'USD - US Dollar', value: 'usd'
    },
    {
        label: 'AUD - Australian Dollar', value: 'aud'
    },
    {
        label: 'CAD - Canadian Dollar', value: 'cad'
    },
    {
        label: 'EUR - Euro', value: 'eur'
    },
    {
        label: 'GBP - British Pound', value: 'gbp'
    }
];

export default Component.extend({
    feature: service(),
    config: service(),
    mediaQueries: service(),

    currencies: null,

    // passed in actions
    setMembersSubscriptionSettings() {},

    defaultContentVisibility: reads('settings.defaultContentVisibility'),

    selectedCurrency: computed('subscriptionSettings.stripeConfig.plans.monthly.currency', function () {
        return CURRENCIES.findBy('value', this.get('subscriptionSettings.stripeConfig.plans.monthly.currency'));
    }),

    mailgunRegion: computed('settings.bulkEmailSettings.baseUrl', function () {
        if (!this.settings.get('bulkEmailSettings.baseUrl')) {
            return US;
        }

        return [US, EU].find((region) => {
            return region.baseUrl === this.settings.get('bulkEmailSettings.baseUrl');
        });
    }),

    blogDomain: computed('config.blogDomain', function () {
        let domain = this.config.blogDomain || '';
        const host = domain.replace('https://', '').replace('http://', '').split('/');
        return (host && host[0]) || '';
    }),

    subscriptionSettings: computed('settings.membersSubscriptionSettings', function () {
        let subscriptionSettings = this.settings.parseSubscriptionSettings(this.get('settings.membersSubscriptionSettings'));
        let stripeProcessor = subscriptionSettings.paymentProcessors.find((proc) => {
            return (proc.adapter === 'stripe');
        });
        let monthlyPlan = stripeProcessor.config.plans.find(plan => plan.interval === 'month');
        let yearlyPlan = stripeProcessor.config.plans.find(plan => plan.interval === 'year');

        // NOTE: need to be careful about division by zero if we introduce zero decimal currencies
        //       ref.: https://stripe.com/docs/currencies#zero-decimal
        monthlyPlan.amount = parseInt(monthlyPlan.amount) ? (monthlyPlan.amount / 100) : 0;
        yearlyPlan.amount = parseInt(yearlyPlan.amount) ? (yearlyPlan.amount / 100) : 0;

        stripeProcessor.config.plans = {
            monthly: monthlyPlan,
            yearly: yearlyPlan
        };
        subscriptionSettings.stripeConfig = stripeProcessor.config;
        subscriptionSettings.allowSelfSignup = !!subscriptionSettings.allowSelfSignup;
        subscriptionSettings.fromAddress = subscriptionSettings.fromAddress || '';

        return subscriptionSettings;
    }),

    bulkEmailSettings: computed('settings.bulkEmailSettings', function () {
        let bulkEmailSettings = this.get('settings.bulkEmailSettings') || {};
        const {apiKey = '', baseUrl = US.baseUrl, domain = ''} = bulkEmailSettings;
        return {apiKey, baseUrl, domain};
    }),

    hasBulkEmailConfig: computed('settings.bulkEmailSettings', function () {
        let bulkEmailSettings = this.get('settings.bulkEmailSettings');
        return !!bulkEmailSettings.isConfig;
    }),

    init() {
        this._super(...arguments);
        this.set('mailgunRegions', [US, EU]);
        this.set('currencies', CURRENCIES);
    },

    actions: {
        setDefaultContentVisibility(value) {
            this.setDefaultContentVisibility(value);
        },

        setBulkEmailSettings(key, event) {
            let bulkEmailSettings = this.get('settings.bulkEmailSettings') || {};
            bulkEmailSettings[key] = event.target.value;
            if (!bulkEmailSettings.baseUrl) {
                set(bulkEmailSettings, 'baseUrl', US.baseUrl);
            }
            this.setBulkEmailSettings(bulkEmailSettings);
        },

        setBulkEmailRegion(region) {
            let bulkEmailSettings = this.get('settings.bulkEmailSettings') || {};
            set(bulkEmailSettings, 'baseUrl', region.baseUrl);
            this.setBulkEmailSettings(bulkEmailSettings);
        },

        setSubscriptionSettings(key, event) {
            let subscriptionSettings = this.settings.parseSubscriptionSettings(this.get('settings.membersSubscriptionSettings'));
            let stripeProcessor = subscriptionSettings.paymentProcessors.find((proc) => {
                return (proc.adapter === 'stripe');
            });
            let stripeConfig = stripeProcessor.config;
            stripeConfig.product = {
                name: this.settings.get('title')
            };
            // TODO: this flag has to be removed as it doesn't serve any purpose
            if (key === 'isPaid') {
                subscriptionSettings.isPaid = event;
            }
            if (key === 'secret_token' || key === 'public_token') {
                stripeConfig[key] = event.target.value;
            }
            if (key === 'month' || key === 'year') {
                stripeConfig.plans = stripeConfig.plans.map((plan) => {
                    if (key === plan.interval) {
                        plan.amount = parseInt(event.target.value) ? (event.target.value * 100) : 0;
                    }
                    return plan;
                });
            }
            if (key === 'allowSelfSignup') {
                subscriptionSettings.allowSelfSignup = !subscriptionSettings.allowSelfSignup;
            }
            if (key === 'fromAddress') {
                subscriptionSettings.fromAddress = event.target.value;
            }

            if (key === 'currency') {
                stripeProcessor.config.plans.forEach((plan) => {
                    if (plan.name !== 'Complimentary') {
                        plan.currency = event.value;
                    }
                });

                // NOTE: need to keep Complimentary plans with all available currencies so they don't conflict
                //       when applied to members with existing subscriptions in different currencies (ref. https://stripe.com/docs/billing/customer#currency)
                let currentCurrencyComplimentary = stripeProcessor.config.plans.filter(plan => (plan.currency === event.value && plan.name === 'Complimentary'));

                if (!currentCurrencyComplimentary.length) {
                    let complimentary = stripeProcessor.config.plans.find(plan => (plan.name === 'Complimentary'));
                    let newComplimentary = Object.assign({}, complimentary, {currency: event.value});
                    stripeProcessor.config.plans.push(newComplimentary);
                }

                stripeProcessor.config.currency = event.value;
            }

            this.setMembersSubscriptionSettings(subscriptionSettings);
        }
    }
});
<commit_msg>🐛 Fixed complimentary plan creation when there was none in plans collection<commit_after>import Component from '@ember/component';
import {computed} from '@ember/object';
import {reads} from '@ember/object/computed';
import {inject as service} from '@ember/service';
import {set} from '@ember/object';

const US = {flag: '🇺🇸', name: 'US', baseUrl: 'https://api.mailgun.net/v3'};
const EU = {flag: '🇪🇺', name: 'EU', baseUrl: 'https://api.eu.mailgun.net/v3'};

const CURRENCIES = [
    {
        label: 'USD - US Dollar', value: 'usd'
    },
    {
        label: 'AUD - Australian Dollar', value: 'aud'
    },
    {
        label: 'CAD - Canadian Dollar', value: 'cad'
    },
    {
        label: 'EUR - Euro', value: 'eur'
    },
    {
        label: 'GBP - British Pound', value: 'gbp'
    }
];

export default Component.extend({
    feature: service(),
    config: service(),
    mediaQueries: service(),

    currencies: null,

    // passed in actions
    setMembersSubscriptionSettings() {},

    defaultContentVisibility: reads('settings.defaultContentVisibility'),

    selectedCurrency: computed('subscriptionSettings.stripeConfig.plans.monthly.currency', function () {
        return CURRENCIES.findBy('value', this.get('subscriptionSettings.stripeConfig.plans.monthly.currency'));
    }),

    mailgunRegion: computed('settings.bulkEmailSettings.baseUrl', function () {
        if (!this.settings.get('bulkEmailSettings.baseUrl')) {
            return US;
        }

        return [US, EU].find((region) => {
            return region.baseUrl === this.settings.get('bulkEmailSettings.baseUrl');
        });
    }),

    blogDomain: computed('config.blogDomain', function () {
        let domain = this.config.blogDomain || '';
        const host = domain.replace('https://', '').replace('http://', '').split('/');
        return (host && host[0]) || '';
    }),

    subscriptionSettings: computed('settings.membersSubscriptionSettings', function () {
        let subscriptionSettings = this.settings.parseSubscriptionSettings(this.get('settings.membersSubscriptionSettings'));
        let stripeProcessor = subscriptionSettings.paymentProcessors.find((proc) => {
            return (proc.adapter === 'stripe');
        });
        let monthlyPlan = stripeProcessor.config.plans.find(plan => plan.interval === 'month');
        let yearlyPlan = stripeProcessor.config.plans.find(plan => plan.interval === 'year');

        // NOTE: need to be careful about division by zero if we introduce zero decimal currencies
        //       ref.: https://stripe.com/docs/currencies#zero-decimal
        monthlyPlan.amount = parseInt(monthlyPlan.amount) ? (monthlyPlan.amount / 100) : 0;
        yearlyPlan.amount = parseInt(yearlyPlan.amount) ? (yearlyPlan.amount / 100) : 0;

        stripeProcessor.config.plans = {
            monthly: monthlyPlan,
            yearly: yearlyPlan
        };
        subscriptionSettings.stripeConfig = stripeProcessor.config;
        subscriptionSettings.allowSelfSignup = !!subscriptionSettings.allowSelfSignup;
        subscriptionSettings.fromAddress = subscriptionSettings.fromAddress || '';

        return subscriptionSettings;
    }),

    bulkEmailSettings: computed('settings.bulkEmailSettings', function () {
        let bulkEmailSettings = this.get('settings.bulkEmailSettings') || {};
        const {apiKey = '', baseUrl = US.baseUrl, domain = ''} = bulkEmailSettings;
        return {apiKey, baseUrl, domain};
    }),

    hasBulkEmailConfig: computed('settings.bulkEmailSettings', function () {
        let bulkEmailSettings = this.get('settings.bulkEmailSettings');
        return !!bulkEmailSettings.isConfig;
    }),

    init() {
        this._super(...arguments);
        this.set('mailgunRegions', [US, EU]);
        this.set('currencies', CURRENCIES);
    },

    actions: {
        setDefaultContentVisibility(value) {
            this.setDefaultContentVisibility(value);
        },

        setBulkEmailSettings(key, event) {
            let bulkEmailSettings = this.get('settings.bulkEmailSettings') || {};
            bulkEmailSettings[key] = event.target.value;
            if (!bulkEmailSettings.baseUrl) {
                set(bulkEmailSettings, 'baseUrl', US.baseUrl);
            }
            this.setBulkEmailSettings(bulkEmailSettings);
        },

        setBulkEmailRegion(region) {
            let bulkEmailSettings = this.get('settings.bulkEmailSettings') || {};
            set(bulkEmailSettings, 'baseUrl', region.baseUrl);
            this.setBulkEmailSettings(bulkEmailSettings);
        },

        setSubscriptionSettings(key, event) {
            let subscriptionSettings = this.settings.parseSubscriptionSettings(this.get('settings.membersSubscriptionSettings'));
            let stripeProcessor = subscriptionSettings.paymentProcessors.find((proc) => {
                return (proc.adapter === 'stripe');
            });
            let stripeConfig = stripeProcessor.config;
            stripeConfig.product = {
                name: this.settings.get('title')
            };
            // TODO: this flag has to be removed as it doesn't serve any purpose
            if (key === 'isPaid') {
                subscriptionSettings.isPaid = event;
            }
            if (key === 'secret_token' || key === 'public_token') {
                stripeConfig[key] = event.target.value;
            }
            if (key === 'month' || key === 'year') {
                stripeConfig.plans = stripeConfig.plans.map((plan) => {
                    if (key === plan.interval) {
                        plan.amount = parseInt(event.target.value) ? (event.target.value * 100) : 0;
                    }
                    return plan;
                });
            }
            if (key === 'allowSelfSignup') {
                subscriptionSettings.allowSelfSignup = !subscriptionSettings.allowSelfSignup;
            }
            if (key === 'fromAddress') {
                subscriptionSettings.fromAddress = event.target.value;
            }

            if (key === 'currency') {
                stripeProcessor.config.plans.forEach((plan) => {
                    if (plan.name !== 'Complimentary') {
                        plan.currency = event.value;
                    }
                });

                // NOTE: need to keep Complimentary plans with all available currencies so they don't conflict
                //       when applied to members with existing subscriptions in different currencies (ref. https://stripe.com/docs/billing/customer#currency)
                let currentCurrencyComplimentary = stripeProcessor.config.plans.filter(plan => (plan.currency === event.value && plan.name === 'Complimentary'));

                if (!currentCurrencyComplimentary.length) {
                    let complimentary = {
                        name: 'Complimentary',
                        currency: event.value,
                        interval: 'year',
                        amount: '0'
                    };

                    stripeProcessor.config.plans.push(complimentary);
                }

                stripeProcessor.config.currency = event.value;
            }

            this.setMembersSubscriptionSettings(subscriptionSettings);
        }
    }
});
<|endoftext|>


<commit_before>var MathUtil = require('../util/math-util');
var Promise = require('promise');

function Scratch3SoundBlocks(runtime) {
    /**
     * The runtime instantiating this block package.
     * @type {Runtime}
     */
    this.runtime = runtime;
}

/**
 * Retrieve the block primitives implemented by this package.
 * @return {Object.<string, Function>} Mapping of opcode to Function.
 */
Scratch3SoundBlocks.prototype.getPrimitives = function() {
    return {
        'sound_play': this.playSound,
        'sound_playuntildone': this.playSoundAndWait,
        'sound_stopallsounds': this.stopAllSounds,
        'sound_playnoteforbeats': this.playNoteForBeats,
        'sound_playdrumforbeats': this.playDrumForBeats,
        'sound_seteffectto' : this.setEffect,
        'sound_changeeffectby' : this.changeEffect,
        'sound_cleareffects' : this.clearEffects,
        'sound_sounds_menu' : this.soundsMenu,
        'sound_beats_menu' : this.beatsMenu,
        'sound_effects_menu' : this.effectsMenu
    };
};

Scratch3SoundBlocks.prototype.playSound = function (args, util) {
    var index = this._getSoundIndex(args.SOUND_MENU, util);
    util.target.audioEngine.playSound(index);
};

Scratch3SoundBlocks.prototype.playSoundAndWait = function (args, util) {
    var index = this._getSoundIndex(args.SOUND_MENU, util);
    util.target.audioEngine.playSound(index);

    var duration = util.target.audioEngine.getSoundDuration(index);

    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve();
        }, 1000*duration);
    });
};

Scratch3SoundBlocks.prototype._getSoundIndex = function (soundName, util) {
    if (util.target.sprite.sounds.length == 0) {
        return 0;
    }
    var index;
    if (typeof soundName === 'number') {
        var len = util.target.sprite.sounds.length;
        index = MathUtil.wrapClamp(soundName,0,len-1);
    } else {
        index = util.target.getSoundIndexByName(soundName);
        if (index == -1) {
            index = 0;
        }
    }
    return index;
};

Scratch3SoundBlocks.prototype.stopAllSounds = function (args, util) {
    util.target.audioEngine.stopAllSounds();
};

Scratch3SoundBlocks.prototype.playNoteForBeats = function (args, util) {
    util.target.audioEngine.playNoteForBeats(args.NOTE, args.BEATS);
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve();
        }, (1000 * args.BEATS) );
    });
};

Scratch3SoundBlocks.prototype.playDrumForBeats = function (args, util) {
    util.target.audioEngine.playDrumForBeats(args.DRUMTYPE, args.BEATS);
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve();
        }, (1000 * args.BEATS) );
    });
};

Scratch3SoundBlocks.prototype.setEffect = function (args, util) {
    util.target.audioEngine.setEffect(args.EFFECT, args.VALUE);
};

Scratch3SoundBlocks.prototype.changeEffect = function (args, util) {
    util.target.audioEngine.changeEffect(args.EFFECT, args.VALUE);
};

Scratch3SoundBlocks.prototype.clearEffects = function (args, util) {
    util.target.audioEngine.clearEffects();
};

Scratch3SoundBlocks.prototype.soundsMenu = function (args) {
    return args.SOUND_MENU;
};

Scratch3SoundBlocks.prototype.beatsMenu = function (args) {
    return args.BEATS;
};

Scratch3SoundBlocks.prototype.effectsMenu = function (args) {
    return args.EFFECT;
};

module.exports = Scratch3SoundBlocks;
<commit_msg>adding theremin block and set instrument<commit_after>var MathUtil = require('../util/math-util');
var Cast = require('../util/cast');
var Promise = require('promise');

function Scratch3SoundBlocks(runtime) {
    /**
     * The runtime instantiating this block package.
     * @type {Runtime}
     */
    this.runtime = runtime;
}

/**
 * Retrieve the block primitives implemented by this package.
 * @return {Object.<string, Function>} Mapping of opcode to Function.
 */
Scratch3SoundBlocks.prototype.getPrimitives = function() {
    return {
        'sound_play': this.playSound,
        'sound_playuntildone': this.playSoundAndWait,
        'sound_stopallsounds': this.stopAllSounds,
        'sound_playnoteforbeats': this.playNoteForBeats,
        'sound_playthereminforbeats': this.playThereminForBeats,
        'sound_playdrumforbeats': this.playDrumForBeats,
        'sound_setinstrumentto': this.setInstrument,
        'sound_seteffectto' : this.setEffect,
        'sound_changeeffectby' : this.changeEffect,
        'sound_cleareffects' : this.clearEffects,
        'sound_sounds_menu' : this.soundsMenu,
        'sound_beats_menu' : this.beatsMenu,
        'sound_effects_menu' : this.effectsMenu
    };
};

Scratch3SoundBlocks.prototype.playSound = function (args, util) {
    var index = this._getSoundIndex(args.SOUND_MENU, util);
    util.target.audioEngine.playSound(index);
};

Scratch3SoundBlocks.prototype.playSoundAndWait = function (args, util) {
    var index = this._getSoundIndex(args.SOUND_MENU, util);
    util.target.audioEngine.playSound(index);

    var duration = util.target.audioEngine.getSoundDuration(index);

    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve();
        }, 1000*duration);
    });
};

Scratch3SoundBlocks.prototype._getSoundIndex = function (soundName, util) {
    if (util.target.sprite.sounds.length == 0) {
        return 0;
    }
    var index;
    if (typeof soundName === 'number') {
        var len = util.target.sprite.sounds.length;
        index = MathUtil.wrapClamp(soundName,0,len-1);
    } else {
        index = util.target.getSoundIndexByName(soundName);
        if (index == -1) {
            index = 0;
        }
    }
    return index;
};

Scratch3SoundBlocks.prototype.stopAllSounds = function (args, util) {
    util.target.audioEngine.stopAllSounds();
};

Scratch3SoundBlocks.prototype.playNoteForBeats = function (args, util) {
    util.target.audioEngine.playNoteForBeats(args.NOTE, args.BEATS);
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve();
        }, (1000 * args.BEATS) );
    });
};

Scratch3SoundBlocks.prototype.playThereminForBeats = function (args, util) {
    util.target.audioEngine.playThereminForBeats(args.NOTE, args.BEATS);
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve();
        }, (1000 * args.BEATS) );
    });
};

Scratch3SoundBlocks.prototype.playDrumForBeats = function (args, util) {
    util.target.audioEngine.playDrumForBeats(args.DRUMTYPE, args.BEATS);
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve();
        }, (1000 * args.BEATS) );
    });
};

Scratch3SoundBlocks.prototype.setInstrument = function (args, util) {
    var instNum = Cast.toNumber(args.INSTRUMENT);
    return util.target.audioEngine.setInstrument(instNum);
};

Scratch3SoundBlocks.prototype.setEffect = function (args, util) {
    util.target.audioEngine.setEffect(args.EFFECT, args.VALUE);
};

Scratch3SoundBlocks.prototype.changeEffect = function (args, util) {
    util.target.audioEngine.changeEffect(args.EFFECT, args.VALUE);
};

Scratch3SoundBlocks.prototype.clearEffects = function (args, util) {
    util.target.audioEngine.clearEffects();
};

Scratch3SoundBlocks.prototype.soundsMenu = function (args) {
    return args.SOUND_MENU;
};

Scratch3SoundBlocks.prototype.beatsMenu = function (args) {
    return args.BEATS;
};

Scratch3SoundBlocks.prototype.effectsMenu = function (args) {
    return args.EFFECT;
};

module.exports = Scratch3SoundBlocks;
<|endoftext|>


<commit_before>var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');

canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock;

var x = 50;
var y = 50;

document.addEventListener('pointerlockchange', lockChangeAlert, false);
document.addEventListener('mozpointerlockchange', lockChangeAlert, false);
document.addEventListener('webkitpointerlockchange', lockChangeAlert, false);

function lockChangeAlert() {
	if (document.pointerLockElement === canvas || document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas) {
		document.addEventListener("mousemove", canvasLoop, false);
	} else {
		document.removeEventListener("mousemove", canvasLoop, false);
	}
}

var tracker = document.createElement('p');
var body = document.querySelector('body');
body.appendChild(tracker);
tracker.style.position = 'absolute';
tracker.style.top = '0';
tracker.style.right = '10px';
tracker.style.backgroundColor = 'white';

function canvasLoop(e) {
	var movementX = e.movementX || e.mozMovementX || e.webkitMovementX || 0;
	var movementY = e.movementY || e.mozMovementY || e.webkitMovementY || 0;

	x += movementX;
	y += movementY;

	socket.emit('controller:mouseupdate', x, y);

	tracker.innerHTML = "X position: " + x + ', Y position: ' + y;

	window.requestAnimationFrame(canvasLoop);
}

////////////////////////////////////////////////////////////////////////////////

var socket = io();

socket.on('connect', function() {
	socket.emit('controller:initialize', roomID);
});

socket.on('client:ready', function() {
	// Show stuff

	// Pointerlock
	canvas.requestPointerLock();
});

canvas.addEventListener('keydown', function(event) {
	var key = String.fromCharCode((event || window.event).which);

	switch(key) {
		case 'E':
		case 'W':
		case 'Q':
		case 'A':
		case 'D':
		case 'S':
			socket.emit('keydown', key);
	}
});

canvas.addEventListener('keyup', function(event) {
	var key = String.fromCharCode((event || window.event).which);

	switch(key) {
		case 'E':
		case 'W':
		case 'Q':
		case 'A':
		case 'D':
		case 'S':
			socket.emit('keyup', key);
	}
});
<commit_msg>Remove crud from controller<commit_after>var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');

canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock;

var x = 50;
var y = 50;

document.addEventListener('pointerlockchange', lockChangeAlert, false);
document.addEventListener('mozpointerlockchange', lockChangeAlert, false);
document.addEventListener('webkitpointerlockchange', lockChangeAlert, false);

function lockChangeAlert() {
	if (document.pointerLockElement === canvas || document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas) {
		document.addEventListener("mousemove", canvasLoop, false);
	} else {
		document.removeEventListener("mousemove", canvasLoop, false);
	}
}

function canvasLoop(e) {
	var movementX = e.movementX || e.mozMovementX || e.webkitMovementX || 0;
	var movementY = e.movementY || e.mozMovementY || e.webkitMovementY || 0;

	x += movementX;
	y += movementY;

	socket.emit('controller:mouseupdate', x, y);

	window.requestAnimationFrame(canvasLoop);
}

////////////////////////////////////////////////////////////////////////////////

var socket = io();

socket.on('connect', function() {
	socket.emit('controller:initialize', roomID);
});

socket.on('client:ready', function() {
	// Show stuff

	// Pointerlock
	canvas.requestPointerLock();
});

canvas.addEventListener('keydown', function(event) {
	var key = String.fromCharCode((event || window.event).which);

	switch(key) {
		case 'E':
		case 'W':
		case 'Q':
		case 'A':
		case 'D':
		case 'S':
			socket.emit('keydown', key);
	}
});

canvas.addEventListener('keyup', function(event) {
	var key = String.fromCharCode((event || window.event).which);

	switch(key) {
		case 'E':
		case 'W':
		case 'Q':
		case 'A':
		case 'D':
		case 'S':
			socket.emit('keyup', key);
	}
});
<|endoftext|>


<commit_before>angular.module('taskcoin' , [
     'ui.router' ,'mgcrea.ngStrap' ,
     'config' , 'authyComponent' ,
     'general.factories' , 'checkoutModule',
     'betalistModule' , 'ngSanitize',
     'homeModule'
])

//
.directive('inputOptions' , function(){
     return {
         scope:{
             selected:'=selected'
         },

         link: function(scope , elem , attrs){
             scope.placeholder  = attrs.placeholder;
             scope.list = scope.$eval(attrs.list);
         },

         template:['',
                       '',
                             '<input type="text" placeholder="{{placeholder}}" ng-model="newItem" input-focused="focused">',
                             '',
                                   '',
                             '',
                             '<suggestions list="list" select="newItem" ng-show="focused"></suggestions>',
                       '',
                       '',
                            '{{option}}',
                            '',
                         '',
                   ''].join(''),

         controller: function($scope , $timeout){
             //
             $scope.$watch('list' , function(newVal){
                  if(newVal){
                      $scope.list = newVal;
                  }
             });

             //
             $scope.$watch('selected' , function(newVal){
                  console.log(newVal);
             });

             $scope.removeItem = function(item){
                  $scope.selected.splice($scope.selected.indexOf(item),1);
             }

             //
             $scope.addItem = function(item){
                  if(item && $scope.selected.indexOf(item) == -1 && $scope.list.indexOf(item) != -1){
                       $scope.selected.push(item);
                  }
                  else{
                      console.log('invalid option');
                  }
             }

             $timeout(function () {

             }, 1000);
         }
     }
})

//
.directive('inputFocused' , function($timeout){
     return{
         scope:{focused:'=inputFocused'},
         link:function(scope , elem , attrs){
             elem.bind('focus' , function(e){
                  console.log('focus');
                  scope.focused = true;
             }).bind('blur' , function(e){
                 console.log('Blur');
                 $timeout(function(){
                      scope.focused = false;
                 } , 300);
             });
         }
     }
})

//
.directive('suggestions'  , function(){
      return{
           scope: {
               list:'=list',
               select:'=select'
           },

           template:[
               '
',
                    '
',
                        '
{{item}}
',
                    '
',
               '
',
           ].join(''),
           controller:function($scope){
               //
               $scope.$watch('list' , function(newVal){
                    if(newVal){
                        $scope.list = newVal;
                    }
               });

               //
               $scope.selectItem = function(item){
                    console.log(item);
                    $scope.select
               }
           }
      }
})

//
.factory('profile' , function($q , $http , $timeout){
      var user;

      //
      function getUser(){
          var promise = $q.defer();
          if(user){
             console.log('here');
             promise.resolve(user);
          }
          else{
             $http({
                method:'GET',
                url:'/profile'
             })
             .success(function(data){
                 user = data;
                 promise.resolve(user);
             })
             .error(function(err){
                promise.reject(err);
             });
          }

          return promise.promise;
      }

      //
      function reset(){
          user = undefined;
      }

      //
      return{
          getUser:getUser,
          reset:reset
      };
})

//======================== Dashboard controller logged in state=============================
.controller('dashboardController' , function($scope , $state ,$timeout,  authy , myMedia , profile , betalistFactory){
       //Logic that requires user to be authenticated goes here
       authy.isAuth().then(
          function(stutus){
             profile.getUser().then(
                 function(user){
                     $scope.user = user;
                 },
                 function(err){
                      console.log(err);
                 }
             );
          },
          function(err){
              $state.go('home');
          }
       );

       //logic for logging out
      $scope.logout = function(){
          authy.logout().then(
              function(){
                  console.log('logged out');
                  profile.reset();
                  betalistFactory.reset();
                  $state.go('home');
              },
              function(err){
                  alert(err);
              }
          );
      }

       $scope.dropdown = [
           {text: ' Profile', href: '#', active: true},
           {divider: true},
           {text: ' API', href: '#', active: true},
           {divider: true},
           {text: ' Pricing', href: '#', active: true},
           {divider: true},
           {text: ' Help center', href: '#', active: true},
           {divider: true},
           {text: ' Logout', active: true , click:"logout()"},
      ];

       var currentState = '';
       $scope.isActiveClass = function(state){
           return currentState==state ? 'active' : '';
       }

       //Media query for small screen
       $scope.isSmall = function(){
           if(myMedia['gt-xs']){
               $scope.submenuVisible = true;
           }
           return myMedia.xs;
       }

       //
       $scope.submenuVisible = myMedia['gt-xs'];

       $scope.toggleSubmenu = function(){
            $scope.submenuVisible = !$scope.submenuVisible;
       }

       //Listen to state change events
       $scope.$on('$stateChangeSuccess' , function(e , toS){
             if(myMedia.xs){
                 $scope.submenuVisible = false;
             }
             currentState = $state.$current.url.source.split('/')[2];
       });

})

//
.factory('Surveys' , function($q , $http , $timeout){
     var surveys = [
        {
          _id:'236496586',
          title:'Taskcoin User Experience Survey',
          created:Date.now(),
          modified:Date.now(),
          responses:'568'
        },
        {
          _id:'236487886',
          title:'Taskcoin User Experience Survey',
          created:Date.now(),
          modified:Date.now(),
          responses:'568'
        },
        {
          _id:'2368797886',
          title:'Microsoft Windows 10 Survey',
          created:Date.now(),
          modified:Date.now(),
          responses:'568'
        },
        {
          _id:'236489786',
          title:'Music Taste survey',
          created:Date.now(),
          modified:Date.now(),
          responses:'568'
        },
     ];

     //
     function all(){
          var promise = $q.defer();

          //
          $timeout(function(){
              promise.resolve(surveys);
          } , 100);
          return promise.promise;
     }

     //
     return {
        all:all
     };
})

//Abstract state controller for surveys route
.controller('surveysController' , function($scope , $state){
       console.log('surveys abstract controller loaded');
       //Act as a God to all its child-views
})

//
.controller('surveysOverviewController' , function($scope , $state , myMedia , Surveys){
       //
       Surveys.all().then(
            function(data){
                $scope.surveys = data;
            },
            function(err){
                console.log(err);
            }
       );
})

//
.controller('surveysEditController' , function($scope , $state , $stateParams){
       //Setup default stage
       $scope.stage = 'setup';

       //
       $scope.changeStage = function(newStage){
           $scope.stage = newStage;
       }

       //
       $scope.getActiveStage = function(stage){
            return stage == $scope.stage?'active':'inactive';
       }

       //
       $scope.infoActive = false;
       $scope.info = '';

       //
       $scope.setAndDisplayInfo = function(info){
           if($scope.infoActive && $scope.info == info){
             $scope.infoActive = false;
             $scope.info = '';
           }
           else{
             $scope.infoActive = true;
             $scope.info = info;
           }
       }

       //
       $scope.getInfoClass = function(info){
           if($scope.infoActive){
              return $scope.info == info ?'active':'';
           }
           else{
             return '';
           }
       }

       //Setup partial view controls defined here============================//
       $scope.packages = [
            {
               title:'10',
               highlight:false
            },
            {
               title:'20',
               highlight:true
            },
            {
               title:'30',
               highlight:false
            },
       ];

       //
       $scope.activePackage  = '';
       $scope.setPackage = function(package){
           $scope.activePackage = package;
           console.log($scope.activePackage);
       }

       //
       $scope.activePackageClass = function(package){
            return $scope.activePackage == package ? 'active' : '';
       }

       $scope.interest = {
           suggessions:['merron' , 'jay'],
           selected:[]
       };

       $scope.country = {
           suggessions:['nigeria' , 'united states' , 'united kingdom' , 'ghana' , 'kenya' , 'merge' , 'hera' , 'jerr'  ,'puri' ,'juni'],
           selected:[]
       };

})

//
.controller('surveysPreviewController' , function($scope , $state, $stateParams){
       $scope.hello = 'surveys/preview '+$stateParams.id;
})

//
.controller('surveysStatsController' , function($scope , $state, $stateParams){
       $scope.hello = 'surveys/stats '+$stateParams.id;
})

//
.controller('merchantController' , function($scope){
       $scope.hello = 'merchant';
})

//
.controller('historyController' , function($scope){
       $scope.hello = 'history';
})

//
.controller('searchController' , function($scope){
       $scope.hello = 'search';
});
<commit_msg>Signed-off-by: codemuhammed <codemuhammed@gmail.com><commit_after>angular.module('taskcoin' , [
     'ui.router' ,'mgcrea.ngStrap' ,
     'config' , 'authyComponent' ,
     'general.factories' , 'checkoutModule',
     'betalistModule' , 'ngSanitize',
     'homeModule'
])

//
.directive('inputOptions' , function(){
     return {
         scope:{
             selected:'=selected'
         },

         link: function(scope , elem , attrs){
             scope.placeholder  = attrs.placeholder;
             scope.list = scope.$eval(attrs.list);
         },

         template:['',
                       '',
                             '<input type="text" placeholder="{{placeholder}}" ng-model="newItem" input-focused="focused">',
                             '',
                                   '',
                             '',
                             '<suggestions list="list" select="newItem" ng-show="focused"></suggestions>',
                       '',
                       '',
                            '{{option}}',
                            '',
                         '',
                   ''].join(''),

         controller: function($scope , $timeout){
             //
             $scope.$watch('list' , function(newVal){
                  if(newVal){
                      $scope.list = newVal;
                  }
             });

             //
             $scope.$watch('selected' , function(newVal){
                  console.log(newVal);
             });

             $scope.removeItem = function(item){
                  $scope.selected.splice($scope.selected.indexOf(item),1);
             }

             //
             $scope.addItem = function(item){
                  if(item && $scope.selected.indexOf(item) == -1 && $scope.list.indexOf(item) != -1){
                       $scope.selected.push(item);
                  }
                  else{
                      console.log('invalid option');
                  }
             }

             $timeout(function () {

             }, 1000);
         }
     }
})

//
.directive('inputFocused' , function($timeout){
     return{
         scope:{focused:'=inputFocused'},
         link:function(scope , elem , attrs){
             elem.bind('focus' , function(e){
                  console.log('focus');
                  scope.focused = true;
             }).bind('blur' , function(e){
                 console.log('Blur');
                 $timeout(function(){
                      scope.focused = false;
                 } , 300);
             });
         }
     }
})

//
.directive('suggestions'  , function(){
      return{
           scope: {
               list:'=list',
               select:'=select'
           },

           template:[
               '
',
                    '
',
                        '
{{item}}
',
                    '
',
               '
',
           ].join(''),
           controller:function($scope){
               //
               $scope.$watch('list' , function(newVal){
                    if(newVal){
                        $scope.list = newVal;
                    }
               });

               //
               $scope.selectItem = function(item){
                    console.log(item);
                    $scope.select  = item;
               }
           }
      }
})

//
.factory('profile' , function($q , $http , $timeout){
      var user;

      //
      function getUser(){
          var promise = $q.defer();
          if(user){
             console.log('here');
             promise.resolve(user);
          }
          else{
             $http({
                method:'GET',
                url:'/profile'
             })
             .success(function(data){
                 user = data;
                 promise.resolve(user);
             })
             .error(function(err){
                promise.reject(err);
             });
          }

          return promise.promise;
      }

      //
      function reset(){
          user = undefined;
      }

      //
      return{
          getUser:getUser,
          reset:reset
      };
})

//======================== Dashboard controller logged in state=============================
.controller('dashboardController' , function($scope , $state ,$timeout,  authy , myMedia , profile , betalistFactory){
       //Logic that requires user to be authenticated goes here
       authy.isAuth().then(
          function(stutus){
             profile.getUser().then(
                 function(user){
                     $scope.user = user;
                 },
                 function(err){
                      console.log(err);
                 }
             );
          },
          function(err){
              $state.go('home');
          }
       );

       //logic for logging out
      $scope.logout = function(){
          authy.logout().then(
              function(){
                  console.log('logged out');
                  profile.reset();
                  betalistFactory.reset();
                  $state.go('home');
              },
              function(err){
                  alert(err);
              }
          );
      }

       $scope.dropdown = [
           {text: ' Profile', href: '#', active: true},
           {divider: true},
           {text: ' API', href: '#', active: true},
           {divider: true},
           {text: ' Pricing', href: '#', active: true},
           {divider: true},
           {text: ' Help center', href: '#', active: true},
           {divider: true},
           {text: ' Logout', active: true , click:"logout()"},
      ];

       var currentState = '';
       $scope.isActiveClass = function(state){
           return currentState==state ? 'active' : '';
       }

       //Media query for small screen
       $scope.isSmall = function(){
           if(myMedia['gt-xs']){
               $scope.submenuVisible = true;
           }
           return myMedia.xs;
       }

       //
       $scope.submenuVisible = myMedia['gt-xs'];

       $scope.toggleSubmenu = function(){
            $scope.submenuVisible = !$scope.submenuVisible;
       }

       //Listen to state change events
       $scope.$on('$stateChangeSuccess' , function(e , toS){
             if(myMedia.xs){
                 $scope.submenuVisible = false;
             }
             currentState = $state.$current.url.source.split('/')[2];
       });

})

//
.factory('Surveys' , function($q , $http , $timeout){
     var surveys = [
        {
          _id:'236496586',
          title:'Taskcoin User Experience Survey',
          created:Date.now(),
          modified:Date.now(),
          responses:'568'
        },
        {
          _id:'236487886',
          title:'Taskcoin User Experience Survey',
          created:Date.now(),
          modified:Date.now(),
          responses:'568'
        },
        {
          _id:'2368797886',
          title:'Microsoft Windows 10 Survey',
          created:Date.now(),
          modified:Date.now(),
          responses:'568'
        },
        {
          _id:'236489786',
          title:'Music Taste survey',
          created:Date.now(),
          modified:Date.now(),
          responses:'568'
        },
     ];

     //
     function all(){
          var promise = $q.defer();

          //
          $timeout(function(){
              promise.resolve(surveys);
          } , 100);
          return promise.promise;
     }

     //
     return {
        all:all
     };
})

//Abstract state controller for surveys route
.controller('surveysController' , function($scope , $state){
       console.log('surveys abstract controller loaded');
       //Act as a God to all its child-views
})

//
.controller('surveysOverviewController' , function($scope , $state , myMedia , Surveys){
       //
       Surveys.all().then(
            function(data){
                $scope.surveys = data;
            },
            function(err){
                console.log(err);
            }
       );
})

//
.controller('surveysEditController' , function($scope , $state , $stateParams){
       //Setup default stage
       $scope.stage = 'setup';

       //
       $scope.changeStage = function(newStage){
           $scope.stage = newStage;
       }

       //
       $scope.getActiveStage = function(stage){
            return stage == $scope.stage?'active':'inactive';
       }

       //
       $scope.infoActive = false;
       $scope.info = '';

       //
       $scope.setAndDisplayInfo = function(info){
           if($scope.infoActive && $scope.info == info){
             $scope.infoActive = false;
             $scope.info = '';
           }
           else{
             $scope.infoActive = true;
             $scope.info = info;
           }
       }

       //
       $scope.getInfoClass = function(info){
           if($scope.infoActive){
              return $scope.info == info ?'active':'';
           }
           else{
             return '';
           }
       }

       //Setup partial view controls defined here============================//
       $scope.packages = [
            {
               title:'10',
               highlight:false
            },
            {
               title:'20',
               highlight:true
            },
            {
               title:'30',
               highlight:false
            },
       ];

       //
       $scope.activePackage  = '';
       $scope.setPackage = function(package){
           $scope.activePackage = package;
           console.log($scope.activePackage);
       }

       //
       $scope.activePackageClass = function(package){
            return $scope.activePackage == package ? 'active' : '';
       }

       $scope.interest = {
           suggessions:['merron' , 'jay'],
           selected:[]
       };

       $scope.country = {
           suggessions:['nigeria' , 'united states' , 'united kingdom' , 'ghana' , 'kenya' , 'merge' , 'hera' , 'jerr'  ,'puri' ,'juni'],
           selected:[]
       };

})

//
.controller('surveysPreviewController' , function($scope , $state, $stateParams){
       $scope.hello = 'surveys/preview '+$stateParams.id;
})

//
.controller('surveysStatsController' , function($scope , $state, $stateParams){
       $scope.hello = 'surveys/stats '+$stateParams.id;
})

//
.controller('merchantController' , function($scope){
       $scope.hello = 'merchant';
})

//
.controller('historyController' , function($scope){
       $scope.hello = 'history';
})

//
.controller('searchController' , function($scope){
       $scope.hello = 'search';
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Paper, RaisedButton, Popover, Menu, MenuItem } from 'material-ui';
import PlayIcon from 'material-ui/svg-icons/av/play-circle-filled';
import { teal300 as playColor } from 'material-ui/styles/colors';

const styles = {
  paper: {
    width: 167  ,
    height: 167,
    margin: 10,
    textAlign: 'center',
    display: 'inline-block',
    backgroundColor: 'white',
  },
  menu: {
    position: 'relative',
    top: 50,
  },
  text: {
    color: 'black',
  },
  icon: {
    play: {
      cursor: 'pointer',
      position: 'relative',
      top: 20,
      width: 60,
      height: 60,
    }
  }
};

export default class AlbumPaper extends Component {

  constructor(props) {
    super(props);
    this.state = {
      open: false,
    };
    this.handlerOnClick = this.handlerOnClick.bind(this);
    this.handleTouchTap = this.handleTouchTap.bind(this);
    this.handleRequestClose = this.handleRequestClose.bind(this);
  }

  handleTouchTap = (event) => {
    event.stopPropagation();
    // This prevents ghost click.
    event.preventDefault();

    this.setState({
      open: true,
      anchorEl: event.currentTarget,
    });
  };

  handleRequestClose = () => {
    this.setState({
      open: false,
    });
  };

  handlerOnClick() {
    const { record, urlManagerActions } = this.props;
    urlManagerActions.transitionTo(`/run-album/${record.id}`);
  }

  render() {
    const { record, handleToRun, handleToEdit, handleRemove } = this.props;
    return (
      <Paper style={styles.paper} zDepth={2} onClick={this.handlerOnClick}>

          {record.name}

        <PlayIcon style={styles.icon.play} color={playColor} />

          <RaisedButton
            onClick={this.handleTouchTap}
            label="Options"
            primary={true}
            fullWidth={true}
          />
          <Popover
            open={this.state.open}
            anchorEl={this.state.anchorEl}
            anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
            targetOrigin={{horizontal: 'left', vertical: 'top'}}
            onRequestClose={this.handleRequestClose}
          >
            <Menu>
              <MenuItem primaryText="Run" onClick={handleToRun} />
              <MenuItem primaryText="Edit" onClick={handleToEdit} />
              <MenuItem primaryText="Remove" onClick={handleRemove} />
            </Menu>
          </Popover>

      </Paper>
    );
  }
}
<commit_msg>Paper styling<commit_after>import React, { Component } from 'react';
import { Paper, RaisedButton, Popover, Menu, MenuItem } from 'material-ui';
import PlayIcon from 'material-ui/svg-icons/av/play-circle-filled';
import BaseComponent from 'lex/libs/base/component';

const styles = {
  paper: {
    width: 167  ,
    height: 167,
    margin: 10,
    textAlign: 'center',
    display: 'inline-block',
    backgroundColor: 'white',
  },
  menu: {
    position: 'relative',
    top: 50,
  },
  text: {
    color: 'black',
  },
  icon: {
    play: {
      cursor: 'pointer',
      position: 'relative',
      top: 20,
      width: 60,
      height: 60,
    }
  }
};

export default class AlbumPaper extends BaseComponent {

  constructor(props) {
    super(props);
    this.state = {
      open: false,
    };
    this.handlerOnClick = this.handlerOnClick.bind(this);
    this.handleTouchTap = this.handleTouchTap.bind(this);
    this.handleRequestClose = this.handleRequestClose.bind(this);
  }

  handleTouchTap = (event) => {
    event.stopPropagation();
    // This prevents ghost click.
    event.preventDefault();

    this.setState({
      open: true,
      anchorEl: event.currentTarget,
    });
  };

  handleRequestClose = () => {
    this.setState({
      open: false,
    });
  };

  handlerOnClick() {
    const { record, urlManagerActions } = this.props;
    urlManagerActions.transitionTo(`/run-album/${record.id}`);
  }

  render() {
    this.decorateStyle();
    const { record, handleToRun, handleToEdit, handleRemove } = this.props;
    return (
      <Paper style={styles.paper} zDepth={2} onClick={this.handlerOnClick}>

          {record.name}

        <PlayIcon style={styles.icon.play} color={this.styles.palette.primary3Color} />

          <RaisedButton
            onClick={this.handleTouchTap}
            label="Options"
            primary={true}
            fullWidth={true}
          />
          <Popover
            open={this.state.open}
            anchorEl={this.state.anchorEl}
            anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
            targetOrigin={{horizontal: 'left', vertical: 'top'}}
            onRequestClose={this.handleRequestClose}
          >
            <Menu>
              <MenuItem primaryText="Run" onClick={handleToRun} />
              <MenuItem primaryText="Edit" onClick={handleToEdit} />
              <MenuItem primaryText="Remove" onClick={handleRemove} />
            </Menu>
          </Popover>

      </Paper>
    );
  }
}
<|endoftext|>


<commit_before>// @flow
import { compose } from 'recompose'
import {
  withCall,
  withProgress,
  withData,
  withError,
  withActions,
  recentlyCompletedStrategy
} from 'spunky'

import LoginLedgerNanoS from './LoginLedgerNanoS'
import ledgerActions from '../../actions/ledgerActions'
import { ledgerLoginActions } from '../../actions/authActions'

const mapLedgerActionsToProps = actions => ({
  connect: () => ledgerActions.call()
})

const mapAccountActionsToProps = actions => ({
  login: publicKey => ledgerLoginActions.call({ publicKey })
})

const mapLedgerDataToProps = data => {
  const { deviceInfo, publicKey } = data || {}
  return { deviceInfo, publicKey }
}

const mapLedgerErrorToProps = error => ({ error })

export default compose(
  withCall(ledgerActions),
  withActions(ledgerActions, mapLedgerActionsToProps),
  withActions(ledgerLoginActions, mapAccountActionsToProps),
  withProgress(ledgerActions, {
    strategy: recentlyCompletedStrategy
  }),
  withData(ledgerActions, mapLedgerDataToProps),
  withError(ledgerActions, mapLedgerErrorToProps)
)(LoginLedgerNanoS)
<commit_msg>refactor: remove unused actions parameter from LoginLedgerNanoS<commit_after>// @flow
import { compose } from 'recompose'
import {
  withCall,
  withProgress,
  withData,
  withError,
  withActions,
  recentlyCompletedStrategy
} from 'spunky'

import LoginLedgerNanoS from './LoginLedgerNanoS'
import ledgerActions from '../../actions/ledgerActions'
import { ledgerLoginActions } from '../../actions/authActions'

const mapLedgerActionsToProps = () => ({
  connect: () => ledgerActions.call()
})

const mapAccountActionsToProps = () => ({
  login: publicKey => ledgerLoginActions.call({ publicKey })
})

const mapLedgerDataToProps = data => {
  const { deviceInfo, publicKey } = data || {}
  return { deviceInfo, publicKey }
}

const mapLedgerErrorToProps = error => ({ error })

export default compose(
  withCall(ledgerActions),
  withActions(ledgerActions, mapLedgerActionsToProps),
  withActions(ledgerLoginActions, mapAccountActionsToProps),
  withProgress(ledgerActions, {
    strategy: recentlyCompletedStrategy
  }),
  withData(ledgerActions, mapLedgerDataToProps),
  withError(ledgerActions, mapLedgerErrorToProps)
)(LoginLedgerNanoS)
<|endoftext|>


<commit_before>Meteor.startup(function meteorStartup() {
  if ( Meteor.settings.enableEmail && Meteor.settings && Meteor.settings.mandrill ) {
    console.log('======> Email enabled.')
    Meteor.Mandrill.config({
      username: Meteor.settings.mandrill.username,
      key: Meteor.settings.mandrill.key
    });
  }
});<commit_msg>Clean up conditions for sending email, add server logging<commit_after>Meteor.startup(function meteorStartup() {
  if ( Meteor.settings && Meteor.settings.enableEmail && Meteor.settings.mandrill ) {
    console.log('======> Email enabled.')
    Meteor.Mandrill.config({
      username: Meteor.settings.mandrill.username,
      key: Meteor.settings.mandrill.key
    });

    return;
  }

  console.log('======> Email disabled.');
});<|endoftext|>


<commit_before>define([
  'jquery',
  'underscore',
  'backbone',
  'texchat',
  'util/util',

  'views/chat',
  ], function($, _, Backbone, TeXchat, Util, ChatView) {

// View

var RoomView = Backbone.View.extend({

  el: '#room',

  events: {
    "click #send-btn":   'sendMessage',
    'keyup #send-text':  'onType',
  },

  initialize: function() {
    this.chatView = new ChatView({el: '#chat'});
    this.previewView = new ChatView({el: '#send-preview'});
    // this.userlistView = new UserlistView({model: this.model});
  },

  render: function() {

    // set name
    $(this.el).find('#name').text(this.model.get('name'));

    this.chatView.render();
    this.previewView.render();
    // this.userlistView.render();
  },

  sendMessage: function() {
    var msg = this.message();

    // append message to chat for now.
    if (msg.text) {
      this.chatView.appendMessage(msg);
      Util.scrollToBottom(this.chatView.el, {animate: true});
      TeXchat.view.resize();
    }

    // clear send box.
    this.elSendBox().val('');
    this.previewView.clear();
  },

  message: function() {
    return {
      name: TeXchat.username(),
      text: this.elSendBox().val().trim(),
      date: Util.dateToString(new Date()),
    };
  },

  onType: function(e) {
    if (!e.shiftKey && (e.keyCode || e.which) == 13) { // enter = send message
      this.sendMessage();
      this.previewView.clear();
      return false;
    }
    // preview text for anything typed in (enter ought to clear it).

    this.previewView.clear();
    var msg = this.message();
    if (msg.text) {
      this.previewView.appendMessage(msg);
    }
  },

  elSendBox: function() {
    return $(this.el).find('#send-text');
  },

});

return RoomView;
});<commit_msg>added test messages<commit_after>define([
  'jquery',
  'underscore',
  'backbone',
  'texchat',
  'util/util',

  'views/chat',
  ], function($, _, Backbone, TeXchat, Util, ChatView) {

// View

var RoomView = Backbone.View.extend({

  el: '#room',

  events: {
    "click #send-btn":   'sendMessage',
    'keyup #send-text':  'onType',
  },

  initialize: function() {
    this.chatView = new ChatView({el: '#chat'});
    this.previewView = new ChatView({el: '#send-preview'});
    // this.userlistView = new UserlistView({model: this.model});
  },

  render: function() {

    // set name
    $(this.el).find('#name').text(this.model.get('name'));

    this.chatView.render();
    this.previewView.render();
    // this.userlistView.render();

    for (var i = 0; i < 100; i++) {
      this.elSendBox().val('herp ' + i + ' + ' + i + ' = ' + (i+i));
      this.sendMessage();
    }
  },

  sendMessage: function() {
    var msg = this.message();

    // append message to chat for now.
    if (msg.text) {
      this.chatView.appendMessage(msg);
      Util.scrollToBottom(this.chatView.el, {animate: true});
      TeXchat.view.resize();
    }

    // clear send box.
    this.elSendBox().val('');
    this.previewView.clear();
  },

  message: function() {
    return {
      name: TeXchat.username(),
      text: this.elSendBox().val().trim(),
      date: Util.dateToString(new Date()),
    };
  },

  onType: function(e) {
    if (!e.shiftKey && (e.keyCode || e.which) == 13) { // enter = send message
      this.sendMessage();
      this.previewView.clear();
      return false;
    }
    // preview text for anything typed in (enter ought to clear it).

    this.previewView.clear();
    var msg = this.message();
    if (msg.text) {
      this.previewView.appendMessage(msg);
    }
  },

  elSendBox: function() {
    return $(this.el).find('#send-text');
  },

});

return RoomView;
});<|endoftext|>


<commit_before>/**
 * Checklist-model
 * AngularJS directive for list of checkboxes
 */

angular.module('checklist-model', [])
.directive('checklistModel', ['$parse', '$compile', function($parse, $compile) {
  // contains
  function contains(arr, item) {
    if (angular.isArray(arr)) {
      for (var i = 0; i < arr.length; i++) {
        if (angular.equals(arr[i], item)) {
          return true;
        }
      }
    }
    return false;
  }

  // add
  function add(arr, item) {
    arr = angular.isArray(arr) ? arr : [];
    for (var i = 0; i < arr.length; i++) {
      if (angular.equals(arr[i], item)) {
        return;
      }
    }
    arr.push(item);
  }

  // remove
  function remove(arr, item) {
    if (angular.isArray(arr)) {
      for (var i = 0; i < arr.length; i++) {
        if (angular.equals(arr[i], item)) {
          arr.splice(i, 1);
          return;
        }
      }
    }
  }

  return {
    restrict: 'A',
    scope: true,
    link: function(scope, elem, attrs) {
      if (elem[0].tagName !== 'INPUT' || !elem.attr('type', 'checkbox')) {
        throw 'checklist-model should be applied to `input[type="checkbox"]`.';
      }

      if (!attrs.checklistValue) {
        throw 'You should provide  `checklist-value`.';
      }

      // link to original model. Initially assigned in $watch
      var model;// = modelGet(scope);
      var value = $parse(attrs.checklistValue)(scope.$parent);

      // local var storing individual checkbox model
      // scope.checked - will be set in $watch

      // exclude recursion
      elem.removeAttr('checklist-model');
      elem.attr('ng-model', 'checked');
      $compile(elem)(scope);

      // watch UI checked change
      scope.$watch('checked', function(newValue, oldValue) {
        if (newValue === oldValue) {
          return;
        } if (newValue === true) {
          add(model, value);
        } else if (newValue === false) {
          remove(model, value);
        }
      });

      // watch model change
      scope.$parent.$watch(attrs.checklistModel, function(newArr, oldArr) {
        // need this line to keep link with original model
        model = newArr;
        scope.checked = contains(newArr, value);
      }, true);
    }
  };
}]);
<commit_msg>fix case when original model is undefined, closes #11<commit_after>/**
 * Checklist-model
 * AngularJS directive for list of checkboxes
 */

angular.module('checklist-model', [])
.directive('checklistModel', ['$parse', '$compile', function($parse, $compile) {
  // contains
  function contains(arr, item) {
    if (angular.isArray(arr)) {
      for (var i = 0; i < arr.length; i++) {
        if (angular.equals(arr[i], item)) {
          return true;
        }
      }
    }
    return false;
  }

  // add
  function add(arr, item) {
    arr = angular.isArray(arr) ? arr : [];
    for (var i = 0; i < arr.length; i++) {
      if (angular.equals(arr[i], item)) {
        return arr;
      }
    }
    arr.push(item);
    return arr;
  }

  // remove
  function remove(arr, item) {
    if (angular.isArray(arr)) {
      for (var i = 0; i < arr.length; i++) {
        if (angular.equals(arr[i], item)) {
          arr.splice(i, 1);
          return;
        }
      }
    }
  }

  return {
    restrict: 'A',
    scope: true,
    link: function(scope, elem, attrs) {
      if (elem[0].tagName !== 'INPUT' || !elem.attr('type', 'checkbox')) {
        throw 'checklist-model should be applied to `input[type="checkbox"]`.';
      }

      if (!attrs.checklistValue) {
        throw 'You should provide `checklist-value`.';
      }

      // link to original model. Initially assigned in $watch
      var model;
      // need setter for case when original model not array
      var setter = $parse(attrs.checklistModel).assign;
      // value added to list
      var value = $parse(attrs.checklistValue)(scope.$parent);

      // local var storing individual checkbox model
      // scope.checked - will be set in $watch

      // exclude recursion
      elem.removeAttr('checklist-model');
      // compile with `ng-model` pointing to `checked`
      elem.attr('ng-model', 'checked');
      $compile(elem)(scope);

      // watch UI checked change
      scope.$watch('checked', function(newValue, oldValue) {
        if (newValue === oldValue) {
          return;
        } if (newValue === true) {
          // see https://github.com/vitalets/checklist-model/issues/11
          if (!angular.isArray(model)) {
            setter(scope.$parent, add([], value));
            // `model` will be updated in $watch
          } else {
            add(model, value);
          }
        } else if (newValue === false) {
          remove(model, value);
        }
      });

      // watch model change
      scope.$parent.$watch(attrs.checklistModel, function(newArr, oldArr) {
        // keep link with original model
        model = newArr;
        scope.checked = contains(newArr, value);
      }, true);
    }
  };
}]);
<|endoftext|>


<commit_before>'use strict';

const path = require('path')
const app = require('koa')()
const router = require('koa-router')({ prefix: '/api' })
const serve = require('koa-static')
const bodyParser = require('koa-bodyparser')
const logger = require('koa-logger')
const helmet = require('koa-helmet')
const favicon = require('koa-favicon')
const send = require('koa-send')
const tracer = require('tracer').colorConsole()

app.use(function *(next) {
  yield send(this, path.resolve(__dirname, '/../public/', 'index.html'))
  yield next
})

app.use(function *(next) {
  try {
    yield next
  } catch (err) {
    this.status = err.status || 500
    this.body = { code: this.status, message: err.message || 'Internal server error' }

    if (400 < this.status && this.status < 500) {
      tracer.warn(err)
    } else {
      tracer.error(err)
    }
    this.app.emit('error', err, this)
  }
})

app.use(logger())
app.use(helmet())
app.use(bodyParser())
app.use(serve(__dirname + '/../public'))
app.use(favicon(__dirname + '/../public/favicon.ico'))
app.use(router.routes())
app.use(router.allowedMethods())

require('./src/routes/saveNetRoute.js')(router)

app.listen(process.env.PORT || 5000)
tracer.info('Solar Nets is running on port ', process.env.PORT || 5000)
<commit_msg>semicolon<commit_after>'use strict'

const path = require('path')
const app = require('koa')()
const router = require('koa-router')({ prefix: '/api' })
const serve = require('koa-static')
const bodyParser = require('koa-bodyparser')
const logger = require('koa-logger')
const helmet = require('koa-helmet')
const favicon = require('koa-favicon')
const send = require('koa-send')
const tracer = require('tracer').colorConsole()

app.use(function *(next) {
  yield send(this, path.resolve(__dirname, '/../public/', 'index.html'))
  yield next
})

app.use(function *(next) {
  try {
    yield next
  } catch (err) {
    this.status = err.status || 500
    this.body = { code: this.status, message: err.message || 'Internal server error' }

    if (400 < this.status && this.status < 500) {
      tracer.warn(err)
    } else {
      tracer.error(err)
    }
    this.app.emit('error', err, this)
  }
})

app.use(logger())
app.use(helmet())
app.use(bodyParser())
app.use(serve(__dirname + '/../public'))
app.use(favicon(__dirname + '/../public/favicon.ico'))
app.use(router.routes())
app.use(router.allowedMethods())

require('./src/routes/saveNetRoute.js')(router)

app.listen(process.env.PORT || 5000)
tracer.info('Solar Nets is running on port ', process.env.PORT || 5000)
<|endoftext|>


<commit_before>var express = require('express')
var bodyParser = require('body-parser');
var cors = require('cors');
var config = require("./src/config.js");
var firebase = require('firebase');

var payments = require("./src/braintree.js");
var stocks = require("./src/robinhood.js");
var database = require("./src/database.js");

var trading = require("./src/app.js");

var provider = new firebase.auth.GoogleAuthProvider();

var app = express();

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// passport oauth sign-in
/*
firebase.auth().signInWithPopup(provider).then(function(result) {
    var token = result.credential.accessToken;
    var user = result.user;
    // ...
}).catch(function(error) {
    var errorCode = error.code;
    var errorMessage = error.message;
    var email = error.email;
    var credential = error.credential;
});
*/

// gives the token to the client to individually authorize the payment
app.get("/client_token", function(req, res) {
    payments.token(res);
});

app.post("/checkout", function(req, res) {
    console.log("hey");
    console.log(req.body);

    //console.log(nonceFromTheClient);
    // Use payment method nonce here
    payments.transaction(req.body.payment_method_nonce, req.body.amount, function(page) {
        res.send(page);
    });
});

app.post("/buy", function(req, res) {
    console.log("Buying " + req.shareNum + " shares of " + req.symbol);

    trading.buy(req.symbol, req.shareNum, function(page) {
        res.send(page);
    });
});

app.post("/sell", function(req, res) {
    console.log("Selling " + req.shareNum + " shares of " + req.symbol);

    trading.sell(req.symbol, req.shareNum, function(page) {
        res.send(page);
    });
});

// get info about the stock
app.get("/stock_info", function(req, res) {
    //console.log(req.symbol);
    stocks.info(req.query.symbol, function(page) {
        res.send(page);
    });
});

app.get('/pending_transactions', function(req, res) {
    //database.init();
    database.pending(function(data) {
        res.send(data);
        res.end();
    })
})

app.listen(config.ports.listen, function() {
    console.log('Example app listening on port 3000!')
})<commit_msg>endpoint changes<commit_after>var express = require('express')
var bodyParser = require('body-parser');
var cors = require('cors');
var config = require("./src/config.js");
var firebase = require('firebase');

var payments = require("./src/braintree.js");
var stocks = require("./src/robinhood.js");
var database = require("./src/database.js");

var trading = require("./src/app.js");

var provider = new firebase.auth.GoogleAuthProvider();

var app = express();

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// passport oauth sign-in
/*
firebase.auth().signInWithPopup(provider).then(function(result) {
    var token = result.credential.accessToken;
    var user = result.user;
    // ...
}).catch(function(error) {
    var errorCode = error.code;
    var errorMessage = error.message;
    var email = error.email;
    var credential = error.credential;
});
*/

// gives the token to the client to individually authorize the payment
app.get("/client_token", function(req, res) {
    payments.token(res);
});

app.post("/checkout", function(req, res) {
    console.log("hey");
    console.log(req.body);

    //console.log(nonceFromTheClient);
    // Use payment method nonce here
    payments.transaction(req.body.payment_method_nonce, req.body.amount, function(page) {
        res.send(page);
    });
});

app.post("/buy", function(req, res) {
    console.log("Buying " + req.shareNum + " shares of " + req.symbol);

    trading.buy(req.symbol, req.shareNum, function(page) {
        res.send(page);
    });
});

app.post("/sell", function(req, res) {
    console.log("Selling " + req.shareNum + " shares of " + req.symbol);

    trading.sell(req.symbol, req.shareNum, function(page) {
        res.send(page);
    });
});

// get info about the stock
app.get("/stock_info", function(req, res) {
    //console.log(req.symbol);
    stocks.info(req.query.symbol, function(page) {
        res.send(page);
    });
});

app.get('/pending_transactions', function(req, res) {
    //database.init();
    database.pending(function(data) {
        res.send(data);
        res.end();
    })
})

app.listen(config.ports.listen, function() {
    console.log('Example app listening on port 3000!')
})
<|endoftext|>


<commit_before>// record check-ins
require('nko')('15Mr9rFk1qr71_mD');

var config = require('./config');
var express = require('express');
var fs = require('fs');
var _ = require('underscore')._;
var World = require('./models/world');
var io = require('socket.io');

// express setup
require('express-namespace');
var app = module.exports = express();
var server = app.listen(config.port);

// start socket.io
app.io = io.listen(server);
app.use(express.compress());
app.use(express.urlencoded());
app.use(express.json());
app.use(express.cookieParser());
app.use(express.cookieSession(config.session));
app.use(express.static('public'));

// add game state, app.world
app.world = new World();
app.world.start();

// controllers
var files = fs.readdirSync(__dirname + '/controllers');
var controllers = _.without(files);
_.each(controllers, function (controller) {
  if (controller[0] === '.') return;
  require('./controllers/' + controller)(app);
});

// system settings

// if run as root, downgrade to the owner of this file
if (process.getuid() === 0) {
  require('fs').stat(__filename, function (err, stats) {
    if (err) { return console.error(err); }
    process.setuid(stats.uid);
  });
}

// signal hooks
process.on('SIGTERM', function () {
  console.log('received SIGTERM');
  app.world.stop();
  server.close();
  setTimeout(process.exit.bind(process.exit), 100);
});
<commit_msg>SHHHHHH socket.io<commit_after>// record check-ins
require('nko')('15Mr9rFk1qr71_mD');

var config = require('./config');
var express = require('express');
var fs = require('fs');
var _ = require('underscore')._;
var World = require('./models/world');
var io = require('socket.io');

// express setup
require('express-namespace');
var app = module.exports = express();
var server = app.listen(config.port);

// start socket.io
app.io = io.listen(server);
app.io.set('log level', 0);
app.use(express.compress());
app.use(express.urlencoded());
app.use(express.json());
app.use(express.cookieParser());
app.use(express.cookieSession(config.session));
app.use(express.static('public'));

// add game state, app.world
app.world = new World();
app.world.start();

// controllers
var files = fs.readdirSync(__dirname + '/controllers');
var controllers = _.without(files);
_.each(controllers, function (controller) {
  if (controller[0] === '.') return;
  require('./controllers/' + controller)(app);
});

// system settings

// if run as root, downgrade to the owner of this file
if (process.getuid() === 0) {
  require('fs').stat(__filename, function (err, stats) {
    if (err) { return console.error(err); }
    process.setuid(stats.uid);
  });
}

// signal hooks
process.on('SIGTERM', function () {
  console.log('received SIGTERM');
  app.world.stop();
  server.close();
  setTimeout(process.exit.bind(process.exit), 100);
});
<|endoftext|>


<commit_before>const fs = require("fs");
require('./algorithm.js')();

let str = '';
const stream = fs.createReadStream('Startup.wav');
stream.on('readable', () => {
    let chunk;
    while (chunk = stream.read(1)) {
        str += String.fromCharCode(parseInt(chunk.toString('hex'), 16));
    }
    let comp = encode(str);
    let decomp = decode(comp);
    console.log('input: ' + str.length +'\tcompressed: '+ comp.length + '\tdecompressed: ' + decomp.length);
    fs.writeFileSync('output.wav', decomp, 'binary');
});

/*
stream.on('end', () => {
    comp = encode(str);
    let toSave = comp.map((e) => {
        return String.fromCharCode(e);
    }).join('');

    fs.writeFileSync('compressed.txt', toSave, 'utf8');
    let readed = fs.readFileSync('compressed.txt', 'utf8');

    let toDecode = readed.split('').map((e) => {
        return e.charCodeAt(e);
    });

    let decomp = decode(toDecode);
    fs.writeFileSync('decompressed.wav', decomp, 'binary');
});
*/
<commit_msg>better code<commit_after>const fs = require("fs");
require('./algorithm.js')();

let str = fs.readFileSync('Startup.wav', 'binary');
let comp = encode(str);
let compUTF8 = comp.map((e) => {
    return String.fromCharCode(e);
}).join('');

fs.writeFileSync('compressed.txt', compUTF8, 'binary');
let readed = fs.readFileSync('compressed.txt', 'binary');

let decomp = decode(comp);
let toSave = decomp.split('').map((e) => {
    return e.charCodeAt(e);
});

fs.writeFileSync('output.wav', decomp, 'binary')

console.log('original: \t' + Buffer.byteLength(str))
console.log('compressed: \t' + Buffer.byteLength(compUTF8))
console.log('output: \t' + Buffer.byteLength(decomp))
<|endoftext|>


<commit_before>'use strict';

const DIR_ROOT = __dirname + '/..';
const path = require('path');

const restafary = require('restafary/legacy');
const socketFile = require('socket-file');
const express = require('express');
const currify = require('currify/legacy');
const storage = require('fullstore/legacy');
const join = require('join-io');

const editFn = require('./edit');

const Router = express.Router;

const rootStorage = storage();
const optionsStorage = storage();

const optionsFn = currify(configFn);
const restafaryFn = currify(_restafaryFn);
const joinFn = currify(_joinFn);

const readjson = require('readjson');
const HOME = require('os-homedir')();

const isDev = process.env.NODE_ENV === 'development';

const readJSHINT = () => {
    const home = path.join(HOME, '.jshintrc');
    const root = path.join(DIR_ROOT,'.jshintrc')

    return readjson.sync.try(home) || readjson.sync(root);
}

const jshint = readJSHINT();

module.exports = (options) => {
    options = options || {};
    optionsStorage(options);

    const router = Router();
    const prefix = options.prefix || '/dword';

    router.route(prefix + '/*')
        .get(dword(options))
        .get(optionsFn(options))
        .get(editFn)
        .get(modulesFn)
        .get(jshintFn)
        .get(restafaryFn(''))
        .get(joinFn(options))
        .get(staticFn)
        .put(restafaryFn(prefix));

    return router;
};

module.exports.listen = (socket, options = {}) => {
    if (!options.prefix)
        options.prefix = '/dword';

    if (!options.root)
        options.root = '/';

    rootStorage(options.root);

    return socketFile(socket, options);
};

function checkOption(isOption) {
    if (typeof isOption === 'function')
        return isOption();

    if (typeof isOption === 'undefined')
        return true;

    return isOption;
}

function dword(options) {
    return serve.bind(null, options);
}

function serve(options, req, res, next) {
    const o = options || {};
    const prefix = o.prefix || '/dword';
    const url = req.url

    if (url.indexOf(prefix))
        return next();

    req.url = req.url.replace(prefix, '');

    if (/^\/dword\.js(\.map)?$/.test(req.url))
        req.url = `/dist${req.url}`;

    if (/^\/dist\/codemirror.js(\.map)?$/.test(req.url))
        return next();

    if (isDev)
        req.url = req.url.replace(/^\/dist\//, '/dist-dev/');

    next();
}

function configFn(o, req, res, next) {
    const online = checkOption(o.online);
    const diff = checkOption(o.diff);
    const zip = checkOption(o.zip);

    if (req.url.indexOf('/options.json'))
        return next();

    res .type('json')
        .send({
            diff,
            zip,
            online,
        });
}

function jshintFn(req, res, next) {
    if (req.url.indexOf('/jshint.json'))
        return next();

    res .type('json')
        .send(jshint);
}

function modulesFn(req, res, next) {
    if (req.url.indexOf('/modules.json'))
        return next();

    req.url = '/json/' + req.url;

    next();
}

function _joinFn(o, req, res, next) {
    if (req.url.indexOf('/join'))
        return next ();

    const joinFunc = join({
        minify: false,
        dir: DIR_ROOT
    });

    joinFunc(req, res, next);
}

function _restafaryFn(prefix, req, res, next) {
    const {url} = req;
    const api = '/api/v1/fs';
    const indexOf = url.indexOf.bind(url);
    const not = (fn) => (a) => !fn(a);
    const isRestafary = [
        `${prefix}/api/v1/fs`,
        '/restafary.js'
    ].some(not(indexOf));

    if (!isRestafary)
        return next();

    req.url = url.replace(prefix, '');

    const restafaryFunc = restafary({
        prefix: api,
        root: rootStorage()
    });

    restafaryFunc(req, res, next);
}

function staticFn(req, res) {
    const file = path.normalize(DIR_ROOT + req.url);
    res.sendFile(file);
}

<commit_msg>fix(index) node v4 support<commit_after>'use strict';

const DIR_ROOT = __dirname + '/..';
const path = require('path');

const restafary = require('restafary/legacy');
const socketFile = require('socket-file');
const express = require('express');
const currify = require('currify/legacy');
const storage = require('fullstore/legacy');
const join = require('join-io');

const editFn = require('./edit');

const Router = express.Router;

const rootStorage = storage();
const optionsStorage = storage();

const optionsFn = currify(configFn);
const restafaryFn = currify(_restafaryFn);
const joinFn = currify(_joinFn);

const readjson = require('readjson');
const HOME = require('os-homedir')();

const isDev = process.env.NODE_ENV === 'development';

const readJSHINT = () => {
    const home = path.join(HOME, '.jshintrc');
    const root = path.join(DIR_ROOT,'.jshintrc')

    return readjson.sync.try(home) || readjson.sync(root);
}

const jshint = readJSHINT();

module.exports = (options) => {
    options = options || {};
    optionsStorage(options);

    const router = Router();
    const prefix = options.prefix || '/dword';

    router.route(prefix + '/*')
        .get(dword(options))
        .get(optionsFn(options))
        .get(editFn)
        .get(modulesFn)
        .get(jshintFn)
        .get(restafaryFn(''))
        .get(joinFn(options))
        .get(staticFn)
        .put(restafaryFn(prefix));

    return router;
};

module.exports.listen = (socket, options) => {
    options = options || {};

    if (!options.prefix)
        options.prefix = '/dword';

    if (!options.root)
        options.root = '/';

    rootStorage(options.root);

    return socketFile(socket, options);
};

function checkOption(isOption) {
    if (typeof isOption === 'function')
        return isOption();

    if (typeof isOption === 'undefined')
        return true;

    return isOption;
}

function dword(options) {
    return serve.bind(null, options);
}

function serve(options, req, res, next) {
    const o = options || {};
    const prefix = o.prefix || '/dword';
    const url = req.url

    if (url.indexOf(prefix))
        return next();

    req.url = req.url.replace(prefix, '');

    if (/^\/dword\.js(\.map)?$/.test(req.url))
        req.url = `/dist${req.url}`;

    if (/^\/dist\/codemirror.js(\.map)?$/.test(req.url))
        return next();

    if (isDev)
        req.url = req.url.replace(/^\/dist\//, '/dist-dev/');

    next();
}

function configFn(o, req, res, next) {
    const online = checkOption(o.online);
    const diff = checkOption(o.diff);
    const zip = checkOption(o.zip);

    if (req.url.indexOf('/options.json'))
        return next();

    res .type('json')
        .send({
            diff,
            zip,
            online,
        });
}

function jshintFn(req, res, next) {
    if (req.url.indexOf('/jshint.json'))
        return next();

    res .type('json')
        .send(jshint);
}

function modulesFn(req, res, next) {
    if (req.url.indexOf('/modules.json'))
        return next();

    req.url = '/json/' + req.url;

    next();
}

function _joinFn(o, req, res, next) {
    if (req.url.indexOf('/join'))
        return next ();

    const joinFunc = join({
        minify: false,
        dir: DIR_ROOT
    });

    joinFunc(req, res, next);
}

function _restafaryFn(prefix, req, res, next) {
    const {url} = req;
    const api = '/api/v1/fs';
    const indexOf = url.indexOf.bind(url);
    const not = (fn) => (a) => !fn(a);
    const isRestafary = [
        `${prefix}/api/v1/fs`,
        '/restafary.js'
    ].some(not(indexOf));

    if (!isRestafary)
        return next();

    req.url = url.replace(prefix, '');

    const restafaryFunc = restafary({
        prefix: api,
        root: rootStorage()
    });

    restafaryFunc(req, res, next);
}

function staticFn(req, res) {
    const file = path.normalize(DIR_ROOT + req.url);
    res.sendFile(file);
}

<|endoftext|>


<commit_before>function Queue()
{
	var q = this;

	q.jobs = [];
	q.interval = false;
	q.flushing = false;
	q.disabled = false;

	q.push = function(job)
	{
		$('#save-info').text('Saving...');
		enableExitConfirmation('Changes were not saved!');
		q.jobs.push(job);
	}

	q.flush = function(callback)
	{
		if (q.disabled)
		{
			return;
		}

		if (q.flushing)
		{
			window.setTimeout(q.flush, 500);
			return;
		}

		q.flushing = true;

		var url = '/exec';
		var data = {jobs: q.jobs};
		$.post(url, data, function(rawContent)
		{
			var content = $(rawContent);

			//check for any errors, if errors were found - disable all editing
			if (content.find('.error').length > 0)
			{
				alert("An error occured:\n\n" +
					content.find('.error').text() +
					"\n\nPlease reload the page and redo the changes.");
				q.disabled = true;
			}

			if (typeof(callback) !== 'undefined')
				callback();

			disableExitConfirmation();
			$('#save-info').text('Saved');

			q.flushing = false;
			q.jobs = [];
		});
	}

	q.delayedFlush = function()
	{
		if (q.interval)
			window.clearTimeout(q.interval);

		q.interval = window.setTimeout(q.flush, 1000);
	}
}

function Job(name, args)
{
	this.name = name;
	this.args = args;
}
<commit_msg>Queue - changed "saving..." behavior<commit_after>function Queue()
{
	var q = this;

	q.jobs = [];
	q.interval = false;
	q.flushing = false;
	q.disabled = false;

	q.push = function(job)
	{
		enableExitConfirmation('Changes were not saved!');
		q.jobs.push(job);
	}

	q.flush = function(callback)
	{
		if (q.disabled)
		{
			return;
		}

		if (q.flushing)
		{
			window.setTimeout(q.flush, 500);
			return;
		}

		q.flushing = true;

		var url = '/exec';
		var data = {jobs: q.jobs};
		$.post(url, data, function(rawContent)
		{
			var content = $(rawContent);

			//check for any errors, if errors were found - disable all editing
			if (content.find('.error').length > 0)
			{
				alert("An error occured:\n\n" +
					content.find('.error').text() +
					"\n\nPlease reload the page and redo the changes.");
				q.disabled = true;
			}

			if (typeof(callback) !== 'undefined')
				callback();

			disableExitConfirmation();
			$('#save-info').text('Saved');

			q.flushing = false;
			q.jobs = [];
		});
	}

	q.delayedFlush = function()
	{
		$('#save-info').text('Saving...');

		if (q.interval)
			window.clearTimeout(q.interval);

		q.interval = window.setTimeout(q.flush, 1000);
	}
}

function Job(name, args)
{
	this.name = name;
	this.args = args;
}
<|endoftext|>


<commit_before>#!/usr/bin/env node -r babel/register

/**
 * Server loader
 * @flow
 */
import koa from 'koa'
import qs from 'koa-qs'
import debug from 'debug'
import responseTime from 'koa-response-time'

/**
 * Application imports
 */
import * as config from './config'
import modelLoader from './models'
import controllerLoader from './controllers'

/**
 * Initialize models and server
 */
export const models = modelLoader(config.database)
export const server = Object.assign(qs(koa()), {
  name: config.name,
  keys: config.keys,
  env: config.env,
  models: models
})

// Add ctx.models
server.context.models = models

/**
 * Middleware
 */
if (server.env === 'development') {
  const logger = require('koa-logger')
  server.use(logger())
}
server.use(responseTime())
server.use(controllerLoader())

/**
 * Server initializer
 * @param port to listen on
 * @returns server instance
 */
const log = debug('app:server')
export function init (port = config.port) {
  log(`initializing server using port ${port}`)
  server.instance = server.listen(port, () => log(`listening on port ${port}`))
  return server.instance
}

// Initialize server if called directly
if (require.main === module) {
  server.init()
}
<commit_msg>Fix server entry point<commit_after>#!/usr/bin/env node -r babel/register

/**
 * Server loader
 * @flow
 */
import koa from 'koa'
import qs from 'koa-qs'
import path from 'path'
import debug from 'debug'
import fileServer from 'koa-static'
import responseTime from 'koa-response-time'

// import csrf from 'koa-csrf'
import session from 'koa-session'
import * as middleware from './lib/middleware'

// Application imports
import s3Loader from './lib/s3'
import * as config from './config'
import modelLoader from './models'
import loadSchema from './db/schema'
import controllerLoader from './controllers'

// Initialize s3, models, and server
export const s3 = s3Loader(config.aws)
export const models = modelLoader(config.database)
export const server = Object.assign(qs(koa()), {
  // keys: config.keys,
  keys: ['keys'],
  name: config.name,
  env: config.env
})

// Initialize GraphQL schema
export const schema = loadSchema(models)

// Add s3, models, and graphql options to context
server.context.s3 = s3
server.context.models = models
server.context.graphql = {
  schema: schema,
  rootValue: {}
}

// Middleware
if (server.env === 'development') {
  const logger = require('koa-logger')
  server.use(logger())
}

// X-RESPONSE-TIME
server.use(responseTime())

// Expose errors outside of production
server.use(middleware.exposeError(config.env))

// Cookie sessions
server.use(session({ key: 'bshed' }, server))

// CSRF token
// server.use(csrf())

// Set user
server.use(middleware.setUser())

// XSRF-TOKEN
// server.use(middleware.setCsrfToken())

// Controllers
server.use(controllerLoader())

// File server
// server.use(fileServer(path.resolve(__dirname, '../../graphiql/example/dist')))
server.use(fileServer(path.resolve(__dirname, '../build/assets')))

// Server initializer
const log = debug('app:server')
export function init (port = config.port) {
  log(`initializing server using port ${port}`)
  server.instance = server.listen(port, () => log(`listening on port ${port}`))
  return server.instance
}

// Initialize server if called directly
if (require.main === module) {
  init()
}
<|endoftext|>