<commit_before>/*
 * Copyright (c) 2014 gm9
 * This software is released under the MIT License.
 * http://opensource.org/licenses/mit-license.php
 */

(function(){
    // import
    var igt = gm9.IngressGlyphTools;
    var Glyph = igt.Glyph;
    var Dictionary = igt.Dictionary;
    var DictionaryEntry = igt.DictionaryEntry;

    // ref: http://glyphtionary.com/
    var DIC =
            [
                "1634486a8a", ["Abandon"]
                ,"587a8a", ["Adapt"]
                ,"0949", ["Advance"]
                ,"49676a898a", ["Again", "Repeat"]
                ,"010512233445", ["All"]
                ,"67697a", ["Answer"]
                ,"06092649", ["Attack", "War"]
                ,"05061617", ["Avoid"] //"Struggle"
                ,"0a277a", ["Barrier", "Obstacle"]
                ,"083738", ["Begin"]
                ,"3738676989", ["Being", "Human"]
                ,"696a9a", ["Body", "Shell"]
                ,"16596a9a", ["Breathe"]
                //,"", ["Calibration Grid"]
                ,"1734487a8a", ["Capture"]
                ,"373a8a", ["Change","Modify"]
                ,"01051638456a8a", ["Chaos","Disorder"]
                ,"0a3a", ["Clear"]
                ,"01050a1223343a45", ["Close All", "Clearall"]
                ,"698a9a", ["Complex"]
                ,"2649677889", ["Conflict"]
                ,"011223386a899a", ["Contemplate"]
                ,"2667", ["Contract"]
                ,"497889", ["Courage"]
                ,"16486a8a", ["Create","Creation"]
                ,"1216274548597a9a", ["Creativity","Thought","Idea"]//"Mind"
                ,"093a9a", ["Danger"]
                ,"06386a8a", ["Data","Signal","Message"]
                ,"17373858", ["Defend"]
                ,"38676a789a", ["Destiny"]
                ,"27597a9a", ["Destroy","Destruction"]
                ,"488a9a", ["Deteriorate","Erode"]
                ,"27487a8a", ["Die"]
                ,"16677a8a", ["Difficult"]
                ,"122334", ["Discover"]
                ,"0545", ["Distance","Outside"]
                ,"010a17373a", ["End","Close"]
                ,"01091223696a9a", ["Enlightened", "Enlightenment"]
                ,"676989", ["Equal"]
                ,"01166989", ["Escape"]
                ,"0a899a", ["Evolution", "Success"]
                ,"0a676a", ["Failure"]
                ,"176769", ["Fear"]
                ,"061216", ["Follow"]
                ,"48", ["Forget"]
                ,"162767", ["Future","Forward-Time"]
                ,"58", ["Gain"]
                ,"1659677889", ["Government","City","Civilization","Structure"]
                ,"0609276a7a9a", ["Harm"]
                ,"060937386a7a8a9a", ["Harmony","Peace"]
                ,"59788a9a", ["Help"]
                ,"16176978", ["Hide"]
                ,"363969", ["I","Me"] //"Self"
                ,"27", ["Ignore"]
                ,"166a7a", ["Improve"]
                ,"3a898a9a", ["Impure"]
                ,"163445596a9a", ["Journey"]
                ,"36396a9a", ["Knowledge"]
                ,"05384548", ["Lead"]
                ,"6a9a", ["Less"]
                ,"0116496a9a", ["Liberate"]
                ,"676a7a899a", ["Lie"]
                ,"17", ["Lose"]
                ,"17497a9a", ["Message"]
                ,"383a899a", ["Mind","Idea","Thought"]
                ,"7a8a", ["More"]
                ,"2748676989", ["Nature"]
                ,"2767", ["New"]
                ,"6769", ["No","Not","Absent","Inside"]
                ,"343a488a", ["Nourish"]
                ,"5989", ["Old"]
                ,"373878", ["Open","Accept"]
                ,"010512233437384578", ["Open All", "Openall"]
                ,"1216274548596978", ["Opening","Doorway","Portal"]
                ,"485989", ["Past"]
                ,"0a232734487a8a", ["Perfection","Balance"]
                ,"0a12277a", ["Potential"]
                ,"677889", ["Present","Now"]
                ,"0a676a7a", ["Pure","Purity"]
                ,"060959", ["Pursue"]
                ,"0a48899a", ["Pursue","Chase"]
                ,"066989", ["Question"]
                ,"27697a9a", ["React"]
                ,"1216586a8a", ["Rebel"]
                ,"050a599a", ["Recharge"]
                ,"090a383a69", ["Resist","Resistance","Struggle"]
                ,"2327597a9a", ["Restraint"]
                ,"0626", ["Retreat"]
                ,"264969", ["Safety"]
                ,"177a8a", ["Save","Rescue"]
                ,"09", ["See"]
                ,"696a7889", ["Seek","Search"]
                ,"2334", ["Self"]
                ,"2759676a898a", ["Separate"]
                ,"060927486789", ["Shaper","Shapers","Collective"]
                //"060927373848676989", ["Shaper/Collective + Being/Human"]
                ,"27344878", ["Share"]
                ,"78", ["Simple"]
                ,"373a676a", ["Soul","Spirit","Life Force"]
                ,"274878", ["Stability", "Stay"]
                ,"67697889", ["Strong"]
                ,"48696a8a9a", ["Together"]
                ,"676a7a898a9a", ["Truth"]
                ,"177a", ["Use"]
                ,"06093639", ["Victory"]
                ,"373848", ["Want"]
                ,"3669", ["We","Us"]
                ,"596769", ["Weak"]
                ,"67697a898a", ["XM"] //(Exotic Matter)
                ,"070878", ["You","Other"]
                //,"0109122334696a9a", ["[unknown]"]
                //,"0609232734486789", ["[unknown]"]
                //,"01061226", ["[unknown]"]
                //,"090a373a69", ["[unknown]"]

                //-----
                // gm9
                //-----
                ,"387a8a", ["Have"] // Human Have Impure Civilization
                ,"0a488a", ["Path"] // Shapers Have Strong Path
            ];

    var dic = new Dictionary();
    for(var ei = 0; ei < DIC.length; ei += 2){
        dic.add(Glyph.fromString(DIC[ei+0]), DIC[ei+1]);
    }
    igt.glyphtionary = dic;
    igt.glyphtionaryIndex = dic.createIndex();
})();
<commit_msg>ImperfectとEasyを追加した。<commit_after>/*
 * Copyright (c) 2014 gm9
 * This software is released under the MIT License.
 * http://opensource.org/licenses/mit-license.php
 */

(function(){
    // import
    var igt = gm9.IngressGlyphTools;
    var Glyph = igt.Glyph;
    var Dictionary = igt.Dictionary;
    var DictionaryEntry = igt.DictionaryEntry;

    // ref: http://glyphtionary.com/
    var DIC =
            [
                "1634486a8a", ["Abandon"]
                ,"587a8a", ["Adapt"]
                ,"0949", ["Advance"]
                ,"49676a898a", ["Again", "Repeat"]
                ,"010512233445", ["All"]
                ,"67697a", ["Answer"]
                ,"06092649", ["Attack", "War"]
                ,"05061617", ["Avoid"] //"Struggle"
                ,"0a277a", ["Barrier", "Obstacle"]
                ,"083738", ["Begin"]
                ,"3738676989", ["Being", "Human"]
                ,"696a9a", ["Body", "Shell"]
                ,"16596a9a", ["Breathe"]
                //,"", ["Calibration Grid"]
                ,"1734487a8a", ["Capture"]
                ,"373a8a", ["Change","Modify"]
                ,"01051638456a8a", ["Chaos","Disorder"]
                ,"0a3a", ["Clear"]
                ,"01050a1223343a45", ["Close All", "Clearall"]
                ,"698a9a", ["Complex"]
                ,"2649677889", ["Conflict"]
                ,"011223386a899a", ["Contemplate"]
                ,"2667", ["Contract"]
                ,"497889", ["Courage"]
                ,"16486a8a", ["Create","Creation"]
                ,"1216274548597a9a", ["Creativity","Thought","Idea"]//"Mind"
                ,"093a9a", ["Danger"]
                ,"06386a8a", ["Data","Signal","Message"]
                ,"17373858", ["Defend"]
                ,"38676a789a", ["Destiny"]
                ,"27597a9a", ["Destroy","Destruction"]
                ,"488a9a", ["Deteriorate","Erode"]
                ,"386a8a", ["Easy"]
                ,"27487a8a", ["Die"]
                ,"16677a8a", ["Difficult"]
                ,"122334", ["Discover"]
                ,"0545", ["Distance","Outside"]
                ,"010a17373a", ["End","Close"]
                ,"01091223696a9a", ["Enlightened", "Enlightenment"]
                ,"676989", ["Equal"]
                ,"01166989", ["Escape"]
                ,"0a899a", ["Evolution", "Success"]
                ,"0a676a", ["Failure"]
                ,"176769", ["Fear"]
                ,"061216", ["Follow"]
                ,"48", ["Forget"]
                ,"162767", ["Future","Forward-Time"]
                ,"58", ["Gain"]
                ,"1659677889", ["Government","City","Civilization","Structure"]
                ,"0609276a7a9a", ["Harm"]
                ,"060937386a7a8a9a", ["Harmony","Peace"]
                ,"59788a9a", ["Help"]
                ,"16176978", ["Hide"]
                ,"363969", ["I","Me"] //"Self"
                ,"27", ["Ignore"]
                ,"6a898a9a", ["Imperfect"]
                ,"166a7a", ["Improve"]
                ,"3a898a9a", ["Impure"]
                ,"163445596a9a", ["Journey"]
                ,"36396a9a", ["Knowledge"]
                ,"05384548", ["Lead"]
                ,"6a9a", ["Less"]
                ,"0116496a9a", ["Liberate"]
                ,"676a7a899a", ["Lie"]
                ,"17", ["Lose"]
                ,"17497a9a", ["Message"]
                ,"383a899a", ["Mind","Idea","Thought"]
                ,"7a8a", ["More"]
                ,"2748676989", ["Nature"]
                ,"2767", ["New"]
                ,"6769", ["No","Not","Absent","Inside"]
                ,"343a488a", ["Nourish"]
                ,"5989", ["Old"]
                ,"373878", ["Open","Accept"]
                ,"010512233437384578", ["Open All", "Openall"]
                ,"1216274548596978", ["Opening","Doorway","Portal"]
                ,"485989", ["Past"]
                ,"0a232734487a8a", ["Perfection","Balance"]
                ,"0a12277a", ["Potential"]
                ,"677889", ["Present","Now"]
                ,"0a676a7a", ["Pure","Purity"]
                ,"060959", ["Pursue"]
                ,"0a48899a", ["Pursue","Chase"]
                ,"066989", ["Question"]
                ,"27697a9a", ["React"]
                ,"1216586a8a", ["Rebel"]
                ,"050a599a", ["Recharge"]
                ,"090a383a69", ["Resist","Resistance","Struggle"]
                ,"2327597a9a", ["Restraint"]
                ,"0626", ["Retreat"]
                ,"264969", ["Safety"]
                ,"177a8a", ["Save","Rescue"]
                ,"09", ["See"]
                ,"696a7889", ["Seek","Search"]
                ,"2334", ["Self"]
                ,"2759676a898a", ["Separate"]
                ,"060927486789", ["Shaper","Shapers","Collective"]
                //"060927373848676989", ["Shaper/Collective + Being/Human"]
                ,"27344878", ["Share"]
                ,"78", ["Simple"]
                ,"373a676a", ["Soul","Spirit","Life Force"]
                ,"274878", ["Stability", "Stay"]
                ,"67697889", ["Strong"]
                ,"48696a8a9a", ["Together"]
                ,"676a7a898a9a", ["Truth"]
                ,"177a", ["Use"]
                ,"06093639", ["Victory"]
                ,"373848", ["Want"]
                ,"3669", ["We","Us"]
                ,"596769", ["Weak"]
                ,"67697a898a", ["XM"] //(Exotic Matter)
                ,"070878", ["You","Other"]
                //,"0109122334696a9a", ["[unknown]"]
                //,"0609232734486789", ["[unknown]"]
                //,"01061226", ["[unknown]"]
                //,"090a373a69", ["[unknown]"]

                //-----
                // gm9
                //-----
                ,"387a8a", ["Have"] // Human Have Impure Civilization
                ,"0a488a", ["Path"] // Shapers Have Strong Path
            ];

    var dic = new Dictionary();
    for(var ei = 0; ei < DIC.length; ei += 2){
        dic.add(Glyph.fromString(DIC[ei+0]), DIC[ei+1]);
    }
    igt.glyphtionary = dic;
    igt.glyphtionaryIndex = dic.createIndex();
})();
<|endoftext|>


<commit_before>'use strict';

var initProject = require('../../lib/utils/init-project');

module.exports = {
  name: 'ember-cordova',

  availableOptions: [
    {
      name: 'name',
      type: String
    }, {
      name: 'cordovaid',
      type: String
    }, {
      name: 'template-path',
      type: String
    }
  ],

  fileMapTokens: function() {
    return {
      __root__: function() { return '/'; }
    };
  },

  normalizeEntityName: function() {
    // h/t mirage
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  afterInstall: function(options) {
    return initProject(options, this.project, this.ui);
  }
};
<commit_msg>feat(blueprint): alert users to corber/ember-cordova changes<commit_after>'use strict';

var initProject = require('../../lib/utils/init-project');
var chalk = require('chalk');

module.exports = {
  name: 'ember-cordova',

  availableOptions: [
    {
      name: 'name',
      type: String
    }, {
      name: 'cordovaid',
      type: String
    }, {
      name: 'template-path',
      type: String
    }
  ],

  fileMapTokens: function() {
    return {
      __root__: function() { return '/'; }
    };
  },

  normalizeEntityName: function() {
    // h/t mirage
    // this prevents an error when the entityName is
    // not specified (since that doesn't actually matter
    // to us
  },

  /* eslint-disable max-len */
  afterInstall: function(options) {
    console.log(chalk.yellow(
      'The ember-cordova project is migrating to corber.io, ' +
      'an extension of ember-cordova with added support for Vue/React. \n \n' +

      'Ember users will see no loss of features by migrating. Details:' +
      'http://blog.isleofcode.com/announcing-corber-ember-cordova-vue/ \n \n' +

      'We will continue fixing ember-cordova bugs, however must new features will apply to corber. \n'
    ));

    return initProject(options, this.project, this.ui);
  }
  /* eslint-enable max-len */
};
<|endoftext|>


<commit_before>var margin = {top: 30, right: 120, bottom: 0, left: 120},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x = d3.scale.linear()
    .range([0, width]);

var barHeight = 20;

var color = d3.scale.ordinal()
	.range(["steelblue", "#ccc","red","yellow"]);
    //.range(["steelblue", "#ccc"]);

var duration = 750,
    delay = 25
	shift = 200;

var partition = d3.layout.partition()
    .value(function(d) { return d.ProjectAmount; });

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("top");

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + shift + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + (margin.left + shift) + "," + margin.top + ")");

svg.append("rect")
    .attr("class", "background")
    .attr("width", width)
    .attr("height", height)
    .on("click", up);

svg.append("g")
    .attr("class", "x axis");

svg.append("g")
    .attr("class", "y axis")
  .append("line")
    .attr("y1", "100%");

d3.json("data/data_credit.json", function(error, root) {
  if (error) throw error;

  partition.nodes(root);
  x.domain([0, root.value]).nice();
  down(root, 0);
});

function down(d, i) {
  if (!d.children || this.__transition__) return;
  var end = duration + d.children.length * delay;

  // Mark any currently-displayed bars as exiting.
  var exit = svg.selectAll(".enter")
      .attr("class", "exit");

  // Entering nodes immediately obscure the clicked-on bar, so hide it.
  exit.selectAll("rect").filter(function(p) { return p === d; })
      .style("fill-opacity", 1e-6);

  // Enter the new bars for the clicked-on data.
  // Per above, entering bars are immediately visible.
  var enter = bar(d)
      .attr("transform", stack(i))
      .style("opacity", 1);

  // Have the text fade-in, even though the bars are visible.
  // Color the bars as parents; they will fade to children if appropriate.
  enter.select("text").style("fill-opacity", 1e-6);
  enter.select("rect").style("fill", color(true));

  // Update the x-scale domain.
  x.domain([0, d3.max(d.children, function(d) { return d.value; })]).nice();

  // Update the x-axis.
  svg.selectAll(".x.axis").transition()
      .duration(duration)
      .call(xAxis);

  // Transition entering bars to their new position.
  var enterTransition = enter.transition()
      .duration(duration)
      .delay(function(d, i) { return i * delay; })
      .attr("transform", function(d, i) { return "translate(0," + barHeight * i * 1.2 + ")"; });

  // Transition entering text.
  enterTransition.select("text")
      .style("fill-opacity", 1);

  // Transition entering rects to the new x-scale.
  enterTransition.select("rect")
      .attr("width", function(d) { return x(d.value); })
      .style("fill", function(d) { return color(!!d.children); });

  // Transition exiting bars to fade out.
  var exitTransition = exit.transition()
      .duration(duration)
      .style("opacity", 1e-6)
      .remove();

  // Transition exiting bars to the new x-scale.
  exitTransition.selectAll("rect")
      .attr("width", function(d) { return x(d.value); });

  // Rebind the current node to the background.
  svg.select(".background")
      .datum(d)
    .transition()
      .duration(end);

  d.index = i;
}

function up(d) {
  if (!d.parent || this.__transition__) return;
  var end = duration + d.children.length * delay;

  // Mark any currently-displayed bars as exiting.
  var exit = svg.selectAll(".enter")
      .attr("class", "exit");

  // Enter the new bars for the clicked-on data's parent.
  var enter = bar(d.parent)
      .attr("transform", function(d, i) { return "translate(0," + barHeight * i * 1.2 + ")"; })
      .style("opacity", 1e-6);

  // Color the bars as appropriate.
  // Exiting nodes will obscure the parent bar, so hide it.
  enter.select("rect")
     .style("fill", function(d) { return color(!!d.children); })
    .filter(function(p) { return p === d; })
      .style("fill-opacity", 1e-6);

  // Update the x-scale domain.
  x.domain([0, d3.max(d.parent.children, function(d) { return d.value; })]).nice();

  // Update the x-axis.
  svg.selectAll(".x.axis").transition()
      .duration(duration)
      .call(xAxis);

  // Transition entering bars to fade in over the full duration.
  var enterTransition = enter.transition()
      .duration(end)
      .style("opacity", 1);

  // Transition entering rects to the new x-scale.
  // When the entering parent rect is done, make it visible!
  enterTransition.select("rect")
      .attr("width", function(d) { return x(d.value); })
      .each("end", function(p) { if (p === d) d3.select(this).style("fill-opacity", null); });

  // Transition exiting bars to the parent's position.
  var exitTransition = exit.selectAll("g").transition()
      .duration(duration)
      .delay(function(d, i) { return i * delay; })
      .attr("transform", stack(d.index));

  // Transition exiting text to fade out.
  exitTransition.select("text")
      .style("fill-opacity", 1e-6);

  // Transition exiting rects to the new scale and fade to parent color.
  exitTransition.select("rect")
      .attr("width", function(d) { return x(d.value); })
      .style("fill", color(true));

  // Remove exiting nodes when the last child has finished transitioning.
  exit.transition()
      .duration(end)
      .remove();

  // Rebind the current parent to the background.
  svg.select(".background")
      .datum(d.parent)
    .transition()
      .duration(end);
}

// Creates a set of bars for the given data node, at the specified index.
function bar(d) {
  var bar = svg.insert("g", ".y.axis")
      .attr("class", "enter")
      .attr("transform", "translate(0,5)")
    .selectAll("g")
      .data(d.children)
    .enter().append("g")
      .style("cursor", function(d) { return !d.children ? null : "pointer"; })
      .on("click", down);

  bar.append("text")
      .attr("x", -6)
      .attr("y", barHeight / 2)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) { return d.name; });

  bar.append("rect")
      .attr("width", function(d) { return x(d.value); })
      .attr("height", barHeight);

  return bar;
}

// A stateful closure for stacking bars horizontally.
function stack(i) {
  var x0 = 0;
  return function(d) {
    var tx = "translate(" + x0 + "," + barHeight * i * 1.2 + ")";
    x0 += x(d.value);
    return tx;
  };
}

function changePercVal(){
  //TODO change view
  var optList = document.getElementById("option");
  var selOpt = optList.options[optList.selectedIndex].value;
  alert(selOpt);
}<commit_msg>added data post processing for amounts and percentages<commit_after>var margin = {top: 30, right: 120, bottom: 0, left: 120},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x = d3.scale.linear()
    .range([0, width]);

var barHeight = 20;

var color = d3.scale.ordinal()
	.range(["steelblue", "#ccc","red","yellow"]);
    //.range(["steelblue", "#ccc"]);

var duration = 750,
    delay = 25,
	shift = 200;

var partition = d3.layout.partition()
    .value(function(d) { return d.ProjectAmount; });

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("top");

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + shift + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + (margin.left + shift) + "," + margin.top + ")");

svg.append("rect")
    .attr("class", "background")
    .attr("width", width)
    .attr("height", height)
    .on("click", up);

svg.append("g")
    .attr("class", "x axis");

svg.append("g")
    .attr("class", "y axis")
  .append("line")
    .attr("y1", "100%");

d3.json("data/data_credit.json", function(error, root) {
  if (error) throw error;

  postProcessData(root);

  partition.nodes(root);
  x.domain([0, root.value]).nice();
  down(root, 0);
});

function postProcessData(data) {
    ["ProjectAmount", "WholeSyndicationAmount", "Amount", "UnderwritingAmount", "OwnSynAmount", "FinalTakeAmount"].forEach(amount => {
        var amountEur = amount + "EUR",
            amountPct = amount + "Pct";
        data[amountEur] = d3.sum(data.children.map(type =>
            type[amountEur] = d3.sum(type.children.map(subType =>
                subType[amountEur] = d3.sum(subType.children.map(deal =>
                    deal[amountEur] = deal[amount] / deal.FXrateEUR
                ))
            ))
        ));
        data.children.forEach(type => {
            type[amountPct] = type[amountEur] / data[amountEur];
            type.children.forEach(subType => {
                subType[amountPct] = subType[amountEur] / type[amountEur];
                subType.children.forEach(deal => {
                    deal[amountPct] = deal[amountEur] / subType[amountEur];
                });
            });
        });
    })
}

function down(d, i) {
  if (!d.children || this.__transition__) return;
  var end = duration + d.children.length * delay;

  // Mark any currently-displayed bars as exiting.
  var exit = svg.selectAll(".enter")
      .attr("class", "exit");

  // Entering nodes immediately obscure the clicked-on bar, so hide it.
  exit.selectAll("rect").filter(function(p) { return p === d; })
      .style("fill-opacity", 1e-6);

  // Enter the new bars for the clicked-on data.
  // Per above, entering bars are immediately visible.
  var enter = bar(d)
      .attr("transform", stack(i))
      .style("opacity", 1);

  // Have the text fade-in, even though the bars are visible.
  // Color the bars as parents; they will fade to children if appropriate.
  enter.select("text").style("fill-opacity", 1e-6);
  enter.select("rect").style("fill", color(true));

  // Update the x-scale domain.
  x.domain([0, d3.max(d.children, function(d) { return d.value; })]).nice();

  // Update the x-axis.
  svg.selectAll(".x.axis").transition()
      .duration(duration)
      .call(xAxis);

  // Transition entering bars to their new position.
  var enterTransition = enter.transition()
      .duration(duration)
      .delay(function(d, i) { return i * delay; })
      .attr("transform", function(d, i) { return "translate(0," + barHeight * i * 1.2 + ")"; });

  // Transition entering text.
  enterTransition.select("text")
      .style("fill-opacity", 1);

  // Transition entering rects to the new x-scale.
  enterTransition.select("rect")
      .attr("width", function(d) { return x(d.value); })
      .style("fill", function(d) { return color(!!d.children); });

  // Transition exiting bars to fade out.
  var exitTransition = exit.transition()
      .duration(duration)
      .style("opacity", 1e-6)
      .remove();

  // Transition exiting bars to the new x-scale.
  exitTransition.selectAll("rect")
      .attr("width", function(d) { return x(d.value); });

  // Rebind the current node to the background.
  svg.select(".background")
      .datum(d)
    .transition()
      .duration(end);

  d.index = i;
}

function up(d) {
  if (!d.parent || this.__transition__) return;
  var end = duration + d.children.length * delay;

  // Mark any currently-displayed bars as exiting.
  var exit = svg.selectAll(".enter")
      .attr("class", "exit");

  // Enter the new bars for the clicked-on data's parent.
  var enter = bar(d.parent)
      .attr("transform", function(d, i) { return "translate(0," + barHeight * i * 1.2 + ")"; })
      .style("opacity", 1e-6);

  // Color the bars as appropriate.
  // Exiting nodes will obscure the parent bar, so hide it.
  enter.select("rect")
     .style("fill", function(d) { return color(!!d.children); })
    .filter(function(p) { return p === d; })
      .style("fill-opacity", 1e-6);

  // Update the x-scale domain.
  x.domain([0, d3.max(d.parent.children, function(d) { return d.value; })]).nice();

  // Update the x-axis.
  svg.selectAll(".x.axis").transition()
      .duration(duration)
      .call(xAxis);

  // Transition entering bars to fade in over the full duration.
  var enterTransition = enter.transition()
      .duration(end)
      .style("opacity", 1);

  // Transition entering rects to the new x-scale.
  // When the entering parent rect is done, make it visible!
  enterTransition.select("rect")
      .attr("width", function(d) { return x(d.value); })
      .each("end", function(p) { if (p === d) d3.select(this).style("fill-opacity", null); });

  // Transition exiting bars to the parent's position.
  var exitTransition = exit.selectAll("g").transition()
      .duration(duration)
      .delay(function(d, i) { return i * delay; })
      .attr("transform", stack(d.index));

  // Transition exiting text to fade out.
  exitTransition.select("text")
      .style("fill-opacity", 1e-6);

  // Transition exiting rects to the new scale and fade to parent color.
  exitTransition.select("rect")
      .attr("width", function(d) { return x(d.value); })
      .style("fill", color(true));

  // Remove exiting nodes when the last child has finished transitioning.
  exit.transition()
      .duration(end)
      .remove();

  // Rebind the current parent to the background.
  svg.select(".background")
      .datum(d.parent)
    .transition()
      .duration(end);
}

// Creates a set of bars for the given data node, at the specified index.
function bar(d) {
  var bar = svg.insert("g", ".y.axis")
      .attr("class", "enter")
      .attr("transform", "translate(0,5)")
    .selectAll("g")
      .data(d.children)
    .enter().append("g")
      .style("cursor", function(d) { return !d.children ? null : "pointer"; })
      .on("click", down);

  bar.append("text")
      .attr("x", -6)
      .attr("y", barHeight / 2)
      .attr("dy", ".35em")
      .style("text-anchor", "end")
      .text(function(d) { return d.name; });

  bar.append("rect")
      .attr("width", function(d) { return x(d.value); })
      .attr("height", barHeight);

  return bar;
}

// A stateful closure for stacking bars horizontally.
function stack(i) {
  var x0 = 0;
  return function(d) {
    var tx = "translate(" + x0 + "," + barHeight * i * 1.2 + ")";
    x0 += x(d.value);
    return tx;
  };
}

function changePercVal(){
  //TODO change view
  var optList = document.getElementById("option");
  var selOpt = optList.options[optList.selectedIndex].value;
  alert(selOpt);
}<|endoftext|>


<commit_before>// ==========================================================================
//                            DG.MenuPane
//
//  Author:   William Finzer
//
//  Copyright (c) 2015 by The Concord Consortium, Inc. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// ==========================================================================

/** @class DG.MenuPane A simple extension of SC.MenuPane to allow passing arguments
 *
 * There are two reasons for this override:
 *  1. We want to adjust the width of the menu before we display it.
 *  2. We want to pass arguments to the function being called.
 *
 *  Note that dgAction is the property of the menu item that will be used to invoke the
 *  the action of selecting the item from the menu.
 *
 *   @extends SC.Object
*/
DG.MenuPane = SC.MenuPane.extend(
/** @scope DG.MenuPane.prototype */
{
  /**
   * @property {String | Function}
   */
  dgAction: null,

  getDesiredMenuWidth: function() {
    var tMaxCharCount = 0,
        kAvgCharWidth = 5,  // Use 5 pixels/character for estimation
        kWidthMargins = 60;
    this.get('items').forEach( function( iItem) {
      if( iItem && iItem.title)
        tMaxCharCount = Math.max( tMaxCharCount, iItem.title.loc().length);
    });
    // Note: Currently we use a heuristic. Eventually we will probably need
    // to measure the text more precisely.
    return tMaxCharCount * kAvgCharWidth + kWidthMargins;
  },

  selectedItemDidChange: function() {
    var tSelectedItem = this.get('selectedItem'),
        tArgs = tSelectedItem.get('args') || [],
        tAction = tSelectedItem.get( 'dgAction');
    if( typeof tAction === 'string') {
      tAction = tSelectedItem.target[tAction] || this[tAction];
    }
    if( tAction)
      tAction.apply( tSelectedItem.get( 'target'), tArgs);
    this.selectedItem = null;
  }.observes('selectedItem'),

  popup: function() {
    this.adjust('width', this.getDesiredMenuWidth());
    sc_super();
  }

});

<commit_msg>[Fixed #104671544] Test for 'string' before attempting compute number of characters<commit_after>// ==========================================================================
//                            DG.MenuPane
//
//  Author:   William Finzer
//
//  Copyright (c) 2015 by The Concord Consortium, Inc. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// ==========================================================================

/** @class DG.MenuPane A simple extension of SC.MenuPane to allow passing arguments
 *
 * There are two reasons for this override:
 *  1. We want to adjust the width of the menu before we display it.
 *  2. We want to pass arguments to the function being called.
 *
 *  Note that dgAction is the property of the menu item that will be used to invoke the
 *  the action of selecting the item from the menu.
 *
 *   @extends SC.Object
*/
DG.MenuPane = SC.MenuPane.extend(
/** @scope DG.MenuPane.prototype */
{
  /**
   * @property {String | Function}
   */
  dgAction: null,

  getDesiredMenuWidth: function() {
    var tMaxCharCount = 0,
        kAvgCharWidth = 5,  // Use 5 pixels/character for estimation
        kWidthMargins = 60;
    this.get('items').forEach( function( iItem) {
      if( iItem && iItem.title && (typeof iItem.title === 'string'))
        tMaxCharCount = Math.max( tMaxCharCount, iItem.title.loc().length);
    });
    // Note: Currently we use a heuristic. Eventually we will probably need
    // to measure the text more precisely.
    return tMaxCharCount * kAvgCharWidth + kWidthMargins;
  },

  selectedItemDidChange: function() {
    var tSelectedItem = this.get('selectedItem'),
        tArgs = tSelectedItem.get('args') || [],
        tAction = tSelectedItem.get( 'dgAction');
    if( typeof tAction === 'string') {
      tAction = tSelectedItem.target[tAction] || this[tAction];
    }
    if( tAction)
      tAction.apply( tSelectedItem.get( 'target'), tArgs);
    this.selectedItem = null;
  }.observes('selectedItem'),

  popup: function() {
    this.adjust('width', this.getDesiredMenuWidth());
    sc_super();
  }

});

<|endoftext|>


<commit_before>import throttle from 'lodash.throttle';
import uuid from './uuid';
import Socket from './Socket';

// Socket logic
const uniqueId = uuid();

let activeCursors = {};

const socket = new Socket(uniqueId, {
    open: handleSocketOpen,
    MOVE_EXT_CURSOR: handleExtCursor,
    DELETE_CURSOR: deleteCursor,
});

const header = document.getElementById('header');
window.addEventListener('mousemove', throttle(handleMouseMove, 20));
window.addEventListener('resize', handleResize);
let width;
let height;
handleResize();

function handleResize(event) {
    width = window.innerWidth;
    height = window.innerHeight;
}

function handleSocketOpen() {
    // After the WebSocket has been opened, we need to reset because we might
    // have missed some delete events.
    activeCursors = {};
}

function handleMouseMove(event) {
    const x = event.pageX;
    const y = event.pageY;
    socket.send({
        type: 'MOVE_MY_CURSOR',
        data: {
            id: uniqueId,
            x: (x / width) * 100,
            y: (y / height) * 100,
        },
    });

    // This doesn't make any sense, but so does life :')
    header.style.transform = `rotate(${x - y}deg)`;
}

// External cursors logic
function handleExtCursor(data) {
    const x = data.x;
    const y = data.y;
    const id = data.id;

    activeCursors[id] = { x, y };
    calcColors();

    let el = document.getElementById(id);
    if (!el) {
        el = document.createElement('div');
        el.classList.add('cursor');
        el.id = id;
        document.body.appendChild(el);
    }
    el.style.top = y + '%';
    el.style.left = x + '%';
}

// Delete cursor logic
function deleteCursor(data) {
    delete activeCursors[data.id];
    calcColors();
    const el = document.getElementById(data.id);

    if (el) {
        document.body.removeChild(el);
    }
}

function calcColors() {
    // Contains the x + y values (in percent) for all active cursors.
    // So if there is only one cursor, and it is at the most top right of the screen, this would be 200.
    // For two users at the most top right of the screen, this would be 400.
    let totalValue = 0;
    // Amount of active cursors
    let length = 0;
    for (const c in activeCursors) {
        const data = activeCursors[c];
        totalValue += data.x + data.y;
        length += 1;
    }
    // Hue can be 0 - 360.
    // TODO: `totalValue /length` can only be maximum 200, should do some calculations so it can go to 360.
    const hue = totalValue / length;
    // Saturation can be 0 - 100.
    // TDOO: hmm this is boring, do some weird calculation or something.
    const saturation = totalValue / length / 2;
    // Lightness can be 0 - 100.
    document.body.style.background = `hsl(${hue}, ${saturation}%, 50%)`;
}
<commit_msg>fix for firefox... sigh<commit_after>import throttle from 'lodash.throttle';
import uuid from './uuid';
import Socket from './Socket';

// Socket logic
const uniqueId = uuid();

let activeCursors = {};

const socket = new Socket(uniqueId, {
    open: handleSocketOpen,
    MOVE_EXT_CURSOR: handleExtCursor,
    DELETE_CURSOR: deleteCursor,
});

const header = document.getElementById('header');
window.addEventListener('mousemove', throttle(handleMouseMove, 20));
window.addEventListener('resize', handleResize);
let width;
let height;
handleResize();

function handleResize(event) {
    width = window.innerWidth;
    height = window.innerHeight;
}

function handleSocketOpen() {
    // After the WebSocket has been opened, we need to reset because we might
    // have missed some delete events.
    activeCursors = {};
}

function handleMouseMove(event) {
    const x = event.pageX;
    const y = event.pageY;
    socket.send({
        type: 'MOVE_MY_CURSOR',
        data: {
            id: uniqueId,
            x: (x / width) * 100,
            y: (y / height) * 100,
        },
    });

    // This doesn't make any sense, but so does life :')
    header.style.transform = `rotate(${x - y}deg)`;
}

// External cursors logic
function handleExtCursor(data) {
    const x = data.x;
    const y = data.y;
    const id = data.id;

    activeCursors[id] = { x, y };
    calcColors();

    let el = document.getElementById(id);
    if (!el) {
        el = document.createElement('div');
        el.classList.add('cursor');
        el.id = id;
        document.body.appendChild(el);
    }
    el.style.top = y + '%';
    el.style.left = x + '%';
}

// Delete cursor logic
function deleteCursor(data) {
    delete activeCursors[data.id];
    calcColors();
    const el = document.getElementById(data.id);

    if (el) {
        document.body.removeChild(el);
    }
}

function calcColors() {
    // Contains the x + y values (in percent) for all active cursors.
    // So if there is only one cursor, and it is at the most top right of the screen, this would be 200.
    // For two users at the most top right of the screen, this would be 400.
    let totalValue = 0;
    // Amount of active cursors
    let length = 0;
    for (let c in activeCursors) {
        const data = activeCursors[c];
        totalValue += data.x + data.y;
        length += 1;
    }
    // Hue can be 0 - 360.
    // TODO: `totalValue /length` can only be maximum 200, should do some calculations so it can go to 360.
    const hue = totalValue / length;
    // Saturation can be 0 - 100.
    // TDOO: hmm this is boring, do some weird calculation or something.
    const saturation = totalValue / length / 2;
    // Lightness can be 0 - 100.
    document.body.style.background = `hsl(${hue}, ${saturation}%, 50%)`;
}
<|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 120 */
/*global module, require, exports */

////////////////////////////////////////////////////////////////////////////////
/// @brief Foxx Request Context
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2013 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Lucas Dohmen
/// @author Copyright 2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var RequestContext,
  RequestContextBuffer,
  SwaggerDocs,
  _ = require("underscore"),
  extend = _.extend,
  internal = require("org/arangodb/foxx/internals"),
  is = require("org/arangodb/is"),
  UnauthorizedError = require("org/arangodb/foxx/authentication").UnauthorizedError,
  createErrorBubbleWrap,
  addCheck;

createErrorBubbleWrap = function (handler, errorClass, code, reason, errorHandler) {
  'use strict';
  if (is.notExisty(errorHandler)) {
    errorHandler = function () {
      return { error: reason };
    };
  }

  return function (req, res) {
    try {
      handler(req, res);
    } catch (e) {
      if (e instanceof errorClass) {
        res.status(code);
        res.json(errorHandler(e));
      } else {
        throw e;
      }
    }
  };
};

addCheck = function (handler, check) {
  'use strict';
  return function (req, res) {
    check(req);
    handler(req, res);
  };
};

// Wraps the docs object of a route to add swagger compatible documentation
SwaggerDocs = function (docs) {
  'use strict';
  this.docs = docs;
};

extend(SwaggerDocs.prototype, {
  addNickname: function (httpMethod, match) {
    'use strict';
    this.docs.nickname = internal.constructNickname(httpMethod, match);
  },

  addPathParam: function (paramName, description, dataType) {
    'use strict';
    this.docs.parameters.push(internal.constructPathParamDoc(paramName, description, dataType));
  },

  addQueryParam: function (paramName, description, dataType, required, allowMultiple) {
    'use strict';
    this.docs.parameters.push(internal.constructQueryParamDoc(
      paramName,
      description,
      dataType,
      required,
      allowMultiple
    ));
  },

  addSummary: function (summary) {
    'use strict';
    this.docs.summary = summary;
  },

  addNotes: function (notes) {
    'use strict';
    this.docs.notes = notes;
  }
});

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_initializer
/// @brief Context of a Request Definition
///
/// Used for documenting and constraining the routes.
////////////////////////////////////////////////////////////////////////////////

RequestContext = function (executionBuffer, route) {
  'use strict';
  this.route = route;
  this.typeToRegex = {
    "int": "/[0-9]+/",
    "string": "/.+/"
  };
  this.docs = new SwaggerDocs(this.route.docs);
  this.docs.addNickname(route.docs.httpMethod, route.url.match);

  executionBuffer.applyEachFunction(this);
};

extend(RequestContext.prototype, {

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_pathParam
/// @brief Describe a path parameter
///
/// If you defined a route "/foxx/:id", you can constrain which format a path
/// parameter (`/foxx/12`) can have by giving it a type.  We currently support
/// the following types:
///
/// * int
/// * string
///
/// You can also provide a description of this parameter.
///
/// @EXAMPLES
///
/// @code
///     app.get("/foxx/:id", function {
///       // Do something
///     }).pathParam("id", {
///       description: "Id of the Foxx",
///       type: "int"
///     });
/// @endcode
////////////////////////////////////////////////////////////////////////////////

  pathParam: function (paramName, attributes) {
    'use strict';
    var url = this.route.url,
      docs = this.route.docs,
      constraint = url.constraint || {};

    constraint[paramName] = this.typeToRegex[attributes.type];
    this.route.url = internal.constructUrlObject(url.match, constraint, url.methods[0]);
    this.docs.addPathParam(paramName, attributes.description, attributes.type);
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_queryParam
/// @brief Describe a Query Parameter
///
/// @FUN{FoxxController::queryParam(@FA{id}, @FA{options})}
///
/// Describe a query parameter:
///
/// If you defined a route "/foxx", you can constrain which format a query
/// parameter (`/foxx?a=12`) can have by giving it a type.  We currently support
/// the following types:
///
/// * int
/// * string
///
/// You can also provide a description of this parameter, if it is required and
/// if you can provide the parameter multiple times.
///
/// @EXAMPLES
///
/// @code
///     app.get("/foxx", function {
///       // Do something
///     }).queryParam("id", {
///       description: "Id of the Foxx",
///       type: "int",
///       required: true,
///       allowMultiple: false
///     });
/// @endcode
////////////////////////////////////////////////////////////////////////////////

  queryParam: function (paramName, attributes) {
    'use strict';
    this.docs.addQueryParam(
      paramName,
      attributes.description,
      attributes.type,
      attributes.required,
      attributes.allowMultiple
    );
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_summary
/// @brief Set the summary for this route in the documentation
///
/// @FUN{FoxxController::summary(@FA{description})}
///
/// Set the summary for this route in the documentation. Can't be longer than 60.
/// characters
////////////////////////////////////////////////////////////////////////////////

  summary: function (summary) {
    'use strict';
    if (summary.length > 60) {
      throw new Error("Summary can't be longer than 60 characters");
    }
    this.docs.addSummary(summary);
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_notes
/// @brief Set the notes for this route in the documentation
///
/// @FUN{FoxxController::notes(@FA{description})}
///
/// Set the notes for this route in the documentation
////////////////////////////////////////////////////////////////////////////////

  notes: function (notes) {
    'use strict';
    this.docs.addNotes(notes);
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_errorResponse
/// @brief Define an error response
///
/// @FUN{FoxxController::errorResponse(@FA{errorClass}, @FA{code}, @FA{description})}
///
/// Define a reaction to a thrown error for this route: If your handler throws an error
/// of the defined errorClass, it will be caught and the response will have the given
/// status code and a JSON with error set to your description as the body.
///
/// If you want more control over the returned JSON, you can give an optional fourth
/// parameter in form of a function. It gets the error as an argument, the return
/// value will transformed into JSON and then be used as the body.
/// The status code will be used as described above. The description will be used for
/// the documentation.
///
/// It also adds documentation for this error response to the generated documentation.
///
/// @EXAMPLES
///
/// @code
///     app.get("/foxx", function {
///       throw new FoxxyError();
///     }).errorResponse(FoxxyError, 303, "This went completely wrong. Sorry!");
///
///     app.get("/foxx", function {
///       throw new FoxxyError();
///     }).errorResponse(FoxxyError, 303, "This went completely wrong. Sorry!", function (e) {
///       return {
///         code: 123,
///         desc: e.description
///       };
///     });
/// @endcode
////////////////////////////////////////////////////////////////////////////////
  errorResponse: function (errorClass, code, reason, errorHandler) {
    'use strict';
    var handler = this.route.action.callback;
    this.route.action.callback = createErrorBubbleWrap(handler, errorClass, code, reason, errorHandler);
    this.route.docs.errorResponses.push(internal.constructErrorResponseDoc(code, reason));
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_onlyIf
/// @brief Only let the request get through if a condition holds
///
/// @FUN{FoxxController::onlyIf(@FA{check})}
///
/// Provide it with a function that throws an exception if the normal processing should
/// not be executed. Provide an `errorResponse` to define the behavior in this case.
/// This can be used for authentication or authorization for example.
///
/// @EXAMPLES
///
/// @code
///     app.get("/foxx", function {
///       // Do something
///     }).onlyIf(aFunction).errorResponse(ErrorClass, 303, "This went completely wrong. Sorry!");
/// @endcode
////////////////////////////////////////////////////////////////////////////////
  onlyIf: function (check, ErrorClass) {
    'use strict';
    var handler = this.route.action.callback;
    this.route.action.callback = addCheck(handler, check);
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_onlyIfAuthenticated
/// @brief Only let the request get through if the user is logged in
///
/// @FUN{FoxxController::onlyIf(@FA{code}, @FA{reason})}
///
/// Please activate authentification for this app if you want to use this function.
/// If the user is logged in, it will do nothing. Otherwise it will respond with
/// the status code and the reason you provided (the route handler won't be called).
/// This will also add the according documentation for this route.
///
/// @EXAMPLES
///
/// @code
///     app.get("/foxx", function {
///       // Do something
///     }).onlyIfAuthenticated(401, "You need to be authenticated");
/// @endcode
////////////////////////////////////////////////////////////////////////////////
  onlyIfAuthenticated: function (code, reason) {
    'use strict';
    var handler = this.route.action.callback,
      check;

    check = function (req) {
      if (!(req.user && req.currentSession)) {
        throw new UnauthorizedError();
      }
    };

    if (is.notExisty(code)) {
      code = 401;
    }
    if (is.notExisty(reason)) {
      reason = "Not authorized";
    }

    this.onlyIf(check);
    this.errorResponse(UnauthorizedError, code, reason);

    return this;
  }
});

RequestContextBuffer = function () {
  this.applyChain = [];
};

extend(RequestContextBuffer.prototype, {
  applyEachFunction: function (target) {
    _.each(this.applyChain, function (x) {
      target[x.functionName].apply(target, x.argumentList);
    });
  }
});

_.each([
////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContextBuffer_errorResponse
/// @brief Defines a controller-wide error response
///
/// @FUN{RequestContextBuffer::errorResponse(@FA{errorClass}, @FA{code}, @FA{description})}
///
/// Defines an `errorResponse` for all routes of this controller. For details on
/// `errorResponse` see the according method on routes.
///
/// @EXAMPLES
///
/// @code
///     app.allroutes.errorResponse(FoxxyError, 303, "This went completely wrong. Sorry!");
///
///     app.get("/foxx", function {
///       // Do something
///     });
/// @endcode
////////////////////////////////////////////////////////////////////////////////
  "errorResponse",

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContextBuffer_onlyIf
/// @brief Defines a controller-wide onlyIf
///
/// @FUN{RequestContextBuffer::onlyIf(@FA{code}, @FA{reason})}
///
/// Defines an `onlyIf` for all routes of this controller. For details on
/// `onlyIf` see the according method on routes.
///
/// @EXAMPLES
///
/// @code
///     app.allroutes.onlyIf(myPersonalCheck);
///
///     app.get("/foxx", function {
///       // Do something
///     });
/// @endcode
////////////////////////////////////////////////////////////////////////////////
  "onlyIf",

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContextBuffer_onlyIfAuthenticated
/// @brief Defines a controller-wide onlyIfAuthenticated
///
/// @FUN{RequestContextBuffer::errorResponse(@FA{errorClass}, @FA{code}, @FA{description})}
///
/// Defines an `onlyIfAuthenticated` for all routes of this controller. For details on
/// `onlyIfAuthenticated` see the according method on routes.
///
/// @EXAMPLES
///
/// @code
///     app.allroutes.onlyIfAuthenticated(401, "You need to be authenticated");
///
///     app.get("/foxx", function {
///       // Do something
///     });
/// @endcode
////////////////////////////////////////////////////////////////////////////////
  "onlyIfAuthenticated"
], function(functionName) {
  extend(RequestContextBuffer.prototype[functionName] = function () {
    this.applyChain.push({
      functionName: functionName,
      argumentList: arguments
    });
  });
});

exports.RequestContext = RequestContext;
exports.RequestContextBuffer = RequestContextBuffer;

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

/// Local Variables:
/// mode: outline-minor
/// outline-regexp: "/// @brief\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}\\|/\\*jslint"
/// End:
<commit_msg>JSLint<commit_after>/*jslint indent: 2, nomen: true, maxlen: 120 */
/*global module, require, exports */

////////////////////////////////////////////////////////////////////////////////
/// @brief Foxx Request Context
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2013 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Lucas Dohmen
/// @author Copyright 2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var RequestContext,
  RequestContextBuffer,
  SwaggerDocs,
  _ = require("underscore"),
  extend = _.extend,
  internal = require("org/arangodb/foxx/internals"),
  is = require("org/arangodb/is"),
  UnauthorizedError = require("org/arangodb/foxx/authentication").UnauthorizedError,
  createErrorBubbleWrap,
  addCheck;

createErrorBubbleWrap = function (handler, errorClass, code, reason, errorHandler) {
  'use strict';
  if (is.notExisty(errorHandler)) {
    errorHandler = function () {
      return { error: reason };
    };
  }

  return function (req, res) {
    try {
      handler(req, res);
    } catch (e) {
      if (e instanceof errorClass) {
        res.status(code);
        res.json(errorHandler(e));
      } else {
        throw e;
      }
    }
  };
};

addCheck = function (handler, check) {
  'use strict';
  return function (req, res) {
    check(req);
    handler(req, res);
  };
};

// Wraps the docs object of a route to add swagger compatible documentation
SwaggerDocs = function (docs) {
  'use strict';
  this.docs = docs;
};

extend(SwaggerDocs.prototype, {
  addNickname: function (httpMethod, match) {
    'use strict';
    this.docs.nickname = internal.constructNickname(httpMethod, match);
  },

  addPathParam: function (paramName, description, dataType) {
    'use strict';
    this.docs.parameters.push(internal.constructPathParamDoc(paramName, description, dataType));
  },

  addQueryParam: function (paramName, description, dataType, required, allowMultiple) {
    'use strict';
    this.docs.parameters.push(internal.constructQueryParamDoc(
      paramName,
      description,
      dataType,
      required,
      allowMultiple
    ));
  },

  addSummary: function (summary) {
    'use strict';
    this.docs.summary = summary;
  },

  addNotes: function (notes) {
    'use strict';
    this.docs.notes = notes;
  }
});

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_initializer
/// @brief Context of a Request Definition
///
/// Used for documenting and constraining the routes.
////////////////////////////////////////////////////////////////////////////////

RequestContext = function (executionBuffer, route) {
  'use strict';
  this.route = route;
  this.typeToRegex = {
    "int": "/[0-9]+/",
    "string": "/.+/"
  };
  this.docs = new SwaggerDocs(this.route.docs);
  this.docs.addNickname(route.docs.httpMethod, route.url.match);

  executionBuffer.applyEachFunction(this);
};

extend(RequestContext.prototype, {

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_pathParam
/// @brief Describe a path parameter
///
/// If you defined a route "/foxx/:id", you can constrain which format a path
/// parameter (`/foxx/12`) can have by giving it a type.  We currently support
/// the following types:
///
/// * int
/// * string
///
/// You can also provide a description of this parameter.
///
/// @EXAMPLES
///
/// @code
///     app.get("/foxx/:id", function {
///       // Do something
///     }).pathParam("id", {
///       description: "Id of the Foxx",
///       type: "int"
///     });
/// @endcode
////////////////////////////////////////////////////////////////////////////////

  pathParam: function (paramName, attributes) {
    'use strict';
    var url = this.route.url,
      docs = this.route.docs,
      constraint = url.constraint || {};

    constraint[paramName] = this.typeToRegex[attributes.type];
    this.route.url = internal.constructUrlObject(url.match, constraint, url.methods[0]);
    this.docs.addPathParam(paramName, attributes.description, attributes.type);
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_queryParam
/// @brief Describe a Query Parameter
///
/// @FUN{FoxxController::queryParam(@FA{id}, @FA{options})}
///
/// Describe a query parameter:
///
/// If you defined a route "/foxx", you can constrain which format a query
/// parameter (`/foxx?a=12`) can have by giving it a type.  We currently support
/// the following types:
///
/// * int
/// * string
///
/// You can also provide a description of this parameter, if it is required and
/// if you can provide the parameter multiple times.
///
/// @EXAMPLES
///
/// @code
///     app.get("/foxx", function {
///       // Do something
///     }).queryParam("id", {
///       description: "Id of the Foxx",
///       type: "int",
///       required: true,
///       allowMultiple: false
///     });
/// @endcode
////////////////////////////////////////////////////////////////////////////////

  queryParam: function (paramName, attributes) {
    'use strict';
    this.docs.addQueryParam(
      paramName,
      attributes.description,
      attributes.type,
      attributes.required,
      attributes.allowMultiple
    );
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_summary
/// @brief Set the summary for this route in the documentation
///
/// @FUN{FoxxController::summary(@FA{description})}
///
/// Set the summary for this route in the documentation. Can't be longer than 60.
/// characters
////////////////////////////////////////////////////////////////////////////////

  summary: function (summary) {
    'use strict';
    if (summary.length > 60) {
      throw new Error("Summary can't be longer than 60 characters");
    }
    this.docs.addSummary(summary);
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_notes
/// @brief Set the notes for this route in the documentation
///
/// @FUN{FoxxController::notes(@FA{description})}
///
/// Set the notes for this route in the documentation
////////////////////////////////////////////////////////////////////////////////

  notes: function (notes) {
    'use strict';
    this.docs.addNotes(notes);
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_errorResponse
/// @brief Define an error response
///
/// @FUN{FoxxController::errorResponse(@FA{errorClass}, @FA{code}, @FA{description})}
///
/// Define a reaction to a thrown error for this route: If your handler throws an error
/// of the defined errorClass, it will be caught and the response will have the given
/// status code and a JSON with error set to your description as the body.
///
/// If you want more control over the returned JSON, you can give an optional fourth
/// parameter in form of a function. It gets the error as an argument, the return
/// value will transformed into JSON and then be used as the body.
/// The status code will be used as described above. The description will be used for
/// the documentation.
///
/// It also adds documentation for this error response to the generated documentation.
///
/// @EXAMPLES
///
/// @code
///     app.get("/foxx", function {
///       throw new FoxxyError();
///     }).errorResponse(FoxxyError, 303, "This went completely wrong. Sorry!");
///
///     app.get("/foxx", function {
///       throw new FoxxyError();
///     }).errorResponse(FoxxyError, 303, "This went completely wrong. Sorry!", function (e) {
///       return {
///         code: 123,
///         desc: e.description
///       };
///     });
/// @endcode
////////////////////////////////////////////////////////////////////////////////
  errorResponse: function (errorClass, code, reason, errorHandler) {
    'use strict';
    var handler = this.route.action.callback;
    this.route.action.callback = createErrorBubbleWrap(handler, errorClass, code, reason, errorHandler);
    this.route.docs.errorResponses.push(internal.constructErrorResponseDoc(code, reason));
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_onlyIf
/// @brief Only let the request get through if a condition holds
///
/// @FUN{FoxxController::onlyIf(@FA{check})}
///
/// Provide it with a function that throws an exception if the normal processing should
/// not be executed. Provide an `errorResponse` to define the behavior in this case.
/// This can be used for authentication or authorization for example.
///
/// @EXAMPLES
///
/// @code
///     app.get("/foxx", function {
///       // Do something
///     }).onlyIf(aFunction).errorResponse(ErrorClass, 303, "This went completely wrong. Sorry!");
/// @endcode
////////////////////////////////////////////////////////////////////////////////
  onlyIf: function (check, ErrorClass) {
    'use strict';
    var handler = this.route.action.callback;
    this.route.action.callback = addCheck(handler, check);
    return this;
  },

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContext_onlyIfAuthenticated
/// @brief Only let the request get through if the user is logged in
///
/// @FUN{FoxxController::onlyIf(@FA{code}, @FA{reason})}
///
/// Please activate authentification for this app if you want to use this function.
/// If the user is logged in, it will do nothing. Otherwise it will respond with
/// the status code and the reason you provided (the route handler won't be called).
/// This will also add the according documentation for this route.
///
/// @EXAMPLES
///
/// @code
///     app.get("/foxx", function {
///       // Do something
///     }).onlyIfAuthenticated(401, "You need to be authenticated");
/// @endcode
////////////////////////////////////////////////////////////////////////////////
  onlyIfAuthenticated: function (code, reason) {
    'use strict';
    var handler = this.route.action.callback,
      check;

    check = function (req) {
      if (!(req.user && req.currentSession)) {
        throw new UnauthorizedError();
      }
    };

    if (is.notExisty(code)) {
      code = 401;
    }
    if (is.notExisty(reason)) {
      reason = "Not authorized";
    }

    this.onlyIf(check);
    this.errorResponse(UnauthorizedError, code, reason);

    return this;
  }
});

RequestContextBuffer = function () {
  'use strict';
  this.applyChain = [];
};

extend(RequestContextBuffer.prototype, {
  applyEachFunction: function (target) {
    'use strict';
    _.each(this.applyChain, function (x) {
      target[x.functionName].apply(target, x.argumentList);
    });
  }
});

_.each([
////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContextBuffer_errorResponse
/// @brief Defines a controller-wide error response
///
/// @FUN{RequestContextBuffer::errorResponse(@FA{errorClass}, @FA{code}, @FA{description})}
///
/// Defines an `errorResponse` for all routes of this controller. For details on
/// `errorResponse` see the according method on routes.
///
/// @EXAMPLES
///
/// @code
///     app.allroutes.errorResponse(FoxxyError, 303, "This went completely wrong. Sorry!");
///
///     app.get("/foxx", function {
///       // Do something
///     });
/// @endcode
////////////////////////////////////////////////////////////////////////////////
  "errorResponse",

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContextBuffer_onlyIf
/// @brief Defines a controller-wide onlyIf
///
/// @FUN{RequestContextBuffer::onlyIf(@FA{code}, @FA{reason})}
///
/// Defines an `onlyIf` for all routes of this controller. For details on
/// `onlyIf` see the according method on routes.
///
/// @EXAMPLES
///
/// @code
///     app.allroutes.onlyIf(myPersonalCheck);
///
///     app.get("/foxx", function {
///       // Do something
///     });
/// @endcode
////////////////////////////////////////////////////////////////////////////////
  "onlyIf",

////////////////////////////////////////////////////////////////////////////////
/// @fn JSF_foxx_RequestContextBuffer_onlyIfAuthenticated
/// @brief Defines a controller-wide onlyIfAuthenticated
///
/// @FUN{RequestContextBuffer::errorResponse(@FA{errorClass}, @FA{code}, @FA{description})}
///
/// Defines an `onlyIfAuthenticated` for all routes of this controller. For details on
/// `onlyIfAuthenticated` see the according method on routes.
///
/// @EXAMPLES
///
/// @code
///     app.allroutes.onlyIfAuthenticated(401, "You need to be authenticated");
///
///     app.get("/foxx", function {
///       // Do something
///     });
/// @endcode
////////////////////////////////////////////////////////////////////////////////
  "onlyIfAuthenticated"
], function (functionName) {
  'use strict';
  extend(RequestContextBuffer.prototype[functionName] = function () {
    this.applyChain.push({
      functionName: functionName,
      argumentList: arguments
    });
  });
});

exports.RequestContext = RequestContext;
exports.RequestContextBuffer = RequestContextBuffer;

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

/// Local Variables:
/// mode: outline-minor
/// outline-regexp: "/// @brief\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}\\|/\\*jslint"
/// End:
<|endoftext|>


<commit_before>/*global System, declare, it, xit, describe, xdescribe, beforeEach, afterEach, before, after*/
import { Range } from "../../text/range.js";
import { expect } from "mocha-es6";

describe("range", () => {

  describe("merge", () => {

    it("bordered", () =>
      expect(Range.create(0,0, 1, 4).merge(Range.create(1, 4, 1, 5)))
        .stringEquals("Range(0/0 -> 1/5)"));

    it("bordered reverse", () =>
      expect(Range.create(1, 4, 1, 5).merge(Range.create(0,3, 1, 4)))
        .stringEquals("Range(0/3 -> 1/5)"));

    it("overlapping ", () =>
      expect(Range.create(0,0, 1, 4).merge(Range.create(1, 2, 1, 5)))
        .stringEquals("Range(0/0 -> 1/5)"));

    it("overlapping reverse", () =>
      expect(Range.create(1, 2, 1, 5).merge(Range.create(0,3, 1, 4)))
        .stringEquals("Range(0/3 -> 1/5)"));

    it("non overlapping", () =>
      expect(Range.create(1, 2, 1, 5).merge(Range.create(1, 6, 1, 8)))
        .stringEquals("Range(1/2 -> 1/5)"));

  });

  describe("subtract", () => {

    it("overlapping", () =>
      expect(Range.create(0,0, 1, 4).without(Range.create(1, 2, 1, 5)))
        .stringEquals("Range(0/0 -> 1/5)"));

    it("non-overlapping 1", () =>
      expect(Range.create(0,0, 1, 1).without(Range.create(1, 2, 1, 5)))
        .stringEquals("Range(0/0 -> 1/1)"));

    it("non-overlapping 2", () =>
      expect(Range.create(1, 2, 1, 5).without(Range.create(0,0, 1, 1)))
        .stringEquals("Range(1/2 -> 1/5)"));

  });

});<commit_msg>text range: add intersection tests<commit_after>/*global System, declare, it, xit, describe, xdescribe, beforeEach, afterEach, before, after*/
import { Range } from "../../text/range.js";
import { expect } from "mocha-es6";

describe("range", () => {

  describe("merge", () => {

    it("bordered", () =>
      expect(Range.create(0,0, 1, 4).merge(Range.create(1, 4, 1, 5)))
        .stringEquals("Range(0/0 -> 1/5)"));

    it("bordered reverse", () =>
      expect(Range.create(1, 4, 1, 5).merge(Range.create(0,3, 1, 4)))
        .stringEquals("Range(0/3 -> 1/5)"));

    it("overlapping ", () =>
      expect(Range.create(0,0, 1, 4).merge(Range.create(1, 2, 1, 5)))
        .stringEquals("Range(0/0 -> 1/5)"));

    it("overlapping reverse", () =>
      expect(Range.create(1, 2, 1, 5).merge(Range.create(0,3, 1, 4)))
        .stringEquals("Range(0/3 -> 1/5)"));

    it("non overlapping", () =>
      expect(Range.create(1, 2, 1, 5).merge(Range.create(1, 6, 1, 8)))
        .stringEquals("Range(1/2 -> 1/5)"));

  });

  describe("subtract", () => {

    it("overlapping", () =>
      expect(Range.create(0,0, 1, 4).without(Range.create(1, 2, 1, 5)))
        .stringEquals("Range(0/0 -> 1/5)"));

    it("non-overlapping 1", () =>
      expect(Range.create(0,0, 1, 1).without(Range.create(1, 2, 1, 5)))
        .stringEquals("Range(0/0 -> 1/1)"));

    it("non-overlapping 2", () =>
      expect(Range.create(1, 2, 1, 5).without(Range.create(0,0, 1, 1)))
        .stringEquals("Range(1/2 -> 1/5)"));

  });

  describe("intersect", () => {

    it("bordered", () =>
      expect(Range.create(0,0, 1, 4).intersect(Range.create(1, 4, 1, 5)))
        .stringEquals("Range(1/4 -> 1/4)"));

    it("bordered reverse", () =>
      expect(Range.create(1, 4, 1, 5).intersect(Range.create(0,3, 1, 4)))
        .stringEquals("Range(1/4 -> 1/4)"));

    it("overlapping ", () =>
      expect(Range.create(0,0, 1, 4).intersect(Range.create(1, 2, 1, 5)))
        .stringEquals("Range(1/2 -> 1/4)"));

    it("overlapping reverse", () =>
      expect(Range.create(1, 2, 1, 5).intersect(Range.create(0,3, 1, 4)))
        .stringEquals("Range(1/2 -> 1/4)"));

    it("non overlapping", () =>
      expect(Range.create(1, 2, 1, 5).intersect(Range.create(1, 6, 1, 8)))
        .equals(null));

  });
});
<|endoftext|>


<commit_before>var languages = require('./languages');

require('amd-loader');

var dom     = require('jsdom/lib/jsdom/level2/html').dom.level2.html;
var browser = require('jsdom/lib/jsdom/browser/index').windowAugmentation(dom);

global.document  = browser.document;
global.window    = browser.window;
global.self      = browser.self;
global.navigator = browser.navigator;
global.location  = browser.location;

require('./public/deps/ace/ace.js');
require('./public/deps/ace/ext-static_highlight.js');

require('./public/deps/ace/mode-c_cpp.js');
require('./public/deps/ace/mode-javascript.js');

require('./public/deps/ace/theme-gist.js');

var modes = [];
for (var i = 0; i < languages.length; ++i) {
  require('./public/deps/ace/mode-' + languages[i].mode);
  modes[languages[i].name] = 'ace/mode/' + languages[i].mode;
}

var highlighter = ace.require('ace/ext/static_highlight');
var theme = ace.require('ace/theme/gist');

module.exports = function (data, language) {
  return highlighter.renderSync(data, modes[language], theme, 1, true);
};
<commit_msg>Remove useless code<commit_after>var languages = require('./languages');

require('amd-loader');

var dom     = require('jsdom/lib/jsdom/level2/html').dom.level2.html;
var browser = require('jsdom/lib/jsdom/browser/index').windowAugmentation(dom);

global.document  = browser.document;
global.window    = browser.window;
global.self      = browser.self;
global.navigator = browser.navigator;
global.location  = browser.location;

require('./public/deps/ace/ace.js');
require('./public/deps/ace/ext-static_highlight.js');
require('./public/deps/ace/theme-gist.js');

var modes = [];
for (var i = 0; i < languages.length; ++i) {
  require('./public/deps/ace/mode-' + languages[i].mode);
  modes[languages[i].name] = 'ace/mode/' + languages[i].mode;
}

var highlighter = ace.require('ace/ext/static_highlight');
var theme = ace.require('ace/theme/gist');

module.exports = function (data, language) {
  return highlighter.renderSync(data, modes[language], theme, 1, true);
};
<|endoftext|>


<commit_before>/*
 This Source Code Form is subject to the terms of the Mozilla Public
 License, v. 2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.
 Copyright (c) 2014 Mozilla Corporation

 Contributors:
 Jeff Bryner jbryner@mozilla.com
 Anthony Verez averez@mozilla.com
 Sanchit Kapoor sanchitlucknow@gmail.com
 Yash Mehrotra yashmehrotra95@gmail.com
 Avijit Gupta 526avijit@gmail.com
 */

if (Meteor.isClient) {

  var MESHPROPERTIES = {
    count: 4,
    position: [
      {x: 0, y: 0, z: 0},
      {x: -800, y: -20, z: 0},
      {x: -800, y: -20, z: -800},
      {x: 0 , y: -20, z: -800}
    ],
    rotationY: [
      0,
      0,
      Math.PI/2,
      Math.PI/2
    ]
  };

  // TODO: WHY_NO_UNDERSCORE @avijit
  var RANKCOORDINATES = [
    {x: -286, z: -115},
    {x: -15, z: 11},
    {x: -234, z: 232},
    {x: -69, z: -142},
    {x: 124, z: 293},
    {x: 153, z: -869},
    {x: 124, z: -1122},
    {x: -261, z: -1031},
    {x: 87, z: -583},
    {x: -288, z: -625},
    {x: 265, z: -501},
    {x: -850, z: -134},
    {x: -1094, z: -74},
    {x: -576, z: -190},
    {x: -605, z: 98},
    {x: -964, z: 293},
    {x: -1084, z: -554},
    {x: -899, z: -628},
    {x: -589, z: -716},
    {x: -992, z: -962},
    {x: -754, z: -1087}
  ];
  var ATTACKANIMATIONS = {
    'broxss': Examples.smoke,
    'brosqli': Examples.smoke,
    'brotunnel': Examples.smoke,
  };
  var WIDTH  = window.innerWidth;
  var HEIGHT = window.innerHeight;
  var SPEED = 0.01;
  var OPENNAV = 'cbp-spmenu-open';

  var geometry = null;
  var scene = null;
  var camera = null;
  var renderer = null;
  var material = null;
  var json = null;
  var geometry = null;
  var controls = null;
  var clock = null;
  var mesh = null;
  var spotlight = null;
  var loader = null;
  var projector = null;
  var sceneObjects = [];
  var attackedIds = 0;
  var cssRenderer = null;
  var intersectedObject = null;
  var engine = null;
  var enginesList = [];
  var world = {};
  var jsonData = {};

  function init() {
    Meteor.call('getVrJson', function(err, response) {
      jsonData = JSON.parse(response);
      initMeshes();
      setCamera();
      setLights();
      setRenderers();
      setStats();

      document.getElementById("container").appendChild(renderer.domElement);
      document.getElementById("container").appendChild(cssRenderer.domElement);
    });
  }

  function initVariables() {
    clock = new THREE.Clock();
    scene = new THREE.Scene();
    loader = new THREE.JSONLoader();
    camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 10000);
    sceneControls = new THREE.TrackballControls(camera);
    spotLight = new THREE.SpotLight(0xffffff, 1);
    renderer = new THREE.WebGLRenderer({ antialias: true });
    projector = new THREE.Projector();
    cssRenderer = new THREE.CSS3DRenderer();
    controls = new THREE.OrbitControls(camera);
    stats = new Stats();
  }

  function restartEngine(parameters, x, z) {
    parameters.positionBase.x=x;
    parameters.positionBase.z=z;

    engine = new ParticleEngine();
    engine.setValues(parameters);
    engine.initialize(scene);

    enginesList.push(engine);
  }

  function setStats() {
    stats.domElement.style.position = 'absolute';
    stats.domElement.style.bottom = '0px';
    stats.domElement.style.zIndex = 100;
  }

  function setCamera() {
    camera.position.set(-39.52908903855581, -4.352138336979161, 40.70626794923796);
    var lookAt = { x: -30.52908903855581, y: -4.352138336979161, z: 37.70626794923796 }
    camera.lookAt(lookAt);
  }

  function setRenderers() {
    renderer.setSize(WIDTH, HEIGHT);
    renderer.shadowMapEnabled = true;  // enable shadows

    cssRenderer.setSize(WIDTH, HEIGHT);
    cssRenderer.domElement.style.position = 'absolute';
    cssRenderer.domElement.style.top = 0;
  }

  function setLights() {
    spotLight.position.set( 100, 10000, 100 );
    scene.add(spotLight);
    spotLight.castShadow = true;
  }

  function initMeshes() {
    json = loader.parse(jsonData);
    geometry = json.geometry;
    material = new THREE.MeshPhongMaterial(json.materials);
    for (var i = 0; i < MESHPROPERTIES.count; i++) {
      mesh = new THREE.Mesh(geometry, material);
      mesh.scale.x = mesh.scale.y = mesh.scale.z = 50.75;
      mesh.translation = THREE.GeometryUtils.center(geometry);
      mesh.castShadow = true;
      mesh.position.copy(MESHPROPERTIES.position[i]);
      mesh.rotation.y = MESHPROPERTIES.rotationY[i];
      scene.add(mesh);
    }
  }

  function update() {
    controls.update();
    stats.update();
    enginesList.forEach(function(engine) {
      engine.update(0.01*0.5);
    });
  }

  function render() {
    requestAnimationFrame(render);
    update();
    renderer.render(scene, camera);
    cssRenderer.render(scene, camera);
  }

  function parsedb() {
    Meteor.subscribe("attackers-summary-yash", onReady = function() {

      attackers.find().forEach(function(element) {
        // TODO: Take care of timestamp
        element.events.forEach(function(evt) {
          var evtHost = evt.documentsource.details.host;
          var doc = evt.documentsource;
          doc.id = evt.documentid;
          if (evtHost == undefined) {
            return;
          }
          if (world[evtHost]) {
            world[evtHost].push(doc);
          } else {
            world[evtHost] = [doc];
            // TODO: Is the below line required
            world[evtHost].rank = attackedIds++;
            // world[evtHost].host = evtHost || 'hard-coded';
          }
        });
      });

      console.log(world);

      var attacks = Object.keys(world).sort(function(prev, current) {
        return world[current].length - world[prev].length;
      });
      console.log('attacks', attacks);
      attacks.forEach(function(host, index) {
        var attackRank = world[host].rank;
        // Create enclosing transparent sphere
        var sphereGeometry = new THREE.SphereGeometry(70);
        var sphereMaterial = new THREE.MeshBasicMaterial({ transparent: true, opacity: 0 });
        // var sphereMaterial = new THREE.MeshBasicMaterial();
        var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
        sphere.position.x = RANKCOORDINATES[attackRank].x;
        sphere.position.z = RANKCOORDINATES[attackRank].z;
        sphere.name = "EnclosingSphere" + attackRank;
        sphere.rank = attackRank;
        sphere.host = host || 'hard-coded';
        sphere.attacks = [];

        world[host].forEach(function(attack) {
          if (typeof attack === "object") {
            attackType = attack.category;
            console.log("attacks - ", attackType);
            sphere.attacks.push(attack);
            if (Object.keys(ATTACKANIMATIONS).indexOf(attackType) > -1) {
              mappedAttack = ATTACKANIMATIONS[attackType];
              restartEngine(mappedAttack, RANKCOORDINATES[index].x, RANKCOORDINATES[index].z);
              console.log(RANKCOORDINATES[index].x, RANKCOORDINATES[index].z);
            }
          }
        });

        sceneObjects.push(sphere);
        scene.add(sphere);
      });

    });
  }

  Template.vr.created = function () {
    initVariables();
  };

  Template.vr.rendered = function () {
    init();
    render();
    parsedb();
  };//end template.attackers.rendered

  Template.vr.helpers({
    hostAttacks: function() {
      var hostAttacks = Session.get('hostAttacks');
      if (hostAttacks) {
        hostAttacks.attacks.forEach(function(attack, index) {
          attack.index = index;
        });
        return hostAttacks;
      }
    },
    attackDetails: function() {
      return Session.get('attackDetails');
    },
    displayIndex: function(index) {
      return index + 1
    }
  });

  Template.vr.events({

    "click #container": function(e) {
      var mouse = {
        x: (e.clientX / WIDTH)*2 - 1,
        y: (e.clientY / HEIGHT)*2 - 1
      };
      var mouseVector = new THREE.Vector3(mouse.x, mouse.y, 0.5);
      projector.unprojectVector(mouseVector, camera);
      var raycaster = new THREE.Raycaster(camera.position, mouseVector.sub( camera.position).normalize() );
      var intersects = raycaster.intersectObjects(sceneObjects, true);
      var sideNav = $('#attack-sidenav');
      console.log(intersects);

      if (intersects.length) {
        intersects.forEach(function(intersect) {
          // console.log(intersect);
          var attackRank = intersect.object.rank;
          var attackRegion = intersect.object.host;
          var attacks = intersect.object.attacks;
          if (typeof attackRank !== "undefined") {
            var sessionAttackObj = {
              host: attackRegion,
              rank: attackRank,
              attacks: attacks
            };
            Session.set('hostAttacks', sessionAttackObj);
            // Open the nav if not already opened
            if (!sideNav.hasClass(OPENNAV)) {
              sideNav.addClass(OPENNAV);
            }
          }
        });
      }
      else if(sideNav.hasClass(OPENNAV)) {
        sideNav.removeClass(OPENNAV);
      }
    },

  "mousemove": function(e) {
      var mouse = {
        x: (e.clientX / WIDTH)*2 - 1,
        y: (e.clientY / HEIGHT)*2 - 1
      };
      var mouseVector = new THREE.Vector3(mouse.x, mouse.y, 0.5);
      projector.unprojectVector(mouseVector, camera);
      var raycaster = new THREE.Raycaster(camera.position, mouseVector.sub( camera.position).normalize() );
      var intersects = raycaster.intersectObjects(sceneObjects, true);

      $('body').removeClass('mousepointer');

      if (intersects.length) {
        intersects.forEach(function(intersect) {
          var attackRank = intersect.object.rank;
          if (typeof attackRank !== "undefined") {
            $('body').addClass('mousepointer');
          }
        });
      }
    },

    "change .cbox": function(event) {
      var isChecked = $('.cbox').is(':checked');
      var attackId = Session.get('attackDetails').id;
      console.log(attackId, isChecked);
      if (isChecked) {
        // attackers.update()
      }
      else {

      }
    },

    "click .attacks-list-item": function(event) {
      var attackIndex = event.target.getAttribute('data-index');
      var hostName = document.getElementById('attacks-host').innerText;
      var attackDetails = world[hostName][attackIndex];
      console.log(attackDetails);
      Session.set('attackDetails', attackDetails);
      $('#specific-attack-details').slideToggle();
      $('#attacks-list').slideToggle();
    },

    "click .back-button": function() {
      $('#specific-attack-details').slideToggle();
      $('#attacks-list').slideToggle();
    },

    "click .blockip": function(e,t){
      Session.set('blockIPipaddress',($(e.target).attr('data-ipaddress')));
      //disable and hook to re-enable the scene controls so they don't grab the mouse and use it
      sceneControls.enabled = false;
      controls.enabled = false;
      console.log("BLCOK OPPP");
      $('#modalBlockIPWindow').on('hidden', function () {
          sceneControls.enabled=true;
          controls.enabled = true;
      });
      $('#modalBlockIPWindow').modal();
    },

  });

  Template.vr.destroyed = function () {
    container.removeChild(renderer.domElement);
    scene = null;
    camera = null;
    renderer = null;
    WIDTH  = window.innerWidth;
    HEIGHT = window.innerHeight;
    SPEED = 0.01;
  };//end template.attackers.destroyed

}
<commit_msg>Read/Unread feature synchronisation with Mongo<commit_after>/*
 This Source Code Form is subject to the terms of the Mozilla Public
 License, v. 2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.
 Copyright (c) 2014 Mozilla Corporation

 Contributors:
 Jeff Bryner jbryner@mozilla.com
 Anthony Verez averez@mozilla.com
 Sanchit Kapoor sanchitlucknow@gmail.com
 Yash Mehrotra yashmehrotra95@gmail.com
 Avijit Gupta 526avijit@gmail.com
 */

if (Meteor.isClient) {

  var MESHPROPERTIES = {
    count: 4,
    position: [
      {x: 0, y: 0, z: 0},
      {x: -800, y: -20, z: 0},
      {x: -800, y: -20, z: -800},
      {x: 0 , y: -20, z: -800}
    ],
    rotationY: [
      0,
      0,
      Math.PI/2,
      Math.PI/2
    ]
  };

  // TODO: WHY_NO_UNDERSCORE @avijit
  var RANKCOORDINATES = [
    {x: -286, z: -115},
    {x: -15, z: 11},
    {x: -234, z: 232},
    {x: -69, z: -142},
    {x: 124, z: 293},
    {x: 153, z: -869},
    {x: 124, z: -1122},
    {x: -261, z: -1031},
    {x: 87, z: -583},
    {x: -288, z: -625},
    {x: 265, z: -501},
    {x: -850, z: -134},
    {x: -1094, z: -74},
    {x: -576, z: -190},
    {x: -605, z: 98},
    {x: -964, z: 293},
    {x: -1084, z: -554},
    {x: -899, z: -628},
    {x: -589, z: -716},
    {x: -992, z: -962},
    {x: -754, z: -1087}
  ];
  var ATTACKANIMATIONS = {
    'broxss': Examples.smoke,
    'brosqli': Examples.smoke,
    'brotunnel': Examples.smoke,
  };
  var WIDTH  = window.innerWidth;
  var HEIGHT = window.innerHeight;
  var SPEED = 0.01;
  var OPENNAV = 'cbp-spmenu-open';

  var geometry = null;
  var scene = null;
  var camera = null;
  var renderer = null;
  var material = null;
  var json = null;
  var geometry = null;
  var controls = null;
  var clock = null;
  var mesh = null;
  var spotlight = null;
  var loader = null;
  var projector = null;
  var sceneObjects = [];
  var attackedIds = 0;
  var cssRenderer = null;
  var intersectedObject = null;
  var engine = null;
  var enginesList = [];
  var world = {};
  var jsonData = {};

  function init() {
    Meteor.call('getVrJson', function(err, response) {
      jsonData = JSON.parse(response);
      initMeshes();
      setCamera();
      setLights();
      setRenderers();
      setStats();

      document.getElementById("container").appendChild(renderer.domElement);
      document.getElementById("container").appendChild(cssRenderer.domElement);
    });
  }

  function initVariables() {
    clock = new THREE.Clock();
    scene = new THREE.Scene();
    loader = new THREE.JSONLoader();
    camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 10000);
    sceneControls = new THREE.TrackballControls(camera);
    spotLight = new THREE.SpotLight(0xffffff, 1);
    renderer = new THREE.WebGLRenderer({ antialias: true });
    projector = new THREE.Projector();
    cssRenderer = new THREE.CSS3DRenderer();
    controls = new THREE.OrbitControls(camera);
    stats = new Stats();
  }

  function restartEngine(parameters, x, z) {
    parameters.positionBase.x=x;
    parameters.positionBase.z=z;

    engine = new ParticleEngine();
    engine.setValues(parameters);
    engine.initialize(scene);

    enginesList.push(engine);
  }

  function setStats() {
    stats.domElement.style.position = 'absolute';
    stats.domElement.style.bottom = '0px';
    stats.domElement.style.zIndex = 100;
  }

  function setCamera() {
    camera.position.set(-39.52908903855581, -4.352138336979161, 40.70626794923796);
    var lookAt = { x: -30.52908903855581, y: -4.352138336979161, z: 37.70626794923796 }
    camera.lookAt(lookAt);
  }

  function setRenderers() {
    renderer.setSize(WIDTH, HEIGHT);
    renderer.shadowMapEnabled = true;  // enable shadows

    cssRenderer.setSize(WIDTH, HEIGHT);
    cssRenderer.domElement.style.position = 'absolute';
    cssRenderer.domElement.style.top = 0;
  }

  function setLights() {
    spotLight.position.set( 100, 10000, 100 );
    scene.add(spotLight);
    spotLight.castShadow = true;
  }

  function initMeshes() {
    json = loader.parse(jsonData);
    geometry = json.geometry;
    material = new THREE.MeshPhongMaterial(json.materials);
    for (var i = 0; i < MESHPROPERTIES.count; i++) {
      mesh = new THREE.Mesh(geometry, material);
      mesh.scale.x = mesh.scale.y = mesh.scale.z = 50.75;
      mesh.translation = THREE.GeometryUtils.center(geometry);
      mesh.castShadow = true;
      mesh.position.copy(MESHPROPERTIES.position[i]);
      mesh.rotation.y = MESHPROPERTIES.rotationY[i];
      scene.add(mesh);
    }
  }

  function update() {
    controls.update();
    stats.update();
    enginesList.forEach(function(engine) {
      engine.update(0.01*0.5);
    });
  }

  function render() {
    requestAnimationFrame(render);
    update();
    renderer.render(scene, camera);
    cssRenderer.render(scene, camera);
  }

  function parsedb() {
    Meteor.subscribe("attackers-summary-yash", onReady = function() {

      attackers.find().forEach(function(element) {
        // TODO: Take care of timestamp
        element.events.forEach(function(evt) {
          var evtHost = evt.documentsource.details.host;
          var doc = evt.documentsource;
          doc.id = evt.documentid;
          if (evtHost == undefined) {
            return;
          }
          if (world[evtHost]) {
            world[evtHost].push(doc);
          } else {
            world[evtHost] = [doc];
            // TODO: Is the below line required
            world[evtHost].rank = attackedIds++;
            // world[evtHost].host = evtHost || 'hard-coded';
          }
        });
      });

      console.log(world);

      var attacks = Object.keys(world).sort(function(prev, current) {
        return world[current].length - world[prev].length;
      });
      console.log('attacks', attacks);
      attacks.forEach(function(host, index) {
        var attackRank = world[host].rank;
        // Create enclosing transparent sphere
        var sphereGeometry = new THREE.SphereGeometry(70);
        var sphereMaterial = new THREE.MeshBasicMaterial({ transparent: true, opacity: 0 });
        // var sphereMaterial = new THREE.MeshBasicMaterial();
        var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
        sphere.position.x = RANKCOORDINATES[attackRank].x;
        sphere.position.z = RANKCOORDINATES[attackRank].z;
        sphere.name = "EnclosingSphere" + attackRank;
        sphere.rank = attackRank;
        sphere.host = host || 'hard-coded';
        sphere.attacks = [];

        world[host].forEach(function(attack) {
          if (typeof attack === "object") {
            attackType = attack.category;
            console.log("attacks - ", attackType);
            sphere.attacks.push(attack);
            if (Object.keys(ATTACKANIMATIONS).indexOf(attackType) > -1) {
              mappedAttack = ATTACKANIMATIONS[attackType];
              restartEngine(mappedAttack, RANKCOORDINATES[index].x, RANKCOORDINATES[index].z);
              console.log(RANKCOORDINATES[index].x, RANKCOORDINATES[index].z);
            }
          }
        });

        sceneObjects.push(sphere);
        scene.add(sphere);
      });

    });
  }

  Template.vr.created = function () {
    initVariables();
  };

  Template.vr.rendered = function () {
    init();
    render();
    parsedb();
  };//end template.attackers.rendered

  Template.vr.helpers({
    hostAttacks: function() {
      var hostAttacks = Session.get('hostAttacks');
      if (hostAttacks) {
        hostAttacks.attacks.forEach(function(attack, index) {
          attack.index = index;
        });
        return hostAttacks;
      }
    },
    attackDetails: function() {
      return Session.get('attackDetails');
    },
    displayIndex: function(index) {
      return index + 1
    }
  });

  Template.vr.events({

    "click #container": function(e) {
      var mouse = {
        x: (e.clientX / WIDTH)*2 - 1,
        y: (e.clientY / HEIGHT)*2 - 1
      };
      var mouseVector = new THREE.Vector3(mouse.x, mouse.y, 0.5);
      projector.unprojectVector(mouseVector, camera);
      var raycaster = new THREE.Raycaster(camera.position, mouseVector.sub( camera.position).normalize() );
      var intersects = raycaster.intersectObjects(sceneObjects, true);
      var sideNav = $('#attack-sidenav');
      console.log(intersects);

      if (intersects.length) {
        intersects.forEach(function(intersect) {
          // console.log(intersect);
          var attackRank = intersect.object.rank;
          var attackRegion = intersect.object.host;
          var attacks = intersect.object.attacks;
          if (typeof attackRank !== "undefined") {
            var sessionAttackObj = {
              host: attackRegion,
              rank: attackRank,
              attacks: attacks
            };
            Session.set('hostAttacks', sessionAttackObj);
            // Open the nav if not already opened
            if (!sideNav.hasClass(OPENNAV)) {
              sideNav.addClass(OPENNAV);
            }
          }
        });
      }
      else if(sideNav.hasClass(OPENNAV)) {
        sideNav.removeClass(OPENNAV);
      }
    },

  "mousemove": function(e) {
      var mouse = {
        x: (e.clientX / WIDTH)*2 - 1,
        y: (e.clientY / HEIGHT)*2 - 1
      };
      var mouseVector = new THREE.Vector3(mouse.x, mouse.y, 0.5);
      projector.unprojectVector(mouseVector, camera);
      var raycaster = new THREE.Raycaster(camera.position, mouseVector.sub( camera.position).normalize() );
      var intersects = raycaster.intersectObjects(sceneObjects, true);

      $('body').removeClass('mousepointer');

      if (intersects.length) {
        intersects.forEach(function(intersect) {
          var attackRank = intersect.object.rank;
          if (typeof attackRank !== "undefined") {
            $('body').addClass('mousepointer');
          }
        });
      }
    },

    "change .cbox": function(event) {
      var isChecked = $('.cbox').is(':checked');
      var attackId = Session.get('attackDetails').id;
      var setModifier = { $set: {}};
      var element = attackers.findOne({"events.documentid": attackId});

      element.events.forEach(function(evt, index) {
        if (evt.documentid === attackId) {
          setModifier.$set['events.' + index + '.read'] = isChecked;
          attackers.update({'_id': element._id}, setModifier);
        }
      });
    },

    "click .attacks-list-item": function(event) {
      var attackIndex = event.target.getAttribute('data-index');
      var hostName = document.getElementById('attacks-host').innerText;
      var attackDetails = world[hostName][attackIndex];
      console.log(attackDetails);
      Session.set('attackDetails', attackDetails);
      $('#specific-attack-details').slideToggle();
      $('#attacks-list').slideToggle();
    },

    "click .back-button": function() {
      $('#specific-attack-details').slideToggle();
      $('#attacks-list').slideToggle();
    },

    "click .blockip": function(e,t){
      Session.set('blockIPipaddress',($(e.target).attr('data-ipaddress')));
      //disable and hook to re-enable the scene controls so they don't grab the mouse and use it
      sceneControls.enabled = false;
      controls.enabled = false;
      console.log("BLCOK OPPP");
      $('#modalBlockIPWindow').on('hidden', function () {
          sceneControls.enabled=true;
          controls.enabled = true;
      });
      $('#modalBlockIPWindow').modal();
    },

  });

  Template.vr.destroyed = function () {
    container.removeChild(renderer.domElement);
    scene = null;
    camera = null;
    renderer = null;
    WIDTH  = window.innerWidth;
    HEIGHT = window.innerHeight;
    SPEED = 0.01;
  };//end template.attackers.destroyed

}
<|endoftext|>


<commit_before>import {expect} from 'chai'
import {ENV_NAME, TEST_SERVICE_NAME} from '../../environment'
import Automator from '../../util/cli-automator'

export default function () {

  this.When(/I get the internal port for port ([0-9]*) for the service using the CLI$/, async function (port) {
    this.port = await Automator.spawn(['-e', ENV_NAME, 'port', TEST_SERVICE_NAME, port], {
      env: {
        NAVY_DEBUG: 'null',
      },
    }).waitForDone()
  })

  this.Then(/I should see the port using the CLI$/, function () {
    expect(this.port).to.be.a.number
  })

  this.Then(/I shouldn't see the port using the CLI$/, function () {
    expect(this.port).to.equal('')
  })

}
<commit_msg>Fix port cli integration test<commit_after>import {expect} from 'chai'
import {ENV_NAME, TEST_SERVICE_NAME} from '../../environment'
import Automator from '../../util/cli-automator'

export default function () {

  this.When(/I get the internal port for port ([0-9]*) for the service using the CLI$/, async function (port) {
    this.port = await Automator.spawn(['-e', ENV_NAME, 'port', TEST_SERVICE_NAME, port], {
      env: {
        ...process.env,
        NAVY_DEBUG: 'null',
      },
    }).waitForDone()
  })

  this.Then(/I should see the port using the CLI$/, function () {
    expect(this.port).to.be.a.number
  })

  this.Then(/I shouldn't see the port using the CLI$/, function () {
    expect(this.port).to.equal('')
  })

}
<|endoftext|>