<commit_before>// VISUALIZATION
// ------------------------------------------

var stageWidth = 1600;
var stageHeight = 12000;
var stageSvg = null;

function visualizationInit() {
    var margin = {top: 20, right: 500, bottom: 0, left: 20};

    stageSvg = d3.select("body").append("svg")
        .attr("width", stageWidth + margin.left + margin.right)
        .attr("height", stageHeight + margin.top + margin.bottom)
        .style("margin-left", margin.left + "px")
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
}

var visualize = function visualize(interval, data) {

    var intervalSeconds = interval * 60 * 1000;

    function truncate(str, maxLength, suffix) {
        if (str.length > maxLength) {
            str = str.substring(0, maxLength + 1);
            str = str.substring(0, Math.min(str.length, str.lastIndexOf(" ")));
            str = str + suffix;
        }
        return str;
    }

    data = data['aggregations']['timeframes']['buckets'];
    var timeframesCount = data.length;
    var clusterList = [];
    data.forEach(function (timeframeData) {
        timeframeData['timeframe_start'] = new Date(timeframeData['key']);
        timeframeData['timeframe_end'] = new Date((timeframeData['key'] + intervalSeconds));
        timeframeData['behaviors']['value']['clusters'].forEach(function (cluster) {
            var timeframe = [
                timeframeData['timeframe_start'],
                timeframeData['timeframe_end'],
                cluster['size'],
                timeframeData['behaviors']['value']['clusters_users_count']
            ];
            var percentValue = Math.round((timeframe[2]/timeframe[3])*10000)/100;
            if(percentValue > 1) {
                var representant = cluster['representants'][0];
                if (clusterList.hasOwnProperty(representant.pathHash)) {
                    clusterList[representant.pathHash].timeframes.push(timeframe)
                } else {
                    clusterList[representant.pathHash] = {
                        "timeframes": [
                            timeframe
                        ],
                        "path": representant['path'],
                        "name": representant['path'].join(', ')
                    }
                }
            }
        });
    });
    console.log(clusterList);
    // fill clusters between timeframes
    data.forEach(function (timeframeData) {
        timeframeData['timeframe_start'] = new Date(timeframeData['key']);
        timeframeData['timeframe_end'] = new Date((timeframeData['key'] + intervalSeconds));
        timeframeData['behaviors']['value']['clusters'].forEach(function (timeFrameCluster) {
            var timeframe = [
                timeframeData['timeframe_start'],
                timeframeData['timeframe_end'],
                timeFrameCluster['size'],
                timeframeData['behaviors']['value']['clusters_users_count']
            ];
            var percentValue = Math.round((timeframe[2]/timeframe[3])*10000)/100;
            if(percentValue > 1) {
                var representant = timeFrameCluster['representants'][0];
                var path = representant['path'];
                var name = path.join(', ');
                for (var key in clusterList) {
                    cluster = clusterList[key];
                    if(path.length > cluster.path.length && name.indexOf(cluster.name) !== -1) {
                        var found = false;
                        for (var timeframeKey in cluster.timeframes) {
                            if(cluster.timeframes[timeframeKey][0].getTime() == timeframe[0].getTime() && cluster.timeframes[timeframeKey][1].getTime() == timeframe[1].getTime()) {
//                                cluster.timeframes[timeframeKey][2] = cluster.timeframes[timeframeKey][2] + timeframe[2];
//                                console.log("boost " + cluster.name + "("+cluster.timeframes[timeframeKey][2]+") with " + name + " by " + timeframe[2] + " on " + timeframe[0]);
                                found = true;
                            }
                        }
                        if(!found) {
                            console.log("boost " + cluster.name + " with " + name + " by " + timeframe[2] + " on " + timeframe[0]);
                            clusterList[key].timeframes.push(timeframe);
                        }
                    }
                }
            }
        });
    });
    clusterList = clusterList.sort(function(a, b) {
        console.log("sorting");
        var aSum = a.timeframes.reduce( function(prev, next){
           return prev + next[2];
        }, 0);
        var bSum = b.timeframes.reduce( function(prev, next){
           return prev + next[2];
        }, 0);
        console.log(a.name + ": " + aSum);
        console.log(b.name + ": " + bSum);
        return parseFloat(aSum) - parseFloat(bSum);
    });
    data = [];
    for (var key in clusterList) {
        if (!clusterList.hasOwnProperty(key)) continue;
        data.push(clusterList[key]);
    }
    clusterList = null;

    var xMin = d3.min(data, function (cluster) {
        return d3.min(cluster['timeframes'], function (timeframe) {
            return timeframe[0];
        });
    });
    var xMax = d3.max(data, function (cluster) {
        return d3.max(cluster['timeframes'], function (timeframe) {
            return timeframe[0];
        });
    });
    console.log(xMin);
    console.log(xMax);

    var xScale = d3.time.scale()
        .domain([xMin, xMax])
        .range([0, stageWidth]);

    var timeFormat = d3.time.format("%m/%d %H:%M");
    xAxis = d3.svg.axis()
        .scale(xScale)
        .orient("top")
        .ticks(timeframesCount)
        .tickPadding(5)
        .tickFormat(timeFormat);

    stageSvg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + 0 + ")")
        .call(xAxis);

    var c = d3.scale.category20c();

    for (var j = 0; j < data.length; j++) {
        var g = stageSvg.append("g").attr("class", "journal");

        var circles = g.selectAll("circle")
            .data(data[j]['timeframes'])
            .enter()
            .append("circle");

        var text = g.selectAll("text")
            .data(data[j]['timeframes'])
            .enter()
            .append("text");

        var rScale = d3.scale.linear()
            .domain([0, d3.max(data[j]['timeframes'], function (d) {
                return d[3];
            })])
            .range([6, 14]);

        circles
            .attr("cx", function (d, i) {
                return xScale(d[0]);
            })
            .attr("cy", j * 30 + 20)
            .attr("r", function (d) {
                return rScale(d[2]);
            })
            .style("fill", function (d) {
                return c(j);
            });

        text
            .attr("y", j * 30 + 25)
            .attr("x", function (d, i) {
                return xScale(d[0]) - 5;
            })
            .attr("class", "value")
            .text(function (d) {
                return (Math.round((d[2]/d[3])*10000)/100)+"%";
            })
            .style("fill", function (d) {
                return c(j);
            })
            .style("display", "none");

        g.append("text")
            .attr("y", j * 30 + 25)
            .attr("x", stageWidth + 50)
            .attr("class", "label")
            .text(truncate(data[j]['name'], 60, "..."))
            .style("fill", function (d) {
                return c(j);
            })
            .on("mouseover", mouseover)
            .on("mouseout", mouseout);
    }
    ;

    function mouseover(p) {
        var g = d3.select(this).node().parentNode;
        d3.select(g).selectAll("circle").style("display", "none");
        d3.select(g).selectAll("text.value").style("display", "block");
    }

    function mouseout(p) {
        var g = d3.select(this).node().parentNode;
        d3.select(g).selectAll("circle").style("display", "block");
        d3.select(g).selectAll("text.value").style("display", "none");
    }
};<commit_msg>adjustments<commit_after>// VISUALIZATION
// ------------------------------------------

var stageWidth = 1600;
var stageHeight = 12000;
var stageSvg = null;

function visualizationInit() {
    var margin = {top: 20, right: 500, bottom: 0, left: 20};

    stageSvg = d3.select("body").append("svg")
        .attr("width", stageWidth + margin.left + margin.right)
        .attr("height", stageHeight + margin.top + margin.bottom)
        .style("margin-left", margin.left + "px")
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
}

var visualize = function visualize(interval, data) {

    var intervalSeconds = interval * 60 * 1000;

    function truncate(str, maxLength, suffix) {
        if (str.length > maxLength) {
            str = str.substring(0, maxLength + 1);
            str = str.substring(0, Math.min(str.length, str.lastIndexOf(" ")));
            str = str + suffix;
        }
        return str;
    }

    data = data['aggregations']['timeframes']['buckets'];
    var timeframesCount = data.length;
    var clusterList = [];
    data.forEach(function (timeframeData) {
        timeframeData['timeframe_start'] = new Date(timeframeData['key']);
        timeframeData['timeframe_end'] = new Date((timeframeData['key'] + intervalSeconds));
        timeframeData['behaviors']['value']['clusters'].forEach(function (cluster) {
            var timeframe = [
                timeframeData['timeframe_start'],
                timeframeData['timeframe_end'],
                cluster['size'],
                timeframeData['behaviors']['value']['clusters_users_count']
            ];
            var percentValue = Math.round((timeframe[2]/timeframe[3])*10000)/100;
            if(percentValue > 1) {
                var representant = cluster['representants'][0];
                if (clusterList.hasOwnProperty(representant.pathHash)) {
                    clusterList[representant.pathHash].timeframes.push(timeframe)
                } else {
                    clusterList[representant.pathHash] = {
                        "timeframes": [
                            timeframe
                        ],
                        "path": representant['path'],
                        "name": representant['path'].join(', ')
                    }
                }
            }
        });
    });
    console.log(clusterList);
    // fill clusters between timeframes
    data.forEach(function (timeframeData) {
        timeframeData['timeframe_start'] = new Date(timeframeData['key']);
        timeframeData['timeframe_end'] = new Date((timeframeData['key'] + intervalSeconds));
        timeframeData['behaviors']['value']['clusters'].forEach(function (timeFrameCluster) {
            var timeframe = [
                timeframeData['timeframe_start'],
                timeframeData['timeframe_end'],
                timeFrameCluster['size'],
                timeframeData['behaviors']['value']['clusters_users_count']
            ];
            var percentValue = Math.round((timeframe[2]/timeframe[3])*10000)/100;
            if(percentValue > 1) {
                var representant = timeFrameCluster['representants'][0];
                var path = representant['path'];
                var name = path.join(', ');
                for (var key in clusterList) {
                    cluster = clusterList[key];
                    if(path.length > cluster.path.length && name.indexOf(cluster.name) !== -1) {
                        var found = false;
                        for (var timeframeKey in cluster.timeframes) {
                            if(cluster.timeframes[timeframeKey][0].getTime() == timeframe[0].getTime() && cluster.timeframes[timeframeKey][1].getTime() == timeframe[1].getTime()) {
                                console.log("boost " + cluster.name + "("+cluster.timeframes[timeframeKey][2]+") with " + name + " by " + timeframe[2] + " on " + timeframe[0]);
                                cluster.timeframes[timeframeKey][2] = cluster.timeframes[timeframeKey][2] + timeframe[2];
                                found = true;
                            }
                        }
                        if(!found) {
                            console.log("boost " + cluster.name + " with " + name + " by " + timeframe[2] + " on " + timeframe[0]);
                            clusterList[key].timeframes.push(timeframe);
                        }
                    }
                }
            }
        });
    });
    clusterList = clusterList.sort(function(a, b) {
        console.log("sorting");
        var aSum = a.timeframes.reduce( function(prev, next){
           return prev + next[2];
        }, 0);
        var bSum = b.timeframes.reduce( function(prev, next){
           return prev + next[2];
        }, 0);
        console.log(a.name + ": " + aSum);
        console.log(b.name + ": " + bSum);
        return parseFloat(aSum) - parseFloat(bSum);
    });
    data = [];
    for (var key in clusterList) {
        if (!clusterList.hasOwnProperty(key)) continue;
        data.push(clusterList[key]);
    }
    clusterList = null;

    var xMin = d3.min(data, function (cluster) {
        return d3.min(cluster['timeframes'], function (timeframe) {
            return timeframe[0];
        });
    });
    var xMax = d3.max(data, function (cluster) {
        return d3.max(cluster['timeframes'], function (timeframe) {
            return timeframe[0];
        });
    });
    console.log(xMin);
    console.log(xMax);

    var xScale = d3.time.scale()
        .domain([xMin, xMax])
        .range([0, stageWidth]);

    var timeFormat = d3.time.format("%m/%d %H:%M");
    xAxis = d3.svg.axis()
        .scale(xScale)
        .orient("top")
        .ticks(timeframesCount)
        .tickPadding(5)
        .tickFormat(timeFormat);

    stageSvg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + 0 + ")")
        .call(xAxis);

    var c = d3.scale.category20c();

    for (var j = 0; j < data.length; j++) {
        var g = stageSvg.append("g").attr("class", "journal");

        var circles = g.selectAll("circle")
            .data(data[j]['timeframes'])
            .enter()
            .append("circle");

        var text = g.selectAll("text")
            .data(data[j]['timeframes'])
            .enter()
            .append("text");

        var rScale = d3.scale.linear()
            .domain([0, d3.max(data[j]['timeframes'], function (d) {
                return d[3];
            })])
            .range([6, 14]);

        circles
            .attr("cx", function (d, i) {
                return xScale(d[0]);
            })
            .attr("cy", j * 30 + 20)
            .attr("r", function (d) {
                return rScale(d[2]);
            })
            .style("fill", function (d) {
                return c(j);
            });

        text
            .attr("y", j * 30 + 25)
            .attr("x", function (d, i) {
                return xScale(d[0]) - 5;
            })
            .attr("class", "value")
            .text(function (d) {
                return (Math.round((d[2]/d[3])*10000)/100)+"%";
            })
            .style("fill", function (d) {
                return c(j);
            })
            .style("display", "none");

        g.append("text")
            .attr("y", j * 30 + 25)
            .attr("x", stageWidth + 50)
            .attr("class", "label")
            .text(truncate(data[j]['name'], 60, "..."))
            .style("fill", function (d) {
                return c(j);
            })
            .on("mouseover", mouseover)
            .on("mouseout", mouseout);
    }
    ;

    function mouseover(p) {
        var g = d3.select(this).node().parentNode;
        d3.select(g).selectAll("circle").style("display", "none");
        d3.select(g).selectAll("text.value").style("display", "block");
    }

    function mouseout(p) {
        var g = d3.select(this).node().parentNode;
        d3.select(g).selectAll("circle").style("display", "block");
        d3.select(g).selectAll("text.value").style("display", "none");
    }
};<|endoftext|>


<commit_before>// Data object contains values read from data-relay
// Accessed with Data.state.______
//
// updateCockpit() is called whenever data is recieved

var Cockpit = (function ($, Data, Log, Network) {

    $(document).ready(function () {
        //Initialize instruments
        drawArtificalHorizon(0, 0);
        drawPitch(0);
        drawRoll(0);
        drawYaw(0);
        drawBattery(0);
        drawScale(0,300,"altimeter","Altitude");

        //Buttons
        $('#goHome').on('click', function () {
            command = "return_home\r\n";
            Network.write(command);
            Log.write(command);
        });
    });

    function drawYaw(yaw) {
        //Initialize canvas
        var canvas = document.getElementById("yaw");
        canvas.height = 200;
        canvas.width = 200;
        canvas.title = yaw*180/Math.PI + "°";
        var context = canvas.getContext("2d");
        context.clearRect(0, 0, canvas.width, canvas.height);

        //Ground
        context.fillStyle = "#8bc34a";
        context.beginPath();
        context.arc(100, 100, 100, 0, Math.PI * 2);
        context.fill();

        //Border
        context.strokeStyle = "black";
        context.lineWidth = 2;
        context.beginPath();
        context.arc(100, 100, 99, 0, 2 * Math.PI);
        context.stroke();

        //Text
        var yawText = (parseFloat(yaw) * (180/Math.PI)).toFixed(2);
        yawText = yawText.toString() + "°";
        context.fillStyle = "black";
        context.font = "20px Calibri";
        context.textAlign="center";
        context.fillText(yawText, 100, 30);

        //Indicator
        image = document.createElement('img');
        image.src = "yaw.png";
        context.translate(36, 36);
        context.translate(64, 64);
        context.rotate(yaw);
        context.drawImage(image, -64, -64);
    }

    function drawRoll(roll) {
        //Initialize canvas
        var canvas = document.getElementById("roll");
        canvas.height = 200;
        canvas.width = 200;
        canvas.title = roll*180/Math.PI + "°";
        var context = canvas.getContext("2d");
        context.clearRect(0, 0, canvas.width, canvas.height);

        //Sky
        context.fillStyle = "#03a9f4";
        context.beginPath();
        context.arc(100, 100, 100, Math.PI, 2 * Math.PI);
        context.fill();

        //Ground
        context.fillStyle = "#8bc34a";
        context.beginPath();
        context.arc(100, 100, 100, 0, Math.PI);
        context.fill();

        //Border
        context.strokeStyle = "black";
        context.lineWidth = 2;
        context.beginPath();
        context.arc(100, 100, 99, 0, 2 * Math.PI);
        context.stroke();

        //Text
        var rollText = (parseFloat(roll) * (180/Math.PI)).toFixed(2);
        rollText = rollText.toString() + "°";
        context.fillStyle = "black";
        context.font = "20px Calibri";
        context.textAlign="center";
        context.fillText(rollText, 100, 30);

        //Indicator
        image = document.createElement('img');
        image.src = "roll.png";
        context.translate(36, 36);
        context.translate(64, 64);
        context.rotate(roll);
        context.drawImage(image, -64, -64);
    }

    function drawPitch(pitch) {
        //Initialize canvas
        var canvas = document.getElementById("pitch");
        canvas.height = 200;
        canvas.width = 200;
        canvas.title = pitch*180/Math.PI + "°";
        var context = canvas.getContext("2d");
        context.clearRect(0, 0, canvas.width, canvas.height);

        //Sky
        context.fillStyle = "#03a9f4";
        context.beginPath();
        context.arc(100, 100, 100, Math.PI, 2 * Math.PI);
        context.fill();

        //Ground
        context.fillStyle = "#8bc34a";
        context.beginPath();
        context.arc(100, 100, 100, 0, Math.PI);
        context.fill();

        //Border
        context.strokeStyle = "black";
        context.lineWidth = 2;
        context.beginPath();
        context.arc(100, 100, 99, 0, 2 * Math.PI);
        context.stroke();

        //Text
        var pitchText = (parseFloat(pitch) * (180/Math.PI)).toFixed(2);
        pitchText = pitchText.toString() + "°";
        context.fillStyle = "black";
        context.font = "20px Calibri";
        context.textAlign="center";
        context.fillText(pitchText, 100, 30);

        //Indicator
        image = document.createElement('img');
        image.src = "pitch.png";
        context.translate(36, 36);
        context.translate(64, 64);
        context.rotate(pitch);
        context.drawImage(image, -64, -64);
    }

    function drawArtificalHorizon(roll, pitch) {
        //Initialize canvas
        var canvas = document.getElementById("horizon");
        canvas.height = 200;
        canvas.width = 200;
        var context = canvas.getContext("2d");
        context.clearRect(0, 0, canvas.width, canvas.height);

        //Sky
        context.fillStyle = "#03a9f4";
        context.beginPath();
        context.arc(100, 100, 100, Math.PI + roll - pitch, 2 * Math.PI + roll + pitch);
        context.fill();

        //Ground
        context.fillStyle = "#795548";
        context.beginPath();
        context.arc(100, 100, 100, 0 + roll + pitch, Math.PI + roll - pitch);
        context.fill();

        //Border
        context.strokeStyle = "black";
        context.lineWidth = 2;
        context.beginPath();
        context.arc(100, 100, 99, 0, 2 * Math.PI);
        context.stroke();

        //Center
        context.fillStyle = "black";
        context.beginPath();
        context.lineWidth = 2;
        context.arc(100, 100, 2, 0, 2 * Math.PI);
        context.fill();
        context.beginPath();
        context.moveTo(120, 100);
        context.lineTo(110, 100);
        context.stroke();
        context.arc(100, 100, 10, 0, Math.PI);
        context.stroke();
        context.lineTo(80, 100);
        context.stroke();
    }

    function drawBattery(batteryLevel) {
        //Initialize canvas
        var canvas = document.getElementById("battery");
        canvas.height = 60;
        canvas.width = 100;
        var context = canvas.getContext("2d");
        context.clearRect(0, 0, canvas.width, canvas.height);

        //Outline
        context.fillStyle = "black";
        context.lineWidth = 5;
        context.rect(10,5,80,50);
        context.stroke();
        context.fillRect(0,20,10,20);
        context.stroke();

        //Fill
        if (batteryLevel <= 100 && batteryLevel >= 80) {
            context.fillStyle = "green";
        }
        else if (batteryLevel >= 20 && batteryLevel < 80) {
            context.fillStyle = "yellow";
        }
        else {
            context.fillStyle = "red";
        }
        context.fillRect(13,8,batteryLevel*0.75,44);

        //Text
        context.fillStyle = "black";
        context.font = "20px Calibri";
        context.textAlign="center";
        context.textAlign="center";
        context.fillText(batteryLevel + "%", 50, 35);
    }

    function drawScale(speed, height, canvasName, title){
      var c = document.getElementById(canvasName);
      var ctx = c.getContext("2d");
      c.width = 110;
      c.height = height;

      //draw the values
      ctx.font = '15pt Calibri';
      ctx.fillText(title,0,20);

      //constants
      var BOX_HEIGHT = 30;
      var BOX_WIDTH = 70;
      var OFFSET = 40;

      //draw the meter
      ctx.beginPath();
      ctx.rect(OFFSET,height/2-BOX_HEIGHT/2, BOX_WIDTH, BOX_HEIGHT);
      ctx.rect(0,30,OFFSET,height-30);
      ctx.lineWidth = 2;
      ctx.strokeStyle = 'black';
      ctx.stroke();

      //draw the values
      ctx.font = '20pt Calibri';
      var mid = height/2+BOX_HEIGHT/2-5.0;

      //draw the scaling
      ctx.fillText(speed, OFFSET+2, mid);
      ctx.textAlign="end";
      ctx.font = '10pt Calibri';
      var A = 20;
      var B= 0.1;
      for (i = mid; i<height; i+=B){
        if ((speed-(i-mid)).toFixed(1) % 1 == 0)
          ctx.fillText((speed-(i-mid)).toFixed(1),OFFSET-2,i*A-(A-1)*mid-2);
      }
      for (i = mid; i>154; i-=B){
        if ((speed-(i-mid)).toFixed(1) % 1 == 0)
          ctx.fillText((speed-(i-mid)).toFixed(1),OFFSET-2,i*A-(A-1)*mid-2);
      }
    }

    Network.on('data', updateCockpit);

    function updateCockpit() {
        var flightData = Data.state;
        roll = flightData.roll * (Math.PI / 180);
        pitch = flightData.pitch * (Math.PI / 180);
        yaw = flightData.yaw * (Math.PI / 180);
        lat = flightData.lat;
        lon = flightData.lon;
        altitude = flightData.altitude;
        heading = flightData.heading;
        speed = flightData.ground_speed;
        batteryLevel = Math.round(flightData.batteryLevel);
        editing_gain = flightData.editing_gain;
        gpsStatus = flightData.gpsStatus;

        drawArtificalHorizon(roll, pitch);
        drawPitch(pitch);
        drawRoll(roll);
        drawYaw(yaw);
        drawBattery(batteryLevel);
        status(editing_gain);
        gps(gpsStatus);
        drawScale(altitude,300,"altimeter","Altitude");
        drawScale(speed,300,"speed","Altitude");
    }

    function status(stat)
    {
      var statusCanva = document.getElementById("statusCanva").getContext("2d");
      statusCanva.font='30px Calibri';
      statusCanva.fillStyle = "black";

      if (stat === "0x00")
        statusCanva.fillText("MANUAL",13,50,75);
      else
        statusCanva.fillText("AUTOPILOT",15,50,75);
    }

    function gps(gpsStatus)
    {
      var gpsCanva = document.getElementById("gpsCanva").getContext("2d");
      gpsCanva.font='35px Calibri';
      gpsCanva.fillStyle = "black";

      if(gpsStatus === "0x1A")
      {
        gpsCanva.fillStyle = "green";
        gpsCanva.fillText("4",15,25,20);
      }
      else if (gpsStatus === "0x24")
      {
        gpsCanva.fillStyle ="green";
        gpsCanva.fillText("10",15,25,20);
      }
      else
      {
        gpsCanva.fillStyle ="red";
        gpsCanva.fillText("0",15,25,20);
      }
    }

    // Don't export anything
    return {};

})($, Data, Log, Network);
<commit_msg>im so sorry everyone<commit_after>// Data object contains values read from data-relay
// Accessed with Data.state.______
//
// updateCockpit() is called whenever data is recieved

var Cockpit = (function ($, Data, Log, Network) {

    $(document).ready(function () {
        //Initialize instruments
        drawArtificalHorizon(0, 0);
        drawPitch(0);
        drawRoll(0);
        drawYaw(0);
        drawBattery(0);
        drawScale(0,300,"altimeter","Altitude");

        //Buttons
        $('#goHome').on('click', function () {
            command = "return_home\r\n";
            Network.write(command);
            Log.write(command);
        });
    });

    function drawYaw(yaw) {
        //Initialize canvas
        var canvas = document.getElementById("yaw");
        canvas.height = 200;
        canvas.width = 200;
        canvas.title = yaw*180/Math.PI + "°";
        var context = canvas.getContext("2d");
        context.clearRect(0, 0, canvas.width, canvas.height);

        //Ground
        context.fillStyle = "#8bc34a";
        context.beginPath();
        context.arc(100, 100, 100, 0, Math.PI * 2);
        context.fill();

        //Border
        context.strokeStyle = "black";
        context.lineWidth = 2;
        context.beginPath();
        context.arc(100, 100, 99, 0, 2 * Math.PI);
        context.stroke();

        //Text
        var yawText = (parseFloat(yaw) * (180/Math.PI)).toFixed(2);
        yawText = yawText.toString() + "°";
        context.fillStyle = "black";
        context.font = "20px Calibri";
        context.textAlign="center";
        context.fillText(yawText, 100, 30);

        //Indicator
        image = document.createElement('img');
        image.src = "yaw.png";
        context.translate(36, 36);
        context.translate(64, 64);
        context.rotate(yaw);
        context.drawImage(image, -64, -64);
    }

    function drawRoll(roll) {
        //Initialize canvas
        var canvas = document.getElementById("roll");
        canvas.height = 200;
        canvas.width = 200;
        canvas.title = roll*180/Math.PI + "°";
        var context = canvas.getContext("2d");
        context.clearRect(0, 0, canvas.width, canvas.height);

        //Sky
        context.fillStyle = "#03a9f4";
        context.beginPath();
        context.arc(100, 100, 100, Math.PI, 2 * Math.PI);
        context.fill();

        //Ground
        context.fillStyle = "#8bc34a";
        context.beginPath();
        context.arc(100, 100, 100, 0, Math.PI);
        context.fill();

        //Border
        context.strokeStyle = "black";
        context.lineWidth = 2;
        context.beginPath();
        context.arc(100, 100, 99, 0, 2 * Math.PI);
        context.stroke();

        //Text
        var rollText = (parseFloat(roll) * (180/Math.PI)).toFixed(2);
        rollText = rollText.toString() + "°";
        context.fillStyle = "black";
        context.font = "20px Calibri";
        context.textAlign="center";
        context.fillText(rollText, 100, 30);

        //Indicator
        image = document.createElement('img');
        image.src = "roll.png";
        context.translate(36, 36);
        context.translate(64, 64);
        context.rotate(roll);
        context.drawImage(image, -64, -64);
    }

    function drawPitch(pitch) {
        //Initialize canvas
        var canvas = document.getElementById("pitch");
        canvas.height = 200;
        canvas.width = 200;
        canvas.title = pitch*180/Math.PI + "°";
        var context = canvas.getContext("2d");
        context.clearRect(0, 0, canvas.width, canvas.height);

        //Sky
        context.fillStyle = "#03a9f4";
        context.beginPath();
        context.arc(100, 100, 100, Math.PI, 2 * Math.PI);
        context.fill();

        //Ground
        context.fillStyle = "#8bc34a";
        context.beginPath();
        context.arc(100, 100, 100, 0, Math.PI);
        context.fill();

        //Border
        context.strokeStyle = "black";
        context.lineWidth = 2;
        context.beginPath();
        context.arc(100, 100, 99, 0, 2 * Math.PI);
        context.stroke();

        //Text
        var pitchText = (parseFloat(pitch) * (180/Math.PI)).toFixed(2);
        pitchText = pitchText.toString() + "°";
        context.fillStyle = "black";
        context.font = "20px Calibri";
        context.textAlign="center";
        context.fillText(pitchText, 100, 30);

        //Indicator
        image = document.createElement('img');
        image.src = "pitch.png";
        context.translate(36, 36);
        context.translate(64, 64);
        context.rotate(pitch);
        context.drawImage(image, -64, -64);
    }

    function drawArtificalHorizon(roll, pitch) {
        //Initialize canvas
        var canvas = document.getElementById("horizon");
        canvas.height = 200;
        canvas.width = 200;
        var context = canvas.getContext("2d");
        context.clearRect(0, 0, canvas.width, canvas.height);

        //Sky
        context.fillStyle = "#03a9f4";
        context.beginPath();
        context.arc(100, 100, 100, Math.PI + roll - pitch, 2 * Math.PI + roll + pitch);
        context.fill();

        //Ground
        context.fillStyle = "#795548";
        context.beginPath();
        context.arc(100, 100, 100, 0 + roll + pitch, Math.PI + roll - pitch);
        context.fill();

        //Border
        context.strokeStyle = "black";
        context.lineWidth = 2;
        context.beginPath();
        context.arc(100, 100, 99, 0, 2 * Math.PI);
        context.stroke();

        //Center
        context.fillStyle = "black";
        context.beginPath();
        context.lineWidth = 2;
        context.arc(100, 100, 2, 0, 2 * Math.PI);
        context.fill();
        context.beginPath();
        context.moveTo(120, 100);
        context.lineTo(110, 100);
        context.stroke();
        context.arc(100, 100, 10, 0, Math.PI);
        context.stroke();
        context.lineTo(80, 100);
        context.stroke();
    }

    function drawBattery(batteryLevel) {
        //Initialize canvas
        var canvas = document.getElementById("battery");
        canvas.height = 60;
        canvas.width = 100;
        var context = canvas.getContext("2d");
        context.clearRect(0, 0, canvas.width, canvas.height);

        //Outline
        context.fillStyle = "black";
        context.lineWidth = 5;
        context.rect(10,5,80,50);
        context.stroke();
        context.fillRect(0,20,10,20);
        context.stroke();

        //Fill
        if (batteryLevel <= 100 && batteryLevel >= 80) {
            context.fillStyle = "green";
        }
        else if (batteryLevel >= 20 && batteryLevel < 80) {
            context.fillStyle = "yellow";
        }
        else {
            context.fillStyle = "red";
        }
        context.fillRect(13,8,batteryLevel*0.75,44);

        //Text
        context.fillStyle = "black";
        context.font = "20px Calibri";
        context.textAlign="center";
        context.textAlign="center";
        context.fillText(batteryLevel + "%", 50, 35);
    }

    function drawScale(speed, height, canvasName, title){
      var c = document.getElementById(canvasName);
      var ctx = c.getContext("2d");
      c.width = 110;
      c.height = height;

      //draw the values
      ctx.font = '15pt Calibri';
      ctx.fillText(title,0,20);

      //constants
      var BOX_HEIGHT = 30;
      var BOX_WIDTH = 70;
      var OFFSET = 40;

      //draw the meter
      ctx.beginPath();
      ctx.rect(OFFSET,height/2-BOX_HEIGHT/2, BOX_WIDTH, BOX_HEIGHT);
      ctx.rect(0,30,OFFSET,height-30);
      ctx.lineWidth = 2;
      ctx.strokeStyle = 'black';
      ctx.stroke();

      //draw the values
      ctx.font = '20pt Calibri';
      var mid = height/2+BOX_HEIGHT/2-5.0;

      //draw the scaling
      ctx.fillText(speed.toFixed(2), OFFSET+2, mid);
      ctx.textAlign="end";
      ctx.font = '10pt Calibri';
      var A = 20;
      var B= 0.1;
      for (i = mid; i<height; i+=B){
        if ((speed-(i-mid)).toFixed(1) % 1 == 0)
          ctx.fillText((speed-(i-mid)).toFixed(1),OFFSET-2,i*A-(A-1)*mid-2);
      }
      for (i = mid; i>154; i-=B){
        if ((speed-(i-mid)).toFixed(1) % 1 == 0)
          ctx.fillText((speed-(i-mid)).toFixed(1),OFFSET-2,i*A-(A-1)*mid-2);
      }
    }

    Network.on('data', updateCockpit);

    function updateCockpit() {
        var flightData = Data.state;
        roll = flightData.roll * (Math.PI / 180);
        pitch = flightData.pitch * (Math.PI / 180);
        yaw = flightData.yaw * (Math.PI / 180);
        lat = flightData.lat;
        lon = flightData.lon;
        altitude = flightData.altitude;
        heading = flightData.heading;
        speed = flightData.ground_speed;
        batteryLevel = Math.round(flightData.batteryLevel);
        editing_gain = flightData.editing_gain;
        gpsStatus = flightData.gpsStatus;

        drawArtificalHorizon(roll, pitch);
        drawPitch(pitch);
        drawRoll(roll);
        drawYaw(yaw);
        drawBattery(batteryLevel);
        status(editing_gain);
        gps(gpsStatus);
        drawScale(altitude,300,"altimeter","Altitude");
        drawScale(speed,300,"speed","Speed");
    }

    function status(stat)
    {
      var statusCanva = document.getElementById("statusCanva").getContext("2d");
      statusCanva.font='30px Calibri';
      statusCanva.fillStyle = "black";

      if (stat === "0x00")
        statusCanva.fillText("MANUAL",13,50,75);
      else
        statusCanva.fillText("AUTOPILOT",15,50,75);
    }

    function gps(gpsStatus)
    {
      var gpsCanva = document.getElementById("gpsCanva").getContext("2d");
      gpsCanva.font='35px Calibri';
      gpsCanva.fillStyle = "black";

      if(gpsStatus === "0x1A")
      {
        gpsCanva.fillStyle = "green";
        gpsCanva.fillText("4",15,25,20);
      }
      else if (gpsStatus === "0x24")
      {
        gpsCanva.fillStyle ="green";
        gpsCanva.fillText("10",15,25,20);
      }
      else
      {
        gpsCanva.fillStyle ="red";
        gpsCanva.fillText("0",15,25,20);
      }
    }

    // Don't export anything
    return {};

})($, Data, Log, Network);
<|endoftext|>


<commit_before>$(document).ready(function()
{
    $("#invite-form").on('submit', function()
    {
        var inviteeEmail = $("#email").val();
        console.log(inviteeEmail)

        if (!inviteeEmail || !inviteeEmail.length) {
            alert('Please enter an email');
            return false;
        }

        $.ajax({
          type: "POST",
          url: "/",
          headers: {
            'X-CSRFToken': csrfToken,
            },
          data: { email: inviteeEmail},
          success: function(data) {
            handleResponse(data);
          }
        });
        return false;
    });
});

function handleResponse(data) {
    $("#response-text").text('Successful! Check your email (:');
    if (data.status === 'fail') {
      $("#response-text").text(getUserFriendlyError(data.error));
    }
    $("#response-div").removeClass('hidden');
}

function getUserFriendlyError(error){
  if(error === 'already_in_team'){
    return 'Already signed up! Click on "Sign in" below to get started';
  } else if(error === 'invalid_email'){
    return 'Thats an invalid email address. Please check again';
  } else if(error === 'already_invited'){
    return 'You have been invited already. Check your inbox!';
  } else if(error === 'invalid_auth'){
    return 'There seems to be some issues with the setup. Please contact the admin of this channel';
  } else{
    return error;
  }
}<commit_msg>Update submit.js<commit_after>$(document).ready(function()
{
    $("#invite-form").on('submit', function()
    {
        var inviteeEmail = $("#email").val();
        console.log(inviteeEmail)

        if (!inviteeEmail || !inviteeEmail.length) {
            alert('Please enter an email');
            return false;
        }

        $.ajax({
          type: "POST",
          url: "/",
          headers: {
            'X-CSRFToken': csrfToken,
            },
          data: { email: inviteeEmail},
          success: function(data) {
            handleResponse(data);
          }
        });
        return false;
    });
});

function handleResponse(data) {
    $("#response-text").text('Successful! Check your email (:');
    if (data.status === 'fail') {
      $("#response-text").text(getUserFriendlyError(data.error));
    }
    $("#response-div").removeClass('hidden');
}

function getUserFriendlyError(error){
  if(error === 'already_in_team'){
    return 'Already signed up! Click on "Sign in" to get started';
  } else if(error === 'invalid_email'){
    return 'Thats an invalid email address. Please check again';
  } else if(error === 'already_invited'){
    return 'You have been invited already. Check your inbox!';
  } else if(error === 'invalid_auth'){
    return 'There seems to be some issues with the setup. Please contact the admin of this channel';
  } else{
    return error;
  }
}
<|endoftext|>


<commit_before>'use babel'

import ClangRenameCommand from '../lib/clang-rename-command'

describe('ClangRenameCommand ', () => {
  it('invokes the command', () => {
    const clangRenameCommand = new ClangRenameCommand('./spec/bin/clang-rename')

    let result = null
    waitsForPromise(() => {
      return clangRenameCommand.rename([], 0, 'bar', 'foo.cpp').then(output => {
        result = output
        return output
      })
    })
    runs(() => {
      expect(result).toBe(`-offset 0 -new-name bar foo.cpp`)
    })
  })
})
<commit_msg>Fix the test case of clang-rename<commit_after>'use babel'

import ClangRenameCommand from '../lib/clang-rename-command'

describe('ClangRenameCommand ', () => {
  it('invokes the command', () => {
    const clangRenameCommand = new ClangRenameCommand('./spec/bin/clang-rename')

    let result = null
    waitsForPromise(() => {
      return clangRenameCommand.rename([], 0, 'bar', 'foo.cpp').then(output => {
        result = output
        return output
      })
    })
    runs(() => {
      expect(result).toBe('-offset 0 -new-name bar foo.cpp')
    })
  })
})
<|endoftext|>


<commit_before>// @flow
import Awral from 'awral'
/**
 * `parseJSON()` adds property "ok"
 *  that identicates that response is OK
 *
 *  This func to determinates is response from API was successful or failed
 *
 * @param  {Object} result - response from API
 * @return {Boolean} - indicates was request successful or not
 */
const check = (result: Object = {ok: false}): boolean => result.ok
const beforeCheck = a => a
const afterCheck = a => a.data
/**
  Create default Awral
  Awral is not recommended for production usage now
  But it can make your work with actions even simpler.
  NOTE:I strongly recommend you check Awral sources!
  Awral is 880B gzipped!
  {@link https://github.com/Metnew/awral}
*/
export const awral = Awral.of({check, beforeCheck, afterCheck})
<commit_msg>feat(actons/utils): disable "FINALLY", "BEFORE_PENDING" in awral<commit_after>// @flow
import Awral from './awral'
/**
 * `parseJSON()` adds property "ok"
 *  that identicates that response is OK
 *
 *  This func to determinates is response from API was successful or failed
 *
 * @param  {Object} result - response from API
 * @return {Boolean} - indicates was request successful or not
 */
const check = (result: Object = {ok: false}): boolean => result.ok
const beforeCheck = a => a
const afterCheck = a => a.data
// disable dispatch of GET_LINKS_FINALLY
const finallyAction = null
// disable dispatch of GET_LINKS_BEFORE_PENDING
const beforePending = null

/**
  Create default Awral
  Awral is not recommended for production usage now
  But it can make your work with actions even simpler.
  NOTE:I strongly recommend you check Awral sources!
  Awral is 880B gzipped!
  {@link https://github.com/Metnew/awral}
*/
export const awral = Awral.of({check, beforeCheck, afterCheck, finally: finallyAction, beforePending})
<|endoftext|>


<commit_before>(function($){
  function ajax(method, url, success){
    var r = new XMLHttpRequest();
    r.onreadystatechange = function(){
      if(r.readyState==4 && (r.status==200 || r.status==0))
        success(r.responseText);
    };
    r.open(method,url,true);
    r.setRequestHeader('X-Requested-With','XMLHttpRequest');
    r.send(null);
  }

  $.get = function(url, success){ ajax('GET', url, success); };
  $.post = function(url, success){ ajax('POST', url, success); };
  $.getJSON = function(url, success){
    $.get(url, function(json){ success(JSON.parse(json)) });
  };
})(Zepto);<commit_msg>jQuery-like load functionality with built-in response html parsing by selector - a peice I will be using as I implement Zepto and I assume others might need it aslo<commit_after>(function($){
  function ajax(method, url, success){
    var r = new XMLHttpRequest();
    r.onreadystatechange = function(){
      if(r.readyState==4 && (r.status==200 || r.status==0))
        success(r.responseText);
    };
    r.open(method,url,true);
    r.setRequestHeader('X-Requested-With','XMLHttpRequest');
    r.send(null);
  }

  $.get = function(url, success){ ajax('GET', url, success); };
  $.post = function(url, success){ ajax('POST', url, success); };
  $.getJSON = function(url, success){
    $.get(url, function(json){ success(JSON.parse(json)) });
  };

  $.fn.load = function(url, selector, success) {   // some functionality and methods inspired from jQuery source (MIT Licensed)
    var that = this;
    if (!this.length) return this;
    if (Object.prototype.toString.call(selector) === "[object Function]") { // if 2nd arg exists and is function
      success = selector;
      selector = null;
    };
    $.get(url, function(data) {
      var resp = data.replace(/<script(.|\s)*?\/script>/gi, '');
      that.html(
        selector ?
          $(document.createElement('div')).html(resp).find(selector).html()
          : resp );
      if (success) success();
    });
    return this;
  };

})(Zepto);<|endoftext|>


<commit_before>var stream = require('stream');
var util = require('util');

var sbp_parser = require('./sbp_parser')
var log = require('../../log').logger('sbp');
var CMD_SPACE_RE = /(\w\w)([ \t]+)([^\s\t,].*)/i
var CMD_RE = /^\s*(\w\w)(((\s*,\s*)([+-]?[0-9]+(\.[0-9]+)?)?)+)\s*$/i
var STUPID_STRING_RE = /(\&[A-Za-z]\w*)\s*=([^\n]*)/i

fastParse = function(statement) {
    var match = statement.match(CMD_RE);
    if(match) {
        if(match[1] === 'IF') {
            return null
        }
        var retval = {
            type : 'cmd',
            cmd : match[1],
            args : []
        }
        var args = match[2].split(',');
        var pargs = args.slice(1);
    for(var i=0; i<pargs.length; i++) {
        var arg = pargs[i]
            if(arg.trim() === '') {
                retval.args.push(undefined);
            } else {
                var n = Number(arg);
                retval.args.push(isNaN(n) ? arg : n);
            }
    }
        return retval;
    }

    var match = statement.match(CMD_SPACE_RE);
    if(match) {
        if(match[1] != 'IF') {
            statement = statement.replace(CMD_SPACE_RE, function(match, cmd, space, rest, offset, string) {
                return cmd + ',' + rest;
            });
        }
    }

    return null;
}

parseLine = function(line) {
    //line = line.replace(/\r/g,'');
    parts = line.split("'");
    statement = parts[0]
    comment = parts.slice(1,parts.length)
    console.log('Parsing line: ', line)
    try {
        // Use parse optimization
        var obj = fastParse(statement)
    if(!obj) {
        log.warn('Cant fastparse ' + statement)
        obj = sbp_parser.parse(statement);
    }
        //var obj = sbp_parser.parse(statement);
    } catch(e) {
        var match = statement.match(STUPID_STRING_RE)
        if(match) {
            log.debug("Got a stupid string: " + match[2]);
            obj = {type:"assign",var:match[1], expr:match[2]}
        }
    }

    if(Array.isArray(obj)) {
        obj = {"type":"comment", "comment":comment};
    } else {
        if(comment != '') {obj.comment = comment}
    }
    if(obj.type == 'cmd') {
        obj.cmd = obj.cmd.toUpperCase();
    }

    console.log(obj)
    return obj
}

parse = function(data) {
    output = []

    // Parse from a string or an array of strings

    if(Array.isArray(data)) {
        lines = data;
    } else {
        lines = data.split('\n');
    }

    log.tock('split lines');

    for(i=0; i<lines.length; i++) {
        try {
            output.push(parseLine(lines[i]))
        } catch(err) {
            if(err.name == 'SyntaxError') {
                log.error("Syntax Error on line " + (i+1))
                log.error("Expected " + JSON.stringify(err.expected) + " but found " + err.found)
                err.line = i+1;
                log.error(err.line)
            } else {
                log.error(err);
            }
            throw err
        }
    }
    log.tock('parse lines')
    throw new Error('FAIL');
    return output
}

function Parser(options) {
    var options = options || {};
    delete options['objectMode']
    options['readableObjectMode'] = true;
    options['writableObjectMode'] = false;

  // allow use without new
  if (!(this instanceof Parser)) {
    return new Parser(options);
  }
  this.lineBuffer = [];

  // init Transform
  stream.Transform.call(this, options);
}
util.inherits(Parser, stream.Transform);

Parser.prototype._transform = function(chunk, enc, cb) {
    var str = chunk.toString()
    try {
      for(var i=0; i<str.length; i++) {
            ch = str[i];
            this.lineBuffer.push(ch);
            if(ch === '\n') {
                var s = this.lineBuffer.join('').trim();
                this.push(parseLine(s));
                this.lineBuffer = [];
            }
        }
    } catch(e) {
        log.error(e)
    }
    console.log("JUMPING OUT")
    return cb();
}

/*
Parser.prototype._flush = function(done) {
  if (this.lineBuffer.length) { this.push(parseLine(this.lineBuffer.join('').trim())); }
  this.lineBuffer = [];
  done();
};
*/

parseStream = function(s, options) {
    var parser = new Parser(options);
    return s.pipe(parser)
}

var main = function(){
    var argv = require('minimist')(process.argv);
    var fs = require('fs');
    var filename = argv['_'][2]

    if(filename) {
        fs.readFile(filename, 'utf8', function(err, data) {
            if(err) {
                return console.log(err);
            }

            var start = new Date().getTime();
            var obj = parse(data);
            var end = new Date().getTime();
            var time = end - start;

            console.log(JSON.stringify(obj, null, ' '));
            console.log('Parse time: ' + time);

        });
    } else {
        console.log("Usage: node parser.js filename.sbp");
    }
}

var main2 = function() {
    var argv = require('minimist')(process.argv);
    var fs = require('fs');
    var filename = argv['_'][2]
    if(filename) {
        var fileStream = fs.createReadStream(filename);
        log.tick();
        parseStream(fileStream).on('finish', function() {
          log.tock('parse');
        });
        setTimeout(function() {}, 5000);
    }
}

if (require.main === module) {
    main2();
}

exports.parse = parse
exports.parseStream = parseStream
<commit_msg>Streaming works<commit_after>var stream = require('stream');
var util = require('util');

var sbp_parser = require('./sbp_parser')
var log = require('../../log').logger('sbp');
var CMD_SPACE_RE = /(\w\w)([ \t]+)([^\s\t,].*)/i
var CMD_RE = /^\s*(\w\w)(((\s*,\s*)([+-]?[0-9]+(\.[0-9]+)?)?)+)\s*$/i
var STUPID_STRING_RE = /(\&[A-Za-z]\w*)\s*=([^\n]*)/i

fastParse = function(statement) {
    var match = statement.match(CMD_RE);
    if(match) {
        if(match[1] === 'IF') {
            return null
        }
        var retval = {
            type : 'cmd',
            cmd : match[1],
            args : []
        }
        var args = match[2].split(',');
        var pargs = args.slice(1);
    for(var i=0; i<pargs.length; i++) {
        var arg = pargs[i]
            if(arg.trim() === '') {
                retval.args.push(undefined);
            } else {
                var n = Number(arg);
                retval.args.push(isNaN(n) ? arg : n);
            }
    }
        return retval;
    }

    var match = statement.match(CMD_SPACE_RE);
    if(match) {
        if(match[1] != 'IF') {
            statement = statement.replace(CMD_SPACE_RE, function(match, cmd, space, rest, offset, string) {
                return cmd + ',' + rest;
            });
        }
    }

    return null;
}

parseLine = function(line) {
    //line = line.replace(/\r/g,'');

    // Extract comment
    parts = line.split("'");
    statement = parts[0]
    comment = parts.slice(1,parts.length)

    try {
        // Use parse optimization
        var obj = fastParse(statement)
    if(!obj) {
        log.warn('Cant fastparse ' + statement)
        obj = sbp_parser.parse(statement);
    }
        //var obj = sbp_parser.parse(statement);
    } catch(e) {
        var match = statement.match(STUPID_STRING_RE)
        if(match) {
            obj = {type:"assign",var:match[1], expr:match[2]}
        }
    }

    if(Array.isArray(obj)) {
        obj = {"type":"comment", "comment":comment};
    } else {
        if(comment != '') {obj.comment = comment}
    }
    if(obj.type == 'cmd') {
        obj.cmd = obj.cmd.toUpperCase();
    }

//    console.log(obj)
    return obj
}

parse = function(data) {
    output = []

    // Parse from a string or an array of strings

    if(Array.isArray(data)) {
        lines = data;
    } else {
        lines = data.split('\n');
    }

    for(i=0; i<lines.length; i++) {
        try {
            output.push(parseLine(lines[i]))
        } catch(err) {
            if(err.name == 'SyntaxError') {
                log.error("Syntax Error on line " + (i+1))
                log.error("Expected " + JSON.stringify(err.expected) + " but found " + err.found)
                err.line = i+1;
                log.error(err.line)
            } else {
                log.error(err);
            }
            throw err
        }
    }
    return output
}

function Parser(options) {
    var options = options || {};
    options.objectMode = true;

  // allow use without new
  if (!(this instanceof Parser)) {
    return new Parser(options);
  }
  this.scrap = ""
  // init Transform
  stream.Transform.call(this, options);
}
util.inherits(Parser, stream.Transform);

Parser.prototype._transform = function(chunk, enc, cb) {
    var str = this.scrap + chunk.toString()
    this.pause();
    try {
      var start = 0;
      for(var i=0; i<str.length; i++) {
            if(str[i] === '\n') {
                var substr = str.substring(start, i)
                //console.log(substr)
                this.push(parseLine(substr));
                start = i+1;
            }
        }
        this.scrap = str.substring(start)
    } catch(e) {
        log.error(e)
    }
    this.resume();
    cb();

}

Parser.prototype._flush = function(done) {
  if (this.scrap) { this.push(parseLine(scrap)); }
  this.scrap = '';
  done();
};

parseStream = function(s, options) {
    var parser = new Parser(options);
    return s.pipe(parser)
}

var main = function(){
    var argv = require('minimist')(process.argv);
    var fs = require('fs');
    var filename = argv['_'][2]

    if(filename) {
        log.tick();
        fs.readFile(filename, 'utf8', function(err, data) {
            if(err) {
                return console.log(err);
            }

            var obj = parse(data);
            console.log("Lines: " + obj.length)
            log.tock('parse');
        });
    } else {
        console.log("Usage: node parser.js filename.sbp");
    }
}

var main2 = function() {
    var argv = require('minimist')(process.argv);
    var fs = require('fs');
    var filename = argv['_'][2]
    if(filename) {
        log.tick();
        var fileStream = fs.createReadStream(filename);
        var obj = []
        parseStream(fileStream)
            .on('data', function(data) {
            // console.log(data);
                obj.push(data)
            })
            .on('end', function() {
                console.log(obj[1],obj[2],obj[3])
                log.tock("parse");
            });
    }
}

if (require.main === module) {
    main();
//    main2();
}

exports.parse = parse
exports.parseStream = parseStream
<|endoftext|>


<commit_before>import { ActionTypes } from './createStore'
import isPlainObject from 'lodash/isPlainObject'
import warning from './utils/warning'

function getUndefinedStateErrorMessage(key, action) {
  const actionType = action && action.type
  const actionName = (actionType && `"${actionType.toString()}"`) || 'an action'

  return (
    `Given action ${actionName}, reducer "${key}" returned undefined. ` +
    `To ignore an action, you must explicitly return the previous state. ` +
    `If you want this reducer to hold no value, you can return null instead of undefined.`
  )
}

function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
  const reducerKeys = Object.keys(reducers)
  const argumentName = action && action.type === ActionTypes.INIT ?
    'preloadedState argument passed to createStore' :
    'previous state received by the reducer'

  if (reducerKeys.length === 0) {
    return (
      'Store does not have a valid reducer. Make sure the argument passed ' +
      'to combineReducers is an object whose values are reducers.'
    )
  }

  if (!isPlainObject(inputState)) {
    return (
      `The ${argumentName} has unexpected type of "` +
      ({}).toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] +
      `". Expected argument to be an object with the following ` +
      `keys: "${reducerKeys.join('", "')}"`
    )
  }

  const unexpectedKeys = Object.keys(inputState).filter(key =>
    !reducers.hasOwnProperty(key) &&
    !unexpectedKeyCache[key]
  )

  unexpectedKeys.forEach(key => {
    unexpectedKeyCache[key] = true
  })

  if (unexpectedKeys.length > 0) {
    return (
      `Unexpected ${unexpectedKeys.length > 1 ? 'keys' : 'key'} ` +
      `"${unexpectedKeys.join('", "')}" found in ${argumentName}. ` +
      `Expected to find one of the known reducer keys instead: ` +
      `"${reducerKeys.join('", "')}". Unexpected keys will be ignored.`
    )
  }
}

function assertReducerShape(reducers) {
  Object.keys(reducers).forEach(key => {
    const reducer = reducers[key]
    const initialState = reducer(undefined, { type: ActionTypes.INIT })

    if (typeof initialState === 'undefined') {
      throw new Error(
        `Reducer "${key}" returned undefined during initialization. ` +
        `If the state passed to the reducer is undefined, you must ` +
        `explicitly return the initial state. The initial state may ` +
        `not be undefined. If you don't want to set a value for this reducer, ` +
        `you can use null instead of undefined.`
      )
    }

    const type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.')
    if (typeof reducer(undefined, { type }) === 'undefined') {
      throw new Error(
        `Reducer "${key}" returned undefined when probed with a random type. ` +
        `Don't try to handle ${ActionTypes.INIT} or other actions in "redux/*" ` +
        `namespace. They are considered private. Instead, you must return the ` +
        `current state for any unknown actions, unless it is undefined, ` +
        `in which case you must return the initial state, regardless of the ` +
        `action type. The initial state may not be undefined, but can be null.`
      )
    }
  })
}

/**
 * Turns an object whose values are different reducer functions, into a single
 * reducer function. It will call every child reducer, and gather their results
 * into a single state object, whose keys correspond to the keys of the passed
 * reducer functions.
 *
 * @param {Object} reducers An object whose values correspond to different
 * reducer functions that need to be combined into one. One handy way to obtain
 * it is to use ES6 `import * as reducers` syntax. The reducers may never return
 * undefined for any action. Instead, they should return their initial state
 * if the state passed to them was undefined, and the current state for any
 * unrecognized action.
 *
 * @returns {Function} A reducer function that invokes every reducer inside the
 * passed object, and builds a state object with the same shape.
 */
export default function combineReducers(reducers) {
  const reducerKeys = Object.keys(reducers)
  const finalReducers = {}
  for (let i = 0; i < reducerKeys.length; i++) {
    const key = reducerKeys[i]

    if (process.env.NODE_ENV !== 'production') {
      if (typeof reducers[key] === 'undefined') {
        warning(`No reducer provided for key "${key}"`)
      }
    }

    if (typeof reducers[key] === 'function') {
      finalReducers[key] = reducers[key]
    }
  }
  const finalReducerKeys = Object.keys(finalReducers)

  let unexpectedKeyCache
  if (process.env.NODE_ENV !== 'production') {
    unexpectedKeyCache = {}
  }

  let shapeAssertionError
  try {
    assertReducerShape(finalReducers)
  } catch (e) {
    shapeAssertionError = e
  }

  return function combination(state = {}, action) {
    if (shapeAssertionError) {
      throw shapeAssertionError
    }

    if (process.env.NODE_ENV !== 'production') {
      const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache)
      if (warningMessage) {
        warning(warningMessage)
      }
    }

    let hasChanged = false
    const nextState = {}
    for (let i = 0; i < finalReducerKeys.length; i++) {
      const key = finalReducerKeys[i]
      const reducer = finalReducers[key]
      const previousStateForKey = state[key]
      const nextStateForKey = reducer(previousStateForKey, action)
      if (typeof nextStateForKey === 'undefined') {
        const errorMessage = getUndefinedStateErrorMessage(key, action)
        throw new Error(errorMessage)
      }
      nextState[key] = nextStateForKey
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey
    }
    return hasChanged ? nextState : state
  }
}
<commit_msg>Fixed quote types inconsistency in a warning message (#2297)<commit_after>import { ActionTypes } from './createStore'
import isPlainObject from 'lodash/isPlainObject'
import warning from './utils/warning'

function getUndefinedStateErrorMessage(key, action) {
  const actionType = action && action.type
  const actionDescription = (actionType && `action "${String(actionType)}"`) || 'an action'

  return (
    `Given ${actionDescription}, reducer "${key}" returned undefined. ` +
    `To ignore an action, you must explicitly return the previous state. ` +
    `If you want this reducer to hold no value, you can return null instead of undefined.`
  )
}

function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
  const reducerKeys = Object.keys(reducers)
  const argumentName = action && action.type === ActionTypes.INIT ?
    'preloadedState argument passed to createStore' :
    'previous state received by the reducer'

  if (reducerKeys.length === 0) {
    return (
      'Store does not have a valid reducer. Make sure the argument passed ' +
      'to combineReducers is an object whose values are reducers.'
    )
  }

  if (!isPlainObject(inputState)) {
    return (
      `The ${argumentName} has unexpected type of "` +
      ({}).toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] +
      `". Expected argument to be an object with the following ` +
      `keys: "${reducerKeys.join('", "')}"`
    )
  }

  const unexpectedKeys = Object.keys(inputState).filter(key =>
    !reducers.hasOwnProperty(key) &&
    !unexpectedKeyCache[key]
  )

  unexpectedKeys.forEach(key => {
    unexpectedKeyCache[key] = true
  })

  if (unexpectedKeys.length > 0) {
    return (
      `Unexpected ${unexpectedKeys.length > 1 ? 'keys' : 'key'} ` +
      `"${unexpectedKeys.join('", "')}" found in ${argumentName}. ` +
      `Expected to find one of the known reducer keys instead: ` +
      `"${reducerKeys.join('", "')}". Unexpected keys will be ignored.`
    )
  }
}

function assertReducerShape(reducers) {
  Object.keys(reducers).forEach(key => {
    const reducer = reducers[key]
    const initialState = reducer(undefined, { type: ActionTypes.INIT })

    if (typeof initialState === 'undefined') {
      throw new Error(
        `Reducer "${key}" returned undefined during initialization. ` +
        `If the state passed to the reducer is undefined, you must ` +
        `explicitly return the initial state. The initial state may ` +
        `not be undefined. If you don't want to set a value for this reducer, ` +
        `you can use null instead of undefined.`
      )
    }

    const type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.')
    if (typeof reducer(undefined, { type }) === 'undefined') {
      throw new Error(
        `Reducer "${key}" returned undefined when probed with a random type. ` +
        `Don't try to handle ${ActionTypes.INIT} or other actions in "redux/*" ` +
        `namespace. They are considered private. Instead, you must return the ` +
        `current state for any unknown actions, unless it is undefined, ` +
        `in which case you must return the initial state, regardless of the ` +
        `action type. The initial state may not be undefined, but can be null.`
      )
    }
  })
}

/**
 * Turns an object whose values are different reducer functions, into a single
 * reducer function. It will call every child reducer, and gather their results
 * into a single state object, whose keys correspond to the keys of the passed
 * reducer functions.
 *
 * @param {Object} reducers An object whose values correspond to different
 * reducer functions that need to be combined into one. One handy way to obtain
 * it is to use ES6 `import * as reducers` syntax. The reducers may never return
 * undefined for any action. Instead, they should return their initial state
 * if the state passed to them was undefined, and the current state for any
 * unrecognized action.
 *
 * @returns {Function} A reducer function that invokes every reducer inside the
 * passed object, and builds a state object with the same shape.
 */
export default function combineReducers(reducers) {
  const reducerKeys = Object.keys(reducers)
  const finalReducers = {}
  for (let i = 0; i < reducerKeys.length; i++) {
    const key = reducerKeys[i]

    if (process.env.NODE_ENV !== 'production') {
      if (typeof reducers[key] === 'undefined') {
        warning(`No reducer provided for key "${key}"`)
      }
    }

    if (typeof reducers[key] === 'function') {
      finalReducers[key] = reducers[key]
    }
  }
  const finalReducerKeys = Object.keys(finalReducers)

  let unexpectedKeyCache
  if (process.env.NODE_ENV !== 'production') {
    unexpectedKeyCache = {}
  }

  let shapeAssertionError
  try {
    assertReducerShape(finalReducers)
  } catch (e) {
    shapeAssertionError = e
  }

  return function combination(state = {}, action) {
    if (shapeAssertionError) {
      throw shapeAssertionError
    }

    if (process.env.NODE_ENV !== 'production') {
      const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache)
      if (warningMessage) {
        warning(warningMessage)
      }
    }

    let hasChanged = false
    const nextState = {}
    for (let i = 0; i < finalReducerKeys.length; i++) {
      const key = finalReducerKeys[i]
      const reducer = finalReducers[key]
      const previousStateForKey = state[key]
      const nextStateForKey = reducer(previousStateForKey, action)
      if (typeof nextStateForKey === 'undefined') {
        const errorMessage = getUndefinedStateErrorMessage(key, action)
        throw new Error(errorMessage)
      }
      nextState[key] = nextStateForKey
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey
    }
    return hasChanged ? nextState : state
  }
}
<|endoftext|>


<commit_before>var expect = require('expect');
var _ = require('lodash');
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var subject = require('../../../backend/lib/openfisca/test');
var tmp = require('tmp');

var details = {
    name: 'Ideal name',
    description: 'Thorough description',
    output: {
        rsa: 545.48,
    },
    absolute_error_margin: 0.1,
};

var currentPeriod = '2018-01';
var situation = {
    dateDeValeur: new Date(currentPeriod),
    famille: {},
    foyer_fiscal: {},
    individus: [{
        id: 'id',
        date_naissance: new Date('1989-01-01'),
        role: 'demandeur',
        specificSituations: []
    }],
    menage: {
        personne_de_reference: ['id'],
        statut_occupation_logement: 'sans_domicile'
    },
};

describe('openfisca generateTest', function() {
    var result = subject.generateTest(details, situation);

    it('does not add rsa_non_calculable', function() {
        expect(typeof result.input.familles._.rsa_non_calculable[currentPeriod]).toBe('undefined');
    });
});

function run_cmd(cmd, args) {
    return new Promise(function(resolve, reject) {
        var spawn = require('child_process').spawn;
        var child = spawn(cmd, args);
        var respErr = "";
        var respOut = "";

        child.stdout.on('data', function (buffer) { respOut += buffer.toString(); });
        child.stderr.on('data', function (buffer) { respErr += buffer.toString(); });
        child.on('exit', function(code) {
            var result = {
                stdout: respOut,
                stderr: respErr
            };
            if (code) {
                result.error = 'Exit code was ' + code;
                reject(result);
            } else {
                resolve(result);
            }
        });
        child.on('error', function(err) { reject({ error: err }); });
    });
}

function runOpenFiscaTest(yaml, extension) {
    var tmpobj = tmp.fileSync({postfix: '.yaml'});
    return fs.writeFileAsync(tmpobj.fd, yaml, 'utf8')
        .then(function() {
            var args = extension ? [tmpobj.name, '--extensions', extension] : [tmpobj.name];

            return run_cmd('openfisca-run-test', args);
        });
}

describe('openfisca generateYAMLTest', function() {
    var result = subject.generateYAMLTest(details, situation);

    it('generates a non empty string', function() {
        expect(result).toBeTruthy();
    });

    it('contains provided output', function() {
        expect(result).toContain('rsa: 545.48');
    });

    function validateYAMLRun(payload, extension) {
        return runOpenFiscaTest(payload, extension)
            .catch(function(failure) {
                console.log(payload);
                expect(failure).toBeFalsy();

                return failure;
            })
            .then(function(result) {
                expect(result.stdout).toMatch(/passed in/);

                expect(result.stdout).not.toMatch(/failed in/);
                expect(result.stdout).not.toMatch(/= ERRORS =/);
                expect(result.stdout).not.toMatch(/= FAILURES =/);
            });
    }

    if (process.env.VIRTUAL_ENV) {
        describe('generates processable YAML files', function() {
            it('passes OpenFisca test without extension', function() {
                var info = Object.assign({}, details);
                var yamlContent = subject.generateYAMLTest(info, situation);

                return validateYAMLRun(yamlContent);
            });

            Object.keys(subject.EXTENSION_VARIABLES).forEach(function(extensionName) {
                it('passes OpenFisca test with ' + extensionName  + ' extension', function() {
                    var info = Object.assign({ extension: extensionName }, details);
                    var yamlContent = subject.generateYAMLTest(info, situation);

                    var variableListRegex = _.values(subject.EXTENSION_VARIABLES[extensionName]).map(function(variableList) { return variableList.join('|'); }).join('|');
                    expect(yamlContent).toMatch(new RegExp(variableListRegex));

                    return validateYAMLRun(yamlContent, extensionName.replace(/-/g, '_'));
                });
            });
        });
    }
});
<commit_msg>Améliore les critères de succès de tests OpenFisca<commit_after>var expect = require('expect');
var _ = require('lodash');
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var subject = require('../../../backend/lib/openfisca/test');
var tmp = require('tmp');

var details = {
    name: 'Ideal name',
    description: 'Thorough description',
    output: {
        rsa: 545.48,
    },
    absolute_error_margin: 0.1,
};

var currentPeriod = '2018-01';
var situation = {
    dateDeValeur: new Date(currentPeriod),
    famille: {},
    foyer_fiscal: {},
    individus: [{
        id: 'id',
        date_naissance: new Date('1989-01-01'),
        role: 'demandeur',
        specificSituations: []
    }],
    menage: {
        personne_de_reference: ['id'],
        statut_occupation_logement: 'sans_domicile'
    },
};

describe('openfisca generateTest', function() {
    var result = subject.generateTest(details, situation);

    it('does not add rsa_non_calculable', function() {
        expect(typeof result.input.familles._.rsa_non_calculable[currentPeriod]).toBe('undefined');
    });
});

function run_cmd(cmd, args) {
    return new Promise(function(resolve, reject) {
        var spawn = require('child_process').spawn;
        var child = spawn(cmd, args);
        var respErr = "";
        var respOut = "";

        child.stdout.on('data', function (buffer) { respOut += buffer.toString(); });
        child.stderr.on('data', function (buffer) { respErr += buffer.toString(); });
        child.on('exit', function(code) {
            var result = {
                stdout: respOut,
                stderr: respErr
            };
            if (code) {
                result.error = 'Exit code was ' + code;
                reject(result);
            } else {
                resolve(result);
            }
        });
        child.on('error', function(err) { reject({ error: err }); });
    });
}

function runOpenFiscaTest(yaml, extension) {
    var tmpobj = tmp.fileSync({postfix: '.yaml'});
    return fs.writeFileAsync(tmpobj.fd, yaml, 'utf8')
        .then(function() {
            var args = extension ? [tmpobj.name, '--extensions', extension] : [tmpobj.name];

            return run_cmd('openfisca-run-test', args);
        });
}

describe('openfisca generateYAMLTest', function() {
    var result = subject.generateYAMLTest(details, situation);

    it('generates a non empty string', function() {
        expect(result).toBeTruthy();
    });

    it('contains provided output', function() {
        expect(result).toContain('rsa: 545.48');
    });

    function validateYAMLRun(payload, extension) {
        return runOpenFiscaTest(payload, extension)
            .catch(function(failure) {
                console.log(payload);
                expect(failure).toBeFalsy();

                return failure;
            })
            .then(function(result) {
                expect(result.stdout).toMatch(/ passed/);

                expect(result.stdout).not.toMatch(/ failed /);
                expect(result.stdout).not.toMatch(/= ERRORS =/);
                expect(result.stdout).not.toMatch(/= FAILURES =/);
            });
    }

    if (process.env.VIRTUAL_ENV) {
        describe('generates processable YAML files', function() {
            it('passes OpenFisca test without extension', function() {
                var info = Object.assign({}, details);
                var yamlContent = subject.generateYAMLTest(info, situation);

                return validateYAMLRun(yamlContent);
            });

            Object.keys(subject.EXTENSION_VARIABLES).forEach(function(extensionName) {
                it('passes OpenFisca test with ' + extensionName  + ' extension', function() {
                    var info = Object.assign({ extension: extensionName }, details);
                    var yamlContent = subject.generateYAMLTest(info, situation);

                    var variableListRegex = _.values(subject.EXTENSION_VARIABLES[extensionName]).map(function(variableList) { return variableList.join('|'); }).join('|');
                    expect(yamlContent).toMatch(new RegExp(variableListRegex));

                    return validateYAMLRun(yamlContent, extensionName.replace(/-/g, '_'));
                });
            });
        });
    }
});
<|endoftext|>


<commit_before>/**
 * Copyright 2016 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var BBPromise = require('bluebird');
var argv = require('minimist')(process.argv.slice(2));
var child_process = require('child_process');
var exec = BBPromise.promisify(child_process.exec);
var fs = BBPromise.promisifyAll(require('fs'));
var gulp = require('gulp-help')(require('gulp'));
var util = require('gulp-util');

/**
 * @param {string} filename
 * @param {string=} opt_branch
 * @return {!Promise}
 */
function checkoutBranchConfigs(filename, opt_branch) {
  var branch = opt_branch || 'origin/master';
  // One bad path here will fail the whole operation.
  return exec(`git checkout ${branch} ${filename}`)
      .catch(function(e) {
        // This means the files don't exist in master. Assume that it exists
        // in the current branch.
        if (/did not match any file/.test(e.message)) {
          return;
        }
        throw e;
      });
}

/**
 * @param {string} configString
 * @param {string} fileString
 * @return {string}
 */
function prependConfig(configString, fileString) {
  return `window.AMP_CONFIG||(window.AMP_CONFIG=${configString});` +
    `/*AMP_CONFIG*/${fileString}`;
}

/**
 * @param {string} filename
 * @param {string} fileString
 * @param {boolean=} opt_dryrun
 * @return {!Promise}
 */
function writeTarget(filename, fileString, opt_dryrun) {
  if (opt_dryrun) {
    util.log(util.colors.blue(`overwriting: ${filename}`));
    util.log(fileString);
    return Promise.resolve();
  }
  return fs.writeFileAsync(filename, fileString);
}

/**
 * @param {string|boolean}
 * @param {string}
 * @return {string}
 */
function valueOrDefault(value, defaultValue) {
  if (typeof value == 'string') {
    return value;
  }
  return defaultValue;
}

function main() {
  if (!argv.target) {
    util.log(util.colors.red('Missing --target.'));
    return;
  }

  if (!(argv.prod || argv.canary)) {
    util.log(util.colors.red('One of --prod or --canary should be provided.'));
    return;
  }

  var globs = [].concat(argv.files).filter(x => typeof x == 'string');
  var branch = argv.branch;
  var target = argv.target;
  var filename = '';

  // Prod by default.
  if (argv.canary) {
    filename = valueOrDefault(argv.canary,
        'build-system/global-configs/canary-config.json');
  } else {
    filename = valueOrDefault(argv.prod,
        'build-system/global-configs/prod-config.json');
  }
  return checkoutBranchConfigs(filename, branch)
      .then(() => {
       return Promise.all([
         fs.readFileAsync(filename),
         fs.readFileAsync(target),
       ]);
      })
      .then(files => {
        var configFile;
        try {
          configFile = JSON.stringify(JSON.parse(files[0].toString()));
        } catch (e) {
          util.log(util.colors.red(`Error parsing config file: ${filename}`));
          throw e;
        }
        var targetFile = files[1].toString();
        return prependConfig(configFile, targetFile);
      })
      .then(fileString => {
        return writeTarget(target, fileString, argv.dryrun);
      });
}

gulp.task('prepend-global', 'test', main);

exports.checkoutBranchConfigs = checkoutBranchConfigs;
exports.prependConfig = prependConfig;
exports.writeTarget = writeTarget;
exports.valueOrDefault = valueOrDefault;
<commit_msg>add help documentation for prepend-global (#3947)<commit_after>/**
 * Copyright 2016 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var BBPromise = require('bluebird');
var argv = require('minimist')(process.argv.slice(2));
var child_process = require('child_process');
var exec = BBPromise.promisify(child_process.exec);
var fs = BBPromise.promisifyAll(require('fs'));
var gulp = require('gulp-help')(require('gulp'));
var util = require('gulp-util');

/**
 * @param {string} filename
 * @param {string=} opt_branch
 * @return {!Promise}
 */
function checkoutBranchConfigs(filename, opt_branch) {
  var branch = opt_branch || 'origin/master';
  // One bad path here will fail the whole operation.
  return exec(`git checkout ${branch} ${filename}`)
      .catch(function(e) {
        // This means the files don't exist in master. Assume that it exists
        // in the current branch.
        if (/did not match any file/.test(e.message)) {
          return;
        }
        throw e;
      });
}

/**
 * @param {string} configString
 * @param {string} fileString
 * @return {string}
 */
function prependConfig(configString, fileString) {
  return `window.AMP_CONFIG||(window.AMP_CONFIG=${configString});` +
    `/*AMP_CONFIG*/${fileString}`;
}

/**
 * @param {string} filename
 * @param {string} fileString
 * @param {boolean=} opt_dryrun
 * @return {!Promise}
 */
function writeTarget(filename, fileString, opt_dryrun) {
  if (opt_dryrun) {
    util.log(util.colors.blue(`overwriting: ${filename}`));
    util.log(fileString);
    return Promise.resolve();
  }
  return fs.writeFileAsync(filename, fileString);
}

/**
 * @param {string|boolean}
 * @param {string}
 * @return {string}
 */
function valueOrDefault(value, defaultValue) {
  if (typeof value == 'string') {
    return value;
  }
  return defaultValue;
}

function main() {
  if (!argv.target) {
    util.log(util.colors.red('Missing --target.'));
    return;
  }

  if (!(argv.prod || argv.canary)) {
    util.log(util.colors.red('One of --prod or --canary should be provided.'));
    return;
  }

  var globs = [].concat(argv.files).filter(x => typeof x == 'string');
  var branch = argv.branch;
  var target = argv.target;
  var filename = '';

  // Prod by default.
  if (argv.canary) {
    filename = valueOrDefault(argv.canary,
        'build-system/global-configs/canary-config.json');
  } else {
    filename = valueOrDefault(argv.prod,
        'build-system/global-configs/prod-config.json');
  }
  return checkoutBranchConfigs(filename, branch)
      .then(() => {
       return Promise.all([
         fs.readFileAsync(filename),
         fs.readFileAsync(target),
       ]);
      })
      .then(files => {
        var configFile;
        try {
          configFile = JSON.stringify(JSON.parse(files[0].toString()));
        } catch (e) {
          util.log(util.colors.red(`Error parsing config file: ${filename}`));
          throw e;
        }
        var targetFile = files[1].toString();
        return prependConfig(configFile, targetFile);
      })
      .then(fileString => {
        return writeTarget(target, fileString, argv.dryrun);
      });
}

gulp.task('prepend-global', 'Prepends a json config to a target file', main, {
  options: {
    'target': '  The file to prepend the json config to.',
    'canary': '  Prepend the default canary config. ' +
        'Takes in an optional value for a custom canary config source.',
    'prod': '  Prepend the default prod config. ' +
        'Takes in an optional value for a custom prod config source.',
    'branch': '  Switch to a git branch to get config source from. ' +
        'Uses master by default.',
  }
});

exports.checkoutBranchConfigs = checkoutBranchConfigs;
exports.prependConfig = prependConfig;
exports.writeTarget = writeTarget;
exports.valueOrDefault = valueOrDefault;
<|endoftext|>


<commit_before>import React from 'react';

import SuggestionsTab from 'Main/SuggestionsTab';
import Tab from 'Main/Tab';
import Talents from 'Main/Talents';

import CoreCombatLogParser from 'Parser/Core/CombatLogParser';
import HealingDone from 'Parser/Core/Modules/HealingDone';
import DamageDone from 'Parser/Core/Modules/DamageDone';
import DamageTaken from 'Parser/Core/Modules/DamageTaken';

import PainChart from './Modules/PainChart/Pain';

import AlwaysBeCasting from './Modules/Features/AlwaysBeCasting';
import CastEfficiency from './Modules/Features/CastEfficiency';
import CooldownTracker from './Modules/Features/CooldownTracker';

import SoulFragments from './Modules/Statistics/SoulFragments/SoulFragments';
import SpiritBomb from './Modules/Statistics/SpiritBomb/SpiritBomb';

import ImmolationAura from './Modules/Statistics/Spells/ImmolationAura';
import DemonSpikes from './Modules/Statistics/Spells/DemonSpikes';
import EmpowerWards from './Modules/Statistics/Spells/EmpowerWards';
import SigilOfFlame from './Modules/Statistics/Spells/SigilOfFlame';

import Tier202PBonus from './Modules/Tier/Tier20/Tier20-2P.js';
import Tier204PBonus from './Modules/Tier/Tier20/Tier20-4P.js';

class CombatLogParser extends CoreCombatLogParser {
  static specModules = {
    // Core Statistics
    damageDone: [DamageDone, { showStatistic: true }],
    damageTaken: [DamageTaken, { showStatistic: true }],
    healingDone: [HealingDone, { showStatistic: true }],

    // Features
    alwaysBeCasting: AlwaysBeCasting,
    castEfficiency: CastEfficiency,
		cooldownTracker: CooldownTracker,

		// Spirit Bomb
    spiritBomb: SpiritBomb,

    // Soul Fragments
    soulFragments: SoulFragments,

    // Spell Statistics
    immolationAura: ImmolationAura,
    demonSpikes: DemonSpikes,
    empowerWards: EmpowerWards,
    sigilOfFlame: SigilOfFlame,

    // Tier 20
    tier202PBonus: Tier202PBonus,
    tier204PBonus: Tier204PBonus,
  };

  generateResults() {
    const results = super.generateResults();

    results.tabs = [
      {
        title: 'Suggestions',
        url: 'suggestions',
        render: () => (
          <SuggestionsTab issues={results.issues} />
        ),
      },
      {
        title: 'Talents',
        url: 'talents',
        render: () => (
          <Tab title="Talents">
            <Talents combatant={this.modules.combatants.selected} />
          </Tab>
        ),
      },
      {
        title: 'Pain Chart',
        url: 'pain',
        render: () => (
          <Tab title="Pain" style={{ padding: '15px 22px' }}>
            <PainChart
              reportCode={this.report.code}
              actorId={this.playerId}
              start={this.fight.start_time}
              end={this.fight.end_time}
            />
          </Tab>
        ),
      },
      ...results.tabs,
    ];

    return results;
  }
}

export default CombatLogParser;
<commit_msg>Update CombatLogParser.js<commit_after>import React from 'react';

import SuggestionsTab from 'Main/SuggestionsTab';
import Tab from 'Main/Tab';
import Talents from 'Main/Talents';

import CoreCombatLogParser from 'Parser/Core/CombatLogParser';
import HealingDone from 'Parser/Core/Modules/HealingDone';
import DamageDone from 'Parser/Core/Modules/DamageDone';
import DamageTaken from 'Parser/Core/Modules/DamageTaken';

import PainChart from './Modules/PainChart/Pain';

import AlwaysBeCasting from './Modules/Features/AlwaysBeCasting';
import CastEfficiency from './Modules/Features/CastEfficiency';
import CooldownTracker from './Modules/Features/CooldownTracker';

import SoulFragments from './Modules/Statistics/SoulFragments/SoulFragments';
import SpiritBomb from './Modules/Statistics/SpiritBomb/SpiritBomb';

import ImmolationAura from './Modules/Statistics/Spells/ImmolationAura';
import DemonSpikes from './Modules/Statistics/Spells/DemonSpikes';
import EmpowerWards from './Modules/Statistics/Spells/EmpowerWards';
import SigilOfFlame from './Modules/Statistics/Spells/SigilOfFlame';

import Tier202PBonus from './Modules/Tier/Tier20/Tier20-2P.js';
import Tier204PBonus from './Modules/Tier/Tier20/Tier20-4P.js';

class CombatLogParser extends CoreCombatLogParser {
  static specModules = {
    // Core Statistics
    damageDone: [DamageDone, { showStatistic: true }],
    damageTaken: [DamageTaken, { showStatistic: true }],
    healingDone: [HealingDone, { showStatistic: true }],

    // Features
    alwaysBeCasting: AlwaysBeCasting,
    castEfficiency: CastEfficiency,
		cooldownTracker: CooldownTracker,

		// Spirit Bomb Tracker Module (Frailty uptime tracker)
    spiritBomb: SpiritBomb,

    // Soul Fragments Tracker module (includes Generated and Wasted)
    soulFragments: SoulFragments,

    // Spell Statistics
    immolationAura: ImmolationAura,
    demonSpikes: DemonSpikes,
    empowerWards: EmpowerWards,
    sigilOfFlame: SigilOfFlame,

    // Tier 20
    tier202PBonus: Tier202PBonus,
    tier204PBonus: Tier204PBonus,
  };

  generateResults() {
    const results = super.generateResults();

    results.tabs = [
      {
        title: 'Suggestions',
        url: 'suggestions',
        render: () => (
          <SuggestionsTab issues={results.issues} />
        ),
      },
      {
        title: 'Talents',
        url: 'talents',
        render: () => (
          <Tab title="Talents">
            <Talents combatant={this.modules.combatants.selected} />
          </Tab>
        ),
      },
      {
        title: 'Pain Chart',
        url: 'pain',
        render: () => (
          <Tab title="Pain" style={{ padding: '15px 22px' }}>
            <PainChart
              reportCode={this.report.code}
              actorId={this.playerId}
              start={this.fight.start_time}
              end={this.fight.end_time}
            />
          </Tab>
        ),
      },
      ...results.tabs,
    ];

    return results;
  }
}

export default CombatLogParser;
<|endoftext|>


<commit_before>phaserLifeCycleFunctions.preload = function(){
  game.load.image('sky', 'assets/sky.png')
  game.load.image('ground', 'assets/platform.png')
  game.load.image('star', 'assets/star.png')
  game.load.image('dude', 'assets/ship.png')
  game.load.spritesheet('invader', 'assets/baddie.png', 32, 32)
  game.load.spritesheet('rain', 'assets/rain.png', 17, 17)
  game.load.image('bullet', 'assets/bullets.png')
}

<commit_msg>alter js assets to be relative so they can be loaded in on the deck show and included deck show pages<commit_after>phaserLifeCycleFunctions.preload = function(){
  game.load.image('sky', '../assets/sky.png')
  game.load.image('ground', '../assets/platform.png')
  game.load.image('star', '../assets/star.png')
  game.load.image('dude', '../assets/ship.png')
  game.load.spritesheet('invader', '../assets/baddie.png', 32, 32)
  game.load.spritesheet('rain', '../assets/rain.png', 17, 17)
  game.load.image('bullet', '../assets/bullets.png')
}

<|endoftext|>


<commit_before><commit_msg>Displays colours for cultures<commit_after><|endoftext|>