<commit_before>var app = angular.module('app',[]);

// Default configuration service
app.value('defaults', {width: 60, height: 40, blockSize: 10, blanksRatio: 10,
                 firstColorRatio: 50, secondColorRatio: 50, threshold: "3",
                 speed: "100", fillStroke: true, round: 0, unsatisfied: 0,
                 firstColorName: "Blue", secondColorName: "Yellow",
                 colors: ["Black", "Blue", "Cyan", "Brown", "Gray", "Green",
                 "Maroon", "Olive", "Orange", "Pink", "Red", "Teal", "Violet", "Yellow"]});

app.controller('SimulationController', function($scope, $timeout, $interval, defaults) {
    $scope.conf = defaults;

    function runSimulation(){
        var unsatisfiedAndBlanks = listUnsatisfiedAndBlanks($scope.board, $scope.conf.threshold);
        $scope.conf.round++;
        $scope.conf.unsatisfied = (unsatisfiedAndBlanks.length - $scope.blanksTotal) / ($scope.conf.width * $scope.conf.height) * 100;
        // If there are still unsatisfied agenst, update their position and redraw the board
        if(unsatisfiedAndBlanks.length > $scope.blanksTotal){
            swapAgents(unsatisfiedAndBlanks, $scope.board);
            $scope.draw();
        // Otherwise, the simulation is done
        }else{
            $scope.stop();
            alert("Finished!")
        }
    }

    $scope.initializeBoard = function(){
            var rows = $scope.conf.width;
            var cols = $scope.conf.height;
            $scope.blanksTotal = rows * cols * ($scope.conf.blanksRatio/100);

            /*
            The agents array is initially populated with the distribution of the colors based on the configuration values.

            Note: The array construction will be optimized when major browsers fully support ES6's Array comprehension.
            Currently, the code below only works on Firefox.

            var boardArray = [...[for (i of [...Array((rows * cols - $scope.blanksTotal) * ($scope.conf.firstColorRatio / 100)).keys()]) A],
                              ...[for (i of [...Array((rows * cols - $scope.blanksTotal) * (1 - ($scope.conf.firstColorRatio / 100))).keys()]) B],
                              ...[for (i of [...Array($scope.blanksTotal).keys()]) E]];

            Until then, the best approach is to use the String.repeat() functionality.
            */

            var toInt = function(e){ return parseInt(e); };
            var agentsArray = [...(""+A).repeat((rows * cols - $scope.blanksTotal) * ($scope.conf.firstColorRatio / 100)).split("").map(toInt),
                         ...(""+B).repeat((rows * cols - $scope.blanksTotal) * (1 - ($scope.conf.firstColorRatio / 100))).split("").map(toInt),
                         ...(""+E).repeat($scope.blanksTotal).split("").map(toInt)];

            shuffleArray(agentsArray);

            // Now that we have the agents shuffled, it's time to build the board
            $scope.board = [];
            for(var i = 0; i < rows; i++){
                $scope.board.push(agentsArray.splice(0, cols));
            }
            $scope.draw();
            $scope.conf.unsatisfied = countUnsatisfied($scope.board, $scope.conf.threshold) / ($scope.conf.width * $scope.conf.height) * 100;
    }

    $scope.draw = function() {
        $timeout(function(){
            var canvas = document.getElementById("canvas");
            if (canvas.getContext) {
                var ctx = canvas.getContext("2d");
                var blockSize = $scope.conf.blockSize;
                var palette = ["white", $scope.conf.firstColorName, $scope.conf.secondColorName];
                ctx.strokeStyle = "black";
                ctx.lineWidth = 0.5;
                for(var x = 0; x < $scope.conf.width; x++){
                    for (var y = 0; y < $scope.conf.height; y++){
                        ctx.fillStyle = palette[$scope.board[x][y]];
                        ctx.fillRect(x * blockSize, y * blockSize, blockSize, blockSize);
                        if($scope.conf.fillStroke)
                            ctx.strokeRect(x * blockSize, y * blockSize, blockSize, blockSize);
                    }
                }
            }else{
                alert("This browser doesn't support canvas technology. In order to use this application, you'll have to either update your browser or use another one.");
            }
        });
    }

    $scope.start = function(){
        $("#btnStart").prop("disabled", true);
        $("#btnStop").prop("disabled", false);
        $("#btnReset").prop("disabled", true);
        $scope.intervalID = $interval(function(){ runSimulation() }, $scope.conf.speed);
    }

    $scope.stop = function(){
        $("#btnStart").prop("disabled", false);
        $("#btnStop").prop("disabled", true);
        $("#btnReset").prop("disabled", false);
        $interval.cancel($scope.intervalID);
    }

    $scope.initializeBoard();
});

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

const E = 0, A = 1, B = 2;

function Coord(x, y){
    this.x = x;
    this.y = y;
}

var surroundings = [new Coord(-1, -1), new Coord(-1, 0), new Coord(-1, 1), new Coord(0, -1), new Coord(0, 1), new Coord(1, -1), new Coord(1, 0), new Coord(1, 1)];

function swapAgents(array, board){
    var copy = array.slice();
    shuffleArray(array);
    for(var i = 0; i < array.length; i++){
        board[array[i].x][array[i].y] = board[array[i].x][array[i].y] ^ board[copy[i].x][copy[i].y];
        board[copy[i].x][copy[i].y] = board[copy[i].x][copy[i].y] ^ board[array[i].x][array[i].y];
        board[array[i].x][array[i].y] = board[array[i].x][array[i].y] ^ board[copy[i].x][copy[i].y];
    }
}

function listUnsatisfiedAndBlanks(board, threshold){
    var unsatisfied = [];
    for(var x = 0; x < board.length; x++){
        for(var y = 0; y < board[x].length; y++){
            if(board[x][y] == E || countSurroundings(board, x, y) > threshold){
                unsatisfied.push(new Coord(x, y));
            }
        }
    }
    return unsatisfied;
}

function countUnsatisfied(board, threshold){
    var unsatisfied = 0;
    for(var x = 0; x < board.length; x++){
        for(var y = 0; y < board[x].length; y++){
            if(countSurroundings(board, x, y) > threshold){
                unsatisfied++;
            }
        }
    }
    return unsatisfied;
}

function countSurroundings(board, x, y){
    var count = 0;
    var refValue = board[x][y];
    if(refValue !== E){
        for(let coord of surroundings){
            var px = x + coord.x;
            var py = y + coord.y;
            if(board[px] && board[px][py] && board[px][py] !== E && board[px][py] !== refValue){
                count++;
            }
        }
    }
    return count;
}

function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * i);
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}
<commit_msg>New configuration defaults and minor improvements<commit_after>var app = angular.module('app',[]);

// Default configuration service
app.value('defaults', {width: 60, height: 30, blockSize: 10, blanksRatio: 10,
                 firstColorRatio: 50, secondColorRatio: 50, threshold: "3",
                 speed: "100", fillStroke: true, round: 0, unsatisfied: 0,
                 firstColorName: "Teal", secondColorName: "Yellow",
                 colors: ["Black", "Blue", "Cyan", "Brown", "Gray", "Green",
                 "Maroon", "Olive", "Orange", "Pink", "Red", "Teal", "Violet", "Yellow"]});

app.controller('SimulationController', function($scope, $timeout, $interval, defaults) {
    $scope.conf = defaults;

    function runSimulation(){
        var unsatisfiedAndBlanks = listUnsatisfiedAndBlanks($scope.board, $scope.conf.threshold);
        $scope.conf.round++;
        $scope.conf.unsatisfied = (unsatisfiedAndBlanks.length - $scope.blanksTotal) / ($scope.conf.width * $scope.conf.height) * 100;
        // If there are still unsatisfied agenst, update their position and redraw the board
        if(unsatisfiedAndBlanks.length > $scope.blanksTotal){
            swapAgents(unsatisfiedAndBlanks, $scope.board);
            $scope.draw();
        // Otherwise, the simulation is done
        }else{
            $scope.stop();
            $timeout(() => alert("Finished!"));
        }
    }

    $scope.initializeBoard = function(){
        // Fill an array distributing the agents and the blank cells according to the configuration
        var total = $scope.conf.width * $scope.conf.height;
        var blanks = $scope.blanksTotal = total * ($scope.conf.blanksRatio/100);
        var firstColorTotal = (total - blanks) * ($scope.conf.firstColorRatio / 100);
        var agentsArray = Array(total).fill(A, 0, firstColorTotal)
                                      .fill(B, firstColorTotal, total - blanks)
                                      .fill(E, total - blanks, total);
        shuffleArray(agentsArray);

        // Now that the agents are shuffled, it's time to build the board
        $scope.board = [];
        for(var i = 0; i < $scope.conf.width; i++){
            $scope.board.push(agentsArray.splice(0, $scope.conf.height));
        }

        // Now we draw the blocks in the canvas element based on the board
        $scope.draw();
        $scope.conf.unsatisfied = countUnsatisfied($scope.board, $scope.conf.threshold) / ($scope.conf.width * $scope.conf.height) * 100;
        $scope.conf.round = 0;
    }

    $scope.draw = function() {
        $timeout(() => {
            var canvas = document.getElementById("canvas");
            if (canvas.getContext) {
                var context = canvas.getContext("2d");
                var blockSize = $scope.conf.blockSize;
                var palette = ["white", $scope.conf.firstColorName, $scope.conf.secondColorName];
                context.strokeStyle = "black";
                context.lineWidth = 0.5;
                for(var x = 0; x < $scope.conf.width; x++){
                    for (var y = 0; y < $scope.conf.height; y++){
                        context.fillStyle = palette[$scope.board[x][y]];
                        context.fillRect(x * blockSize, y * blockSize, blockSize, blockSize);
                        if($scope.conf.fillStroke)
                            context.strokeRect(x * blockSize, y * blockSize, blockSize, blockSize);
                    }
                }
            }else{
                alert("This browser doesn't support canvas technology. In order to use this application, you'll have to either update your browser or use another one.");
            }
        });
    }

    $scope.start = function(){
        $("#btnStart").prop("disabled", true);
        $("#btnStop").prop("disabled", false);
        $("#btnReset").prop("disabled", true);
        $scope.intervalID = $interval(() => runSimulation(), $scope.conf.speed);
    }

    $scope.stop = function(){
        $("#btnStart").prop("disabled", false);
        $("#btnStop").prop("disabled", true);
        $("#btnReset").prop("disabled", false);
        $interval.cancel($scope.intervalID);
    }

    $scope.initializeBoard();
});

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

const E = 0, A = 1, B = 2;

function Coord(x, y){
    this.x = x;
    this.y = y;
}

var surroundings = [new Coord(-1, -1), new Coord(-1, 0), new Coord(-1, 1), new Coord(0, -1), new Coord(0, 1), new Coord(1, -1), new Coord(1, 0), new Coord(1, 1)];

function swapAgents(array, board){
    var copy = array.slice();
    shuffleArray(array);
    for(var i = 0; i < array.length; i++){
        board[array[i].x][array[i].y] = board[array[i].x][array[i].y] ^ board[copy[i].x][copy[i].y];
        board[copy[i].x][copy[i].y] = board[copy[i].x][copy[i].y] ^ board[array[i].x][array[i].y];
        board[array[i].x][array[i].y] = board[array[i].x][array[i].y] ^ board[copy[i].x][copy[i].y];
    }
}

function listUnsatisfiedAndBlanks(board, threshold){
    var unsatisfied = [];
    for(var x = 0; x < board.length; x++){
        for(var y = 0; y < board[x].length; y++){
            if(board[x][y] == E || countSurroundings(board, x, y) > threshold){
                unsatisfied.push(new Coord(x, y));
            }
        }
    }
    return unsatisfied;
}

function countUnsatisfied(board, threshold){
    var unsatisfied = 0;
    for(var x = 0; x < board.length; x++){
        for(var y = 0; y < board[x].length; y++){
            if(countSurroundings(board, x, y) > threshold){
                unsatisfied++;
            }
        }
    }
    return unsatisfied;
}

function countSurroundings(board, x, y){
    var count = 0;
    var refValue = board[x][y];
    if(refValue !== E){
        for(let coord of surroundings){
            var px = x + coord.x;
            var py = y + coord.y;
            if(board[px] && board[px][py] && board[px][py] !== E && board[px][py] !== refValue){
                count++;
            }
        }
    }
    return count;
}

function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * i);
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}
<|endoftext|>


<commit_before>'use strict'

const si = require('search-index')()
let paribasan_jawa = require('./paribasa.json')

function Paribasan () {
  // lapo iki?
}

Paribasan.prototype.indexing = () => {
  let paribasan_jawa_array = Paribasan._toArray(paribasan_jawa)
  return new Promise((resolve, reject) => {
    si.add(paribasan_jawa_array, function (err) {
      err ? reject(err) : resolve(true)
    })
  })
}

Paribasan.prototype.search = (q) => {
  let kata = {}
  kata.query = {'*': [q]}
  return new Promise((resolve, reject) => {
    si.search(kata, (err, searchResult) => {
      err ? reject(err) : resolve(searchResult)
    })
  })
}

Paribasan.prototype.get = function () {
  let paribasan_array = Paribasan._toArray(paribasan_jawa)
  let moratmarit = paribasan_jawa[Math.floor(Math.random() * paribasan_array.length)]
  return `"${moratmarit.paribasa.trim()}" - ${moratmarit.bahasa}`
}

Paribasan._toArray = (paribasan_object) => {
  return Object.keys(paribasan_object).map((k) => {
    return paribasan_object[k]
  })
}

module.exports = new Paribasan()
<commit_msg>Format search result<commit_after>'use strict'

const si = require('search-index')()
let paribasan_jawa = require('./paribasa.json')

function Paribasan () {
  // lapo iki?
}

Paribasan.prototype.indexing = () => {
  let paribasan_jawa_array = Paribasan._toArray(paribasan_jawa)
  return new Promise((resolve, reject) => {
    si.add(paribasan_jawa_array, function (err) {
      err ? reject(err) : resolve(true)
    })
  })
}

Paribasan.prototype.search = (q) => {
  let kata = {}
  kata.query = {'*': [q]}
  return new Promise((resolve, reject) => {
    si.search(kata, (err, searchResult) => {
      let hits = searchResult.hits
      let search_array = []
      hits.map((val) => {
        search_array.push(`${val.document.paribasa} - ${val.document.bahasa}`)
      })
      err ? reject(err) : resolve(search_array)
    })
  })
}

Paribasan.prototype.get = function () {
  let paribasan_array = Paribasan._toArray(paribasan_jawa)
  let moratmarit = paribasan_jawa[Math.floor(Math.random() * paribasan_array.length)]
  return `"${moratmarit.paribasa.trim()}" - ${moratmarit.bahasa}`
}

Paribasan._toArray = (paribasan_object) => {
  return Object.keys(paribasan_object).map((k) => {
    return paribasan_object[k]
  })
}

module.exports = new Paribasan()
<|endoftext|>


<commit_before>var pubsub = require('../lib/pubsub_service');
var Runtime = require('../zetta_runtime');
var Scientist = Runtime.Scientist;
var assert = require('assert');
var TestDriver = require('./fixture/example_driver');

pubsub.publish = function(){};

describe('Driver', function() {
  var machine = null;

  beforeEach(function(){
    machine = Scientist.configure(TestDriver);
  });

  it('should be attached to the zetta runtime', function() {
    assert.ok(Runtime.Device);
  });

  describe('Configuration', function() {
    it('should be configured by Scientist#configure', function() {
      assert.ok(machine.call);
      assert.equal(machine.type, 'testdriver');
      assert.equal(machine.state, 'ready');
      assert.equal(machine.name, 'Matt\'s Test Device');
    });

    it('should have an id automatically generated for it', function(){
      assert.ok(machine.id);
    });
  });

  describe('Transitions', function() {

    it('should change the state from ready to changed when calling change.', function(done) {
      machine.call('change', function() {
        assert.equal(machine.properties.state, 'changed');
        done();
      });
    });

    it('should throw an error when a disallowed transition tries to happen.', function(done) {
      machine.call('change', function() {
        try {
          machine.call('change');
        } catch (e) {
          assert.ok(e);
          done();
        }
      });
    });
  });

  describe('Streams', function(){

    function wireUpPubSub(stream, done){
      pubsub.publish = function(name, data){
        assert.ok(name);
        assert.ok(data);
        assert.ok(name.indexOf(stream) > -1);
        done();

      }
    }

    it('should stream values of foo once configured', function(done){
      assert.ok(machine.streams.length == 2);
      wireUpPubSub('foo', done);
      machine.foo++;
    });

    it('should stream values of bar once configured', function(done){
      assert.ok(machine.streams.length == 2);
      wireUpPubSub('bar', done);
      machine.incrementStreamValue();
    })
  });
});
<commit_msg>Added a test that will listen for a transition event to occur.<commit_after>var pubsub = require('../lib/pubsub_service');
var Runtime = require('../zetta_runtime');
var Scientist = Runtime.Scientist;
var assert = require('assert');
var TestDriver = require('./fixture/example_driver');

pubsub.publish = function(){};

describe('Driver', function() {
  var machine = null;

  beforeEach(function(){
    machine = Scientist.configure(TestDriver);
  });

  it('should be attached to the zetta runtime', function() {
    assert.ok(Runtime.Device);
  });

  describe('Configuration', function() {
    it('should be configured by Scientist#configure', function() {
      assert.ok(machine.call);
      assert.equal(machine.type, 'testdriver');
      assert.equal(machine.state, 'ready');
      assert.equal(machine.name, 'Matt\'s Test Device');
    });

    it('should have an id automatically generated for it', function(){
      assert.ok(machine.id);
    });
  });

  describe('Transitions', function() {

    it('should change the state from ready to changed when calling change.', function(done) {
      machine.call('change', function() {
        assert.equal(machine.properties.state, 'changed');
        done();
      });
    });

    it('should throw an error when a disallowed transition tries to happen.', function(done) {
      machine.call('change', function() {
        try {
          machine.call('change');
        } catch (e) {
          assert.ok(e);
          done();
        }
      });
    });

    it('should have transitions emitted like events.', function(done) {
      machine.on('change', function() {
        done();
      });

      machine.call('change');
    });
  });

  describe('Streams', function(){

    function wireUpPubSub(stream, done){
      pubsub.publish = function(name, data){
        assert.ok(name);
        assert.ok(data);
        assert.ok(name.indexOf(stream) > -1);
        done();

      }
    }

    it('should stream values of foo once configured', function(done){
      assert.ok(machine.streams.length == 2);
      wireUpPubSub('foo', done);
      machine.foo++;
    });

    it('should stream values of bar once configured', function(done){
      assert.ok(machine.streams.length == 2);
      wireUpPubSub('bar', done);
      machine.incrementStreamValue();
    })
  });
});
<|endoftext|>


<commit_before>var templates = (function () {

var exports = {};

exports.render = function (name, arg) {
    if (Handlebars.templates === undefined) {
        throw "Cannot find compiled templates!";
    }
    if (Handlebars.templates[name] === undefined) {
        throw "Cannot find a template with this name: " + name
              + ". If you are developing a new feature, this likely"
              + "means you need to add the file static/templates/"
              + name + ".handlerbars";
    }

    // The templates should be compiled into compiled.js.  In
    // prod we build compiled.js as part of the deployment process,
    // and for devs we have run_dev.py build compiled.js when templates
    // change.
    return Handlebars.templates[name](arg);
};

// We don't want to wait for DOM ready to register the Handlebars helpers
// below. There's no need to, as they do not access the DOM.
// Furthermore, waiting for DOM ready would introduce race conditions with
// other DOM-ready callbacks that attempt to render templates.

// Regular Handlebars partials require pre-registering.  This allows us to treat
// any template as a partial.  We also allow the partial to be passed additional
// named arguments.  Arguments should alternate between strings which will be
// used as the name and the associated value.
Handlebars.registerHelper('partial', function (template_name) {
    var extra_data = {};
    var args_len = arguments.length;
    var i;

    for (i = 1; i < args_len - 2; i += 2) {
        extra_data[arguments[i]] = arguments[i + 1];
    }
    var data = _.extend({}, this, extra_data);

    return new Handlebars.SafeString(exports.render(template_name, data));
});

Handlebars.registerHelper('plural', function (condition, one, other) {
    return (condition === 1) ? one : other;
});

Handlebars.registerHelper('if_and', function () {
    // Execute the conditional code if all conditions are true.
    // Example usage:
    //     {{#if_and cond1 cond2 cond3}}
    //
All true

    //     {{/if_and}}
    var options = arguments[arguments.length - 1];
    var i;
    for (i = 0; i < arguments.length - 1; i++) {
        if (!arguments[i]) {
            return options.inverse(this);
        }
    }
    return options.fn(this);
});

Handlebars.registerHelper('if_or', function () {
    // Execute the conditional code if any of the conditions are true.
    // Example usage:
    //     {{#if_or cond1 cond2 cond3}}
    //
At least one is true

    //     {{/if_or}}
    var options = arguments[arguments.length - 1];
    var i;
    for (i = 0; i < arguments.length - 1; i++) {
        if (arguments[i]) {
            return options.fn(this);

        }
    }
    return options.inverse(this);
});

Handlebars.registerHelper('t', function (i18n_key) {
    // Marks a string for translation.
    // Example usage:
    //     {{t "some English text"}}
    var result = i18n.t(i18n_key);
    return new Handlebars.SafeString(result);
});

Handlebars.registerHelper('tr', function (context, options) {
    // Marks a block for translation.
    // Example usage 1:
    //     {{#tr context}}
    //
some English text

    //     {{/tr}}
    //
    // Example usage 2:
    //     {{#tr context}}
    //
This __variable__ will get value from context

    //     {{/tr}}
    //
    // Notes:
    //     1. `context` is very important. It can be `this` or an
    //        object or key of the current context.
    //     2. Use `__` instead of `{{` and `}}` to declare expressions
    var result = i18n.t(options.fn(context), context);
    return new Handlebars.SafeString(result);
});

return exports;
}());
if (typeof module !== 'undefined') {
    module.exports = templates;
}
<commit_msg>templates: Fix stack traces throwing handlebars errors.<commit_after>var templates = (function () {

var exports = {};

exports.render = function (name, arg) {
    if (Handlebars.templates === undefined) {
        throw new Error("Cannot find compiled templates!");
    }
    if (Handlebars.templates[name] === undefined) {
        throw new Error("Cannot find a template with this name: " + name
              + ". If you are developing a new feature, this likely"
              + "means you need to add the file static/templates/"
              + name + ".handlebars");
    }

    // The templates should be compiled into compiled.js.  In
    // prod we build compiled.js as part of the deployment process,
    // and for devs we have run_dev.py build compiled.js when templates
    // change.
    return Handlebars.templates[name](arg);
};

// We don't want to wait for DOM ready to register the Handlebars helpers
// below. There's no need to, as they do not access the DOM.
// Furthermore, waiting for DOM ready would introduce race conditions with
// other DOM-ready callbacks that attempt to render templates.

// Regular Handlebars partials require pre-registering.  This allows us to treat
// any template as a partial.  We also allow the partial to be passed additional
// named arguments.  Arguments should alternate between strings which will be
// used as the name and the associated value.
Handlebars.registerHelper('partial', function (template_name) {
    var extra_data = {};
    var args_len = arguments.length;
    var i;

    for (i = 1; i < args_len - 2; i += 2) {
        extra_data[arguments[i]] = arguments[i + 1];
    }
    var data = _.extend({}, this, extra_data);

    return new Handlebars.SafeString(exports.render(template_name, data));
});

Handlebars.registerHelper('plural', function (condition, one, other) {
    return (condition === 1) ? one : other;
});

Handlebars.registerHelper('if_and', function () {
    // Execute the conditional code if all conditions are true.
    // Example usage:
    //     {{#if_and cond1 cond2 cond3}}
    //
All true

    //     {{/if_and}}
    var options = arguments[arguments.length - 1];
    var i;
    for (i = 0; i < arguments.length - 1; i++) {
        if (!arguments[i]) {
            return options.inverse(this);
        }
    }
    return options.fn(this);
});

Handlebars.registerHelper('if_or', function () {
    // Execute the conditional code if any of the conditions are true.
    // Example usage:
    //     {{#if_or cond1 cond2 cond3}}
    //
At least one is true

    //     {{/if_or}}
    var options = arguments[arguments.length - 1];
    var i;
    for (i = 0; i < arguments.length - 1; i++) {
        if (arguments[i]) {
            return options.fn(this);

        }
    }
    return options.inverse(this);
});

Handlebars.registerHelper('t', function (i18n_key) {
    // Marks a string for translation.
    // Example usage:
    //     {{t "some English text"}}
    var result = i18n.t(i18n_key);
    return new Handlebars.SafeString(result);
});

Handlebars.registerHelper('tr', function (context, options) {
    // Marks a block for translation.
    // Example usage 1:
    //     {{#tr context}}
    //
some English text

    //     {{/tr}}
    //
    // Example usage 2:
    //     {{#tr context}}
    //
This __variable__ will get value from context

    //     {{/tr}}
    //
    // Notes:
    //     1. `context` is very important. It can be `this` or an
    //        object or key of the current context.
    //     2. Use `__` instead of `{{` and `}}` to declare expressions
    var result = i18n.t(options.fn(context), context);
    return new Handlebars.SafeString(result);
});

return exports;
}());
if (typeof module !== 'undefined') {
    module.exports = templates;
}
<|endoftext|>


<commit_before>'use strict';

var EventEmitter = require('eventemitter3')
  , Container = require('./container')
  , iframe = require('./iframe');

/**
 * Fortress: Container and Image management for front-end code.
 *
 * @constructor
 * @param {Object} options Fortress configuration
 * @api private
 */
function Fortress(options) {
  if (!(this instanceof Fortress)) return new Fortress(options);
  options = options || {};

  //
  // Create a small dedicated container that houses all our iframes. This might
  // add an extra DOM node to the page in addition to each iframe but it will
  // ultimately result in a cleaner DOM as everything is nicely tucked away.
  //
  var scripts = document.getElementsByTagName('script')
    , append = scripts[scripts.length - 1] || document.body
    , div = document.createElement('div');

  append.parentNode.insertBefore(div, append);

  this.global = (function () { return this; })() || window;
  this.containers = {};
  this.mount = div;

  scripts = null;

  EventEmitter.call(this);
}

Fortress.prototype = new EventEmitter();

/**
 * Detect HTMLfile support.
 *
 * @type {Boolean}
 * @api private
 */
Fortress.prototype.htmlfile = false;

try { Fortress.prototype.htmlfile = !!new ActiveXObject('htmlfile'); }
catch (e) {}

/**
 * Detect the current globals that are loaded in to this page. This way we can
 * see if we are leaking data.
 *
 * @param {Array} old Optional array with previous or known leaks.
 * @returns {Array} Names of the leaked globals.
 * @api private
 */
Fortress.prototype.globals = function globals(old) {
  var i = iframe(this.mount, Date.now())
    , global = this.global;

  this.mount.removeChild(i.frame);

  //
  // Detect the globals and return them.
  //
  return Object.keys(global).filter(function filter(key) {
    var introduced = !(key in i.window);

    //
    // We've been given an array, so we should use that as the source of previous
    // and acknowledged leaks and only return an array that contains newly
    // introduced leaks.
    //
    if (introduced && old && old.length) {
      return ~old.indexOf(key)
      ? false
      : true;
    }

    return introduced;
  });
};

/**
 * List all active containers.
 *
 * @returns {Array} Active containers.
 * @api public
 */
Fortress.prototype.all = function all() {
  var everything = [];

  for (var id in this.containers) {
    everything.push(this.containers[id]);
  }

  return everything;
};

/**
 * Generate an unique, unknown id that we can use for our container storage.
 *
 * @returns {String}
 * @api private
 */
Fortress.prototype.id = function id() {
  for (var i = 0, generated = []; i < 4; i++) {
    generated.push(Math.random().toString(36).substring(2));
  }

  generated = 'fortress_'+ generated.join('_');

  //
  // Ensure that we didn't generate a pre-existing id, if we did, generate
  // another id.
  //
  if (generated in this.containers) return this.id();
  return generated;
};

/**
 * Create a new container.
 *
 * @param {String} code
 * @param {Object} options Options for the container
 * @returns {Container}
 * @api public
 */
Fortress.prototype.create = function create(code, options) {
  var container = new Container(this.mount, this.id(), code, options);
  this.containers[container.id] = container;

  return container;
};

/**
 * Get a container based on it's unique id.
 *
 * @param {String} id The container id.
 * @returns {Container}
 * @api public
 */
Fortress.prototype.get = function get(id) {
  return this.containers[id];
};

/**
 * Inspect a running Container in order to get more detailed information about
 * the process. In recent browsers we can access:
 *
 * - console.memory(), performance.memory
 *
 * @param {String} id The container id.
 * @api public
 */
Fortress.prototype.inspect = function inspect(id) {
  return this;
};

/**
 * Start the container with the given id.
 *
 * @param {String} id The container id.
 * @api public
 */
Fortress.prototype.start = function start(id) {
  var container = this.get(id);
  if (!container) return this;

  container.start();
  return this;
};

/**
 * Stop a running container, this does not fully destroy the container. It
 * merely stops it from running. Stopping an container will cause the container
 * to start from the beginning again once it's started. This is not a pause
 * function.
 *
 * @param {String} id The container id.
 * @api public
 */
Fortress.prototype.stop = function stop(id) {
  var container = this.get(id);
  if (!container) return this;

  container.stop();
  return this;
};

/**
 * Restart a container. Basically, just a start and stop.
 *
 * @param {String} id The container id.
 * @api public
 */
Fortress.prototype.restart = function restart(id) {
  var container = this.get(id);
  if (!container) return this;

  container.stop().start();

  return this;
};

/**
 * Completely remove and shutdown the given container id.
 *
 * @param {String} id The container id.
 * @api public
 */
Fortress.prototype.kill = function kill(id) {
  var container = this.get(id);
  if (!container) return this;

  container.destroy();
  delete this.containers[id];

  return this;
};

/**
 * Start streaming logging information and cached logs.
 *
 * @param {String} id
 * @api public
 */
Fortress.prototype.attach = function attach(id) {
  return this;
};

/**
 * Destroy all active containers and clean up all references. We expect no more
 * further calls to this Fortress instance.
 *
 * @api public
 */
Fortress.prototype.destroy = function destroy() {
  for (var id in this.containers) {
    this.kill(id);
  }

  this.mount.parentNode.removeChild(this.mount);
  this.global = this.mount = this.containers = null;
};

//
// Expose our Container and Image so it can be extended by third party.
//
Fortress.Container = Container;
Fortress.Image = Image;

//
// Expose the module.
//
module.exports = Fortress;
<commit_msg>[api] Add a Fortress#stringify<commit_after>'use strict';

var EventEmitter = require('eventemitter3')
  , Container = require('./container')
  , iframe = require('./iframe');

/**
 * Fortress: Container and Image management for front-end code.
 *
 * @constructor
 * @param {Object} options Fortress configuration
 * @api private
 */
function Fortress(options) {
  if (!(this instanceof Fortress)) return new Fortress(options);
  options = options || {};

  //
  // Create a small dedicated container that houses all our iframes. This might
  // add an extra DOM node to the page in addition to each iframe but it will
  // ultimately result in a cleaner DOM as everything is nicely tucked away.
  //
  var scripts = document.getElementsByTagName('script')
    , append = scripts[scripts.length - 1] || document.body
    , div = document.createElement('div');

  append.parentNode.insertBefore(div, append);

  this.global = (function () { return this; })() || window;
  this.containers = {};
  this.mount = div;

  scripts = null;

  EventEmitter.call(this);
}

Fortress.prototype = new EventEmitter();

/**
 * Detect HTMLfile support.
 *
 * @type {Boolean}
 * @api private
 */
Fortress.prototype.htmlfile = false;

try { Fortress.prototype.htmlfile = !!new ActiveXObject('htmlfile'); }
catch (e) {}

/**
 * Detect the current globals that are loaded in to this page. This way we can
 * see if we are leaking data.
 *
 * @param {Array} old Optional array with previous or known leaks.
 * @returns {Array} Names of the leaked globals.
 * @api private
 */
Fortress.prototype.globals = function globals(old) {
  var i = iframe(this.mount, Date.now())
    , global = this.global;

  this.mount.removeChild(i.frame);

  //
  // Detect the globals and return them.
  //
  return Object.keys(global).filter(function filter(key) {
    var introduced = !(key in i.window);

    //
    // We've been given an array, so we should use that as the source of previous
    // and acknowledged leaks and only return an array that contains newly
    // introduced leaks.
    //
    if (introduced && old && old.length) {
      return ~old.indexOf(key)
      ? false
      : true;
    }

    return introduced;
  });
};

/**
 * List all active containers.
 *
 * @returns {Array} Active containers.
 * @api public
 */
Fortress.prototype.all = function all() {
  var everything = [];

  for (var id in this.containers) {
    everything.push(this.containers[id]);
  }

  return everything;
};

/**
 * Generate an unique, unknown id that we can use for our container storage.
 *
 * @returns {String}
 * @api private
 */
Fortress.prototype.id = function id() {
  for (var i = 0, generated = []; i < 4; i++) {
    generated.push(Math.random().toString(36).substring(2));
  }

  generated = 'fortress_'+ generated.join('_');

  //
  // Ensure that we didn't generate a pre-existing id, if we did, generate
  // another id.
  //
  if (generated in this.containers) return this.id();
  return generated;
};

/**
 * Create a new container.
 *
 * @param {String} code
 * @param {Object} options Options for the container
 * @returns {Container}
 * @api public
 */
Fortress.prototype.create = function create(code, options) {
  var container = new Container(this.mount, this.id(), code, options);
  this.containers[container.id] = container;

  return container;
};

/**
 * Get a container based on it's unique id.
 *
 * @param {String} id The container id.
 * @returns {Container}
 * @api public
 */
Fortress.prototype.get = function get(id) {
  return this.containers[id];
};

/**
 * Inspect a running Container in order to get more detailed information about
 * the process. In recent browsers we can access:
 *
 * - console.memory(), performance.memory
 *
 * @param {String} id The container id.
 * @api public
 */
Fortress.prototype.inspect = function inspect(id) {
  return this;
};

/**
 * Start the container with the given id.
 *
 * @param {String} id The container id.
 * @api public
 */
Fortress.prototype.start = function start(id) {
  var container = this.get(id);
  if (!container) return this;

  container.start();
  return this;
};

/**
 * Stop a running container, this does not fully destroy the container. It
 * merely stops it from running. Stopping an container will cause the container
 * to start from the beginning again once it's started. This is not a pause
 * function.
 *
 * @param {String} id The container id.
 * @api public
 */
Fortress.prototype.stop = function stop(id) {
  var container = this.get(id);
  if (!container) return this;

  container.stop();
  return this;
};

/**
 * Restart a container. Basically, just a start and stop.
 *
 * @param {String} id The container id.
 * @api public
 */
Fortress.prototype.restart = function restart(id) {
  var container = this.get(id);
  if (!container) return this;

  container.stop().start();

  return this;
};

/**
 * Completely remove and shutdown the given container id.
 *
 * @param {String} id The container id.
 * @api public
 */
Fortress.prototype.kill = function kill(id) {
  var container = this.get(id);
  if (!container) return this;

  container.destroy();
  delete this.containers[id];

  return this;
};

/**
 * Start streaming logging information and cached logs.
 *
 * @param {String} id
 * @api public
 */
Fortress.prototype.attach = function attach(id) {
  return this;
};

/**
 * Destroy all active containers and clean up all references. We expect no more
 * further calls to this Fortress instance.
 *
 * @api public
 */
Fortress.prototype.destroy = function destroy() {
  for (var id in this.containers) {
    this.kill(id);
  }

  this.mount.parentNode.removeChild(this.mount);
  this.global = this.mount = this.containers = null;
};

/**
 * Prepare a file or function to be loaded in to a Fortress based Container.
 * When the transfer boolean is set we assume that you want to load pass the
 * result of to a function or assign it a variable from the server to the client
 * side:
 *
 * ```
 * <script>
 * var code = <%- Fortress.stringify(code, true) %>
 * </script>
 * ```
 *
 * @param {String|Function} code The code that needs to be transformed.
 * @param {Boolean} transfer Prepare the code for transfer.
 * @returns {String}
 * @api public
 */
Fortress.stringify = function stringify(code, transfer) {
  if ('function' === typeof code) {
    //
    // We've been given a pure function, so we need to wrap it a little bit
    // after we've done a `toString` for the source retrieval so the function
    // will automatically execute when it's activated.
    //
    code = '('+ code.toString() +'())';
  } else {
    //
    // We've been given a string, so we're going to assume that it's path to file
    // that should be included instead.
    //
    code = require('fs').readFileSync(code, 'utf-8');
  }

  return transfer ? JSON.stringify(code) : code;
};

//
// Expose our Container and Image so it can be extended by third party.
//
Fortress.Container = Container;
Fortress.Image = Image;

//
// Expose the module.
//
module.exports = Fortress;
<|endoftext|>


<commit_before>var posix = require("posix");
var sys = require('sys');
var nerve = require('./../deps/nerve/nerve');
var pls = require('./genpls');
var redis = require('./../deps/redis/redis');
var utils = require('./utils');

function listSongs(req, res) {
    var r = new redis.Client();
    var resp = "";
    r.connect( function() {
        r.keys('song:*').addCallback( function(songlist) {
            _.each(songlist, function( songkey, i ) {
                r.get(songkey).addCallback( function( songdata ) {
                    utils.render('info', JSON.parse(songdata), function(out) {
                        resp += out;
                    });
                    if( i == songlist.length-1 ) {
                        res.respond( resp );
                        r.close();
                    }
                }).addErrback( function() {
                    res.respond("hi2");
                    res.finish();
                });
            });
            r.close();
        }).addErrback( function() {
            res.respond("hi3");
            res.finish();
        });
    });
}

// define an application using request matcher/handler pairs
var app = [

	[/^\/play\/(\w+)/, function(req, res, hash) {
        var r = new redis.Client();
        r.connect( function() {
            r.get('song:'+hash).addCallback( function(meta) {
                utils.render('info', JSON.parse(meta), _(res.respond).bind(res));
            });
        });
	}],

    [/^\/songs/, listSongs ],

	// this handler will respond to any request method
	[/a.*/, function(req, res) {
        var p = new pls.Playlist( "http://localhost/play/" );
        p.generate(1).addCallback( function( r ) {
            res.respond({
                headers: { "Content-Type" : "audio/x-scpls" }
                , content: r
            });
        });

	}]

];

// create and serve the application with various options
nerve.create(app, {
    port: 8000
}).serve();
<commit_msg>utils -> view<commit_after>var posix = require("posix");
var sys = require('sys');
var nerve = require('./../deps/nerve/nerve');
var pls = require('./genpls');
var redis = require('./../deps/redis/redis');
var view = require('./view');

function listSongs(req, res) {
    var r = new redis.Client();
    var resp = "";
    r.connect( function() {
        r.keys('song:*').addCallback( function(songlist) {
            _.each(songlist, function( songkey, i ) {
                r.get(songkey).addCallback( function( songdata ) {
                    view.render('info', JSON.parse(songdata), function(out) {
                        resp += out;
                    });
                    if( i == songlist.length-1 ) {
                        res.respond( resp );
                        r.close();
                    }
                }).addErrback( function() {
                    res.respond("hi2");
                    res.finish();
                });
            });
            r.close();
        }).addErrback( function() {
            res.respond("hi3");
            res.finish();
        });
    });
}

// define an application using request matcher/handler pairs
var app = [

	[/^\/play\/(\w+)/, function(req, res, hash) {
        var r = new redis.Client();
        r.connect( function() {
            r.get('song:'+hash).addCallback( function(meta) {
                utils.render('info', JSON.parse(meta), _(res.respond).bind(res));
            });
        });
	}],

    [/^\/songs/, listSongs ],

	// this handler will respond to any request method
	[/a.*/, function(req, res) {
        var p = new pls.Playlist( "http://localhost/play/" );
        p.generate(1).addCallback( function( r ) {
            res.respond({
                headers: { "Content-Type" : "audio/x-scpls" }
                , content: r
            });
        });

	}]

];

// create and serve the application with various options
nerve.create(app, {
    port: 8000
}).serve();
<|endoftext|>


<commit_before>#!/usr/bin/env node

var Generator = require('./lib/generator');
var utils = require('./lib/utils');
var argv = require('optimist').argv;
var mkdirp = require('mkdirp');
var fs = require('fs');
var path = require('path');
var request = require('request');

if (!argv.schemadir) {
  throw new Error('Please specfiy an output directory to store the generated schema!');
}

if (!argv.file && !argv.url) {
  throw new Error('Please specify a local file (path) or a URL of a JSON document');
}

mkdirp.sync(argv.schemadir);

var logger = function(msg) {
  console.log("\n", msg);
};

var writeFile = function(data, file) {
  var writer = fs.createWriteStream(file);
  data = utils.isString(data) ? data : JSON.stringify(data);
  var buff = new Buffer(Buffer.byteLength(data));
  buff.write(data.toString('utf8'));
  writer.write(buff);
  writer.close();
  logger('Wrote schema: ' + file);
}

var setName = function(str) {
  var name = str.substr(str.lastIndexOf('/'), str.length);
  if (name.lastIndexOf('.') === -1) {
    name += '.json';
  }

  return name;
}

var process = function(data, filename) {
  var generator = new Generator();
  var schema = generator.generate(data);
  var filepath = path.resolve(path.normalize(argv.schemadir + '/' + filename));
  writeFile(schema, filepath);
}

if (argv.file) {
  var data = '';
  reader = fs.createReadStream(argv.file);
  reader.on('data', function(chunks) {
    data += chunks;
  }).on('end', function() {
    var filename = setName(argv.file);
    process(JSON.parse(data.toString('utf8')), filename);
  }).on('error', function(e) {
    throw e;
  });
} else {
  if (argv.jsondir) {
    mkdirp.sync(argv.jsondir);
  }

  logger('Fetching URL resource: ' + argv.url);

  request(argv.url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      body = (utils.isString(body)) ? JSON.parse(body) : body;
      var filename = setName(argv.url);
      process(body, filename);
      if (argv.jsondir) {
        writeFile(body, argv.jsondir + '/' + filename);
      }
    } else {
      logger('There was an error loading the requested resource');
      logger('>>> ' + argv.url);
      if (error) {
        logger(e.toString('utf8'));
      }
    }
  })
}

<commit_msg>Added source documentation<commit_after>#!/usr/bin/env node

var Generator = require('./lib/generator');
var utils = require('./lib/utils');
var argv = require('optimist').argv;
var mkdirp = require('mkdirp');
var fs = require('fs');
var path = require('path');
var request = require('request');

if (!argv.schemadir) {
  throw new Error('Please specfiy an output directory to store the generated schema!');
}

if (!argv.file && !argv.url) {
  throw new Error('Please specify a local file (path) or a URL of a JSON document');
}

mkdirp.sync(argv.schemadir);

var logger = function(msg) {
  console.log("\n", msg);
};

/**
Fetches a remote JSON document and generate
the schema based on the contents of the remote
resource. If an output directory is specified,
the document will be saved locally.

@param {String} url The location of the remote
  resource
@return void
*/
var fetchResource = function(url) {
  logger('Fetching URL resource: ' + url);

  request(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      body = (utils.isString(body)) ? JSON.parse(body) : body;
      var filename = getName(url);
      process(body, filename);
      if (argv.jsondir) {
        writeFile(body, argv.jsondir + '/' + filename);
      }
    } else {
      logger('There was an error loading the requested resource');
      logger('>>> ' + url);

      if (error) {
        logger(e.toString('utf8'));
      }
    }
  });
};

/**
Reads the specified JSON file from the
filesystem which is used to generate
the schema.

@param {String} filepath Path to JSON
  document to load.
@return void
*/
var readFile = function(filepath) {
  var data = '';
  reader = fs.createReadStream(filepath);
  reader.on('data', function(chunks) {
    data += chunks;
  }).on('end', function() {
    var filename = getName(filepath);
    process(JSON.parse(data.toString('utf8')), filename);
  }).on('error', function(e) {
    throw e;
  });
}

/**
Writes the given data to the specified
file location.

@param {String} data The data to write to the FS
@param {String} file The file to write the data to
@return void
*/
var writeFile = function(data, file) {
  var writer = fs.createWriteStream(file);
  data = utils.isString(data) ? data : JSON.stringify(data);
  var buff = new Buffer(Buffer.byteLength(data));
  buff.write(data.toString('utf8'));
  writer.write(buff);
  writer.close();
  logger('Wrote schema: ' + file);
};

/**
Get the name of the JSON resource so the schema
matches the source. The .json extension is added
if it's missing from the filename.

@param {String} str File name
@return {String} The name of the file only.
*/
var getName = function(str) {
  var name = str.substr(str.lastIndexOf('/'), str.length);
  if (name.lastIndexOf('.') === -1) {
    name += '.json';
  }

  return name;
}

var process = function(data, filename) {
  var generator = new Generator();
  var schema = generator.generate(data);
  var filepath = path.resolve(path.normalize(argv.schemadir + '/' + filename));
  writeFile(schema, filepath);
}

if (argv.file) {
  readFile(argv.file);
} else {
  if (argv.jsondir) {
    mkdirp.sync(argv.jsondir);
  }

  fetchResource(argv.url);
}

<|endoftext|>


<commit_before>/**
 * ANGLULAR APP
 **/

    /**
     * web_service_url for whole app
     */

    //var web_service_url = 'http://www.omicsdi.org/ws/';
    var web_service_url = 'http://localhost:9091/';
    var proteomics_list = "pride,peptideatlas,peptide_atlas,massive,PRIDE,PeptideAtlas,MassIVE, Massive, gpmdb, GPMDB, GPMdb";
    var metabolomics_list = "MetaboLights Dataset, MetaboLights,metabolights,metabolights_dataset,MetabolomicsWorkbench, Metabolomics Workbench, metabolomics_workbench, metabolome_express, MetabolomeExpress, Metabolomics Workbench, GNPS, gnps";
    var transcriptomics_list = "ArrayExpress, arrayexpress-repository, ExpressionAtlas, expression-atlas, atlas-experiments, Expression Atlas Experiments, atlas-experiments";
    var genomics_list = "ega,EGA";
    var repositories = {
        "pride": "PRIDE",
        "PRIDE": "PRIDE",
        "peptideatlas": "PeptideAtlas",
        "peptide_atlas": "PeptideAtlas",
        "PeptideAtlas": "PeptideAtlas",
        "massive": "MassIVE",
        "MassIVE": "MassIVE",
        "Massive": "MassIVE",
        "metabolights": "MetaboLights",
        "metabolights_dataset": "MetaboLights",
        "MetaboLights": "MetaboLights",
        "metabolome_workbench": "MetabolomicsWorkbench",
        "metabolomics_workbench": "MetabolomicsWorkbench",
        "Metabolomics Workbench": "MetabolomicsWorkbench",
        "MetabolomicsWorkbench": "MetabolomicsWorkbench",
        "ega": "EGA",
        "EGA": "EGA",
        "GPMDB": "GPMDB",
        "gpmdb": "GPMDB",
        "GNPS":"GNPS",
        "metabolome_express": "MetabolomeExpress MetaPhenDB",
        "MetabolomeExpress MetaPhenDB": "MetabolomeExpress MetaPhenDB",
        "MetabolomeExpress":"MetabolomeExpress MetaPhenDB",
        "ArrayExpress":"ArrayExpress",
        "arrayexpress":"ArrayExpress",
        "arrayexpress-repository":"ArrayExpress",
        "expression-atlas":"ExpressionAtlas",
        "ExpressionAtlas":"ExpressionAtlas",
        "atlas-experiments":"ExpressionAtlas",
        "Expression Atlas Experiments": "ExpressionAtlas"

    };
    var database_urls = {
        "PRIDE": "http://www.ebi.ac.uk/pride/archive/",
        "MetaboLights": "http://www.ebi.ac.uk/metabolights/",
        "MetabolomicsWorkbench": "http://www.metabolomicsworkbench.org/",
        "PeptideAtlas": "http://www.peptideatlas.org/",
        "MassIVE": "https://massive.ucsd.edu/ProteoSAFe/datasets.jsp",
        "GPMDB":"http://gpmdb.thegpm.org/",
        "GNPS":"http://gnps.ucsd.edu/ProteoSAFe/static/gnps-splash.jsp",
        "EGA":"https://www.ebi.ac.uk/ega/",
        "MetabolomeExpress":"https://www.metabolome-express.org/",
        "ArrayExpress":"https://www.ebi.ac.uk/arrayexpress/",
        "ExpressionAtlas":"http://www.ebi.ac.uk/gxa/home"
    }

/**
 * Make it possible to include underscore as a dependency.
 */
var underscore = angular.module('underscore', []);
underscore.factory('_', function () {
    return window._;
});

var ddiApp = angular.module('ddiApp',['underscore','ngRoute','ngAnimate', 'autocomplete', 'ngCookies', 'ngProgress','ui.bootstrap', 'slick']);

// $.getJSON('http://api.metabolomexchange.org/providers', function(data) {
//     for (var i in data) {
//         console.log(data[i].name);
//     }
// });

/**
 * Turn on html5mode only in modern browsers because
 * in the older ones html5mode rewrites urls with Hangbangs
 * which break normal pages.
 * With html5mode off IE lt 10 will be able to navigate the site
 * but won't be able to open deep links to Angular pages
 * (for example, a link to a search result won't load in IE 9).
 */
// angular.module('ddiApp').config(['$locationProvider', function ($locationProvider) {
//       $locationProvider.html5Mode(false);
// }]);

/**
 * ANGLULAR CONFIG
 **/
ddiApp.config(function($routeProvider) {
    $routeProvider.
    when('/about', { templateUrl: 'app/views/about.html', controller: 'MainContentCtrl' }).
    when('/api', { templateUrl: 'app/views/api.html', controller: 'MainContentCtrl' }).
    when('/databases', { templateUrl: 'app/views/databases.html', controller: 'MainContentCtrl' }).
    when('/help', {  templateUrl: 'app/views/help.html', controller: 'MainContentCtrl' }).
    when('/', {  templateUrl: 'app/views/home.html', controller: 'MainContentCtrl' }).
    when('/home', { templateUrl: 'app/views/home.html', controller: 'MainContentCtrl' }).
//    when('/search', { templateUrl: 'app/views/search.html', controller: 'MainContentCtrl' }).
    when('/search?:searchstring', { templateUrl: 'app/views/browse.html', controller: 'MainContentCtrl' }).
//    when('/search/:search', { templateUrl: 'app/views/search.html', controller: 'MainContentCtrl' }).
    when('/dataset/:domain/:acc', { templateUrl: 'app/views/dataset.html', controller: 'MainContentCtrl' }).
//    when('/check', {templateUrl: 'app/views/check.html', controller: 'MainContentCtrl'});
    when('/check', {templateUrl: 'app/views/check.html', controller: 'MainContentCtrl'}).
    otherwise({  templateUrl: 'app/views/home.html', controller: 'MainContentCtrl' });

});
/* ----------------------------*/

/**
 * ANGLULAR CONTROLLERS
 **/
//ddiApp.controller('MainContentCtrl', ['$scope', '$routeParams', '$location', '$anchorScroll',
//    function ($scope, $routeParams, $location, $anchorScroll){
//        if ($location.path() === '/about'){
//            $scope.show_top_search = 'true'
//        }else{
//            $scope.show_top_search = 'false'
//
//        }
//
//        // set focus to search
////        if (document.getElementById("search")) { document.getElementById("search").focus(); }
//    }
//]);

/*
ddiApp.factory('ddiAppApi', function($http) {

    var useCache = true;

    return {
        getDatasets: function() { return $http.get('http://api.metabolomexchange.org/datasets', { cache: useCache }); },
        getDataset: function(provider, accession) { return $http.get('http://api.metabolomexchange.org/provider/' + provider + '/' + accession, { cache: useCache }); },
        getProviders: function() { return $http.get('http://api.metabolomexchange.org/providers', { cache: useCache }); },
        getProvider: function(provider) { return $http.get('http://api.metabolomexchange.org/provider/' + provider, { cache: useCache }); },
        findDatasets: function(search) {
            var andMatch = search.replace(new RegExp(' ', 'g'), '&');
            var searchUrl = 'http://api.metabolomexchange.org/datasets/' + andMatch;
            return $http.get(searchUrl, { cache: useCache });
        }
    };
});
*/
/* ----------------------------*/
<commit_msg>some changes<commit_after>/**
 * ANGLULAR APP
 **/

    /**
     * web_service_url for whole app
     */

    var web_service_url = 'http://www.omicsdi.org/ws/';
    var proteomics_list = "pride,peptideatlas,peptide_atlas,massive,PRIDE,PeptideAtlas,MassIVE, Massive, gpmdb, GPMDB, GPMdb";
    var metabolomics_list = "MetaboLights Dataset, MetaboLights,metabolights,metabolights_dataset,MetabolomicsWorkbench, Metabolomics Workbench, metabolomics_workbench, metabolome_express, MetabolomeExpress, Metabolomics Workbench, GNPS, gnps";
    var transcriptomics_list = "ArrayExpress, arrayexpress-repository, ExpressionAtlas, expression-atlas, atlas-experiments, Expression Atlas Experiments, atlas-experiments";
    var genomics_list = "ega,EGA";
    var repositories = {
        "pride": "PRIDE",
        "PRIDE": "PRIDE",
        "peptideatlas": "PeptideAtlas",
        "peptide_atlas": "PeptideAtlas",
        "PeptideAtlas": "PeptideAtlas",
        "massive": "MassIVE",
        "MassIVE": "MassIVE",
        "Massive": "MassIVE",
        "metabolights": "MetaboLights",
        "metabolights_dataset": "MetaboLights",
        "MetaboLights": "MetaboLights",
        "metabolome_workbench": "MetabolomicsWorkbench",
        "metabolomics_workbench": "MetabolomicsWorkbench",
        "Metabolomics Workbench": "MetabolomicsWorkbench",
        "MetabolomicsWorkbench": "MetabolomicsWorkbench",
        "ega": "EGA",
        "EGA": "EGA",
        "GPMDB": "GPMDB",
        "gpmdb": "GPMDB",
        "GNPS":"GNPS",
        "metabolome_express": "MetabolomeExpress MetaPhenDB",
        "MetabolomeExpress MetaPhenDB": "MetabolomeExpress MetaPhenDB",
        "MetabolomeExpress":"MetabolomeExpress MetaPhenDB",
        "ArrayExpress":"ArrayExpress",
        "arrayexpress":"ArrayExpress",
        "arrayexpress-repository":"ArrayExpress",
        "expression-atlas":"ExpressionAtlas",
        "ExpressionAtlas":"ExpressionAtlas",
        "atlas-experiments":"ExpressionAtlas",
        "Expression Atlas Experiments": "ExpressionAtlas"

    };
    var database_urls = {
        "PRIDE": "http://www.ebi.ac.uk/pride/archive/",
        "MetaboLights": "http://www.ebi.ac.uk/metabolights/",
        "MetabolomicsWorkbench": "http://www.metabolomicsworkbench.org/",
        "PeptideAtlas": "http://www.peptideatlas.org/",
        "MassIVE": "https://massive.ucsd.edu/ProteoSAFe/datasets.jsp",
        "GPMDB":"http://gpmdb.thegpm.org/",
        "GNPS":"http://gnps.ucsd.edu/ProteoSAFe/static/gnps-splash.jsp",
        "EGA":"https://www.ebi.ac.uk/ega/",
        "MetabolomeExpress":"https://www.metabolome-express.org/",
        "ArrayExpress":"https://www.ebi.ac.uk/arrayexpress/",
        "ExpressionAtlas":"http://www.ebi.ac.uk/gxa/home"
    }

/**
 * Make it possible to include underscore as a dependency.
 */
var underscore = angular.module('underscore', []);
underscore.factory('_', function () {
    return window._;
});

var ddiApp = angular.module('ddiApp',['underscore','ngRoute','ngAnimate', 'autocomplete', 'ngCookies', 'ngProgress','ui.bootstrap', 'slick']);

// $.getJSON('http://api.metabolomexchange.org/providers', function(data) {
//     for (var i in data) {
//         console.log(data[i].name);
//     }
// });

/**
 * Turn on html5mode only in modern browsers because
 * in the older ones html5mode rewrites urls with Hangbangs
 * which break normal pages.
 * With html5mode off IE lt 10 will be able to navigate the site
 * but won't be able to open deep links to Angular pages
 * (for example, a link to a search result won't load in IE 9).
 */
angular.module('ddiApp').config(['$locationProvider', function ($locationProvider) {
      $locationProvider.html5Mode(true);
}]);

/**
 * ANGLULAR CONFIG
 **/
ddiApp.config(function($routeProvider) {
    $routeProvider.
    when('/about', { templateUrl: 'app/views/about.html', controller: 'MainContentCtrl' }).
    when('/api', { templateUrl: 'app/views/api.html', controller: 'MainContentCtrl' }).
    when('/databases', { templateUrl: 'app/views/databases.html', controller: 'MainContentCtrl' }).
    when('/help', {  templateUrl: 'app/views/help.html', controller: 'MainContentCtrl' }).
    when('/', {  templateUrl: 'app/views/home.html', controller: 'MainContentCtrl' }).
    when('/home', { templateUrl: 'app/views/home.html', controller: 'MainContentCtrl' }).
//    when('/search', { templateUrl: 'app/views/search.html', controller: 'MainContentCtrl' }).
    when('/search?:searchstring', { templateUrl: 'app/views/browse.html', controller: 'MainContentCtrl' }).
//    when('/search/:search', { templateUrl: 'app/views/search.html', controller: 'MainContentCtrl' }).
    when('/dataset/:domain/:acc', { templateUrl: 'app/views/dataset.html', controller: 'MainContentCtrl' }).
//    when('/check', {templateUrl: 'app/views/check.html', controller: 'MainContentCtrl'});
    when('/check', {templateUrl: 'app/views/check.html', controller: 'MainContentCtrl'}).
    otherwise({  templateUrl: 'app/views/home.html', controller: 'MainContentCtrl' });

});
/* ----------------------------*/

/**
 * ANGLULAR CONTROLLERS
 **/
//ddiApp.controller('MainContentCtrl', ['$scope', '$routeParams', '$location', '$anchorScroll',
//    function ($scope, $routeParams, $location, $anchorScroll){
//        if ($location.path() === '/about'){
//            $scope.show_top_search = 'true'
//        }else{
//            $scope.show_top_search = 'false'
//
//        }
//
//        // set focus to search
////        if (document.getElementById("search")) { document.getElementById("search").focus(); }
//    }
//]);

/*
ddiApp.factory('ddiAppApi', function($http) {

    var useCache = true;

    return {
        getDatasets: function() { return $http.get('http://api.metabolomexchange.org/datasets', { cache: useCache }); },
        getDataset: function(provider, accession) { return $http.get('http://api.metabolomexchange.org/provider/' + provider + '/' + accession, { cache: useCache }); },
        getProviders: function() { return $http.get('http://api.metabolomexchange.org/providers', { cache: useCache }); },
        getProvider: function(provider) { return $http.get('http://api.metabolomexchange.org/provider/' + provider, { cache: useCache }); },
        findDatasets: function(search) {
            var andMatch = search.replace(new RegExp(' ', 'g'), '&');
            var searchUrl = 'http://api.metabolomexchange.org/datasets/' + andMatch;
            return $http.get(searchUrl, { cache: useCache });
        }
    };
});
*/
/* ----------------------------*/
<|endoftext|>


<commit_before>$(document).ready(function() {
    var content = $('#content');

    function eat(response) {
            var trips = $("#trip");
            trips.empty();
            if (response.length == 0)
                trips.html("

No trips.

");
            response.forEach(function (day) {
                var daydate = day["date"];
                var daydata = day["data"];
                var daytable = buildday(daydata, daydate);
                trips.append(daytable);
            });

        $(".activity").not(".STILL").css("cursor", "pointer");
        $(".activity").not(".STILL").on("click", function(event) {
            var td = event.currentTarget;
            selectedLegId = td.getAttribute("legid");

            // Set mode on dialog
            var mode = td.className.split(" ")[1];
            $("#"+mode).prop("checked", true);
            $("#mode").buttonset("refresh");

            // Set line on dialog
            var parts = td.firstChild.textContent.split(" ");
            if (parts.length > 1)
                $("#line").val(parts[1]);

            dialog.dialog("open");
        });

	content.css('opacity', '');
    }

    function buildday(data, date) {
        var trip = $(document.createElement("table"));

        var daycell = document.createElement("td");
        daycell.appendChild(document.createTextNode(date));
        var p = daycell.appendChild(document.createElement("p"));
        var weekday = (new Date(Date.parse(date))).toDateString().slice(0, 3);
        p.appendChild(document.createTextNode(weekday));
        daycell.setAttribute("rowspan", 3);
        daycell.setAttribute("class", "daycell");

        $.each(data, function (i, row) {
                var classname = row[0];
                var cells = row[1];
                var tr = $(document.createElement("tr"));
                trip.append(tr);
                if (daycell) {
                    tr.append(daycell)
                    daycell = null;
                }
                cells.forEach(function (col) {
                    var td = $(document.createElement("td"));
                    td.addClass(classname);
                    tr.append(td);
                    td.attr("colspan", col[1]);
                    if (col[0] === null) {
                        td.addClass("gap");
                    } else if (classname == "time") {
                        td.text(col[0][0]);
                        switch (col[0][1]) { // align
                        case "start": td.addClass("left"); break;
                        case "both": td.addClass("left both"); break;
                        case "end": td.addClass("right"); break;
                        }
                    } else if (classname == "activity") {
                        var activity = col[0][0];
                        td.text(activity);
                        var mode = activity.split(" ")[0];
                        td.addClass(mode);
                        var glyph = null;
                        switch (mode) {
                        case 'ON_BICYCLE': glyph = "directions_bike"; break;
                        case 'WALKING':
                        case 'ON_FOOT':    glyph = "directions_walk"; break;
                        case 'RUNNING':    glyph = "directions_run"; break;
                        case 'IN_VEHICLE': glyph = "directions_car"; break;
                        case "TRAIN":      glyph = "train"; break;
                        case 'SUBWAY':     glyph = "subway"; break;
                        case 'TRAM':       glyph = "tram"; break;
                        case 'FERRY':      glyph = "directions_boat"; break;
                        case 'BUS':        glyph = "directions_bus"; break;
                        case 'TILTING':    glyph = "screen_rotation"; break;
                        case 'STILL':      glyph = "\xa0"; break;
                        case 'UNKNOWN':    glyph = "?"; break;
//                      default:           glyph = "!"; break;
                        }

                        var icon = $(document.createElement("div"));
                        var matic = $(document.createElement("span"));
                        matic.addClass("material-icons");
                        matic.text(glyph);
                        icon.append(matic);
                        td.append(icon);

                        td.append(col[0][1]); // duration

                        td.attr("legid", col[0][2]);
                    } else if (classname == "place") {
                        var label = col[0];
                        if (label === false) {
                            var div = $(document.createElement("div"));
                            td.append(div);
                            $(td).addClass("move");
                            return; // uh
                        }

                        // Disallow slash alone on a line, bind to shorter word
                        var names = label.split(" / ");
                        var text = names[0];
                        if (names.length > 1) {
                            var lof = names[0].split(" ").slice(-1)[0];
                            var fol = names[1].split(" ")[0];
                            var sep = lof.length < fol.length
                                ? "\xa0/ " : " /\xa0";
                            // Join tail just in case there were more slashes,
                            // js has maxsplit would crop the tail
                            text += sep + names.slice(1).join(" / ");
                        }
                        $(td).text(text);
                    }
                });
        });
        return trip;
    }

    var selectedLegId;

    function setLegMode() {
        var checked = $.grep(
            $("#mode").get(0).children,
            function (x) {return (x.checked)})[0];
        var mode = $(checked).val();

        if (mode == "RESET")
            mode = null;

        var data = {
            id: selectedLegId, activity: mode, line_name: $("#line").val()};
        $.ajax({
            type: "POST",
            url: 'setlegmode',
            data: JSON.stringify(data),
            contentType: "application/json",
            success: hashchange});
        dialog.dialog("close");
    }

    function radioChecked(buttonset) {
        var checked = $.grep(
            buttonset.children,
            function (x) {return (x.checked)})[0];
        var mode = $(checked).val();
        var masses = ["FERRY", "SUBWAY", "TRAIN", "TRAM", "BUS"];
        if (-1 == $.inArray(mode, masses)) {
            $("#line").hide(200);
            $("#line").prev().hide(200);
        } else {
            $("#line").show(200);
            $("#line").prev().show(200);
        }
    }

    var dialog = $("#dialog-form").dialog({
        autoOpen: false,
        height: 400,
        width: 400,
        modal: true,
        buttons: {
            "Submit": setLegMode,
            Cancel: function() { dialog.dialog("close") }
        },
        close: function() {
            form[0].reset();
        },
        open: function() {
            $("#mode").buttonset().change(function (event) {
                radioChecked(event.currentTarget);
            });
            radioChecked($("#mode").get(0));
        }
    });

    var form = dialog.find("form").on("submit", function(event) {
        event.preventDefault();
        setLegMode();
    })

    $("#mode").buttonset();

    function hashchange() {
        var hash = location.hash.split("#").splice(-1)[0];
        var dates = hash.split("/");
        var firstday = dates[0];
        var lastday = dates[1];

        var args = [];
        if (firstday)
            args.push("firstday=" + firstday);
        if (lastday)
            args.push("lastday=" + lastday);
        args = args.join("&");
        var qs = args ? "?" + args : "";
        $("#csvlink").attr("href", "trips_csv" + qs);

	content.css('opacity', 0.1);
	$.getJSON("trips_json" + qs, eat);

    }

    $(window).on("hashchange", hashchange);
    hashchange();
});
<commit_msg>Add link from trips to energymap for single day<commit_after>$(document).ready(function() {
    var content = $('#content');

    function eat(response) {
            var trips = $("#trip");
            trips.empty();
            if (response.length == 0)
                trips.html("

No trips.

");
            response.forEach(function (day) {
                var daydate = day["date"];
                var daydata = day["data"];
                var daytable = buildday(daydata, daydate);
                trips.append(daytable);
            });

        $(".activity").not(".STILL").css("cursor", "pointer");
        $(".activity").not(".STILL").on("click", function(event) {
            var td = event.currentTarget;
            selectedLegId = td.getAttribute("legid");

            // Set mode on dialog
            var mode = td.className.split(" ")[1];
            $("#"+mode).prop("checked", true);
            $("#mode").buttonset("refresh");

            // Set line on dialog
            var parts = td.firstChild.textContent.split(" ");
            if (parts.length > 1)
                $("#line").val(parts[1]);

            dialog.dialog("open");
        });

	content.css('opacity', '');
    }

    function buildday(data, date) {
        var trip = $(document.createElement("table"));

        var daycell = document.createElement("td");
        var datelink = document.createElement("a");
        datelink.textContent = date;
        datelink.setAttribute("href", "/energymap#" + date);
        daycell.appendChild(datelink);
        var p = daycell.appendChild(document.createElement("p"));
        var weekday = (new Date(Date.parse(date))).toDateString().slice(0, 3);
        p.appendChild(document.createTextNode(weekday));
        daycell.setAttribute("rowspan", 3);
        daycell.setAttribute("class", "daycell");

        $.each(data, function (i, row) {
                var classname = row[0];
                var cells = row[1];
                var tr = $(document.createElement("tr"));
                trip.append(tr);
                if (daycell) {
                    tr.append(daycell)
                    daycell = null;
                }
                cells.forEach(function (col) {
                    var td = $(document.createElement("td"));
                    td.addClass(classname);
                    tr.append(td);
                    td.attr("colspan", col[1]);
                    if (col[0] === null) {
                        td.addClass("gap");
                    } else if (classname == "time") {
                        td.text(col[0][0]);
                        switch (col[0][1]) { // align
                        case "start": td.addClass("left"); break;
                        case "both": td.addClass("left both"); break;
                        case "end": td.addClass("right"); break;
                        }
                    } else if (classname == "activity") {
                        var activity = col[0][0];
                        td.text(activity);
                        var mode = activity.split(" ")[0];
                        td.addClass(mode);
                        var glyph = null;
                        switch (mode) {
                        case 'ON_BICYCLE': glyph = "directions_bike"; break;
                        case 'WALKING':
                        case 'ON_FOOT':    glyph = "directions_walk"; break;
                        case 'RUNNING':    glyph = "directions_run"; break;
                        case 'IN_VEHICLE': glyph = "directions_car"; break;
                        case "TRAIN":      glyph = "train"; break;
                        case 'SUBWAY':     glyph = "subway"; break;
                        case 'TRAM':       glyph = "tram"; break;
                        case 'FERRY':      glyph = "directions_boat"; break;
                        case 'BUS':        glyph = "directions_bus"; break;
                        case 'TILTING':    glyph = "screen_rotation"; break;
                        case 'STILL':      glyph = "\xa0"; break;
                        case 'UNKNOWN':    glyph = "?"; break;
//                      default:           glyph = "!"; break;
                        }

                        var icon = $(document.createElement("div"));
                        var matic = $(document.createElement("span"));
                        matic.addClass("material-icons");
                        matic.text(glyph);
                        icon.append(matic);
                        td.append(icon);

                        td.append(col[0][1]); // duration

                        td.attr("legid", col[0][2]);
                    } else if (classname == "place") {
                        var label = col[0];
                        if (label === false) {
                            var div = $(document.createElement("div"));
                            td.append(div);
                            $(td).addClass("move");
                            return; // uh
                        }

                        // Disallow slash alone on a line, bind to shorter word
                        var names = label.split(" / ");
                        var text = names[0];
                        if (names.length > 1) {
                            var lof = names[0].split(" ").slice(-1)[0];
                            var fol = names[1].split(" ")[0];
                            var sep = lof.length < fol.length
                                ? "\xa0/ " : " /\xa0";
                            // Join tail just in case there were more slashes,
                            // js has maxsplit would crop the tail
                            text += sep + names.slice(1).join(" / ");
                        }
                        $(td).text(text);
                    }
                });
        });
        return trip;
    }

    var selectedLegId;

    function setLegMode() {
        var checked = $.grep(
            $("#mode").get(0).children,
            function (x) {return (x.checked)})[0];
        var mode = $(checked).val();

        if (mode == "RESET")
            mode = null;

        var data = {
            id: selectedLegId, activity: mode, line_name: $("#line").val()};
        $.ajax({
            type: "POST",
            url: 'setlegmode',
            data: JSON.stringify(data),
            contentType: "application/json",
            success: hashchange});
        dialog.dialog("close");
    }

    function radioChecked(buttonset) {
        var checked = $.grep(
            buttonset.children,
            function (x) {return (x.checked)})[0];
        var mode = $(checked).val();
        var masses = ["FERRY", "SUBWAY", "TRAIN", "TRAM", "BUS"];
        if (-1 == $.inArray(mode, masses)) {
            $("#line").hide(200);
            $("#line").prev().hide(200);
        } else {
            $("#line").show(200);
            $("#line").prev().show(200);
        }
    }

    var dialog = $("#dialog-form").dialog({
        autoOpen: false,
        height: 400,
        width: 400,
        modal: true,
        buttons: {
            "Submit": setLegMode,
            Cancel: function() { dialog.dialog("close") }
        },
        close: function() {
            form[0].reset();
        },
        open: function() {
            $("#mode").buttonset().change(function (event) {
                radioChecked(event.currentTarget);
            });
            radioChecked($("#mode").get(0));
        }
    });

    var form = dialog.find("form").on("submit", function(event) {
        event.preventDefault();
        setLegMode();
    })

    $("#mode").buttonset();

    function hashchange() {
        var hash = location.hash.split("#").splice(-1)[0];
        var dates = hash.split("/");
        var firstday = dates[0];
        var lastday = dates[1];

        var args = [];
        if (firstday)
            args.push("firstday=" + firstday);
        if (lastday)
            args.push("lastday=" + lastday);
        args = args.join("&");
        var qs = args ? "?" + args : "";
        $("#csvlink").attr("href", "trips_csv" + qs);

	content.css('opacity', 0.1);
	$.getJSON("trips_json" + qs, eat);

    }

    $(window).on("hashchange", hashchange);
    hashchange();
});
<|endoftext|>


<commit_before>'use strict';

const angular = require('angular');
const ngRoute = require('angular-route');
const ngMessages = require('angular-messages');
const turnover = angular.module('turnover', ['ngRoute', 'ngMessages']);

turnover.config(['$routeProvider', function($routeProvider) {

    // Is there a way for this to be env-dependent?
    $routeProvider.when('/', {
         templateUrl : 'app/partials/home/home.html',
         controller : 'HomeController',
         controllerAs : 'homeCtrl'
    });

    $routeProvider.when('/results', {
         templateUrl : 'app/partials/results/results.html',
         controller : 'ResultsController',
         controllerAs : 'resultsCtrl'
    });

}]);

turnover.service('ResultsService', ['$location', require('./js/services/resultsService')]);
turnover.controller('HomeController', ['$http', '$location', 'ResultsService', require('./partials/home/homeController')]);
turnover.controller('ResultsController', ['$http', '$location', 'ResultsService', require('./partials/results/resultsController')]);<commit_msg>added advanced controller to the app.js<commit_after>'use strict';

const angular = require('angular');
const ngRoute = require('angular-route');
const ngMessages = require('angular-messages');
const turnover = angular.module('turnover', ['ngRoute', 'ngMessages']);

turnover.config(['$routeProvider', function($routeProvider) {

    // Is there a way for this to be env-dependent?
    $routeProvider.when('/', {
         templateUrl : 'app/partials/home/home.html',
         controller : 'HomeController',
         controllerAs : 'homeCtrl'
    });

    $routeProvider.when('/results', {
         templateUrl : 'app/partials/results/results.html',
         controller : 'ResultsController',
         controllerAs : 'resultsCtrl'
    });

    $routeProvider.when('/advanced', {
         templateUrl : 'app/partials/advanced/advanced.html',
         controller : 'AdvancedController',
         controllerAs : 'advancedCtrl'
    });

}]);

turnover.service('ResultsService', ['$location', require('./js/services/resultsService')]);
turnover.controller('HomeController', ['$http', '$location', 'ResultsService', require('./partials/home/homeController')]);
turnover.controller('ResultsController', ['$http', '$location', 'ResultsService', require('./partials/results/resultsController')]);
turnover.controller('AdvancedController', ['$http', '$location', 'ResultsService', require('./partials/advanced/advancedController')]);<|endoftext|>


<commit_before>/*************************************************
 *
 * Functions for file upload fields
 *
 ************************************************/
var FileUpload = {
	// Create a file upload field
	// Options can include:
	//		truncate: 	the maximum number of characters in the filename to be shown
	//		onUpload:	method to be called after a file is uploaded
	convertFileField: function(field_id, options) {
		var that = this;

		if( typeof(options) == 'undefined' ) {
			options = {};
		}

		var upload = $('#upload_button_' + field_id).fileupload({
			dataType: 'text', // type of the response
			replaceFileInput: false,
			url: baseUrl + '/file/upload',
			paramName: field_id,
			add: function(e, data) {
				oldFile = $('#' + field_id).val();
				if (oldFile != '' && oldFile != 'existing*' && oldFile != '*deleted*' ) {
					if (!confirm('The old file is deleted when uploading a new file. Do you want to continue?')) {
						return false;
					}
				}
				data.formData = {
					'field': field_id,
					'oldFile': oldFile
				};

				// Give feedback to the user
				var filename = data.files[0].name;
				$('#' + field_id + 'Example').html('Uploading ' + that.createFileHTML(filename, options.truncate));
				$('#' + field_id + 'Delete').hide();

				data.submit();
			},
			done: function (e, data) {
				var response = data.result;
				var filename = data.files[0].name;

				//If there is HTML in the response, just retrieve the text value.
				if(response.indexOf("<") != -1) {
					response = $(response).text().split("//<![CDATA[")[0];
				}
				if (response == "") {
					$('#' + field_id).val('');
					$('#' + field_id + 'Example').html('Error uploading ' + that.createFileHTML(filename, options.truncate) + '');
					$('#' + field_id + 'Delete').hide();
				} else {
					$('#' + field_id).val(response).change(); // explicitly trigger change event, as this is not called when changing programmatically
					$('#' + field_id + 'Example').html('Uploaded ' + that.createFileHTML(filename, options.truncate));
					$('#' + field_id + 'Delete').show();
				}

				// Call user specified onComplete method
				if( typeof(options.onUpload) != 'undefined' ) {
					options.onUpload(file, response);
				}
			}
		});

		// Reroute click from icon to (invisible) file input
		$('#upload_icon_' + field_id).on('click', function() {
			$('#upload_button_' + field_id).click();
		})

		// Enable delete button
		$( '#' + field_id + "Delete").on( "click", function() {
			if( confirm( 'Are you sure to delete this file?' ) ) {
				that.deleteFile( field_id );
			}
			return false;
		});

		return upload;
	},

	deleteFile: function(field_id) {
		$('#' + field_id).val('*deleted*');
		$('#' + field_id + 'Example').html('File deleted');
		$('#' + field_id + 'Delete').hide();
	},

	createFileHTML: function(filename, truncate) {
		// See whether the filename should be truncated to a certain number of characters
		var label = filename;
		if( typeof(truncate) != 'undefined' && filename.length > truncate ) {
			label = filename.substring(0, truncate) + "...";
		}

		return '' + label + '';
	}
};
<commit_msg>Fix typo (remaining from replacing file upload)<commit_after>/*************************************************
 *
 * Functions for file upload fields
 *
 ************************************************/
var FileUpload = {
	// Create a file upload field
	// Options can include:
	//		truncate: 	the maximum number of characters in the filename to be shown
	//		onUpload:	method to be called after a file is uploaded
	convertFileField: function(field_id, options) {
		var that = this;

		if( typeof(options) == 'undefined' ) {
			options = {};
		}

		var upload = $('#upload_button_' + field_id).fileupload({
			dataType: 'text', // type of the response
			replaceFileInput: false,
			url: baseUrl + '/file/upload',
			paramName: field_id,
			add: function(e, data) {
				oldFile = $('#' + field_id).val();
				if (oldFile != '' && oldFile != 'existing*' && oldFile != '*deleted*' ) {
					if (!confirm('The old file is deleted when uploading a new file. Do you want to continue?')) {
						return false;
					}
				}
				data.formData = {
					'field': field_id,
					'oldFile': oldFile
				};

				// Give feedback to the user
				var filename = data.files[0].name;
				$('#' + field_id + 'Example').html('Uploading ' + that.createFileHTML(filename, options.truncate));
				$('#' + field_id + 'Delete').hide();

				data.submit();
			},
			done: function (e, data) {
				var response = data.result;
				var filename = data.files[0].name;

				//If there is HTML in the response, just retrieve the text value.
				if(response.indexOf("<") != -1) {
					response = $(response).text().split("//<![CDATA[")[0];
				}
				if (response == "") {
					$('#' + field_id).val('');
					$('#' + field_id + 'Example').html('Error uploading ' + that.createFileHTML(filename, options.truncate) + '');
					$('#' + field_id + 'Delete').hide();
				} else {
					$('#' + field_id).val(response).change(); // explicitly trigger change event, as this is not called when changing programmatically
					$('#' + field_id + 'Example').html('Uploaded ' + that.createFileHTML(filename, options.truncate));
					$('#' + field_id + 'Delete').show();
				}

				// Call user specified onComplete method
				if( typeof(options.onUpload) != 'undefined' ) {
					options.onUpload(filename, response);
				}
			}
		});

		// Reroute click from icon to (invisible) file input
		$('#upload_icon_' + field_id).on('click', function() {
			$('#upload_button_' + field_id).click();
		})

		// Enable delete button
		$( '#' + field_id + "Delete").on( "click", function() {
			if( confirm( 'Are you sure to delete this file?' ) ) {
				that.deleteFile( field_id );
			}
			return false;
		});

		return upload;
	},

	deleteFile: function(field_id) {
		$('#' + field_id).val('*deleted*');
		$('#' + field_id + 'Example').html('File deleted');
		$('#' + field_id + 'Delete').hide();
	},

	createFileHTML: function(filename, truncate) {
		// See whether the filename should be truncated to a certain number of characters
		var label = filename;
		if( typeof(truncate) != 'undefined' && filename.length > truncate ) {
			label = filename.substring(0, truncate) + "...";
		}

		return '' + label + '';
	}
};
<|endoftext|>


<commit_before>var _ = require("underscore");
var Twit = require("twit");

var express = require("express");
var bodyParser = require("body-parser");
var errorHandler = require("errorhandler");

var config;
try {
  config = require("./config");
} catch(e) {
  console.log("Failed to find local config, falling back to environment variables");
  config = {
    pusher_app_id: process.env.PUSHER_APP_ID,
    pusher_key: process.env.PUSHER_KEY,
    pusher_secret: process.env.PUSHER_SECRET,
    twitter_consumer_key: process.env.TWITTER_CONSUMER_KEY,
    twitter_consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
    twitter_access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
    twitter_access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
    DEBUG: process.env.DEBUG || false
  }
}

var keywords = config.keywords;
var keywordStats = {};

function log() {
  if( config.DEBUG ) {
    console.log.apply( null, arguments );
  }
}

// Capture uncaught errors
process.on("uncaughtException", function(err) {
  console.log(err);

  log("Attempting to restart stream");
  setImmediate(restartStream);
});

// --------------------------------------------------------------------
// SET UP PUSHER
// --------------------------------------------------------------------
var Pusher = require("pusher");
var pusher = new Pusher({
  appId: config.pusher_app_id,
  key: config.pusher_key,
  secret: config.pusher_secret
});

// --------------------------------------------------------------------
// SET UP EXPRESS
// --------------------------------------------------------------------

var app = express();

// Ping
app.get("/ping", function(req, res) {
  res.status(200).end();
});

// Error handler
app.use(errorHandler({
  dumpExceptions: true,
  showStack: true
}));

// Open server on specified port
log("Starting Express server");
app.listen(process.env.PORT || 5001);

// --------------------------------------------------------------------
// SET UP TWITTER
// --------------------------------------------------------------------

var twit = new Twit({
  consumer_key: config.twitter_consumer_key,
  consumer_secret: config.twitter_consumer_secret,
  access_token: config.twitter_access_token_key,
  access_token_secret: config.twitter_access_token_secret
});

var streamRetryCount = 0;
var streamRetryLimit = 10;
var streamRetryDelay = 1000;
var stream;

var startStream = function() {
  var keywords = [ 'santa', 'christmas', 'xmas', 'hohoho', 'humbug' ];
  stream = twit.stream('statuses/filter', { track: keywords.join(',') } );

  stream.on('tweet', function (tweet) {
    if (streamRetryCount > 0) {
      streamRetryCount = 0;
    }

    processTweet(tweet);
  });

  stream.on("error", function(error) {
    console.log("Error");
    console.log(error);

    setImmediate(restartStream);
  });

  stream.on("disconnect", function(response) {
    console.log("Stream end");
    setImmediate(restartStream);
  });

};

var restartingStream = false;
var restartStream = function() {
  if (restartingStream) {
    log("Aborting stream retry as it is already being restarted");
  }

  log("Aborting previous stream");
  if (stream) {
    stream.stop();
  }

  streamRetryCount += 1;
  restartingStream = true;

  if (streamRetryCount >= streamRetryLimit) {
    log("Aborting stream retry after too many attempts");
    return;
  }

  setTimeout(function() {
    restartingStream = false;
    stream.start();
  }, streamRetryDelay * (streamRetryCount * 2));
};

var processTweet = function(tweet) {
  if( publishFilter( tweet ) ) {
    log(tweet);

    pusher.trigger( 'tweets', 'new-tweet', tweet );
  }
};

var publishFilter = function(tweet) {
  // Only send tweets to the client that will be used
  if(!tweet || !tweet.place || !tweet.lang || !tweet.geo) return false;
  if(tweet.lang !== 'en') return false;
  return true;
}

// Start stream after short timeout to avoid triggering multi-connection errors
setTimeout(startStream, 2000);
<commit_msg>Filter data even further<commit_after>var _ = require("underscore");
var Twit = require("twit");

var express = require("express");
var bodyParser = require("body-parser");
var errorHandler = require("errorhandler");

var config;
try {
  config = require("./config");
} catch(e) {
  console.log("Failed to find local config, falling back to environment variables");
  config = {
    pusher_app_id: process.env.PUSHER_APP_ID,
    pusher_key: process.env.PUSHER_KEY,
    pusher_secret: process.env.PUSHER_SECRET,
    twitter_consumer_key: process.env.TWITTER_CONSUMER_KEY,
    twitter_consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
    twitter_access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
    twitter_access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
    DEBUG: process.env.DEBUG || false
  }
}

var keywords = config.keywords;
var keywordStats = {};

function log() {
  if( config.DEBUG ) {
    console.log.apply( null, arguments );
  }
}

// Capture uncaught errors
process.on("uncaughtException", function(err) {
  console.log(err);

  log("Attempting to restart stream");
  setImmediate(restartStream);
});

// --------------------------------------------------------------------
// SET UP PUSHER
// --------------------------------------------------------------------
var Pusher = require("pusher");
var pusher = new Pusher({
  appId: config.pusher_app_id,
  key: config.pusher_key,
  secret: config.pusher_secret
});

// --------------------------------------------------------------------
// SET UP EXPRESS
// --------------------------------------------------------------------

var app = express();

// Ping
app.get("/ping", function(req, res) {
  res.status(200).end();
});

// Error handler
app.use(errorHandler({
  dumpExceptions: true,
  showStack: true
}));

// Open server on specified port
log("Starting Express server");
app.listen(process.env.PORT || 5001);

// --------------------------------------------------------------------
// SET UP TWITTER
// --------------------------------------------------------------------

var twit = new Twit({
  consumer_key: config.twitter_consumer_key,
  consumer_secret: config.twitter_consumer_secret,
  access_token: config.twitter_access_token_key,
  access_token_secret: config.twitter_access_token_secret
});

var streamRetryCount = 0;
var streamRetryLimit = 10;
var streamRetryDelay = 1000;
var stream;

var startStream = function() {
  var keywords = [ 'santa', 'christmas', 'xmas', 'hohoho', 'humbug' ];
  stream = twit.stream('statuses/filter', { track: keywords.join(',') } );

  stream.on('tweet', function (tweet) {
    if (streamRetryCount > 0) {
      streamRetryCount = 0;
    }

    processTweet(tweet);
  });

  stream.on("error", function(error) {
    console.log("Error");
    console.log(error);

    setImmediate(restartStream);
  });

  stream.on("disconnect", function(response) {
    console.log("Stream end");
    setImmediate(restartStream);
  });

};

var restartingStream = false;
var restartStream = function() {
  if (restartingStream) {
    log("Aborting stream retry as it is already being restarted");
  }

  log("Aborting previous stream");
  if (stream) {
    stream.stop();
  }

  streamRetryCount += 1;
  restartingStream = true;

  if (streamRetryCount >= streamRetryLimit) {
    log("Aborting stream retry after too many attempts");
    return;
  }

  setTimeout(function() {
    restartingStream = false;
    stream.start();
  }, streamRetryDelay * (streamRetryCount * 2));
};

var processTweet = function(tweet) {
  var sendData = publishFilter( tweet );
  if( sendData !== null ) {
    pusher.trigger( 'tweets', 'new-tweet', sendData );
  }
};

var publishFilter = function(tweet) {
  // Only send tweets and data to the client that will be used
  var sendData = null;
  if(!tweet || !tweet.place || !tweet.lang || !tweet.geo) return sendData;
  if(tweet.lang !== 'en') return sendData;

  sendData = {};
  sendData.geo = tweet.geo;
  sendData.place = tweet.place;
  sendData.user = tweet.user;
  sendData.id_str = tweet.id_str;
  sendData.timestamp_ms = tweet.timestamp_ms;
  sendData.text = tweet.text;

  return sendData;
}

// Start stream after short timeout to avoid triggering multi-connection errors
setTimeout(startStream, 2000);
<|endoftext|>