<commit_before>function makeData() {
  "use strict";
  return d3.csv("../../examples/data/hygxyzTruncated.csv");
}

function run(div, data, Plottable) {
  "use strict";
  d3.csv("../../examples/data/hygxyzTruncated.csv", function(d) {
  var svg = div.append("svg").attr("height", 500);
  var xScale = new Plottable.Scale.Linear();
  var yScale = new Plottable.Scale.ModifiedLog();
  var rScale = new Plottable.Scale.Linear();
  var colorScale = new Plottable.Scale.Color();

  var xAxis = new Plottable.Axis.Numeric(xScale, "bottom");
  var yAxis = new Plottable.Axis.Numeric(yScale, "left");
  var scatterRenderer = new Plottable.Plot.Scatter(d, xScale, yScale)
    .project("x", "Distance", xScale)
    .project("y", function(d) {return Math.abs(d.Mag)}, yScale)
    .project("r", function(d) {return Math.abs(d.AbsMag)})
    .project("fill", "ColorIndex", colorScale);

  var titleLabel = new Plottable.Component.TitleLabel("Absolute Value of Absolute Visual Magnitudes of Stars");
  var subtitleLabel = new Plottable.Component.Label("Data from The HYG Database at The Astronomy Nexus");
  var titleTable = new Plottable.Component.Table([
                                                  [titleLabel],
                                                  [subtitleLabel]
                                                  ]).xAlign("center");

  var yAxisLabel = new Plottable.Component.AxisLabel("Absolute Value of Apparent Visual Magnitude", "vertical-left");
  var xAxisLabel = new Plottable.Component.AxisLabel("Distance in parsecs");
  var plotTable = new Plottable.Component.Table([
                                                 [yAxisLabel, yAxis, scatterRenderer],
                                                 [null, null, xAxis],
                                                 [null, null, xAxisLabel]
                                                 ]);

  new Plottable.Component.Table([
                                 [titleTable],
                                 [plotTable]
                                 ]).renderTo(svg);
  });
}<commit_msg>Colors are more accurate<commit_after>function makeData() {
  "use strict";
  return d3.csv("../../examples/data/hygxyzTruncated.csv");
}

function run(div, data, Plottable) {
  "use strict";
  d3.csv("../../examples/data/hygxyzTruncated.csv", function(d) {
  var svg = div.append("svg").attr("height", 500);
  var xScale = new Plottable.Scale.Linear();
  var yScale = new Plottable.Scale.ModifiedLog();
  var rScale = new Plottable.Scale.Linear();
  var colorScale = new Plottable.Scale.InterpolatedColor(["blue", "red"]).domain([-0.33, 1.4]);

  var xAxis = new Plottable.Axis.Numeric(xScale, "bottom");
  var yAxis = new Plottable.Axis.Numeric(yScale, "left");
  var scatterRenderer = new Plottable.Plot.Scatter(d, xScale, yScale)
    .project("x", "Distance", xScale)
    .project("y", function(d) {return Math.abs(d.Mag)}, yScale)
    .project("r", function(d) {return Math.abs(d.AbsMag)})
    .project("fill", "ColorIndex", colorScale);

  var titleLabel = new Plottable.Component.TitleLabel("Absolute Value of Absolute Visual Magnitudes of Stars");
  var subtitleLabel = new Plottable.Component.Label("Data from The HYG Database at The Astronomy Nexus");
  var titleTable = new Plottable.Component.Table([
                                                  [titleLabel],
                                                  [subtitleLabel]
                                                  ]).xAlign("center");

  var yAxisLabel = new Plottable.Component.AxisLabel("Absolute Value of Apparent Visual Magnitude", "vertical-left");
  var xAxisLabel = new Plottable.Component.AxisLabel("Distance in parsecs");
  var plotTable = new Plottable.Component.Table([
                                                 [yAxisLabel, yAxis, scatterRenderer],
                                                 [null, null, xAxis],
                                                 [null, null, xAxisLabel]
                                                 ]);

  new Plottable.Component.Table([
                                 [titleTable],
                                 [plotTable]
                                 ]).renderTo(svg);
  });
}<|endoftext|>


<commit_before>var divEl = document.getElementById('testdiv');
divEl.innerHTML = "Onload not required";
divEl.style.color = 'red';

window.onmessage = (event) => {
  divEl = document.getElementById('testdiv');
  divEl.innerHTML = "messages arriving";
  divEl.style.color = 'green';
};

window.onload = function() {

//   var divEl = document.getElementById('testdiv');
//   divEl.innerHTML = "Onload happened";
//   divEl.style.color = 'blue';

//   window.onmessage = (event) => {
//     divEl = document.getElementById('testdiv');
//     divEl.innerHTML = "messages arriving";
//     divEl.style.color = 'green';
//
//     console.log("C1 message received from parent");
//     if (event.data) {
//       // console.log(JSON.stringify(event));
//       // console.log(JSON.stringify(event.data));
//
//       if (event.data.action === "Init") {
//           initUI(event.data.content);
//       } else if (event.data.action === "Freeze") {
//           console.log("C1 Freeze request");
//           setFrozen(true);
//       } else if (event.data.action === "Unfreeze") {
//           console.log("C1 Unfreeze request");
//           setFrozen(false);
//       } else if (event.data.action === "Remove") {
//           removeIngredient(event.data.content);
//       }
//     }
//   }
}

const assets = "https://alexlamb.github.io/js/assets/"
// const assets = "assets/"
const leftChev = "chevron-left.png";
const rightChev = "chevron-right.png";
const width = 1000;
const height = 130;
const optionsWidth = width - 100;
const optionOffset = 45;
const itemsPerPage = 6;
const itemWidth = 150;
const itemHeight = 100;

var optionButtons = [];
var optionBorders = [];
var optionRects = [];
var optionShades = [];
var buttons;
var state;
var buttonData;
var frozen = false;
var shift = 0;
var pages = 1;
var page = 0;
// var selected = 0;

var leftChevron;
var rightChevron;

function initUI(data) {
    buttonData = data;
    state = new Array(data.length);
    state.fill(0);

    pages = Math.floor((data.length * itemWidth) / optionsWidth);
    console.log("C1 pages:"+pages);

    frozen = false;

    var buttonSideW = itemWidth * 3 / 4;
    var buttonSideH = itemHeight * 3 / 4;
    var buttonRimW = (itemWidth - buttonSideW) / 2;
    var buttonRimH = (itemHeight - buttonSideH) / 2;
    var borderSideW = itemWidth * 5 / 6;
    var borderSideH = itemHeight * 5 / 6;
    var borderRimW = (itemWidth - borderSideW) / 2;
    var borderRimH = (itemHeight - borderSideH) / 2;

    var svgNode = document.getElementById("svgCanvas");
    while (svgNode.firstChild) {
        svgNode.removeChild(svgNode.firstChild);
    }

    draw = SVG('svgCanvas').size(width, height);
    draw.rect(width, height).fill("#F0F0F0");
    buttons = draw.group();
    edges = draw.group();

    for (let i = 0; i < data.length; i++) {
        var item = data[i];

        let optionRect = buttons.rect(borderSideW,borderSideH).fill('none');
        optionRect.move(borderRimW+(optionOffset+i*itemWidth),borderRimH);
        optionRect.radius(15);
        optionRects.push(optionRect);

        let optionShade = buttons.rect(borderSideW,borderSideH).fill('none');
        optionShade.move(borderRimW+(optionOffset+i*itemWidth),borderRimH);
        optionShade.radius(15);
        optionShades.push(optionShade);

        let optionButton = buttons.image(assets+data[i].image,buttonSideW,buttonSideH);
        optionButtons.push(optionButton);
        optionButton.move(buttonRimW+(optionOffset+i*itemWidth),buttonRimH);

        optionButton.style('cursor', 'pointer');
        optionButton.click(function() {selectOption(i)});
        optionButton.mouseover(function() {highlightOption(i)});
        optionButton.mouseout(function() {fadeOption(i)});

        let optionBorder = buttons.rect(borderSideW,borderSideH);
        optionBorders.push(optionBorder);
        optionBorder.fill('none').stroke({color: 'Silver', width: 1});
        optionBorder.move(borderRimW+(optionOffset+i*itemWidth),borderRimH);
        optionBorder.radius(15);

        let optionText = buttons.text(data[i].name);
        let length = optionText.length();
        let adjust = (borderSideW - length)/2;
        optionText.move(borderRimW+(optionOffset+i*itemWidth)+adjust,borderRimH+borderSideH+10);
        optionText.fill('Black');
    }

    leftEdge = edges.rect(optionOffset, height);
    leftEdge.fill('#F0F0F0');
    leftEdge.click(function() {pageLeft()});
    // leftIm = edges.image(assets+leftChev,optionOffset, height);
    // leftIm.click(function() {pageLeft()});

    rightEdge = edges.rect(optionOffset, height).move(width-(optionOffset),0);
    rightEdge.fill('#F0F0F0');
    rightEdge.click(function() {pageRight()});

    // rimX = edges.rect(width,height);
    // rimX.fill('none').stroke('Silver');

    const chevronL = optionOffset/2 - 10;
    const chevronR = optionOffset/2 + 10;
    const chevronT = height/2 - 18;
    const chevronB = height/2 + 18;

    let leftPathString = "M "+chevronR+" "+chevronT+" ";
    leftPathString += "L "+chevronL+" "+(height/2)+" ";
    leftPathString += "L "+chevronR+" "+chevronB+" ";
    leftChevron = edges.path(leftPathString);
    let chevStroke = {
        width:4,
        color:'Gray',
        linecap:'round'
    };

    leftChevron.fill('none').stroke(chevStroke);

    let rightPathString = "M "+chevronL+" "+chevronT+" ";
    rightPathString += "L "+chevronR+" "+(height/2)+" ";
    rightPathString += "L "+chevronL+" "+chevronB+" ";
    rightChevron = edges.path(rightPathString);
    rightChevron.fill('none').stroke(chevStroke);
    rightChevron.dmove(width-(optionOffset+5),0);

    // updateChevrons();
}

function highlightOption(i) {
    console.log("C1 highlight:"+i);
    if (!frozen || state[i] > 0) {
        optionShades[i].animate(5).fill('White');
    }
}

function fadeOption(i) {
    console.log("C1 fade:"+i+" frozen:"+frozen+" state:"+state[i]+" func:"+(!frozen || state[i] > 1));
    if (!frozen || state[i] > 0) {
        console.log("C1 fading");
        optionShades[i].animate(5).fill('none');
    }
}

function pageLeft() {
    if (page > 0) {
        page--;
        buttons.animate(250).dmove(itemWidth*itemsPerPage,0);
        // updateChevrons();
    } else {
        page = pages - 1;
        buttons.dmove(-itemWidth*itemsPerPage*pages,0);
        buttons.animate(250).dmove(itemWidth*itemsPerPage,0);
    }
    console.log("C1 page:"+page+" shift:"+buttons.x());
}

function pageRight() {
    if (page < pages-1) {
        page++;
        buttons.animate(250).dmove(-itemWidth*itemsPerPage,0);
        // updateChevrons();
    } else {
        page = 0;
        buttons.dmove(itemWidth*itemsPerPage*pages,0);
        buttons.animate(250).dmove(-itemWidth*itemsPerPage,0);
    }
    console.log("C1 page:"+page+" shift:"+buttons.x());
}

// function updateChevrons() {
//     console.log("page:"+page+" pages:"+pages);
//     if (page == 0) {
//         leftChevron.stroke('none');
//     } else {
//         leftChevron.stroke('Gray');
//     }
//     if (page == pages - 1) {
//         rightChevron.stroke('none');
//     } else {
//         rightChevron.stroke('Gray');
//     }
// }

function setFrozen(value) {
    console.log("C1 setFrozen");
    frozen = value;

    for (let i = 0; i < state.length; i++) {
        if (state[i] == 0) {
            if (frozen) {
                // optionBorders[i].stroke('DimGray');
                optionRects[i].fill('DimGray');
            } else {
                // optionBorders[i].stroke('Silver');
                optionRects[i].fill('none');
            }
        }
    }
}

function selectOption(i) {

    let sendMessage = false;

    console.log("C1 selectOption:"+i);
    // if (state[i] == 0 && !frozen && selected < 5) {
    if (state[i] == 0 && !frozen) {
        optionBorders[i].stroke({color:'#52009A', width:2});
        optionRects[i].fill('#BAB6CA');
        state[i] = 1;
        sendMessage = true;
        // selected++;
        // if (selected >= 5) {
        //     setFrozen(true);
        // }

    // } else if (state[i] > 0 && selected < 5) {
    } else if (state[i] > 0) {
        optionBorders[i].stroke({color:'Silver', width:1});
        console.log("C1 Unfreezing");
        state[i] = 0;
        setFrozen(false);
        sendMessage = true;
        // selected--;
    }

    if (sendMessage) {
        var message = {
            action: "UpdateSelection",
            selection: state
        };
        window.parent.postMessage(message,"*");
    }
    // console.log("Selected:"+selected);
}

function removeIngredient(data) {
    for (let i = 0; i < data.length; i++) {
        if (data[i] == 0 && state[i] > 0) {

            optionBorders[i].stroke('none');
            console.log("C1 Unfreezing");
            state[i] = 0;
            setFrozen(false);
        }
    }
}
<commit_msg>Update iChild1.js<commit_after>// var divEl = document.getElementById('testdiv');
// divEl.innerHTML = "Onload not required";
// divEl.style.color = 'red';

window.onmessage = (event) => {
  let divEl = document.getElementById('testdiv');
  divEl.innerHTML = "messages arriving";
  divEl.style.color = 'green';
};

window.onload = function() {

//   var divEl = document.getElementById('testdiv');
//   divEl.innerHTML = "Onload happened";
//   divEl.style.color = 'blue';

//   window.onmessage = (event) => {
//     divEl = document.getElementById('testdiv');
//     divEl.innerHTML = "messages arriving";
//     divEl.style.color = 'green';
//
//     console.log("C1 message received from parent");
//     if (event.data) {
//       // console.log(JSON.stringify(event));
//       // console.log(JSON.stringify(event.data));
//
//       if (event.data.action === "Init") {
//           initUI(event.data.content);
//       } else if (event.data.action === "Freeze") {
//           console.log("C1 Freeze request");
//           setFrozen(true);
//       } else if (event.data.action === "Unfreeze") {
//           console.log("C1 Unfreeze request");
//           setFrozen(false);
//       } else if (event.data.action === "Remove") {
//           removeIngredient(event.data.content);
//       }
//     }
//   }
}

const assets = "https://alexlamb.github.io/js/assets/"
// const assets = "assets/"
const leftChev = "chevron-left.png";
const rightChev = "chevron-right.png";
const width = 1000;
const height = 130;
const optionsWidth = width - 100;
const optionOffset = 45;
const itemsPerPage = 6;
const itemWidth = 150;
const itemHeight = 100;

var optionButtons = [];
var optionBorders = [];
var optionRects = [];
var optionShades = [];
var buttons;
var state;
var buttonData;
var frozen = false;
var shift = 0;
var pages = 1;
var page = 0;
// var selected = 0;

var leftChevron;
var rightChevron;

function initUI(data) {
    buttonData = data;
    state = new Array(data.length);
    state.fill(0);

    pages = Math.floor((data.length * itemWidth) / optionsWidth);
    console.log("C1 pages:"+pages);

    frozen = false;

    var buttonSideW = itemWidth * 3 / 4;
    var buttonSideH = itemHeight * 3 / 4;
    var buttonRimW = (itemWidth - buttonSideW) / 2;
    var buttonRimH = (itemHeight - buttonSideH) / 2;
    var borderSideW = itemWidth * 5 / 6;
    var borderSideH = itemHeight * 5 / 6;
    var borderRimW = (itemWidth - borderSideW) / 2;
    var borderRimH = (itemHeight - borderSideH) / 2;

    var svgNode = document.getElementById("svgCanvas");
    while (svgNode.firstChild) {
        svgNode.removeChild(svgNode.firstChild);
    }

    draw = SVG('svgCanvas').size(width, height);
    draw.rect(width, height).fill("#F0F0F0");
    buttons = draw.group();
    edges = draw.group();

    for (let i = 0; i < data.length; i++) {
        var item = data[i];

        let optionRect = buttons.rect(borderSideW,borderSideH).fill('none');
        optionRect.move(borderRimW+(optionOffset+i*itemWidth),borderRimH);
        optionRect.radius(15);
        optionRects.push(optionRect);

        let optionShade = buttons.rect(borderSideW,borderSideH).fill('none');
        optionShade.move(borderRimW+(optionOffset+i*itemWidth),borderRimH);
        optionShade.radius(15);
        optionShades.push(optionShade);

        let optionButton = buttons.image(assets+data[i].image,buttonSideW,buttonSideH);
        optionButtons.push(optionButton);
        optionButton.move(buttonRimW+(optionOffset+i*itemWidth),buttonRimH);

        optionButton.style('cursor', 'pointer');
        optionButton.click(function() {selectOption(i)});
        optionButton.mouseover(function() {highlightOption(i)});
        optionButton.mouseout(function() {fadeOption(i)});

        let optionBorder = buttons.rect(borderSideW,borderSideH);
        optionBorders.push(optionBorder);
        optionBorder.fill('none').stroke({color: 'Silver', width: 1});
        optionBorder.move(borderRimW+(optionOffset+i*itemWidth),borderRimH);
        optionBorder.radius(15);

        let optionText = buttons.text(data[i].name);
        let length = optionText.length();
        let adjust = (borderSideW - length)/2;
        optionText.move(borderRimW+(optionOffset+i*itemWidth)+adjust,borderRimH+borderSideH+10);
        optionText.fill('Black');
    }

    leftEdge = edges.rect(optionOffset, height);
    leftEdge.fill('#F0F0F0');
    leftEdge.click(function() {pageLeft()});
    // leftIm = edges.image(assets+leftChev,optionOffset, height);
    // leftIm.click(function() {pageLeft()});

    rightEdge = edges.rect(optionOffset, height).move(width-(optionOffset),0);
    rightEdge.fill('#F0F0F0');
    rightEdge.click(function() {pageRight()});

    // rimX = edges.rect(width,height);
    // rimX.fill('none').stroke('Silver');

    const chevronL = optionOffset/2 - 10;
    const chevronR = optionOffset/2 + 10;
    const chevronT = height/2 - 18;
    const chevronB = height/2 + 18;

    let leftPathString = "M "+chevronR+" "+chevronT+" ";
    leftPathString += "L "+chevronL+" "+(height/2)+" ";
    leftPathString += "L "+chevronR+" "+chevronB+" ";
    leftChevron = edges.path(leftPathString);
    let chevStroke = {
        width:4,
        color:'Gray',
        linecap:'round'
    };

    leftChevron.fill('none').stroke(chevStroke);

    let rightPathString = "M "+chevronL+" "+chevronT+" ";
    rightPathString += "L "+chevronR+" "+(height/2)+" ";
    rightPathString += "L "+chevronL+" "+chevronB+" ";
    rightChevron = edges.path(rightPathString);
    rightChevron.fill('none').stroke(chevStroke);
    rightChevron.dmove(width-(optionOffset+5),0);

    // updateChevrons();
}

function highlightOption(i) {
    console.log("C1 highlight:"+i);
    if (!frozen || state[i] > 0) {
        optionShades[i].animate(5).fill('White');
    }
}

function fadeOption(i) {
    console.log("C1 fade:"+i+" frozen:"+frozen+" state:"+state[i]+" func:"+(!frozen || state[i] > 1));
    if (!frozen || state[i] > 0) {
        console.log("C1 fading");
        optionShades[i].animate(5).fill('none');
    }
}

function pageLeft() {
    if (page > 0) {
        page--;
        buttons.animate(250).dmove(itemWidth*itemsPerPage,0);
        // updateChevrons();
    } else {
        page = pages - 1;
        buttons.dmove(-itemWidth*itemsPerPage*pages,0);
        buttons.animate(250).dmove(itemWidth*itemsPerPage,0);
    }
    console.log("C1 page:"+page+" shift:"+buttons.x());
}

function pageRight() {
    if (page < pages-1) {
        page++;
        buttons.animate(250).dmove(-itemWidth*itemsPerPage,0);
        // updateChevrons();
    } else {
        page = 0;
        buttons.dmove(itemWidth*itemsPerPage*pages,0);
        buttons.animate(250).dmove(-itemWidth*itemsPerPage,0);
    }
    console.log("C1 page:"+page+" shift:"+buttons.x());
}

// function updateChevrons() {
//     console.log("page:"+page+" pages:"+pages);
//     if (page == 0) {
//         leftChevron.stroke('none');
//     } else {
//         leftChevron.stroke('Gray');
//     }
//     if (page == pages - 1) {
//         rightChevron.stroke('none');
//     } else {
//         rightChevron.stroke('Gray');
//     }
// }

function setFrozen(value) {
    console.log("C1 setFrozen");
    frozen = value;

    for (let i = 0; i < state.length; i++) {
        if (state[i] == 0) {
            if (frozen) {
                // optionBorders[i].stroke('DimGray');
                optionRects[i].fill('DimGray');
            } else {
                // optionBorders[i].stroke('Silver');
                optionRects[i].fill('none');
            }
        }
    }
}

function selectOption(i) {

    let sendMessage = false;

    console.log("C1 selectOption:"+i);
    // if (state[i] == 0 && !frozen && selected < 5) {
    if (state[i] == 0 && !frozen) {
        optionBorders[i].stroke({color:'#52009A', width:2});
        optionRects[i].fill('#BAB6CA');
        state[i] = 1;
        sendMessage = true;
        // selected++;
        // if (selected >= 5) {
        //     setFrozen(true);
        // }

    // } else if (state[i] > 0 && selected < 5) {
    } else if (state[i] > 0) {
        optionBorders[i].stroke({color:'Silver', width:1});
        console.log("C1 Unfreezing");
        state[i] = 0;
        setFrozen(false);
        sendMessage = true;
        // selected--;
    }

    if (sendMessage) {
        var message = {
            action: "UpdateSelection",
            selection: state
        };
        window.parent.postMessage(message,"*");
    }
    // console.log("Selected:"+selected);
}

function removeIngredient(data) {
    for (let i = 0; i < data.length; i++) {
        if (data[i] == 0 && state[i] > 0) {

            optionBorders[i].stroke('none');
            console.log("C1 Unfreezing");
            state[i] = 0;
            setFrozen(false);
        }
    }
}
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.4.0
(function() {
  var getParameter, getPermalinkQuery, getResults, getTemplateOutput, isEmbed, isFormComplete, isNewQuery, isPermalinkPage, printResult, pushState, queryAPI, renderError, renderResults, roundNumber, syncFormWithPermalink;

  $.support.history = !!(window.history && history.pushState);

  Number.prototype.approximate = function() {
    var millions, thousands;
    if (this < 1000) {
      return this;
    }
    thousands = Math.round(this / 100) / 10;
    if (thousands < 1000) {
      return thousands.toString() + 'K';
    }
    millions = Math.round(thousands / 100) / 10;
    return millions.toString() + 'M';
  };

  (function() {
    var Line, animate, draw, easeInOutQuad, init, lines, randomBetween;
    lines = [];
    this.requestAnimFrame = (function() {
      return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, element) {
        return window.setTimeout(callback, 1000 / 60);
      };
    })();
    this.conconjr = function() {
      if (!$('.header').is(':visible')) {
        return;
      }
      init();
      return animate();
    };
    init = function() {
      var $conconjr, context, count, diff, index, maxY, mean, peak, _results;
      $conconjr = $('#conconjr');
      context = $conconjr[0].getContext('2d');
      context.fillStyle = '#dfdfdf';
      this.clear = function() {
        return context.clearRect(0, 0, $conconjr.width(), $conconjr.height());
      };
      context.translate(0, $conconjr.height());
      context.scale(1, -1);
      peak = 30;
      count = index = 50;
      _results = [];
      while (index--) {
        mean = count / 2;
        diff = Math.abs(mean - index);
        maxY = Math.round(Math.pow(Math.abs(mean - diff), 2) * (peak / Math.pow(mean, 2)));
        _results.push(lines.push(new Line({
          height: 0,
          x: index * 5,
          context: context,
          maxY: maxY
        })));
      }
      return _results;
    };
    animate = function() {
      requestAnimFrame(animate);
      return draw();
    };
    easeInOutQuad = function(time, start, change, steps) {
      time /= steps / 2;
      if (time < 1) {
        return change / 2 * time * time + start;
      }
      time--;
      return -change / 2 * (time * (time - 2) - 1) + start;
    };
    randomBetween = function(min, max) {
      return Math.round((Math.random() * (max - min)) + min);
    };
    Line = function(options) {
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        x: 0,
        y: 0,
        width: 3,
        height: 0,
        ease: easeInOutQuad,
        minY: 0,
        maxY: 30,
        minSteps: 15,
        maxSteps: 45
      });
      _.extend(this, options);
      return this.reset();
    };
    _.extend(Line.prototype, {
      change: function() {
        return this.end - this.start;
      },
      reset: function() {
        this.time = 1;
        this.start = this.height;
        this.end = randomBetween(this.minY, this.maxY);
        return this.steps = randomBetween(this.minSteps, this.maxSteps);
      },
      draw: function() {
        this.time++;
        this.height = Math.round(this.ease(this.time, this.start, this.change(), this.steps));
        this.context.fillRect(this.x, this.y, this.width, this.height);
        if (this.height === this.end) {
          return this.reset();
        }
      }
    });
    draw = function() {
      this.clear();
      return _.invoke(lines, 'draw');
    };
    return this.conconjr.draw = draw;
  })();

  roundNumber = function(number, decimals) {
    if (decimals == null) {
      decimals = 0;
    }
    return Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
  };

  getPermalinkQuery = function(query) {
    var conConMap, results;
    results = {};
    conConMap = {
      conversions_control: 'cc',
      samples_control: 'sc',
      conversions_experiment: 'ce',
      samples_experiment: 'se'
    };
    $.map(query, function(value, key) {
      return results[conConMap[key]] = value;
    });
    return results;
  };

  isPermalinkPage = function() {
    if (!getParameter('cc')) {
      return false;
    }
    if (!getParameter('sc')) {
      return false;
    }
    if (!getParameter('ce')) {
      return false;
    }
    if (!getParameter('se')) {
      return false;
    }
    return true;
  };

  getTemplateOutput = function(template, input) {
    var compiled, source;
    source = template.html();
    compiled = Handlebars.compile(source);
    return compiled(input);
  };

  renderError = function(error) {
    var html;
    html = getTemplateOutput($('#error-template'), {
      error: error
    });
    return printResult(html);
  };

  renderResults = function(stat_results, query) {
    var html, percentagize, permalink, results;
    results = [];
    percentagize = function(numbers) {
      var percents;
      percents = {};
      $.each(numbers, function(key, value) {
        var decimals;
        value = 100 * value;
        decimals = value >= 1000 ? 0 : 1;
        return percents[key] = roundNumber(value, decimals);
      });
      return percents;
    };
    permalink = ("http://" + window.location.host + "?") + $.param(getPermalinkQuery(query));
    results.push($.extend({
      title: 'Original',
      chart: stat_results.confidence.chart.control,
      inputs: {
        conversions: parseInt(query.conversions_control, 10).approximate(),
        samples: parseInt(query.samples_control, 10).approximate()
      }
    }, percentagize(stat_results.confidence.results.control)));
    results.push($.extend({
      title: 'Experiment',
      chart: stat_results.confidence.chart.experiment,
      inputs: {
        conversions: parseInt(query.conversions_experiment, 10).approximate(),
        samples: parseInt(query.samples_experiment, 10).approximate()
      }
    }, percentagize(stat_results.confidence.results.experiment)));
    results.push($.extend({
      title: 'Significance',
      chart: stat_results.significance.chart
    }, percentagize({
      average: stat_results.significance.results.experiment
    })));
    results.push($.extend({
      title: 'Improvement',
      chart: stat_results.improvement.chart
    }, percentagize(stat_results.improvement.results)));
    html = getTemplateOutput($('#results-template'), {
      results: results,
      permalink: permalink
    });
    return printResult(html);
  };

  printResult = function(html, options) {
    if (options == null) {
      options = {};
    }
    return $('.results').fadeOut(200, function() {
      return $(this).hide().delay(300).html(html).fadeIn(options.speed);
    });
  };

  pushState = function(query) {
    var url;
    url = '?' + $.param(getPermalinkQuery(query));
    if ($.support.history) {
      return history.pushState(query, '', url);
    }
  };

  isEmbed = function() {
    return !$('.header').is(':visible');
  };

  isNewQuery = function(queryString) {
    return queryString !== window.location.search;
  };

  getResults = function(query, options) {
    var lastQuery, newQuery;
    if (options == null) {
      options = {};
    }
    lastQuery = window.location.search;
    newQuery = '?' + $.param(getPermalinkQuery(query));
    if (!isEmbed() && (isNewQuery(newQuery) || !history.state)) {
      pushState(query);
    }
    if (!options.force && lastQuery === newQuery) {
      return false;
    }
    return queryAPI(query).done(function(stat_results) {
      $('.alert').fadeOut();
      if (stat_results.error) {
        return renderError(stat_results.error);
      }
      $('body').removeClass('home').addClass('permalink');
      return renderResults(stat_results, query);
    });
  };

  syncFormWithPermalink = function() {
    $("input#control-conversions").val(getParameter('cc'));
    $("input#control-samples").val(getParameter('sc'));
    $("input#experiment-conversions").val(getParameter('ce'));
    return $("input#experiment-samples").val(getParameter('se'));
  };

  queryAPI = function(query) {
    return $.getJSON('api?' + $.param(query));
  };

  getParameter = function(paramName) {
    var param, params, searchString, val, _i, _len;
    searchString = window.location.search.substring(1);
    params = searchString.split('&');
    for (_i = 0, _len = params.length; _i < _len; _i++) {
      param = params[_i];
      val = param.split('=');
      if (val[0] === paramName) {
        return unescape(val[1]);
      }
    }
    return null;
  };

  isFormComplete = function() {
    if (!$('input#control-conversions').val()) {
      return false;
    }
    if (!$('input#control-samples').val()) {
      return false;
    }
    if (!$('input#experiment-conversions').val()) {
      return false;
    }
    if (!$('input#experiment-samples').val()) {
      return false;
    }
    return true;
  };

  $(function() {
    if ($.support.history) {
      $(window).on('popstate', function(event) {
        var state;
        state = event.originalEvent.state;
        if (state) {
          getResults(state, {
            force: true
          });
          return syncFormWithPermalink();
        }
      });
    }
    $("form :input:visible:first").focus();
    $("form").on('submit', function(event) {
      event.preventDefault();
      if (!isFormComplete()) {
        return false;
      }
      return getResults({
        conversions_control: $('input#control-conversions').val(),
        samples_control: $('input#control-samples').val(),
        conversions_experiment: $('input#experiment-conversions').val(),
        samples_experiment: $('input#experiment-samples').val()
      });
    });
    if (isPermalinkPage()) {
      syncFormWithPermalink();
      getResults({
        conversions_control: getParameter('cc'),
        samples_control: getParameter('sc'),
        conversions_experiment: getParameter('ce'),
        samples_experiment: getParameter('se')
      }, {
        force: true
      });
    } else {
      $('body').removeClass('permalink').addClass('home');
      $('.alert-info').delay(1400).fadeIn('slow');
    }
    $('form input[type=text]').keyup(function() {
      clearTimeout(this.keyup_timer);
      return this.keyup_timer = setTimeout(function() {
        return $('form').submit();
      }, 800);
    });
    return conconjr();
  });

}).call(this);
<commit_msg>Compile CoffeeScript<commit_after>// Generated by CoffeeScript 1.4.0
(function() {
  var getParameter, getPermalinkQuery, getQueryString, getResults, getTemplateOutput, isEmbed, isFormComplete, isNewQuery, isPermalinkPage, printResult, pushState, queryAPI, renderError, renderResults, roundNumber, syncFormWithPermalink;

  $.support.history = !!(window.history && history.pushState);

  Number.prototype.approximate = function() {
    var millions, thousands;
    if (this < 1000) {
      return this;
    }
    thousands = Math.round(this / 100) / 10;
    if (thousands < 1000) {
      return thousands.toString() + 'K';
    }
    millions = Math.round(thousands / 100) / 10;
    return millions.toString() + 'M';
  };

  (function() {
    var Line, animate, draw, easeInOutQuad, init, lines, randomBetween;
    lines = [];
    this.requestAnimFrame = (function() {
      return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, element) {
        return window.setTimeout(callback, 1000 / 60);
      };
    })();
    this.conconjr = function() {
      if (!$('.header').is(':visible')) {
        return;
      }
      init();
      return animate();
    };
    init = function() {
      var $conconjr, context, count, diff, index, maxY, mean, peak, _results;
      $conconjr = $('#conconjr');
      context = $conconjr[0].getContext('2d');
      context.fillStyle = '#dfdfdf';
      this.clear = function() {
        return context.clearRect(0, 0, $conconjr.width(), $conconjr.height());
      };
      context.translate(0, $conconjr.height());
      context.scale(1, -1);
      peak = 30;
      count = index = 50;
      _results = [];
      while (index--) {
        mean = count / 2;
        diff = Math.abs(mean - index);
        maxY = Math.round(Math.pow(Math.abs(mean - diff), 2) * (peak / Math.pow(mean, 2)));
        _results.push(lines.push(new Line({
          height: 0,
          x: index * 5,
          context: context,
          maxY: maxY
        })));
      }
      return _results;
    };
    animate = function() {
      requestAnimFrame(animate);
      return draw();
    };
    easeInOutQuad = function(time, start, change, steps) {
      time /= steps / 2;
      if (time < 1) {
        return change / 2 * time * time + start;
      }
      time--;
      return -change / 2 * (time * (time - 2) - 1) + start;
    };
    randomBetween = function(min, max) {
      return Math.round((Math.random() * (max - min)) + min);
    };
    Line = function(options) {
      if (options == null) {
        options = {};
      }
      _.defaults(options, {
        x: 0,
        y: 0,
        width: 3,
        height: 0,
        ease: easeInOutQuad,
        minY: 0,
        maxY: 30,
        minSteps: 15,
        maxSteps: 45
      });
      _.extend(this, options);
      return this.reset();
    };
    _.extend(Line.prototype, {
      change: function() {
        return this.end - this.start;
      },
      reset: function() {
        this.time = 1;
        this.start = this.height;
        this.end = randomBetween(this.minY, this.maxY);
        return this.steps = randomBetween(this.minSteps, this.maxSteps);
      },
      draw: function() {
        this.time++;
        this.height = Math.round(this.ease(this.time, this.start, this.change(), this.steps));
        this.context.fillRect(this.x, this.y, this.width, this.height);
        if (this.height === this.end) {
          return this.reset();
        }
      }
    });
    draw = function() {
      this.clear();
      return _.invoke(lines, 'draw');
    };
    return this.conconjr.draw = draw;
  })();

  roundNumber = function(number, decimals) {
    if (decimals == null) {
      decimals = 0;
    }
    return Math.round(number * Math.pow(10, decimals)) / Math.pow(10, decimals);
  };

  getPermalinkQuery = function(query) {
    var conConMap, results;
    results = {};
    conConMap = {
      conversions_control: 'cc',
      samples_control: 'sc',
      conversions_experiment: 'ce',
      samples_experiment: 'se'
    };
    $.map(query, function(value, key) {
      return results[conConMap[key]] = value;
    });
    return results;
  };

  isPermalinkPage = function() {
    if (!getParameter('cc')) {
      return false;
    }
    if (!getParameter('sc')) {
      return false;
    }
    if (!getParameter('ce')) {
      return false;
    }
    if (!getParameter('se')) {
      return false;
    }
    return true;
  };

  getTemplateOutput = function(template, input) {
    var compiled, source;
    source = template.html();
    compiled = Handlebars.compile(source);
    return compiled(input);
  };

  renderError = function(error) {
    var html;
    html = getTemplateOutput($('#error-template'), {
      error: error
    });
    return printResult(html);
  };

  renderResults = function(stat_results, query) {
    var html, percentagize, permalink, results;
    results = [];
    percentagize = function(numbers) {
      var percents;
      percents = {};
      $.each(numbers, function(key, value) {
        var decimals;
        value = 100 * value;
        decimals = value >= 1000 ? 0 : 1;
        return percents[key] = roundNumber(value, decimals);
      });
      return percents;
    };
    permalink = ("http://" + window.location.host + "?") + getQueryString(query);
    results.push($.extend({
      title: 'Original',
      chart: stat_results.confidence.chart.control,
      inputs: {
        conversions: parseInt(query.conversions_control, 10).approximate(),
        samples: parseInt(query.samples_control, 10).approximate()
      }
    }, percentagize(stat_results.confidence.results.control)));
    results.push($.extend({
      title: 'Experiment',
      chart: stat_results.confidence.chart.experiment,
      inputs: {
        conversions: parseInt(query.conversions_experiment, 10).approximate(),
        samples: parseInt(query.samples_experiment, 10).approximate()
      }
    }, percentagize(stat_results.confidence.results.experiment)));
    results.push($.extend({
      title: 'Significance',
      chart: stat_results.significance.chart
    }, percentagize({
      average: stat_results.significance.results.experiment
    })));
    results.push($.extend({
      title: 'Improvement',
      chart: stat_results.improvement.chart
    }, percentagize(stat_results.improvement.results)));
    html = getTemplateOutput($('#results-template'), {
      results: results,
      permalink: permalink
    });
    return printResult(html);
  };

  printResult = function(html, options) {
    if (options == null) {
      options = {};
    }
    return $('.results').fadeOut(200, function() {
      return $(this).hide().delay(300).html(html).fadeIn(options.speed);
    });
  };

  pushState = function(query) {
    var url;
    url = '?' + getQueryString(query);
    if ($.support.history) {
      return history.pushState(query, '', url);
    }
  };

  isEmbed = function() {
    return !$('.header').is(':visible');
  };

  isNewQuery = function(queryString) {
    return queryString !== window.location.search;
  };

  getQueryString = function(query) {
    return $.param(getPermalinkQuery(query));
  };

  getResults = function(query, options) {
    var lastQuery, newQuery;
    if (options == null) {
      options = {};
    }
    lastQuery = window.location.search;
    newQuery = '?' + getQueryString(query);
    if (!isEmbed() && (isNewQuery(newQuery) || !history.state)) {
      pushState(query);
    }
    if (!options.force && lastQuery === newQuery) {
      return false;
    }
    return queryAPI(query).done(function(stat_results) {
      $('.alert').fadeOut();
      if (stat_results.error) {
        return renderError(stat_results.error);
      }
      $('body').removeClass('home').addClass('permalink');
      return renderResults(stat_results, query);
    });
  };

  syncFormWithPermalink = function() {
    $("input#control-conversions").val(getParameter('cc'));
    $("input#control-samples").val(getParameter('sc'));
    $("input#experiment-conversions").val(getParameter('ce'));
    return $("input#experiment-samples").val(getParameter('se'));
  };

  queryAPI = function(query) {
    return $.getJSON('api?' + $.param(query));
  };

  getParameter = function(paramName) {
    var param, params, searchString, val, _i, _len;
    searchString = window.location.search.substring(1);
    params = searchString.split('&');
    for (_i = 0, _len = params.length; _i < _len; _i++) {
      param = params[_i];
      val = param.split('=');
      if (val[0] === paramName) {
        return unescape(val[1]);
      }
    }
    return null;
  };

  isFormComplete = function() {
    if (!$('input#control-conversions').val()) {
      return false;
    }
    if (!$('input#control-samples').val()) {
      return false;
    }
    if (!$('input#experiment-conversions').val()) {
      return false;
    }
    if (!$('input#experiment-samples').val()) {
      return false;
    }
    return true;
  };

  $(function() {
    if ($.support.history) {
      $(window).on('popstate', function(event) {
        var state;
        state = event.originalEvent.state;
        if (state) {
          getResults(state, {
            force: true
          });
          return syncFormWithPermalink();
        }
      });
    }
    $("form :input:visible:first").focus();
    $("form").on('submit', function(event) {
      event.preventDefault();
      if (!isFormComplete()) {
        return false;
      }
      return getResults({
        conversions_control: $('input#control-conversions').val(),
        samples_control: $('input#control-samples').val(),
        conversions_experiment: $('input#experiment-conversions').val(),
        samples_experiment: $('input#experiment-samples').val()
      });
    });
    if (isPermalinkPage()) {
      syncFormWithPermalink();
      getResults({
        conversions_control: getParameter('cc'),
        samples_control: getParameter('sc'),
        conversions_experiment: getParameter('ce'),
        samples_experiment: getParameter('se')
      }, {
        force: true
      });
    } else {
      $('body').removeClass('permalink').addClass('home');
      $('.alert-info').delay(1400).fadeIn('slow');
    }
    $('form input[type=text]').keyup(function() {
      clearTimeout(this.keyup_timer);
      return this.keyup_timer = setTimeout(function() {
        return $('form').submit();
      }, 800);
    });
    return conconjr();
  });

}).call(this);
<|endoftext|>


<commit_before><commit_msg>Auto synchronize Journal after file upload<commit_after><|endoftext|>


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

/*****************************************************************************/

var nfc = window.nfc = {};

nfc.reset = function() {
	nfc.busName = "org.neard";
	nfc.bus = null;
	nfc.uri = null;
	nfc.manager = null;
	nfc.adapter = null;
	nfc.defaultAdapter = null;
};

nfc.init = function(uri, manifest, successCB, errorCB) {
	nfc.reset();

	function onAdapterPropsOk(props) {
		nfc.adapter.props = props;
		nfc.defaultAdapter = new nfc.NFCAdapter(nfc.adapter);
		if (successCB)
			successCB();
	}

	function onAdapterOk() {
		nfc.adapter.GetProperties(onAdapterPropsOk, errorCB);
	}

	function onManagerPropsOk(props) {
		if (props.Adapters.length == 0)
			errorCB("No NFC Adapter found");
		else {
			nfc.adapter = nfc.bus.getObject(nfc.busName,
					props.Adapters[0],
					onAdapterOk,
					errorCB);
		}
	}

	function onManagerOk() {
		nfc.manager.GetProperties(onManagerPropsOk, errorCB);
	}

	function onConnectOk() {
		nfc.bus = cloudeebus.SystemBus();
		nfc.uri = uri;
		nfc.manager = nfc.bus.getObject(nfc.busName, "/", onManagerOk, errorCB);
	}

	cloudeebus.connect(uri, manifest, onConnectOk, errorCB);
};

nfc.getDefaultAdapter = function() {
	return nfc.defaultAdapter;
};

/*****************************************************************************/

nfc.NFCAdapter = function(proxy) {
	this.proxy = proxy;
	if (proxy) {
		this.id = proxy.objectPath;
		this.powered = proxy.props.Powered ? true : false;
		this.polling = proxy.props.Polling ? true : false;
	}
	this.tagListener = this.peerListener = null;
	return this;
};

nfc.NFCAdapter.prototype.setPowered = function(state, successCB, errorCB) {

	var self = this;

	function onPoweredOk() {
		self.powered = state;
		if (successCB)
			successCB();
	}

	self.proxy.SetProperty("Powered", state, onPoweredOk, errorCB);
};

nfc.NFCAdapter.prototype.setPolling = function(state, successCB, errorCB) {

	var self = this;

	function onPollingOk() {
		self.polling = state;
		if (successCB)
			successCB();
	}

	if (state)
		self.proxy.StartPollLoop("Initiator", onPollingOk, errorCB);
	else
		self.proxy.StopPollLoop(onPollingOk, errorCB);
};

nfc.NFCAdapter.prototype.setListener = function(listenerKey, errorCB) {

	var self = this;

	var tag = null;
	var peer = null;

	function onTagPropsOk(props) {
		tag.props = props;
		tag.type = props.Type;
		if (self.tagListener)
			self.tagListener.onattach(tag);
	}

	function onPeerPropsOk(props) {
		peer.props = props;
		if (self.peerListener)
			self.peerListener.onattach(peer);
	}

	function onTagFound(tagId) {
		if (tag) /* trigger "found" callback only once */
			return;
		tag = new nfc.NFCTag(nfc.bus.getObject(nfc.busName, tagId));
		tag.proxy.callMethod("org.neard.Tag", "GetProperties",
				[]).then(onTagPropsOk, errorCB);
	}

	function onPeerFound(deviceId) {
		if (peer) /* trigger "found" callback only once */
			return;
		peer = new nfc.NFCPeer(nfc.bus.getObject(nfc.busName, deviceId));
		peer.proxy.callMethod("org.neard.Device", "GetProperties",
				[]).then(onPeerPropsOk, errorCB);
	}

	function onPropertyChanged(key, table) {
		if (key == "Tags") {
			if (table.length == 0) {
				tag = null;
				if (self.tagListener)
					self.tagListener.ondetach();
				self.setPolling(true);
			}
			else
				onTagFound(table[0]);
		}
		if (key == "Devices") {
			if (table.length == 0) {
				peer = null;
				if (self.peerListener)
					self.peerListener.ondetach();
				self.setPolling(true);
			}
			else
				onPeerFound(table[0]);
		}
	}

	if (!self.connected) {
		self.proxy.connectToSignal("org.neard.Adapter","PropertyChanged",
				onPropertyChanged);
		self.connected = true;
	}
};

nfc.NFCAdapter.prototype.setTagListener = function(detectCB, errorCB, tagFilter) {
	this.tagListener = detectCB;
	return this.setListener("Tags", errorCB);
};

nfc.NFCAdapter.prototype.setPeerListener = function(detectCB, errorCB) {
	this.peerListener = detectCB;
	return this.setListener("Devices", errorCB);
};

nfc.NFCAdapter.prototype.unsetListener = function() {
	if (this.tagListener || this.peerListener)
		return;
	this.proxy.disconnectSignal("org.neard.Adapter","PropertyChanged");
	this.connected = false;
};

nfc.NFCAdapter.prototype.unsetTagListener = function() {
	this.tagListener = null;
	return this.unsetListener();
};

nfc.NFCAdapter.prototype.unsetPeerListener = function() {
	this.peerListener = null;
	return this.unsetListener();
};

/*****************************************************************************/

nfc.NFCPeer = function(proxy) {
	this.proxy = proxy;
	if (proxy) {
		this.id = proxy.objectPath;
	}
	this.isConnected = false;
	return this;
};

nfc.NFCPeer.prototype.setReceiveNDEFListener = function(receiveCB, errorCB) {

	var self = this;

	if (!self.props)
		return errorCB("Peer properties unknown.");

	var records = [];

	function onRecPropsOk(props) {
		records.push(nfc.NDEFRecordForProps(props));
		if (records.length == self.props.Records.length && receiveCB)
			receiveCB(new NDEFMessage(records));
	}

	function NDEFMessageForRecords() {
		records = [];
		for (var i=0; i<self.props.Records.length; i++) {
			var recProxy = nfc.bus.getObject(nfc.busName, self.props.Records[i]);
			recProxy.callMethod("org.neard.Record", "GetProperties",
					[]).then(onRecPropsOk, errorCB);
		}
	}

	function onPropertyChanged(key, table) {
		if (key == "Records") {
			self.props.Records = table;
			NDEFMessageForRecords();
		}
	}

	if (!self.isConnected) {
		self.proxy.connectToSignal("org.neard.Device","PropertyChanged",
				onPropertyChanged);
		self.isConnected = true;
		NDEFMessageForRecords();
	}
};

nfc.NFCPeer.prototype.unsetReceiveNDEFListener = function() {
	this.proxy.disconnectSignal("org.neard.Device","PropertyChanged");
	this.isConnected = false;
};

nfc.NFCPeer.prototype.sendNDEF = function(ndefMessage, successCB, errorCB) {
	for (var i=0; i< ndefMessage.records.length; i++) {
		var ndefRecord = ndefMessage.records[i];
		var rec = ndefRecord.neardRecord();
		this.proxy.callMethod("org.neard.Device", "Push",
			[rec]).then(successCB, errorCB);
	}
};

nfc.NFCPeer.prototype.startHandover = function(type, successCB, errorCB) {
	this.proxy.callMethod("org.neard.Device", "Push",
		[{
			 Type: "Handover",
			 Carrier: type
		}]).then(
		successCB, errorCB);
};

/*****************************************************************************/

nfc.NFCTag = function(proxy) {
	this.proxy = proxy;
	this.type = "GENERIC_TARGET";
	if (proxy) {
		this.id = proxy.objectPath;
	}
	return this;
};

nfc.NFCTag.prototype.readNDEF = function(readCB, errorCB) {

	var self = this;

	if (!self.props)
		return errorCB("Tag properties unknown.");

	var records = [];

	function onRecPropsOk(props) {
		records.push(nfc.NDEFRecordForProps(props));
		if (records.length == self.props.Records.length && readCB)
			readCB(new NDEFMessage(records));
	}

	for (var i=0; i<self.props.Records.length; i++) {
		var recProxy = nfc.bus.getObject(nfc.busName, self.props.Records[i]);
		recProxy.callMethod("org.neard.Record", "GetProperties",
				[]).then(onRecPropsOk, errorCB);
	}
};

nfc.NFCTag.prototype.writeNDEF = function(ndefMessage, successCB, errorCB) {
	var ndefRecord = ndefMessage.records[0];
	var rec = ndefRecord.neardRecord();
	this.proxy.callMethod("org.neard.Tag", "Write",
			[rec]).then(successCB, errorCB);
};

/*****************************************************************************/

nfc.NDEFMessage = function() {
	return this;
};

NDEFMessage = function(records) {
	nfc.NDEFMessage.call(this);
	this.records = records;
	return this;
};

NDEFMessage.prototype = new nfc.NDEFMessage();
NDEFMessage.prototype.constructor = NDEFMessage;

/*****************************************************************************/

nfc.NDEFRecord = function(props) {
	return this;
};

nfc.NDEFRecord.prototype.neardRecord = function() {
	return {};
};

/*****************************************************************************/

nfc.NDEFRecordText = function(props) {
	nfc.NDEFRecord.call(this,props);
	if (props) {
		this.text = props.Representation;
		this.languageCode = props.Language;
		this.encoding = props.Encoding;
	}
	return this;
};

nfc.NDEFRecordText.prototype = new nfc.NDEFRecord();
nfc.NDEFRecordText.prototype.constructor = nfc.NDEFRecordText;

nfc.NDEFRecordText.prototype.neardRecord = function() {
	return {
		Type: "Text",
		Representation: this.text,
		Language: this.languageCode,
		Encoding: this.encoding
	};
};

NDEFRecordText = function(text, languageCode, encoding) {
	nfc.NDEFRecordText.call(this);
	this.text = text;
	this.languageCode = languageCode ? languageCode : "en-US";
	this.encoding = encoding ? encoding : "UTF-8";
	return this;
};

NDEFRecordText.prototype = new nfc.NDEFRecordText();
NDEFRecordText.prototype.constructor = NDEFRecordText;

/*****************************************************************************/

nfc.NDEFRecordURI = function(props) {
	nfc.NDEFRecord.call(this,props);
	if (props) {
		this.uri = props.URI;
	}
	return this;
};

nfc.NDEFRecordURI.prototype = new nfc.NDEFRecord();
nfc.NDEFRecordURI.prototype.constructor = nfc.NDEFRecordURI;

nfc.NDEFRecordURI.prototype.neardRecord = function() {
	return {
		Type: "URI",
		URI: this.uri
	};
};

NDEFRecordURI = function(uri) {
	nfc.NDEFRecordURI.call(this);
	this.uri = uri;
	return this;
};

NDEFRecordURI.prototype = new nfc.NDEFRecordURI();
NDEFRecordURI.prototype.constructor = NDEFRecordURI;

/*****************************************************************************/

nfc.NDEFRecordForProps = function(props) {
	if (props.Type == "Text")
		return new nfc.NDEFRecordText(props);
	if (props.Type == "URI")
		return new nfc.NDEFRecordURI(props);
	return new nfc.NDEFRecord(props);
};

<commit_msg>rewrite all calls to proxy-generated methods to pass callbacks with the request .then method<commit_after>/******************************************************************************
 * Copyright 2012 Intel Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/*****************************************************************************/

var nfc = window.nfc = {};

nfc.reset = function() {
	nfc.busName = "org.neard";
	nfc.bus = null;
	nfc.uri = null;
	nfc.manager = null;
	nfc.adapter = null;
	nfc.defaultAdapter = null;
};

nfc.init = function(uri, manifest, successCB, errorCB) {
	nfc.reset();

	function onAdapterPropsOk(props) {
		nfc.adapter.props = props;
		nfc.defaultAdapter = new nfc.NFCAdapter(nfc.adapter);
		if (successCB)
			successCB();
	}

	function onAdapterOk() {
		nfc.adapter.GetProperties().then(onAdapterPropsOk, errorCB);
	}

	function onManagerPropsOk(props) {
		if (props.Adapters.length == 0)
			errorCB("No NFC Adapter found");
		else {
			nfc.adapter = nfc.bus.getObject(nfc.busName,
					props.Adapters[0],
					onAdapterOk,
					errorCB);
		}
	}

	function onManagerOk() {
		nfc.manager.GetProperties().then(onManagerPropsOk, errorCB);
	}

	function onConnectOk() {
		nfc.bus = cloudeebus.SystemBus();
		nfc.uri = uri;
		nfc.manager = nfc.bus.getObject(nfc.busName, "/", onManagerOk, errorCB);
	}

	cloudeebus.connect(uri, manifest, onConnectOk, errorCB);
};

nfc.getDefaultAdapter = function() {
	return nfc.defaultAdapter;
};

/*****************************************************************************/

nfc.NFCAdapter = function(proxy) {
	this.proxy = proxy;
	if (proxy) {
		this.id = proxy.objectPath;
		this.powered = proxy.props.Powered ? true : false;
		this.polling = proxy.props.Polling ? true : false;
	}
	this.tagListener = this.peerListener = null;
	return this;
};

nfc.NFCAdapter.prototype.setPowered = function(state, successCB, errorCB) {

	var self = this;

	function onPoweredOk() {
		self.powered = state;
		if (successCB)
			successCB();
	}

	self.proxy.SetProperty("Powered", state).then(onPoweredOk, errorCB);
};

nfc.NFCAdapter.prototype.setPolling = function(state, successCB, errorCB) {

	var self = this;

	function onPollingOk() {
		self.polling = state;
		if (successCB)
			successCB();
	}

	if (state)
		self.proxy.StartPollLoop("Initiator").then(onPollingOk, errorCB);
	else
		self.proxy.StopPollLoop().then(onPollingOk, errorCB);
};

nfc.NFCAdapter.prototype.setListener = function(listenerKey, errorCB) {

	var self = this;

	var tag = null;
	var peer = null;

	function onTagPropsOk(props) {
		tag.props = props;
		tag.type = props.Type;
		if (self.tagListener)
			self.tagListener.onattach(tag);
	}

	function onPeerPropsOk(props) {
		peer.props = props;
		if (self.peerListener)
			self.peerListener.onattach(peer);
	}

	function onTagFound(tagId) {
		if (tag) /* trigger "found" callback only once */
			return;
		tag = new nfc.NFCTag(nfc.bus.getObject(nfc.busName, tagId));
		tag.proxy.callMethod("org.neard.Tag", "GetProperties",
				[]).then(onTagPropsOk, errorCB);
	}

	function onPeerFound(deviceId) {
		if (peer) /* trigger "found" callback only once */
			return;
		peer = new nfc.NFCPeer(nfc.bus.getObject(nfc.busName, deviceId));
		peer.proxy.callMethod("org.neard.Device", "GetProperties",
				[]).then(onPeerPropsOk, errorCB);
	}

	function onPropertyChanged(key, table) {
		if (key == "Tags") {
			if (table.length == 0) {
				tag = null;
				if (self.tagListener)
					self.tagListener.ondetach();
				self.setPolling(true);
			}
			else
				onTagFound(table[0]);
		}
		if (key == "Devices") {
			if (table.length == 0) {
				peer = null;
				if (self.peerListener)
					self.peerListener.ondetach();
				self.setPolling(true);
			}
			else
				onPeerFound(table[0]);
		}
	}

	if (!self.connected) {
		self.proxy.connectToSignal("org.neard.Adapter","PropertyChanged",
				onPropertyChanged);
		self.connected = true;
	}
};

nfc.NFCAdapter.prototype.setTagListener = function(detectCB, errorCB, tagFilter) {
	this.tagListener = detectCB;
	return this.setListener("Tags", errorCB);
};

nfc.NFCAdapter.prototype.setPeerListener = function(detectCB, errorCB) {
	this.peerListener = detectCB;
	return this.setListener("Devices", errorCB);
};

nfc.NFCAdapter.prototype.unsetListener = function() {
	if (this.tagListener || this.peerListener)
		return;
	this.proxy.disconnectSignal("org.neard.Adapter","PropertyChanged");
	this.connected = false;
};

nfc.NFCAdapter.prototype.unsetTagListener = function() {
	this.tagListener = null;
	return this.unsetListener();
};

nfc.NFCAdapter.prototype.unsetPeerListener = function() {
	this.peerListener = null;
	return this.unsetListener();
};

/*****************************************************************************/

nfc.NFCPeer = function(proxy) {
	this.proxy = proxy;
	if (proxy) {
		this.id = proxy.objectPath;
	}
	this.isConnected = false;
	return this;
};

nfc.NFCPeer.prototype.setReceiveNDEFListener = function(receiveCB, errorCB) {

	var self = this;

	if (!self.props)
		return errorCB("Peer properties unknown.");

	var records = [];

	function onRecPropsOk(props) {
		records.push(nfc.NDEFRecordForProps(props));
		if (records.length == self.props.Records.length && receiveCB)
			receiveCB(new NDEFMessage(records));
	}

	function NDEFMessageForRecords() {
		records = [];
		for (var i=0; i<self.props.Records.length; i++) {
			var recProxy = nfc.bus.getObject(nfc.busName, self.props.Records[i]);
			recProxy.callMethod("org.neard.Record", "GetProperties",
					[]).then(onRecPropsOk, errorCB);
		}
	}

	function onPropertyChanged(key, table) {
		if (key == "Records") {
			self.props.Records = table;
			NDEFMessageForRecords();
		}
	}

	if (!self.isConnected) {
		self.proxy.connectToSignal("org.neard.Device","PropertyChanged",
				onPropertyChanged);
		self.isConnected = true;
		NDEFMessageForRecords();
	}
};

nfc.NFCPeer.prototype.unsetReceiveNDEFListener = function() {
	this.proxy.disconnectSignal("org.neard.Device","PropertyChanged");
	this.isConnected = false;
};

nfc.NFCPeer.prototype.sendNDEF = function(ndefMessage, successCB, errorCB) {
	for (var i=0; i< ndefMessage.records.length; i++) {
		var ndefRecord = ndefMessage.records[i];
		var rec = ndefRecord.neardRecord();
		this.proxy.callMethod("org.neard.Device", "Push",
			[rec]).then(successCB, errorCB);
	}
};

nfc.NFCPeer.prototype.startHandover = function(type, successCB, errorCB) {
	this.proxy.callMethod("org.neard.Device", "Push",
		[{
			 Type: "Handover",
			 Carrier: type
		}]).then(
		successCB, errorCB);
};

/*****************************************************************************/

nfc.NFCTag = function(proxy) {
	this.proxy = proxy;
	this.type = "GENERIC_TARGET";
	if (proxy) {
		this.id = proxy.objectPath;
	}
	return this;
};

nfc.NFCTag.prototype.readNDEF = function(readCB, errorCB) {

	var self = this;

	if (!self.props)
		return errorCB("Tag properties unknown.");

	var records = [];

	function onRecPropsOk(props) {
		records.push(nfc.NDEFRecordForProps(props));
		if (records.length == self.props.Records.length && readCB)
			readCB(new NDEFMessage(records));
	}

	for (var i=0; i<self.props.Records.length; i++) {
		var recProxy = nfc.bus.getObject(nfc.busName, self.props.Records[i]);
		recProxy.callMethod("org.neard.Record", "GetProperties",
				[]).then(onRecPropsOk, errorCB);
	}
};

nfc.NFCTag.prototype.writeNDEF = function(ndefMessage, successCB, errorCB) {
	var ndefRecord = ndefMessage.records[0];
	var rec = ndefRecord.neardRecord();
	this.proxy.callMethod("org.neard.Tag", "Write",
			[rec]).then(successCB, errorCB);
};

/*****************************************************************************/

nfc.NDEFMessage = function() {
	return this;
};

NDEFMessage = function(records) {
	nfc.NDEFMessage.call(this);
	this.records = records;
	return this;
};

NDEFMessage.prototype = new nfc.NDEFMessage();
NDEFMessage.prototype.constructor = NDEFMessage;

/*****************************************************************************/

nfc.NDEFRecord = function(props) {
	return this;
};

nfc.NDEFRecord.prototype.neardRecord = function() {
	return {};
};

/*****************************************************************************/

nfc.NDEFRecordText = function(props) {
	nfc.NDEFRecord.call(this,props);
	if (props) {
		this.text = props.Representation;
		this.languageCode = props.Language;
		this.encoding = props.Encoding;
	}
	return this;
};

nfc.NDEFRecordText.prototype = new nfc.NDEFRecord();
nfc.NDEFRecordText.prototype.constructor = nfc.NDEFRecordText;

nfc.NDEFRecordText.prototype.neardRecord = function() {
	return {
		Type: "Text",
		Representation: this.text,
		Language: this.languageCode,
		Encoding: this.encoding
	};
};

NDEFRecordText = function(text, languageCode, encoding) {
	nfc.NDEFRecordText.call(this);
	this.text = text;
	this.languageCode = languageCode ? languageCode : "en-US";
	this.encoding = encoding ? encoding : "UTF-8";
	return this;
};

NDEFRecordText.prototype = new nfc.NDEFRecordText();
NDEFRecordText.prototype.constructor = NDEFRecordText;

/*****************************************************************************/

nfc.NDEFRecordURI = function(props) {
	nfc.NDEFRecord.call(this,props);
	if (props) {
		this.uri = props.URI;
	}
	return this;
};

nfc.NDEFRecordURI.prototype = new nfc.NDEFRecord();
nfc.NDEFRecordURI.prototype.constructor = nfc.NDEFRecordURI;

nfc.NDEFRecordURI.prototype.neardRecord = function() {
	return {
		Type: "URI",
		URI: this.uri
	};
};

NDEFRecordURI = function(uri) {
	nfc.NDEFRecordURI.call(this);
	this.uri = uri;
	return this;
};

NDEFRecordURI.prototype = new nfc.NDEFRecordURI();
NDEFRecordURI.prototype.constructor = NDEFRecordURI;

/*****************************************************************************/

nfc.NDEFRecordForProps = function(props) {
	if (props.Type == "Text")
		return new nfc.NDEFRecordText(props);
	if (props.Type == "URI")
		return new nfc.NDEFRecordURI(props);
	return new nfc.NDEFRecord(props);
};

<|endoftext|>


<commit_before>function start() {

  console.time('init');

  var svg = d3.select("svg");
      width = window.innerWidth,
      height = window.innerHeight,
      color = d3.scaleOrdinal(d3.schemeCategory20);

  var nodes = [],
      links = [],
      data = {},
      originalData = {};

  var svg = d3.select("svg")
      .attr("id", "screen")
      .attr("width", width)
      .attr("height", height);

  var startYear = 1950;
  var year = startYear;
  var speed = 1000;
  var filters = $('#search').val();

  var simulation = null;
  var g = null;

  initializeNav();

  d3.json("data/converted.json", function(error, response) {
    if (error) throw error;

    // Filter out nodes we don't need to look at for now
    data = response;
    originalData = jQuery.extend({}, response);

    data = prepareData(data, filters);
    nodes = []; //data.nodes;
    links = []; // data.links;

    simulation = getSimulation(nodes, links);

    g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"),
        link = g.append("g").attr("stroke", "#000").attr("stroke-width", 1.5).selectAll(".link"),
        node = g.append("g").attr("stroke", "#fff").attr("stroke-width", 1.5).selectAll(".node");

    restart();
    console.timeEnd('init');
    var cancel = null;

    cancel = d3.interval(loop, speed, d3.now());

    function loop() {
      console.time("loop 10");
      year = advanceYear(year);

      console.time("loop 20");
      data.nodes.forEach(addRemoveNode);

      console.time("loop 25");
      // pop off any ones we don't
      visibleNodeMap = nodes.map(function(node) { return node.id });

      console.time("loop 30");
      data.links.forEach(addRemoveLinks);
      console.time("loop 40");
      restart();
      console.timeEnd("loop 10");
      console.timeEnd("loop 20");
      console.timeEnd("loop 25");
      console.timeEnd("loop 30");
      console.timeEnd("loop 40");
      console.log("--------");
    }

    function advanceYear(year) {
      return year + 1;
    }

    function addRemoveNode(n) {
      if (n.birthDate != null) {
        var nodeYear = n.birthDate.substring(0,4);
        if (nodes.indexOf(n) == -1 && nodeYear <= year) {
          nodes.push(n);
        }
        else if (nodes.indexOf(n) > -1 && (nodeYear > year)) {
          nodes.splice(nodes.indexOf(n), 1);
        }
      }
    }

    function addRemoveLinks(l) {
      if (links.indexOf(l) == -1 && nodes.indexOf(l.source) > -1 && nodes.indexOf(l.target) > -1) {
        links.push(l);
      }
      else if (links.indexOf(l) > -1 && (nodes.indexOf(l.source) == -1 || nodes.indexOf(l.target) == -1)) {
        links.splice(links.indexOf(l), 1);
      }
    }

    function prepareData(data, filters) {
      data.nodes = data.nodes.filter( function(n) {
        filterItems = filters.split(" ");
        return inFilter(n, filterItems);
      });

      // link directly instead of using indices
      data.links.forEach( function(link, index) {
        link.source = getNodeById(data.nodes, link.source);
        link.target = getNodeById(data.nodes, link.target);
      });

      return data;
    }

    function getSimulation(nodes, links) {
      var simulation = d3.forceSimulation(nodes)
        .force("charge", d3.forceManyBody(1))
        .force("centering", d3.forceCenter(0,0))
        .force("link", d3.forceLink(links))
        .force("x", d3.forceX())
        .force("y", d3.forceY())
        .alphaTarget(1)
        .on("tick", ticked);
      return simulation;
    }

    function updateYear(year) {
      $('#year').html(year)
        .css('left', width/2 - 105)
        .css('top', height - 140);
    }

    function resizeScreen() {
      height = window.innerHeight;
      width = window.innerWidth;
      svg.attr("height", height)
        .attr("width", width);
      console.log(width/2, height/2);
    }

    function updateFilter() {
      if ($('#search').val() != filters) {
        filters = $('#search').val();
        nodes.length = 0;
        links.length = 0;
        filterItems = filters.split(" ");
        for (var i=0; i<originalData.nodes.length; i++) {
          if (inFilter(originalData.nodes[i], filterItems)) {
            nodes.push(originalData.nodes[i]);
          }
        }
      }
    }

    function restart() {
			updateYear(year);
      updateFilter();
      // Apply the general update pattern to the nodes.
      node = node.data(nodes, function(d) { return d.id;});
      node.exit().remove();
      node = node.enter()
        .append("circle")
        .attr("fill", function(d) { return color(d.lastName); })
        .attr("r", 5)
        .attr("x", width/2)
        .attr("y", height/2)
        .merge(node)
        .call(d3.drag()
          .on("start", function(d) {dragstarted(d, simulation);})
          .on("drag", dragged)
          .on("end", function(d) {dragended(d, simulation);}));

      node.append("title")
        .text(function(d) { return d.name; });

      // Apply the general update pattern to the links.
      link = link.data(links, function(d) { return d.source.id + "-" + d.target.id; });
      link.exit().remove();
      link = link.enter()
        .append("line")
        .style("stroke-width", 1)
        .style("stroke", function(d) { return d.color; })
        .merge(link);

      // Update and restart the simulation.
      simulation.nodes(nodes);
      simulation.force("link").links(links);
    }

    function ticked() {
      node.attr("cx", function(d) { return d.x; })
          .attr("cy", function(d) { return d.y; })

      link.attr("x1", function(d) { return d.source.x; })
          .attr("y1", function(d) { return d.source.y; })
          .attr("x2", function(d) { return d.target.x; })
          .attr("y2", function(d) { return d.target.y; });
    }
  });

  function inFilter(node, filterItems) {
    if (filterItems.length == 0) {
      return true;
    }
    var regex = null;
    for(i=0; i<filterItems.length; i++) {
      regex = new RegExp(filterItems[i], 'ig');
      if (node.name.match(regex)) {
        return true;
      }
    }
    return false;
  }

  function dragstarted(d, sim) {
    if (!d3.event.active) sim.alphaTarget(0.3).restart();
    d.fx = d.x;
    d.fy = d.y;
  }

  function dragged(d) {
    d.fx = d3.event.x;
    d.fy = d3.event.y;
  }

  function dragended(d, sim) {
    if (!d3.event.active) sim.alphaTarget(0);
    d.fx = null;
    d.fy = null;
  }

  function initializeNav() {
    d3.select('#timeNavigation')
      .on('mouseover', function(d) {
        d3.select('#timeNavigation')
          .style("left", 0);
      })
      .on('mouseout', function(d) {
        d3.select('#timeNavigation')
          .style("left", -890);
      });
  }

  function getNodeById(nodes, id) {
    for(i=0; i<nodes.length; i++) {
      if (nodes[i].id === id) {
        return nodes[i];
      }
    }
    return -1;
  }

}
<commit_msg>cleaned up some messy anonymous functions<commit_after>function start() {

  console.time('init');

  var svg = d3.select("svg");
      width = window.innerWidth,
      height = window.innerHeight,
      color = d3.scaleOrdinal(d3.schemeCategory20);

  var nodes = [],
      links = [],
      data = {},
      originalData = {};

  var svg = d3.select("svg")
      .attr("id", "screen")
      .attr("width", width)
      .attr("height", height);

  var startYear = 1950;
  var year = startYear;
  var speed = 1000;
  var filters = $('#search').val();

  var simulation = null;
  var g = null;

  initializeNav();

  d3.json("data/converted.json", go);

  function go(error, response) {
    if (error) throw error;

    data = response;
    originalData = jQuery.extend({}, response);

    data = prepareData(data, filters);
    nodes = [];
    links = [];

    simulation = getSimulation(nodes, links);

    g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"),
        link = g.append("g").attr("stroke", "#000").attr("stroke-width", 1.5).selectAll(".link"),
        node = g.append("g").attr("stroke", "#fff").attr("stroke-width", 1.5).selectAll(".node");

    restart();
    console.timeEnd('init');

    d3.interval(loop, speed, d3.now());
  }

  function loop() {
    console.time("loop 10");
    year = advanceYear(year);

    console.time("loop 20");
    data.nodes.forEach(addRemoveNode);

    console.time("loop 30");
    data.links.forEach(addRemoveLink);

    console.time("loop 40");
    restart();

    console.timeEnd("loop 10");
    console.timeEnd("loop 20");
    console.timeEnd("loop 30");
    console.timeEnd("loop 40");
    console.log("--------");
  }

  function advanceYear(year) {
    return year + 1;
  }

  function addRemoveNode(n) {
    if (n.birthDate != null) {
      var nodeYear = n.birthDate.substring(0,4);
      if (nodes.indexOf(n) == -1 && nodeYear <= year) {
        nodes.push(n);
      }
      else if (nodes.indexOf(n) > -1 && (nodeYear > year)) {
        nodes.splice(nodes.indexOf(n), 1);
      }
    }
  }

  function addRemoveLink(l) {
    if (links.indexOf(l) == -1 && nodes.indexOf(l.source) > -1 && nodes.indexOf(l.target) > -1) {
      links.push(l);
    }
    else if (links.indexOf(l) > -1 && (nodes.indexOf(l.source) == -1 || nodes.indexOf(l.target) == -1)) {
      links.splice(links.indexOf(l), 1);
    }
  }

  function prepareData(data, filters) {
    data.nodes = data.nodes.filter( function(n) {
      filterItems = filters.split(" ");
      return inFilter(n, filterItems);
    });

    // link directly instead of using indices
    data.links.forEach( function(link, index) {
      link.source = getNodeById(data.nodes, link.source);
      link.target = getNodeById(data.nodes, link.target);
    });

    return data;
  }

  function getSimulation(nodes, links) {
    var simulation = d3.forceSimulation(nodes)
      .force("charge", d3.forceManyBody(1))
      .force("centering", d3.forceCenter(0,0))
      .force("link", d3.forceLink(links))
      .force("x", d3.forceX())
      .force("y", d3.forceY())
      .alphaTarget(1)
      .on("tick", ticked);
    return simulation;
  }

  function updateYear(year) {
    $('#year').html(year)
      .css('left', width/2 - 105)
      .css('top', height - 140);
  }

  function resizeScreen() {
    height = window.innerHeight;
    width = window.innerWidth;
    svg.attr("height", height)
      .attr("width", width);
    console.log(width/2, height/2);
  }

  function updateFilter() {
    if ($('#search').val() != filters) {
      filters = $('#search').val();
      nodes.length = 0;
      links.length = 0;
      filterItems = filters.split(" ");
      for (var i=0; i<originalData.nodes.length; i++) {
        if (inFilter(originalData.nodes[i], filterItems)) {
          nodes.push(originalData.nodes[i]);
        }
      }
    }
  }

  function restart() {
    updateYear(year);
    updateFilter();
    // Apply the general update pattern to the nodes.
    node = node.data(nodes, function(d) { return d.id;});
    node.exit().remove();
    node = node.enter()
      .append("circle")
      .attr("fill", function(d) { return color(d.lastName); })
      .attr("r", 5)
      .attr("x", width/2)
      .attr("y", height/2)
      .merge(node)
      .call(d3.drag()
        .on("start", function(d) {dragstarted(d, simulation);})
        .on("drag", dragged)
        .on("end", function(d) {dragended(d, simulation);}));

    node.append("title")
      .text(function(d) { return d.name; });

    // Apply the general update pattern to the links.
    link = link.data(links, function(d) { return d.source.id + "-" + d.target.id; });
    link.exit().remove();
    link = link.enter()
      .append("line")
      .style("stroke-width", 1)
      .style("stroke", function(d) { return d.color; })
      .merge(link);

    // Update and restart the simulation.
    simulation.nodes(nodes);
    simulation.force("link").links(links);
  }

  function ticked() {
    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; })

    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });
  }

  function inFilter(node, filterItems) {
    if (filterItems.length == 0) {
      return true;
    }
    var regex = null;
    for(i=0; i<filterItems.length; i++) {
      regex = new RegExp(filterItems[i], 'ig');
      if (node.name.match(regex)) {
        return true;
      }
    }
    return false;
  }

  function dragstarted(d, sim) {
    if (!d3.event.active) sim.alphaTarget(0.3).restart();
    d.fx = d.x;
    d.fy = d.y;
  }

  function dragged(d) {
    d.fx = d3.event.x;
    d.fy = d3.event.y;
  }

  function dragended(d, sim) {
    if (!d3.event.active) sim.alphaTarget(0);
    d.fx = null;
    d.fy = null;
  }

  function initializeNav() {
    d3.select('#timeNavigation')
      .on('mouseover', function(d) {
        d3.select('#timeNavigation')
          .style("left", 0);
      })
      .on('mouseout', function(d) {
        d3.select('#timeNavigation')
          .style("left", -890);
      });
  }

  function getNodeById(nodes, id) {
    for(i=0; i<nodes.length; i++) {
      if (nodes[i].id === id) {
        return nodes[i];
      }
    }
    return -1;
  }

}
<|endoftext|>


<commit_before>function tooltipHtml(n, d){ /* function to create html content string in tooltip div. */
  return "
"+n+"

"+
  "
Percentage:	"+(d.feeling)+"%
"
  "
";
}

function emo_score() {
		var dict = {

		};
		$.ajax({
        type:     "POST",
        async: 	  false,
        url:     "../get_sentiments.php",
        success: function(data) {
            var emos = $.parseJSON(data);
            console.log(emos);
/*
            for (var i = 0; i < 50; i++) {
            	for (var key in emos[i].state) {
            		if(key != null) {
            			dict[key] = {};
            			console.log(1);
            		}
            	}

            }*/

        }
    });
}

function getEmotionVals(emotion, state) {
	//emo_score();
	return Math.round(100*Math.random());
}

function setStates() {
	var states ={};
	["HI", "AK", "FL", "SC", "GA", "AL", "NC", "TN", "RI", "CT", "MA",
	"ME", "NH", "VT", "NY", "NJ", "PA", "DE", "MD", "WV", "KY", "OH",
	"MI", "WY", "MT", "ID", "WA", "DC", "TX", "CA", "AZ", "NV", "UT",
	"CO", "NM", "OR", "ND", "SD", "NE", "IA", "MS", "IN", "IL", "MN",
	"WI", "MO", "AR", "OK", "KS", "LS", "VA"]
	.forEach(function(d){
	  var feeling=getEmotionVals(0,0);
	  states[d]={feeling:feeling, color:d3.interpolate("#ffffcc", "#800026")(feeling/100)};
	});
	return states;
}

var states = setStates();

/*
var states ={};
["HI", "AK", "FL", "SC", "GA", "AL", "NC", "TN", "RI", "CT", "MA",
"ME", "NH", "VT", "NY", "NJ", "PA", "DE", "MD", "WV", "KY", "OH",
"MI", "WY", "MT", "ID", "WA", "DC", "TX", "CA", "AZ", "NV", "UT",
"CO", "NM", "OR", "ND", "SD", "NE", "IA", "MS", "IN", "IL", "MN",
"WI", "MO", "AR", "OK", "KS", "LS", "VA"]
.forEach(function(d){
  var feeling=getEmotionVals(0,0);
  states[d]={feeling:feeling, color:d3.interpolate("#ffffcc", "#800026")(feeling/100)};
});*/

/* draw states on id #statesvg */
uStates.draw("#statesvg", states, tooltipHtml);

d3.select(self.frameElement).style("height", "600px");<commit_msg>debugging<commit_after>function tooltipHtml(n, d){ /* function to create html content string in tooltip div. */
  return "
"+n+"

"+
  "
Percentage:	"+(d.feeling)+"%
"
  "
";
}

function emo_score() {
		var dict = {

		};
		$.ajax({
        type:     "POST",
        async: 	  false,
        url:     "../get_sentiments.php",
        success: function(data) {
            var emos = $.parseJSON(data);
            console.log(data + ",1");
/*
            for (var i = 0; i < 50; i++) {
            	for (var key in emos[i].state) {
            		if(key != null) {
            			dict[key] = {};
            			console.log(1);
            		}
            	}

            }*/

        }
    });
}

function getEmotionVals(emotion, state) {
	//emo_score();
	return Math.round(100*Math.random());
}

function setStates() {
	var states ={};
	["HI", "AK", "FL", "SC", "GA", "AL", "NC", "TN", "RI", "CT", "MA",
	"ME", "NH", "VT", "NY", "NJ", "PA", "DE", "MD", "WV", "KY", "OH",
	"MI", "WY", "MT", "ID", "WA", "DC", "TX", "CA", "AZ", "NV", "UT",
	"CO", "NM", "OR", "ND", "SD", "NE", "IA", "MS", "IN", "IL", "MN",
	"WI", "MO", "AR", "OK", "KS", "LS", "VA"]
	.forEach(function(d){
	  var feeling=getEmotionVals(0,0);
	  states[d]={feeling:feeling, color:d3.interpolate("#ffffcc", "#800026")(feeling/100)};
	});
	return states;
}

var states = setStates();

/*
var states ={};
["HI", "AK", "FL", "SC", "GA", "AL", "NC", "TN", "RI", "CT", "MA",
"ME", "NH", "VT", "NY", "NJ", "PA", "DE", "MD", "WV", "KY", "OH",
"MI", "WY", "MT", "ID", "WA", "DC", "TX", "CA", "AZ", "NV", "UT",
"CO", "NM", "OR", "ND", "SD", "NE", "IA", "MS", "IN", "IL", "MN",
"WI", "MO", "AR", "OK", "KS", "LS", "VA"]
.forEach(function(d){
  var feeling=getEmotionVals(0,0);
  states[d]={feeling:feeling, color:d3.interpolate("#ffffcc", "#800026")(feeling/100)};
});*/

/* draw states on id #statesvg */
uStates.draw("#statesvg", states, tooltipHtml);

d3.select(self.frameElement).style("height", "600px");<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import SprkCardHighlightedHeader from './components/SprkCardHighlightedHeader/SprkCardHighlightedHeader';
import SprkCardTeaser from './components/SprkCardTeaser/SprkCardTeaser';

const SprkCard = (props) => {
  const {
    additionalClasses,
    additionalContentClasses,
    children,
    highlightedHeaderConfig,
    idString,
    isStandout,
    teaserConfig,
    variant,
  } = props;

  const GetCardContent = () => {
    if (variant === 'highlightedHeader') {
      return (
        <SprkCardHighlightedHeader
          highlightedHeaderConfig={highlightedHeaderConfig}
        />
      );
    }

    if (variant === 'teaser') {
      return <SprkCardTeaser teaserConfig={teaserConfig} />;
    }

    return (
      <div
        className={cx(
          'sprk-c-Card__content sprk-o-Stack__item',
          additionalContentClasses,
        )}
      >
        {children}
      </div>
    );
  };

  return (
    <div
      className={cx('sprk-c-Card sprk-o-Stack', additionalClasses, {
        'sprk-c-Card--standout': isStandout,
        'sprk-u-TextAlign--center': teaserConfig.media.mediaVariant === 'icon',
      })}
      data-id={idString}
    >
      <GetCardContent />
    </div>
  );
};

SprkCard.propTypes = {
  /**
   * A space-separated string of classes to
   * add to the outermost container of the component.
   */
  additionalClasses: PropTypes.string,
  /**
   * A space-separated string of classes to add to the card content container.
   */
  additionalContentClasses: PropTypes.string,
  /** Content to render inside of SprkCard. */
  children: PropTypes.node,
  /**
   * Assigned to the `data-id` attribute serving
   * as a unique selector for automated tools.
   */
  idString: PropTypes.string,
  /**
   * Determines if card style has a deeper shadow.
   */
  isStandout: PropTypes.bool,
  // TODO: Turn this prop into a oneOf type and include
  // the possible possibilities.It could also need a
  // default/base variant style. Issue #2496
  /**
   * Determines the type of card.
   * If none provided, it defaults to
   * the base card style.
   */
  variant: PropTypes.oneOf(['highlightedHeader', 'teaser']),
  /**
   * Configurations that
   * populate the content of SprkCard
   * with a highlighted Header.
   */
  highlightedHeaderConfig: PropTypes.shape({
    /**
     * The Highlighted Header Card's main body text.
     */
    bodyText: PropTypes.string,
    /**
     * The Highlighted Header Card's description.
     */
    description: PropTypes.string,
    /**
     * The Card's title.
     */
    title: PropTypes.string,
  }),
  /**
   * Configuration that populate the content of SprkCard teaser.
   */
  teaserConfig: PropTypes.shape({
    /**
     * Teaser Card's body text.
     */
    bodyText: PropTypes.string,
    /**
     * Configures the call to action of a Teaser Card.
     */
    cta: PropTypes.shape({
      /**
       * A space-separated string of classes to add to the call-to-action icon.
       */
      additionalCtaIconClasses: PropTypes.string,
      /**
       * Value assigned to the
       * `data-analytics` attribute on the Call to Action.
       * Intended for an outside
       * library to capture data.
       */
      ctaAnalytics: PropTypes.string,
      /**
       * Determines what icon `SprkIcon` renders next to the Call to Action.
       */
      ctaIcon: PropTypes.string,
      /**
       * Determines if link renders as an anchor tag, or router link.
       */
      ctaLinkElement: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.func,
        PropTypes.elementType,
      ]),
      /**
       * Determinds if the CTA is a link or a button.
       * Will default to `link` if none provided.
       */
      ctaVariant: PropTypes.oneOf(['link', 'button']),
      /**
       * Determines the href of the media.
       */
      href: PropTypes.string,
      /** Text of the CTA. */
      text: PropTypes.string,
      /**
       * The button variant to use for the call to action.
       */
      buttonVariant: PropTypes.oneOf([
        'primary',
        'secondary',
        'tertiary',
        'quaternary',
      ]),
    }),
    /**
     * Configures the main media of the Teaser Card.
     */
    media: PropTypes.shape({
      /**
       * A space-separated string of classes to add to the media icon.
       */
      additionalMediaIconClasses: PropTypes.string,
      /**
       * Determines the href of the media.
       */
      href: PropTypes.string,
      /**
       * Determines if link renders as an Anchor tag, or router link.
       */
      mediaLinkElement: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
      /**
       * Determines what icon `SprkIcon` renders
       * as the main media of the Teaser Card.
       */
      iconName: PropTypes.string,
      /** Alternative text for the main media of Teaser Card. */
      imgAlt: PropTypes.string,
      /** The source link for the media. */
      imgSrc: PropTypes.string,
      /**
       * Assigned to the `data-analytics` attribute serving
       * as a unique selector for outside libraries to capture data.
       */
      mediaAnalyticsString: PropTypes.string,
      /**
       * Determines which type of media renders.
       * Defaults to `img` if none provided.
       */
      mediaVariant: PropTypes.oneOf(['img', 'icon']),
    }),
    /**
     * Text that will show as as
     * the main headline of the Teaser Card.
     */
    title: PropTypes.string,
    /**
     * Determines if the Teaser Card's
     * title is at the top or below the main media.
     */
    titleFirst: PropTypes.bool,
  }),
};

SprkCard.defaultProps = {
  isStandout: false,
  teaserConfig: {
    cta: {
      ctaVariant: 'link',
      ctaLinkElement: 'SprkLink',
    },
    media: {
      mediaVariant: 'img',
      mediaLinkElement: 'a',
    },
  },
};

export default SprkCard;
<commit_msg>add ...other to react card, was missing<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import SprkCardHighlightedHeader from './components/SprkCardHighlightedHeader/SprkCardHighlightedHeader';
import SprkCardTeaser from './components/SprkCardTeaser/SprkCardTeaser';

const SprkCard = (props) => {
  const {
    additionalClasses,
    additionalContentClasses,
    children,
    highlightedHeaderConfig,
    idString,
    isStandout,
    teaserConfig,
    variant,
    ...other
  } = props;

  const GetCardContent = () => {
    if (variant === 'highlightedHeader') {
      return (
        <SprkCardHighlightedHeader
          highlightedHeaderConfig={highlightedHeaderConfig}
        />
      );
    }

    if (variant === 'teaser') {
      return <SprkCardTeaser teaserConfig={teaserConfig} />;
    }

    return (
      <div
        className={cx(
          'sprk-c-Card__content sprk-o-Stack__item',
          additionalContentClasses,
        )}
      >
        {children}
      </div>
    );
  };

  return (
    <div
      className={cx('sprk-c-Card sprk-o-Stack', additionalClasses, {
        'sprk-c-Card--standout': isStandout,
        'sprk-u-TextAlign--center': teaserConfig.media.mediaVariant === 'icon',
      })}
      data-id={idString}
      {...other}
    >
      <GetCardContent />
    </div>
  );
};

SprkCard.propTypes = {
  /**
   * A space-separated string of classes to
   * add to the outermost container of the component.
   */
  additionalClasses: PropTypes.string,
  /**
   * A space-separated string of classes to add to the card content container.
   */
  additionalContentClasses: PropTypes.string,
  /** Content to render inside of SprkCard. */
  children: PropTypes.node,
  /**
   * Assigned to the `data-id` attribute serving
   * as a unique selector for automated tools.
   */
  idString: PropTypes.string,
  /**
   * Determines if card style has a deeper shadow.
   */
  isStandout: PropTypes.bool,
  // TODO: Turn this prop into a oneOf type and include
  // the possible possibilities.It could also need a
  // default/base variant style. Issue #2496
  /**
   * Determines the type of card.
   * If none provided, it defaults to
   * the base card style.
   */
  variant: PropTypes.oneOf(['highlightedHeader', 'teaser']),
  /**
   * Configurations that
   * populate the content of SprkCard
   * with a highlighted Header.
   */
  highlightedHeaderConfig: PropTypes.shape({
    /**
     * The Highlighted Header Card's main body text.
     */
    bodyText: PropTypes.string,
    /**
     * The Highlighted Header Card's description.
     */
    description: PropTypes.string,
    /**
     * The Card's title.
     */
    title: PropTypes.string,
  }),
  /**
   * Configuration that populate the content of SprkCard teaser.
   */
  teaserConfig: PropTypes.shape({
    /**
     * Teaser Card's body text.
     */
    bodyText: PropTypes.string,
    /**
     * Configures the call to action of a Teaser Card.
     */
    cta: PropTypes.shape({
      /**
       * A space-separated string of classes to add to the call-to-action icon.
       */
      additionalCtaIconClasses: PropTypes.string,
      /**
       * Value assigned to the
       * `data-analytics` attribute on the Call to Action.
       * Intended for an outside
       * library to capture data.
       */
      ctaAnalytics: PropTypes.string,
      /**
       * Determines what icon `SprkIcon` renders next to the Call to Action.
       */
      ctaIcon: PropTypes.string,
      /**
       * Determines if link renders as an anchor tag, or router link.
       */
      ctaLinkElement: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.func,
        PropTypes.elementType,
      ]),
      /**
       * Determinds if the CTA is a link or a button.
       * Will default to `link` if none provided.
       */
      ctaVariant: PropTypes.oneOf(['link', 'button']),
      /**
       * Determines the href of the media.
       */
      href: PropTypes.string,
      /** Text of the CTA. */
      text: PropTypes.string,
      /**
       * The button variant to use for the call to action.
       */
      buttonVariant: PropTypes.oneOf([
        'primary',
        'secondary',
        'tertiary',
        'quaternary',
      ]),
    }),
    /**
     * Configures the main media of the Teaser Card.
     */
    media: PropTypes.shape({
      /**
       * A space-separated string of classes to add to the media icon.
       */
      additionalMediaIconClasses: PropTypes.string,
      /**
       * Determines the href of the media.
       */
      href: PropTypes.string,
      /**
       * Determines if link renders as an Anchor tag, or router link.
       */
      mediaLinkElement: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
      /**
       * Determines what icon `SprkIcon` renders
       * as the main media of the Teaser Card.
       */
      iconName: PropTypes.string,
      /** Alternative text for the main media of Teaser Card. */
      imgAlt: PropTypes.string,
      /** The source link for the media. */
      imgSrc: PropTypes.string,
      /**
       * Assigned to the `data-analytics` attribute serving
       * as a unique selector for outside libraries to capture data.
       */
      mediaAnalyticsString: PropTypes.string,
      /**
       * Determines which type of media renders.
       * Defaults to `img` if none provided.
       */
      mediaVariant: PropTypes.oneOf(['img', 'icon']),
    }),
    /**
     * Text that will show as as
     * the main headline of the Teaser Card.
     */
    title: PropTypes.string,
    /**
     * Determines if the Teaser Card's
     * title is at the top or below the main media.
     */
    titleFirst: PropTypes.bool,
  }),
};

SprkCard.defaultProps = {
  isStandout: false,
  teaserConfig: {
    cta: {
      ctaVariant: 'link',
      ctaLinkElement: 'SprkLink',
    },
    media: {
      mediaVariant: 'img',
      mediaLinkElement: 'a',
    },
  },
};

export default SprkCard;
<|endoftext|>