<commit_before>"use strict";

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var VERBOSE = true;

var Domain = (function () {
  function Domain(options) {
    _classCallCheck(this, Domain);

    this.domain = options.domain;
    this.template = null;
    this.productivity = options.productivity == undefined ? options.productivity : 0;
    this.visits = options.visits;
    this.history = {};
  }

  /**** TEST DUMMY DATA ****/

  _createClass(Domain, [{
    key: "render",
    value: function render() {
      var compiled = _.template(this.template);
      return compiled(this.toObject());
    }
  }, {
    key: "toObject",
    value: function toObject() {
      var obj = {};
      obj.domain = this.domain;
      obj.productivity = this.productivity;
      return obj;
    }
  }, {
    key: "setTemplate",
    value: function setTemplate(template) {
      if (typeof template == "object") {
        template = template.join("\n");
      }
      this.template = template;
    }
  }, {
    key: "setHistory",
    value: function setHistory(historyObject) {}
  }, {
    key: "isProductive",
    value: function isProductive(val) {
      /* 0: UNKNOWN | 1: UNPRODUCTIVE | 2: PRODUCTIVE */
      if (val != undefined) {
        this.isProductive = val;
      }
      return this.isProductive;
    }
  }]);

  return Domain;
})();

var exampleDomains = [{
  domain: "domain.com",
  visits: 58,
  lastSevenDays: null,
  productivity: 2
}, {
  domain: "bomb.com",
  visits: 68,
  lastSevenDays: null,
  productivity: 1
}, {
  domain: "wombo.com",
  visits: 20,
  lastSevenDays: null,
  productivity: 1
}, {
  domain: "everybodywombo.com",
  visits: 90,
  lastSevenDays: null,
  productivity: 0
}];

var domains = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;

try {
  for (var _iterator = exampleDomains[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
    var item = _step.value;

    var d = new Domain(item);
    domains.push(d);
  }
  //*/
  /**** END TEST DUMMY DATA ****/

  //var data = [{ val: 2, legend: "Productive" }, { val: 6, legend: "Unknown" }, { val: 4, legend: "Unproductive" }];
} catch (err) {
  _didIteratorError = true;
  _iteratorError = err;
} finally {
  try {
    if (!_iteratorNormalCompletion && _iterator["return"]) {
      _iterator["return"]();
    }
  } finally {
    if (_didIteratorError) {
      throw _iteratorError;
    }
  }
}

var renderGraph = function renderGraph(domains) {
  ///recieve data to render and decide what to render
  if (VERBOSE) {
    console.debug("FUNCTION CALL: renderGraph()");
  }
  var categoryData = [{ x: "Unknown", visits: 0, value: 0 }, { x: "Unproductive", visits: 0, value: 1 }, { x: "Productive", visits: 0, value: 2 }];
  var _iteratorNormalCompletion2 = true;
  var _didIteratorError2 = false;
  var _iteratorError2 = undefined;

  try {
    for (var _iterator2 = domains[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
      item = _step2.value;

      categoryData[item.productivity].visits += item.visits;
    }
    //renderPieGraph(categoryData);
  } catch (err) {
    _didIteratorError2 = true;
    _iteratorError2 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion2 && _iterator2["return"]) {
        _iterator2["return"]();
      }
    } finally {
      if (_didIteratorError2) {
        throw _iteratorError2;
      }
    }
  }

  renderBarGraph(categoryData);
};

var renderBarGraph = function renderBarGraph(data) {
  console.log(data);
  var colorScale = new Plottable.Scales.Color();
  colorScale.range(["#FF00FF", "#FF0000", "#0000FF"]);

  var xScale = new Plottable.Scales.Category();
  var yScale = new Plottable.Scales.Linear();

  var xAxis = new Plottable.Axes.Category(xScale, "bottom");
  var yAxis = new Plottable.Axes.Numeric(yScale, "left");

  var baseVal = data[0].visits / 2;
  var _iteratorNormalCompletion3 = true;
  var _didIteratorError3 = false;
  var _iteratorError3 = undefined;

  try {
    for (var _iterator3 = data[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
      item = _step3.value;

      if (item.visits / 2 < baseVal) {
        baseVal = item.visits / 2;
      }
    }
  } catch (err) {
    _didIteratorError3 = true;
    _iteratorError3 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion3 && _iterator3["return"]) {
        _iterator3["return"]();
      }
    } finally {
      if (_didIteratorError3) {
        throw _iteratorError3;
      }
    }
  }

  var plot = new Plottable.Plots.Bar().addDataset(new Plottable.Dataset(data)).x(function (d) {
    return d.x;
  }, xScale).y(function (d) {
    return d.visits;
  }, yScale).animated(true).attr("fill", function (d) {
    return d.visits;
  }, colorScale).baselineValue(baseVal).labelsEnabled(true);
  new Plottable.Components.Table([[yAxis, plot], [null, xAxis]]).renderTo("svg#graph");
  window.addEventListener("resize", function () {
    plot.redraw();
  });
};

var renderPieGraph = function renderPieGraph(data) {
  var scale = new Plottable.Scales.Linear();
  var colorScale = new Plottable.Scales.InterpolatedColor();
  colorScale.range(["#BDCEF0", "#5279C7"]);
  var legend = new Plottable.Components.Legend(colorScale);
  colorScale.domain([data[0].visits, data[1].visits, data[2].visits]);
  console.log(colorScale.domain());
  legend.xAlignment("left");
  legend.yAlignment("top");

  var plot = new Plottable.Plots.Pie().addDataset(new Plottable.Dataset(data)).sectorValue(function (d) {
    return d.visits;
  }, scale).innerRadius(0).attr("fill", function (d) {
    return d.visits;
  }, colorScale).outerRadius(60).renderTo("svg#graph");
  legend.renderTo("svg#graph");
  window.addEventListener("resize", function () {
    plot.redraw();
  });
};

var fetchWikipediaArticle = function fetchWikipediaArticle(titleName) {

  var wikiArticleLink = "http://en.wikipedia.org/wiki/" + titleName;

  var container = $(".wikipedia-container");
  var templateString = wikipediaArticleTemplate.join("\n");
  var compiled = _.template(templateString);

  var handleData = function handleData(data) {

    var truncatedSummary = "not found";
    var imageUrl = "images/notfound.png";
    var title = "Article Could Not Be Fetched";

    if (data.summary != undefined) {
      if (data.summary.title != undefined) {
        title = data.summary.title;
      }

      if (data.summary.image != undefined) {
        imageUrl = data.summary.image;
      }

      if (data.summary.summary != undefined) {
        truncatedSummary = data.summary.summary.substring(0, 150) + "...";
      }
    }

    var rendered = compiled({
      title: title,
      imageUrl: imageUrl,
      summary: truncatedSummary
    });

    container.append(rendered);
  };

  WIKIPEDIA.getData(wikiArticleLink, handleData);

  /****
  var wikiArticleLink = "http://en.wikipedia.org/wiki/Invasion_of_Normandy";
  var handleData = function(data){
     console.log(data.summary);
    console.log(data.summary.title);
     $("#title").html($("#title").html() + "" + data.summary.title);
     console.log(data.summary.summary);
    $("#summary").html($("#summary").html() + "" + data.summary.summary.substring(0,150) + "...");
     console.log(data.summary.image);
    //$("#image").html($("#image").html() + "" + data.summary.image);
    $("#put-image-here").attr("src", imageLink(data));
    $("#image-link").attr("href", wikiArticleLink);
  }
   function imageLink(data){
    return data.summary.image;
  }
   var handleError = function handleError(error){
    console.log(error);
  }
   */
};

var renderDomainList = function renderDomainList(domains, renderTargetSelector) {
  if (VERBOSE) {
    console.debug("FUNCTION: renderDomainList()", domains, renderTargetSelector);
  }

  //Somewhere in here throws the error
  /*Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval'
    is not an allowed source of script in the following Content Security Policy directive:
    "script-src 'self' blob: filesystem: chrome-extension-resource:".*/

  var str = "";
  var _iteratorNormalCompletion4 = true;
  var _didIteratorError4 = false;
  var _iteratorError4 = undefined;

  try {
    for (var _iterator4 = domains[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
      var d = _step4.value;

      d.setTemplate(domainListingTemplate);
      str += d.render();
    }
  } catch (err) {
    _didIteratorError4 = true;
    _iteratorError4 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion4 && _iterator4["return"]) {
        _iterator4["return"]();
      }
    } finally {
      if (_didIteratorError4) {
        throw _iteratorError4;
      }
    }
  }

  var _iteratorNormalCompletion5 = true;
  var _didIteratorError5 = false;
  var _iteratorError5 = undefined;

  try {
    for (var _iterator5 = $(renderTargetSelector)[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
      var n = _step5.value;

      n.innerHTML = str;
    }
  } catch (err) {
    _didIteratorError5 = true;
    _iteratorError5 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion5 && _iterator5["return"]) {
        _iterator5["return"]();
      }
    } finally {
      if (_didIteratorError5) {
        throw _iteratorError5;
      }
    }
  }
};

var DOMLoaded = function DOMLoaded() {
  if (VERBOSE) {
    console.debug("EVENT: DOMContentLoaded");
  }
  console.log(getDomains());
  renderGraph(exampleDomains);
  renderDomainList(domains, "ul.domain-list-productive");
  var articles = ["Invasion_of_Normandy", "Banana", "Arthur_Tedder,_1st_Baron_Tedder"];
  var _iteratorNormalCompletion6 = true;
  var _didIteratorError6 = false;
  var _iteratorError6 = undefined;

  try {
    for (var _iterator6 = articles[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
      var a = _step6.value;

      fetchWikipediaArticle(a);
    }
  } catch (err) {
    _didIteratorError6 = true;
    _iteratorError6 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion6 && _iterator6["return"]) {
        _iterator6["return"]();
      }
    } finally {
      if (_didIteratorError6) {
        throw _iteratorError6;
      }
    }
  }
};

document.addEventListener('DOMContentLoaded', DOMLoaded, false);<commit_msg>Not sure why but extension/js/newtab.js changed<commit_after>"use strict";

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var VERBOSE = true;

var Domain = (function () {
  function Domain(options) {
    _classCallCheck(this, Domain);

    this.domain = options.domain;
    this.template = null;
    this.productivity = options.productivity == undefined ? options.productivity : 0;
    this.visits = options.visits;
    this.history = {};
  }

  /**** TEST DUMMY DATA ****/

  _createClass(Domain, [{
    key: "render",
    value: function render() {
      var compiled = _.template(this.template);
      return compiled(this.toObject());
    }
  }, {
    key: "toObject",
    value: function toObject() {
      var obj = {};
      obj.domain = this.domain;
      obj.productivity = this.productivity;
      return obj;
    }
  }, {
    key: "setTemplate",
    value: function setTemplate(template) {
      if (typeof template == "object") {
        template = template.join("\n");
      }
      this.template = template;
    }
  }, {
    key: "setHistory",
    value: function setHistory(historyObject) {}
  }, {
    key: "isProductive",
    value: function isProductive(val) {
      /* 0: UNKNOWN | 1: UNPRODUCTIVE | 2: PRODUCTIVE */
      if (val != undefined) {
        this.isProductive = val;
      }
      return this.isProductive;
    }
  }]);

  return Domain;
})();

var exampleDomains = [{
  domain: "domain.com",
  visits: 58,
  lastSevenDays: null,
  productivity: 2
}, {
  domain: "bomb.com",
  visits: 68,
  lastSevenDays: null,
  productivity: 1
}, {
  domain: "wombo.com",
  visits: 20,
  lastSevenDays: null,
  productivity: 1
}, {
  domain: "everybodywombo.com",
  visits: 90,
  lastSevenDays: null,
  productivity: 0
}];

var domains = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;

try {
  for (var _iterator = exampleDomains[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
    var item = _step.value;

    var d = new Domain(item);
    domains.push(d);
  }
  //*/
  /**** END TEST DUMMY DATA ****/

  /*
  *   recieve data to render and decide what to render
  *   renderGraph manages and decides which graph to render
  *   based on input
  */
} catch (err) {
  _didIteratorError = true;
  _iteratorError = err;
} finally {
  try {
    if (!_iteratorNormalCompletion && _iterator["return"]) {
      _iterator["return"]();
    }
  } finally {
    if (_didIteratorError) {
      throw _iteratorError;
    }
  }
}

var renderGraph = function renderGraph(domains) {
  if (VERBOSE) {
    console.debug("FUNCTION CALL: renderGraph()");
  }
  var categoryData = [{ x: "Unknown", visits: 0, value: 0 }, { x: "Unproductive", visits: 0, value: 1 }, { x: "Productive", visits: 0, value: 2 }];
  var _iteratorNormalCompletion2 = true;
  var _didIteratorError2 = false;
  var _iteratorError2 = undefined;

  try {
    for (var _iterator2 = domains[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
      item = _step2.value;

      categoryData[item.productivity].visits += item.visits;
    }
  } catch (err) {
    _didIteratorError2 = true;
    _iteratorError2 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion2 && _iterator2["return"]) {
        _iterator2["return"]();
      }
    } finally {
      if (_didIteratorError2) {
        throw _iteratorError2;
      }
    }
  }

  renderPieGraph(categoryData);
  //renderBarGraph(categoryData);
};

var renderBarGraph = function renderBarGraph(data) {
  console.log(data);
  var colorScale = new Plottable.Scales.Color();
  colorScale.range(["#FF00FF", "#FF0000", "#0000FF"]);

  var xScale = new Plottable.Scales.Category();
  var yScale = new Plottable.Scales.Linear();

  var xAxis = new Plottable.Axes.Category(xScale, "bottom");
  var yAxis = new Plottable.Axes.Numeric(yScale, "left");

  var baseVal = data[0].visits / 2;
  var _iteratorNormalCompletion3 = true;
  var _didIteratorError3 = false;
  var _iteratorError3 = undefined;

  try {
    for (var _iterator3 = data[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
      item = _step3.value;

      if (item.visits / 2 < baseVal) {
        baseVal = item.visits / 2;
      }
    }
  } catch (err) {
    _didIteratorError3 = true;
    _iteratorError3 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion3 && _iterator3["return"]) {
        _iterator3["return"]();
      }
    } finally {
      if (_didIteratorError3) {
        throw _iteratorError3;
      }
    }
  }

  var plot = new Plottable.Plots.Bar().addDataset(new Plottable.Dataset(data)).x(function (d) {
    return d.x;
  }, xScale).y(function (d) {
    return d.visits;
  }, yScale).animated(true).attr("fill", function (d) {
    return d.visits;
  }, colorScale).baselineValue(baseVal).labelsEnabled(true);
  new Plottable.Components.Table([[yAxis, plot], [null, xAxis]]).renderTo("svg#graph");
  window.addEventListener("resize", function () {
    plot.redraw();
  });
};

var renderPieGraph = function renderPieGraph(data) {
  var scale = new Plottable.Scales.Linear();
  var colorScale = new Plottable.Scales.Color();
  colorScale.range(["#FF00FF", "#FF0000", "#0000FF"]);
  var legend = new Plottable.Components.Legend(colorScale);
  colorScale.domain([data[0].x, data[1].x, data[2].x]);
  legend.xAlignment("left");
  legend.yAlignment("top");

  var plot = new Plottable.Plots.Pie().addDataset(new Plottable.Dataset(data)).sectorValue(function (d) {
    return d.visits;
  }, scale).innerRadius(0).attr("fill", function (d) {
    return d.x;
  }, colorScale).outerRadius(60).labelsEnabled(true).renderTo("svg#graph");
  legend.renderTo("svg#graph");
  window.addEventListener("resize", function () {
    plot.redraw();
  });
};

var fetchWikipediaArticle = function fetchWikipediaArticle(titleName) {

  var wikiArticleLink = "http://en.wikipedia.org/wiki/" + titleName;

  var container = $(".wikipedia-container");
  var templateString = wikipediaArticleTemplate.join("\n");
  var compiled = _.template(templateString);

  var handleData = function handleData(data) {

    var truncatedSummary = "not found";
    var imageUrl = "images/notfound.png";
    var title = "Article Could Not Be Fetched";

    if (data.summary != undefined) {
      if (data.summary.title != undefined) {
        title = data.summary.title;
      }

      if (data.summary.image != undefined) {
        imageUrl = data.summary.image;
      }

      if (data.summary.summary != undefined) {
        truncatedSummary = data.summary.summary.substring(0, 150) + "...";
      }
    }

    var rendered = compiled({
      title: title,
      imageUrl: imageUrl,
      summary: truncatedSummary
    });

    container.append(rendered);
  };

  WIKIPEDIA.getData(wikiArticleLink, handleData);

  /****
  var wikiArticleLink = "http://en.wikipedia.org/wiki/Invasion_of_Normandy";
  var handleData = function(data){
     console.log(data.summary);
    console.log(data.summary.title);
     $("#title").html($("#title").html() + "" + data.summary.title);
     console.log(data.summary.summary);
    $("#summary").html($("#summary").html() + "" + data.summary.summary.substring(0,150) + "...");
     console.log(data.summary.image);
    //$("#image").html($("#image").html() + "" + data.summary.image);
    $("#put-image-here").attr("src", imageLink(data));
    $("#image-link").attr("href", wikiArticleLink);
  }
   function imageLink(data){
    return data.summary.image;
  }
   var handleError = function handleError(error){
    console.log(error);
  }
   */
};

var renderDomainList = function renderDomainList(domains, renderTargetSelector) {
  if (VERBOSE) {
    console.debug("FUNCTION: renderDomainList()", domains, renderTargetSelector);
  }

  //Somewhere in here throws the error
  /*Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval'
    is not an allowed source of script in the following Content Security Policy directive:
    "script-src 'self' blob: filesystem: chrome-extension-resource:".*/

  var str = "";
  var _iteratorNormalCompletion4 = true;
  var _didIteratorError4 = false;
  var _iteratorError4 = undefined;

  try {
    for (var _iterator4 = domains[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
      var d = _step4.value;

      d.setTemplate(domainListingTemplate);
      str += d.render();
    }
  } catch (err) {
    _didIteratorError4 = true;
    _iteratorError4 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion4 && _iterator4["return"]) {
        _iterator4["return"]();
      }
    } finally {
      if (_didIteratorError4) {
        throw _iteratorError4;
      }
    }
  }

  var _iteratorNormalCompletion5 = true;
  var _didIteratorError5 = false;
  var _iteratorError5 = undefined;

  try {
    for (var _iterator5 = $(renderTargetSelector)[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
      var n = _step5.value;

      n.innerHTML = str;
    }
  } catch (err) {
    _didIteratorError5 = true;
    _iteratorError5 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion5 && _iterator5["return"]) {
        _iterator5["return"]();
      }
    } finally {
      if (_didIteratorError5) {
        throw _iteratorError5;
      }
    }
  }
};

var DOMLoaded = function DOMLoaded() {
  if (VERBOSE) {
    console.debug("EVENT: DOMContentLoaded");
  }
  console.log(getDomains());
  renderGraph(exampleDomains);
  renderDomainList(domains, "ul.domain-list-productive");
  var articles = ["Invasion_of_Normandy", "Banana", "Arthur_Tedder,_1st_Baron_Tedder"];
  var _iteratorNormalCompletion6 = true;
  var _didIteratorError6 = false;
  var _iteratorError6 = undefined;

  try {
    for (var _iterator6 = articles[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
      var a = _step6.value;

      fetchWikipediaArticle(a);
    }
  } catch (err) {
    _didIteratorError6 = true;
    _iteratorError6 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion6 && _iterator6["return"]) {
        _iterator6["return"]();
      }
    } finally {
      if (_didIteratorError6) {
        throw _iteratorError6;
      }
    }
  }
};

document.addEventListener('DOMContentLoaded', DOMLoaded, false);<|endoftext|>


<commit_before>//Read http://lodash.com/docs#template to understand what is "${whatever}" is.
//TLDR: do not change ids inside of ${...}

//Value can be a string or function that will return a string

define(function (require, exports, module){
    module.exports = {
        downloads: 'Загрузки',
        hide: 'Скрыть',
        more: 'ещё',
        oneMoreVersion: '
... и ещё одна версия.
',
        sortby: 'Сортировать по ...',
        author: 'Автор',
        update: 'Обновление',
        trending: 'Тренд', //0.3.0
        name: 'Название',
        daily: 'загрузок за день', //0.3.0
        stars: 'Звёзды', //0.4.0
        forks: 'Форки', //0.4.0
        themes: 'Темы', //0.5.0

        /*BADGES - 0.3.2*/
        badgeAdobe: 'Adobe',
        badgeAdobeTitle: 'Расширение от Adobe',

        badge100k: '100 тыс. загрузок',
        badge100kTitle: 'Первое расширение, набравщее 100 тыс. загрузок',

        badgeTop: 'Лучшее',
        badgeTopTitle: 'Самое популярное расширение',

        badgeTrend: 'Трендовое',
        badgeTrendTitle: 'Самое трендовое расширение',

        badgeNew: 'Новое',
        badgeNewTitle: 'Новое расширение',

        badgeStarsTitle: 'Самое популярное расширение на GitHub`е', //0.4.0
        badgeForksTitle: 'Расширение, больше всего раз форкнутое на GitHub`е', //0.4.0

        themeTitle: 'Тема для Brackets',
        /*END of BADGES*/

        onlineTitle: 'Количество пользователей, которые используют это расширение сейчас. Нажмите, чтобы узнать как это число вычисляется.', //0.5.0
        maxUsersTitle: 'Общее количество пользователей, использующих это расширение.', //0.5.0

        //Detailed info about ##
        'click-more': 'Подробная информация о', //0.3.0

        //Online for ## days, ## downloads per day
        statusTemplate: '
В сети ${days} дней, ${daily} ${str_daily}, ${dpd} загрузок за день
',

        //v ## from ## - ## downloads

        versionTemplate: '
v ${version} от ${date} - ${downloads} загрузок
',

        //... and ## more versions
        moreVersionsTemplate: '
... и ${count} ещё версий
',

        //0.5.4
        colorDark: 'тёмная',
        colorLight: 'светлая'
    }
});
<commit_msg>A few change for Russian translation<commit_after>//Read http://lodash.com/docs#template to understand what is "${whatever}" is.
//TLDR: do not change ids inside of ${...}

//Value can be a string or function that will return a string

define(function (require, exports, module){
    module.exports = {
        downloads: 'Загрузки',
        hide: 'Скрыть',
        more: 'ещё',
        oneMoreVersion: '
... и ещё одна версия.
',
        sortby: 'Сортировать по ...',
        author: 'Автор',
        update: 'Обновление',
        trending: 'Тренд', //0.3.0
        name: 'Название',
        daily: 'загрузок за день', //0.3.0
        stars: 'Звёзды', //0.4.0
        forks: 'Форки', //0.4.0
        themes: 'Темы', //0.5.0

        /*BADGES - 0.3.2*/
        badgeAdobe: 'Adobe',
        badgeAdobeTitle: 'Расширение от Adobe',

        badge100k: '100 тыс. загрузок',
        badge100kTitle: 'Первое расширение, набравщее 100 тыс. загрузок',

        badgeTop: 'Лучшее',
        badgeTopTitle: 'Самое популярное расширение',

        badgeTrend: 'Трендовое',
        badgeTrendTitle: 'Самое трендовое расширение',

        badgeNew: 'Новое',
        badgeNewTitle: 'Новое расширение',

        badgeStarsTitle: 'Самое популярное расширение на GitHub`е', //0.4.0
        badgeForksTitle: 'Расширение, больше всего раз форкнутое на GitHub`е', //0.4.0

        themeTitle: 'Тема для Brackets',
        /*END of BADGES*/

        onlineTitle: 'Количество пользователей, которые используют это расширение сейчас. Нажмите, чтобы узнать как это число вычисляется.', //0.5.0
        maxUsersTitle: 'Общее количество пользователей, использующих это расширение.', //0.5.0

        //Detailed info about ##
        'click-more': 'Подробная информация о', //0.3.0

        //Online for ## days, ## downloads per day
        statusTemplate: '
В сети ${days} дней, ${daily} ${str_daily}, ${dpd} загрузок за день
',

        //v ## from ## - ## downloads

        versionTemplate: '
v ${version} от ${date} - ${downloads} загрузок
',

        //... and ## more versions
        moreVersionsTemplate: '
... и ещё ${count} версий
',

        //0.5.4
        colorDark: 'тёмная',
        colorLight: 'светлая'
    }
});
<|endoftext|>


<commit_before>import { sortBy } from "lodash";

const adForRequest = ad => ({
  id: ad.id,
  html: ad.html,
  targeting: ad.targeting
});

const endpoint =
  process.env.NODE_ENV === "production"
    ? "https://projects.propublica.org/facebook-ads/ads"
    : "http://localhost:8080/facebook-ads/ads";

const headers = language =>
  new Headers({
    "Accept-Language": language.language + "-" + language.country + ";q=1.0"
  });

const sendAds = (body, language) =>
  fetch(endpoint, {
    method: "POST",
    mode: "no-cors",
    headers: headers(language),
    body: JSON.stringify(body)
  });

const getAds = (language, cb) =>
  fetch(endpoint, {
    method: "GET",
    headers: headers(language)
  })
    .then(res => res.json())
    .then(ads => cb(ads.ads || ads));

const mergeAds = (ads, newAds) => {
  let ids = new Map(ads.map(ad => [ad.id, ad]));
  newAds.forEach(ad => {
    if (ids.has(ad.id)) {
      let old = ids.get(ad.id);
      let newAd = Object.assign({}, old, ad);
      ids.set(newAd.id, newAd);
    } else {
      ids.set(ad.id, ad);
    }
  });
  const idSort = sortBy(
    Array.from(ids.values()),
    a => -1 * Date.parse(a.created_at)
  );
  return sortBy(idSort, a => a.rating === "political").slice(0, 100);
};

const updateBadge = ratings => {
  const num = ratings.filter(rating => !("rating" in rating)).length;
  if (num > 0) {
    chrome.browserAction.setBadgeText({ text: num > 100 ? "100+" : "" + num });
  } else {
    chrome.browserAction.setBadgeText({ text: "" });
  }
};

const getBrowserLocale = () => ({
  language: navigator.language.split("-")[0],
  country: navigator.language.split("-")[1]
});

export {
  sendAds,
  getAds,
  mergeAds,
  updateBadge,
  adForRequest,
  getBrowserLocale
};
<commit_msg>Adds multiple languages check<commit_after>import { sortBy } from "lodash";

const adForRequest = ad => ({
  id: ad.id,
  html: ad.html,
  targeting: ad.targeting
});

const endpoint =
  process.env.NODE_ENV === "production"
    ? "https://projects.propublica.org/facebook-ads/ads"
    : "http://localhost:8080/facebook-ads/ads";

const headers = language =>
  new Headers({
    "Accept-Language": language.language + "-" + language.country + ";q=1.0"
  });

const sendAds = (body, language) =>
  fetch(endpoint, {
    method: "POST",
    mode: "no-cors",
    headers: headers(language),
    body: JSON.stringify(body)
  });

const getAds = (language, cb) =>
  fetch(endpoint, {
    method: "GET",
    headers: headers(language)
  })
    .then(res => res.json())
    .then(ads => cb(ads.ads || ads));

const mergeAds = (ads, newAds) => {
  let ids = new Map(ads.map(ad => [ad.id, ad]));
  newAds.forEach(ad => {
    if (ids.has(ad.id)) {
      let old = ids.get(ad.id);
      let newAd = Object.assign({}, old, ad);
      ids.set(newAd.id, newAd);
    } else {
      ids.set(ad.id, ad);
    }
  });
  const idSort = sortBy(
    Array.from(ids.values()),
    a => -1 * Date.parse(a.created_at)
  );
  return sortBy(idSort, a => a.rating === "political").slice(0, 100);
};

const updateBadge = ratings => {
  const num = ratings.filter(rating => !("rating" in rating)).length;
  if (num > 0) {
    chrome.browserAction.setBadgeText({ text: num > 100 ? "100+" : "" + num });
  } else {
    chrome.browserAction.setBadgeText({ text: "" });
  }
};

const getBrowserLocale = () => {
  const lang = navigator.languages && navigator.languages.length ? navigator.languages[0] : navigator.language;
  return {
    language: lang.split("-")[0],
    country: lang.split("-")[1]
  };
};

export {
  sendAds,
  getAds,
  mergeAds,
  updateBadge,
  adForRequest,
  getBrowserLocale
};
<|endoftext|>


<commit_before>// Extensions

// keep this wrapper around the ones you use!
(function( undefined ){

	wrap.fn.parent = function(){
		var ret = [],
			parent;
		this.each(function(){
			parent = this.parentElement;
			if( parent ){
				ret.push( parent );
			}
		});
		return wrap(ret);
	};

	wrap.fn.parents = function( sel ){
		var ret = [];

		this.each(function(){
			var curr = this,
				match;
			while( curr.parentElement && !match ){
				curr = curr.parentElement;
				if( sel ){
					if( curr === wrap( sel )[0] ){
						match = true;
						if( !wrap.inArray( ret, curr ) ){
							ret.push( curr );
						}
					}
				}
				else {
					if( !wrap.inArray( ret, curr ) ){
						ret.push( curr );
					}
				}
			}
		});
		return wrap(ret);
	};

	wrap.fn.next = function(){
		var ret = [],
			next;
		this.each(function( i ){
			next = this.nextElementSibling;
			if( next ){
				ret = ret.concat( next );
			}
		});
		return wrap(ret);
	};

	wrap.fn.prev = function(){
		var ret = [],
			next;
		this.each(function( i ){
			next = this.previousElementSibling;
			if( next ){
				ret = ret.concat( next );
			}
		});
		return wrap(ret);
	};

	wrap.fn.addClass = function( cname ){
		return this.each(function(){
			this.className += " " + cname;
		});
	};

	wrap.fn.removeClass = function( cname ){
		return this.each(function(){
			this.className = this.className.replace( new RegExp( cname, "gmi" ), "" );
		});
	};

	wrap.fn.attr = function( name, val ){
		if( val !== undefined ){
			return this.each(function(){
				this.setAttribute( name, val );
			});
		}
		else {
			return this[ 0 ].getAttribute( name );
		}
	};

	wrap.fn.prop = function( name, val ){
		if( val !== undefined ){
			return this.each(function(){
				this[ name ] = val;
			});
		}
		else {
			return this[ 0 ][ name ];
		}
	};

	wrap.fn.html = function( html ){
		if( html ){
			return this.each(function(){
				this.innerHTML = html;
			});
		}
		else{
			var pile = "";
			return this.each(function(){
				pile += this.innerHTML;
			});
			return pile;
		}
	};

	wrap.fn.append = function( frag ){
		if( typeof( frag ) === "string" ){
			frag = wrap( frag );
		}
		return this.each(function( i ){
			for( var j = 0, jl = frag.length; j < jl; j++ ){
				this.appendChild( i > 0 ? frag[ j ].cloneNode( true ) : frag[ j ] );
			}
		});
	};

	wrap.fn.prepend = function( frag ){
		if( typeof( frag ) === "string" ){
			frag = wrap( frag );
		}
		return this.each(function( i ){
			for( var j = 0, jl = frag.length; j < jl; j++ ){
				var insertEl = i > 0 ? frag[ j ].cloneNode( true ) : frag[ j ];
				if ( this.firstChild ){
					this.insertBefore( insertEl, this.firstChild );
				}
				else {
					this.appendChild( insertEl );
				}
			}
		});
	};

	wrap.fn.before = function( frag ){
		if( typeof( frag ) === "string" ){
			frag = wrap( frag );
		}
		return this.each(function( i ){
			for( var j = 0, jl = frag.length; j < jl; j++ ){
				this.parentNode.insertBefore( i > 0 ? frag[ j ].cloneNode( true ) : frag[ j ], this );
			}
		});
	};

	wrap.fn.after = function( frag ){
		if( typeof( frag ) === "string" ){
			frag = wrap( frag );
		}
		return this.each(function( i ){
			for( var j = 0, jl = frag.length; j < jl; j++ ){
				var insertEl = i > 0 ? frag[ j ].cloneNode( true ) : frag[ j ];
				this.parentNode.insertBefore( insertEl, this );
				this.parentNode.insertBefore( this, insertEl );
			}
		});
	};

	wrap.fn.replaceWith = function( frag ){
		if( typeof( frag ) === "string" ){
			frag = wrap( frag );
		}
		var ret = [];
		this.each(function( i ){
			for( var j = 0, jl = frag.length; j < jl; j++ ){
				var insertEl = i > 0 ? frag[ j ].cloneNode( true ) : frag[ j ];
				this.parentNode.insertBefore( insertEl, this );
				insertEl.parentNode.removeChild( this );
				ret.push( insertEl );
			}
		});
		return wrap( ret );
	};

	wrap.fn.filter = function( sel ){
		var ret = [],
			sel = wrap( sel );
		this.each(function( i ){
			if( wrap.inArray( sel, this ) ){
				ret.push( this );
			}
		});
		return wrap( ret );
	};

	wrap.fn.not = function( sel ){
		var ret = [],
			sel = wrap( sel );
		this.each(function( i ){
			if( !wrap.inArray( sel, this ) ){
				ret.push( this );
			}
		});
		return wrap( ret );
	};

	wrap.fn.is = function( sel ){
		var ret = false,
			sel = wrap( sel );
		this.each(function( i ){
			if( wrap.inArray( sel, this ) ){
				ret = true;
			}
		});
		return ret;
	};

})();<commit_msg>added eq method<commit_after>// Extensions

// keep this wrapper around the ones you use!
(function( undefined ){

	wrap.fn.parent = function(){
		var ret = [],
			parent;
		this.each(function(){
			parent = this.parentElement;
			if( parent ){
				ret.push( parent );
			}
		});
		return wrap(ret);
	};

	wrap.fn.parents = function( sel ){
		var ret = [];

		this.each(function(){
			var curr = this,
				match;
			while( curr.parentElement && !match ){
				curr = curr.parentElement;
				if( sel ){
					if( curr === wrap( sel )[0] ){
						match = true;
						if( !wrap.inArray( ret, curr ) ){
							ret.push( curr );
						}
					}
				}
				else {
					if( !wrap.inArray( ret, curr ) ){
						ret.push( curr );
					}
				}
			}
		});
		return wrap(ret);
	};

	wrap.fn.next = function(){
		var ret = [],
			next;
		this.each(function( i ){
			next = this.nextElementSibling;
			if( next ){
				ret = ret.concat( next );
			}
		});
		return wrap(ret);
	};

	wrap.fn.prev = function(){
		var ret = [],
			next;
		this.each(function( i ){
			next = this.previousElementSibling;
			if( next ){
				ret = ret.concat( next );
			}
		});
		return wrap(ret);
	};

	wrap.fn.addClass = function( cname ){
		return this.each(function(){
			this.className += " " + cname;
		});
	};

	wrap.fn.removeClass = function( cname ){
		return this.each(function(){
			this.className = this.className.replace( new RegExp( cname, "gmi" ), "" );
		});
	};

	wrap.fn.attr = function( name, val ){
		if( val !== undefined ){
			return this.each(function(){
				this.setAttribute( name, val );
			});
		}
		else {
			return this[ 0 ].getAttribute( name );
		}
	};

	wrap.fn.prop = function( name, val ){
		if( val !== undefined ){
			return this.each(function(){
				this[ name ] = val;
			});
		}
		else {
			return this[ 0 ][ name ];
		}
	};

	wrap.fn.html = function( html ){
		if( html ){
			return this.each(function(){
				this.innerHTML = html;
			});
		}
		else{
			var pile = "";
			return this.each(function(){
				pile += this.innerHTML;
			});
			return pile;
		}
	};

	wrap.fn.append = function( frag ){
		if( typeof( frag ) === "string" ){
			frag = wrap( frag );
		}
		return this.each(function( i ){
			for( var j = 0, jl = frag.length; j < jl; j++ ){
				this.appendChild( i > 0 ? frag[ j ].cloneNode( true ) : frag[ j ] );
			}
		});
	};

	wrap.fn.prepend = function( frag ){
		if( typeof( frag ) === "string" ){
			frag = wrap( frag );
		}
		return this.each(function( i ){
			for( var j = 0, jl = frag.length; j < jl; j++ ){
				var insertEl = i > 0 ? frag[ j ].cloneNode( true ) : frag[ j ];
				if ( this.firstChild ){
					this.insertBefore( insertEl, this.firstChild );
				}
				else {
					this.appendChild( insertEl );
				}
			}
		});
	};

	wrap.fn.before = function( frag ){
		if( typeof( frag ) === "string" ){
			frag = wrap( frag );
		}
		return this.each(function( i ){
			for( var j = 0, jl = frag.length; j < jl; j++ ){
				this.parentNode.insertBefore( i > 0 ? frag[ j ].cloneNode( true ) : frag[ j ], this );
			}
		});
	};

	wrap.fn.after = function( frag ){
		if( typeof( frag ) === "string" ){
			frag = wrap( frag );
		}
		return this.each(function( i ){
			for( var j = 0, jl = frag.length; j < jl; j++ ){
				var insertEl = i > 0 ? frag[ j ].cloneNode( true ) : frag[ j ];
				this.parentNode.insertBefore( insertEl, this );
				this.parentNode.insertBefore( this, insertEl );
			}
		});
	};

	wrap.fn.replaceWith = function( frag ){
		if( typeof( frag ) === "string" ){
			frag = wrap( frag );
		}
		var ret = [];
		this.each(function( i ){
			for( var j = 0, jl = frag.length; j < jl; j++ ){
				var insertEl = i > 0 ? frag[ j ].cloneNode( true ) : frag[ j ];
				this.parentNode.insertBefore( insertEl, this );
				insertEl.parentNode.removeChild( this );
				ret.push( insertEl );
			}
		});
		return wrap( ret );
	};

	wrap.fn.filter = function( sel ){
		var ret = [],
			sel = wrap( sel );
		this.each(function( i ){
			if( wrap.inArray( sel, this ) ){
				ret.push( this );
			}
		});
		return wrap( ret );
	};

	wrap.fn.not = function( sel ){
		var ret = [],
			sel = wrap( sel );
		this.each(function( i ){
			if( !wrap.inArray( sel, this ) ){
				ret.push( this );
			}
		});
		return wrap( ret );
	};

	wrap.fn.is = function( sel ){
		var ret = false,
			sel = wrap( sel );
		this.each(function( i ){
			if( wrap.inArray( sel, this ) ){
				ret = true;
			}
		});
		return ret;
	};

	wrap.fn.eq = function( num ){
		return this[ num ];
	};

})();<|endoftext|>


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

/**
 * blessed-telnet.js
 * https://github.com/chjj/blessed
 * Copyright (c) 2013-2015, Christopher Jeffrey (MIT License)
 * A blessed telnet server.
 * See: https://github.com/TooTallNate/node-telnet
 */

process.title = 'blessed-telnet';

var fs = require('fs');
var blessed = require('blessed');
var telnet = require('telnet');

var server = telnet.createServer(function(client) {
  client.do.transmit_binary();
  client.do.terminal_type();
  client.do.window_size();

  client.on('terminal type', function(data) {
    // https://tools.ietf.org/html/rfc884
    if (data.command === 'sb' && data.buf[3] === 1) {
      var TERM = data.buf.slice(4, -2).toString('ascii');
      screen.terminal = TERM;
      screen.render();
    }
  });

  client.on('window size', function(data) {
    if (data.command === 'sb') {
      client.columns = data.columns;
      client.rows = data.rows;
      client.emit('resize');
    }
  });

  // Make the client look like a tty:
  client.setRawMode = function(mode) {
    client.isRaw = mode;
    if (!client.writable) return;
    if (mode) {
      client.do.suppress_go_ahead();
      client.will.suppress_go_ahead();
      client.will.echo();
    } else {
      client.dont.suppress_go_ahead();
      client.wont.suppress_go_ahead();
      client.wont.echo();
    }
  };
  client.isTTY = true;
  client.isRaw = false;
  client.columns = 80;
  client.rows = 24;

  var screen = blessed.screen({
    smartCSR: true,
    input: client,
    output: client,
    terminal: 'xterm-256color'
  });

  client.on('close', function() {
    if (!screen.destroyed) {
      screen.destroy();
    }
  });

  screen.key(['C-c', 'q'], function(ch, key) {
    screen.destroy();
  });

  screen.on('destroy', function() {
    if (client.writable) {
      client.destroy();
    }
  });

  if (test === 'widget-simple') {
    return simpleTest(screen);
  }

  loadTest(screen, test);
});

function simpleTest(screen) {
  screen.data.main = blessed.box({
    parent: screen,
    width: '80%',
    height: '90%',
    border: 'line',
    content: 'Welcome to my server. Here is your own private session.',
    style: {
      bg: 'red'
    }
  });

  screen.key('i', function() {
    screen.data.main.style.bg = 'blue';
    screen.render();
  });

  screen.render();
}

var test = 'widget-' + (process.argv[2] || 'shadow');
if (test === 'widget-png') process.argv.length = 2;

function loadTest(screen, name) {
  var Screen = blessed.screen;
  var key = screen.key;
  blessed.screen = function() { return screen; };
  screen.key = function(keys) {
    keys = [].concat(keys)
    if (~keys.indexOf('q') || ~keys.indexOf('C-c') || ~keys.indexOf('escape')) {
      return;
    }
    return key.apply(screen, arguments);
  };
  var path = require.resolve('../test/' + name);
  delete require.cache[path];
  require('../test/' + name);
  blessed.screen = Screen;
  screen.key = key;
}

server.listen(2300);
console.log('Listening on 2300...');
<commit_msg>blessed-telnet: handle env variables.<commit_after>#!/usr/bin/env node

/**
 * blessed-telnet.js
 * https://github.com/chjj/blessed
 * Copyright (c) 2013-2015, Christopher Jeffrey (MIT License)
 * A blessed telnet server.
 * See: https://github.com/TooTallNate/node-telnet
 */

process.title = 'blessed-telnet';

var fs = require('fs');
var blessed = require('blessed');
var telnet = require('telnet');

process.on('uncaughtException', function(err) {
  console.error(err ? err.stack : err + '');
});

var server = telnet.createServer(function(client) {
  client.do.transmit_binary();
  client.do.terminal_type();
  client.do.window_size();
  client.do.environment_variables();

  client.on('environment variables', function(data) {
    if (data.command === 'sb') {
      if (data.name === 'TERM') {
        screen.terminal = data.value;
        screen.render();
      }
    }
  });

  client.on('terminal type', function(data) {
    // https://tools.ietf.org/html/rfc884
    if (data.command === 'sb' && data.buf[3] === 1) {
      var TERM = data.buf.slice(4, -2).toString('ascii');
      screen.terminal = TERM;
      screen.render();
    }
  });

  client.on('window size', function(data) {
    if (data.command === 'sb') {
      client.columns = data.columns;
      client.rows = data.rows;
      client.emit('resize');
    }
  });

  // Make the client look like a tty:
  client.setRawMode = function(mode) {
    client.isRaw = mode;
    if (!client.writable) return;
    if (mode) {
      client.do.suppress_go_ahead();
      client.will.suppress_go_ahead();
      client.will.echo();
    } else {
      client.dont.suppress_go_ahead();
      client.wont.suppress_go_ahead();
      client.wont.echo();
    }
  };
  client.isTTY = true;
  client.isRaw = false;
  client.columns = 80;
  client.rows = 24;

  var screen = blessed.screen({
    smartCSR: true,
    input: client,
    output: client,
    terminal: 'xterm-256color'
  });

  client.on('close', function() {
    if (!screen.destroyed) {
      screen.destroy();
    }
  });

  screen.key(['C-c', 'q'], function(ch, key) {
    screen.destroy();
  });

  screen.on('destroy', function() {
    if (client.writable) {
      client.destroy();
    }
  });

  if (test === 'widget-simple') {
    return simpleTest(screen);
  }

  loadTest(screen, test);
});

function simpleTest(screen) {
  screen.data.main = blessed.box({
    parent: screen,
    width: '80%',
    height: '90%',
    border: 'line',
    content: 'Welcome to my server. Here is your own private session.',
    style: {
      bg: 'red'
    }
  });

  screen.key('i', function() {
    screen.data.main.style.bg = 'blue';
    screen.render();
  });

  screen.render();
}

var test = 'widget-' + (process.argv[2] || 'shadow');
if (test === 'widget-png') process.argv.length = 2;

function loadTest(screen, name) {
  var Screen = blessed.screen;
  var key = screen.key;
  blessed.screen = function() { return screen; };
  screen.key = function(keys) {
    keys = [].concat(keys)
    if (~keys.indexOf('q') || ~keys.indexOf('C-c') || ~keys.indexOf('escape')) {
      return;
    }
    return key.apply(screen, arguments);
  };
  var path = require.resolve('../test/' + name);
  delete require.cache[path];
  require('../test/' + name);
  blessed.screen = Screen;
  screen.key = key;
}

server.listen(2300);
console.log('Listening on 2300...');
<|endoftext|>


<commit_before>// ==UserScript==
// @name          Google Thumbnails for Safari
// @version       0.2
// @namespace     http://niw.at/
// @description   Adds web site thumbnail images to google search results, original is from http://flet.ch/things/greasemonkey/
// @include       http://www.google.*/search*
// ==/UserScript==

(function () {
try {
	function array_each(a, f) {
		for(var i = 0; i < a.length; i++) {
			f(a[i]);
		}
	}
	function insertNext(h, a) {
		h.parentNode.insertBefore(a, h.nextSibling);
	}
	function xpath(xpath, context) {
		var result = [];
		var elements = document.evaluate(xpath, context, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		for(var i = 0; i < elements.snapshotLength; i++) {
			result.push(elements.snapshotItem(i));
		}
		return result;
	}
	array_each(xpath("//*[((name() = 'LI' or name() = 'li') and contains(@class,'g'))]", document), function(result) {
		var result_link = xpath("./h3/a", result)[0];
		if(result_link) {
			result.setAttribute("style", result.getAttribute("style") + "; clear: left;");
			var result_url = result_link.getAttribute("href");
			var real_result_url = result_url.replace(/^(?:([^\/].*)|\/url\?.*q=([^&]+)&?.*$)/i, "$1$2");
			var letter = real_result_url.replace(/^[^:]*:\/\/(?:www\.)?(.).*/, "$1");
			var thumb_url = "http://" + letter + ".googlepreview.com/preview?s=" + real_result_url;

			var thumbnail = document.createElement("div");
			thumbnail.setAttribute("style", "float: left; margin: 0 8px 2px 0; width: 110px; height: 80px; overflow: hidden; background: #D5DDF3; border: 1px solid #3366CC;");
			thumbnail.innerHTML = '';
			insertNext(result_link, thumbnail);
		}
	});
} catch(exception) {
	var tag = document.createElement("div");
	tag.setAttribute("style", "padding: 4px; font-size: 10px; color: #fff; border: 1px solid #f00; background: #c00;");
	tag.appendChild(document.createTextNode(exception));
	document.body.insertBefore(tag, document.body.firstChild);
}
})();
<commit_msg>Support AutoPagerize<commit_after>// ==UserScript==
// @name          Google Thumbnails for Safari
// @version       0.2.1
// @namespace     http://niw.at/
// @description   Adds web site thumbnail images to google search results, original is from http://flet.ch/things/greasemonkey/
// @include       http://www.google.*/search*
// ==/UserScript==

(function () {
try {
	function array_each(a, f) {
		for(var i = 0; i < a.length; i++) {
			f(a[i]);
		}
	}
	function insertNext(h, a) {
		h.parentNode.insertBefore(a, h.nextSibling);
	}
	function xpath(xpath, context) {
		var result = [];
		var elements = document.evaluate(xpath, context, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		for(var i = 0; i < elements.snapshotLength; i++) {
			result.push(elements.snapshotItem(i));
		}
		return result;
	}
	function addThumbnails(target) {
		array_each(xpath(".//*[((name() = 'LI' or name() = 'li') and contains(@class,'g'))]", target), function(result) {
			var result_link = xpath("./h3/a", result)[0];
			if(result_link) {
				result.setAttribute("style", result.getAttribute("style") + "; clear: left;");
				var result_url = result_link.getAttribute("href");
				var real_result_url = result_url.replace(/^(?:([^\/].*)|\/url\?.*q=([^&]+)&?.*$)/i, "$1$2");
				var letter = real_result_url.replace(/^[^:]*:\/\/(?:www\.)?(.).*/, "$1");
				var thumb_url = "http://" + letter + ".googlepreview.com/preview?s=" + real_result_url;

				var thumbnail = document.createElement("div");
				thumbnail.setAttribute("style", "float: left; margin: 0 8px 2px 0; width: 110px; height: 80px; overflow: hidden; background: #D5DDF3; border: 1px solid #3366CC;");
				thumbnail.innerHTML = '';
				insertNext(result_link, thumbnail);
			}
		});
	}
	document.body.addEventListener("AutoPagerize_DOMNodeInserted", function(e){
		var node = e.target;
		addThumbnails(node);
	}, false);
	addThumbnails(document);
} catch(exception) {
	var tag = document.createElement("div");
	tag.setAttribute("style", "padding: 4px; font-size: 10px; color: #fff; border: 1px solid #f00; background: #c00;");
	tag.appendChild(document.createTextNode(exception));
	document.body.insertBefore(tag, document.body.firstChild);
}
})();
<|endoftext|>


<commit_before>(function () {
  // Stop from running again, if accidently included more than once.
  if (window.hasCookieConsent) return;
  window.hasCookieConsent = true;

  /*
   Constants
   */

  // Client variable which may be present containing options to override with
  var OPTIONS_VARIABLE = 'cookieconsent_options';

  // Change cookie consent options on the fly.
  var OPTIONS_UPDATER = 'update_cookieconsent_options';

  // Name of cookie to be set when dismissed
  var DISMISSED_COOKIE = 'cookieconsent_dismissed';

  // The path to built in themes (s3 bucket)
  var THEME_BUCKET_PATH = '//s3.amazonaws.com/cc.silktide.com/';

  // No point going further if they've already dismissed.
  if (document.cookie.indexOf(DISMISSED_COOKIE) > -1 || (window.navigator && window.navigator.CookiesOK)) {
    return;
  }

  // IE8...
  if(typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function() {
      return this.replace(/^\s+|\s+$/g, '');
    };
  }

  /*
   Helper methods
   */
  var Util = {
    isArray: function (obj) {
      var proto = Object.prototype.toString.call(obj);
      return proto == '[object Array]';
    },

    isObject: function (obj) {
      return Object.prototype.toString.call(obj) == '[object Object]';
    },

    each: function (arr, callback, /* optional: */context, force) {
      if (Util.isObject(arr) && !force) {
        for (var key in arr) {
          if (arr.hasOwnProperty(key)) {
            callback.call(context, arr[key], key, arr);
          }
        }
      } else {
        for (var i = 0, ii = arr.length; i < ii; i++) {
          callback.call(context, arr[i], i, arr);
        }
      }
    },

    merge: function (obj1, obj2) {
      if (!obj1) return;
      Util.each(obj2, function (val, key) {
        if (Util.isObject(val) && Util.isObject(obj1[key])) {
          Util.merge(obj1[key], val);
        } else {
          obj1[key] = val;
        }
      })
    },

    bind: function (func, context) {
      return function () {
        return func.apply(context, arguments);
      };
    },

    /*
     find a property based on a . separated path.
     i.e. queryObject({details: {name: 'Adam'}}, 'details.name') // -> 'Adam'
     returns null if not found
     */
    queryObject: function (object, query) {
      var queryPart;
      var i = 0;
      var head = object;
      query = query.split('.');
      while ( (queryPart = query[i++]) && head.hasOwnProperty(queryPart) && (head = head[queryPart]) )  {
        if (i === query.length) return head;
      }
      return null;
    },

    setCookie: function (name, value, expiryDays, domain, path) {
      expiryDays = expiryDays || 365;

      var exdate = new Date();
      exdate.setDate(exdate.getDate() + expiryDays);

      var cookie = [
        name + '=' + value,
        'expires=' + exdate.toUTCString(),
        'path=' + path || '/'
      ];

      if (domain) {
        cookie.push(
          'domain=' + domain
        );
      }

      document.cookie = cookie.join(';');
    },

    addEventListener: function (el, event, eventListener) {
      if (el.addEventListener) {
        el.addEventListener(event, eventListener);
      } else {
        el.attachEvent('on' + event, eventListener);
      }
    }
  };

  var DomBuilder = (function () {
    /*
     The attribute we store events in.
     */
    var eventAttribute = 'data-cc-event';
    var conditionAttribute = 'data-cc-if';

    /*
     Shim to make addEventListener work correctly with IE.
     */
    var addEventListener = function (el, event, eventListener) {
      // Add multiple event listeners at once if array is passed.
      if (Util.isArray(event)) {
        return Util.each(event, function (ev) {
          addEventListener(el, ev, eventListener);
        });
      }

      if (el.addEventListener) {
        el.addEventListener(event, eventListener);
      } else {
        el.attachEvent('on' + event, eventListener);
      }
    };

    /*
     Replace {{variable.name}} with it's property on the scope
     Also supports {{variable.name || another.name || 'string'}}
     */
    var insertReplacements = function (htmlStr, scope) {
      return htmlStr.replace(/\{\{(.*?)\}\}/g, function (_match, sub) {
        var tokens = sub.split('||');
        var value, token;
        while (token = tokens.shift()) {
          token = token.trim();

          // If string
          if (token[0] === '"') return token.slice(1, token.length - 1);

          // If query matches
          value =  Util.queryObject(scope, token);

          if (value) return value;
        }

        return '';
      });
    };

    /*
     Turn a string of html into DOM
     */
    var buildDom = function (htmlStr) {
      var container = document.createElement('div');
      container.innerHTML = htmlStr;
      return container.children[0];
    };

    var applyToElementsWithAttribute = function (dom, attribute, func) {
      var els = dom.parentNode.querySelectorAll('[' + attribute + ']');
      Util.each(els, function (element) {
        var attributeVal = element.getAttribute(attribute);
        func(element, attributeVal);
      }, window, true);
    };

    /*
     Parse event attributes in dom and set listeners to their matching scope methods
     */
    var applyEvents = function (dom, scope) {
      applyToElementsWithAttribute(dom, eventAttribute, function (element, attributeVal) {
        var parts = attributeVal.split(':');
        var listener = Util.queryObject(scope, parts[1]);
        addEventListener(element, parts[0], Util.bind(listener, scope));
      });
    };

    var applyConditionals = function (dom, scope) {
      applyToElementsWithAttribute(dom, conditionAttribute, function (element, attributeVal) {
        var value = Util.queryObject(scope, attributeVal);
        if (!value) {
          element.parentNode.removeChild(element);
        }
      });
    };

    return {
      build: function (htmlStr, scope) {
        if (Util.isArray(htmlStr)) htmlStr = htmlStr.join('');

        htmlStr = insertReplacements(htmlStr, scope);
        var dom = buildDom(htmlStr);
        applyEvents(dom, scope);
        applyConditionals(dom, scope);

        return dom;
      }
    };
  })();

  /*
   Plugin
   */
  var cookieconsent = {
    options: {
      message: 'This website uses cookies to ensure you get the best experience on our website. ',
      dismiss: 'Got it!',
      learnMore: 'More info',
      link: null,
      target: '_self',
      container: null, // selector
      theme: 'light-floating',
      domain: null, // default to current domain.
      path: '/',
      expiryDays: 365,
      markup: [
        '
',
        '
',
        '{{options.dismiss}}',

        '
{{options.message}} {{options.learnMore}}
',

        'Cookie Consent plugin for the EU cookie law',
        '
',
        '
'
      ]
    },

    init: function () {
      var options = window[OPTIONS_VARIABLE];
      if (options) this.setOptions(options);

      this.setContainer();

      // Calls render when theme is loaded.
      if (this.options.theme) {
        this.loadTheme(this.render);
      } else {
        this.render();
      }
    },

    setOptionsOnTheFly: function (options) {
      this.setOptions(options);
      this.render();
    },

    setOptions: function (options) {
      Util.merge(this.options, options);
    },

    setContainer: function () {
      if (this.options.container) {
        this.container = document.querySelector(this.options.container);
      } else {
        this.container = document.body;
      }

      // Add class to container classes so we can specify css for IE8 only.
      this.containerClasses = '';
      if (navigator.appVersion.indexOf('MSIE 8') > -1) {
        this.containerClasses += ' cc_ie8'
      }
    },

    loadTheme: function (callback) {
      var theme = this.options.theme;

      // If theme is specified by name
      if (theme.indexOf('.css') === -1) {
        theme = THEME_BUCKET_PATH + theme + '.css';
      }

      var link = document.createElement('link');
      link.rel = 'stylesheet';
      link.type = 'text/css';
      link.href = theme;

      var loaded = false;
      link.onload = Util.bind(function () {
        if (!loaded && callback) {
          callback.call(this);
          loaded = true;
        }
      }, this);

      document.getElementsByTagName("head")[0].appendChild(link);
    },

    render: function () {
      // remove current element (if we've already rendered)
      if (this.element && this.element.parentNode) {
        this.element.parentNode.removeChild(this.element);
        delete this.element;
      }

      this.element = DomBuilder.build(this.options.markup, this);
      if (!this.container.firstChild) {
        this.container.appendChild(this.element);
      } else {
        this.container.insertBefore(this.element, this.container.firstChild);
      }
    },

    dismiss: function (evt) {
      evt.preventDefault && evt.preventDefault();
      evt.returnValue = false;
      this.setDismissedCookie();
      this.container.removeChild(this.element);
    },

    setDismissedCookie: function () {
      Util.setCookie(DISMISSED_COOKIE, 'yes', this.options.expiryDays, this.options.domain, this.options.path);
    }
  };

  var init;
  var initialized = false;
  (init = function () {
    if (!initialized && document.readyState == 'complete') {
      cookieconsent.init();
      initialized = true;
      window[OPTIONS_UPDATER] = Util.bind(cookieconsent.setOptionsOnTheFly, cookieconsent);
    }
  })();

  Util.addEventListener(document, 'readystatechange', init);

})();
<commit_msg>updated theme bucket path<commit_after>(function () {
  // Stop from running again, if accidently included more than once.
  if (window.hasCookieConsent) return;
  window.hasCookieConsent = true;

  /*
   Constants
   */

  // Client variable which may be present containing options to override with
  var OPTIONS_VARIABLE = 'cookieconsent_options';

  // Change cookie consent options on the fly.
  var OPTIONS_UPDATER = 'update_cookieconsent_options';

  // Name of cookie to be set when dismissed
  var DISMISSED_COOKIE = 'cookieconsent_dismissed';

  // The path to built in themes
  // Note: Directly linking to a version on the CDN like this is horrible, but it's less horrible than people downloading the code
  // then discovering that their CSS bucket disappeared
  var THEME_BUCKET_PATH = '//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/1.0.10/';

  // No point going further if they've already dismissed.
  if (document.cookie.indexOf(DISMISSED_COOKIE) > -1 || (window.navigator && window.navigator.CookiesOK)) {
    return;
  }

  // IE8...
  if(typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function() {
      return this.replace(/^\s+|\s+$/g, '');
    };
  }

  /*
   Helper methods
   */
  var Util = {
    isArray: function (obj) {
      var proto = Object.prototype.toString.call(obj);
      return proto == '[object Array]';
    },

    isObject: function (obj) {
      return Object.prototype.toString.call(obj) == '[object Object]';
    },

    each: function (arr, callback, /* optional: */context, force) {
      if (Util.isObject(arr) && !force) {
        for (var key in arr) {
          if (arr.hasOwnProperty(key)) {
            callback.call(context, arr[key], key, arr);
          }
        }
      } else {
        for (var i = 0, ii = arr.length; i < ii; i++) {
          callback.call(context, arr[i], i, arr);
        }
      }
    },

    merge: function (obj1, obj2) {
      if (!obj1) return;
      Util.each(obj2, function (val, key) {
        if (Util.isObject(val) && Util.isObject(obj1[key])) {
          Util.merge(obj1[key], val);
        } else {
          obj1[key] = val;
        }
      })
    },

    bind: function (func, context) {
      return function () {
        return func.apply(context, arguments);
      };
    },

    /*
     find a property based on a . separated path.
     i.e. queryObject({details: {name: 'Adam'}}, 'details.name') // -> 'Adam'
     returns null if not found
     */
    queryObject: function (object, query) {
      var queryPart;
      var i = 0;
      var head = object;
      query = query.split('.');
      while ( (queryPart = query[i++]) && head.hasOwnProperty(queryPart) && (head = head[queryPart]) )  {
        if (i === query.length) return head;
      }
      return null;
    },

    setCookie: function (name, value, expiryDays, domain, path) {
      expiryDays = expiryDays || 365;

      var exdate = new Date();
      exdate.setDate(exdate.getDate() + expiryDays);

      var cookie = [
        name + '=' + value,
        'expires=' + exdate.toUTCString(),
        'path=' + path || '/'
      ];

      if (domain) {
        cookie.push(
          'domain=' + domain
        );
      }

      document.cookie = cookie.join(';');
    },

    addEventListener: function (el, event, eventListener) {
      if (el.addEventListener) {
        el.addEventListener(event, eventListener);
      } else {
        el.attachEvent('on' + event, eventListener);
      }
    }
  };

  var DomBuilder = (function () {
    /*
     The attribute we store events in.
     */
    var eventAttribute = 'data-cc-event';
    var conditionAttribute = 'data-cc-if';

    /*
     Shim to make addEventListener work correctly with IE.
     */
    var addEventListener = function (el, event, eventListener) {
      // Add multiple event listeners at once if array is passed.
      if (Util.isArray(event)) {
        return Util.each(event, function (ev) {
          addEventListener(el, ev, eventListener);
        });
      }

      if (el.addEventListener) {
        el.addEventListener(event, eventListener);
      } else {
        el.attachEvent('on' + event, eventListener);
      }
    };

    /*
     Replace {{variable.name}} with it's property on the scope
     Also supports {{variable.name || another.name || 'string'}}
     */
    var insertReplacements = function (htmlStr, scope) {
      return htmlStr.replace(/\{\{(.*?)\}\}/g, function (_match, sub) {
        var tokens = sub.split('||');
        var value, token;
        while (token = tokens.shift()) {
          token = token.trim();

          // If string
          if (token[0] === '"') return token.slice(1, token.length - 1);

          // If query matches
          value =  Util.queryObject(scope, token);

          if (value) return value;
        }

        return '';
      });
    };

    /*
     Turn a string of html into DOM
     */
    var buildDom = function (htmlStr) {
      var container = document.createElement('div');
      container.innerHTML = htmlStr;
      return container.children[0];
    };

    var applyToElementsWithAttribute = function (dom, attribute, func) {
      var els = dom.parentNode.querySelectorAll('[' + attribute + ']');
      Util.each(els, function (element) {
        var attributeVal = element.getAttribute(attribute);
        func(element, attributeVal);
      }, window, true);
    };

    /*
     Parse event attributes in dom and set listeners to their matching scope methods
     */
    var applyEvents = function (dom, scope) {
      applyToElementsWithAttribute(dom, eventAttribute, function (element, attributeVal) {
        var parts = attributeVal.split(':');
        var listener = Util.queryObject(scope, parts[1]);
        addEventListener(element, parts[0], Util.bind(listener, scope));
      });
    };

    var applyConditionals = function (dom, scope) {
      applyToElementsWithAttribute(dom, conditionAttribute, function (element, attributeVal) {
        var value = Util.queryObject(scope, attributeVal);
        if (!value) {
          element.parentNode.removeChild(element);
        }
      });
    };

    return {
      build: function (htmlStr, scope) {
        if (Util.isArray(htmlStr)) htmlStr = htmlStr.join('');

        htmlStr = insertReplacements(htmlStr, scope);
        var dom = buildDom(htmlStr);
        applyEvents(dom, scope);
        applyConditionals(dom, scope);

        return dom;
      }
    };
  })();

  /*
   Plugin
   */
  var cookieconsent = {
    options: {
      message: 'This website uses cookies to ensure you get the best experience on our website. ',
      dismiss: 'Got it!',
      learnMore: 'More info',
      link: null,
      target: '_self',
      container: null, // selector
      theme: 'light-floating',
      domain: null, // default to current domain.
      path: '/',
      expiryDays: 365,
      markup: [
        '
',
        '
',
        '{{options.dismiss}}',

        '
{{options.message}} {{options.learnMore}}
',

        'Cookie Consent plugin for the EU cookie law',
        '
',
        '
'
      ]
    },

    init: function () {
      var options = window[OPTIONS_VARIABLE];
      if (options) this.setOptions(options);

      this.setContainer();

      // Calls render when theme is loaded.
      if (this.options.theme) {
        this.loadTheme(this.render);
      } else {
        this.render();
      }
    },

    setOptionsOnTheFly: function (options) {
      this.setOptions(options);
      this.render();
    },

    setOptions: function (options) {
      Util.merge(this.options, options);
    },

    setContainer: function () {
      if (this.options.container) {
        this.container = document.querySelector(this.options.container);
      } else {
        this.container = document.body;
      }

      // Add class to container classes so we can specify css for IE8 only.
      this.containerClasses = '';
      if (navigator.appVersion.indexOf('MSIE 8') > -1) {
        this.containerClasses += ' cc_ie8'
      }
    },

    loadTheme: function (callback) {
      var theme = this.options.theme;

      // If theme is specified by name
      if (theme.indexOf('.css') === -1) {
        theme = THEME_BUCKET_PATH + theme + '.css';
      }

      var link = document.createElement('link');
      link.rel = 'stylesheet';
      link.type = 'text/css';
      link.href = theme;

      var loaded = false;
      link.onload = Util.bind(function () {
        if (!loaded && callback) {
          callback.call(this);
          loaded = true;
        }
      }, this);

      document.getElementsByTagName("head")[0].appendChild(link);
    },

    render: function () {
      // remove current element (if we've already rendered)
      if (this.element && this.element.parentNode) {
        this.element.parentNode.removeChild(this.element);
        delete this.element;
      }

      this.element = DomBuilder.build(this.options.markup, this);
      if (!this.container.firstChild) {
        this.container.appendChild(this.element);
      } else {
        this.container.insertBefore(this.element, this.container.firstChild);
      }
    },

    dismiss: function (evt) {
      evt.preventDefault && evt.preventDefault();
      evt.returnValue = false;
      this.setDismissedCookie();
      this.container.removeChild(this.element);
    },

    setDismissedCookie: function () {
      Util.setCookie(DISMISSED_COOKIE, 'yes', this.options.expiryDays, this.options.domain, this.options.path);
    }
  };

  var init;
  var initialized = false;
  (init = function () {
    if (!initialized && document.readyState == 'complete') {
      cookieconsent.init();
      initialized = true;
      window[OPTIONS_UPDATER] = Util.bind(cookieconsent.setOptionsOnTheFly, cookieconsent);
    }
  })();

  Util.addEventListener(document, 'readystatechange', init);

})();
<|endoftext|>


<commit_before>var WebSocketServer = require('websocket').server;
var http = require('http');
var express = require('express');
var app     = express();
var server  = http.createServer(app);

var config = require('../config/gokart-timer');
var routes = require('./gokart-timer');

app.configure(function() {

  app.use(express.logger('dev')); // log every request to the console

  app.use("/css",  express.static(__dirname + '/../views/css'));
  app.use("/js", express.static(__dirname + '/../views/js'));

  //pretty print templated resources
  app.locals.pretty = true;

  app.set('view engine', 'jade');
  app.set('views', __dirname + '/../views');
});

routes(app);

console.log("Web starting...");
exports = module.exports = app;

server.listen(config.port, function() { // startup our app at http://localhost:port
  console.log("Web ok! Listening on " + config.port + "...");
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  return true;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log('Connection from', request.origin, 'rejected!');
      return;
    }

    var connection = request.accept('echo-protocol', request.origin);
    console.log('Connection from', connection.remoteAddress, 'accepted (origin ' + request.origin + ').');

    connection.send(JSON.stringify({message: 'hello'}));

    connection.on('message', function(message) {
      if (message.type === 'utf8') {
        console.log('Received Message from', connection.remoteAddress, ':', message.utf8Data);

        var js = JSON.parse(message.utf8Data);
        connection.sendUTF(JSON.stringify({message: js.txt}));
      }
      else if (message.type === 'binary') {
        console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
        connection.sendBytes(message.binaryData);
      }
    });
    connection.on('close', function(reasonCode, description) {
      console.log('Connection', connection.remoteAddress, 'disconnected.');
    });
});

process.on('SIGINT', function() {
  process.exit(0);
});

process.on('exit', function(code) {
  console.log("Web shut down");
});
<commit_msg>send messages to connected clients<commit_after>var WebSocketServer = require('websocket').server;
var http = require('http');
var express = require('express');
var app     = express();
var server  = http.createServer(app);

var config = require('../config/gokart-timer');
var routes = require('./gokart-timer');

app.configure(function() {

  app.use(express.logger('dev')); // log every request to the console

  app.use("/css",  express.static(__dirname + '/../views/css'));
  app.use("/js", express.static(__dirname + '/../views/js'));

  //pretty print templated resources
  app.locals.pretty = true;

  app.set('view engine', 'jade');
  app.set('views', __dirname + '/../views');
});

routes(app);

console.log("Web starting...");
exports = module.exports = app;

server.listen(config.port, function() { // startup our app at http://localhost:port
  console.log("Web ok! Listening on " + config.port + "...");
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  return true;
}

var clients = [];

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log('Connection from', request.origin, 'rejected!');
      return;
    }

    var connection = request.accept('echo-protocol', request.origin);
    clients.push(connection);
    console.log('Connection from', connection.remoteAddress, 'accepted (origin ' + request.origin + ').');

    connection.send(JSON.stringify({message: 'hello'}));

    connection.on('message', function(message) {
      if (message.type === 'utf8') {
        console.log('Received Message from', connection.remoteAddress, ':', message.utf8Data);

        var js = JSON.parse(message.utf8Data);
        connection.sendUTF(JSON.stringify({message: js.txt}));
      }
      else if (message.type === 'binary') {
        console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
        connection.sendBytes(message.binaryData);
      }
    });
    connection.on('close', function(reasonCode, description) {
      console.log('Connection', connection.remoteAddress, 'disconnected.');
    });
});

process.on('message', function(m) {
  clients.forEach(function(c) {
    c.send(JSON.stringify(m));
  });
});

process.on('SIGINT', function() {
  process.exit(0);
});

process.on('exit', function(code) {
  console.log("Web shut down");
});
<|endoftext|>


<commit_before>(function($angular) {

    // Рукописи не горят!
    var app = $angular.module('menuApp', ['ngContextMenu']);

    /**
     * @controller MessagesController
     * @type {Function}
     */
    app.controller('MessagesController', function MessagesController($scope) {

        /**
         * @property messages
         * @type {Object}
         */
        $scope.messages = [
            { subject: 'Really it is Possible? I want to believe...', from: 'Carla', date: new Date() },
            { subject: 'Facebook.com: New Message', from: 'Simon', date: new Date() },
            { subject: 'I Recommend "JavaScript: The Good Parts"!', from: 'Alison', date: new Date() }
        ];

        $scope.replyTo = function replyTo(name) {
            console.log('Reply to ' + name);
        };

    });

})(window.angular);<commit_msg>Using Angular.js'  factory<commit_after>(function($angular) {

    // Рукописи не горят!
    var app = $angular.module('menuApp', ['ngContextMenu']);

    /**
     * @controller MessagesController
     * @type {Function}
     */
    app.controller('MessagesController', function MessagesController($scope, $log) {

        /**
         * @property messages
         * @type {Object}
         */
        $scope.messages = [
            { subject: 'Really it is Possible? I want to believe...', from: 'Carla', date: new Date() },
            { subject: 'Facebook.com: New Message', from: 'Simon', date: new Date() },
            { subject: 'I Recommend "JavaScript: The Good Parts"!', from: 'Alison', date: new Date() }
        ];

        /**
         * @method replyTo
         * @param name {String}
         * @return {void}
         */
        $scope.replyTo = function replyTo(name) {
            $log.info('Reply to ' + name);
        };

    });

})(window.angular);<|endoftext|>


<commit_before>var gpio = require('rpi-gpio');
var sensorLib = require('node-dht-sensor');
var AM_PIN = 17;
var AM_RESET_PIN = 15;
var readingnumber = 0;
var readingInterval;

console.log("before gpio setup");
//gpio.setup(AM_PIN, gpio.DIR_OUT);
gpio.setup(AM_RESET_PIN, gpio.DIR_OUT, function(err){
  if (err) throw err;
  console.log("Calling amreset");
  amReset();
});
console.log("after gpio setup");

// var sensor = {
//     initialize: function () {
//         return sensorLib.initialize(22, AM_PIN);
//     },
//     read: function () {
//         var readout = sensorLib.read();
//         readingnumber++;
//         console.log("Reading Number: "+ readingnumber+' Temperature: ' + readout.temperature.toFixed(2) + 'C, ' +
//             'humidity: ' + readout.humidity.toFixed(2) + '%');
//         // setTimeout(function () {
//         //     sensor.read();
//         // }, 2000);
//     }
// };
var sensor = {
    sensors: [ {
        name: "Indoor",
        type: 22,
        pin: AM_PIN
    }],
    read: function() {
        for (var a in this.sensors) {
            var b = sensorLib.readSpec(this.sensors[a].type, this.sensors[a].pin);
            readingnumber++;
            console.log("Reading Number: "+ readingnumber+" " +this.sensors[a].name + ": " +
              b.temperature.toFixed(1) + "C, " +
              b.humidity.toFixed(1) + "%");
        }
        // setTimeout(function() {
        //     sensor.read();
        // }, 2000);
    }
};

var amReset = function(){
  console.log("Starting AMRESET")
  gpio.write(AM_RESET_PIN,0,function(err){
    if (err) throw err;
    console.log('RESETTING AM2302');
  });
  setTimeout(function(){
    gpio.write(AM_RESET_PIN,1,function(err){
      if (err) throw err;
      console.log('Power On AM2302');
      setTimeout(startReadings,5000);
    });
  },5000);
}
var startReadings = function(){
  readingInterval = setInterval(function(){
    sensor.read();
    // if(!sensorLib.initialized){
    //     console.log("inialize sensor")
    //   if (sensor.initialize()) {
    //       sensor.read();
    //   } else {
    //       console.warn('Failed to initialize sensor');
    //       clearInterval(readingInterval);
    //       amReset();
    //   }
    // }else{
    //   sensor.read();
    // }
  },5000);
}
<commit_msg>updated sensor initialization in am2302test.js<commit_after>var gpio = require('rpi-gpio');
var sensorLib = require('node-dht-sensor');
var AM_PIN = 17;
var AM_RESET_PIN = 15;
var readingnumber = 0;
var readingInterval;

console.log("before gpio setup");
//gpio.setup(AM_PIN, gpio.DIR_OUT);
gpio.setup(AM_RESET_PIN, gpio.DIR_OUT, function(err){
  if (err) throw err;
  console.log("Calling amreset");
  amReset();
});
console.log("after gpio setup");

// var sensor = {
//     initialize: function () {
//         return sensorLib.initialize(22, AM_PIN);
//     },
//     read: function () {
//         var readout = sensorLib.read();
//         readingnumber++;
//         console.log("Reading Number: "+ readingnumber+' Temperature: ' + readout.temperature.toFixed(2) + 'C, ' +
//             'humidity: ' + readout.humidity.toFixed(2) + '%');
//         // setTimeout(function () {
//         //     sensor.read();
//         // }, 2000);
//     }
// };
var sensor = {
    sensors: [ {
        name: "Indoor",
        type: 22,
        pin: AM_PIN
    }],
    read: function() {
        for (var a in this.sensors) {
            var b = sensorLib.readSpec(this.sensors[a].type, this.sensors[a].pin);
            readingnumber++;
            console.log("Reading Number: "+ readingnumber+" " +this.sensors[a].name + ": " +
              b.temperature.toFixed(1) + "C, " +
              b.humidity.toFixed(1) + "%" + "Errors: " + b.errors;);
        }
        // setTimeout(function() {
        //     sensor.read();
        // }, 2000);
    }
};

var amReset = function(){
  console.log("Starting AMRESET")
  gpio.write(AM_RESET_PIN,0,function(err){
    if (err) throw err;
    console.log('RESETTING AM2302');
  });
  setTimeout(function(){
    gpio.write(AM_RESET_PIN,1,function(err){
      if (err) throw err;
      console.log('Power On AM2302');
      setTimeout(startReadings,5000);
    });
  },5000);
}
var startReadings = function(){
  readingInterval = setInterval(function(){
    sensor.read();
    // if(!sensorLib.initialized){
    //     console.log("inialize sensor")
    //   if (sensor.initialize()) {
    //       sensor.read();
    //   } else {
    //       console.warn('Failed to initialize sensor');
    //       clearInterval(readingInterval);
    //       amReset();
    //   }
    // }else{
    //   sensor.read();
    // }
  },5000);
}
<|endoftext|>


<commit_before>import React from 'react';
import moment from 'moment';

moment.locale('nb');

export default (props) => (

Om utregningen

                    Oversikten er basert på Holder de ords database over avstemninger og forslag på Stortinget fra 2009 til i dag.

                    Datagrunnlaget kommer i hovedsak fra Stortingets datatjeneste, som er lisensiert under NLOD.

Inneværende sesjon ({props.currentSession}) er ufullstendig. Tallene oppdateres daglig, og ble sist oppdatert {moment(props.lastUpdate).fromNow()}.

På Stortinget stemmes det ofte over mange forslag samtidig for å spare tid. For å unngå at sekretariatets inndeling av forslag i avstemninger påvirker resultatet, teller vi hvert forslag for seg. Resultatet blir da likt som om Stortinget hadde stemt over hvert forslag enkeltvis.

Siden over 35% av avstemningene på Stortinget ender med enstemmige vedtak, har vi valgt å utelate disse fra vår utregning. Dette gjør forskjellen på partiene tydeligere.

Kategoriene og inndelingen av saker i kategorier er gjort av Stortinget. Vi bruker de 23 hovedkategoriene fra Stortingets kategori-tre, og saker som er kategorisert i flere kategorier telles en gang i hver hovedkategori.

For å unngå at fravær påvirker prosentbrøken, er nevneren alltid lik antall forslag som begge de aktuelle partiene har stemt over.

);<commit_msg>Add update note about bug fix.<commit_after>import React from 'react';
import moment from 'moment';

moment.locale('nb');

export default (props) => (

Om utregningen

                    Oversikten er basert på Holder de ords database over avstemninger og forslag på Stortinget fra 2009 til i dag.

                    Datagrunnlaget kommer i hovedsak fra Stortingets datatjeneste, som er lisensiert under NLOD.

Inneværende sesjon ({props.currentSession}) er ufullstendig. Tallene oppdateres daglig, og ble sist oppdatert {moment(props.lastUpdate).fromNow()}.

På Stortinget stemmes det ofte over mange forslag samtidig for å spare tid. For å unngå at sekretariatets inndeling av forslag i avstemninger påvirker resultatet, teller vi hvert forslag for seg. Resultatet blir da likt som om Stortinget hadde stemt over hvert forslag enkeltvis.

Siden over 35% av avstemningene på Stortinget ender med enstemmige vedtak, har vi valgt å utelate disse fra vår utregning. Dette gjør forskjellen på partiene tydeligere.

Kategoriene og inndelingen av saker i kategorier er gjort av Stortinget. Vi bruker de 23 hovedkategoriene fra Stortingets kategori-tre, og saker som er kategorisert i flere kategorier telles en gang i hver hovedkategori.

For å unngå at fravær påvirker prosentbrøken, er nevneren alltid lik antall forslag som begge de aktuelle partiene har stemt over.

                    Oppdateringer

                            17. februar 2016: Rettet et problem hvor enstemmige avstemninger feilaktig
                            ble tatt med i matrisen når man hadde valgt alle sesjoner og en bestemt kategori.
                            Dette førte til at partiene fremsto mer enige i enkeltkategorier enn de gjorde totalt.

);<|endoftext|>


<commit_before>var s = document.createElement('script');
s.src = chrome.extension.getURL('myscript.js');
(document.head||document.documentElement).appendChild(s);
s.onload = function() {
    s.parentNode.removeChild(s);
};<commit_msg>Delete loader.js<commit_after><|endoftext|>


<commit_before>const About = () => {
  return (

      Gå til hovedsiden

Velkommen til Online, linjeforeningen for informatikkstudenter ved NTNU.

Det er vi som sørger for at studietiden blir den beste tiden i ditt liv! Vi i Online arrangerer utflukter, turer, fester, holder kurs og bedriftspresentasjoner gjennom hele året.

      Hopp til program

  );
};

export default About;
<commit_msg>add info to start<commit_after>const About = () => {
  return (

      Gå til hovedsiden

Velkommen til Online, linjeforeningen for informatikkstudenter ved NTNU.

Det er vi som sørger for at studietiden blir den beste tiden i ditt liv! Vi i Online arrangerer utflukter, turer, fester, holder kurs og bedriftspresentasjoner gjennom hele året.

Vi har samlet litt info for nye informatikkere med spørsmål, ta en titt på wikien for å sjekke den ut!

      Hopp til program

  );
};

export default About;
<|endoftext|>


<commit_before>/*
 * Licensed to Apereo under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Apereo licenses this file to you 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 the following location:
 *
 *   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.
 */
define(['angular'], function(angular) {
  /* Keep in sync with docs/markdown/configuration.md*/
  return angular.module('override', [])
    .constant('OVERRIDE', {
      'APP_OPTIONS': {
        'appMenuTemplateURL': 'portal/misc/partials/example-menu.html',
        'appMenuItems': [
          {
            'label': 'MyUW home',
            'icon': 'home',
            'url': '/web',
          },
        ],
        'enablePushContentMenu': true,
      },
    });
});
<commit_msg>fix: Default to normal side nav<commit_after>/*
 * Licensed to Apereo under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Apereo licenses this file to you 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 the following location:
 *
 *   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.
 */
define(['angular'], function(angular) {
  /* Keep in sync with docs/markdown/configuration.md*/
  return angular.module('override', [])
    .constant('OVERRIDE', {
      'APP_OPTIONS': {
        'appMenuTemplateURL': 'portal/misc/partials/example-menu.html',
        'appMenuItems': [
          {
            'label': 'MyUW home',
            'icon': 'home',
            'url': '/web',
          },
        ],
      },
    });
});
<|endoftext|>


<commit_before>const Generator = require('yeoman-generator');
const to = require('to-case');

const genModelNames = model => ({
  slugName: to.slug(model),
  pascalName: to.pascal(model),
  camelName: to.camel(model)
});

const serverGenerator = Generator.extend({
  prompting: {
    ask() {
      return this.prompt([
        {
          name: 'models',
          type: 'input',
          message: 'Models: (singular and comma separated)',
          filter: answer => answer.split(','),
          default: 'newModel'
        }
      ]).then((answers) => {
        this.models = answers.models.map(genModelNames);
      });
    }
  },

  writing: {
    model() {
      this.models.forEach((model) => {
        const controllerPath = `model/${model.slugName}/controller.js`;
        const facadePath = `model/${model.slugName}/facade.js`;
        const routerPath = `model/${model.slugName}/router.js`;
        const schemaPath = `model/${model.slugName}/schema.js`;

        if (
          this.fs.exists(this.destinationPath(controllerPath)) ||
          this.fs.exists(this.destinationPath(facadePath)) ||
          this.fs.exists(this.destinationPath(routerPath)) ||
          this.fs.exists(this.destinationPath(schemaPath))
        ) {
          this.log(`Model ${model.slugName} already exists`);
        } else {
          if (this.fs.exists(this.destinationPath('routes.js'))) {
            let routes = this.fs.read(this.destinationPath('routes.js'));
            routes = routes.split('\n');
            const routerPathmini = routerPath.slice(0, -3);
            let lineindex = routes.findIndex(line => line.includes('router.use'));
            routes.splice(3, 0, `const ${model.slugName} = require('./${routerPathmini}');`);
            if (lineindex === -1) {
              lineindex = 11;
            }
            routes.splice(lineindex, 0, `router.use('/${model.slugName}', ${model.slugName});`);
            routes = routes.join('\n');

            this.fs.write(this.destinationPath('routes.js'), routes);
          }

          this.fs.copyTpl(
            this.templatePath('./../../app/templates/model/controller.js'),
            this.destinationPath(`model/${model.slugName}/controller.js`),
            {
              model
            }
          );

          this.fs.copyTpl(
            this.templatePath('./../../app/templates/model/facade.js'),
            this.destinationPath(facadePath),
            {
              model
            }
          );

          this.fs.copyTpl(
            this.templatePath('./../../app/templates/model/router.js'),
            this.destinationPath(routerPath),
            {
              model
            }
          );

          this.fs.copyTpl(
            this.templatePath('./../../app/templates/model/schema.js'),
            this.destinationPath(schemaPath),
            {
              model
            }
          );
        }
      });
    }
  }
});

module.exports = serverGenerator;
<commit_msg>Update index.js<commit_after>const Generator = require('yeoman-generator');
const to        = require('to-case');

const genModelNames = model => ({
  slugName  : to.slug(model),
  pascalName: to.pascal(model),
  camelName : to.camel(model)
});

const serverGenerator = Generator.extend({
  prompting: {
    ask() {
      return this.prompt([{
        name   : 'models',
        type   : 'input',
        message: 'Models: (singular and comma separated)',
        filter : answer => answer.split(','),
        default: 'newModel'
      }]).then((answers) => {
        this.models = answers.models.map(genModelNames);
      });
    }
  },

  writing: {
    model() {
      this.models.forEach((model) => {

        const controllerPath = `model/${model.slugName}/controller.js`;
        const facadePath     = `model/${model.slugName}/facade.js`;
        const routerPath     = `model/${model.slugName}/router.js`;
        const schemaPath     = `model/${model.slugName}/schema.js`;

        if (
          this.fs.exists(this.destinationPath(controllerPath)) ||
          this.fs.exists(this.destinationPath(facadePath))     ||
          this.fs.exists(this.destinationPath(routerPath))     ||
          this.fs.exists(this.destinationPath(schemaPath))
        ) {
          this.log(`Model ${model.slugName} already exists`);
          return;
        }
        if (this.fs.exists(this.destinationPath('routes.js'))) {
           let routes = this.fs.read(this.destinationPath('routes.js'));
           routes = routes.split('\n');
           const routerPathmini = routerPath.slice(0, -3);
           let lineindex = routes.findIndex(line => line.includes('router.use'));
           routes.splice(3, 0, `const ${model.slugName} = require('./${routerPathmini}');`);
           if (lineindex === -1) {
             lineindex = 11;
           }
           routes.splice(lineindex, 0, `router.use('/${model.slugName}', ${model.slugName});`);
           routes = routes.join('\n');

           this.fs.write(this.destinationPath('routes.js'), routes);
         }
        this.fs.copyTpl(
          this.templatePath('./../../app/templates/model/controller.js'),
          this.destinationPath(`model/${model.slugName}/controller.js`), {
            model
          }
        );

        this.fs.copyTpl(
          this.templatePath('./../../app/templates/model/facade.js'),
          this.destinationPath(facadePath), {
            model
          }
        );

        this.fs.copyTpl(
          this.templatePath('./../../app/templates/model/router.js'),
          this.destinationPath(routerPath), {
            model
          }
        );

        this.fs.copyTpl(
          this.templatePath('./../../app/templates/model/schema.js'),
          this.destinationPath(schemaPath), {
            model
          }
        );
      });
    }
  }
});

module.exports = serverGenerator;
<|endoftext|>


<commit_before>(function() {
	'use strict';

	window.App = function() {
		this.init();
	};

	App.prototype.init = function() {
		var _this = this;

		window.$body = $('body');

		_this.build();
		_this.plugins();
		_this.events();
	};

	App.prototype.plugins = function($context) {
		//var _this = this;

		//$context = $context || $('body');

		$('.owl-carousel').owlCarousel({
			loop: true,
			margin: 0,
			items: 1,
			nav: true
		});

		var $genome = $('#genome-listing');
		if ($genome.length) {
			$genome.genome({url: $genome.data('genome-url')});
		}
	};

	App.prototype.events = function() {
		//var _this = this;

	};

	App.prototype.build = function() {

	};

	$(document).on('ready', function() {
		window.app = new App();
	});

})();<commit_msg>genome table<commit_after>(function() {
	'use strict';

	window.App = function() {
		this.init();
	};

	App.prototype.init = function() {
		var _this = this;

		window.$body = $('body');

		_this.build();
		_this.plugins();
		_this.events();
	};

	App.prototype.plugins = function($context) {
		//var _this = this;

		//$context = $context || $('body');

		var $genome = $('#genome-listing');
		if ($genome.length) {
			$genome.genome({url: $genome.data('genome-url')});
		}
	};

	App.prototype.events = function() {
		//var _this = this;

	};

	App.prototype.build = function() {

	};

	$(document).on('ready', function() {
		window.app = new App();
	});

})();<|endoftext|>


<commit_before>// Implementing recursive solution
module.exports = function factorial (number) {
  if(number<=1) return 1;
  return number*(factorial(number - 1));
}

// Implementing iterative solution
module.exports = function (number){
   var result = 1 ;
   for(i=1; i<=number; i++){
     result *= i;
   }
   return result;
}

//Implementing iterative solution 2 (going backwards in loop)

module.exports = function (number){
   var result = 1 ;
   for(i=number; i>1; i++){
     result *= i;
   }
   return result;
}
<commit_msg>Corrected Typos. Made it error free (most probably)<commit_after>// Implementing recursive solution
module.exports = function factorial (number) {
  if(number<=1) return 1;
  return number*(factorial(number - 1));
}

// Implementing iterative solution
module.exports = function (number){
   var result = 1 ;
   for(i=1; i<=number; i++){
     result *= i;
   }
   return result;
}

//Implementing iterative solution 2 (going backwards in loop)

module.exports = function (number){
   var result = 1 ;
   for(i=number; i>1; i--){
     result *= i;
   }
   return result;
}
<|endoftext|>