<commit_before>define([
    'signals',
    'glmat',
    'slam/Map',
    'slam/Math',
    'slam/Robot',
    'slam/MockServer'
], function SlamClient(signals,
                       glmat,
                       Map,
                       Math,
                       Robot,
                       server) {
    var SlamClient = function SlamClient(width, height) {
        var self = {};

        var PX_PER_FT = 30; // TODO: Un hard code
        var IN_PER_FT = 12;
        var PX_PER_IN = PX_PER_FT / IN_PER_FT; // TODO: Sane scaling system
        var MAX_DRIVE = 6 * PX_PER_IN;

        var waypoints = [
            [800, 700],
            [800, 200],
            [550, 200],
            [550, 300],
            [250, 300],
            [250, 500],
            [250, 840],
            [800, 830]
        ];
        var waypointIdx = 1;

        var doing = false;
        var curBot;
        var deadBots = [];
        self.allBots = true;
        self.autoStep = false;
        var map = new Map(width, height);

        // --------------------------------------------- constants ----------------------------------------------------
        var ROBOT_COUNT = 40;

        // --------------------------------------------- events -------------------------------------------------------
        self.invalidate = new signals.Signal();

        // ------------------------------------------- private vars ---------------------------------------------------
        var robots = [];
        var history = [];

        // ------------------------------------------ constructor -----------------------------------------------------
        var ctor = function () {
            server.setPos(waypoints[0]);
            for (var i = 0; i < ROBOT_COUNT; i++) {
                var bot = new Robot('' + i, width, height, map);
                bot.setPos(waypoints[0]);
                robots.push(bot);
            }
        };

        // ------------------------------------------ public methods --------------------------------------------------
        self.showBot = function (bot) {
            curBot = bot;
        };

        self.showAll = function (val) {
            self.allBots = val;
        };

        self.autoDrive = function (val) {
            self.autoStep = val;
        };

        self.start = function () {
            server.scan(onScanComplete);
        };

        self.draw = function (ctx) {
            robots.forEach(function (robot) {
                if (curBot === robot) {
                    robot.drawMap(ctx);
                    robot.drawSamples(ctx);
                }
                if (self.allBots === true || curBot === robot) {
                    robot.drawRobot(ctx);
                }
            });
            deadBots.forEach(function (robot) {
                ctx.strokeStyle = '#FF0000';
                var pos = robot.pos;
                var dir = robot.ang;
                ctx.translate(pos[0], pos[1]);
                ctx.rotate(dir);

                ctx.strokeRect(-server.SIZE[0] / 2 * PX_PER_IN, -server.SIZE[1] / 2 * PX_PER_IN, server.SIZE[0] * PX_PER_IN, server.SIZE[1] * PX_PER_IN);
                ctx.beginPath();
                ctx.moveTo(-server.SIZE[0] / 2 * PX_PER_IN, -server.SIZE[1] / 2 * PX_PER_IN);
                ctx.lineTo(server.SIZE[0] / 2 * PX_PER_IN, server.SIZE[1] / 2 * PX_PER_IN);
                ctx.moveTo(server.SIZE[0] / 2 * PX_PER_IN, -server.SIZE[1] / 2 * PX_PER_IN);
                ctx.lineTo(-server.SIZE[0] / 2 * PX_PER_IN, server.SIZE[1] / 2 * PX_PER_IN);
                ctx.stroke();

                ctx.rotate(-dir);
                ctx.translate(-pos[0], -pos[1]);
            });
            if (self.autoStep) {
                self.step();
            }
        };

        self.turn = function (radians) {
            console.log('' + history.length + ' turning');
            server.turn(radians, onTurnComplete);
        };

        self.drive = function (inches) {
            console.log('' + history.length + ' driving ' + inches);
            server.drive(inches, onDriveComplete);
        };

        self.getRobots = function () {
            return robots;
        };

        // ----------------------------------------- private methods --------------------------------------------------
        self.step = function () {
            if (doing) {
                return;
            }
            doing = true;

            var curPos = server.getPos();
            var nxtPos = waypoints[waypointIdx];

            // At destination, pick next waypoint
            if (glmat.vec2.dist(curPos, nxtPos) < 3 * PX_PER_IN) {
                waypointIdx = (waypointIdx + 1) % waypoints.length;
                nxtPos = waypoints[waypointIdx];
            }

            // Turn
            var delta = glmat.vec2.sub([], nxtPos, curPos);
            var curAng = server.getAngle();
            var nxtAng = Math.atan2(delta[1], delta[0]);
            if (Math.abs(curAng - nxtAng) > 0.01) {
                self.turn(nxtAng - curAng);
                return;
            }

            // Drive
            var dist = glmat.vec2.length(delta);
            var stepCount = Math.ceil(dist / MAX_DRIVE);
            var stepDist = dist / stepCount;
            self.drive(stepDist);
        };

        var onTurnComplete = function (measuredRads) {
            //console.log('' + history.length + ' finished turn');
            robots.forEach(function (robot) {
                robot.turn(measuredRads);
            });
            server.scan(onScanComplete);
        };

        var onDriveComplete = function (measuredDist) {
            //console.log('' + history.length + ' finished drive');
            robots.forEach(function (robot) {
                robot.drive(measuredDist);
            });
            server.scan(onScanComplete);
        };

        var getStats = function (robots) {
            // Figure out distance and standard deviation
            var meanPos = robots.reduce(function (meanPos, robot) {
                return glmat.vec2.add(meanPos, meanPos, robot.getPos());
            }, [0, 0]);
            glmat.vec2.scale(meanPos, meanPos, 1 / robots.length);
            var dists = robots.map(function (robot) {
                return glmat.vec2.distance(meanPos, robot.getPos());
            });
            var distMean = Math.avg(dists);
            var distStdDv = Math.stddev(dists);

            // Figure out fitness stddev
            var fitnesses = robots.map(function (robot) {
                return robot.cachedFitness;
            });
            var fitMean = Math.avg(fitnesses);
            var fitStdDv = Math.stddev(fitnesses);
            return {
                meanPos: meanPos,
                distMean: distMean,
                distStdDv: distStdDv,
                fitMean: fitMean,
                fitStdDv: fitStdDv
            };
        };

        var onScanComplete = function (samples) {
            //console.log('' + history.length + ' got samples');
            history.push({action: 'scan', data: samples});

            // Calculate fitness based on how well each robot would have guessed these samples
            robots.forEach(function (robot) {
                robot.fitness(samples);
            });
            var min = robots.reduce(function (prev, robot) {
                return Math.min(prev, robot.cachedFitness)
            }, Number.POSITIVE_INFINITY);
            var max = robots.reduce(function (prev, robot) {
                return Math.max(prev, robot.cachedFitness)
            }, Number.NEGATIVE_INFINITY);
            //console.log('best=' + max + ' worst=' + min);
            var range = max - min;
            robots.forEach(function (robot) {
                robot.normalizedFitness = range > 0 ? (robot.cachedFitness - min) / range : 1;
            });

            // Cull the bad bots
            var stats = getStats(robots);
            console.log('distMean=' + stats.distMean + ' distStdDv=' + stats.distStdDv + ' fitMean=' + stats.fitMean + ' fitStdDv=' + stats.fitStdDv);
            if (stats.fitStdDv > 0.01) {
                var goodBots = [];
                var badBots = [];
                deadBots = [];

                // Collect bots to be killed
                var sorted = robots.slice().sort(function (a, b) {
                    return b.cachedFitness - a.cachedFitness;
                });
                var totalFitness = robots.reduce(function (prev, robot) {
                    return prev + robot.cachedFitness;
                }, 0);
                var curFitness = 0;
                for (var i = 0; i < sorted.length; i++) {
                    var robot = sorted[i];
                    if (robot.getAge() < 5) {
                        continue; // Don't kill children
                    }
                    curFitness += robot.cachedFitness;
                    var rnd = Math.random() * totalFitness;
                    if(curFitness < rnd) {
                        goodBots.push(robot);
                        continue;
                    }
                    var zombie = {pos: robot.getPos().slice(), ang: robot.getAngle()};
                    deadBots.push(zombie);
                    console.log('killed robot' + i
                        + ' at fitness ' + robot.cachedFitness
                        //+ ' ' + deviation + ' stddev from mean '
                        + '[' + Math.round(zombie.pos[0]) + ',' + Math.round(zombie.pos[1]) + '] '
                        + ' vs [' + Math.round(stats.meanPos[0]) + ',' + Math.round(stats.meanPos[1]) + ']'
                    );
                    badBots.push(robot);
                }

                // Regenerate bots
                if (badBots.length > 0) {
                    console.log('culled ' + badBots.length + ' robots');
                    stats = getStats(goodBots);
                    console.log('distMean=' + stats.distMean + ' distStdDv=' + stats.distStdDv + ' fitMean=' + stats.fitMean + ' fitStdDv=' + stats.fitStdDv);
                    for (var i = 0; i < badBots.length; i++) {
                        var robot = badBots[i];
                        var ang = server.getAngle(); // TODO: Randomness
                        var pos = stats.meanPos.slice();
                        var len = Math.nextGaussian(stats.distMean, stats.distStdDv);
                        pos[0] += Math.cos(ang) * len;
                        pos[1] += Math.sin(ang) * len;
                        robot.reset(pos, ang);
                    }
                }
            }

            // Tell the robots to update their maps based on the new data
            robots[0].applySamples(samples, stats.meanPos, server.getAngle(), map);

            //robots.sort(function(a,b) {return a.cachedFitness - b.cachedFitness;});

            doing = false;
            self.invalidate.dispatch();
        };

        ctor();
        return self;
    };

    return SlamClient;
});<commit_msg>More robots, don't memory leak history<commit_after>define([
    'signals',
    'glmat',
    'slam/Map',
    'slam/Math',
    'slam/Robot',
    'slam/MockServer'
], function SlamClient(signals,
                       glmat,
                       Map,
                       Math,
                       Robot,
                       server) {
    var SlamClient = function SlamClient(width, height) {
        var self = {};

        // --------------------------------------------- constants ----------------------------------------------------
        var ROBOT_COUNT = 100;
        var PX_PER_FT = 30; // TODO: Un hard code
        var IN_PER_FT = 12;
        var PX_PER_IN = PX_PER_FT / IN_PER_FT; // TODO: Sane scaling system
        var MAX_DRIVE = 6 * PX_PER_IN;

        var waypoints = [
            [800, 700],
            [800, 200],
            [550, 200],
            [550, 300],
            [250, 300],
            [250, 500],
            [250, 840],
            [800, 830]
        ];
        var waypointIdx = 1;

        var doing = false;
        var curBot;
        var deadBots = [];
        self.allBots = true;
        self.autoStep = false;
        var map = new Map(width, height);

        // --------------------------------------------- events -------------------------------------------------------
        self.invalidate = new signals.Signal();

        // ------------------------------------------- private vars ---------------------------------------------------
        var robots = [];
        var history = [];
        var iterations = 0;

        // ------------------------------------------ constructor -----------------------------------------------------
        var ctor = function () {
            server.setPos(waypoints[0]);
            for (var i = 0; i < ROBOT_COUNT; i++) {
                var bot = new Robot('' + i, width, height, map);
                bot.setPos(waypoints[0]);
                robots.push(bot);
            }
        };

        // ------------------------------------------ public methods --------------------------------------------------
        self.showBot = function (bot) {
            curBot = bot;
        };

        self.showAll = function (val) {
            self.allBots = val;
        };

        self.autoDrive = function (val) {
            self.autoStep = val;
        };

        self.start = function () {
            server.scan(onScanComplete);
        };

        self.draw = function (ctx) {
            robots.forEach(function (robot) {
                if (curBot === robot) {
                    robot.drawMap(ctx);
                    robot.drawSamples(ctx);
                }
                if (self.allBots === true || curBot === robot) {
                    robot.drawRobot(ctx);
                }
            });
            deadBots.forEach(function (robot) {
                ctx.strokeStyle = '#FF0000';
                var pos = robot.pos;
                var dir = robot.ang;
                ctx.translate(pos[0], pos[1]);
                ctx.rotate(dir);

                ctx.strokeRect(-server.SIZE[0] / 2 * PX_PER_IN, -server.SIZE[1] / 2 * PX_PER_IN, server.SIZE[0] * PX_PER_IN, server.SIZE[1] * PX_PER_IN);
                ctx.beginPath();
                ctx.moveTo(-server.SIZE[0] / 2 * PX_PER_IN, -server.SIZE[1] / 2 * PX_PER_IN);
                ctx.lineTo(server.SIZE[0] / 2 * PX_PER_IN, server.SIZE[1] / 2 * PX_PER_IN);
                ctx.moveTo(server.SIZE[0] / 2 * PX_PER_IN, -server.SIZE[1] / 2 * PX_PER_IN);
                ctx.lineTo(-server.SIZE[0] / 2 * PX_PER_IN, server.SIZE[1] / 2 * PX_PER_IN);
                ctx.stroke();

                ctx.rotate(-dir);
                ctx.translate(-pos[0], -pos[1]);
            });
            if (self.autoStep) {
                self.step();
            }
        };

        self.turn = function (radians) {
            console.log('' + iterations + ' turning');
            server.turn(radians, onTurnComplete);
        };

        self.drive = function (inches) {
            console.log('' + iterations + ' driving ' + inches);
            server.drive(inches, onDriveComplete);
        };

        self.getRobots = function () {
            return robots;
        };

        // ----------------------------------------- private methods --------------------------------------------------
        self.step = function () {
            if (doing) {
                return;
            }
            doing = true;

            var curPos = server.getPos();
            var nxtPos = waypoints[waypointIdx];

            // At destination, pick next waypoint
            if (glmat.vec2.dist(curPos, nxtPos) < 3 * PX_PER_IN) {
                waypointIdx = (waypointIdx + 1) % waypoints.length;
                nxtPos = waypoints[waypointIdx];
            }

            // Turn
            var delta = glmat.vec2.sub([], nxtPos, curPos);
            var curAng = server.getAngle();
            var nxtAng = Math.atan2(delta[1], delta[0]);
            if (Math.abs(curAng - nxtAng) > 0.01) {
                self.turn(nxtAng - curAng);
                return;
            }

            // Drive
            var dist = glmat.vec2.length(delta);
            var stepCount = Math.ceil(dist / MAX_DRIVE);
            var stepDist = dist / stepCount;
            self.drive(stepDist);
        };

        var onTurnComplete = function (measuredRads) {
            //console.log('' + iterations + ' finished turn');
            robots.forEach(function (robot) {
                robot.turn(measuredRads);
            });
            server.scan(onScanComplete);
        };

        var onDriveComplete = function (measuredDist) {
            //console.log('' + iterations + ' finished drive');
            robots.forEach(function (robot) {
                robot.drive(measuredDist);
            });
            server.scan(onScanComplete);
        };

        var getStats = function (robots) {
            // Figure out distance and standard deviation
            var meanPos = robots.reduce(function (meanPos, robot) {
                return glmat.vec2.add(meanPos, meanPos, robot.getPos());
            }, [0, 0]);
            glmat.vec2.scale(meanPos, meanPos, 1 / robots.length);
            var dists = robots.map(function (robot) {
                return glmat.vec2.distance(meanPos, robot.getPos());
            });
            var distMean = Math.avg(dists);
            var distStdDv = Math.stddev(dists);

            // Figure out fitness stddev
            var fitnesses = robots.map(function (robot) {
                return robot.cachedFitness;
            });
            var fitMean = Math.avg(fitnesses);
            var fitStdDv = Math.stddev(fitnesses);
            return {
                meanPos: meanPos,
                distMean: distMean,
                distStdDv: distStdDv,
                fitMean: fitMean,
                fitStdDv: fitStdDv
            };
        };

        var onScanComplete = function (samples) {
            //console.log('' + iterations + ' got samples');
            //history.push({action: 'scan', data: samples});
            iterations++;

            // Calculate fitness based on how well each robot would have guessed these samples
            robots.forEach(function (robot) {
                robot.fitness(samples);
            });
            var min = robots.reduce(function (prev, robot) {
                return Math.min(prev, robot.cachedFitness)
            }, Number.POSITIVE_INFINITY);
            var max = robots.reduce(function (prev, robot) {
                return Math.max(prev, robot.cachedFitness)
            }, Number.NEGATIVE_INFINITY);
            //console.log('best=' + max + ' worst=' + min);
            var range = max - min;
            robots.forEach(function (robot) {
                robot.normalizedFitness = range > 0 ? (robot.cachedFitness - min) / range : 1;
            });

            // Cull the bad bots
            var stats = getStats(robots);
            console.log('distMean=' + stats.distMean + ' distStdDv=' + stats.distStdDv + ' fitMean=' + stats.fitMean + ' fitStdDv=' + stats.fitStdDv);
            if (stats.fitStdDv > 0.01) {
                var goodBots = [];
                var badBots = [];
                deadBots = [];

                // Collect bots to be killed
                var sorted = robots.slice().sort(function (a, b) {
                    return b.cachedFitness - a.cachedFitness;
                });
                var totalFitness = robots.reduce(function (prev, robot) {
                    return prev + robot.cachedFitness;
                }, 0);
                var curFitness = 0;
                for (var i = 0; i < sorted.length; i++) {
                    var robot = sorted[i];
                    if (robot.getAge() < 5) {
                        continue; // Don't kill children
                    }
                    curFitness += robot.cachedFitness;
                    var rnd = Math.random() * totalFitness;
                    if(curFitness < rnd) {
                        goodBots.push(robot);
                        continue;
                    }
                    var zombie = {pos: robot.getPos().slice(), ang: robot.getAngle()};
                    deadBots.push(zombie);
                    console.log('killed robot' + i
                        + ' at fitness ' + robot.cachedFitness
                        //+ ' ' + deviation + ' stddev from mean '
                        + '[' + Math.round(zombie.pos[0]) + ',' + Math.round(zombie.pos[1]) + '] '
                        + ' vs [' + Math.round(stats.meanPos[0]) + ',' + Math.round(stats.meanPos[1]) + ']'
                    );
                    badBots.push(robot);
                }

                // Regenerate bots
                if (badBots.length > 0) {
                    console.log('culled ' + badBots.length + ' robots');
                    stats = getStats(goodBots);
                    console.log('distMean=' + stats.distMean + ' distStdDv=' + stats.distStdDv + ' fitMean=' + stats.fitMean + ' fitStdDv=' + stats.fitStdDv);
                    for (var i = 0; i < badBots.length; i++) {
                        var robot = badBots[i];
                        var ang = server.getAngle(); // TODO: Randomness
                        var pos = stats.meanPos.slice();
                        var len = Math.nextGaussian(stats.distMean, stats.distStdDv);
                        pos[0] += Math.cos(ang) * len;
                        pos[1] += Math.sin(ang) * len;
                        robot.reset(pos, ang);
                    }
                }
            }

            // Tell the robots to update their maps based on the new data
            robots[0].applySamples(samples, stats.meanPos, server.getAngle(), map);

            //robots.sort(function(a,b) {return a.cachedFitness - b.cachedFitness;});

            doing = false;
            self.invalidate.dispatch();
        };

        ctor();
        return self;
    };

    return SlamClient;
});<|endoftext|>


<commit_before>/*jshint esversion: 6 */
'use strict';
const AWSXRay = require('aws-xray-sdk-core');
const AWS = AWSXRay.captureAWS(require('aws-sdk'));
const dynamodb = new AWS.DynamoDB.DocumentClient();

exports.handler = (event, context, callback) => {
    const today = new Date();
    var yyyy = today.getFullYear();
    var mm = today.getMonth();
    var dd = today.getDate();
    const todayEpoch = new Date(yyyy, mm, dd).getTime() / 1000;
    console.log(todayEpoch);

    let startTime = todayEpoch + 21600;
    console.log('startTime = ' + startTime);
    if (event.lastupdated !== undefined) {
        console.log('Detecting lastupdated variable, ' + event.lastupdated);
        startTime = Number(event.lastupdated);
    }
    console.log('startTime = ' + startTime);
    let startTimeString = startTime.toString([10]);

    console.log('startTimeString = ' + startTimeString);

    var params = {
    TableName: "impact-map",
    ProjectionExpression: "Coordinates, #b",
    FilterExpression: "#a > :start",
    ExpressionAttributeNames: {
        "#a": "Added",
        "#b": "Action"
    },
    ExpressionAttributeValues: {
         ":start": {
           "N": startTimeString
         }
    }
    };

let combinedData = [];

    console.log("Scanning table.");
    dynamodb.scan(params, onScan);

    function onScan(err, data) {
        if (err) {
            console.error("Unable to scan the table. Error JSON:", JSON.stringify(err, null, 2));
        } else {
            // print all items
            console.log("Scan succeeded.");
            data.Items.forEach(function(item) {
               combinedData = combinedData.concat(item);
            });

            // continue scanning if we have more items, because
            // scan can retrieve a maximum of 1MB of data
            if (typeof data.LastEvaluatedKey != "undefined") {
                console.log("Scanning for more...");
                params.ExclusiveStartKey = data.LastEvaluatedKey;
                dynamodb.scan(params, onScan);
            }
            callback(null, combinedData);
        }
    }
};
<commit_msg>Change condition for lastupdated variable processing<commit_after>/*jshint esversion: 6 */
'use strict';
const AWSXRay = require('aws-xray-sdk-core');
const AWS = AWSXRay.captureAWS(require('aws-sdk'));
const dynamodb = new AWS.DynamoDB.DocumentClient();

exports.handler = (event, context, callback) => {
    const today = new Date();
    var yyyy = today.getFullYear();
    var mm = today.getMonth();
    var dd = today.getDate();
    const todayEpoch = new Date(yyyy, mm, dd).getTime() / 1000;
    console.log(todayEpoch);

    let startTime = todayEpoch + 21600;
    console.log('startTime = ' + startTime);
    if (event.lastupdated > 1) {
        console.log('Detecting lastupdated variable, ' + event.lastupdated);
        startTime = Number(event.lastupdated);
    }
    console.log('startTime = ' + startTime);
    let startTimeString = startTime.toString([10]);

    console.log('startTimeString = ' + startTimeString);

    var params = {
    TableName: "impact-map",
    ProjectionExpression: "Coordinates, #b",
    FilterExpression: "#a > :start",
    ExpressionAttributeNames: {
        "#a": "Added",
        "#b": "Action"
    },
    ExpressionAttributeValues: {
         ":start": {
           "N": startTimeString
         }
    }
    };

let combinedData = [];

    console.log("Scanning table.");
    dynamodb.scan(params, onScan);

    function onScan(err, data) {
        if (err) {
            console.error("Unable to scan the table. Error JSON:", JSON.stringify(err, null, 2));
        } else {
            // print all items
            console.log("Scan succeeded.");
            data.Items.forEach(function(item) {
               combinedData = combinedData.concat(item);
            });

            // continue scanning if we have more items, because
            // scan can retrieve a maximum of 1MB of data
            if (typeof data.LastEvaluatedKey != "undefined") {
                console.log("Scanning for more...");
                params.ExclusiveStartKey = data.LastEvaluatedKey;
                dynamodb.scan(params, onScan);
            }
            callback(null, combinedData);
        }
    }
};
<|endoftext|>


<commit_before>"use strict"

define('console', [], function() {
  if (!console.exception) {
    console.exception = function(exc){
      console.error(exc.message)
      console.error(exc.stack);
    }
  }
  return console;
});

define('r7/timer', [], function(){
  return {
    t: function(){
      return new Date().getTime();
    }
  };
});

define('main', [
    'r7/Ring',
    'r7/evt',
    'r7/timer',
    'r7/Stage4LogEvent',
    'ui',
    'rules',
    'console'
], function(
  Ring,
  evt,
  timer,
  Stage4LogEvent,
  ui,
  rules,
  console
) {

  return function(){
    var container = window.document.getElementById('layers');
    var ring = Ring([
      Stage4LogEvent(['Init', 'SpawnObj', 'DespawnObj', 'BeginContact', 'Start', 'Stop']).onEvent,
      ui(container).onEvent,
      rules.onEvent
    ]);

    ring.push(evt.Init);
    //ring.push(evt.Start); //TODO push Start when ready and user hit star button
    var lastDelta500 = -1;
    var loop = function() {
      // loop on r<F10>equest animation loop
      // - it has to be at the beginning of the function
      // - @see http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
      //RequestAnimationFrame.request(loop);
      // note: three.js includes requestAnimationFrame shim
      requestAnimationFrame(loop);
      var t = new Date().getTime();
      var delta500 = null;
      if (lastDelta500 === -1) {
        lastDelta500 = t;
        delta500 = 0;
      }
      var d = (t - lastDelta500) / 500;
      if (d >=  1) {
        lastDelta500 = t;
        delta500 = d;
      }
      ring.push(evt.Tick(t, delta500));
    };

    loop();
  };
});
<commit_msg>failed to try code to force 30FPS<commit_after>"use strict"

define('console', [], function() {
  if (!console.exception) {
    console.exception = function(exc){
      console.error(exc.message)
      console.error(exc.stack);
    }
  }
  return console;
});

define('r7/timer', [], function(){
  return {
    t: function(){
      return new Date().getTime();
    }
  };
});

define('main', [
    'r7/Ring',
    'r7/evt',
    'r7/timer',
    'r7/Stage4LogEvent',
    'ui',
    'rules',
    'console'
], function(
  Ring,
  evt,
  timer,
  Stage4LogEvent,
  ui,
  rules,
  console
) {

  return function(){
    var container = window.document.getElementById('layers');
    var ring = Ring([
      Stage4LogEvent(['Init', 'SpawnObj', 'DespawnObj', 'BeginContact', 'Start', 'Stop']).onEvent,
      ui(container).onEvent,
      rules.onEvent
    ]);

    ring.push(evt.Init);
    //ring.push(evt.Start); //TODO push Start when ready and user hit star button
    var lastDelta500 = -1;
    var loop = function() {
      // loop on r<F10>equest animation loop
      // - it has to be at the beginning of the function
      // - @see http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
      //RequestAnimationFrame.request(loop);
      // note: three.js includes requestAnimationFrame shim
      //setTimeout(function() { requestAnimationFrame(loop); }, 1000/30);
      requestAnimationFrame(loop);
      var t = new Date().getTime();
      var delta500 = null;
      if (lastDelta500 === -1) {
        lastDelta500 = t;
        delta500 = 0;
      }
      var d = (t - lastDelta500) / 500;
      if (d >=  1) {
        lastDelta500 = t;
        delta500 = d;
      }
      ring.push(evt.Tick(t, delta500));
    };

    loop();
  };
});
<|endoftext|>


<commit_before>/*
 * biojs-io-snparser
 * https://github.com/jameshiew/biojs-io-snparser
 *
 * Copyright (c) 2015 James Hiew
 * Licensed under the MIT license.
 */

'use strict'

const csv = require('csv')

/** @type {Map<string, object>} */
const dialects = new Map()
dialects.set('23andMe-2015-07-22', {
  auto_parse: true,
  columns: [
    'rsid',
    'chromosome',
    'position',
    'genotype'
  ],
  comment: '#',
  delimiter: '\t',
  quote: ''
})

/**
 * Encapsulates a SNP.
 *
 * @param {Object} args
 * @param {Array<string>} args.alleles
 * @param {string} args.chromosome
 * @param {int} args.position
 * @param {string} args.referenceAssembly
 * @param {string} args.rsid
 * @param {string} args.strand
 * @constructor
 */
function SNP (args) {
  this.alleles = args.alleles
  this.chromosome = args.chromosome
  this.referenceAssembly = args.referenceAssembly
  this.rsid = args.rsid
  this.position = args.position
  this.strand = args.strand
}

/**
 * Parse raw data into SNP Javascript objects.
 *
 * @param {Object} options
 * @param {string} options.data - contents of the raw data set
 * @param {string} options.format - e.g. '23andMe-2015-07-22'
 * @return {Array<SNP>}
 */
module.exports.parse = function parse (options) {
  options = options || {}
  // validate arguments
  const dialect = dialects.get(options.format)
  if (!dialect) {
    throw new Error(`Unrecognised format specified: ${options.format}`)
  }

  // parse to SNP objects sychronously
  let snps = []
  csv.parse(options.data, dialect, function (error, output) {
    if (error) {
      throw error
    }
    if (options.format === '23andMe-2015-07-22') {
      for (let rawSnp of output) {
        snps.push(new SNP({
          alleles: rawSnp.genotype.split(''),
          chromosome: rawSnp.chromosome,
          position: rawSnp.position,
          referenceAssembly: 'GRCh37',
          rsid: rawSnp.rsid.match(/rs\d*/)
            ? rawSnp.rsid
            : undefined,
          strand: '+'
        }))
      }
    }
  })
  return snps
}
<commit_msg>Use OLOO pattern instead of class pattern<commit_after>/*
 * biojs-io-snparser
 * https://github.com/jameshiew/biojs-io-snparser
 *
 * Copyright (c) 2015 James Hiew
 * Licensed under the MIT license.
 */

'use strict'

const csv = require('csv')

/** @type {Map<string, object>} */
const dialects = new Map()
dialects.set('23andMe-2015-07-22', {
  auto_parse: true,
  columns: [
    'rsid',
    'chromosome',
    'position',
    'genotype'
  ],
  comment: '#',
  delimiter: '\t',
  quote: ''
})

const SNP = {
  /**
   * Encapsulates a SNP.
   *
   * @param {Object} args
   * @param {Array<string>} args.alleles
   * @param {string} args.chromosome
   * @param {int} args.position
   * @param {string} args.referenceAssembly
   * @param {string} args.rsid
   * @param {string} args.strand
   */
  init: function init (args) {
    this.alleles = args.alleles
    this.chromosome = args.chromosome
    this.referenceAssembly = args.referenceAssembly
    this.rsid = args.rsid
    this.position = args.position
    this.strand = args.strand
    return this
  }
}

/**
 * Parse raw data into SNP Javascript objects.
 *
 * @param {Object} options
 * @param {string} options.data - contents of the raw data set
 * @param {string} options.format - e.g. '23andMe-2015-07-22'
 * @return {Array<SNP>}
 */
module.exports.parse = function parse (options) {
  options = options || {}
  // validate arguments
  const dialect = dialects.get(options.format)
  if (!dialect) {
    throw new Error(`Unrecognised format specified: ${options.format}`)
  }

  // parse to SNP objects sychronously
  let snps = []
  csv.parse(options.data, dialect, function (error, output) {
    if (error) {
      throw error
    }
    if (options.format === '23andMe-2015-07-22') {
      for (let rawSnp of output) {
        snps.push(Object.create(SNP).init({
          alleles: rawSnp.genotype.split(''),
          chromosome: rawSnp.chromosome,
          position: rawSnp.position,
          referenceAssembly: 'GRCh37',
          rsid: rawSnp.rsid.match(/rs\d*/)
            ? rawSnp.rsid
            : undefined,
          strand: '+'
        }))
      }
    }
  })
  return snps
}
<|endoftext|>


<commit_before>'use strict';

var server = require('http').createServer();
var WebSocketServer = require('ws').Server;
var webSocketServer = new WebSocketServer({ server: server });
var express = require('express');
var _ = require('lodash');
var app = express();
var PORT = 8080;
var playerManager = require('./player_manager')();
var messageHandler = require('./message_handler')();

app.use(express.static('app'));

webSocketServer.on('connection', function connection(socket) {
  var playerId = playerManager.createPlayer(socket);
  socket.send(JSON.stringify({type: 'login', playerId: playerId}));
  var otherPlayers = playerManager.getOtherPlayers(playerId);
  _.each(otherPlayers, function (player) {
    socket.send(JSON.stringify({type: 'newPlayer', playerId: player.id, position: player.position}));
    player.socket.send(JSON.stringify({type: 'newPlayer', playerId: playerId}));
  });

  socket.on('message', function incoming(message) {
    message = JSON.parse(message);
    messageHandler[message.type](message);
  });

  socket.on('close', function incoming(code, message) {
    playerManager.deletePlayer(playerId);
    _.each(playerManager.players, function (player) {
      player.socket.send(JSON.stringify({type: 'deletePlayer', playerId: playerId}));
    });
  });
});

server.on('request', app);
server.listen(PORT, function () {
  console.log('Grupica debilizma up and running!');
});<commit_msg>map to port 80<commit_after>'use strict';

var server = require('http').createServer();
var WebSocketServer = require('ws').Server;
var webSocketServer = new WebSocketServer({ server: server });
var express = require('express');
var _ = require('lodash');
var app = express();
var PORT = 80;
var playerManager = require('./player_manager')();
var messageHandler = require('./message_handler')();

app.use(express.static('app'));

webSocketServer.on('connection', function connection(socket) {
  var playerId = playerManager.createPlayer(socket);
  socket.send(JSON.stringify({type: 'login', playerId: playerId}));
  var otherPlayers = playerManager.getOtherPlayers(playerId);
  _.each(otherPlayers, function (player) {
    socket.send(JSON.stringify({type: 'newPlayer', playerId: player.id, position: player.position}));
    player.socket.send(JSON.stringify({type: 'newPlayer', playerId: playerId}));
  });

  socket.on('message', function incoming(message) {
    message = JSON.parse(message);
    messageHandler[message.type](message);
  });

  socket.on('close', function incoming(code, message) {
    playerManager.deletePlayer(playerId);
    _.each(playerManager.players, function (player) {
      player.socket.send(JSON.stringify({type: 'deletePlayer', playerId: playerId}));
    });
  });
});

server.on('request', app);
server.listen(PORT, function () {
  console.log('Grupica debilizma up and running!');
});<|endoftext|>


<commit_before>var assert = require('assert')
  , path = require('path')
  , request = require('request')
  , portfinder = require('portfinder')
  , Server = require('..').Server
  , Client = require('..').Client
  ;

describe ('Thalassa', function () {

  describe ('api', function () {

     var localhost = '127.0.0.1'
       , PORT = null
       , HOST = localhost
       , API_PORT = null
       , API_HOST = localhost
       , server = null
       , apiRoot = null
       ;

     before (function (done) {

       portfinder.getPort(function (err, port) {
         assert.ifError(err);
         PORT = port;
         portfinder.basePort = 9000;
         portfinder.getPort(function (err, port) {
           assert.ifError(err);
           API_PORT = port;
           apiRoot = 'http://' + API_HOST + ':' + API_PORT;
           server = new Server( {
             port: PORT,
             host: HOST,
             apiport: API_PORT,
             apihost: API_HOST,
             reaperFreq: 100
           });
           done();
         });
       });
     });

     after (function () {
       server.close();
     });

     it ('should return all for registrations', function (done) {
       this.timeout(10000);

       //need to wait until it comes up
       setTimeout(function () {
         request({
           uri: apiRoot + '/registrations',
           json: true
         }, function (error, response, body) {
           assert.ifError(error);
           assert.equal(200, response.statusCode);

           var thalassas = body.filter(function (it) { return (it.name === 'thalassa'); });

           assert.equal(1, thalassas.length);
           done();
         });
       }, 100);
     });

     it ('should 404 for unknown route', function (done) {
       this.timeout(5000);

       //need to wait until it comes up
       setTimeout(function () {
         request({
           uri: apiRoot + '/bogus',
           json: true
         }, function (error, response, body) {
           assert.ifError(error);
           assert.equal(404, response.statusCode);
           done();
         });
       }, 100);
     });

     it ('should return registrations by name', function (done) {
       this.timeout(5000);

       //need to wait until it comes up
       setTimeout(function () {
         request({
           uri: apiRoot + '/registrations/thalassa',
           json: true
         }, function (error, response, body) {
           assert.ifError(error);
           assert.equal(200, response.statusCode);

           assert.equal(1, body.length);
           assert.equal('thalassa', body[0].name);
           done();
         });
       }, 100);
     });

     it ('should return registrations by name and version', function (done) {
       this.timeout(5000);
       var version = require('../package.json').version;

       //need to wait until it comes up
       setTimeout(function () {
         request({
           uri: apiRoot + '/registrations/thalassa/'+version,
           json: true
         }, function (error, response, body) {
           assert.ifError(error);
           assert.equal(200, response.statusCode);

           assert.equal(1, body.length);
           assert.equal('thalassa', body[0].name);
           assert.equal(version, body[0].version);
           done();
         });
       }, 100);
     });

     it ('should return nothing for query by unknown name', function (done) {
       this.timeout(5000);

       //need to wait until it comes up
       setTimeout(function () {
         request({
           uri: apiRoot + '/registrations/bogus',
           json: true
         }, function (error, response, body) {
           assert.ifError(error);
           assert.equal(200, response.statusCode);

           assert.equal(0, body.length);
           done();
         });
       }, 100);
     });

     it ('should register and find custom registration', function (done) {
       this.timeout(5000);
       var name = 'foo'
         , version = '2.0.0'
         , host = '10.10.10.10'
         , port = 8411
         , meta = { myMeta: 'foo', myOtherMeta: 1 }
         ;
       var client = new Client({
         host: HOST,
         port: PORT
       });
       client.register(name, version, port, meta);
       client.start();

       //need to wait until it comes up
       setTimeout(function () {
         request({
           uri: apiRoot + '/registrations/' + name +'/'+version,
           json: true
         }, function (error, response, body) {
           assert.ifError(error);
           assert.equal(200, response.statusCode);

           assert.equal(1, body.length);
           assert.equal(name, body[0].name);
           assert.equal(version, body[0].version);
           assert.equal(port, body[0].port);
           assert.equal(meta.myMeta, body[0].meta.myMeta);
           assert.equal(meta.myOtherMeta, body[0].meta.myOtherMeta);

           //also test get registrations
           client.getRegistrations(name, version, function(err,regs){
             assert.ifError(err);
             assert.equal(regs.length, 1);
             done();
           });
         });
       }, 100);
     });

     it ('should stop and restart properly', function (done) {
       this.timeout(5000);
       var name = 'bar'
         , version = '2.0.0'
         , host = '10.10.10.10'
         , port = 8412
         , secondsToExpire = 1
         ;
       var client = new Client({
         host: HOST,
         port: PORT
       });

       client.register(name, version, port, { secondsToExpire: secondsToExpire});
       setTimeout(function() {
         client.stop();
         setTimeout(function() {
           request({
             uri: apiRoot + '/registrations/' + name +'/'+version,
             json: true
           }, function (error, response, body) {
             assert.ifError(error);
             assert.equal(200, response.statusCode);
             assert.equal(0, body.length);

             client.start();
             setTimeout(function() {
               request({
                 uri: apiRoot + '/registrations/' + name +'/'+version,
                 json: true
               }, function (error, response, body) {
                 assert.ifError(error);
                 assert.equal(200, response.statusCode);

                 assert.equal(1, body.length);
                 assert.equal(name, body[0].name);
                 assert.equal(version, body[0].version);
                 assert.equal(port, body[0].port);
                 done();
               });
             }, 100);
           });
         }, secondsToExpire*1000);
       }, 100);
     });

     it ('should register and unregister properly', function (done) {
       this.timeout(5000);
       var name = 'baz'
         , version = '3.0.0'
         , host = '10.10.10.10'
         , port = 8413
         ;
       var client = new Client({
         host: HOST,
         port: PORT
       });

       client.register(name, version, port);
       client.start();

       setTimeout(function() {
         request({
           uri: apiRoot + '/registrations/' + name +'/'+version,
           json: true
         }, function (error, response, body) {
           assert.ifError(error);
           assert.equal(200, response.statusCode);

           assert.equal(1, body.length);
           assert.equal(name, body[0].name);
           assert.equal(version, body[0].version);
           assert.equal(port, body[0].port);
           client.unregister(name, version, port);
           setTimeout(function() {
             request({
               uri: apiRoot + '/registrations/' + name +'/'+version,
               json: true
             }, function (error, response, body) {
               assert.ifError(error);
               assert.equal(200, response.statusCode);
               assert.equal(0, body.length);
               done();
             });
           }, 100);
         });
       }, 100);
     });

  });
});
<commit_msg>add tests for new feature where server always emits 'online' for registration<commit_after>var assert = require('assert')
  , path = require('path')
  , request = require('request')
  , portfinder = require('portfinder')
  , Server = require('..').Server
  , Client = require('..').Client
  ;

describe ('Thalassa', function () {

  describe ('api', function () {

     var localhost = '127.0.0.1'
       , PORT = null
       , HOST = localhost
       , API_PORT = null
       , API_HOST = localhost
       , server = null
       , apiRoot = null
       ;

     before (function (done) {

       portfinder.getPort(function (err, port) {
         assert.ifError(err);
         PORT = port;
         portfinder.basePort = 9000;
         portfinder.getPort(function (err, port) {
           assert.ifError(err);
           API_PORT = port;
           apiRoot = 'http://' + API_HOST + ':' + API_PORT;
           server = new Server( {
             port: PORT,
             host: HOST,
             apiport: API_PORT,
             apihost: API_HOST,
             reaperFreq: 100
           });
           done();
         });
       });
     });

     after (function () {
       server.close();
     });

     it ('should return all for registrations', function (done) {
       this.timeout(10000);

       //need to wait until it comes up
       setTimeout(function () {
         request({
           uri: apiRoot + '/registrations',
           json: true
         }, function (error, response, body) {
           assert.ifError(error);
           assert.equal(200, response.statusCode);

           var thalassas = body.filter(function (it) { return (it.name === 'thalassa'); });

           assert.equal(1, thalassas.length);
           done();
         });
       }, 100);
     });

     it ('should 404 for unknown route', function (done) {
       this.timeout(5000);

       //need to wait until it comes up
       setTimeout(function () {
         request({
           uri: apiRoot + '/bogus',
           json: true
         }, function (error, response, body) {
           assert.ifError(error);
           assert.equal(404, response.statusCode);
           done();
         });
       }, 100);
     });

     it ('should return registrations by name', function (done) {
       this.timeout(5000);

       //need to wait until it comes up
       setTimeout(function () {
         request({
           uri: apiRoot + '/registrations/thalassa',
           json: true
         }, function (error, response, body) {
           assert.ifError(error);
           assert.equal(200, response.statusCode);

           assert.equal(1, body.length);
           assert.equal('thalassa', body[0].name);
           done();
         });
       }, 100);
     });

     it ('should return registrations by name and version', function (done) {
       this.timeout(5000);
       var version = require('../package.json').version;

       //need to wait until it comes up
       setTimeout(function () {
         request({
           uri: apiRoot + '/registrations/thalassa/'+version,
           json: true
         }, function (error, response, body) {
           assert.ifError(error);
           assert.equal(200, response.statusCode);

           assert.equal(1, body.length);
           assert.equal('thalassa', body[0].name);
           assert.equal(version, body[0].version);
           done();
         });
       }, 100);
     });

     it ('should return nothing for query by unknown name', function (done) {
       this.timeout(5000);

       //need to wait until it comes up
       setTimeout(function () {
         request({
           uri: apiRoot + '/registrations/bogus',
           json: true
         }, function (error, response, body) {
           assert.ifError(error);
           assert.equal(200, response.statusCode);
           assert.equal(0, body.length);
           done();
         });
       }, 100);
     });

     it( 'should register and receive one online event if metadata stays the same', function (done) {
       this.timeout(5000);
       var eventCount = 0;
       var name = 'foobar'
         , version = '1.0.0'
         , host = '10.10.10.10'
         , port = 8411
         , meta = { myMeta: 'foo', myOtherMeta: 1 }
         ;
       var client = new Client({
         host: HOST,
         port: PORT,
         updateFreq: 2000
       });
       client.on('online', function(reg){
        eventCount++;
        setInterval(function() {
           if(eventCount == 1){
             assert.equal(reg.name,name);
             assert.equal(reg.version,version);
             assert.equal(reg.port, port);
             assert.deepEqual(reg.meta, meta);
             done();
           }
         },3000);
       });
       client.subscribe(name, version);
       client.register(name, version, port, meta);
       client.start();
     });

     it( 'should register, receive an online event, unregister, then receive another online event', function (done) {
       this.timeout(5000);
       var eventCount = 0;
       var offlineRecieved = false;
       var name = 'foobar'
         , version = '1.0.0'
         , host = '10.10.10.10'
         , port = 8411
         , meta = { myMeta: 'foo', myOtherMeta: 1 }
         ;
       var client = new Client({
         host: HOST,
         port: PORT,
         updateFreq: 2000
       });
       client.on('online', function(reg){
        eventCount++;
        if(eventCount == 1){
          assert.equal(reg.name,name);
          assert.equal(reg.version,version);
          assert.equal(reg.port, port);
          assert.deepEqual(reg.meta, meta);
          client.unregister(name,version,port);
        }
        else if(offlineReceived){
          assert.equal(reg.name,name);
          assert.equal(reg.version,version);
          assert.equal(reg.port, port);
          done();
        }
       });
       client.on('offline', function(reg){
         offlineReceived = true;
       });
       client.subscribe(name, version);
       client.register(name, version, port, meta);
       client.start();
     });

     it ('should register and find custom registration', function (done) {
       this.timeout(5000);
       var name = 'foo'
         , version = '2.0.0'
         , host = '10.10.10.10'
         , port = 8411
         , meta = { myMeta: 'foo', myOtherMeta: 1 }
         ;
       var client = new Client({
         host: HOST,
         port: PORT
       });
       client.register(name, version, port, meta);
       client.start();

       //need to wait until it comes up
       setTimeout(function () {
         request({
           uri: apiRoot + '/registrations/' + name +'/'+version,
           json: true
         }, function (error, response, body) {
           assert.ifError(error);
           assert.equal(200, response.statusCode);

           assert.equal(1, body.length);
           assert.equal(name, body[0].name);
           assert.equal(version, body[0].version);
           assert.equal(port, body[0].port);
           assert.equal(meta.myMeta, body[0].meta.myMeta);
           assert.equal(meta.myOtherMeta, body[0].meta.myOtherMeta);

           //also test get registrations
           client.getRegistrations(name, version, function(err,regs){
             assert.ifError(err);
             assert.equal(regs.length, 1);
             done();
           });
         });
       }, 100);
     });

     it ('should stop and restart properly', function (done) {
       this.timeout(5000);
       var name = 'bar'
         , version = '2.0.0'
         , host = '10.10.10.10'
         , port = 8412
         , secondsToExpire = 1
         ;
       var client = new Client({
         host: HOST,
         port: PORT
       });

       client.register(name, version, port, { secondsToExpire: secondsToExpire});
       setTimeout(function() {
         client.stop();
         setTimeout(function() {
           request({
             uri: apiRoot + '/registrations/' + name +'/'+version,
             json: true
           }, function (error, response, body) {
             assert.ifError(error);
             assert.equal(200, response.statusCode);
             assert.equal(0, body.length);

             client.start();
             setTimeout(function() {
               request({
                 uri: apiRoot + '/registrations/' + name +'/'+version,
                 json: true
               }, function (error, response, body) {
                 assert.ifError(error);
                 assert.equal(200, response.statusCode);

                 assert.equal(1, body.length);
                 assert.equal(name, body[0].name);
                 assert.equal(version, body[0].version);
                 assert.equal(port, body[0].port);
                 done();
               });
             }, 100);
           });
         }, secondsToExpire*1000);
       }, 100);
     });

     it ('should register and unregister properly', function (done) {
       this.timeout(5000);
       var name = 'baz'
         , version = '3.0.0'
         , host = '10.10.10.10'
         , port = 8413
         ;
       var client = new Client({
         host: HOST,
         port: PORT
       });

       client.register(name, version, port);
       client.start();

       setTimeout(function() {
         request({
           uri: apiRoot + '/registrations/' + name +'/'+version,
           json: true
         }, function (error, response, body) {
           assert.ifError(error);
           assert.equal(200, response.statusCode);

           assert.equal(1, body.length);
           assert.equal(name, body[0].name);
           assert.equal(version, body[0].version);
           assert.equal(port, body[0].port);
           client.unregister(name, version, port);
           setTimeout(function() {
             request({
               uri: apiRoot + '/registrations/' + name +'/'+version,
               json: true
             }, function (error, response, body) {
               assert.ifError(error);
               assert.equal(200, response.statusCode);
               assert.equal(0, body.length);
               done();
             });
           }, 100);
         });
       }, 100);
     });

  });
});
<|endoftext|>


<commit_before>import { extend, override } from 'flarum/extend';
import app from 'flarum/app';

import PostControls from 'flarum/utils/PostControls';
import CommentPost from 'flarum/components/CommentPost';

app.initializers.add('flarum-akismet', () => {
  extend(PostControls, 'destructiveControls', function(items, post) {
    if (items.has('approve')) {
      const flags = post.flags();

      if (flags && flags.some(flag => flag.type() === 'akismet')) {
        items.get('approve').props.children = app.translator.trans('flarum-akismet.forum.post.not_spam_button');
      }
    }
  });

  override(CommentPost.prototype, 'flagReason', function(original, flag) {
    if (flag.type() === 'akismet') {
      return app.translator.trans('flarum-akismet.forum.post.akismet_flagged_text');
    }

    return original(flag);
  });
}, -20); // run after the approval extension
<commit_msg>update for mithril 2<commit_after>import { extend, override } from 'flarum/extend';
import app from 'flarum/app';

import PostControls from 'flarum/utils/PostControls';
import CommentPost from 'flarum/components/CommentPost';

app.initializers.add('flarum-akismet', () => {
  extend(PostControls, 'destructiveControls', function(items, post) {
    if (items.has('approve')) {
      const flags = post.flags();

      if (flags && flags.some(flag => flag.type() === 'akismet')) {
        items.get('approve').children = app.translator.trans('flarum-akismet.forum.post.not_spam_button');
      }
    }
  });

  override(CommentPost.prototype, 'flagReason', function(original, flag) {
    if (flag.type() === 'akismet') {
      return app.translator.trans('flarum-akismet.forum.post.akismet_flagged_text');
    }

    return original(flag);
  });
}, -20); // run after the approval extension
<|endoftext|>


<commit_before>var check = require('./lib/util/check')
var extend = require('./lib/util/extend')
var dynamic = require('./lib/dynamic')
var raf = require('./lib/util/raf')
var clock = require('./lib/util/clock')
var createStringStore = require('./lib/strings')
var initWebGL = require('./lib/webgl')
var wrapExtensions = require('./lib/extension')
var wrapLimits = require('./lib/limits')
var wrapBuffers = require('./lib/buffer')
var wrapElements = require('./lib/elements')
var wrapTextures = require('./lib/texture')
var wrapRenderbuffers = require('./lib/renderbuffer')
var wrapFramebuffers = require('./lib/framebuffer')
var wrapAttributes = require('./lib/attribute')
var wrapShaders = require('./lib/shader')
var wrapRead = require('./lib/read')
var createCore = require('./lib/core')
var createStats = require('./lib/stats')
var createTimer = require('./lib/timer')

var GL_COLOR_BUFFER_BIT = 16384
var GL_DEPTH_BUFFER_BIT = 256
var GL_STENCIL_BUFFER_BIT = 1024

var GL_ARRAY_BUFFER = 34962

var CONTEXT_LOST_EVENT = 'webglcontextlost'
var CONTEXT_RESTORED_EVENT = 'webglcontextrestored'

var DYN_PROP = 1
var DYN_CONTEXT = 2
var DYN_STATE = 3

module.exports = function wrapREGL () {
  var args = initWebGL(Array.prototype.slice.call(arguments))
  var gl = args.gl
  var options = args.options

  var stringStore = createStringStore()
  var stats = createStats()

  var extensionState = wrapExtensions(gl)
  var extensions = extensionState.extensions
  var timer = createTimer(gl, extensions)

  var START_TIME = clock()
  var WIDTH = gl.drawingBufferWidth
  var HEIGHT = gl.drawingBufferHeight

  var contextState = {
    tick: 0,
    time: 0,
    viewportWidth: WIDTH,
    viewportHeight: HEIGHT,
    framebufferWidth: WIDTH,
    framebufferHeight: HEIGHT,
    drawingBufferWidth: WIDTH,
    drawingBufferHeight: HEIGHT,
    pixelRatio: options.pixelRatio
  }
  var uniformState = {}
  var drawState = {
    elements: null,
    primitive: 4, // GL_TRIANGLES
    count: -1,
    offset: 0,
    instances: -1
  }

  var limits = wrapLimits(gl, extensions)
  var bufferState = wrapBuffers(gl, stats)
  var elementState = wrapElements(gl, extensions, bufferState, stats)
  var attributeState = wrapAttributes(
    gl,
    extensions,
    limits,
    bufferState,
    stringStore)
  var shaderState = wrapShaders(gl, stringStore, stats)
  var textureState = wrapTextures(
    gl,
    extensions,
    limits,
    poll,
    contextState,
    stats)
  var renderbufferState = wrapRenderbuffers(gl, extensions, limits, stats)
  var framebufferState = wrapFramebuffers(
    gl,
    extensions,
    limits,
    textureState,
    renderbufferState,
    stats)
  var readPixels = wrapRead(gl, poll, contextState)

  var core = createCore(
    gl,
    stringStore,
    extensions,
    limits,
    bufferState,
    elementState,
    textureState,
    framebufferState,
    uniformState,
    attributeState,
    shaderState,
    drawState,
    contextState,
    timer)

  var nextState = core.next
  var canvas = gl.canvas

  var rafCallbacks = []
  var activeRAF = 0
  function handleRAF () {
    // schedule next animation frame
    activeRAF = raf.next(handleRAF)

    // increment frame count
    contextState.tick += 1

    // Update time
    contextState.time = (clock() - START_TIME) / 1000.0

    // poll for changes
    poll()

    // fire a callback for all pending rafs
    for (var i = 0; i < rafCallbacks.length; ++i) {
      var cb = rafCallbacks[i]
      cb(contextState, null, 0)
    }

    // flush all pending webgl calls
    gl.flush()
  }

  function startRAF () {
    if (!activeRAF && rafCallbacks.length > 0) {
      handleRAF()
    }
  }

  function stopRAF () {
    if (activeRAF) {
      raf.cancel(handleRAF)
      activeRAF = 0
    }
  }

  function handleContextLoss (event) {
    // TODO
  }

  function handleContextRestored (event) {
    // TODO
  }

  if (canvas) {
    canvas.addEventListener(CONTEXT_LOST_EVENT, handleContextLoss, false)
    canvas.addEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored, false)
  }

  function destroy () {
    stopRAF()

    if (canvas) {
      canvas.removeEventListener(CONTEXT_LOST_EVENT, handleContextLoss)
      canvas.removeEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored)
    }

    shaderState.clear()
    framebufferState.clear()
    renderbufferState.clear()
    textureState.clear()
    elementState.clear()
    bufferState.clear()

    if (timer) {
      timer.clear()
    }

    if (options.onDestroy) {
      options.onDestroy()
    }
  }

  function compileProcedure (options) {
    check(!!options, 'invalid args to regl({...})')
    check.type(options, 'object', 'invalid args to regl({...})')

    function flattenNestedOptions (options) {
      var result = extend({}, options)
      delete result.uniforms
      delete result.attributes
      delete result.context

      function merge (name) {
        if (name in result) {
          var child = result[name]
          delete result[name]
          Object.keys(child).forEach(function (prop) {
            result[name + '.' + prop] = child[prop]
          })
        }
      }
      merge('blend')
      merge('depth')
      merge('cull')
      merge('stencil')
      merge('polygonOffset')
      merge('scissor')
      merge('sample')

      return result
    }

    function separateDynamic (object) {
      var staticItems = {}
      var dynamicItems = {}
      Object.keys(object).forEach(function (option) {
        var value = object[option]
        if (dynamic.isDynamic(value)) {
          dynamicItems[option] = dynamic.unbox(value, option)
        } else {
          staticItems[option] = value
        }
      })
      return {
        dynamic: dynamicItems,
        static: staticItems
      }
    }

    // Treat context variables separate from other dynamic variables
    var context = separateDynamic(options.context || {})
    var uniforms = separateDynamic(options.uniforms || {})
    var attributes = separateDynamic(options.attributes || {})
    var opts = separateDynamic(flattenNestedOptions(options))

    var stats = {
      gpuTime: 0.0
    }

    var compiled = core.compile(opts, attributes, uniforms, context, stats)

    var draw = compiled.draw
    var batch = compiled.batch
    var scope = compiled.scope

    var EMPTY_ARRAY = []
    function reserve (count) {
      while (EMPTY_ARRAY.length < count) {
        EMPTY_ARRAY.push(null)
      }
      return EMPTY_ARRAY
    }

    function REGLCommand (args, body) {
      var i
      if (typeof args === 'function') {
        return scope.call(this, null, args, 0)
      } else if (typeof body === 'function') {
        if (typeof args === 'number') {
          for (i = 0; i < args; ++i) {
            scope.call(this, null, body, i)
          }
          return
        } else if (Array.isArray(args)) {
          for (i = 0; i < args.length; ++i) {
            scope.call(this, args[i], body, i)
          }
          return
        } else {
          return scope.call(this, args, body, 0)
        }
      } else if (typeof args === 'number') {
        if (args > 0) {
          return batch.call(this, reserve(args | 0), args | 0)
        }
      } else if (Array.isArray(args)) {
        if (args.length) {
          return batch.call(this, args, args.length)
        }
      } else {
        return draw.call(this, args)
      }
    }

    return extend(REGLCommand, {
      stats: stats
    })

//    return REGLCommand
  }

  function clear (options) {
    check(
      typeof options === 'object' && options,
      'regl.clear() takes an object as input')

    var clearFlags = 0
    core.procs.poll()

    var c = options.color
    if (c) {
      gl.clearColor(+c[0] || 0, +c[1] || 0, +c[2] || 0, +c[3] || 0)
      clearFlags |= GL_COLOR_BUFFER_BIT
    }
    if ('depth' in options) {
      gl.clearDepth(+options.depth)
      clearFlags |= GL_DEPTH_BUFFER_BIT
    }
    if ('stencil' in options) {
      gl.clearStencil(options.stencil | 0)
      clearFlags |= GL_STENCIL_BUFFER_BIT
    }

    check(!!clearFlags, 'called regl.clear with no buffer specified')
    gl.clear(clearFlags)
  }

  function frame (cb) {
    check.type(cb, 'function', 'regl.frame() callback must be a function')

    rafCallbacks.push(cb)

    function cancel () {
      var index = rafCallbacks.find(function (item) {
        return item === cb
      })
      if (index < 0) {
        return
      }
      rafCallbacks.splice(index, 1)
      if (rafCallbacks.length <= 0) {
        stopRAF()
      }
    }

    startRAF()

    return {
      cancel: cancel
    }
  }

  // poll viewport
  function pollViewport () {
    var viewport = nextState.viewport
    var scissorBox = nextState.scissor_box
    viewport[0] = viewport[1] = scissorBox[0] = scissorBox[1] = 0
    contextState.viewportWidth =
      contextState.framebufferWidth =
      contextState.drawingBufferWidth =
      viewport[2] =
      scissorBox[2] = gl.drawingBufferWidth
    contextState.viewportHeight =
      contextState.framebufferHeight =
      contextState.drawingBufferHeight =
      viewport[3] =
      scissorBox[3] = gl.drawingBufferHeight
  }

  function poll () {
    pollViewport()
    core.procs.poll()
  }

  function refresh () {
    pollViewport()
    core.procs.refresh()
  }

  refresh()

  return extend(compileProcedure, {
    // Clear current FBO
    clear: clear,

    // Short cuts for dynamic variables
    prop: dynamic.define.bind(null, DYN_PROP),
    context: dynamic.define.bind(null, DYN_CONTEXT),
    this: dynamic.define.bind(null, DYN_STATE),

    // executes an empty draw command
    draw: compileProcedure({}),

    // Resources
    buffer: function (options) {
      return bufferState.create(options, GL_ARRAY_BUFFER)
    },
    elements: elementState.create,
    texture: textureState.create2D,
    cube: textureState.createCube,
    renderbuffer: renderbufferState.create,
    framebuffer: framebufferState.create,
    framebufferCube: function (options) {
      check.raise('framebuffer cube not yet implemented')
    },

    // Expose context attributes
    attributes: gl.getContextAttributes(),

    // Frame rendering
    frame: frame,

    // System limits
    limits: limits,
    hasExtension: function (name) {
      return limits.extensions.indexOf(name.toLowerCase()) >= 0
    },

    // Read pixels
    read: readPixels,

    // Destroy regl and all associated resources
    destroy: destroy,

    // Direct GL state manipulation
    _gl: gl,
    _refresh: refresh,

    // regl Statistics Information
    stats: stats,

    updateTimer: function () {
      timer.update()
    }
  })
}
<commit_msg>Add null-check for `timer` to `updateTimer()`<commit_after>var check = require('./lib/util/check')
var extend = require('./lib/util/extend')
var dynamic = require('./lib/dynamic')
var raf = require('./lib/util/raf')
var clock = require('./lib/util/clock')
var createStringStore = require('./lib/strings')
var initWebGL = require('./lib/webgl')
var wrapExtensions = require('./lib/extension')
var wrapLimits = require('./lib/limits')
var wrapBuffers = require('./lib/buffer')
var wrapElements = require('./lib/elements')
var wrapTextures = require('./lib/texture')
var wrapRenderbuffers = require('./lib/renderbuffer')
var wrapFramebuffers = require('./lib/framebuffer')
var wrapAttributes = require('./lib/attribute')
var wrapShaders = require('./lib/shader')
var wrapRead = require('./lib/read')
var createCore = require('./lib/core')
var createStats = require('./lib/stats')
var createTimer = require('./lib/timer')

var GL_COLOR_BUFFER_BIT = 16384
var GL_DEPTH_BUFFER_BIT = 256
var GL_STENCIL_BUFFER_BIT = 1024

var GL_ARRAY_BUFFER = 34962

var CONTEXT_LOST_EVENT = 'webglcontextlost'
var CONTEXT_RESTORED_EVENT = 'webglcontextrestored'

var DYN_PROP = 1
var DYN_CONTEXT = 2
var DYN_STATE = 3

module.exports = function wrapREGL () {
  var args = initWebGL(Array.prototype.slice.call(arguments))
  var gl = args.gl
  var options = args.options

  var stringStore = createStringStore()
  var stats = createStats()

  var extensionState = wrapExtensions(gl)
  var extensions = extensionState.extensions
  var timer = createTimer(gl, extensions)

  var START_TIME = clock()
  var WIDTH = gl.drawingBufferWidth
  var HEIGHT = gl.drawingBufferHeight

  var contextState = {
    tick: 0,
    time: 0,
    viewportWidth: WIDTH,
    viewportHeight: HEIGHT,
    framebufferWidth: WIDTH,
    framebufferHeight: HEIGHT,
    drawingBufferWidth: WIDTH,
    drawingBufferHeight: HEIGHT,
    pixelRatio: options.pixelRatio
  }
  var uniformState = {}
  var drawState = {
    elements: null,
    primitive: 4, // GL_TRIANGLES
    count: -1,
    offset: 0,
    instances: -1
  }

  var limits = wrapLimits(gl, extensions)
  var bufferState = wrapBuffers(gl, stats)
  var elementState = wrapElements(gl, extensions, bufferState, stats)
  var attributeState = wrapAttributes(
    gl,
    extensions,
    limits,
    bufferState,
    stringStore)
  var shaderState = wrapShaders(gl, stringStore, stats)
  var textureState = wrapTextures(
    gl,
    extensions,
    limits,
    poll,
    contextState,
    stats)
  var renderbufferState = wrapRenderbuffers(gl, extensions, limits, stats)
  var framebufferState = wrapFramebuffers(
    gl,
    extensions,
    limits,
    textureState,
    renderbufferState,
    stats)
  var readPixels = wrapRead(gl, poll, contextState)

  var core = createCore(
    gl,
    stringStore,
    extensions,
    limits,
    bufferState,
    elementState,
    textureState,
    framebufferState,
    uniformState,
    attributeState,
    shaderState,
    drawState,
    contextState,
    timer)

  var nextState = core.next
  var canvas = gl.canvas

  var rafCallbacks = []
  var activeRAF = 0
  function handleRAF () {
    // schedule next animation frame
    activeRAF = raf.next(handleRAF)

    // increment frame count
    contextState.tick += 1

    // Update time
    contextState.time = (clock() - START_TIME) / 1000.0

    // poll for changes
    poll()

    // fire a callback for all pending rafs
    for (var i = 0; i < rafCallbacks.length; ++i) {
      var cb = rafCallbacks[i]
      cb(contextState, null, 0)
    }

    // flush all pending webgl calls
    gl.flush()
  }

  function startRAF () {
    if (!activeRAF && rafCallbacks.length > 0) {
      handleRAF()
    }
  }

  function stopRAF () {
    if (activeRAF) {
      raf.cancel(handleRAF)
      activeRAF = 0
    }
  }

  function handleContextLoss (event) {
    // TODO
  }

  function handleContextRestored (event) {
    // TODO
  }

  if (canvas) {
    canvas.addEventListener(CONTEXT_LOST_EVENT, handleContextLoss, false)
    canvas.addEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored, false)
  }

  function destroy () {
    stopRAF()

    if (canvas) {
      canvas.removeEventListener(CONTEXT_LOST_EVENT, handleContextLoss)
      canvas.removeEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored)
    }

    shaderState.clear()
    framebufferState.clear()
    renderbufferState.clear()
    textureState.clear()
    elementState.clear()
    bufferState.clear()

    if (timer) {
      timer.clear()
    }

    if (options.onDestroy) {
      options.onDestroy()
    }
  }

  function compileProcedure (options) {
    check(!!options, 'invalid args to regl({...})')
    check.type(options, 'object', 'invalid args to regl({...})')

    function flattenNestedOptions (options) {
      var result = extend({}, options)
      delete result.uniforms
      delete result.attributes
      delete result.context

      function merge (name) {
        if (name in result) {
          var child = result[name]
          delete result[name]
          Object.keys(child).forEach(function (prop) {
            result[name + '.' + prop] = child[prop]
          })
        }
      }
      merge('blend')
      merge('depth')
      merge('cull')
      merge('stencil')
      merge('polygonOffset')
      merge('scissor')
      merge('sample')

      return result
    }

    function separateDynamic (object) {
      var staticItems = {}
      var dynamicItems = {}
      Object.keys(object).forEach(function (option) {
        var value = object[option]
        if (dynamic.isDynamic(value)) {
          dynamicItems[option] = dynamic.unbox(value, option)
        } else {
          staticItems[option] = value
        }
      })
      return {
        dynamic: dynamicItems,
        static: staticItems
      }
    }

    // Treat context variables separate from other dynamic variables
    var context = separateDynamic(options.context || {})
    var uniforms = separateDynamic(options.uniforms || {})
    var attributes = separateDynamic(options.attributes || {})
    var opts = separateDynamic(flattenNestedOptions(options))

    var stats = {
      gpuTime: 0.0
    }

    var compiled = core.compile(opts, attributes, uniforms, context, stats)

    var draw = compiled.draw
    var batch = compiled.batch
    var scope = compiled.scope

    var EMPTY_ARRAY = []
    function reserve (count) {
      while (EMPTY_ARRAY.length < count) {
        EMPTY_ARRAY.push(null)
      }
      return EMPTY_ARRAY
    }

    function REGLCommand (args, body) {
      var i
      if (typeof args === 'function') {
        return scope.call(this, null, args, 0)
      } else if (typeof body === 'function') {
        if (typeof args === 'number') {
          for (i = 0; i < args; ++i) {
            scope.call(this, null, body, i)
          }
          return
        } else if (Array.isArray(args)) {
          for (i = 0; i < args.length; ++i) {
            scope.call(this, args[i], body, i)
          }
          return
        } else {
          return scope.call(this, args, body, 0)
        }
      } else if (typeof args === 'number') {
        if (args > 0) {
          return batch.call(this, reserve(args | 0), args | 0)
        }
      } else if (Array.isArray(args)) {
        if (args.length) {
          return batch.call(this, args, args.length)
        }
      } else {
        return draw.call(this, args)
      }
    }

    return extend(REGLCommand, {
      stats: stats
    })

//    return REGLCommand
  }

  function clear (options) {
    check(
      typeof options === 'object' && options,
      'regl.clear() takes an object as input')

    var clearFlags = 0
    core.procs.poll()

    var c = options.color
    if (c) {
      gl.clearColor(+c[0] || 0, +c[1] || 0, +c[2] || 0, +c[3] || 0)
      clearFlags |= GL_COLOR_BUFFER_BIT
    }
    if ('depth' in options) {
      gl.clearDepth(+options.depth)
      clearFlags |= GL_DEPTH_BUFFER_BIT
    }
    if ('stencil' in options) {
      gl.clearStencil(options.stencil | 0)
      clearFlags |= GL_STENCIL_BUFFER_BIT
    }

    check(!!clearFlags, 'called regl.clear with no buffer specified')
    gl.clear(clearFlags)
  }

  function frame (cb) {
    check.type(cb, 'function', 'regl.frame() callback must be a function')

    rafCallbacks.push(cb)

    function cancel () {
      var index = rafCallbacks.find(function (item) {
        return item === cb
      })
      if (index < 0) {
        return
      }
      rafCallbacks.splice(index, 1)
      if (rafCallbacks.length <= 0) {
        stopRAF()
      }
    }

    startRAF()

    return {
      cancel: cancel
    }
  }

  // poll viewport
  function pollViewport () {
    var viewport = nextState.viewport
    var scissorBox = nextState.scissor_box
    viewport[0] = viewport[1] = scissorBox[0] = scissorBox[1] = 0
    contextState.viewportWidth =
      contextState.framebufferWidth =
      contextState.drawingBufferWidth =
      viewport[2] =
      scissorBox[2] = gl.drawingBufferWidth
    contextState.viewportHeight =
      contextState.framebufferHeight =
      contextState.drawingBufferHeight =
      viewport[3] =
      scissorBox[3] = gl.drawingBufferHeight
  }

  function poll () {
    pollViewport()
    core.procs.poll()
  }

  function refresh () {
    pollViewport()
    core.procs.refresh()
  }

  refresh()

  return extend(compileProcedure, {
    // Clear current FBO
    clear: clear,

    // Short cuts for dynamic variables
    prop: dynamic.define.bind(null, DYN_PROP),
    context: dynamic.define.bind(null, DYN_CONTEXT),
    this: dynamic.define.bind(null, DYN_STATE),

    // executes an empty draw command
    draw: compileProcedure({}),

    // Resources
    buffer: function (options) {
      return bufferState.create(options, GL_ARRAY_BUFFER)
    },
    elements: elementState.create,
    texture: textureState.create2D,
    cube: textureState.createCube,
    renderbuffer: renderbufferState.create,
    framebuffer: framebufferState.create,
    framebufferCube: function (options) {
      check.raise('framebuffer cube not yet implemented')
    },

    // Expose context attributes
    attributes: gl.getContextAttributes(),

    // Frame rendering
    frame: frame,

    // System limits
    limits: limits,
    hasExtension: function (name) {
      return limits.extensions.indexOf(name.toLowerCase()) >= 0
    },

    // Read pixels
    read: readPixels,

    // Destroy regl and all associated resources
    destroy: destroy,

    // Direct GL state manipulation
    _gl: gl,
    _refresh: refresh,

    // regl Statistics Information
    stats: stats,

    updateTimer: function () {
      if (timer) {
        timer.update()
      }
    }
  })
}
<|endoftext|>


<commit_before>/**
 * Main entry point for the scenario editor
 * @author mattwigway
 */

import React from 'react'
import {render} from 'react-dom'
import {Provider} from 'react-redux'
import {browserHistory, IndexRoute, Router, Route} from 'react-router'
import {syncHistoryWithStore} from 'react-router-redux'

import Application from './application'
import bootstrap from './bootstrap'
import EditProject from './edit-project'
import EditScenario from './edit-scenario'
import ImportShapefile from './import-shapefile'
import Login from './login'
import Project from './project'
import Scenario from './scenario'
import SelectProject from './select-project'
import SelectScenario from './select-scenario'
import store from './store'

if (process.env.NODE_ENV === 'development') {
  window.Perf = require('react-addons-perf')
}

import './styles.css'

bootstrap(store)

const history = syncHistoryWithStore(browserHistory, store)

// initialize the application
render(
  <Provider store={store}>
    <Router history={history}>
      <Route path='/' component={Application}>
        <IndexRoute component={SelectProject} />
        <Route path='projects/:projectId' component={Project}>
          <IndexRoute component={SelectScenario} />
          <Route path='edit' component={EditProject} />
          <Route path='scenarios/create' component={EditScenario} />
          <Route path='scenarios/:scenarioId' component={Scenario}>
            <Route path='edit' component={EditScenario} />
          </Route>
        </Route>
        <Route path='/import-shapefile' component={ImportShapefile} />
      </Route>
      <Route path='/login' component={Login} />
    </Router>
  </Provider>,
  document.getElementById('root')
)
<commit_msg>chore(perf): Automatically start Perf checking in development<commit_after>/**
 * Main entry point for the scenario editor
 * @author mattwigway
 */

import React from 'react'
import {render} from 'react-dom'
import {Provider} from 'react-redux'
import {browserHistory, IndexRoute, Router, Route} from 'react-router'
import {syncHistoryWithStore} from 'react-router-redux'

import Application from './application'
import bootstrap from './bootstrap'
import EditProject from './edit-project'
import EditScenario from './edit-scenario'
import ImportShapefile from './import-shapefile'
import Login from './login'
import Project from './project'
import Scenario from './scenario'
import SelectProject from './select-project'
import SelectScenario from './select-scenario'
import store from './store'

if (process.env.NODE_ENV === 'development') {
  const Perf = window.Perf = require('react-addons-perf')
  Perf.start()
}

import './styles.css'

bootstrap(store)

const history = syncHistoryWithStore(browserHistory, store)

// initialize the application
render(
  <Provider store={store}>
    <Router history={history}>
      <Route path='/' component={Application}>
        <IndexRoute component={SelectProject} />
        <Route path='projects/:projectId' component={Project}>
          <IndexRoute component={SelectScenario} />
          <Route path='edit' component={EditProject} />
          <Route path='scenarios/create' component={EditScenario} />
          <Route path='scenarios/:scenarioId' component={Scenario}>
            <Route path='edit' component={EditScenario} />
          </Route>
        </Route>
        <Route path='/import-shapefile' component={ImportShapefile} />
      </Route>
      <Route path='/login' component={Login} />
    </Router>
  </Provider>,
  document.getElementById('root')
)
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var test = require( 'tape' );
var isfinite = require( 'validate.io-finite' );
var isnan = require( 'validate.io-nan' );
var abs = require( 'math-abs' );
var betaln = require( './../lib' );

// FIXTURES //

var arg1 = require( './fixtures/arg1.json' );
var arg2 = require( './fixtures/arg2.json' );
var expected = require( './fixtures/expected.json' );
var i;
var v;
for ( i = 0; i < expected.length; i++ ) {
	v = expected[ i ];
	if ( v === 'Inf' ) {
		expected[ i ] = Number.POSITIVE_INFINITY;
	}
	else if ( v === 'NaN' ) {
		expected[ i ] = NaN;
	}
}

// TESTS //

test( 'main export is a function', function test( t ) {
	t.ok( typeof betaln === 'function', 'main export is a function' );
	t.end();
});

test( 'the function returns `NaN` if provided a `NaN`', function test( t ) {
	var val = betaln( NaN, 2 );
	t.notOk( val === val, 'returns NaN' );
	val = betaln( 2, NaN );
	t.notOk( val === val, 'returns NaN' );
	t.end();
});

test( 'the function returns `NaN` if provided negative values', function test( t ) {
	var val = betaln( -2, 5 );
	t.notOk( val === val, 'returns NaN' );
	val = betaln( 4, -3 );
	t.notOk( val === val, 'returns NaN' );
	t.end();
});

test( 'the function returns +Infinity if at least one argument is zero', function test( t ) {
	var val = betaln( 0, 2 );
	t.ok( !isfinite( val ), 'returns +Infinity' );
	val = betaln( 1, 0 );
	t.ok( !isfinite( val ), 'returns +Infinity' );
	t.end();
});

test( 'the function evaluates the logarithm of the beta function', function test( t ) {
	var actual;
	var b1;
	var b2;
	var i;
	for ( i = 0; i < arg1.length; i++ ) {
		actual =  betaln( arg1[ i ], arg2[ i ] );

		b1 = isfinite( actual );
		b2 = isfinite( expected[ i ] );
		t.equal( b1, b2, 'returned result is ' + ( (b2) ? 'finite' : 'not finite' ) );

		b1 = isnan( actual );
		b2 = isnan( expected[ i ] );
		t.equal( b1, b2, 'returned result is ' + ( (b1) ? '' : 'not' ) + ' NaN' );
		if ( !b1 ) {
			t.ok( abs( actual - expected[ i ] ) < 1e-14, 'returned result is within tolerance. actual: ' + actual + '; expected: ' + expected[ i ] + '.' );
		}
	}
	t.end();
});
<commit_msg>Rename tape variable<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var isfinite = require( 'validate.io-finite' );
var isnan = require( 'validate.io-nan' );
var abs = require( 'math-abs' );
var betaln = require( './../lib' );

// FIXTURES //

var arg1 = require( './fixtures/arg1.json' );
var arg2 = require( './fixtures/arg2.json' );
var expected = require( './fixtures/expected.json' );
var i;
var v;
for ( i = 0; i < expected.length; i++ ) {
	v = expected[ i ];
	if ( v === 'Inf' ) {
		expected[ i ] = Number.POSITIVE_INFINITY;
	}
	else if ( v === 'NaN' ) {
		expected[ i ] = NaN;
	}
}

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( typeof betaln === 'function', 'main export is a function' );
	t.end();
});

tape( 'the function returns `NaN` if provided a `NaN`', function test( t ) {
	var val = betaln( NaN, 2 );
	t.notOk( val === val, 'returns NaN' );
	val = betaln( 2, NaN );
	t.notOk( val === val, 'returns NaN' );
	t.end();
});

tape( 'the function returns `NaN` if provided negative values', function test( t ) {
	var val = betaln( -2, 5 );
	t.notOk( val === val, 'returns NaN' );
	val = betaln( 4, -3 );
	t.notOk( val === val, 'returns NaN' );
	t.end();
});

tape( 'the function returns +Infinity if at least one argument is zero', function test( t ) {
	var val = betaln( 0, 2 );
	t.ok( !isfinite( val ), 'returns +Infinity' );
	val = betaln( 1, 0 );
	t.ok( !isfinite( val ), 'returns +Infinity' );
	t.end();
});

tape( 'the function evaluates the logarithm of the beta function', function test( t ) {
	var actual;
	var b1;
	var b2;
	var i;
	for ( i = 0; i < arg1.length; i++ ) {
		actual =  betaln( arg1[ i ], arg2[ i ] );

		b1 = isfinite( actual );
		b2 = isfinite( expected[ i ] );
		t.equal( b1, b2, 'returned result is ' + ( (b2) ? 'finite' : 'not finite' ) );

		b1 = isnan( actual );
		b2 = isnan( expected[ i ] );
		t.equal( b1, b2, 'returned result is ' + ( (b1) ? '' : 'not' ) + ' NaN' );
		if ( !b1 ) {
			t.ok( abs( actual - expected[ i ] ) < 1e-14, 'returned result is within tolerance. actual: ' + actual + '; expected: ' + expected[ i ] + '.' );
		}
	}
	t.end();
});
<|endoftext|>