<commit_before>"use strict";
var TXT_LENGTH = 50;
var HINT_DELAY = 1500;

var hint = function() {
    var storedKeyDOM;
    var timer;

    var reset = function() {
        window.clearTimeout(timer);
        if ("classList" in storedKeyDOM) {
            storedKeyDOM.classList.remove("hint");
        }
    };

    var set =  function(keyDOM) {
        reset();
        storedKeyDOM = keyDOM;
        timer = window.setTimeout(function() {
            if ("classList" in storedKeyDOM) {
                storedKeyDOM.classList.add("hint");
            };
        }, HINT_DELAY);
    };

    return {
        reset: reset,
        set: set
    };
}();

function exercise() {
    var lessonString;
    var pos;
    var error;
    var timeStamp;
    var keyLogging = {};
    var rankedKeys = JSON.parse(localStorage.getItem("rankedKeys"));
    var orderdKeys = JSON.parse(localStorage.getItem("orderdKeys"));

    var txtDone = document.getElementById('txtDone');
    var txtNow = document.getElementById('txtNow');
    var txtNext = document.getElementById('txtNext');

    document.getElementById("exercise").classList.remove("hide");
    keyboard.setKeyboard(localStorage.keyboard);
    newLesson();

    window.onkeypress = function(event){
        checkInput(event);
    };

    function updateView() {
        txtDone.innerHTML = lessonString.substring(0, pos);
        txtNow.innerHTML = lessonString[pos] || "";
        txtNow.classList.remove("error");
        txtNext.innerHTML = lessonString.substring(pos+1, TXT_LENGTH);

        if (pos === 0) {
            var buffer = "";
            rankedKeys.forEach(function(item, _) {
                buffer += '';
                buffer += item.key;
                buffer += '';
            });
            document.getElementById("keysRanked").innerHTML = buffer;
            buffer = "";
            orderdKeys.forEach(function(item, _) {
                buffer += '';
                buffer += item;
                buffer += '';
            });
            document.getElementById("keysNext").innerHTML = buffer;
        }
    }

    function newLesson() {
        var space = 4 + Math.floor(Math.random() * 4);
        if (rankedKeys[rankedKeys.length-1].points > 1500) {
               rankedKeys.push({
                   "key": orderdKeys[0],
                   "points": 0,
                   "count": 0
               });
                orderdKeys.splice(0, 1);
                localStorage.setItem("rankedKeys", JSON.stringify(rankedKeys));
                localStorage.setItem("orderdKeys", JSON.stringify(orderdKeys));
           }

        keyLogging = {};
        lessonString = "";
        pos = 0;
        for (var i = 0; i < TXT_LENGTH; i++) {
            if (i === space && i < TXT_LENGTH-2) {
                lessonString += " ";
                space += 4 + Math.floor(Math.random() * 4);
                continue;
            }
            var keyPos = Math.floor(Math.random() * rankedKeys.length);
            lessonString += rankedKeys[keyPos].key;
        }
        updateView();
        hint.set(keyboard.getDOM(lessonString[pos]));
    }

    function checkInput(event) {
        if (lessonString[pos] === String.fromCharCode(event.which)) {
            var timeStampEnd = new Date().getTime();
            if (pos !== 0) {
                var key = lessonString[pos];
                if (typeof(keyLogging[key]) === "undefined") {
                    keyLogging[key] = {count: 0, time: 0, err: 0};
                }
                keyLogging[key].count++;
                keyLogging[key].time += timeStampEnd - timeStamp;
                keyLogging[key].err += error;
            }
            pos++;
            if (pos < TXT_LENGTH) {
                hint.set(keyboard.getDOM(lessonString[pos]));
            } else {
                calculatePoints();
                hint.reset();
                newLesson();
            }
            updateView();
            timeStamp = new Date().getTime();
            error = false;
        } else {
            txtNow.classList.add("error");
            error = true;
        }
    }

    function calculatePoints() {
        rankedKeys.forEach(function(item, index) {
            var k = item.key;
            if (typeof(keyLogging[k]) === "undefined") {
                return;
            }
            var speed = 2000 - (keyLogging[k].time / keyLogging[k].count);
            if (speed < 0) {
                speed = 0;
            }
            var errors = (1 - (keyLogging[k].err / keyLogging[k].count));
            var points = (speed*errors);
            if (item.points !== 0) {
                points += item.points * 2;
                points /= 3;
            }
            rankedKeys[index].points = points.toFixed(2);
            rankedKeys[index].count += keyLogging[k].count;
        });
        rankedKeys.sort(function(a, b){
            return b.points - a.points;
        });
        localStorage.setItem("rankedKeys", JSON.stringify(rankedKeys));
    }
}

var keyboard = function(){
    var keyDOMs = {};

    function setKeyboard(){
        document.getElementById("keyboard").innerHTML =
            keyboards[localStorage.keyboard].svg;
        var layout = keyboards[localStorage.keyboard].layout[localStorage.layout].mapping;
        for (var l in layout) {
            keyDOMs[l] = document.getElementById(layout[l]);
        }
    }

    function getDOM(key) {
        return keyDOMs[key];
    }

    return {
        setKeyboard: setKeyboard,
        getDOM: getDOM
    };
}();

function setup() {
    var setup = document.getElementById("setup");
    var setupLanguage = document.getElementById("setupLanguage");
    var setupLayout = document.getElementById("setupLayout");
    var saveConfig = document.getElementById("saveConfig");
    var selectKeyboard = document.getElementById("selectKeyboard");
    var selectLayout = document.getElementById("selectLayout");
    var ownLayout = document.getElementById("ownLayout");
    var selectLanguage = document.getElementById("selectLanguage");
    var startLayoutConfig = document.getElementById("startLayoutConfig");

    setup.classList.remove("hide");
    updateKeyboards();

    selectKeyboard.onchange = function(event) {
        updateLayout(event.target.value);
        showKeyboardPreview(event.target.value);
        selectLayout.disabled = false;
        //ownLayout.disabled = false;
    };

    selectLayout.onchange = function() {
        saveConfig.disabled = false;
    };

    ownLayout.onclick = function() {
        setup.classList.add("hide");
        for (var l in languages) {
            var option = document.createElement("option");
            option.text = l;
            selectLanguage.add(option);
        }
        setupLanguage.classList.remove("hide");
    };

    startLayoutConfig.onclick = function() {
        setupLanguage.classList.add("hide");
        document.getElementById("setupLayoutKeyboard").innerHTML =
            keyboards[selectKeyboard.value].svg;
        setupLayout.classList.remove("hide");
        localStorage.keyboard = selectKeyboard.value;
        configKeys.setLanguage(languages[selectLanguage.value]);
    };

    function updateKeyboards() {
        selectKeyboard.innerHTML = "";
        for (var k in keyboards) {
            var option = document.createElement("option");
            option.text = k;
            selectKeyboard.add(option);
        }
        selectKeyboard.selectedIndex = -1;
    }

    function showKeyboardPreview(keyboardType) {
        document.getElementById("preview").innerHTML = keyboards[keyboardType].svg;
    }

    function updateLayout(keyboardType) {
        selectLayout.innerHTML = "";
        for (var l in keyboards[keyboardType].layout) {
            var option = document.createElement("option");
            option.text = l;
            selectLayout.add(option);
        }
        selectLayout.selectedIndex = -1;
        selectLayout.disabled = true;
    }

    function createOrder() {
        var orderdKeys = [];
        var layout = keyboards[localStorage.keyboard].layout[localStorage.layout];
        var order = keyboards[localStorage.keyboard].ordering;
        for (var o = 0; o < order.length; o++) {
            for (var l in layout.mapping) {
                if (layout.mapping[l] === order[o] &&
                    languages[layout.language].indexOf(l) !== -1
                   ) {
                       orderdKeys.push(l);
                   }
            }
        }
        var rankedKeys = [];
        for (var i = 0; i < 4; i++) {
            rankedKeys.push({
                "key": orderdKeys[0],
                "points": 0,
                "count": 0
            });
            orderdKeys.splice(0, 1);
        }
        localStorage.setItem("rankedKeys", JSON.stringify(rankedKeys));
        localStorage.setItem("orderdKeys", JSON.stringify(orderdKeys));
    }

    function save() {
        if (
            selectKeyboard.selectedIndex === -1 ||
            selectLayout.selectedIndex === -1
        ) {
            alert("You have to select a keyboard design and a layout");
            return;
        }

        localStorage.keyboard = selectKeyboard.value;
        localStorage.layout = selectLayout.value;
        createOrder();
        setup.classList.add("hide");
        exercise();
    }

    saveConfig.onclick = function() {
        save();
    };
}

function showWelcome() {
    var welcome = document.getElementById("welcome");
    var startSetup = document.getElementById("startSetup");

    welcome.classList.remove("hide");
    startSetup.onclick = function() {
        welcome.classList.add("hide");
        setup();
    };
}

var configKeys = function() {
    var lang;
    var pos = 0;
    var mapping = {};
    var setupLayoutKey = document.getElementById("setupLayoutKey");

    function update() {
        if (pos < lang.length) {
            setupLayoutKey.innerHTML = lang[pos];
            pos++;
        } else {
            console.log("finished");
        }
    }

    function setLanguage(l) {
        lang = l;
        update();
    }

    function setKey(id) {
        if (typeof(lang) === "undefined") {
            return;
        };
        mapping[lang[pos - 1]] = id;
        update();
    }

    return {
        setLanguage: setLanguage,
        setKey: setKey
    }
}();

function init() {
    //window.localStorage.clear();

    // drop backspace
    document.addEventListener("keydown", function(event) {
        if (event.which === 8) {
           event.preventDefault();
        }
    });

    if (
        typeof(localStorage.keyboard) === "undefined" ||
        typeof(localStorage.layout) === "undefined" ||
        typeof(localStorage.orderdKeys) === "undefined" ||
        typeof(localStorage.rankedKeys) === "undefined"
    ) {
        showWelcome();
    } else {
        exercise();
    }
}
<commit_msg>Revert "workaround because typeof is not supported by IE (part 2)"<commit_after>"use strict";
var TXT_LENGTH = 50;
var HINT_DELAY = 1500;

var hint = function() {
    var storedKeyDOM;
    var timer;

    var reset = function() {
        window.clearTimeout(timer);
        if ("classList" in storedKeyDOM) {
            storedKeyDOM.classList.remove("hint");
        }
    };

    var set =  function(keyDOM) {
        reset();
        storedKeyDOM = keyDOM;
        timer = window.setTimeout(function() {
            storedKeyDOM.classList.add("hint");
        }, HINT_DELAY);
    };

    return {
        reset: reset,
        set: set
    };
}();

function exercise() {
    var lessonString;
    var pos;
    var error;
    var timeStamp;
    var keyLogging = {};
    var rankedKeys = JSON.parse(localStorage.getItem("rankedKeys"));
    var orderdKeys = JSON.parse(localStorage.getItem("orderdKeys"));

    var txtDone = document.getElementById('txtDone');
    var txtNow = document.getElementById('txtNow');
    var txtNext = document.getElementById('txtNext');

    document.getElementById("exercise").classList.remove("hide");
    keyboard.setKeyboard(localStorage.keyboard);
    newLesson();

    window.onkeypress = function(event){
        checkInput(event);
    };

    function updateView() {
        txtDone.innerHTML = lessonString.substring(0, pos);
        txtNow.innerHTML = lessonString[pos] || "";
        txtNow.classList.remove("error");
        txtNext.innerHTML = lessonString.substring(pos+1, TXT_LENGTH);

        if (pos === 0) {
            var buffer = "";
            rankedKeys.forEach(function(item, _) {
                buffer += '';
                buffer += item.key;
                buffer += '';
            });
            document.getElementById("keysRanked").innerHTML = buffer;
            buffer = "";
            orderdKeys.forEach(function(item, _) {
                buffer += '';
                buffer += item;
                buffer += '';
            });
            document.getElementById("keysNext").innerHTML = buffer;
        }
    }

    function newLesson() {
        var space = 4 + Math.floor(Math.random() * 4);
        if (rankedKeys[rankedKeys.length-1].points > 1500) {
               rankedKeys.push({
                   "key": orderdKeys[0],
                   "points": 0,
                   "count": 0
               });
                orderdKeys.splice(0, 1);
                localStorage.setItem("rankedKeys", JSON.stringify(rankedKeys));
                localStorage.setItem("orderdKeys", JSON.stringify(orderdKeys));
           }

        keyLogging = {};
        lessonString = "";
        pos = 0;
        for (var i = 0; i < TXT_LENGTH; i++) {
            if (i === space && i < TXT_LENGTH-2) {
                lessonString += " ";
                space += 4 + Math.floor(Math.random() * 4);
                continue;
            }
            var keyPos = Math.floor(Math.random() * rankedKeys.length);
            lessonString += rankedKeys[keyPos].key;
        }
        updateView();
        hint.set(keyboard.getDOM(lessonString[pos]));
    }

    function checkInput(event) {
        if (lessonString[pos] === String.fromCharCode(event.which)) {
            var timeStampEnd = new Date().getTime();
            if (pos !== 0) {
                var key = lessonString[pos];
                if (typeof(keyLogging[key]) === "undefined") {
                    keyLogging[key] = {count: 0, time: 0, err: 0};
                }
                keyLogging[key].count++;
                keyLogging[key].time += timeStampEnd - timeStamp;
                keyLogging[key].err += error;
            }
            pos++;
            if (pos < TXT_LENGTH) {
                hint.set(keyboard.getDOM(lessonString[pos]));
            } else {
                calculatePoints();
                hint.reset();
                newLesson();
            }
            updateView();
            timeStamp = new Date().getTime();
            error = false;
        } else {
            txtNow.classList.add("error");
            error = true;
        }
    }

    function calculatePoints() {
        rankedKeys.forEach(function(item, index) {
            var k = item.key;
            if (typeof(keyLogging[k]) === "undefined") {
                return;
            }
            var speed = 2000 - (keyLogging[k].time / keyLogging[k].count);
            if (speed < 0) {
                speed = 0;
            }
            var errors = (1 - (keyLogging[k].err / keyLogging[k].count));
            var points = (speed*errors);
            if (item.points !== 0) {
                points += item.points * 2;
                points /= 3;
            }
            rankedKeys[index].points = points.toFixed(2);
            rankedKeys[index].count += keyLogging[k].count;
        });
        rankedKeys.sort(function(a, b){
            return b.points - a.points;
        });
        localStorage.setItem("rankedKeys", JSON.stringify(rankedKeys));
    }
}

var keyboard = function(){
    var keyDOMs = {};

    function setKeyboard(){
        document.getElementById("keyboard").innerHTML =
            keyboards[localStorage.keyboard].svg;
        var layout = keyboards[localStorage.keyboard].layout[localStorage.layout].mapping;
        for (var l in layout) {
            keyDOMs[l] = document.getElementById(layout[l]);
        }
    }

    function getDOM(key) {
        return keyDOMs[key];
    }

    return {
        setKeyboard: setKeyboard,
        getDOM: getDOM
    };
}();

function setup() {
    var setup = document.getElementById("setup");
    var setupLanguage = document.getElementById("setupLanguage");
    var setupLayout = document.getElementById("setupLayout");
    var saveConfig = document.getElementById("saveConfig");
    var selectKeyboard = document.getElementById("selectKeyboard");
    var selectLayout = document.getElementById("selectLayout");
    var ownLayout = document.getElementById("ownLayout");
    var selectLanguage = document.getElementById("selectLanguage");
    var startLayoutConfig = document.getElementById("startLayoutConfig");

    setup.classList.remove("hide");
    updateKeyboards();

    selectKeyboard.onchange = function(event) {
        updateLayout(event.target.value);
        showKeyboardPreview(event.target.value);
        selectLayout.disabled = false;
        //ownLayout.disabled = false;
    };

    selectLayout.onchange = function() {
        saveConfig.disabled = false;
    };

    ownLayout.onclick = function() {
        setup.classList.add("hide");
        for (var l in languages) {
            var option = document.createElement("option");
            option.text = l;
            selectLanguage.add(option);
        }
        setupLanguage.classList.remove("hide");
    };

    startLayoutConfig.onclick = function() {
        setupLanguage.classList.add("hide");
        document.getElementById("setupLayoutKeyboard").innerHTML =
            keyboards[selectKeyboard.value].svg;
        setupLayout.classList.remove("hide");
        localStorage.keyboard = selectKeyboard.value;
        configKeys.setLanguage(languages[selectLanguage.value]);
    };

    function updateKeyboards() {
        selectKeyboard.innerHTML = "";
        for (var k in keyboards) {
            var option = document.createElement("option");
            option.text = k;
            selectKeyboard.add(option);
        }
        selectKeyboard.selectedIndex = -1;
    }

    function showKeyboardPreview(keyboardType) {
        document.getElementById("preview").innerHTML = keyboards[keyboardType].svg;
    }

    function updateLayout(keyboardType) {
        selectLayout.innerHTML = "";
        for (var l in keyboards[keyboardType].layout) {
            var option = document.createElement("option");
            option.text = l;
            selectLayout.add(option);
        }
        selectLayout.selectedIndex = -1;
        selectLayout.disabled = true;
    }

    function createOrder() {
        var orderdKeys = [];
        var layout = keyboards[localStorage.keyboard].layout[localStorage.layout];
        var order = keyboards[localStorage.keyboard].ordering;
        for (var o = 0; o < order.length; o++) {
            for (var l in layout.mapping) {
                if (layout.mapping[l] === order[o] &&
                    languages[layout.language].indexOf(l) !== -1
                   ) {
                       orderdKeys.push(l);
                   }
            }
        }
        var rankedKeys = [];
        for (var i = 0; i < 4; i++) {
            rankedKeys.push({
                "key": orderdKeys[0],
                "points": 0,
                "count": 0
            });
            orderdKeys.splice(0, 1);
        }
        localStorage.setItem("rankedKeys", JSON.stringify(rankedKeys));
        localStorage.setItem("orderdKeys", JSON.stringify(orderdKeys));
    }

    function save() {
        if (
            selectKeyboard.selectedIndex === -1 ||
            selectLayout.selectedIndex === -1
        ) {
            alert("You have to select a keyboard design and a layout");
            return;
        }

        localStorage.keyboard = selectKeyboard.value;
        localStorage.layout = selectLayout.value;
        createOrder();
        setup.classList.add("hide");
        exercise();
    }

    saveConfig.onclick = function() {
        save();
    };
}

function showWelcome() {
    var welcome = document.getElementById("welcome");
    var startSetup = document.getElementById("startSetup");

    welcome.classList.remove("hide");
    startSetup.onclick = function() {
        welcome.classList.add("hide");
        setup();
    };
}

var configKeys = function() {
    var lang;
    var pos = 0;
    var mapping = {};
    var setupLayoutKey = document.getElementById("setupLayoutKey");

    function update() {
        if (pos < lang.length) {
            setupLayoutKey.innerHTML = lang[pos];
            pos++;
        } else {
            console.log("finished");
        }
    }

    function setLanguage(l) {
        lang = l;
        update();
    }

    function setKey(id) {
        if (typeof(lang) === "undefined") {
            return;
        };
        mapping[lang[pos - 1]] = id;
        update();
    }

    return {
        setLanguage: setLanguage,
        setKey: setKey
    }
}();

function init() {
    //window.localStorage.clear();

    // drop backspace
    document.addEventListener("keydown", function(event) {
        if (event.which === 8) {
           event.preventDefault();
        }
    });

    if (
        typeof(localStorage.keyboard) === "undefined" ||
        typeof(localStorage.layout) === "undefined" ||
        typeof(localStorage.orderdKeys) === "undefined" ||
        typeof(localStorage.rankedKeys) === "undefined"
    ) {
        showWelcome();
    } else {
        exercise();
    }
}
<|endoftext|>


<commit_before>//Main game file
"use strict";
var game = game || {};
//Battle balls game file
game.battleBalls = {
    canvas : undefined,
    ctx : undefined,
    arena : undefined,
    playerIDs : [],
    players : {},
    sparks : [],
    booms : [],
    state : "START",
    startDelay : 500,
    arenaShrinkDelay : /*1000*/200,

    bgMusic : undefined,
    chargeSound : undefined,
    dashSound : undefined,
    boomSound : undefined,
    readySound : undefined,
    collideSound : undefined,

    init : function(){
        var me = this;
        // create new instance of socket.io
        var num = Math.floor(Math.random()*10);
        var name ='user'+num;
        //setting client's own properties (MIGHT NOT BE THE BEST PRACTICE);
        me.canvas = document.querySelector('#area');
        me.ctx = me.canvas.getContext('2d');
        me.ctx.lineWidth = 5;
        me.arena = game.createArena('white', me.canvas.height/2-10, me.canvas.width/2, me.canvas.height/2);
        //set up sounds
        me.bgMusic = document.querySelector("#bgMusic");
        me.bgMusic.volume = 0.2;
        me.bgMusic.play();

        me.chargeSound = document.querySelector("#chargeSound");
        me.chargeSound.volume = 1;

        me.dashSound = document.querySelector("#dashSound");
        me.dashSound.volume = 1;

        me.boomSound = document.querySelector("#boomSound");
        me.boomSound.volume = 1;

        me.readySound = document.querySelector("#readySound");
        me.readySound.volume = 1;

        me.collideSound = document.querySelector("#collideSound");
        me.collideSound.volume = 1;

        //set up socket
        game.socketHandlers.init(me);//This line of code needs to be called last
    },
    //main loop
    loop : function() {
        requestAnimationFrame(this.loop.bind(this));
        this.update();
        this.render();
    },
    //Sets start positions of all players
    setPlayerStarts : function() {
        var theta = 2*Math.PI/this.playerIDs.length; //Distance between each player
        var playerPositions = []; //Array of player start positions
        var startDist = 100; //Distance from center of map
        for(var i = 0; i < this.playerIDs.length; i++) {
            var point = {};
            point.x = this.canvas.width/2 + startDist*Math.cos(theta * i);
            point.y = this.canvas.height/2 + startDist*Math.sin(theta * i);
            playerPositions[i] = point;
        }
        var me = this;
        //set each player's position
        this.playerIDs.forEach(function(id, index){
            me.players[id].setPosition(playerPositions[index].x, playerPositions[index].y);
            me.players[id].updateAcceleration(0,0);
            me.players[id].velocity = {x: 0, y: 0};
            //me.players[id].setPosition(me.canvas.width/2, me.canvas.height/2);
        });
    },
    //Update function for start menu
    updateStartMenu : function() {
        //console.log("START MENU");
        var canStart = true;
        var me = this;
        //Check if all players are ready
        me.playerIDs.forEach(function(id){
            if(!me.players[id].ready)
                canStart = false;
        });
        //If all players are read and there are more than 2
        if(me.playerIDs.length >= 2 && canStart) {
            //Begin game
            me.state = "GAME";
            game.socketHandlers.changeState("GAME");
            me.reset();
        }

        //audio controls
        if(me.bgMusic.currentTime >= 80) me.bgMusic.currentTime = 0;
    },
    //update function for end game screen
    updateGameEnd : function() {
        var canStart = true;
        var me = this;
        //Check if all players are ready
        this.playerIDs.forEach(function(id){
            if(!me.players[id].ready)
                canStart = false;
        });
        //If players are ready play again
        if(this.playerIDs.length >= 2 && canStart) {
            this.state = "GAME";
            game.socketHandlers.changeState("GAME");
            me.bgMusic.currentTime = 80;
            me.reset();
        }
    },
    //Main game loop
    updateGameLoop : function() {
        var dt = 0;
        var me = this;//save reference to this
        var KOes = 0;//number of players knocked out
        //Loop through all players
        me.playerIDs.forEach(function(id) {
            var player = me.players[id];//get player reference
            //If the player isn't knocked out
            if(!player.KOed) {
                //loop through the rest of the players for collisions
                me.playerIDs.forEach(function(id2){
                    var player2 = me.players[id2]; //reference to player to collide with
                    if(player2.id !== player.id){//if the players aren't the same
                        //Check collision if they aren't already colliding
                        if(game.physicsUtils.circleCollision(player, player2) && !player.colliding(player2)) {
                            me.collideSound.play();
                            //get impulse
                            var impulse = game.physicsUtils.getImpulse(player, player2, 1.5);
                            player.applyImpulse(impulse);//apply impluse to first player
                            player.collisions.push({player: player2, force: impulse});//Add collision to player obj
                            //get inverse of impulse
                            impulse.x = impulse.x * -1;
                            impulse.y = impulse.y * -1;
                            player2.applyImpulse(impulse);//send inverse to second player
                            player2.collisions.push({player: player, force: impulse});
                            //me.addSparks(player, player2, impulse);
                        }
                    }
                });
                //Bad code for resetting player if they leave the arena
                if(!me.arena.inBounds(player)) {
                    /*player.x = me.canvas.width/2;
          player.y = me.canvas.width/2;*/
                    player.KOed = true;
                }
                player.update(dt);//update the player
            } else {//if the player is koed
                KOes++;
            }
        });
        //If all players are knocked out end the game
        if(KOes >= me.playerIDs.length -1 && me.playerIDs.length > 1) {
            me.state = "END";
            game.socketHandlers.changeState("END");
        }
        //Loop through and update akk if the booms
        me.booms.forEach(function(boom, index, array){
            boom.update(dt);//update boom
            //make a copy of the boom
            var boomc = {
                x : boom.play.x,
                y : boom.play.y,
                velocity : {x:0, y:0},
                mass : boom.pow * 20,
                radius : boom.radius
            };
            //!!!!!!!!!!!!!!duplicate, make a helper function
            //Loop through all players
            me.playerIDs.forEach(function(id){
                var player = me.players[id];
                if(boom.id !== player.id){
                    //check for collison between a boom and other players
                    if(game.physicsUtils.circleCollision(player, boomc)) {
                        //get impulse
                        var impulse = {x:0, y:0};
                        impulse = game.physicsUtils.normalize(game.physicsUtils.vecDiff(player, boomc));
                        impulse.x *= 20;
                        impulse.y *= 20;
                        player.applyImpulse(impulse);
                        //me.addSparks(player, player2, impulse);
                    }
                }
            });
            //remove a boom if it is done
            if(boom.remove) {
                array.splice(index, 1);
            }
        });
        //loop through the sparks
        this.sparks.forEach(function(spark, index, array){
            spark.update(dt);
            if(spark.remove) {
                array.splice(index, 1);
            }
        });
//        if(this.arenaShrinkDelay < 1)
          this.arena.radius -= 0.03;
//        else
//          this.arenaShrinkDelay--;

        if(me.bgMusic.currentTime < 80) me.bgMusic.currentTime = 80;
    },
    //Update loop that handles all states
    update : function() {
        switch(this.state) {
            case "START" :
                this.updateStartMenu();
                break;
            case "GAME" :
                //if(this.startDelay < 1)
                  this.updateGameLoop();
                //else
                  //this.startDelay--;
                break;
            case "END" :
                this.updateGameEnd();
                break;
            default :
                break;
        }
    },
    //Resets game to state at start of game loop
    reset : function() {
      var me = this;
      me.arenaShrinkDelay = 10000;
      me.startDelay = 500;
      me.arena.radius = me.canvas.height/2-10;
      this.playerIDs.forEach(function(id){
        me.players[id].ready = false;
        me.players[id].KOed = false;
      });
      me.setPlayerStarts();
    },
    /** Creates sparks based on an impulse
   * @param c1 : first circle object in collison
   * @param c2 : second circle object in collison
   * @param impulse : impulse the sparks are created from
   */
    addSparks : function(c1, c2, impulse) {
        /*var line = game.physicsUtils.getPerp(game.physicsUtils.getSlope(c1, c2));
    var x = c1.x - (c1.x - c2.x)/2;
    var y = c1.y - (c1.y - c2.y)/2;

    this.sparks.push(new game.Spark(x, y, line.x/5, line.y/5));
    this.sparks.push(new game.Spark(x, y, -line.x/5, -line.y/5));*/
    },
    //Draw function for the start menu
    renderStart : function() {
        var me = this;
        me.ctx.save();
        me.ctx.fillStyle = 'black';
        me.ctx.fillRect(0,0, me.canvas.width, me.canvas.height);
        me.ctx.restore();
        me.text(me.ctx, "Players in " + me.playerIDs.length, me.canvas.width/2, me.canvas.height/4, 100, "white");

        me.playerIDs.forEach(function(id, index) {
            var player = me.players[id];
            me.ctx.save();
            me.ctx.strokeStyle = player.color;
            me.ctx.fillStyle = player.color;
            if(player.ready) {
                me.ctx.shadowBlur = 10;
                me.ctx.shadowColor = player.color;
                me.text(me.ctx, "player "+(index+1),me.canvas.width/3,me.canvas.height/2+index*55,50,player.color);

                me.ctx.beginPath();
                me.ctx.arc(me.canvas.width*2/3,me.canvas.height/2-20+index*55,20,0,Math.PI*2,false);
                me.ctx.closePath();
                me.ctx.stroke();

                me.ctx.beginPath();
                me.ctx.arc(me.canvas.width*2/3,me.canvas.height/2-20+index*55,10,0,Math.PI*2,false);
                me.ctx.closePath();
                me.ctx.fill();
            } else {
                me.text(me.ctx, "player "+(index+1),me.canvas.width/3,me.canvas.height/2+index*55,50,player.color);

                me.ctx.beginPath();
                me.ctx.arc(me.canvas.width*2/3,me.canvas.height/2-20+index*55,20,0,Math.PI*2,false);
                me.ctx.closePath();
                me.ctx.stroke();
            }
            me.ctx.restore();
        });

    },
    /** Draws text to the screen
   * @param ctx : drawing context
   * @param string : text to be rendered
   * @param x : x coord of text
   * @param y : y coord of text
   * @param size : size of text
   * @param col : color of text
   */
    text: function(ctx, string, x, y, size, col) {
        ctx.save();
        ctx.font = size+'px BAAAAALLLLLLLLLLS';
        ctx.textAlign = "center";
        ctx.fillStyle = col;
        ctx.fillText(string, x, y);
        ctx.restore();
    },
    //Render in game screen
    renderGame : function() {
        var me = this;//save reference to this
        me.ctx.save();
        me.ctx.fillStyle = 'black';
        me.ctx.fillRect(0,0, me.canvas.width, me.canvas.height);
        me.ctx.restore();
        me.arena.render(me.ctx);//draw arena
        //loop through and draw each player
        me.playerIDs.forEach(function(id) {
            var player = me.players[id];
            player.render(me.ctx);
        });
        //loop through and draw each boom
        me.booms.forEach(function(boom) {
            boom.render(me.ctx);
        });
        //loop through and draw each spark
        me.sparks.forEach(function(spark) {
            spark.render(me.ctx);
        });
    },
    //Draw function for the end game screen
    renderEnd : function() {
        var me = this;
        me.ctx.save();
        me.ctx.fillStyle = 'black';
        me.ctx.fillRect(0,0, me.canvas.width, me.canvas.height);
        me.ctx.restore();
//        me.text(me.ctx, "Game Over", me.canvas.width/2, me.canvas.height/4, 100, "white");
        me.text(me.ctx,"ready up to play again",me.canvas.width/2,me.canvas.height/4+50,50,"white");

        me.playerIDs.forEach(function(id, index) {
            var player = me.players[id];
            if(!player.KOed) me.text(me.ctx,"player "+(index+1)+" won",me.canvas.width/2,me.canvas.height/4,100,"white");

            me.ctx.save();
            me.ctx.strokeStyle = player.color;
            me.ctx.fillStyle = player.color;
            if(player.ready) {
                me.ctx.shadowBlur = 10;
                me.ctx.shadowColor = player.color;
                me.text(me.ctx, "player "+(index+1),me.canvas.width/3,me.canvas.height/2+index*55,50,player.color);

                me.ctx.beginPath();
                me.ctx.arc(me.canvas.width*2/3,me.canvas.height/2-20+index*55,20,0,Math.PI*2,false);
                me.ctx.closePath();
                me.ctx.stroke();

                me.ctx.beginPath();
                me.ctx.arc(me.canvas.width*2/3,me.canvas.height/2-20+index*55,10,0,Math.PI*2,false);
                me.ctx.closePath();
                me.ctx.fill();
            } else {
                me.text(me.ctx, "player "+(index+1),me.canvas.width/3,me.canvas.height/2+index*55,50,player.color);

                me.ctx.beginPath();
                me.ctx.arc(me.canvas.width*2/3,me.canvas.height/2-20+index*55,20,0,Math.PI*2,false);
                me.ctx.closePath();
                me.ctx.stroke();
            }
            me.ctx.restore();
        });
    },
    //Main render function that handles different render states
    render : function() {
        switch(this.state) {
            case "START" :
                this.renderStart();
                break;
            case "GAME" :
                this.renderGame();
                break;
            case "END" :
                this.renderEnd();
                break;
            default :
                break;
        }
    }
}<commit_msg>Onboarding + Start Screen Change<commit_after>//Main game file
"use strict";
var game = game || {};
//Battle balls game file
game.battleBalls = {
    canvas : undefined,
    ctx : undefined,
    arena : undefined,
    playerIDs : [],
    players : {},
    sparks : [],
    booms : [],
    state : "START",
    startDelay : 500,
    arenaShrinkDelay : /*1000*/200,
    ticker: 100,

    bgMusic : undefined,
    chargeSound : undefined,
    dashSound : undefined,
    boomSound : undefined,
    readySound : undefined,
    collideSound : undefined,

    init : function(){
        var me = this;
        // create new instance of socket.io
        var num = Math.floor(Math.random()*10);
        var name ='user'+num;
        //setting client's own properties (MIGHT NOT BE THE BEST PRACTICE);
        me.canvas = document.querySelector('#area');
        me.ctx = me.canvas.getContext('2d');
        me.ctx.lineWidth = 5;
        me.arena = game.createArena('white', me.canvas.height/2-10, me.canvas.width/2, me.canvas.height/2);
        //set up sounds
        me.bgMusic = document.querySelector("#bgMusic");
        me.bgMusic.volume = 0.2;
        me.bgMusic.play();

        me.chargeSound = document.querySelector("#chargeSound");
        me.chargeSound.volume = 1;

        me.dashSound = document.querySelector("#dashSound");
        me.dashSound.volume = 1;

        me.boomSound = document.querySelector("#boomSound");
        me.boomSound.volume = 1;

        me.readySound = document.querySelector("#readySound");
        me.readySound.volume = 1;

        me.collideSound = document.querySelector("#collideSound");
        me.collideSound.volume = 1;

        //set up socket
        game.socketHandlers.init(me);//This line of code needs to be called last
    },
    //main loop
    loop : function() {
        requestAnimationFrame(this.loop.bind(this));
        this.update();
        this.render();
    },
    //Sets start positions of all players
    setPlayerStarts : function() {
        var theta = 2*Math.PI/this.playerIDs.length; //Distance between each player
        var playerPositions = []; //Array of player start positions
        var startDist = 100; //Distance from center of map
        for(var i = 0; i < this.playerIDs.length; i++) {
            var point = {};
            point.x = this.canvas.width/2 + startDist*Math.cos(theta * i);
            point.y = this.canvas.height/2 + startDist*Math.sin(theta * i);
            playerPositions[i] = point;
        }
        var me = this;
        //set each player's position
        this.playerIDs.forEach(function(id, index){
            me.players[id].setPosition(playerPositions[index].x, playerPositions[index].y);
            me.players[id].updateAcceleration(0,0);
            me.players[id].velocity = {x: 0, y: 0};
            //me.players[id].setPosition(me.canvas.width/2, me.canvas.height/2);
        });
    },
    //Update function for start menu
    updateStartMenu : function() {
        //console.log("START MENU");
        var canStart = true;
        var me = this;
        //Check if all players are ready
        me.playerIDs.forEach(function(id){
            if(!me.players[id].ready)
                canStart = false;
        });
        //If all players are read and there are more than 2
        if(me.playerIDs.length >= 2 && canStart) {
            //Begin game
            me.state = "ONBOARD";
            game.socketHandlers.changeState("GAME");
            me.reset();
        }

        //audio controls
        if(me.bgMusic.currentTime >= 80) me.bgMusic.currentTime = 0;
    },
    //update function for end game screen
    updateGameEnd : function() {
        var canStart = true;
        var me = this;
        //Check if all players are ready
        this.playerIDs.forEach(function(id){
            if(!me.players[id].ready)
                canStart = false;
        });
        //If players are ready play again
        if(this.playerIDs.length >= 2 && canStart) {
            this.state = "GAME";
            game.socketHandlers.changeState("GAME");
            me.bgMusic.currentTime = 80;
            me.reset();
        }
    },
    //Main game loop
    updateGameLoop : function() {
        var dt = 0;
        var me = this;//save reference to this
        var KOes = 0;//number of players knocked out
        //Loop through all players
        me.playerIDs.forEach(function(id) {
            var player = me.players[id];//get player reference
            //If the player isn't knocked out
            if(!player.KOed) {
                //loop through the rest of the players for collisions
                me.playerIDs.forEach(function(id2){
                    var player2 = me.players[id2]; //reference to player to collide with
                    if(player2.id !== player.id){//if the players aren't the same
                        //Check collision if they aren't already colliding
                        if(game.physicsUtils.circleCollision(player, player2) && !player.colliding(player2)) {
                            me.collideSound.play();
                            //get impulse
                            var impulse = game.physicsUtils.getImpulse(player, player2, 1.5);
                            player.applyImpulse(impulse);//apply impluse to first player
                            player.collisions.push({player: player2, force: impulse});//Add collision to player obj
                            //get inverse of impulse
                            impulse.x = impulse.x * -1;
                            impulse.y = impulse.y * -1;
                            player2.applyImpulse(impulse);//send inverse to second player
                            player2.collisions.push({player: player, force: impulse});
                            //me.addSparks(player, player2, impulse);
                        }
                    }
                });
                //Bad code for resetting player if they leave the arena
                if(!me.arena.inBounds(player)) {
                    /*player.x = me.canvas.width/2;
          player.y = me.canvas.width/2;*/
                    player.KOed = true;
                }
                player.update(dt);//update the player
            } else {//if the player is koed
                KOes++;
            }
        });
        //If all players are knocked out end the game
        if(KOes >= me.playerIDs.length -1 && me.playerIDs.length > 1) {
            me.state = "END";
            game.socketHandlers.changeState("END");
        }
        //Loop through and update akk if the booms
        me.booms.forEach(function(boom, index, array){
            boom.update(dt);//update boom
            //make a copy of the boom
            var boomc = {
                x : boom.play.x,
                y : boom.play.y,
                velocity : {x:0, y:0},
                mass : boom.pow * 20,
                radius : boom.radius
            };
            //!!!!!!!!!!!!!!duplicate, make a helper function
            //Loop through all players
            me.playerIDs.forEach(function(id){
                var player = me.players[id];
                if(boom.id !== player.id){
                    //check for collison between a boom and other players
                    if(game.physicsUtils.circleCollision(player, boomc)) {
                        //get impulse
                        var impulse = {x:0, y:0};
                        impulse = game.physicsUtils.normalize(game.physicsUtils.vecDiff(player, boomc));
                        impulse.x *= 20;
                        impulse.y *= 20;
                        player.applyImpulse(impulse);
                        //me.addSparks(player, player2, impulse);
                    }
                }
            });
            //remove a boom if it is done
            if(boom.remove) {
                array.splice(index, 1);
            }
        });
        //loop through the sparks
        this.sparks.forEach(function(spark, index, array){
            spark.update(dt);
            if(spark.remove) {
                array.splice(index, 1);
            }
        });
//        if(this.arenaShrinkDelay < 1)
          this.arena.radius -= 0.03;
//        else
//          this.arenaShrinkDelay--;

        if(me.bgMusic.currentTime < 80) me.bgMusic.currentTime = 80;
    },
    updateOnboard: function() {
        if(this.ticker <= 0){
            this.state = "GAME";
        }
        this.ticker--;
        console.log(this.ticker);
    },
    //Update loop that handles all states
    update : function() {
        switch(this.state) {
            case "START" :
                this.updateStartMenu();
                break;
            case "ONBOARD" :
                this.updateOnboard();
                break;
            case "GAME" :
                //if(this.startDelay < 1)
                  this.updateGameLoop();
                //else
                  //this.startDelay--;
                break;
            case "END" :
                this.updateGameEnd();
                break;
            default :
                break;
        }
    },
    //Resets game to state at start of game loop
    reset : function() {
      var me = this;
      me.arenaShrinkDelay = 10000;
      me.startDelay = 500;
      me.arena.radius = me.canvas.height/2-10;
      this.playerIDs.forEach(function(id){
        me.players[id].ready = false;
        me.players[id].KOed = false;
      });
      me.setPlayerStarts();
    },
    /** Creates sparks based on an impulse
   * @param c1 : first circle object in collison
   * @param c2 : second circle object in collison
   * @param impulse : impulse the sparks are created from
   */
    addSparks : function(c1, c2, impulse) {
        /*var line = game.physicsUtils.getPerp(game.physicsUtils.getSlope(c1, c2));
    var x = c1.x - (c1.x - c2.x)/2;
    var y = c1.y - (c1.y - c2.y)/2;

    this.sparks.push(new game.Spark(x, y, line.x/5, line.y/5));
    this.sparks.push(new game.Spark(x, y, -line.x/5, -line.y/5));*/
    },
    //Draw function for the start menu
    renderStart : function() {
        var me = this;
        me.ctx.save();
        me.ctx.fillStyle = 'black';
        me.ctx.fillRect(0,0, me.canvas.width, me.canvas.height);
        me.ctx.restore();
        me.text(me.ctx, "battle balls", me.canvas.width/2, me.canvas.height/4, 100, "white");
        me.text(me.ctx, "battleballs.herokuapp.com to connect", me.canvas.width/2, me.canvas.height/4+35, 30, "white");

        me.playerIDs.forEach(function(id, index) {
            var player = me.players[id];
            me.ctx.save();
            me.ctx.strokeStyle = player.color;
            me.ctx.fillStyle = player.color;
            if(player.ready) {
                me.ctx.shadowBlur = 10;
                me.ctx.shadowColor = player.color;
                me.text(me.ctx, "player "+(index+1),me.canvas.width/3,me.canvas.height/2+index*55,50,player.color);

                me.ctx.beginPath();
                me.ctx.arc(me.canvas.width*2/3,me.canvas.height/2-20+index*55,20,0,Math.PI*2,false);
                me.ctx.closePath();
                me.ctx.stroke();

                me.ctx.beginPath();
                me.ctx.arc(me.canvas.width*2/3,me.canvas.height/2-20+index*55,10,0,Math.PI*2,false);
                me.ctx.closePath();
                me.ctx.fill();
            } else {
                me.text(me.ctx, "player "+(index+1),me.canvas.width/3,me.canvas.height/2+index*55,50,player.color);

                me.ctx.beginPath();
                me.ctx.arc(me.canvas.width*2/3,me.canvas.height/2-20+index*55,20,0,Math.PI*2,false);
                me.ctx.closePath();
                me.ctx.stroke();
            }
            me.ctx.restore();
        });

    },
    /** Draws text to the screen
   * @param ctx : drawing context
   * @param string : text to be rendered
   * @param x : x coord of text
   * @param y : y coord of text
   * @param size : size of text
   * @param col : color of text
   */
    text: function(ctx, string, x, y, size, col) {
        ctx.save();
        ctx.font = size+'px BAAAAALLLLLLLLLLS';
        ctx.textAlign = "center";
        ctx.fillStyle = col;
        ctx.fillText(string, x, y);
        ctx.restore();
    },
    //Render in game screen
    renderGame : function() {
        var me = this;//save reference to this
        me.ctx.save();
        me.ctx.fillStyle = 'black';
        me.ctx.fillRect(0,0, me.canvas.width, me.canvas.height);
        me.ctx.restore();
        me.arena.render(me.ctx);//draw arena
        //loop through and draw each player
        me.playerIDs.forEach(function(id) {
            var player = me.players[id];
            player.render(me.ctx);
        });
        //loop through and draw each boom
        me.booms.forEach(function(boom) {
            boom.render(me.ctx);
        });
        //loop through and draw each spark
        me.sparks.forEach(function(spark) {
            spark.render(me.ctx);
        });
    },
    //Draw function for the end game screen
    renderEnd : function() {
        var me = this;
        me.ctx.save();
        me.ctx.fillStyle = 'black';
        me.ctx.fillRect(0,0, me.canvas.width, me.canvas.height);
        me.ctx.restore();
//        me.text(me.ctx, "Game Over", me.canvas.width/2, me.canvas.height/4, 100, "white");
        me.text(me.ctx,"ready up to play again",me.canvas.width/2,me.canvas.height/4+50,50,"white");

        me.playerIDs.forEach(function(id, index) {
            var player = me.players[id];
            if(!player.KOed) me.text(me.ctx,"player "+(index+1)+" won",me.canvas.width/2,me.canvas.height/4,100,"white");

            me.ctx.save();
            me.ctx.strokeStyle = player.color;
            me.ctx.fillStyle = player.color;
            if(player.ready) {
                me.ctx.shadowBlur = 10;
                me.ctx.shadowColor = player.color;
                me.text(me.ctx, "player "+(index+1),me.canvas.width/3,me.canvas.height/2+index*55,50,player.color);

                me.ctx.beginPath();
                me.ctx.arc(me.canvas.width*2/3,me.canvas.height/2-20+index*55,20,0,Math.PI*2,false);
                me.ctx.closePath();
                me.ctx.stroke();

                me.ctx.beginPath();
                me.ctx.arc(me.canvas.width*2/3,me.canvas.height/2-20+index*55,10,0,Math.PI*2,false);
                me.ctx.closePath();
                me.ctx.fill();
            } else {
                me.text(me.ctx, "player "+(index+1),me.canvas.width/3,me.canvas.height/2+index*55,50,player.color);

                me.ctx.beginPath();
                me.ctx.arc(me.canvas.width*2/3,me.canvas.height/2-20+index*55,20,0,Math.PI*2,false);
                me.ctx.closePath();
                me.ctx.stroke();
            }
            me.ctx.restore();
        });
    },

    renderOnboard: function() {
        var me = this;
        me.ctx.fillStyle = "black"
        me.ctx.fillRect(0,0,me.canvas.width,me.canvas.height);
        me.text(me.ctx,"tilt phone to move",me.canvas.width/2,me.canvas.height/4,50,"white");
        me.text(me.ctx,"power controls on phone",me.canvas.width/2,me.canvas.height/4+100,50,"white");
        console.log("h");
    },

    //Main render function that handles different render states
    render : function() {
        switch(this.state) {
            case "START" :
                this.renderStart();
                break;
            case "ONBOARD" :
                this.renderOnboard();
                break;
            case "GAME" :
                this.renderGame();
                break;
            case "END" :
                this.renderEnd();
                break;
            default :
                break;
        }
    }
}<|endoftext|>


<commit_before>const {app, BrowserWindow, globalShortcut} = require('electron')
const path = require('path')
const url = require('url')
const client = require('electron-connect').client;

//api: api.openweathermap.org/data/2.5/forecast?zip=76131,de&APPID=c314e4b540eac4e88cee00e53b7bf99f

let win

function createWindow() {
    // Create the browser window.
    win = new BrowserWindow({width: 800, height: 600})

    // and load the index.html of the app.
    win.loadURL(url.format({
        pathname: path.join(__dirname, 'app/index.html'),
        protocol: 'file:',
        slashes: true
    }))

    // Open the DevTools.
    win.webContents.openDevTools()

    // Emitted when the window is closed.
    win.on('closed', () => {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        win = null
    })
    client.create(win)
}

function defineGlobalShortcuts() {
    globalShortcut.register('CommandOrControl+X', () => {
        app.quit();
    });
}

app.on('ready', createWindow)
app.on('ready', defineGlobalShortcuts)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (win === null) {
        createWindow()
    }
})<commit_msg>demo dialog in form of a messagebox which is displayed when the app is started.<commit_after>const {app, BrowserWindow, globalShortcut, dialog} = require('electron')
const path = require('path')
const url = require('url')
const client = require('electron-connect').client;

//api: api.openweathermap.org/data/2.5/forecast?zip=76131,de&APPID=c314e4b540eac4e88cee00e53b7bf99f

let win

function createWindow() {
    // Create the browser window.
    win = new BrowserWindow({width: 800, height: 600})

    // and load the index.html of the app.
    win.loadURL(url.format({
        pathname: path.join(__dirname, 'app/index.html'),
        protocol: 'file:',
        slashes: true
    }))

    // Open the DevTools.
    win.webContents.openDevTools()

    // Emitted when the window is closed.
    win.on('closed', () => {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        win = null
    })
    client.create(win)
}

function defineGlobalShortcuts() {
    globalShortcut.register('CommandOrControl+X', () => {
        app.quit();
    });
}

function showWelcomeMessage() {
	dialog.showMessageBox( { type: "info", message: "Willkommen!", buttons: ["OK"] });
}

app.on('ready', createWindow)
app.on('ready', defineGlobalShortcuts)
app.on('ready', showWelcomeMessage)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (win === null) {
        createWindow()
    }
})<|endoftext|>


<commit_before>var http = require('http');
var fs = require('fs');
var formidable = require("formidable");
var util = require('util');

var server = http.createServer(function (req, res) {
    if (req.method.toLowerCase() == 'get') {
        displayForm(res);
    } else if (req.method.toLowerCase() == 'post') {
        //processAllFieldsOfTheForm(req, res);
        processFormFieldsIndividual(req, res);
    }
});

function displayForm(res) {
    fs.readFile('form.html', function (err, data) {
        res.writeHead(200, {
            'Content-Type': 'text/html',
                'Content-Length': data.length
        });
        res.write(data);
        res.end();
    });
}

function processAllFieldsOfTheForm(req, res) {
    var form = new formidable.IncomingForm();

    form.parse(req, function (err, fields, files) {
        //Store the data from the fields in your data store.
        //The data store could be a file or database or any other store based
        //on your application.
        res.writeHead(200, {
            'content-type': 'text/plain'
        });
        res.write('received the data:\n\n');
        res.end(util.inspect({
            fields: fields,
            files: files
        }));
    });
}

function processFormFieldsIndividual(req, res) {
    //Store the data from the fields in your data store.
    //The data store could be a file or database or any other store based
    //on your application.
    var fields = [];
    var form = new formidable.IncomingForm();
    //Call back when each field in the form is parsed.
    form.on('field', function (field, value) {
        console.log(field);
        console.log(value);
        fields[field] = value;
    });
    //Call back when each file in the form is parsed.
    form.on('file', function (name, file) {
        console.log(name);
        console.log(file);
        fields[name] = file;
        //Storing the files meta in fields array.
        //Depending on the application you can process it accordingly.
    });

    //Call back for file upload progress.
    form.on('progress', function (bytesReceived, bytesExpected) {
        var progress = {
            type: 'progress',
            bytesReceived: bytesReceived,
            bytesExpected: bytesExpected
        };
        console.log(progress);
        //Logging the progress on console.
        //Depending on your application you can either send the progress to client
        //for some visual feedback or perform some other operation.
    });

    //Call back at the end of the form.
    form.on('end', function () {
        res.writeHead(200, {
            'content-type': 'text/plain'
        });
        res.write('received the data:\n\n');
        res.end(util.inspect({
            fields: fields
        }));
    });
    form.parse(req);
}

server.listen(1185);
console.log("server listening on 1234");
<commit_msg>Update #4<commit_after>var http = require('http');
var fs = require('fs');
var formidable = require("formidable");
var util = require('util');

var server = http.createServer(function (req, res) {
    if (req.method.toLowerCase() == 'get') {
        displayForm(res);
    } else if (req.method.toLowerCase() == 'post') {
        //processAllFieldsOfTheForm(req, res);
        processFormFieldsIndividual(req, res);
    }
});

function displayForm(res) {
    fs.readFile('form.html', function (err, data) {
        res.writeHead(200, {
            'Content-Type': 'text/html',
                'Content-Length': data.length
        });
        res.write(data);
        res.end();
    });
}

function processAllFieldsOfTheForm(req, res) {
    var form = new formidable.IncomingForm();

    form.parse(req, function (err, fields, files) {
        //Store the data from the fields in your data store.
        //The data store could be a file or database or any other store based
        //on your application.
        res.writeHead(200, {
            'content-type': 'text/plain'
        });
        res.write('received the data:\n\n');
        res.end(util.inspect({
            fields: fields,
            files: files
        }));
    });
}

function processFormFieldsIndividual(req, res) {
    //Store the data from the fields in your data store.
    //The data store could be a file or database or any other store based
    //on your application.
    var fields = [];
    var form = new formidable.IncomingForm();
    //Call back when each field in the form is parsed.
    form.on('field', function (field, value) {
        console.log(field);
        console.log(value);
        fields[field] = value;
    });
    //Call back when each file in the form is parsed.
    form.on('file', function (name, file) {
        console.log(name);
        console.log(file);
        fields[name] = file;
        //Storing the files meta in fields array.
        //Depending on the application you can process it accordingly.
    });

    //Call back for file upload progress.
    form.on('progress', function (bytesReceived, bytesExpected) {
        var progress = {
            type: 'progress',
            bytesReceived: bytesReceived,
            bytesExpected: bytesExpected
        };
        console.log(progress);
        //Logging the progress on console.
        //Depending on your application you can either send the progress to client
        //for some visual feedback or perform some other operation.
    });

    //Call back at the end of the form.
    form.on('end', function () {
        res.writeHead(200, {
            'content-type': 'text/plain'
        });
        res.write('received the data:\n\n');
        res.end(util.inspect({
            fields: fields
        }));
    });
    form.parse(req);
}

server.listen(1185);
console.log("server listening on 1111");
<|endoftext|>


<commit_before>const path = require('path')
const dateFormat = require('dateformat')
const express = require('express')
const bodyParser = require('body-parser')
const expressValidator = require('express-validator')
const hbs = require('express-handlebars')

const index = require('./routes/index')

const app = express()

process.on('unhandledRejection', (error, promise) => {
  console.error('UNHANDLED REJECTION', error.stack)
})

// Middleware
app.engine('hbs', hbs({
  extname: 'hbs',
  defaultLayout: 'main',
  helpers: {
    selectOption: function (selected, options) {
      return options.fn(this).replace(new RegExp('value="' + `${selected}` + '"'), '$& selected="selected"').replace(new RegExp('>' + selected + '</option>'), ' selected="selected"$&')
    },
    viewFormat: function (date) {
      return dateFormat(date, 'mmmm dd yyyy')
    },
    editFormat: function (date) {
      return dateFormat(date, 'yyyy-mm-dd')
    }
  }
}))
app.set('view engine', 'hbs')
app.set('views', path.join(__dirname, 'views'))
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: true }))
app.use(expressValidator())

// Routes

app.use('/', index)

module.exports = (connection) => {
  app.set('connection', connection)
  return app
}
<commit_msg>Remove express validator<commit_after>const path = require('path')
const dateFormat = require('dateformat')
const express = require('express')
const bodyParser = require('body-parser')
const hbs = require('express-handlebars')

const index = require('./routes/index')

const app = express()

process.on('unhandledRejection', (error, promise) => {
  console.error('UNHANDLED REJECTION', error.stack)
})

// Middleware
app.engine('hbs', hbs({
  extname: 'hbs',
  defaultLayout: 'main',
  helpers: {
    selectOption: function (selected, options) {
      return options.fn(this).replace(new RegExp('value="' + `${selected}` + '"'), '$& selected="selected"').replace(new RegExp('>' + selected + '</option>'), ' selected="selected"$&')
    },
    viewFormat: function (date) {
      return dateFormat(date, 'mmmm dd yyyy')
    },
    editFormat: function (date) {
      return dateFormat(date, 'yyyy-mm-dd')
    }
  }
}))
app.set('view engine', 'hbs')
app.set('views', path.join(__dirname, 'views'))
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: true }))

// Routes

app.use('/', index)

module.exports = (connection) => {
  app.set('connection', connection)
  return app
}
<|endoftext|>


<commit_before>var recursive = require('recursive-readdir');
var Path = require("path");
var async = require("async");

var files = [];
var location = Path.join("tmp","wc4"); //TODO: this ought to be better
var output = require('./reporters/console');

var argv = require('yargs')
    .option('r', {
        alias : 'repo',
        demand: true,
        describe: 'Repository to scan',
        type: 'string',
        nargs: 1
    })
    .option('t', {
        alias : 'type',
        demand: false,
        default: 'auto',
        describe: 'Type of repository. Accepts "git", "svn", or "auto"',
        type: 'string',
        nargs: 1
    })
    .argv;

if (argv.type === 'auto') {
	if (argv.repo.indexOf('git') > -1) {
		argv.type = 'git';
		console.log("Auto-detected Git repository");
	} else if (argv.repo.indexOf('svn') > -1) {
		argv.type = 'svn';
		console.log("Auto-detected SVN repository");
	} else {
		console.log("Could not detect repository type, please be explicit!");
		return;
	}
}

var repoAdapter = require("./lib/" + argv.type.toLowerCase());

repoAdapter.init(argv.repo, location, function(err) {
	if (err) {
		output.reportErr(err);
		return;
	}
	recursive(location, [Path.join("**",".git","*"),".gitignore",Path.join("**",".svn","*")], function (err, lsFiles) {
		async.each(lsFiles,function(file, cb) {
			file = file.replace(location + Path.sep,"");
			repoAdapter.getOwner(file,function(err, owner) {
				if (!err) {
					files.push({
						"filename": file,
						"owner": owner
					});
				};
				cb(err);
			})
		}, function(err) {
			if (err) {
				output.reportErr(err);
				return;
			}

			var numfiles = files.length;
			var candidates = {};

			for (var i = 0; i < numfiles; i++) {
				var owner = files[i].owner;
				if (!candidates[owner]) {
					candidates[owner] = 0;
				}
				candidates[owner]++;
			}

			//Sort the authors
			var ownersSorted = Object.keys(candidates).sort(function(a,b){return candidates[b]-candidates[a]})
			var numAuthors = ownersSorted.length;

			var runningTotal = 0;
			var busFactor = 0;
			var dead = false;

			for (var i = 0; i < numAuthors; i++) {
				runningTotal += candidates[ownersSorted[i]];

				if (!dead) busFactor++;
				if (runningTotal >= numfiles/2 && !dead) {
					dead = true;
				}
			}

			var data = {
				"numfiles": numfiles,
				"files": files,
				"numAuthors": numAuthors,
				"owners": candidates,
				"ownersSorted": ownersSorted,
				"busFactor": busFactor
			};

			output.report(data);

		});
	});

})<commit_msg>Fix reportError typo<commit_after>var recursive = require('recursive-readdir');
var Path = require("path");
var async = require("async");

var files = [];
var location = Path.join("tmp","wc4"); //TODO: this ought to be better
var output = require('./reporters/console');

var argv = require('yargs')
    .option('r', {
        alias : 'repo',
        demand: true,
        describe: 'Repository to scan',
        type: 'string',
        nargs: 1
    })
    .option('t', {
        alias : 'type',
        demand: false,
        default: 'auto',
        describe: 'Type of repository. Accepts "git", "svn", or "auto"',
        type: 'string',
        nargs: 1
    })
    .argv;

if (argv.type === 'auto') {
	if (argv.repo.indexOf('git') > -1) {
		argv.type = 'git';
		console.log("Auto-detected Git repository");
	} else if (argv.repo.indexOf('svn') > -1) {
		argv.type = 'svn';
		console.log("Auto-detected SVN repository");
	} else {
		console.log("Could not detect repository type, please be explicit!");
		return;
	}
}

var repoAdapter = require("./lib/" + argv.type.toLowerCase());

repoAdapter.init(argv.repo, location, function(err) {
	if (err) {
		output.reportErr(err);
		return;
	}
	recursive(location, [Path.join("**",".git","*"),".gitignore",Path.join("**",".svn","*")], function (err, lsFiles) {
		async.each(lsFiles,function(file, cb) {
			file = file.replace(location + Path.sep,"");
			repoAdapter.getOwner(file,function(err, owner) {
				if (!err) {
					files.push({
						"filename": file,
						"owner": owner
					});
				};
				cb(err);
			})
		}, function(err) {
			if (err) {
				output.reportError(err);
				return;
			}

			var numfiles = files.length;
			var candidates = {};

			for (var i = 0; i < numfiles; i++) {
				var owner = files[i].owner;
				if (!candidates[owner]) {
					candidates[owner] = 0;
				}
				candidates[owner]++;
			}

			//Sort the authors
			var ownersSorted = Object.keys(candidates).sort(function(a,b){return candidates[b]-candidates[a]})
			var numAuthors = ownersSorted.length;

			var runningTotal = 0;
			var busFactor = 0;
			var dead = false;

			for (var i = 0; i < numAuthors; i++) {
				runningTotal += candidates[ownersSorted[i]];

				if (!dead) busFactor++;
				if (runningTotal >= numfiles/2 && !dead) {
					dead = true;
				}
			}

			var data = {
				"numfiles": numfiles,
				"files": files,
				"numAuthors": numAuthors,
				"owners": candidates,
				"ownersSorted": ownersSorted,
				"busFactor": busFactor
			};

			output.report(data);

		});
	});

})
<|endoftext|>


<commit_before>"use strict";

class Player{

    constructor(id, name, collisionObject)
    {
        this.id = id;
        this.name = name;
        this.collisionObject = collisionObject;
    }
}

class PlayerManager{

    constructor(world)
    {
        this.players = new Map();
        this.world = world;
        this.playerCount = 0;
    }

    getPlayerAsJson(player)
    {
        if(player.collisionObject && typeof player.collisionObject.toJSON == "function")
        {
            return JSON.stringify({"id":player.id, "name":player.name, "physProps":player.collisionObject.toJSON()});
        }
        else
        {
            console.log("Could not get collision information from player, collisionObject was of Type \""+typeof player.collisionObject+"\"");
            return null;
        }
    }

    getUniqueId()
    {
        this.playerCount++;
        return this.playerCount;
    }

    createPlayer(name)
    {
        var uId = this.getUniqueId();
        this.players.set(uId, new Player(uId, name));
    }

}<commit_msg>* player manager finished I think<commit_after>"use strict";

class Player{

    constructor(id, name, team, collisionObject)
    {
        this.id = id;
        this.name = name;
        this.team = team;
        this.collisionObject = collisionObject;
    }
}

class PlayerManager{

    constructor(world)
    {
        this.players = new Map();
        this.world = world;
        this.playerCount = 0;
    }

    getPlayerAsJson(player)
    {
        if(player.collisionObject && typeof player.collisionObject.toJSON == "function")
        {
            return JSON.stringify({"id":player.id, "name":player.name, "team":player.team, "physProps":player.collisionObject.toJSON()});
        }
        else
        {
            console.log("Could not get collision information from player, collisionObject was of Type \""+typeof player.collisionObject+"\"");
            return null;
        }
    }

    getOtherPlayers(player)
    {
        var players = [];
        for(var id in this.players)
        {
            if(id !== player.id)
            {
                players.push(this.players[id]);
            }
        }

        return players;
    }

    getUniqueId()
    {
        this.playerCount++;
        return this.playerCount;
    }

    createPlayer(name, team, position, radius)
    {
        var uId = this.getUniqueId(),
            playerCollider = this.world.createPlayerCollider(position, radius),
            player = new Player(uId, name, team, playerCollider);

        this.players.set(uId, player);

        return player;
    }

}<|endoftext|>


<commit_before>require('shelljs/make');

var fs      = require('fs');
var path    = require('path');
var spawn   = require('child_process').spawn;

var _        = require('lodash');
var shell    = require('shelljs');
var chokidar = require('chokidar');
var express  = require('express');
/*var tgz    = */ require('express-tgz');

var meteor_bin = process.platform == 'win32' ? 'meteor.bat' : 'meteor';
var node_bin = process.platform == 'win32' ? 'node.exe' : 'node';

var NODE_MODS = path.join(__dirname, 'node_modules');
var ISTANBUL  = path.join(NODE_MODS, 'istanbul', 'lib', 'cli.js');
var _MOCHA    = path.join(NODE_MODS, 'mocha', 'bin', '_mocha');
var _MOCHA    = path.join(NODE_MODS, 'mocha', 'bin', '_mocha');
var NPMCHECK  = path.join(NODE_MODS, 'npm-check', 'lib', 'cli.js');

// setup local env with local symlinks and proper configs
target.setup = function() {
  log('setting up everything for development');

  // serve tar package
  target.tar();

  // list folder paths
  var parent                 = path.join(__dirname, '..');
  var leaderboard            = path.join(parent, 'leaderboard');
  var packages_dir           = path.join(leaderboard, 'packages');
  var node_modules           = path.join(parent, 'node_modules');
  var node_modules_electrify = path.join(node_modules, 'electrify');

  // reset folders
  shell.rm('-rf', leaderboard);
  shell.rm('-rf', node_modules);

  // create sample test app in parent dir
  spawn(meteor_bin, ['create', '--example', 'leaderboard'], {
    stdio: 'inherit',
    cwd: parent
  }).on('exit', function(){

    // linking electrify inside it
    shell.mkdir('-p', packages_dir);
    shell.ln('-s', __dirname, path.join(packages_dir, 'arboleya-electrify'));

    // linking also a parent node_modules
    shell.mkdir('-p', node_modules);
    shell.ln('-s', __dirname, node_modules_electrify);

    // removes mobile platforms
    spawn(meteor_bin, ['remove-platform', 'ios', 'android'], {
      stdio: 'inherit',
      cwd: leaderboard
    }).on('exit', function(){

      // adding electrify package so everything gets cool
      spawn(meteor_bin, ['add', 'arboleya:electrify'], {
        stdio: 'inherit',
        cwd: leaderboard,
        // modify env var so electrify package will know how to proceed,
        // fetching the npm package locally or from remote npm registry
        env: _.extend({DEVELECTRIFY: true, LOGELECTRIFY: 'ALL'}, process.env)

      // finish
      }).on('exit', function(){
        process.exit();
      });

    });
  });

};

// start test app in dev mode
target.dev = function(){
  var meteor;
  var electyrify_npm       = path.join(__dirname, '..', '.npm');
  var leaderboard           = path.join(__dirname, '..', 'leaderboard');
  var leaderboard_electrify = path.join(leaderboard, '.electrify');

  shell.rm('-rf', electyrify_npm);
  shell.rm('-rf', leaderboard_electrify);

  log('starting in dev mode');

  // starts tar server
  target.tar();

  // watch changes and restart the whole process
  chokidar.watch(__dirname, {
    ignored: /[\\\/]\.|test|node_modules|\.md\.npm/
  }).on('all', _.debounce(restart, 100));

  function restart(/* event, path */){

    if(meteor) {
      console.log('+++++ ELECTRIFY RESTART +++++');
      meteor.kill();
    }

    setTimeout(function(){

      shell.rm('-rf', path.join(__dirname, '.npm', 'package', 'node_modules'));
      shell.rm('-rf', path.join(leaderboard, '.meteor', 'local'));

      meteor = spawn(meteor_bin, [], {
        stdio: 'inherit',
        cwd: leaderboard,
        env: _.extend({DEVELECTRIFY: true, LOGELECTRIFY: 'ALL'}, process.env)
      });
    }, 2500);
  }
};

// start serving tar.gz version of electrify package
target.tar = function(){
  log('serving tar package');

  var app  = express();
  var sha = 'bf658fd1c03d53ba0d0eb87b1a853eb34ade362e';

  app.get('/' + sha, function(req, res) {
    res.tgz('../electrify/', sha + '.tar.gz', true);
  });

  return app.listen(7777);
};

// tests
target.test = function() {
  var server = target.tar();
  spawn(node_bin, [_MOCHA, 'test'], {
    stdio: 'inherit',
    env: _.extend({DEVELECTRIFY: true, LOGELECTRIFY: 'ALL'}, process.env)
  }).on('exit', function() {
    server.close();
  });
};

target['test.cover'] = function(done){
  var server = target.tar();
  spawn(node_bin, [ISTANBUL, 'cover', _MOCHA], {
    stdio: 'inherit',
    env: _.extend({DEVELECTRIFY: true, LOGELECTRIFY: 'ALL'}, process.env)
  }).on('exit', function(){
    server.close();
    if(done) done();
  });
};

target['test.cover.preview'] = function(){
  target['test.cover'](function(){
    if(!fs.existsSync('./coverage/lcov-report')) return;
    spawn('python', ['-m', 'SimpleHTTPServer', '8080'], {
      cwd: './coverage/lcov-report',
      stdio: 'inherit',
      env: _.extend({DEVELECTRIFY: true, LOGELECTRIFY: 'ALL'}, process.env)
    });
    console.log('preview coverage at: http://localhost:8080');
  });
};

target['test.cover.send'] = function() {
  var repo_token = process.env.CODECLIMATE_REPO_TOKEN;

  if(repo_token === undefined || repo_token.trim() === '') {
    console.error('No CODECLIMATE_REPO_TOKEN found.');
    process.exit(1);
  }

  target['test.cover'](function(){
    // reads lcov data
    var lcov_path   = path.join(__dirname, 'coverage', 'lcov.info');
    var lcov        = fs.readFileSync(lcov_path, 'utf-8');

    var node_mods = path.join(
      __dirname,
      'node_modules',
      'codeclimate-test-reporter'
    );

    var Formatter = require(path.join(node_mods, 'formatter'));
    var client    = require(path.join(node_mods, 'http_client'));

    var formatter = new Formatter();
    formatter.format(lcov, function(err, json) {
      if (err)
        console.error("A problem occurred parsing the lcov data", err);
      else {
        json.repo_token = repo_token;
        client.postJson(json);
        console.log('coverage sent to codeclimate');
      }
    });
  });
};

target['deps.check'] = function(){
  spawn(node_bin, [NPMCHECK], {
    stdio: 'inherit'
  });
};

target['deps.upgrade'] = function(){
  spawn(node_bin, [NPMCHECK, '-u'], {
    stdio: 'inherit'
  });
};

target.publish = function(){
  var version = require('./package.json').version;
  shell.exec('git tag -a $(VERSION) -m "Releasing '+ version +'")');
  shell.exec('git push origin master --tags');
  shell.exec('npm publish');
  shell.exec('meteor publish');
};

function log(){
  var args = Array.prototype.slice.call(arguments);
  console.log.apply(null, ['electrify: '].concat(args));
}<commit_msg>fixing publish target<commit_after>require('shelljs/make');

var fs      = require('fs');
var path    = require('path');
var spawn   = require('child_process').spawn;

var _        = require('lodash');
var shell    = require('shelljs');
var chokidar = require('chokidar');
var express  = require('express');
/*var tgz    = */ require('express-tgz');

var meteor_bin = process.platform == 'win32' ? 'meteor.bat' : 'meteor';
var node_bin = process.platform == 'win32' ? 'node.exe' : 'node';

var NODE_MODS = path.join(__dirname, 'node_modules');
var ISTANBUL  = path.join(NODE_MODS, 'istanbul', 'lib', 'cli.js');
var _MOCHA    = path.join(NODE_MODS, 'mocha', 'bin', '_mocha');
var _MOCHA    = path.join(NODE_MODS, 'mocha', 'bin', '_mocha');
var NPMCHECK  = path.join(NODE_MODS, 'npm-check', 'lib', 'cli.js');

// setup local env with local symlinks and proper configs
target.setup = function() {
  log('setting up everything for development');

  // serve tar package
  target.tar();

  // list folder paths
  var parent                 = path.join(__dirname, '..');
  var leaderboard            = path.join(parent, 'leaderboard');
  var packages_dir           = path.join(leaderboard, 'packages');
  var node_modules           = path.join(parent, 'node_modules');
  var node_modules_electrify = path.join(node_modules, 'electrify');

  // reset folders
  shell.rm('-rf', leaderboard);
  shell.rm('-rf', node_modules);

  // create sample test app in parent dir
  spawn(meteor_bin, ['create', '--example', 'leaderboard'], {
    stdio: 'inherit',
    cwd: parent
  }).on('exit', function(){

    // linking electrify inside it
    shell.mkdir('-p', packages_dir);
    shell.ln('-s', __dirname, path.join(packages_dir, 'arboleya-electrify'));

    // linking also a parent node_modules
    shell.mkdir('-p', node_modules);
    shell.ln('-s', __dirname, node_modules_electrify);

    // removes mobile platforms
    spawn(meteor_bin, ['remove-platform', 'ios', 'android'], {
      stdio: 'inherit',
      cwd: leaderboard
    }).on('exit', function(){

      // adding electrify package so everything gets cool
      spawn(meteor_bin, ['add', 'arboleya:electrify'], {
        stdio: 'inherit',
        cwd: leaderboard,
        // modify env var so electrify package will know how to proceed,
        // fetching the npm package locally or from remote npm registry
        env: _.extend({DEVELECTRIFY: true, LOGELECTRIFY: 'ALL'}, process.env)

      // finish
      }).on('exit', function(){
        process.exit();
      });

    });
  });

};

// start test app in dev mode
target.dev = function(){
  var meteor;
  var electyrify_npm       = path.join(__dirname, '..', '.npm');
  var leaderboard           = path.join(__dirname, '..', 'leaderboard');
  var leaderboard_electrify = path.join(leaderboard, '.electrify');

  shell.rm('-rf', electyrify_npm);
  shell.rm('-rf', leaderboard_electrify);

  log('starting in dev mode');

  // starts tar server
  target.tar();

  // watch changes and restart the whole process
  chokidar.watch(__dirname, {
    ignored: /[\\\/]\.|test|node_modules|\.md\.npm/
  }).on('all', _.debounce(restart, 100));

  function restart(/* event, path */){

    if(meteor) {
      console.log('+++++ ELECTRIFY RESTART +++++');
      meteor.kill();
    }

    setTimeout(function(){

      shell.rm('-rf', path.join(__dirname, '.npm', 'package', 'node_modules'));
      shell.rm('-rf', path.join(leaderboard, '.meteor', 'local'));

      meteor = spawn(meteor_bin, [], {
        stdio: 'inherit',
        cwd: leaderboard,
        env: _.extend({DEVELECTRIFY: true, LOGELECTRIFY: 'ALL'}, process.env)
      });
    }, 2500);
  }
};

// start serving tar.gz version of electrify package
target.tar = function(){
  log('serving tar package');

  var app  = express();
  var sha = 'bf658fd1c03d53ba0d0eb87b1a853eb34ade362e';

  app.get('/' + sha, function(req, res) {
    res.tgz('../electrify/', sha + '.tar.gz', true);
  });

  return app.listen(7777);
};

// tests
target.test = function() {
  var server = target.tar();
  spawn(node_bin, [_MOCHA, 'test'], {
    stdio: 'inherit',
    env: _.extend({DEVELECTRIFY: true, LOGELECTRIFY: 'ALL'}, process.env)
  }).on('exit', function() {
    server.close();
  });
};

target['test.cover'] = function(done){
  var server = target.tar();
  spawn(node_bin, [ISTANBUL, 'cover', _MOCHA], {
    stdio: 'inherit',
    env: _.extend({DEVELECTRIFY: true, LOGELECTRIFY: 'ALL'}, process.env)
  }).on('exit', function(){
    server.close();
    if(done) done();
  });
};

target['test.cover.preview'] = function(){
  target['test.cover'](function(){
    if(!fs.existsSync('./coverage/lcov-report')) return;
    spawn('python', ['-m', 'SimpleHTTPServer', '8080'], {
      cwd: './coverage/lcov-report',
      stdio: 'inherit',
      env: _.extend({DEVELECTRIFY: true, LOGELECTRIFY: 'ALL'}, process.env)
    });
    console.log('preview coverage at: http://localhost:8080');
  });
};

target['test.cover.send'] = function() {
  var repo_token = process.env.CODECLIMATE_REPO_TOKEN;

  if(repo_token === undefined || repo_token.trim() === '') {
    console.error('No CODECLIMATE_REPO_TOKEN found.');
    process.exit(1);
  }

  target['test.cover'](function(){
    // reads lcov data
    var lcov_path   = path.join(__dirname, 'coverage', 'lcov.info');
    var lcov        = fs.readFileSync(lcov_path, 'utf-8');

    var node_mods = path.join(
      __dirname,
      'node_modules',
      'codeclimate-test-reporter'
    );

    var Formatter = require(path.join(node_mods, 'formatter'));
    var client    = require(path.join(node_mods, 'http_client'));

    var formatter = new Formatter();
    formatter.format(lcov, function(err, json) {
      if (err)
        console.error("A problem occurred parsing the lcov data", err);
      else {
        json.repo_token = repo_token;
        client.postJson(json);
        console.log('coverage sent to codeclimate');
      }
    });
  });
};

target['deps.check'] = function(){
  spawn(node_bin, [NPMCHECK], {
    stdio: 'inherit'
  });
};

target['deps.upgrade'] = function(){
  spawn(node_bin, [NPMCHECK, '-u'], {
    stdio: 'inherit'
  });
};

target.publish = function(){
  var version = require('./package.json').version;
  shell.exec('git tag -a '+ version +' -m "Releasing '+ version +'")');
  shell.exec('git push origin master --tags');
  shell.exec('npm publish');
  shell.exec('meteor publish');
};

function log(){
  var args = Array.prototype.slice.call(arguments);
  console.log.apply(null, ['electrify: '].concat(args));
}<|endoftext|>


<commit_before>/* Copyright (c) 2013-present The TagSpaces Authors.
 * Use of this source code is governed by the MIT license which can be found in the LICENSE.txt file. */
/* globals Handlebars, Nanobar, marked */
'use strict';

var isCordova;

var isWin;
var isWeb = (document.URL.startsWith('http') && !document.URL.startsWith('http://localhost:1212/'));
var JSZip, JSZipUtils;
var maxPreviewSize = (1024 * 3) || {}; //3kb limit for preview

$(document).ready(function() {
  function getParameterByName(name) {
    name = name.replace(/[\[]/ , '\\\[').replace(/[\]]/ , '\\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)') ,
            results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g , ' '));
  }

  var locale = getParameterByName('locale');
  var filePath = getParameterByName('file');

  var extSettings;
  loadExtSettings();

  // isCordova = parent.isCordova;
  // isWin = parent.isWin;

  initI18N(locale, 'ns.viewerZIP.json');

  function loadExtSettings() {
    extSettings = JSON.parse(localStorage.getItem('viewerZIPSettings'));
  }

  JSZipUtils.getBinaryContent(filePath , function(err, data) {
    if (err) {
      throw err; // or handle err
    }
    JSZip.loadAsync(data).then(function(data) {
      loadZipFile(data, filePath);
    });
    //JSZip.loadAsync(data).then(function (zip) {
    //  var re = /(.jpg|.png|.gif|.ps|.jpeg)$/;
    //  var promises = Object.keys(zip.files).filter(function(fileName) {
    //    // don't consider non image files
    //    console.log(fileName);
    //    return re.test(fileName.toLowerCase());
    //  })
    //});
    //  Object.keys(zip.files).map(function (fileName) {
    //    var file = zip.files[fileName];
    //    return file.async("text").then(function (blob) {
    //      console.log(blob);
    //      return [
    //        fileName,  // keep the link between the file name and the content
    //        URL.createObjectURL(blob) // create an url. img.src = URL.createObjectURL(...) will work
    //      ];
    //    });
    //  });
    //  // `promises` is an array of promises, `Promise.all` transforms it
    //  // into a promise of arrays
    //  return Promise.all(promises);
    //}).then(function (result) {
    //  // we have here an array of [fileName, url]
    //  // if you want the same result as imageSrc:
    //  return result.reduce(function (acc, val) {
    //    acc[val[0]] = val[1];
    //    return acc;
    //  }, {});
    //}).catch(function (e) {
    //  console.error(e);
    //});
  });
});

function loadZipFile(zipFile, filePath) {
  var $zipContent = $('#zipContent');

  $zipContent.append(zipFile);

  // if (filePath.indexOf('file://') === 0) {
  //   filePath = filePath.substring(('file://').length , filePath.length);
  // }

  $zipContent.append('
').css({
    'overflow': 'auto' ,
    'padding': '5px' ,
    'background-color': 'white' ,
    'fontSize': 12 ,
    'width': '100%' ,
    'height': '100%'
  });
  $zipContent.append('

 Contents of file ' + filePath + '

');
  var ulFiles = $zipContent.append('
');

  function showPreviewDialog(event) {
    event.preventDefault();
    var containFile = zipFile.files[$(this).text()];
    containFile.options.compression = 'STORE';
    containFile.async("text").then(function (blob) {
      showContentFilePreviewDialog(blob);
      //return [
      //  fileName,  // keep the link between the file name and the content
      //  URL.createObjectURL(blob) // create an url. img.src = URL.createObjectURL(...) will work
      //];
    });
  }

  if (!!Object.keys(zipFile.files) &&
    (typeof zipFile !== 'function' ||
    zipFile === null)) {
    for (var fileName in zipFile.files) {
      if (zipFile.files[fileName].dir === true) {
        continue;
      }
      var linkToFile = $('').attr('href' , '#').text(fileName);
      linkToFile.click(showPreviewDialog);
      var liFile = $('
').css('list-style-type' , 'none').append(linkToFile);
      ulFiles.append(liFile);
    }
  } else {
    throw new TypeError('Object.keys called on non-object');
  }
}

function showContentFilePreviewDialog(containFile) {
  //var unitArr = containFile._data.compressedContent;
  var previewText = '';
  //var byteLength = (unitArr.byteLength > maxPreviewSize) ? maxPreviewSize : unitArr.byteLength;

  //for (var i = 0; i < byteLength; i++) {
  //  previewText += String.fromCharCode(unitArr[i]);
  //}
  previewText = containFile;
  var fileContent = $('
').text(previewText);

  $.post('previewDialog.html' , function(uiTPL) {
    if ($('#previewDialog').length < 1) {
      var uiTemplate = Handlebars.compile(uiTPL);
      $('body').append(uiTemplate());
    }
    var dialogPreview = $('#previewDialog');
    dialogPreview.find('.modal-body').empty().append(fileContent);
    dialogPreview.modal({
      backdrop: 'static' ,
      show: true
    });
    var nanobar = new Nanobar({
      bg: '#42BEDB' , //(optional) background css property, '#000' by default
      target: document.getElementById('nanoBar') , //(optional) Where to put the progress bar, nanobar will be fixed to top of document if target is null
      // id for new nanobar
      id: 'nanoBar' // (optional) id for nanobar d
    });

    var progressChunk = parseInt(byteLength / 100);
    var currentProgress = 0;
    for (var i = 0; i < byteLength; i++) {
      var check = ((i % progressChunk) === 0);
      if (check) {
        currentProgress++;
        if (currentProgress <= 100) {
          nanobar.go(currentProgress);
        }
      }
      previewText += String.fromCharCode(unitArr[i]);
    }
  }).always(function() {
    window.setTimeout(function() {
      document.getElementById('nanoBar').remove();
    } , 1000);
  });
}
<commit_msg>cleaned content<commit_after>/* Copyright (c) 2013-present The TagSpaces Authors.
 * Use of this source code is governed by the MIT license which can be found in the LICENSE.txt file. */
/* globals Handlebars, Nanobar, marked */
'use strict';

var isCordova;

var isWin;
var isWeb = (document.URL.startsWith('http') && !document.URL.startsWith('http://localhost:1212/'));
var JSZip, JSZipUtils;
var maxPreviewSize = (1024 * 3) || {}; //3kb limit for preview

$(document).ready(function() {
  var locale = getParameterByName('locale');
  var filePath = getParameterByName('file');
  initI18N(locale, 'ns.viewerZIP.json');

  var extSettings;
  loadExtSettings();

  function loadExtSettings() {
    extSettings = JSON.parse(localStorage.getItem('viewerZIPSettings'));
  }

  JSZipUtils.getBinaryContent(filePath , function(err, data) {
    if (err) {
      throw err; // or handle err
    }
    JSZip.loadAsync(data).then(function(data) {
      loadZipFile(data, filePath);
    });
    //JSZip.loadAsync(data).then(function (zip) {
    //  var re = /(.jpg|.png|.gif|.ps|.jpeg)$/;
    //  var promises = Object.keys(zip.files).filter(function(fileName) {
    //    // don't consider non image files
    //    console.log(fileName);
    //    return re.test(fileName.toLowerCase());
    //  })
    //});
    //  Object.keys(zip.files).map(function (fileName) {
    //    var file = zip.files[fileName];
    //    return file.async("text").then(function (blob) {
    //      console.log(blob);
    //      return [
    //        fileName,  // keep the link between the file name and the content
    //        URL.createObjectURL(blob) // create an url. img.src = URL.createObjectURL(...) will work
    //      ];
    //    });
    //  });
    //  // `promises` is an array of promises, `Promise.all` transforms it
    //  // into a promise of arrays
    //  return Promise.all(promises);
    //}).then(function (result) {
    //  // we have here an array of [fileName, url]
    //  // if you want the same result as imageSrc:
    //  return result.reduce(function (acc, val) {
    //    acc[val[0]] = val[1];
    //    return acc;
    //  }, {});
    //}).catch(function (e) {
    //  console.error(e);
    //});
  });
});

function loadZipFile(zipFile, filePath) {
  var $zipContent = $('#zipContent');

  $zipContent.append(zipFile);

  // if (filePath.indexOf('file://') === 0) {
  //   filePath = filePath.substring(('file://').length , filePath.length);
  // }

  $zipContent.append('
').css({
    'overflow': 'auto' ,
    'padding': '5px' ,
    'background-color': 'white' ,
    'fontSize': 12 ,
    'width': '100%' ,
    'height': '100%'
  });
  $zipContent.append('

 Contents of file ' + filePath + '

');
  var ulFiles = $zipContent.append('
');

  function showPreviewDialog(event) {
    event.preventDefault();
    var containFile = zipFile.files[$(this).text()];
    containFile.options.compression = 'STORE';
    containFile.async("text").then(function (blob) {
      showContentFilePreviewDialog(blob);
      //return [
      //  fileName,  // keep the link between the file name and the content
      //  URL.createObjectURL(blob) // create an url. img.src = URL.createObjectURL(...) will work
      //];
    });
  }

  if (!!Object.keys(zipFile.files) &&
    (typeof zipFile !== 'function' ||
    zipFile === null)) {
    for (var fileName in zipFile.files) {
      if (zipFile.files[fileName].dir === true) {
        continue;
      }
      var linkToFile = $('').attr('href' , '#').text(fileName);
      linkToFile.click(showPreviewDialog);
      var liFile = $('
').css('list-style-type' , 'none').append(linkToFile);
      ulFiles.append(liFile);
    }
  } else {
    throw new TypeError('Object.keys called on non-object');
  }
}

function showContentFilePreviewDialog(containFile) {
  var unitArr = containFile;
  var previewText = '';
  var byteLength = (unitArr.byteLength > maxPreviewSize) ? maxPreviewSize : unitArr.byteLength;

  for (var i = 0; i < byteLength; i++) {
    previewText += String.fromCharCode(unitArr[i]);
  }
  previewText = containFile;
  var fileContent = $('
').text(previewText);

  $.post('previewDialog.html' , function(uiTPL) {
    if ($('#previewDialog').length < 1) {
      var uiTemplate = Handlebars.compile(uiTPL);
      $('body').append(uiTemplate());
    }
    var dialogPreview = $('#previewDialog');
    dialogPreview.find('.modal-body').empty().append(fileContent);
    dialogPreview.modal({
      backdrop: 'static' ,
      show: true
    });
    var nanobar = new Nanobar({
      bg: '#42BEDB' , //(optional) background css property, '#000' by default
      target: document.getElementById('nanoBar') , //(optional) Where to put the progress bar, nanobar will be fixed to top of document if target is null
      // id for new nanobar
      id: 'nanoBar' // (optional) id for nanobar d
    });

    var progressChunk = parseInt(byteLength / 100);
    var currentProgress = 0;
    for (var i = 0; i < byteLength; i++) {
      var check = ((i % progressChunk) === 0);
      if (check) {
        currentProgress++;
        if (currentProgress <= 100) {
          nanobar.go(currentProgress);
        }
      }
      previewText += String.fromCharCode(unitArr[i]);
    }
  }).always(function() {
    window.setTimeout(function() {
      document.getElementById('nanoBar').remove();
    } , 1000);
  });
}
<|endoftext|>


<commit_before>const Transform = require('stream').Transform;
const util = require('util');

exports.init = function (args, ready) {
    console.log('Dummy.init:', this._name);
    ready();
    //ready(new Error('Hello, Error!'));
};

exports.data = function (args, chunk, next) {
    console.log('Dummy.data:', this._name, chunk);
    next(null, chunk);
};

exports.stream = function (args, stream) {
    const self = this;
    return new Transform({
        objectMode: args.objectMode !== undefined ? args.objectMode : true,
        transform: (chunk, enc, next) => {
            console.log('Dummy.stream.data:', self._name, chunk);
            next(null, chunk);
        }
    });
};
<commit_msg>emit errors for testing<commit_after>const Transform = require('stream').Transform;
const util = require('util');

exports.init = function (args, ready) {
    console.log('Dummy.init:', this._name);
    ready();
    //ready(new Error('Hello, Error!'));
};

exports.data = function (args, chunk, next) {
    console.log('Dummy.data:', this._name, chunk);
    next(null, chunk);
    //next(new Error('Hello, Error!'));
};

exports.stream = function (args, stream) {
    const self = this;
    return new Transform({
        objectMode: args.objectMode !== undefined ? args.objectMode : true,
        transform: (chunk, enc, next) => {
            console.log('Dummy.stream.data:', self._name, chunk);
            next(null, chunk);
            //next(new Error('Hello, Error!'));
        }
    });
};
<|endoftext|>


<commit_before>var express = require('express')
var app = express()
var router = express.Router()
var factstore = require('./dummyfactstore')
var port = process.env.PORT || 8080;
var bodyParser = require( 'body-parser' )
var modRewrite = require('connect-modrewrite')

factStore = new factstore()
router.get('/date/:date', function(req, res) {
  factStore.getByDate(req.params.date)
  .then(function(facts) {
    res.json(facts)
  })
  .catch(function(err) {
    res.send(err)
  })
})

// app.use(modRewrite([
//   '^/wikifactmine-api(.*) /$1'
// ]))
app.use(bodyParser.json())
app.use('/api', router)
app.use('/wikifactmine-api/api', router)
app.get('/wikifactmine-api', function (req, res) {
  res.sendFile(__dirname + '/dist/index.html')
});
app.get('/', function (req, res) {
  res.sendFile(__dirname + '/dist/index.html')
});
app.use(express.static('dist'))

app.listen(port)
<commit_msg>add hacky static serving as welll<commit_after>var express = require('express')
var app = express()
var router = express.Router()
var factstore = require('./dummyfactstore')
var port = process.env.PORT || 8080;
var bodyParser = require( 'body-parser' )
var modRewrite = require('connect-modrewrite')

factStore = new factstore()
router.get('/date/:date', function(req, res) {
  factStore.getByDate(req.params.date)
  .then(function(facts) {
    res.json(facts)
  })
  .catch(function(err) {
    res.send(err)
  })
})

// app.use(modRewrite([
//   '^/wikifactmine-api(.*) /$1'
// ]))
app.use(bodyParser.json())
app.use('/api', router)
app.use('/wikifactmine-api/api', router)
app.get('/wikifactmine-api', function (req, res) {
  res.sendFile(__dirname + '/dist/index.html')
});
app.get('/', function (req, res) {
  res.sendFile(__dirname + '/dist/index.html')
});
app.use(express.static('dist'))
app.use('/wikifactmine-api/', express.static('dist'))

app.listen(port)
<|endoftext|>