<commit_before>/*jslint devel: true*/
/*global perfis */

// variables
var project, beam, v, m, lbForm, section, steel, fyForm, fuForm, EForm, ml, d, bf, tw, tf, h, dl, area, ix, wx, rx, zx, iy, wy, ry, zy, rt, it, mesa, alma, cw, u, fy, fu, E, aw, gama, gama1, cb, kv, lb, kc, tr, beta1, a, lambV, lambpV, lambrV, vpl, vrd, mpl, lambA, lambpA, lambrA, mrA, mcrA, mrdA, lambM, lambpM, lambrM, mrM, mcrM, mrdM, lambT, lambpT, lambrT, mrT, mcrT, mrdT, vsd, msd, vrd, mrd, mrdOut, situationV, situationA, situationM, situationT, result;

var steelProp = [
    {
        "steelType": "ASTM A36/ MR250",
        "fy": 250,
        "fu": 400,
        "E": 200000
    },
    {
        "steelType": "ASTM A572 G50/ AR345",
        "fy": 345,
        "fu": 450,
        "E": 200000
    },
    {
        "steelType": "ASTM A572 G50/ AR345",
        "fy": 345,
        "fu": 450,
        "E": 200000
    }
];

function processFormCS() {
    "use strict";
    var i, j;

    // Getting values from HTML form inputs
    project = document.formCS.projectCS.value;
    if (project === "") {
        alert("Por favor preencha o campo Projeto.");
        console.log("Por favor preencha o campo Projeto.");
        return false;
    }
    beam = document.formCS.beamCS.value;
    if (beam === "") {
        alert("Por favor preencha o campo Viga.");
        console.log("Por favor preencha o campo Viga.");
        return false;
    }
    v = Number(document.formCS.vCS.value);
    if (document.formCS.vCS.value === "" || isNaN(v)) {
        alert("Por favor preencha o campo Cortante com números.");
        console.log("Por favor preencha o campo Cortante.");
        return false;
    }
    m = Number(document.formCS.mCS.value);
    if (document.formCS.mCS.value === "" || isNaN(m)) {
        alert("Por favor preencha o campo Momento com números.");
        console.log("Por favor preencha o campo Momento.");
        return false;
    }
    lbForm = Number(document.formCS.lbCS.value);
    if (document.formCS.lbCS.value === "" || isNaN(lbForm)) {
        alert("Por favor preencha o campo Distância entre travamentos laterais com números.");
        console.log("Por favor preencha o campo Distância entre travamentos laterais com números.");
        return false;
    }
    section = perfis[Number(document.formCS.sectionS.value)].bitola;
    steel = steelProp[Number(document.formCS.typeS.value)].steelType;
    a = Number(document.formCS.aCS.value);
    gama = Number(document.formCS.gama.value);
    gama1 = Number(document.formCS.gama1.value);
    cb = Number(document.formCS.cb.value);

    // Getting section properties
    i = Number(document.getElementById("bitola").value);

    ml = perfis[i].ml;
    d = perfis[i].d;
    bf = perfis[i].bf;
    tw = perfis[i].tw;
    tf = perfis[i].tf;
    h = perfis[i].h;
    dl = perfis[i].dl;
    area = perfis[i].area;
    ix = perfis[i].ix;
    wx = perfis[i].wx;
    rx = perfis[i].rx;
    zx = perfis[i].zx;
    iy = perfis[i].iy;
    wy = perfis[i].wy;
    ry = perfis[i].ry;
    zy = perfis[i].zy;
    it = perfis[i].it;
    mesa = perfis[i].mesa;
    alma = perfis[i].alma;
    cw = perfis[i].cw;
    u = perfis[i].u;

    // Getting values from steel properties array
    j = Number(document.getElementById("acos").value);

    fyForm = steelProp[j].fy;
    fuForm = steelProp[j].fu;
    EForm = steelProp[j].E;

    // Calculating kv
    if (((a / h) > 3) || ((a / h) > Math.pow(260 / (h / tw), 2)) || (document.getElementById("stiffeningCS").checked === true)) {
        kv = 5;
    } else {
        kv = 5 + 5 / (Math.pow(a / h, 2));
    }

    // Calculating parameters
    aw = d * tw;
    lb = lbForm * 100;
    fy = fyForm / 10;
    fu = fuForm / 10;
    E = EForm / 10;
    beta1 = (0.7 * fy * wx) / (E * it);
    kc = 4 / Math.sqrt(h / tw);
    tr = 0.3 * fy;

    // Shear Vrd
    lambV = h / tw;
    lambpV = (1.1 * Math.sqrt(kv * E / fy));
    lambrV = (1.37 * Math.sqrt(kv * E / fy));
    vpl = 0.6 * fy * aw;

    if (lambV <= lambpV) {
        situationV = "Caso 1";
    } else if (lambpV < lambV && lambV <= lambrV) {
        situationV = "Caso 2";
    } else if (lambrV < lambV) {
        situationV = "Caso 3";
    } else {
        situationV = "Error";
    }

    switch (situationV) {
    case "Caso 1":
        vrd = vpl / gama1;
        break;
    case "Caso 2":
        vrd = (lambpV / lambV) * (vpl / gama1);
        break;
    case "Caso 3":
        vrd = 1.24 * Math.pow(lambpV / lambV, 2) * (vpl / gama1);
        break;
    }

    // Bending
    //FLA
    mpl = zx * fy;
    lambA = h / tw;
    lambpA = 3.76 * Math.sqrt(E / fy);
    lambrA = 5.7 * Math.sqrt(E / fy);

    if (lambA <= lambpA) {
        situationA = "Caso 1";
    } else if (lambpA < lambA && lambA <= lambrA) {
        situationA = "Caso 2";
    } else if (lambrA < lambA) {
        situationA = "Caso 3";
    } else {
        situationA = "Error";
    }

    switch (situationA) {
    case "Caso 1":
        mrdA = mpl / gama1;
        break;
    case "Caso 2":
        mrA = 0.7 * fy * wx;
        mrdA = (cb / gama1) * (mpl - ((mpl - mrA) * ((lambA - lambpA) / (lambrA - lambpA))));
        break;
    case "Caso 3":
        // mcrA = Anexo H
        mrdA = mcrA / gama1;
        break;
    }

    //FLM
    lambM = mesa;
    lambpM = 0.38 * Math.sqrt(E / fy);
    lambrM = 0.83 * Math.sqrt(E / (fy - tr));

    if (lambM <= lambpM) {
        situationM = "Caso 1";
    } else if (lambpM < lambM && lambM <= lambrM) {
        situationM = "Caso 2";
    } else if (lambrM < lambM) {
        situationM = "Caso 3";
    } else {
        situationM = "Error";
    }

    switch (situationM) {
    case "Caso 1":
        mrdM = mpl / gama1;
        break;
    case "Caso 2":
        mrM = 0.7 * fy * wx;
        mrdM = (cb / gama1) * (mpl - ((mpl - mrM) * ((lambM - lambpM) / (lambrM - lambpM))));
        break;
    case "Caso 3":
        mcrM = ((0.69 * E) / (lambM * lambM)) * wx;
        mrdM = mcrM / gama1;
        break;
    }

    // FLT
    lambT = lb / ry;
    lambpT = 1.76 * Math.sqrt(E / fy);
    lambrT = ((1.38 * Math.sqrt(fy * it)) / (ry * it * beta1)) * Math.sqrt(1 + Math.sqrt(1 + (27 * cw * beta1 * beta1) / iy));

    if (lambT <= lambpT) {
        situationT = "Caso 1";
    } else if (lambpT < lambT && lambT <= lambrT) {
        situationT = "Caso 2";
    } else if (lambrT < lambT) {
        situationT = "Caso 3";
    } else {
        situationT = "Error";
    }

    switch (situationT) {
    case "Caso 1":
        mrdT = mpl / gama1;
        break;
    case "Caso 2":
        mrT = 0.7 * fy * wx;
        mrdT = (cb / gama1) * (mpl - ((mpl - mrT) * ((lambT - lambpT) / (lambrT - lambpT))));
        break;
    case "Caso 3":
        mcrT = ((0.69 * E) / (lambT * lambT)) * wx;
        mrdT = mcrT / gama1;
        break;
    }

    //Compare & Results
    vsd = v * gama;
    msd = m * gama;
    mrd = Math.min(mrdA, mrdM, mrdT);
    mrdOut = mrd / 100;

    if (vsd <= vrd && msd <= mrdOut) {
        result = "OK";
        alert("OK");
    } else {
        result = "Não OK";
        alert("Não OK");
    }
}

/*
    Cria um objeto bitola
*/
function criarBitola(nomeBitola, linhaBitola) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeBitola);
    opcao.value = linhaBitola;
    opcao.appendChild(texto);
    return opcao;
}

var bitolaLista = document.getElementById("bitola"),
    acoLista = document.getElementById("acos"),
    i;

for (i = 0; i < perfis.length; i += 1) {
    bitolaLista.appendChild(criarBitola(perfis[i].bitola, i));
}

function criarAco(nomeAco, linhaAco) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeAco);
    opcao.value = linhaAco;
    opcao.appendChild(texto);
    return opcao;
}

for (i = 0; i < steelProp.length; i += 1) {
    acoLista.appendChild(criarAco(steelProp[i].steelType, i));
}
<commit_msg>Update script.js<commit_after>/*jslint devel: true*/
/*global perfis */

// variables
var project, beam, v, m, lbForm, section, steel, fyForm, fuForm, EForm, ml, d, bf, tw, tf, h, dl, area, ix, wx, rx, zx, iy, wy, ry, zy, rt, it, mesa, alma, cw, u, fy, fu, E, aw, gama, gama1, cb, kv, lb, kc, tr, beta1, a, lambV, lambpV, lambrV, vpl, vrd, mpl, lambA, lambpA, lambrA, mrA, mcrA, mrdA, lambM, lambpM, lambrM, mrM, mcrM, mrdM, lambT, lambpT, lambrT, mrT, mcrT, mrdT, vsd, msd, vrd, mrd, mrdOut, situationV, situationA, situationM, situationT, result;

var steelProp = [
    {
        "steelType": "ASTM A36/ MR250",
        "fy": 250,
        "fu": 400,
        "E": 200000
    },
    {
        "steelType": "ASTM A572 G50/ AR345",
        "fy": 345,
        "fu": 450,
        "E": 200000
    },
    {
        "steelType": "ASTM A572 G50/ AR345",
        "fy": 345,
        "fu": 450,
        "E": 200000
    }
];

function processFormCS() {
    "use strict";
    var i, j;

    // Getting values from HTML form inputs
    project = document.formCS.projectCS.value;
    if (project === "") {
        alert("Por favor preencha o campo Projeto.");
        console.log("Por favor preencha o campo Projeto.");
        return false;
    }
    beam = document.formCS.beamCS.value;
    if (beam === "") {
        alert("Por favor preencha o campo Viga.");
        console.log("Por favor preencha o campo Viga.");
        return false;
    }
    v = Number(document.formCS.vCS.value);
    if (document.formCS.vCS.value === "" || isNaN(v)) {
        alert("Por favor preencha o campo Cortante com números.");
        console.log("Por favor preencha o campo Cortante.");
        return false;
    }
    m = Number(document.formCS.mCS.value);
    if (document.formCS.mCS.value === "" || isNaN(m)) {
        alert("Por favor preencha o campo Momento com números.");
        console.log("Por favor preencha o campo Momento.");
        return false;
    }
    lbForm = Number(document.formCS.lbCS.value);
    if (document.formCS.lbCS.value === "" || isNaN(lbForm)) {
        alert("Por favor preencha o campo Distância entre travamentos laterais com números.");
        console.log("Por favor preencha o campo Distância entre travamentos laterais com números.");
        return false;
    }
    section = perfis[Number(document.formCS.sectionS.value)].bitola;
    steel = steelProp[Number(document.formCS.typeS.value)].steelType;
    a = Number(document.formCS.aCS.value);
    gama = Number(document.formCS.gama.value);
    gama1 = Number(document.formCS.gama1.value);
    cb = Number(document.formCS.cb.value);

    // Getting section properties
    i = Number(document.getElementById("bitola").value);

    ml = perfis[i].ml;
    d = perfis[i].d;
    bf = perfis[i].bf;
    tw = perfis[i].tw;
    tf = perfis[i].tf;
    h = perfis[i].h;
    dl = perfis[i].dl;
    area = perfis[i].area;
    ix = perfis[i].ix;
    wx = perfis[i].wx;
    rx = perfis[i].rx;
    zx = perfis[i].zx;
    iy = perfis[i].iy;
    wy = perfis[i].wy;
    ry = perfis[i].ry;
    zy = perfis[i].zy;
    it = perfis[i].it;
    mesa = perfis[i].mesa;
    alma = perfis[i].alma;
    cw = perfis[i].cw;
    u = perfis[i].u;

    // Getting values from steel properties array
    j = Number(document.getElementById("acos").value);

    fyForm = steelProp[j].fy;
    fuForm = steelProp[j].fu;
    EForm = steelProp[j].E;

    // Calculating kv
    if (((a / h) > 3) || ((a / h) > Math.pow(260 / (h / tw), 2)) || (document.getElementById("stiffeningCS").checked === true)) {
        kv = 5;
    } else {
        kv = 5 + 5 / (Math.pow(a / h, 2));
    }

    // Calculating parameters
    aw = d * tw;
    lb = lbForm * 100;
    fy = fyForm / 10;
    fu = fuForm / 10;
    E = EForm / 10;
    beta1 = (0.7 * fy * wx) / (E * it);
    kc = 4 / Math.sqrt(h / tw);
    tr = 0.3 * fy;

    // Shear Vrd
    lambV = h / tw;
    lambpV = (1.1 * Math.sqrt(kv * E / fy));
    lambrV = (1.37 * Math.sqrt(kv * E / fy));
    vpl = 0.6 * fy * aw;

    if (lambV <= lambpV) {
        situationV = "Caso 1";
    } else if (lambpV < lambV && lambV <= lambrV) {
        situationV = "Caso 2";
    } else if (lambrV < lambV) {
        situationV = "Caso 3";
    } else {
        situationV = "Error";
    }

    switch (situationV) {
    case "Caso 1":
        vrd = vpl / gama1;
        break;
    case "Caso 2":
        vrd = (lambpV / lambV) * (vpl / gama1);
        break;
    case "Caso 3":
        vrd = 1.24 * Math.pow(lambpV / lambV, 2) * (vpl / gama1);
        break;
    }

    // Bending
    //FLA
    mpl = zx * fy;
    lambA = h / tw;
    lambpA = 3.76 * Math.sqrt(E / fy);
    lambrA = 5.7 * Math.sqrt(E / fy);

    if (lambA <= lambpA) {
        situationA = "Caso 1";
    } else if (lambpA < lambA && lambA <= lambrA) {
        situationA = "Caso 2";
    } else if (lambrA < lambA) {
        situationA = "Caso 3";
    } else {
        situationA = "Error";
    }

    switch (situationA) {
    case "Caso 1":
        mrdA = mpl / gama1;
        break;
    case "Caso 2":
        mrA = 0.7 * fy * wx;
        mrdA = (cb / gama1) * (mpl - ((mpl - mrA) * ((lambA - lambpA) / (lambrA - lambpA))));
        break;
    case "Caso 3":
        // mcrA = Anexo H
        mrdA = mcrA / gama1;
        break;
    }

    //FLM
    lambM = mesa;
    lambpM = 0.38 * Math.sqrt(E / fy);
    lambrM = 0.83 * Math.sqrt(E / (fy - tr));

    if (lambM <= lambpM) {
        situationM = "Caso 1";
    } else if (lambpM < lambM && lambM <= lambrM) {
        situationM = "Caso 2";
    } else if (lambrM < lambM) {
        situationM = "Caso 3";
    } else {
        situationM = "Error";
    }

    switch (situationM) {
    case "Caso 1":
        mrdM = mpl / gama1;
        break;
    case "Caso 2":
        mrM = 0.7 * fy * wx;
        mrdM = (cb / gama1) * (mpl - ((mpl - mrM) * ((lambM - lambpM) / (lambrM - lambpM))));
        break;
    case "Caso 3":
        mcrM = ((0.69 * E) / (lambM * lambM)) * wx;
        mrdM = mcrM / gama1;
        break;
    }

    // FLT
    lambT = lb / ry;
    lambpT = 1.76 * Math.sqrt(E / fy);
    lambrT = ((1.38 * Math.sqrt(iy * it)) / (ry * it * beta1)) * Math.sqrt(1 + Math.sqrt(1 + (27 * cw * beta1 * beta1) / iy));

    if (lambT <= lambpT) {
        situationT = "Caso 1";
    } else if (lambpT < lambT && lambT <= lambrT) {
        situationT = "Caso 2";
    } else if (lambrT < lambT) {
        situationT = "Caso 3";
    } else {
        situationT = "Error";
    }

    switch (situationT) {
    case "Caso 1":
        mrdT = mpl / gama1;
        break;
    case "Caso 2":
        mrT = 0.7 * fy * wx;
        mrdT = (cb / gama1) * (mpl - ((mpl - mrT) * ((lambT - lambpT) / (lambrT - lambpT))));
        break;
    case "Caso 3":
        mcrT = (cb*Math.PI*Math.PI*E*iy)/Math.pow(lb,2))*Math.sqrt((cw/iy)*(1+0.039*(it*lb*lb)/cw);
        mrdT = mcrT / gama1;
        break;
    }

    //Compare & Results
    vsd = v * gama;
    msd = m * gama;
    mrd = Math.min(mrdA, mrdM, mrdT);
    mrdOut = mrd / 100;

    if (vsd <= vrd && msd <= mrdOut) {
        result = "OK";
        alert("OK");
    } else {
        result = "Não OK";
        alert("Não OK");
    }
}

/*
    Cria um objeto bitola
*/
function criarBitola(nomeBitola, linhaBitola) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeBitola);
    opcao.value = linhaBitola;
    opcao.appendChild(texto);
    return opcao;
}

var bitolaLista = document.getElementById("bitola"),
    acoLista = document.getElementById("acos"),
    i;

for (i = 0; i < perfis.length; i += 1) {
    bitolaLista.appendChild(criarBitola(perfis[i].bitola, i));
}

function criarAco(nomeAco, linhaAco) {
    "use strict";
    var opcao = document.createElement("OPTION"),
        texto = document.createTextNode(nomeAco);
    opcao.value = linhaAco;
    opcao.appendChild(texto);
    return opcao;
}

for (i = 0; i < steelProp.length; i += 1) {
    acoLista.appendChild(criarAco(steelProp[i].steelType, i));
}
<|endoftext|>


<commit_before>function input_group_file(){
	$(":text").click(function(){
		if($(this).siblings(":file").size() > 0){
			$(this).siblings("label").click();
		};
	});
	$(":file").change(function(){
		$file_name = $(this).val().replace(/\\/g, '/').replace(/.*\//, '');;
		$(this).siblings(":text").val($file_name);
	});
}<commit_msg>Updated .js<commit_after>function input_group_file(){
	$(":text").click(function(){
		if($(this).siblings(":file").size() > 0){
			$(this).siblings("label").click();
		};
	});
	$(":file").change(function(){
		$file_name = $(this).val().replace(/\\/g, "/").replace(/.*\//, "");;
		$(this).siblings(":text").val($file_name);
	});
}
<|endoftext|>


<commit_before>// namespace
var App = App || {};

App.PlayGameState = (function () {
    "use strict";

    var fn = function (game) {
        Phaser.State.call(this, game);
    };

    fn.prototype = Object.create(Phaser.State.prototype);
    fn.prototype.constructor = fn;

    fn.prototype.init = function () {
        this.asset_manager = new App.AssetManager(this.game);
    };

    fn.prototype.preload = function () {
        // load assets
        this.asset_manager.loadAssets();
        this.game.load.spritesheet('alienBlue', 'assets/images/alienBlue_sheet.png', 66, 96);

    };

    fn.prototype.create = function () {
        // init assets
        this.asset_manager.initAssets();

        // our forest tilemap
        this.forest = this.asset_manager.get_tilemap('forest');

        this.game.world.sendToBack(this.forest.layers.backgroundLayer);

        // resize world to fit the layers
        this.forest.layers.backgroundLayer.resizeWorld();

        this.game.global.player = this.alienBlue = this.game.add.existing(new App.Player(this.game, 140, 160));
        this.game.global.vx = 0;
        this.game.global.vy = 0;
        this.game.world.bringToTop(this.forest.layers.foregroundLayerTop);
        this.key1 = game.input.keyboard.addKey(Phaser.Keyboard.BACKWARD_SLASH);
        this.key1.onDown.add(fn.prototype.enterMessage, this);

        /*this.game.add.existing(new App.FlagGreenLeft(this.game, 0, 0));
        this.game.add.existing(new App.FlagGreenRight(this.game, 100, 0));
        this.game.add.existing(new App.FlagOrangeLeft(this.game, 200, 0));
        this.game.add.existing(new App.FlagOrangeRight(this.game, 300, 0));*/
    };

    fn.prototype.update = function () {
        var g = game.global;
        var p = g.player.body;
        if (p.playerName && (g.vx != p.velocity.x || g.vy != p.velocity.y)) {
            // Already logged in and my Velocity changed.
            // Inform the server.
            g.vx = p.velocity.x;
            g.vy = p.velocity.y;
            g.eurecaServer.updatePlayer({ x: p.position.x, y: p.position.y, vx: g.vx, vy: g.vy });
        }
        this.game.physics.arcade.collide(this.game.global.player, this.forest.layers.collisionLayer);
    };

    fn.prototype.doLogin = function (name) {
        game.global.eurecaServer.login(name).onReady(function (result) {
            //console.log("[DEBUG] server.login(" + name + ") = " + result);
            if (result) {
                game.global.player.playerName = name;
                console.log("Logged in as: " + name);
            }
            else {
                console.log("FAILED TO LOGIN AS: " + name);
            }
        });
    };

    fn.prototype.doChat = function (message) {
        game.global.eurecaServer.chat(message).onReady(function (result) {
            //console.log("[DEBUG] server.chat(" + message + ") = " + result);
            if (!result) {
                console.log("Please /login before chatting.");
            }
        });
    };

    fn.prototype.enterMessage = function () {
        var defaultPrompt = this.game.global.player.playerName ? 'blah' : '/login ';
        var message = prompt("Type command or message", defaultPrompt);
        if (message) {
            var contents = message.split(" ");
            if (contents[0] == '/login') {
                fn.prototype.doLogin(contents[1]);
            }
            else if (contents[0] == '/tell') {
                var realMessage = message.replace(/^\/tell\s+(\S+)\s*(.+)/gi, '$1');
                console.log(this.game.global.player.playerName+" tells "+contents[1]+" the message '"+realMessage+"'");
                // Once Multiplayer is working, then pass the message to the other player's console
            }
            else if (contents[0] == '/logout') {
                this.game.global.player.playerName = '';
                console.log("You are now logged out");
            }
            else if (contents[0].substr(0,1) == '/') {
                console.log("Unknown command: " + contents[0]);
            }
            else {
                // Client is speaking. Send message to server.
                fn.prototype.doChat(message);
            }
        }
    }

    return fn;
})();
<commit_msg>Fix velocity update sniffing logic.<commit_after>// namespace
var App = App || {};

App.PlayGameState = (function () {
    "use strict";

    var fn = function (game) {
        Phaser.State.call(this, game);
    };

    fn.prototype = Object.create(Phaser.State.prototype);
    fn.prototype.constructor = fn;

    fn.prototype.init = function () {
        this.asset_manager = new App.AssetManager(this.game);
    };

    fn.prototype.preload = function () {
        // load assets
        this.asset_manager.loadAssets();
        this.game.load.spritesheet('alienBlue', 'assets/images/alienBlue_sheet.png', 66, 96);

    };

    fn.prototype.create = function () {
        // init assets
        this.asset_manager.initAssets();

        // our forest tilemap
        this.forest = this.asset_manager.get_tilemap('forest');

        this.game.world.sendToBack(this.forest.layers.backgroundLayer);

        // resize world to fit the layers
        this.forest.layers.backgroundLayer.resizeWorld();

        this.game.global.player = this.alienBlue = this.game.add.existing(new App.Player(this.game, 140, 160));
        this.game.global.vx = 0;
        this.game.global.vy = 0;
        this.game.world.bringToTop(this.forest.layers.foregroundLayerTop);
        this.key1 = game.input.keyboard.addKey(Phaser.Keyboard.BACKWARD_SLASH);
        this.key1.onDown.add(fn.prototype.enterMessage, this);

        /*this.game.add.existing(new App.FlagGreenLeft(this.game, 0, 0));
        this.game.add.existing(new App.FlagGreenRight(this.game, 100, 0));
        this.game.add.existing(new App.FlagOrangeLeft(this.game, 200, 0));
        this.game.add.existing(new App.FlagOrangeRight(this.game, 300, 0));*/
    };

    fn.prototype.update = function () {
        var g = this.game.global;
        var p = g.player.body;
        if (g.player.playerName && (g.vx != p.velocity.x || g.vy != p.velocity.y)) {
            // Already logged in and my Velocity changed.
            // Inform the server.
            g.vx = p.velocity.x;
            g.vy = p.velocity.y;
            g.eurecaServer.updatePlayer({ x: p.position.x, y: p.position.y, vx: g.vx, vy: g.vy });
        }
        this.game.physics.arcade.collide(this.game.global.player, this.forest.layers.collisionLayer);
    };

    fn.prototype.doLogin = function (name) {
        game.global.eurecaServer.login(name).onReady(function (result) {
            //console.log("[DEBUG] server.login(" + name + ") = " + result);
            if (result) {
                game.global.player.playerName = name;
                console.log("Logged in as: " + name);
            }
            else {
                console.log("FAILED TO LOGIN AS: " + name);
            }
        });
    };

    fn.prototype.doChat = function (message) {
        game.global.eurecaServer.chat(message).onReady(function (result) {
            //console.log("[DEBUG] server.chat(" + message + ") = " + result);
            if (!result) {
                console.log("Please /login before chatting.");
            }
        });
    };

    fn.prototype.enterMessage = function () {
        var defaultPrompt = this.game.global.player.playerName ? 'blah' : '/login ';
        var message = prompt("Type command or message", defaultPrompt);
        if (message) {
            var contents = message.split(" ");
            if (contents[0] == '/login') {
                // XXX: Should we require a password too?
                fn.prototype.doLogin(contents[1]);
            }
            else if (contents[0] == '/tell') {
                var realMessage = message.replace(/^\/tell\s+(\S+)\s*(.+)/gi, '$1');
                console.log(this.game.global.player.playerName+" tells "+contents[1]+" the message '"+realMessage+"'");
                // Once Multiplayer is working, then pass the message to the other player's console
            }
            else if (contents[0] == '/logout') {
                this.game.global.player.playerName = '';
                console.log("You are now logged out");
            }
            else if (contents[0].substr(0,1) == '/') {
                console.log("Unknown command: " + contents[0]);
            }
            else {
                // Client is speaking. Send message to server.
                fn.prototype.doChat(message);
            }
        }
    }

    return fn;
})();
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor';
import { ValidatedMethod } from 'meteor/mdg:validated-method';

import SimpleSchema from 'simpl-schema';
import assert from 'assert';
import Papa from 'papaparse';
import fs from 'fs';
import { findIndex, isEqual, isEmpty, mapValues,
	partition, omit } from 'lodash';

import { Genes, GeneSchema, SubfeatureSchema,
	VALID_SUBFEATURE_TYPES, VALID_INTERVAL_TYPES } from '/imports/api/genes/gene_collection.js';
import { orthogroupCollection } from '/imports/api/genes/orthogroup_collection.js';
import { genomeSequenceCollection, genomeCollection } from '/imports/api/genomes/genomeCollection.js';
import { Tracks } from '/imports/api/genomes/track_collection.js';
import logger from '/imports/api/util/logger.js';
import { scanGeneAttributes } from '/imports/api/genes/scanGeneAttributes.js';
import { parseAttributeString } from '/imports/api/util/util.js';

/**
 * Interval Class containing a single genomic interval. Every line in a gff3 file is an interval
 * @type {Interval}
 */
const Interval = class Interval {
	constructor({ gffFields, genomeId, deriveIdFromParent = true }){//, genomeSequences }){ //, trackId
		const [ seqid, source, type, start, end,
			_score, strand, phase, attributeString ] = gffFields;
		const score = String(_score);
		const attributes = parseAttributeString(attributeString);

		if (!attributes.hasOwnProperty('ID')){
			logger.warn(`The following line does not have the gff3 ID attribute:`);
			logger.warn(`${gffFields.join('\t')}`);
			if (deriveIdFromParent) {
				const derivedId = `${attributes.Parent}_${type}_${start}_${end}`;
				logger.warn(`Assigning ID based on Parent attribute ${derivedId}`);
				attributes.ID = [derivedId];
			}

		}

		this.ID = attributes.ID[0];
		delete attributes.ID;

		if (typeof attributes.Parent === 'undefined'){
			//top level feature
			Object.assign(this, {
				seqid, source, strand, genomeId
			})
		} else {
			//sub feature
			this.phase = phase;
			this.parents = attributes.Parent;
			delete attributes.Parent;
		}

		Object.assign(this, {
			type, start, end, score, attributes
		})

	}
}

/**
 * Genemodel Class containing all intervals for a single gene.
 * @type {GeneModel}
 */
const GeneModel = class GeneModel {
	constructor(_intervals){
		//filter valid interval types and set parent and children values
		const intervals = _intervals.filter(({ type }) => {
			const isValid = VALID_INTERVAL_TYPES.indexOf(type) >= 0;
			if (!isValid){
				logger.warn(`intervals of type ${type} are not supported, skipping.`)
			}
			return isValid
		})
		intervals.forEach(interval => {
			if (interval.type === 'transcript'){
				interval.type = 'mRNA';
			};
			if (interval.hasOwnProperty('parents')) {
				interval.parents.forEach(parentId => {
					const parentIndex = intervals.map(interval => interval.ID).indexOf(parentId);
					const parent = intervals[parentIndex] || {};
					if (!parent.hasOwnProperty('children')){
						parent.children = []
					}
					parent.children.push(interval.ID)
				})
			}
		})

		//pull out gene interval
		//https://lodash.com/docs/4.17.10#partition
		const [genes, subfeatures] = partition(intervals, interval => typeof interval.parents === 'undefined');
		const gene = genes[0]
		Object.assign(this, gene);

		//set subfeatures
		this.subfeatures = subfeatures;
	}

	fetchGenomeSequence = () => {
		let shiftCoordinates = 10e99;
		const genomicRegion = genomeSequenceCollection.find({
			genomeId: this.genomeId,
			header: this.seqid,
			start: { $lte: this.end },
			end: { $gte: this.start }
		}).fetch().sort((a,b) => {
			return a.start - b.start
		}).map(seqPart => {
			shiftCoordinates = Math.min(shiftCoordinates, seqPart.start);
			return seqPart.seq
		}).join('');
		if (genomicRegion.length > 0){
			this.seq = genomicRegion.slice(this.start - shiftCoordinates - 1,
				this.end - shiftCoordinates);
			this.subfeatures.forEach(subfeature => {
				subfeature.seq = genomicRegion.slice(subfeature.start - shiftCoordinates - 1,
					subfeature.end - shiftCoordinates)
			});
		} else {
			logger.warn(`Could not find sequence for gene ${this.ID} with seqid ${this.seqid}.`+
			 ` Make sure the sequence IDs between the genome fasta and annotation gff3 are the same.`)
		}
		return this
	}

	validate = () => {
		const validationContext = GeneSchema.newContext();
		validationContext.validate(this.dataFields);
		return validationContext
	}

	saveToDb = bulkOp => {
		if (this.type === 'gene'){
			this.fetchGenomeSequence();
			const validation = this.validate();
			if (validation.isValid()) {
				bulkOp.insert(this.dataFields);
			} else {
				validation.validationErrors().forEach(err => {
					logger.warn(`gene ${this.ID}, field ${err.name} is ${err.type}, got '${err.value}'`)
				})
			}
		} else {
			logger.warn(`Not saving top-level feature`)
		}
	}

	get dataFields() {
		return omit(this, ['fetchGenomeSequence', 'validate','saveToDb','dataFields'])
	}
}

/**
 * [description]
 * @param  {String} options.fileName           [description]
 * @param  {String} options.genomeeId        [description]
 * @param  {Object} options.genomeeSequences [description]
 * @param  {String} options.trackId            [description]
 * @return {Promise}                            [description]
 */
const gffFileToMongoDb = ({ fileName, genomeId, strict }) => {
	return new Promise((resolve, reject) => {
		if (!fs.existsSync(fileName)) {
			reject(new Meteor.Error(`${fileName} is not an existing file`));
		};
		const fileHandle = fs.readFileSync(fileName, { encoding: 'binary' });
		let intervals = [];
		let geneCount = 0;
		let lineNumber = 0;

		logger.log('Initializing bulk operation');
		let bulkOp = Genes.rawCollection().initializeUnorderedBulkOp();

		logger.log(`Start reading ${fileName}`)
		Papa.parse(fileHandle, {
			delimiter: '\t',
			dynamicTyping: true,
			skipEmptyLines: true,
			comments: '#',
			fastMode: true,
			error(error,file) {
				reject(error)
			},
			step(line, parser){
				lineNumber += 1;
				try {
					const { data } = line;
					const [ gffFields ] = data;

					assert(gffFields.length === 9,
						`${gffFields} is not a correct gff line with 9 fields`);
					let interval = new Interval({ gffFields, genomeId })

					if (typeof interval.parents === 'undefined'){
						if (!isEmpty(intervals)){
							const gene = new GeneModel(intervals);
							gene.saveToDb(bulkOp);
							geneCount += 1;
						}
						intervals = [];
					}

					intervals.push(interval)

				} catch (error) {
					reject(error)
				}
			},
			complete(results,file) {
				try {
					if ( !isEmpty(intervals) ) {
						logger.log('constructing final gene model')
						const gene = new GeneModel(intervals);
						gene.saveToDb(bulkOp);
						geneCount += 1;
					}

					if (bulkOp.s.currentBatch &&
							bulkOp.s.currentBatch.operations.length) {
						logger.log('Executing bulk operation');
						const result = bulkOp.execute();

						genomeCollection.update({
							_id: genomeId
						},{
							$set: {
								annotationTrack : {
									name: fileName.split('/').pop()
								}
							}
						})

						logger.log(`Finished inserting ${geneCount} genes`)

						resolve(result)
					} else {
						logger.warn('Empty bulk operation')
						throw new Meteor.Error('Empty bulk operation')
					}
				} catch (error) {
					reject(error)
				}
			}
		})
	})
}

export const addAnnotationTrack = new ValidatedMethod({
	name: 'addAnnotationTrack',
	validate: new SimpleSchema({
		fileName: { type: String },
		genomeName: { type: String }
	}).validator(),
	applyOptions: {
		noRetry: true
	},
	run({ fileName, genomeName, strict = true }){
		if (! this.userId) {
			throw new Meteor.Error('not-authorized');
		}
		if (! Roles.userIsInRole(this.userId, 'admin')){
			throw new Meteor.Error('not-authorized');
		}

		logger.log(`Adding annotation file "${fileName}" to genome "${genomeName}"`)

		const existingGenome = genomeCollection.findOne({ name: genomeName })
		if (!existingGenome){
			throw new Meteor.Error(`Invalid genome name: ${genomeName}`)
		}

		if (typeof existingGenome.annotationTrack !== 'undefined'){
			throw new Meteor.Error(`Genome ${genomeName} already has an annotation track`);
		}

		const genomeId = existingGenome._id;

		return gffFileToMongoDb({ fileName, genomeId, strict })
			.catch(error => {
				logger.warn(error);
				throw new Meteor.Error(error);
			})
	}
})

<commit_msg>fix gff line parsing<commit_after>import { Meteor } from 'meteor/meteor';
import { ValidatedMethod } from 'meteor/mdg:validated-method';

import SimpleSchema from 'simpl-schema';
import assert from 'assert';
import Papa from 'papaparse';
import fs from 'fs';
import { findIndex, isEqual, isEmpty, mapValues,
	partition, omit } from 'lodash';

import { Genes, GeneSchema, SubfeatureSchema,
	VALID_SUBFEATURE_TYPES, VALID_INTERVAL_TYPES } from '/imports/api/genes/gene_collection.js';
import { orthogroupCollection } from '/imports/api/genes/orthogroup_collection.js';
import { genomeSequenceCollection, genomeCollection } from '/imports/api/genomes/genomeCollection.js';
import { Tracks } from '/imports/api/genomes/track_collection.js';
import logger from '/imports/api/util/logger.js';
import { scanGeneAttributes } from '/imports/api/genes/scanGeneAttributes.js';
import { parseAttributeString } from '/imports/api/util/util.js';

/**
 * Interval Class containing a single genomic interval. Every line in a gff3 file is an interval
 * @type {Interval}
 */
const Interval = class Interval {
	constructor({ gffFields, genomeId, deriveIdFromParent = true }){//, genomeSequences }){ //, trackId
		const [ seqid, source, type, start, end,
			_score, strand, phase, attributeString ] = gffFields;
		const score = String(_score);
		const attributes = parseAttributeString(attributeString);

		if (!attributes.hasOwnProperty('ID')){
			logger.warn(`The following line does not have the gff3 ID attribute:`);
			logger.warn(`${gffFields.join('\t')}`);
			if (deriveIdFromParent) {
				const derivedId = `${attributes.Parent}_${type}_${start}_${end}`;
				logger.warn(`Assigning ID based on Parent attribute ${derivedId}`);
				attributes.ID = [derivedId];
			}

		}

		this.ID = attributes.ID[0];
		delete attributes.ID;

		if (typeof attributes.Parent === 'undefined'){
			//top level feature
			Object.assign(this, {
				seqid, source, strand, genomeId
			})
		} else {
			//sub feature
			this.phase = phase;
			this.parents = attributes.Parent;
			delete attributes.Parent;
		}

		Object.assign(this, {
			type, start, end, score, attributes
		})

	}
}

/**
 * Genemodel Class containing all intervals for a single gene.
 * @type {GeneModel}
 */
const GeneModel = class GeneModel {
	constructor(_intervals){
		//filter valid interval types and set parent and children values
		const intervals = _intervals.filter(({ type }) => {
			const isValid = VALID_INTERVAL_TYPES.indexOf(type) >= 0;
			if (!isValid){
				logger.warn(`intervals of type ${type} are not supported, skipping.`)
			}
			return isValid
		})
		intervals.forEach(interval => {
			if (interval.type === 'transcript'){
				interval.type = 'mRNA';
			};
			if (interval.hasOwnProperty('parents')) {
				interval.parents.forEach(parentId => {
					const parentIndex = intervals.map(interval => interval.ID).indexOf(parentId);
					const parent = intervals[parentIndex] || {};
					if (!parent.hasOwnProperty('children')){
						parent.children = []
					}
					parent.children.push(interval.ID)
				})
			}
		})

		//pull out gene interval
		//https://lodash.com/docs/4.17.10#partition
		const [genes, subfeatures] = partition(intervals, interval => typeof interval.parents === 'undefined');
		const gene = genes[0]
		Object.assign(this, gene);

		//set subfeatures
		this.subfeatures = subfeatures;
	}

	fetchGenomeSequence = () => {
		let shiftCoordinates = 10e99;
		const genomicRegion = genomeSequenceCollection.find({
			genomeId: this.genomeId,
			header: this.seqid,
			start: { $lte: this.end },
			end: { $gte: this.start }
		}).fetch().sort((a,b) => {
			return a.start - b.start
		}).map(seqPart => {
			shiftCoordinates = Math.min(shiftCoordinates, seqPart.start);
			return seqPart.seq
		}).join('');
		if (genomicRegion.length > 0){
			this.seq = genomicRegion.slice(this.start - shiftCoordinates - 1,
				this.end - shiftCoordinates);
			this.subfeatures.forEach(subfeature => {
				subfeature.seq = genomicRegion.slice(subfeature.start - shiftCoordinates - 1,
					subfeature.end - shiftCoordinates)
			});
		} else {
			logger.warn(`Could not find sequence for gene ${this.ID} with seqid ${this.seqid}.`+
			 ` Make sure the sequence IDs between the genome fasta and annotation gff3 are the same.`)
		}
		return this
	}

	validate = () => {
		const validationContext = GeneSchema.newContext();
		validationContext.validate(this.dataFields);
		return validationContext
	}

	saveToDb = bulkOp => {
		if (this.type === 'gene'){
			this.fetchGenomeSequence();
			const validation = this.validate();
			if (validation.isValid()) {
				bulkOp.insert(this.dataFields);
			} else {
				validation.validationErrors().forEach(err => {
					logger.warn(`gene ${this.ID}, field ${err.name} is ${err.type}, got '${err.value}'`)
				})
			}
		} else {
			logger.warn(`Not saving top-level feature`)
		}
	}

	get dataFields() {
		return omit(this, ['fetchGenomeSequence', 'validate','saveToDb','dataFields'])
	}
}

/**
 * [description]
 * @param  {String} options.fileName           [description]
 * @param  {String} options.genomeeId        [description]
 * @param  {Object} options.genomeeSequences [description]
 * @param  {String} options.trackId            [description]
 * @return {Promise}                            [description]
 */
const gffFileToMongoDb = ({ fileName, genomeId, strict }) => {
	return new Promise((resolve, reject) => {
		if (!fs.existsSync(fileName)) {
			reject(new Meteor.Error(`${fileName} is not an existing file`));
		};
		const fileHandle = fs.readFileSync(fileName, { encoding: 'binary' });
		let intervals = [];
		let geneCount = 0;
		let lineNumber = 0;

		logger.log('Initializing bulk operation');
		let bulkOp = Genes.rawCollection().initializeUnorderedBulkOp();

		logger.log(`Start reading ${fileName}`)
		Papa.parse(fileHandle, {
			delimiter: '\t',
			dynamicTyping: true,
			skipEmptyLines: true,
			comments: '#',
			fastMode: true,
			error(error,file) {
				reject(error)
			},
			step(line, parser){
				lineNumber += 1;
				try {
					const gffFields = line.data;

					assert(gffFields.length === 9,
						`line ${lineNumber} is not a correct gff line with 9 fields: ${gffFields}`);
					let interval = new Interval({ gffFields, genomeId })

					if (typeof interval.parents === 'undefined'){
						if (!isEmpty(intervals)){
							const gene = new GeneModel(intervals);
							gene.saveToDb(bulkOp);
							geneCount += 1;
						}
						intervals = [];
					}

					intervals.push(interval)

				} catch (error) {
					reject(error)
				}
			},
			complete(results,file) {
				try {
					if ( !isEmpty(intervals) ) {
						logger.log('constructing final gene model')
						const gene = new GeneModel(intervals);
						gene.saveToDb(bulkOp);
						geneCount += 1;
					}

					if (bulkOp.s.currentBatch &&
							bulkOp.s.currentBatch.operations.length) {
						logger.log('Executing bulk operation');
						const result = bulkOp.execute();

						genomeCollection.update({
							_id: genomeId
						},{
							$set: {
								annotationTrack : {
									name: fileName.split('/').pop()
								}
							}
						})

						logger.log(`Finished inserting ${geneCount} genes`)

						resolve(result)
					} else {
						logger.warn('Empty bulk operation')
						throw new Meteor.Error('Empty bulk operation')
					}
				} catch (error) {
					reject(error)
				}
			}
		})
	})
}

export const addAnnotationTrack = new ValidatedMethod({
	name: 'addAnnotationTrack',
	validate: new SimpleSchema({
		fileName: { type: String },
		genomeName: { type: String }
	}).validator(),
	applyOptions: {
		noRetry: true
	},
	run({ fileName, genomeName, strict = true }){
		if (! this.userId) {
			throw new Meteor.Error('not-authorized');
		}
		if (! Roles.userIsInRole(this.userId, 'admin')){
			throw new Meteor.Error('not-authorized');
		}

		logger.log(`Adding annotation file "${fileName}" to genome "${genomeName}"`)

		const existingGenome = genomeCollection.findOne({ name: genomeName })
		if (!existingGenome){
			throw new Meteor.Error(`Invalid genome name: ${genomeName}`)
		}

		if (typeof existingGenome.annotationTrack !== 'undefined'){
			throw new Meteor.Error(`Genome ${genomeName} already has an annotation track`);
		}

		const genomeId = existingGenome._id;

		return gffFileToMongoDb({ fileName, genomeId, strict })
			.catch(error => {
				logger.warn(error);
				throw new Meteor.Error(error);
			})
	}
})

<|endoftext|>


<commit_before>// @flow
/* eslint-disable no-unused-vars */

interface Store {

  /**
   * @description Begin a transaction
   */
  begin(): Array;

  /**
   * @description End a transaction
   */
  end(transaction: Array, callback: () => void): any;

  /**
   * @description Cleans the whole storage
   */
  clean(callback: () => void): any;

  /**
   * @description Get contents from bucket's key
   */
  get(bucket: string, key: string | number, callback: () => void): any;

  /**
   * @description Get union of contents of the specified keys in each of the specified buckets
   * and returns a mapping of bucket to union
   */
  unions(bucket: Array, keys: Array, callback: () => void): any;

  /**
   * @description Get union of contents of the specified keys in each of the specified buckets
   * and returns a mapping of bucket to union
   */
  union(bucket: string, keys: Array, callback: () => void): any;

  /**
   * @description Add values to a given key inside a bucket
   */
  add(transaction: Array, bucket: string, key: string | number, values: string | number | Array): any;

  /**
   * @description Delete given key(s) at the bucket
   */
  del(transaction: Array, bucket: string, keys: string | Array): any;

  /**
   * @description Removes values from a given key inside a bucket
   */
  remove(transaction: Array, bucket: string, key: string | number, values: string | number | Array): any;
}
<commit_msg>refact(interfaces/stores.js) transaction params removed<commit_after>// @flow
/* eslint-disable no-unused-vars */

interface Store {

  /**
   * @description Begin a transaction
   */
  begin(): Array;

  /**
   * @description End a transaction
   */
  end(callback: () => void): any;

  /**
   * @description Cleans the whole storage
   */
  clean(callback: () => void): any;

  /**
   * @description Get contents from bucket's key
   */
  get(bucket: string, key: string | number, callback: () => void): any;

  /**
   * @description Get union of contents of the specified keys in each of the specified buckets
   * and returns a mapping of bucket to union
   */
  unions(bucket: Array, keys: Array, callback: () => void): any;

  /**
   * @description Get union of contents of the specified keys in each of the specified buckets
   * and returns a mapping of bucket to union
   */
  union(bucket: string, keys: Array, callback: () => void): any;

  /**
   * @description Add values to a given key inside a bucket
   */
  add(bucket: string, key: string | number, values: string | number | Array): any;

  /**
   * @description Delete given key(s) at the bucket
   */
  del(bucket: string, keys: string | Array): any;

  /**
   * @description Removes values from a given key inside a bucket
   */
  remove(bucket: string, key: string | number, values: string | number | Array): any;
}
<|endoftext|>


<commit_before>import os from 'os';
import path from 'path';
import chai, { expect } from 'chai';
import { promisify } from 'bluebird';
import rimraf from 'rimraf';
import fs from 'chai-fs';
import { runAndGetAlerts } from '../src/vm';
import { compileES6 } from '../src/compiler';

chai.use(fs);

const rm = promisify(rimraf);
const home = os.homedir();
const extensionName = 'rung-database-test';
const dbPath = path.join(home, '.rung', `${extensionName}.db`);

function sourceWithDb(db) {
    return compileES6(`
        export default {
            extension(context) {
                return {
                    alerts: {},
                    db: ${JSON.stringify(db)}
                };
            }
        };
    `);
}

describe.only('db.js', () => {
    before(() => rm(dbPath));

    describe('Database', () => {
        it('should store an object in the database', () => {
            const source = sourceWithDb({
                counter: 1
            });

            return runAndGetAlerts({ name: extensionName, source }, {})
                .then(result => {
                    expect(dbPath).to.be.a.file();
                });
        });

        it('should drop the file when passed undefined', () => {
            const source = sourceWithDb(undefined);

            return runAndGetAlerts({ name: extensionName, source }, {})
                .then(() => {
                    expect(dbPath).to.not.be.a.path();
                });
        });
    });
});
<commit_msg>Destructuring of tests<commit_after>import os from 'os';
import path from 'path';
import chai, { expect } from 'chai';
import { promisify } from 'bluebird';
import rimraf from 'rimraf';
import fs from 'chai-fs';
import { runAndGetAlerts } from '../src/vm';
import { compileES6 } from '../src/compiler';

chai.use(fs);

const rm = promisify(rimraf);
const home = os.homedir();
const extensionName = 'rung-database-test';
const dbPath = path.join(home, '.rung', `${extensionName}.db`);

describe.only('db.js', () => {
    before(() => rm(dbPath));

    describe('Database', () => {
        it('should store an object in the database', () => {
            const source = compileES6(`
                export default {
                    extension(context) {
                        return {
                            alerts: {},
                            db: { counter: 1 }
                        };
                    }
                };
            `);

            return runAndGetAlerts({ name: extensionName, source }, {})
                .then(result => {
                    expect(result.db.counter).to.equals(1);
                    expect(dbPath).to.be.a.file();
                });
        });

        it('should read and update data from db');

        it('should drop the file when passed undefined', () => {
            const source = compileES6(`
                export default {
                    extension(context) {
                        return {
                            alerts: {}
                        };
                    }
                };
            `);

            return runAndGetAlerts({ name: extensionName, source }, {})
                .then(() => {
                    expect(dbPath).to.not.be.a.path();
                });
        });
    });
});
<|endoftext|>


<commit_before>'use strict'

const assert  = require('chai').assert
const temp    = require('temp').track()
const deliver = require('./../src/deliver')

let srcPath = null

describe('deliver()', function() {

	before(function() {

		srcPath = temp.mkdirSync()

	})

	it('should deliver a directory', function(next) {

		const rewrite  = () => {}
		const redirect = () => {}
		const opts     = { open: false }

		deliver(srcPath, rewrite, redirect, opts, next)

	})

})<commit_msg>Dir creation for each test task<commit_after>'use strict'

const assert  = require('chai').assert
const temp    = require('temp').track()
const deliver = require('./../src/deliver')

describe('deliver()', function() {

	it('should deliver a directory', function(next) {

		const srcPath  = temp.mkdirSync()
		const rewrite  = () => {}
		const redirect = () => {}
		const opts     = { open: false }

		deliver(srcPath, rewrite, redirect, opts, next)

	})

})<|endoftext|>


<commit_before>// Made for YogaScript by Douglas Bumby
var count = parseInt(localStorage.getItem("yogapantcount"))||0;

count = 2;

yogaCount = function() {
  count = count++;
  document.getElementById("yoga-tally").innerHTML = count;
  return 0;
};
<commit_msg>Update script.js<commit_after>// Made for YogaScript by Douglas Bumby
var count = parseInt(localStorage.getItem("yogapantcount"))||0;
var yogaCount;

count = 2;

yogaCount = function() {
  count = count++;
  document.getElementById("yoga-tally").innerHTML = count;
  localStorage.setItem("yogapantcount", count);
  return 0;
};
<|endoftext|>


<commit_before>/* global describe, it */
import assert from 'assert'
import Database from '../src/CRUD.js'
import data from './fixtures/data.json'

let db = new Database()
db.drop()

// Quick helper
let searchHugo = () => db.find({ firstName: 'Hugo', lastName: 'Giraudel' })

describe('Real test feature', () => {
  it('should work', () => {
    // Initial insert
    data.forEach((item) => db.insert(item))
    assert(db.count() === data.length)

    // Find developers
    let developers = db.find({ job: 'Developer' })
    assert(developers.length === 4)

    // Find Hugo
    let search = searchHugo()
    let Hugo = search[0]
    assert(search.length === 1)
    assert(search[0].firstName === 'Hugo')
    assert(search[0].lastName === 'Giraudel')

    // Update Hugo
    let update = db.update(Hugo[db.conf.uniqueKey], Object.assign(Hugo, {
      job: 'Front-end developer'
    }))
    assert(update.job === Hugo.job)

    // Check Hugo
    assert(searchHugo()[0].job === 'Front-end developer')

    // Delete Hugo
    db.delete(Hugo[db.conf.uniqueKey])
    assert(searchHugo().length === 0)

    // Insert Hugo back
    db.insert(Hugo)
    search = searchHugo()
    assert(search.length === 1)
    assert(search[0].job === 'Front-end developer')
  })
})
<commit_msg>Update author‘s name<commit_after>/* global describe, it */
import assert from 'assert'
import Database from '../src/CRUD.js'
import data from './fixtures/data.json'

let db = new Database()
db.drop()

// Quick helper
let searchKitty = () => db.find({ firstName: 'Kitty', lastName: 'Giraudel' })

describe('Real test feature', () => {
  it('should work', () => {
    // Initial insert
    data.forEach((item) => db.insert(item))
    assert(db.count() === data.length)

    // Find developers
    let developers = db.find({ job: 'Developer' })
    assert(developers.length === 4)

    // Find Kitty
    let search = searchKitty()
    let Kitty = search[0]
    assert(search.length === 1)
    assert(search[0].firstName === 'Kitty')
    assert(search[0].lastName === 'Giraudel')

    // Update Kitty
    let update = db.update(Kitty[db.conf.uniqueKey], Object.assign(Kitty, {
      job: 'Front-end developer'
    }))
    assert(update.job === Kitty.job)

    // Check Kitty
    assert(searchKitty()[0].job === 'Front-end developer')

    // Delete Kitty
    db.delete(Kitty[db.conf.uniqueKey])
    assert(searchKitty().length === 0)

    // Insert Kitty back
    db.insert(Kitty)
    search = searchKitty()
    assert(search.length === 1)
    assert(search[0].job === 'Front-end developer')
  })
})
<|endoftext|>


<commit_before>import axios from "axios";
import cookie from "react-cookie";
import types from ".";
import { push } from "react-router-redux";
import { initialize, startSubmit, stopSubmit } from "redux-form";
import moment from "moment";

export function createExport(data, formName) {
  return dispatch => {
    dispatch(startSubmit(formName));
    return axios({
      url: "/api/jobs",
      method: "POST",
      contentType: "application/json; version=1.0",
      data,
      headers: {
        "X-CSRFToken": cookie.load("csrftoken")
      }
    })
      .then(rsp => {
        dispatch(stopSubmit(formName));
        dispatch(push(`/exports/detail/${rsp.data.uid}`));
      })
      .catch(err => {
        return dispatch(
          stopSubmit(formName, {
            ...err.response.data,
            _error:
              "Your export is invalid. Please check each page of the form for errors."
          })
        );
      });
  };
}

export function cloneExport(e) {
  return dispatch => {
    dispatch(push("/exports/new"));

    axios({
      url: `/api/jobs/${e.uid}/geom`
    })
      .then(rsp =>
        dispatch(
          initialize("ExportForm", {
            buffer_aoi: e.buffer_aoi,
            description: e.description,
            event: e.event,
            export_formats: e.export_formats,
            feature_selection: e.feature_selection,
            name: e.name,
            published: e.published,
            the_geom: rsp.data.the_geom,
            aoi: {
              description: "Cloned Area",
              geomType: "Polygon",
              title: "Custom Polygon"
            }
          })
        )
      )
      .catch(err => console.warn(err));
  };
}

export function runExport(jobUid) {
  return dispatch => {
    dispatch({
      type: types.RUNNING_EXPORT,
      id: jobUid
    });

    return axios({
      url: `/api/runs?job_uid=${jobUid}`,
      method: "POST",
      headers: {
        "X-CSRFToken": cookie.load("csrftoken")
      }
    }).then(rsp => dispatch(getRuns(jobUid)));
  };
}

export function getOverpassTimestamp() {
  return dispatch =>
    axios({
      url: "/api/overpass_timestamp"
    }).then(rsp => {
      dispatch({
        type: types.RECEIVED_OVERPASS_TIMESTAMP,
        lastUpdated: moment(rsp.data.timestamp).fromNow()
      });
    });
}

export function getExport(id) {
  return dispatch => {
    return axios({
      url: `/api/jobs/${id}`
    }).then(rsp => {
      dispatch({
        type: types.RECEIVED_EXPORT,
        id: id,
        job: rsp.data
      });
    });
  };
}

export function getExports(filters = {}, page = 1) {
  const itemsPerPage = 20;

  return dispatch => {
    return axios({
      params: {
        ...filters,
        limit: itemsPerPage,
        offset: Math.max(0, (page - 1) * itemsPerPage)
      },
      url: "/api/jobs"
    }).then(({ data: response }) => {
      dispatch({
        type: types.RECEIVED_EXPORT_LIST,
        activePage: page,
        itemsPerPage,
        response
      });
    });
  };
}

export function getRuns(jobUid) {
  return dispatch => {
    return axios({
      url: `/api/runs?job_uid=${jobUid}`
    }).then(rsp => {
      dispatch({
        type: types.RECEIVED_RUNS,
        id: jobUid,
        runs: rsp.data
      });
    });
  };
}

// TODO this should be managed beneath the ExportAOI component
export function updateMode(mode) {
  return {
    type: types.SET_MODE,
    mode: mode
  };
}
<commit_msg>Log Overpass update errors<commit_after>import axios from "axios";
import cookie from "react-cookie";
import types from ".";
import { push } from "react-router-redux";
import { initialize, startSubmit, stopSubmit } from "redux-form";
import moment from "moment";

export function createExport(data, formName) {
  return dispatch => {
    dispatch(startSubmit(formName));
    return axios({
      url: "/api/jobs",
      method: "POST",
      contentType: "application/json; version=1.0",
      data,
      headers: {
        "X-CSRFToken": cookie.load("csrftoken")
      }
    })
      .then(rsp => {
        dispatch(stopSubmit(formName));
        dispatch(push(`/exports/detail/${rsp.data.uid}`));
      })
      .catch(err => {
        return dispatch(
          stopSubmit(formName, {
            ...err.response.data,
            _error:
              "Your export is invalid. Please check each page of the form for errors."
          })
        );
      });
  };
}

export function cloneExport(e) {
  return dispatch => {
    dispatch(push("/exports/new"));

    axios({
      url: `/api/jobs/${e.uid}/geom`
    })
      .then(rsp =>
        dispatch(
          initialize("ExportForm", {
            buffer_aoi: e.buffer_aoi,
            description: e.description,
            event: e.event,
            export_formats: e.export_formats,
            feature_selection: e.feature_selection,
            name: e.name,
            published: e.published,
            the_geom: rsp.data.the_geom,
            aoi: {
              description: "Cloned Area",
              geomType: "Polygon",
              title: "Custom Polygon"
            }
          })
        )
      )
      .catch(err => console.warn(err));
  };
}

export function runExport(jobUid) {
  return dispatch => {
    dispatch({
      type: types.RUNNING_EXPORT,
      id: jobUid
    });

    return axios({
      url: `/api/runs?job_uid=${jobUid}`,
      method: "POST",
      headers: {
        "X-CSRFToken": cookie.load("csrftoken")
      }
    }).then(rsp => dispatch(getRuns(jobUid)));
  };
}

export function getOverpassTimestamp() {
  return dispatch =>
    axios({
      url: "/api/overpass_timestamp"
    })
      .then(rsp => {
        dispatch({
          type: types.RECEIVED_OVERPASS_TIMESTAMP,
          lastUpdated: moment(rsp.data.timestamp).fromNow()
        });
      })
      .catch(err => console.warn(err));
}

export function getExport(id) {
  return dispatch => {
    return axios({
      url: `/api/jobs/${id}`
    }).then(rsp => {
      dispatch({
        type: types.RECEIVED_EXPORT,
        id: id,
        job: rsp.data
      });
    });
  };
}

export function getExports(filters = {}, page = 1) {
  const itemsPerPage = 20;

  return dispatch => {
    return axios({
      params: {
        ...filters,
        limit: itemsPerPage,
        offset: Math.max(0, (page - 1) * itemsPerPage)
      },
      url: "/api/jobs"
    }).then(({ data: response }) => {
      dispatch({
        type: types.RECEIVED_EXPORT_LIST,
        activePage: page,
        itemsPerPage,
        response
      });
    });
  };
}

export function getRuns(jobUid) {
  return dispatch => {
    return axios({
      url: `/api/runs?job_uid=${jobUid}`
    }).then(rsp => {
      dispatch({
        type: types.RECEIVED_RUNS,
        id: jobUid,
        runs: rsp.data
      });
    });
  };
}

// TODO this should be managed beneath the ExportAOI component
export function updateMode(mode) {
  return {
    type: types.SET_MODE,
    mode: mode
  };
}
<|endoftext|>


<commit_before>const http = require('http');
const url = require('url');
const fs = require('fs');
const nearestColor = require('../node_modules/nearest-color/nearestColor.js');
const colors = JSON.parse(
  fs.readFileSync(__dirname + '/../dist/colornames.json', 'utf8')
);
const port = process.env.PORT || 8080;
const currentVersion = 'v1';
const APIurl = ''; // subfolder for the API
const baseUrl = `${APIurl}${currentVersion}/`;

/**
 * disassembles a HEX color to its RGB components
 * @param   {string} hex hex color representatin
 * @return  {object}     {r,g,b}
 */
const hexToRgb = (hex) => {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16),
  } : null;
};

// object containing the name:hex pairs for nearestColor()
const colorsObj = {};

colors.forEach((c) => {
  // populates object needed for nearestColor()
  colorsObj[c.name] = c.hex;
  // transform hex to RGB
  c.rgb = hexToRgb(c.hex);
});

const nc = nearestColor.from(colorsObj);
/**
 * validates a hex color
 * @param   {string} color hex representation of color
 * @return {boolen}
 */
const validateColor = (color) => (
  /(^[0-9A-F]{6}$)|(^[0-9A-F]{3}$)/i.test(color)
);

/**
 * names an array of colors
 * @param   {array} colorArr array containing hex values without the hash
 * @return  {object}         object containing all nearest colors
 */
const nameColors = (colorArr) => {
  let colors = {};
  colorArr.forEach((hex) => {
    const closestColor = nc('#' + hex);
    colors['#' + hex] = {
      name: closestColor.name,
      hex: closestColor.value,
      rgb: closestColor.rgb,
      isExactMatch: closestColor.value.substr(1) === hex,
    };
  });
  return colors;
};

const httpRespond = (response, responseObj = {}, statusCode = 200) => {
  response.writeHead(statusCode, {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS',
    'Access-Control-Allow-Credentials': false,
    'Access-Control-Max-Age': '86400',
    'Access-Control-Allow-Headers': 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept',
    'Content-Type': 'application/json; charset=utf-8',
  });
  // ends the response with the API answer
  response.end(JSON.stringify(responseObj));
};

const requestHandler = (request, response) => {
  const requestUrl = url.parse(request.url);
  const isAPI = requestUrl.pathname.indexOf(baseUrl) !== -1;
  let statusCode = 404;
  let colorQuery = request.url.toLowerCase();
      colorQuery = colorQuery.split(baseUrl)[1] || '';

  const urlColorList = colorQuery.split(',');
  const responseObj = {status: 'Someting went wrong', colors: {}};
  const invalidColors = urlColorList.filter((hex) => (
    !validateColor(hex) && hex
  ));

  if (!isAPI) {
    responseObj.status = 'invalid URL: make sure to provide the API version';
    statusCode = 404;
  } else if (!urlColorList[0]) {
    responseObj.status = `no color(s) provided, returning all the ${colors.length} colors`;
    responseObj.colors = colors;
    statusCode = 200;
  } else if (invalidColors.length) {
    responseObj.status = `'${invalidColors.join(', ')}' is not a valid HEX color`;
    statusCode = 404;
  } else if (!invalidColors.length && isAPI) {
    responseObj.status = `names for '${urlColorList.join(', ')}' returned`;
    responseObj.colors = nameColors(urlColorList);
    statusCode = 200;
  }

  httpRespond(response, responseObj, statusCode);
};

const server = http.createServer(requestHandler);
server.listen(port, '0.0.0.0', (error) => {
  if (error) {
    return console.log(`something terrible happened: ${error}`);
  }
  console.log(`Server running and listening on port ${port}`);
  console.log(`http://localhost:${port}/${baseUrl}`);
});
<commit_msg>fix($server): Makes sure hex triplets are compared correctly<commit_after>const http = require('http');
const url = require('url');
const fs = require('fs');
const nearestColor = require('../node_modules/nearest-color/nearestColor.js');
const colors = JSON.parse(
  fs.readFileSync(__dirname + '/../dist/colornames.json', 'utf8')
);
const port = process.env.PORT || 8080;
const currentVersion = 'v1';
const APIurl = ''; // subfolder for the API
const baseUrl = `${APIurl}${currentVersion}/`;

/**
 * disassembles a HEX color to its RGB components
 * @param   {string} hex hex color representatin
 * @return  {object}     {r,g,b}
 */
const hexToRgb = (hex) => {
  const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  hex = hex.replace(shorthandRegex, function(m, r, g, b) {
    return r + r + g + g + b + b;
  });

  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16),
  } : null;
};

// object containing the name:hex pairs for nearestColor()
const colorsObj = {};

colors.forEach((c) => {
  // populates object needed for nearestColor()
  colorsObj[c.name] = c.hex;
  // transform hex to RGB
  c.rgb = hexToRgb(c.hex);
});

const nc = nearestColor.from(colorsObj);
/**
 * validates a hex color
 * @param   {string} color hex representation of color
 * @return {boolen}
 */
const validateColor = (color) => (
  /(^[0-9A-F]{6}$)|(^[0-9A-F]{3}$)/i.test(color)
);

/**
 * names an array of colors
 * @param   {array} colorArr array containing hex values without the hash
 * @return  {object}         object containing all nearest colors
 */
const nameColors = (colorArr) => {
  let colors = {};
  colorArr.forEach((hex) => {
    const closestColor = nc(`#${hex}`);
    const rgb = hexToRgb(hex);
    colors[`#${hex}`] = {
      name: closestColor.name,
      hex: closestColor.value,
      rgb: closestColor.rgb,
      isExactMatch: closestColor.rgb.r === rgb.r &&
                    closestColor.rgb.g === rgb.g &&
                    closestColor.rgb.b === rgb.b
    };
  });
  return colors;
};

const httpRespond = (response, responseObj = {}, statusCode = 200) => {
  response.writeHead(statusCode, {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS',
    'Access-Control-Allow-Credentials': false,
    'Access-Control-Max-Age': '86400',
    'Access-Control-Allow-Headers': 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept',
    'Content-Type': 'application/json; charset=utf-8',
  });
  // ends the response with the API answer
  response.end(JSON.stringify(responseObj));
};

const requestHandler = (request, response) => {
  const requestUrl = url.parse(request.url);
  const isAPI = requestUrl.pathname.indexOf(baseUrl) !== -1;
  let statusCode = 404;
  let colorQuery = request.url.toLowerCase();
      colorQuery = colorQuery.split(baseUrl)[1] || '';

  const urlColorList = colorQuery.split(',');
  const responseObj = {status: 'Someting went wrong', colors: {}};
  const invalidColors = urlColorList.filter((hex) => (
    !validateColor(hex) && hex
  ));

  if (!isAPI) {
    responseObj.status = 'invalid URL: make sure to provide the API version';
    statusCode = 404;
  } else if (!urlColorList[0]) {
    responseObj.status = `no color(s) provided, returning all the ${colors.length} colors`;
    responseObj.colors = colors;
    statusCode = 200;
  } else if (invalidColors.length) {
    responseObj.status = `'${invalidColors.join(', ')}' is not a valid HEX color`;
    statusCode = 404;
  } else if (!invalidColors.length && isAPI) {
    responseObj.status = `names for '${urlColorList.join(', ')}' returned`;
    responseObj.colors = nameColors(urlColorList);
    statusCode = 200;
  }

  httpRespond(response, responseObj, statusCode);
};

const server = http.createServer(requestHandler);
server.listen(port, '0.0.0.0', (error) => {
  if (error) {
    return console.log(`something terrible happened: ${error}`);
  }
  console.log(`Server running and listening on port ${port}`);
  console.log(`http://localhost:${port}/${baseUrl}`);
});
<|endoftext|>


<commit_before>import React from "react";
import { formatCredits } from "utils";
import lbry from "../lbry.js";

//component/icon.js
export class Icon extends React.PureComponent {
  static propTypes = {
    icon: React.PropTypes.string.isRequired,
    className: React.PropTypes.string,
    fixed: React.PropTypes.bool,
  };

  render() {
    const { fixed, className } = this.props;
    const spanClassName =
      "icon " +
      ("fixed" in this.props ? "icon-fixed-width " : "") +
      this.props.icon +
      " " +
      (this.props.className || "");
    return ;
  }
}

export class TruncatedText extends React.PureComponent {
  static propTypes = {
    lines: React.PropTypes.number,
  };

  static defaultProps = {
    lines: null,
  };

  render() {
    return (

        {this.props.children}

    );
  }
}

export class BusyMessage extends React.PureComponent {
  static propTypes = {
    message: React.PropTypes.string,
  };

  render() {
    return (
      {this.props.message}
    );
  }
}

export class CurrencySymbol extends React.PureComponent {
  render() {
    return LBC;
  }
}

export class CreditAmount extends React.PureComponent {
  static propTypes = {
    amount: React.PropTypes.number.isRequired,
    precision: React.PropTypes.number,
    isEstimate: React.PropTypes.bool,
    label: React.PropTypes.bool,
    showFree: React.PropTypes.bool,
    look: React.PropTypes.oneOf(["indicator", "plain"]),
  };

  static defaultProps = {
    precision: 3,
    label: true,
    showFree: false,
    look: "indicator",
  };

  render() {
    const formattedAmount = formatCredits(
      this.props.amount,
      this.props.precision
    );

    let amountText;
    if (this.props.showFree && parseFloat(formattedAmount) === 0) {
      amountText = __("free");
    } else if (this.props.label) {
      amountText =
        formattedAmount +
        " " +
        (parseFloat(formattedAmount) == 1 ? __("credit") : __("credits"));
    } else {
      amountText = formattedAmount;
    }

    return (
      <span className={`credit-amount credit-amount--${this.props.look}`}>

          {amountText}

        {this.props.isEstimate
          ?
              *

          : null}

    );
  }
}

let addressStyle = {
  fontFamily:
    '"Consolas", "Lucida Console", "Adobe Source Code Pro", monospace',
};
export class Address extends React.PureComponent {
  static propTypes = {
    address: React.PropTypes.string,
  };

  constructor(props) {
    super(props);

    this._inputElem = null;
  }

  render() {
    return (
      <input
        className="input-copyable"
        type="text"
        ref={input => {
          this._inputElem = input;
        }}
        onFocus={() => {
          this._inputElem.select();
        }}
        style={addressStyle}
        readOnly="readonly"
        value={this.props.address || ""}
      />
    );
  }
}

export class Thumbnail extends React.PureComponent {
  static propTypes = {
    src: React.PropTypes.string,
  };

  handleError() {
    if (this.state.imageUrl != this._defaultImageUri) {
      this.setState({
        imageUri: this._defaultImageUri,
      });
    }
  }

  constructor(props) {
    super(props);

    this._defaultImageUri = lbry.imagePath("default-thumb.svg");
    this._maxLoadTime = 10000;
    this._isMounted = false;

    this.state = {
      imageUri: this.props.src || this._defaultImageUri,
    };
  }

  componentDidMount() {
    this._isMounted = true;
    setTimeout(() => {
      if (this._isMounted && !this.refs.img.complete) {
        this.setState({
          imageUri: this._defaultImageUri,
        });
      }
    }, this._maxLoadTime);
  }

  componentWillUnmount() {
    this._isMounted = false;
  }

  render() {
    const className = this.props.className ? this.props.className : "",
      otherProps = Object.assign({}, this.props);
    delete otherProps.className;
    return (
       {
          this.handleError();
        }}
        {...otherProps}
        className={className}
        src={this.state.imageUri}
      />
    );
  }
}
<commit_msg>set precision to 2, improve rendering of amounts below precision<commit_after>import React from "react";
import { formatCredits } from "utils";
import lbry from "../lbry.js";

//component/icon.js
export class Icon extends React.PureComponent {
  static propTypes = {
    icon: React.PropTypes.string.isRequired,
    className: React.PropTypes.string,
    fixed: React.PropTypes.bool,
  };

  render() {
    const { fixed, className } = this.props;
    const spanClassName =
      "icon " +
      ("fixed" in this.props ? "icon-fixed-width " : "") +
      this.props.icon +
      " " +
      (this.props.className || "");
    return ;
  }
}

export class TruncatedText extends React.PureComponent {
  static propTypes = {
    lines: React.PropTypes.number,
  };

  static defaultProps = {
    lines: null,
  };

  render() {
    return (

        {this.props.children}

    );
  }
}

export class BusyMessage extends React.PureComponent {
  static propTypes = {
    message: React.PropTypes.string,
  };

  render() {
    return (
      {this.props.message}
    );
  }
}

export class CurrencySymbol extends React.PureComponent {
  render() {
    return LBC;
  }
}

export class CreditAmount extends React.PureComponent {
  static propTypes = {
    amount: React.PropTypes.number.isRequired,
    precision: React.PropTypes.number,
    isEstimate: React.PropTypes.bool,
    label: React.PropTypes.bool,
    showFree: React.PropTypes.bool,
    look: React.PropTypes.oneOf(["indicator", "plain"]),
  };

  static defaultProps = {
    precision: 2,
    label: true,
    showFree: false,
    look: "indicator",
  };

  render() {
    const minimumRenderableAmount = Math.pow(10, -1 * this.props.precision);
    const { amount, precision } = this.props;

    let formattedAmount = amount > 0 && amount < minimumRenderableAmount
      ? "<" + minimumRenderableAmount
      : formatCredits(amount, precision);

    let amountText;
    if (this.props.showFree && parseFloat(this.props.amount) === 0) {
      amountText = __("free");
    } else if (this.props.label) {
      amountText =
        formattedAmount +
        " " +
        (parseFloat(amount) == 1 ? __("credit") : __("credits"));
    } else {
      amountText = formattedAmount;
    }

    return (
      <span className={`credit-amount credit-amount--${this.props.look}`}>

          {amountText}

        {this.props.isEstimate
          ?
              *

          : null}

    );
  }
}

let addressStyle = {
  fontFamily:
    '"Consolas", "Lucida Console", "Adobe Source Code Pro", monospace',
};
export class Address extends React.PureComponent {
  static propTypes = {
    address: React.PropTypes.string,
  };

  constructor(props) {
    super(props);

    this._inputElem = null;
  }

  render() {
    return (
      <input
        className="input-copyable"
        type="text"
        ref={input => {
          this._inputElem = input;
        }}
        onFocus={() => {
          this._inputElem.select();
        }}
        style={addressStyle}
        readOnly="readonly"
        value={this.props.address || ""}
      />
    );
  }
}

export class Thumbnail extends React.PureComponent {
  static propTypes = {
    src: React.PropTypes.string,
  };

  handleError() {
    if (this.state.imageUrl != this._defaultImageUri) {
      this.setState({
        imageUri: this._defaultImageUri,
      });
    }
  }

  constructor(props) {
    super(props);

    this._defaultImageUri = lbry.imagePath("default-thumb.svg");
    this._maxLoadTime = 10000;
    this._isMounted = false;

    this.state = {
      imageUri: this.props.src || this._defaultImageUri,
    };
  }

  componentDidMount() {
    this._isMounted = true;
    setTimeout(() => {
      if (this._isMounted && !this.refs.img.complete) {
        this.setState({
          imageUri: this._defaultImageUri,
        });
      }
    }, this._maxLoadTime);
  }

  componentWillUnmount() {
    this._isMounted = false;
  }

  render() {
    const className = this.props.className ? this.props.className : "",
      otherProps = Object.assign({}, this.props);
    delete otherProps.className;
    return (
       {
          this.handleError();
        }}
        {...otherProps}
        className={className}
        src={this.state.imageUri}
      />
    );
  }
}
<|endoftext|>


<commit_before>import axios from 'axios';
import { unique } from 'src/modules/group-by';

export default {
  state: {
    filter: 'tipps',
    state: '',
    journeyLoaded: false,
    tippsLoaded: false,
    journey: [],
    journeyPoints: [],
    tipps: [],
    info: false,
  },
  mutations: {
    UPDATE_FILTER: (state, action) => { state.filter = action.filter },
    UPDATE_INFO: (state, action) => { state.info = action.info },
    UPDATE_STATE: (state, action) => { state.state = action.state },
    UPDATE_JOURNEY: (state, action) => {
      state.journeyLoaded = true;
      state.journey = action.journey;
      state.journeyPoints = action.journeyPoints;
    },
    UPDATE_TIPPS: (state, action) => {
      state.tippsLoaded = true;
      state.tipps = action.tipps;
    },
  },
  actions: {
    LOAD_JOURNEY: async ({ state, commit }) => {
      if (state.journeyLoaded) return;

      // Get journey data
      const { data: journeyData } = await axios.get('/api/journeys')
        .catch((err) => {
          console.log(err);
        });

      const journey = journeyData.map(location => ({
        lat: location.lat,
        lng: location.lng,
      }));

      const journeyPoints = unique(journeyData, marker => [
        marker.description,
        marker.lat,
        marker.lng,
      ]);

      commit('UPDATE_JOURNEY', {
        journey,
        journeyPoints,
      });
    },
    LOAD_TIPPS: async ({ state, commit }) => {
      if (state.tippsLoaded) return;

      let { data: tipps } = await axios.get('/api/tipps')
        .catch(err => console.log(err));

      // Add title
      tipps = tipps.map((tipp) => {
        const abbr = tipp.text.substring(0, 22);
        tipp.title = `${tipp.name}s Tipp: ${abbr}${tipp.text.length > 22 ? '...' : ''}`;
        return tipp;
      });

      commit('UPDATE_TIPPS', { tipps });
    },
  },
}
<commit_msg>Remove console logs<commit_after>import axios from 'axios';
import { unique } from 'src/modules/group-by';

export default {
  state: {
    filter: 'tipps',
    state: '',
    journeyLoaded: false,
    tippsLoaded: false,
    journey: [],
    journeyPoints: [],
    tipps: [],
    info: false,
  },
  mutations: {
    UPDATE_FILTER: (state, action) => { state.filter = action.filter },
    UPDATE_INFO: (state, action) => { state.info = action.info },
    UPDATE_STATE: (state, action) => { state.state = action.state },
    UPDATE_JOURNEY: (state, action) => {
      state.journeyLoaded = true;
      state.journey = action.journey;
      state.journeyPoints = action.journeyPoints;
    },
    UPDATE_TIPPS: (state, action) => {
      state.tippsLoaded = true;
      state.tipps = action.tipps;
    },
  },
  actions: {
    LOAD_JOURNEY: async ({ state, commit }) => {
      if (state.journeyLoaded) return;

      // Get journey data
      const { data: journeyData } = await axios.get('/api/journeys')

      const journey = journeyData.map(location => ({
        lat: location.lat,
        lng: location.lng,
      }));

      const journeyPoints = unique(journeyData, marker => [
        marker.description,
        marker.lat,
        marker.lng,
      ]);

      commit('UPDATE_JOURNEY', {
        journey,
        journeyPoints,
      });
    },
    LOAD_TIPPS: async ({ state, commit }) => {
      if (state.tippsLoaded) return;

      let { data: tipps } = await axios.get('/api/tipps')
      // .catch(err => console.log(err));

      // Add title
      tipps = tipps.map((tipp) => {
        const abbr = tipp.text.substring(0, 22);
        tipp.title = `${tipp.name}s Tipp: ${abbr}${tipp.text.length > 22 ? '...' : ''}`;
        return tipp;
      });

      commit('UPDATE_TIPPS', { tipps });
    },
  },
}
<|endoftext|>


<commit_before>var control = require('./control');
var m = require('mithril');

function preventing(f) {
  return function(e) {
    if (e.preventDefault) {
      e.preventDefault();
    } else {
      // internet explorer
      e.returnValue = false;
    }
    f();
  };
}

module.exports = {
  bind: function(ctrl) {
    if (!window.Mousetrap) return;
    var kbd = window.Mousetrap;
    kbd.bind(['left', 'k'], preventing(function() {
      control.prev(ctrl);
      m.redraw();
    }));
    kbd.bind(['right', 'j'], preventing(function() {
      control.next(ctrl);
      m.redraw();
    }));
    kbd.bind(['up', '0'], preventing(function() {
      control.first(ctrl);
      m.redraw();
    }));
    kbd.bind(['down', '$'], preventing(function() {
      control.last(ctrl);
      m.redraw();
    }));
    kbd.bind('space', preventing(function() {
      if (ctrl.vm.mode !== 'view') return;
      if (ctrl.getCeval().enabled()) ctrl.playBestMove();
      else ctrl.toggleCeval();
    }));
  }
};
<commit_msg>puzzle: toggle local eval with <l><commit_after>var control = require('./control');
var m = require('mithril');

function preventing(f) {
  return function(e) {
    if (e.preventDefault) {
      e.preventDefault();
    } else {
      // internet explorer
      e.returnValue = false;
    }
    f();
  };
}

module.exports = {
  bind: function(ctrl) {
    if (!window.Mousetrap) return;
    var kbd = window.Mousetrap;
    kbd.bind(['left', 'k'], preventing(function() {
      control.prev(ctrl);
      m.redraw();
    }));
    kbd.bind(['right', 'j'], preventing(function() {
      control.next(ctrl);
      m.redraw();
    }));
    kbd.bind(['up', '0'], preventing(function() {
      control.first(ctrl);
      m.redraw();
    }));
    kbd.bind(['down', '$'], preventing(function() {
      control.last(ctrl);
      m.redraw();
    }));
    kbd.bind('l', preventing(ctrl.toggleCeval));
    kbd.bind('space', preventing(function() {
      if (ctrl.vm.mode !== 'view') return;
      if (ctrl.getCeval().enabled()) ctrl.playBestMove();
      else ctrl.toggleCeval();
    }));
  }
};
<|endoftext|>


<commit_before>/*
  maintain a list of and selected pnode and span

  provide function to retrieve selected pcode

*/

var Reflux=require("reflux");
var actions=require("../actions/selection");

var store_selection=Reflux.createStore({
	listenables: [actions]
	,selections:{}
	,init:function() {
	}
	,removeOverlapSelection:function(selections,start,len) {
		return selections.filter(function(sel){
			return (sel[0]>start+len || sel[0]+sel[1]<start);
		});
	}
	,hasSameSelection:function(selections,start,len) {
		for (var i=0;i<selections.length;i++) {
			var sel=selections[i];
			if (sel[0]==start &&sel[1]==len) return i;
		}
		return -1;
	}
	,onClearSelection:function(wid) {
		this.onSetSelection({},wid);
	}
	,onClearSelections:function() {
		var keys=Object.keys(this.selections);
		var cleared={};
		for (var i=0;i<keys.length;i++) {
			cleared[keys[i]]=[];
		}
		this.onSetSelections(cleared);
	}
	,onAddSelection:function(wid,existingselections,start,len,append) {
		var selections=JSON.parse(JSON.stringify(existingselections));
		var oldselections=selections;
		var same=this.hasSameSelection(selections,start,len);
		var updated=true;

		if (same>-1) { //toggle
			selections.splice(same,1);
		} else {
			oldlength=selections.length;
			selections=this.removeOverlapSelection(selections,start,len);
			if (append && len) {
				selections.push([start,len]);
			} else {
				if (len) {
					selections=[[start,len]];
				} else {
					if (selections.length) selections=[];
					else updated=false;
				}
			}
		}

		if (updated) {
			actions.setSelection(selections , wid);
		}
	}
	,onSetSelection:function(selections,wid) {
		this.selections[wid]=selections;
		actions.clearHighlights();
		this.trigger(this.selections,wid);
	}
	,onSetSelections:function(selections) {
		for (var i in selections) {
			this.selections[i]=selections[i];
		}
		var updated=Object.keys(selections);
		for (var i=0;i<updated.length;i++){
			this.trigger(this.selections,updated[i]); //notify affected view
		}
		actions.clearHighlights();
	}
	,getSelections:function(){
		return this.selections;
	}
	,getSelection:function(wid){
		return this.selections[wid];
	}
});

module.exports=store_selection;<commit_msg>remove wid with empty selection<commit_after>/*
  maintain a list of and selected pnode and span

  provide function to retrieve selected pcode

*/

var Reflux=require("reflux");
var actions=require("../actions/selection");

var store_selection=Reflux.createStore({
	listenables: [actions]
	,selections:{}
	,init:function() {
	}
	,removeOverlapSelection:function(selections,start,len) {
		return selections.filter(function(sel){
			return (sel[0]>start+len || sel[0]+sel[1]<start);
		});
	}
	,hasSameSelection:function(selections,start,len) {
		for (var i=0;i<selections.length;i++) {
			var sel=selections[i];
			if (sel[0]==start &&sel[1]==len) return i;
		}
		return -1;
	}
	,onClearSelection:function(wid) {
		this.onSetSelection({},wid);
	}
	,onClearSelections:function() {
		var keys=Object.keys(this.selections);
		var cleared={};
		for (var i=0;i<keys.length;i++) {
			cleared[keys[i]]=[];
		}
		this.onSetSelections(cleared);
	}
	,onAddSelection:function(wid,existingselections,start,len,append) {
		var selections=JSON.parse(JSON.stringify(existingselections));
		var oldselections=selections;
		var same=this.hasSameSelection(selections,start,len);
		var updated=true;

		if (same>-1) { //toggle
			selections.splice(same,1);
		} else {
			oldlength=selections.length;
			selections=this.removeOverlapSelection(selections,start,len);
			if (append && len) {
				selections.push([start,len]);
			} else {
				if (len) {
					selections=[[start,len]];
				} else {
					if (selections.length) selections=[];
					else updated=false;
				}
			}
		}

		if (updated) {
			actions.setSelection(selections , wid);
		}
	}
	,onSetSelection:function(selections,wid) {
		this.selections[wid]=selections;
		actions.clearHighlights();
		this.trigger(this.selections,wid);

		//remove empty selection after updating views
		if (selections.length==0) {
			delete this.selections[wid];
		}
	}
	,onSetSelections:function(selections) {
		for (var i in selections) {
			this.selections[i]=selections[i];
		}
		var updated=Object.keys(selections);
		for (var i=0;i<updated.length;i++){
			this.trigger(this.selections,updated[i]); //notify affected view
		}
		actions.clearHighlights();
	}
	,getSelections:function(){
		return this.selections;
	}
	,getSelection:function(wid){
		return this.selections[wid];
	}
});

module.exports=store_selection;<|endoftext|>