<commit_before><commit_msg>Delete test.js<commit_after><|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-24 01:58:25<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>/*!
 * fill-range <https://github.com/jonschlinkert/fill-range>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License
 */

'use strict';

var should = require('should');
var range = require('./');

describe('error handling', function () {
  it('should throw when the first arg is not a string.', function () {
    (function() {
      range();
    }).should.throw('fill-range expects the first and second args to be strings.');
  });

  it('should throw when range arguments are invalid.', function () {
    (function() {range('0a', '0z'); }).should.throw('fill-range: invalid range arguments.');
    (function() {range('!', '$'); }).should.throw('fill-range: invalid range arguments.');
  });

  it('should throw when args are incompatible.', function () {
    (function() {
      range('a', 10);
    }).should.throw('fill-range: first range argument is incompatible with second.');

    (function() {
      range(1, 'z');
    }).should.throw('fill-range: first range argument is incompatible with second.');
  });

  it('should throw when the step is bad.', function () {
    (function() {range('1', '10', 'z'); }).should.throw('fill-range: invalid step.');
    (function() {range('a', 'z', 'a'); }).should.throw('fill-range: invalid step.');
    (function() {range('a', 'z', '0a'); }).should.throw('fill-range: invalid step.');
  });
});

describe('ranges: numbers', function () {
  it('should increment numerical ranges', function () {
    range('1', '10').should.eql(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']);
    range('1', '3').should.eql(['1', '2', '3']);
    range('5', '8').should.eql(['5', '6', '7', '8']);
    range(1, '9').should.eql(['1', '2', '3', '4', '5', '6', '7', '8', '9']);
    range(1, 3).should.eql(['1', '2', '3']);
    range(1, 9).should.eql(['1', '2', '3', '4', '5', '6', '7', '8', '9']);
    range(5, 8).should.eql(['5', '6', '7', '8']);
  });

  it('should decrement numerical ranges', function () {
    range('0', '-5').should.eql(['0', '-1', '-2', '-3', '-4', '-5']);
    range(-10, -1).should.eql(['-10', '-9', '-8', '-7', '-6', '-5', '-4', '-3', '-2', '-1']);
    range(0, -5).should.eql(['0', '-1', '-2', '-3', '-4', '-5']);
  });

  it('should handle ranges ranges that are positive and negative:', function () {
    range(9, -4).should.eql(['9', '8', '7', '6', '5', '4', '3', '2', '1', '0', '-1', '-2', '-3', '-4']);
    range(-5, 5).should.eql(['-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5']);
  });
});

describe('ranges: letters', function () {
  it('should increment alphabetical ranges', function () {
    range('a', 'e').should.eql(['a', 'b', 'c', 'd', 'e']);
    range('A', 'E').should.eql(['A', 'B', 'C', 'D', 'E']);
  });

  it('should decrement alphabetical ranges', function () {
    range('E', 'A').should.eql(['E', 'D', 'C', 'B', 'A']);
    range('z', 'm').should.eql(['z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm']);
  });
});

describe('steps: numbers', function () {
  it('should increment ranges using the given step', function () {
    range('1', '10', '1').should.eql(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']);
    range('1', '10', '2').should.eql(['1', '3', '5', '7', '9']);
    range('1', '10', '2').should.eql(['1', '3', '5', '7', '9']);
    range('1', '10', 2).should.eql(['1', '3', '5', '7', '9']);
    range('1', '20', '2').should.eql(['1', '3', '5', '7', '9', '11', '13', '15', '17', '19']);
    range('1', '20', '20').should.eql(['1']);
    range('10', '1', '-2').should.eql(['10', '8', '6', '4', '2']);
    range('10', '1', '2').should.eql(['10', '8', '6', '4', '2']);
    range(2, 10, '2').should.eql(['2', '4', '6', '8', '10']);
    range(2, 10, 1).should.eql(['2', '3', '4', '5', '6', '7', '8', '9', '10']);
    range(2, 10, 2).should.eql(['2', '4', '6', '8', '10']);
    range(2, 10, 3).should.eql(['2', '5', '8']);
    range(2, '10', '2').should.eql(['2', '4', '6', '8', '10']);
    range(2, '10', 1).should.eql(['2', '3', '4', '5', '6', '7', '8', '9', '10']);
    range(2, '10', '2').should.eql(['2', '4', '6', '8', '10']);
    range('2', 10, '3').should.eql(['2', '5', '8']);
  });

  it('should fill in negative ranges using the given step', function () {
    range('-1', '-10', '-2').should.eql(['-1', '-3', '-5', '-7', '-9']);
    range('-1', '-10', '2').should.eql(['-1', '-3', '-5', '-7', '-9']);
    range('10', '1', '-2').should.eql(['10', '8', '6', '4', '2']);
    range(-10, -2, 2).should.eql(['-10', '-8', '-6', '-4', '-2']);
    range(-2, -10, 1).should.eql(['-2', '-3', '-4', '-5', '-6', '-7', '-8', '-9', '-10']);
    range(-2, -10, 2).should.eql(['-2', '-4', '-6', '-8', '-10']);
    range(-2, -10, 3).should.eql(['-2', '-5', '-8']);
    range(-9, 9, 3).should.eql(['-9', '-6', '-3', '0', '3', '6', '9']);
  });

  it('should fill in negative ranges using the given step', function () {
    range('1', '10', '2').should.eql(['1', '3', '5', '7', '9']);
    range('-1', '-10', '2').should.eql(['-1', '-3', '-5', '-7', '-9']);
    range('-1', '-10', '-2').should.eql(['-1', '-3', '-5', '-7', '-9']);
    range('1', '20', '2').should.eql(['1', '3', '5', '7', '9', '11', '13', '15', '17', '19']);
    range('1', '20', '20').should.eql(['1']);
  });
});

describe('steps: letters', function () {
  it('should use increments with alphabetical ranges', function () {
    range('a', 'e', 2).should.eql(['a','c', 'e']);
    range('E', 'A', 2).should.eql(['E', 'C', 'A']);
  });
});

describe('padding: numbers', function () {
  it('should pad numbers:', function () {
    range('01', '03').should.eql(['01', '02', '03']);
    range('0001', '0003').should.eql(['0001', '0002', '0003']);
    range('-10', '00').should.eql(['-10', '-09', '-08', '-07', '-06', '-05', '-04', '-03', '-02', '-01', '000']);
    range('05', '100').should.eql(['005','006','007','008','009','010','011','012','013','014','015','016','017','018','019','020','021','022','023','024','025','026','027','028','029','030','031','032','033','034','035','036','037','038','039','040','041','042','043','044','045','046','047','048','049','050','051','052','053','054','055','056','057','058','059','060','061','062','063','064','065','066','067','068','069','070','071','072','073','074','075','076','077','078','079','080','081','082','083','084','085','086','087','088','089','090','091','092','093','094','095','096','097','098','099','100']);
    range('1', '05').should.eql(['01','02','03','04','05']);
  });

  it('should pad numbers when a step is passed:', function () {
    range('1', '05', '3').should.eql(['01','04']);
    range('02', '10', 2).should.eql(['02', '04', '06', '08', '10']);
    range('002', '10', 2).should.eql(['002', '004', '006', '008', '010']);
    range('002', '010', 2).should.eql(['002', '004', '006', '008', '010']);
    range('-04', 4, 2).should.eql(['-04', '-02', '000', '002', '004']);
  });
});

describe('special cases', function () {
  it('should convert `-0` to `0`:', function () {
    range('-5', '-0', '-1').should.eql(['-5', '-4', '-3', '-2', '-1', '0']);
  });

  it('should adjust padding for negative numbers:', function () {
    range('-01', '5').should.eql(['-01','000','001','002','003','004','005']);
  });
});

describe('special characters:', function () {
  it('should repeat the first arg `n` times:', function () {
    range('a', 3, '+').should.eql(['a', 'a', 'a']);
    range('abc', 2, '+').should.eql(['abc', 'abc']);
  });

  it('should collapse values when `>` is passed:', function () {
    range('a', 'e', '>').should.eql(['abcde']);
    range('A', 'E', '>').should.eql(['ABCDE']);
    range('E', 'A', '>').should.eql(['EDCBA']);
    range('5', '8', '>').should.eql(['5678']);
    range('2', '20', '2>').should.eql(['2468101214161820']);
    range('2', '20', '>2').should.eql(['2468101214161820']);
  });

  it('should randomize using the first two args when `?` is passed:', function () {
    range('A0', 5, '?').should.match(/[\w\d]{5}/);
    range('A0', 5, '?').should.not.match(/[\w\d]{6}/);
    range('A', 5, '?').should.not.match(/\d{5}/);
    range('*', 5, '?').should.match(/.{5}/);
    range('aA0', 10, '?').should.match(/[^\W]{10}/);
  });

  it('should join the array using `|` as the separator:', function () {
    range('a', 'c', '|').should.eql(['(?:a|b|c)']);
    range('a', 'e', '2|').should.eql(['(?:a|c|e)']);
    range('a', 'e', '|2').should.eql(['(?:a|c|e)']);
    range('a', 'z', '|5').should.eql(['(?:a|f|k|p|u|z)']);
  });
});

describe('custom function for expansions:', function () {
  it('should expose the current value as the first param.', function () {
    range(1, 5, function (val, isNumber, padding, i) {
      return val;
    }).should.eql([1, 2, 3, 4, 5]);
  });

  it('should expose the `isNumber` boolean as the second param.', function () {
    range('a', 'e', function (val, isNumber, padding, i) {
      if (!isNumber) {
        return String.fromCharCode(val);
      }
      return val;
    }).should.eql(['a', 'b', 'c', 'd', 'e']);
  });

  it('should expose padding as the third param.', function () {
    range('01', '05', function (val, isNumber, padding, i) {
      return padding + padding + val;
    }).should.eql(['001', '002', '003', '004', '005']);
  });

  it('should expose the index as the fourth param.', function () {
    range('a', 'e', function (val, isNumber, padding, i) {
      if (!isNumber) {
        return String.fromCharCode(val) + i;
      }
      return val;
    }).should.eql(['a0', 'b1', 'c2', 'd3', 'e4']);
  });
});
<commit_msg>add tests<commit_after>/*!
 * fill-range <https://github.com/jonschlinkert/fill-range>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License
 */

'use strict';

var should = require('should');
var range = require('./');

describe('error handling', function () {
  it('should throw when the first arg is not a string.', function () {
    (function() {
      range();
    }).should.throw('fill-range expects the first and second args to be strings.');
  });

  it('should throw when range arguments are invalid.', function () {
    (function() {range('0a', '0z'); }).should.throw('fill-range: invalid range arguments.');
    (function() {range('!', '$'); }).should.throw('fill-range: invalid range arguments.');
  });

  it('should throw when args are incompatible.', function () {
    (function() {
      range('a', 10);
    }).should.throw('fill-range: first range argument is incompatible with second.');

    (function() {
      range(1, 'z');
    }).should.throw('fill-range: first range argument is incompatible with second.');
  });

  it('should throw when the step is bad.', function () {
    (function() {range('1', '10', 'z'); }).should.throw('fill-range: invalid step.');
    (function() {range('a', 'z', 'a'); }).should.throw('fill-range: invalid step.');
    (function() {range('a', 'z', '0a'); }).should.throw('fill-range: invalid step.');
  });
});

describe('ranges: numbers', function () {
  it('should increment numerical ranges', function () {
    range('1', '10').should.eql(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']);
    range('1', '3').should.eql(['1', '2', '3']);
    range('5', '8').should.eql(['5', '6', '7', '8']);
    range(1, '9').should.eql(['1', '2', '3', '4', '5', '6', '7', '8', '9']);
    range(1, 3).should.eql(['1', '2', '3']);
    range(1, 9).should.eql(['1', '2', '3', '4', '5', '6', '7', '8', '9']);
    range(5, 8).should.eql(['5', '6', '7', '8']);
  });

  it('should decrement numerical ranges', function () {
    range('0', '-5').should.eql(['0', '-1', '-2', '-3', '-4', '-5']);
    range(-10, -1).should.eql(['-10', '-9', '-8', '-7', '-6', '-5', '-4', '-3', '-2', '-1']);
    range(0, -5).should.eql(['0', '-1', '-2', '-3', '-4', '-5']);
  });

  it('should handle ranges ranges that are positive and negative:', function () {
    range(9, -4).should.eql(['9', '8', '7', '6', '5', '4', '3', '2', '1', '0', '-1', '-2', '-3', '-4']);
    range(-5, 5).should.eql(['-5', '-4', '-3', '-2', '-1', '0', '1', '2', '3', '4', '5']);
  });
});

describe('ranges: letters', function () {
  it('should increment alphabetical ranges', function () {
    range('a', 'e').should.eql(['a', 'b', 'c', 'd', 'e']);
    range('A', 'E').should.eql(['A', 'B', 'C', 'D', 'E']);
  });

  it('should decrement alphabetical ranges', function () {
    range('E', 'A').should.eql(['E', 'D', 'C', 'B', 'A']);
    range('z', 'm').should.eql(['z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm']);
  });
});

describe('steps: numbers', function () {
  it('should increment ranges using the given step', function () {
    range('1', '10', '1').should.eql(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']);
    range('1', '10', '2').should.eql(['1', '3', '5', '7', '9']);
    range('1', '10', '2').should.eql(['1', '3', '5', '7', '9']);
    range('1', '10', 2).should.eql(['1', '3', '5', '7', '9']);
    range('1', '20', '2').should.eql(['1', '3', '5', '7', '9', '11', '13', '15', '17', '19']);
    range('1', '20', '20').should.eql(['1']);
    range('10', '1', '-2').should.eql(['10', '8', '6', '4', '2']);
    range('10', '1', '2').should.eql(['10', '8', '6', '4', '2']);
    range(2, 10, '2').should.eql(['2', '4', '6', '8', '10']);
    range(2, 10, 1).should.eql(['2', '3', '4', '5', '6', '7', '8', '9', '10']);
    range(2, 10, 2).should.eql(['2', '4', '6', '8', '10']);
    range(2, 10, 3).should.eql(['2', '5', '8']);
    range(2, '10', '2').should.eql(['2', '4', '6', '8', '10']);
    range(2, '10', 1).should.eql(['2', '3', '4', '5', '6', '7', '8', '9', '10']);
    range(2, '10', '2').should.eql(['2', '4', '6', '8', '10']);
    range('2', 10, '3').should.eql(['2', '5', '8']);
  });

  it('should fill in negative ranges using the given step', function () {
    range('-1', '-10', '-2').should.eql(['-1', '-3', '-5', '-7', '-9']);
    range('-1', '-10', '2').should.eql(['-1', '-3', '-5', '-7', '-9']);
    range('10', '1', '-2').should.eql(['10', '8', '6', '4', '2']);
    range(-10, -2, 2).should.eql(['-10', '-8', '-6', '-4', '-2']);
    range(-2, -10, 1).should.eql(['-2', '-3', '-4', '-5', '-6', '-7', '-8', '-9', '-10']);
    range(-2, -10, 2).should.eql(['-2', '-4', '-6', '-8', '-10']);
    range(-2, -10, 3).should.eql(['-2', '-5', '-8']);
    range(-9, 9, 3).should.eql(['-9', '-6', '-3', '0', '3', '6', '9']);
  });

  it('should fill in negative ranges using the given step', function () {
    range('1', '10', '2').should.eql(['1', '3', '5', '7', '9']);
    range('-1', '-10', '2').should.eql(['-1', '-3', '-5', '-7', '-9']);
    range('-1', '-10', '-2').should.eql(['-1', '-3', '-5', '-7', '-9']);
    range('1', '20', '2').should.eql(['1', '3', '5', '7', '9', '11', '13', '15', '17', '19']);
    range('1', '20', '20').should.eql(['1']);
  });
});

describe('steps: letters', function () {
  it('should use increments with alphabetical ranges', function () {
    range('a', 'e', 2).should.eql(['a','c', 'e']);
    range('E', 'A', 2).should.eql(['E', 'C', 'A']);
  });
});

describe('padding: numbers', function () {
  it('should pad numbers:', function () {
    range('01', '03').should.eql(['01', '02', '03']);
    range('0001', '0003').should.eql(['0001', '0002', '0003']);
    range('-10', '00').should.eql(['-10', '-09', '-08', '-07', '-06', '-05', '-04', '-03', '-02', '-01', '000']);
    range('05', '100').should.eql(['005','006','007','008','009','010','011','012','013','014','015','016','017','018','019','020','021','022','023','024','025','026','027','028','029','030','031','032','033','034','035','036','037','038','039','040','041','042','043','044','045','046','047','048','049','050','051','052','053','054','055','056','057','058','059','060','061','062','063','064','065','066','067','068','069','070','071','072','073','074','075','076','077','078','079','080','081','082','083','084','085','086','087','088','089','090','091','092','093','094','095','096','097','098','099','100']);
    range('1', '05').should.eql(['01','02','03','04','05']);
  });

  it('should pad numbers when a step is passed:', function () {
    range('1', '05', '3').should.eql(['01','04']);
    range('02', '10', 2).should.eql(['02', '04', '06', '08', '10']);
    range('002', '10', 2).should.eql(['002', '004', '006', '008', '010']);
    range('002', '010', 2).should.eql(['002', '004', '006', '008', '010']);
    range('-04', 4, 2).should.eql(['-04', '-02', '000', '002', '004']);
  });
});

describe('special cases', function () {
  it('should convert `-0` to `0`:', function () {
    range('-5', '-0', '-1').should.eql(['-5', '-4', '-3', '-2', '-1', '0']);
  });

  it('should adjust padding for negative numbers:', function () {
    range('-01', '5').should.eql(['-01','000','001','002','003','004','005']);
  });
});

describe('special characters:', function () {
  it('should repeat the first arg `n` times:', function () {
    range('a', 3, '+').should.eql(['a', 'a', 'a']);
    range('abc', 2, '+').should.eql(['abc', 'abc']);
  });

  it('should collapse values when `>` is passed:', function () {
    range('a', 'e', '>').should.eql(['abcde']);
    range('A', 'E', '>').should.eql(['ABCDE']);
    range('E', 'A', '>').should.eql(['EDCBA']);
    range('5', '8', '>').should.eql(['5678']);
    range('2', '20', '2>').should.eql(['2468101214161820']);
    range('2', '20', '>2').should.eql(['2468101214161820']);
  });

  it('should randomize using the first two args when `?` is passed:', function () {
    range('A0', 5, '?').should.match(/[\w\d]{5}/);
    range('A0', 5, '?').should.not.match(/[\w\d]{6}/);
    range('A', 5, '?').should.not.match(/\d{5}/);
    range('*', 5, '?').should.match(/.{5}/);
    range('aA0', 10, '?').should.match(/[^\W]{10}/);
  });

  it('should create a string to be used as a regex logical `or`:', function () {
    range('c', 'a', '|').should.eql(['(c|b|a)']);
    range('z', 'a', '|5').should.eql(['(z|u|p|k|f|a)']);
    range('a', 'e', '2|').should.eql(['(a|c|e)']);
    range('a', 'e', '|2').should.eql(['(a|c|e)']);
    range('a', 'z', '|5').should.eql(['(a|f|k|p|u|z)']);
  });

  it('should create a string to be used as a regex range:', function () {
    range('a', 'c', '|').should.eql(['[a-c]']);
    range('a', 'z', '1|').should.eql(['[a-z]']);
    range('a', 'c', '~').should.eql(['[a-c]']);
    range('0', '9', '~').should.eql(['[0-9]']);
    range('5', '1', '|').should.eql(['(5|4|3|2|1)']);
    range('3', '1', '|1').should.eql(['(3|2|1)']);
    range('1', '3', '|1').should.eql(['[1-3]']);
    range('5', '1', '~').should.eql(['(5|4|3|2|1)']);
  });

  it('should not create a regex range when the characters are out of order:', function () {
    range('a', 'e', '~2').should.eql(['(a|c|e)']);
    range('a', 'z', '5~').should.eql(['(a|f|k|p|u|z)']);
  });
});

describe('custom function for expansions:', function () {
  it('should expose the current value as the first param.', function () {
    range(1, 5, function (val, isNumber, padding, i) {
      return val;
    }).should.eql([1, 2, 3, 4, 5]);
  });

  it('should expose the `isNumber` boolean as the second param.', function () {
    range('a', 'e', function (val, isNumber, padding, i) {
      if (!isNumber) {
        return String.fromCharCode(val);
      }
      return val;
    }).should.eql(['a', 'b', 'c', 'd', 'e']);
  });

  it('should expose padding as the third param.', function () {
    range('01', '05', function (val, isNumber, padding, i) {
      return padding + padding + val;
    }).should.eql(['001', '002', '003', '004', '005']);
  });

  it('should expose the index as the fourth param.', function () {
    range('a', 'e', function (val, isNumber, padding, i) {
      if (!isNumber) {
        return String.fromCharCode(val) + i;
      }
      return val;
    }).should.eql(['a0', 'b1', 'c2', 'd3', 'e4']);
  });
});
<|endoftext|>


<commit_before>var input;
var output;

function setup() {
  canvas = createCanvas(1075,500);
  canvas.position(20,180);
  nameP = createP('Search births by his/her name');
  nameP.position(480,122);
  nameP.mousePressed(gotData);

  input = select('#search');
  var button = select('#submit');
  button.mousePressed(search);
}

function search() {
  var term = input.value();
  var url = 'https://www.wikidata.org/w/api.php?action=wbgetentities&sites=enwiki&languages=en&format=json' + '&titles=' + term;
  loadJSON(url, gotData, 'jsonp');
}

function gotData(data) {
  var entity = data.entities[Object.keys(data.entities)];
  if (Object.keys(data.entities)=="-1"){
    nameP.html("This is not a name..");
  }else{
    var birthdate = entity.claims.P569[0].mainsnak.datavalue.value.time;
    var deathdate = entity.claims.P570[0].mainsnak.datavalue.value.time;
    var name = entity.labels.en.value
    var birthdateA = birthdate.slice(1,11).split('-');
    var deathdateA = deathdate.slice(1,11).split('-');
    var wordLocationXAa = (birthdateA[0] - 1800) * 5;
    var wordLocationYA = height - (deathdateA[0] - birthdateA[0]) * 5;
    var colorA = (deathdateA[0] - birthdateA[0]) * 2.5;
    var wordContentA = input.value() + " :  " + birthdate.slice(1,11) + " to " + deathdate.slice(1,11)

    nameP.html(birthdate.slice(1,11) + " to " + deathdate.slice(1,11));
    if (request) {
      request.abort();
    }
    var request;
    var formData = {"Start Date":birthdate.slice(1,11),"End Date":deathdate.slice(1,11),"Headline":name, "Text":name,"Media":"","Media Credit":"","Media Caption":"","Media Thumbnail":"","Type":"title","Tag":""};
    request = $.ajax({
      url: "https://script.google.com/macros/s/AKfycby2WvqsyQa4zO5nQeKzL7QO36S9Ed8BWcFrNBCIL9rfeK7yQ1D_/exec",
      type: "post",
      useDefaultXhrHeader: false,
      data: formData
    });
  }
}
<commit_msg>update test.html<commit_after>var input;
var output;

function setup() {
  canvas = createCanvas(1075,500);
  canvas.position(20,180);
  nameP = createP('Search births by his/her name');
  nameP.position(480,122);
  nameP.mousePressed(gotData);

  input = select('#search');
  var button = select('#submit');
  button.mousePressed(search);
}

function search() {
  var term = input.value();
  var url = 'https://www.wikidata.org/w/api.php?action=wbgetentities&sites=enwiki&languages=en&format=json' + '&titles=' + term;
  loadJSON(url, gotData, 'jsonp');
}

function gotData(data) {
  var entity = data.entities[Object.keys(data.entities)];
  if (Object.keys(data.entities)=="-1"){
    nameP.html("This is not a name..");
  }else{
    var birthdate = entity.claims.P569[0].mainsnak.datavalue.value.time;
    var deathdate = entity.claims.P570[0].mainsnak.datavalue.value.time;
    var name = entity.labels.en.value
    var birthdateA = birthdate.slice(1,11).split('-');
    var deathdateA = deathdate.slice(1,11).split('-');
    var wordLocationXAa = (birthdateA[0] - 1800) * 5;
    var wordLocationYA = height - (deathdateA[0] - birthdateA[0]) * 5;
    var colorA = (deathdateA[0] - birthdateA[0]) * 2.5;
    var wordContentA = input.value() + " :  " + birthdate.slice(1,11) + " to " + deathdate.slice(1,11)
    if deathdate="" {
      nameP.html(birthdate.slice(1,11) + "until now");
    }
    else {
      nameP.html(birthdate.slice(1,11) + " to " + deathdate.slice(1,11));
      if (request) {
        request.abort();
      }
      var request;
      var formData = {"Start Date":birthdate.slice(1,11),"End Date":deathdate.slice(1,11),"Headline":name, "Text":name,"Media":"","Media Credit":"","Media Caption":"","Media Thumbnail":"","Type":"title","Tag":""};
      request = $.ajax({
        url: "https://script.google.com/macros/s/AKfycby2WvqsyQa4zO5nQeKzL7QO36S9Ed8BWcFrNBCIL9rfeK7yQ1D_/exec",
        type: "post",
        useDefaultXhrHeader: false,
        data: formData
      });
    }
  }
}
<|endoftext|>


<commit_before>/*
Name:           planetos - test.js
Source & docs:  https://github.com/fvdm/nodejs-planetos
Feedback:       https://github.com/fvdm/nodejs-planetos/issues
License:        Unlicense (public domain)
*/

var path = require ('path');
var dir = path.dirname (module.filename);

var pkg = require (path.join (dir, 'package.json'));
var app = require (path.join (dir));

var planetos;
var errors = 0;
var warnings = 0;
var queue = [];
var next = -1;

// Setup
// set env PLANETOS_APIKEY  (CI tests)
var config = {
  apikey: process.env.PLANETOS_APIKEY || null,
  endpoint: process.env.PLANETOS_ENDPOINT || null,
  timeout: process.env.PLANETOS_TIMEOUT || 5000
};

if (!config.apikey) {
  config.endpoint = 'https://frankl.in/u/ci_test.php?a=planetos&b=';
}

planetos = app (config);

/**
 * ANSI colorize a string
 *
 * @param color {String} - The color to add
 * @param str {String} - The string to alter
 * @returns {String}
 */

function colorStr (color, str) {
  var colors = {
    red: '\u001b[31m',
    green: '\u001b[32m',
    yellow: '\u001b[33m',
    blue: '\u001b[34m',
    magenta: '\u001b[35m',
    cyan: '\u001b[36m',
    gray: '\u001b[37m',
    bold: '\u001b[1m',
    plain: '\u001b[0m'
  };

  return colors [color] + str + colors.plain;
}

/**
 * console.log with style
 *
 * @param [type] {String=plain} - Formatting style
 * @param str {String} - The string to alter
 * @returns {void}
 */

function log (type, str) {
  var types = {
    fail: ['red', 'FAIL'],
    good: ['green', 'good'],
    warn: ['yellow', 'warn'],
    info: ['cyan', 'info']
  };

  if (!str) {
    str = type;
    type = 'plain';
  }

  switch (type) {
    case 'error': console.log (colorStr ('red', colorStr ('bold', 'ERROR   ')) + str + '\n'); break;
    case 'note': console.log (colorStr ('bold', str)); break;
    case 'plain': console.log (str); break;
    default:
      console.log (colorStr (types[type][0], types[type][1]) + '    ' + str);
      break;
  }
}

/**
 * Detect and wrap string type
 *
 * @param str {String} - The string
 * @returns {String}
 */

function typeStr (str) {
  if (typeof str === 'string') {
    str = '"' + str + '"';
  } else if (str instanceof Object) {
    str = 'Object';
  } else if (str instanceof Array) {
    str = 'Array';
  } else if (str instanceof Error) {
    str = 'Error';
  }

  return colorStr ('magenta', str);
}

// handle exits
process.on ('exit', function processExit () {
  console.log ();
  log ('info', errors + ' errors');
  log ('info', warnings + ' warnings');
  console.log ();

  if (errors) {
    process.exit (1);
  } else {
    process.exit (0);
  }
});

// prevent errors from killing the process
process.on ('uncaughtException', function uncaughtException (err) {
  console.log (err);
  console.log ();
  console.log (err.stack);
  console.log ();
  errors++;
});

/**
 * Queue to prevent flooding
 *
 * @returns {void}
 */

function doNext () {
  next++;
  if (queue [next]) {
    console.log ();
    queue [next] ();
  }
}

/**
 * doTest checks for error
 * else runs specified tests
 *
 * @param {Error} err
 * @param {String} label
 * @param {Array} tests
 * @returns {void}
 *
 * doTest(err, 'label text', [
 *   ['fail', 'feeds', typeof feeds, 'object'],
 *   ['warn', 'music', music instanceof Array, true],
 *   ['info', 'tracks', music.length]
 * ]);
 */

function doTest (err, label, tests) {
  var level = 'good';
  var test;
  var i;

  if (err instanceof Error) {
    log ('error', label);
    console.dir (err, { depth: null, colors: true });
    console.log ();
    console.log (err.stack);
    console.log ();
    errors++;

    doNext ();
    return;
  }

  console.log (colorStr ('blue', '(' + (next + 1) + '/' + queue.length + ') ') + colorStr ('bold', label));

  for (i = 0; i < tests.length; i++) {
    test = {
      level: tests [i] [0],
      label: tests [i] [1],
      result: tests [i] [2],
      expect: tests [i] [3]
    };

    if (test.result === test.expect) {
      log ('good', colorStr ('blue', test.label) + ': ' + typeStr (test.result) + ' is exactly ' + typeStr (test.expect));
    }

    if (test.level === 'fail' && test.result !== test.expect) {
      errors++;
      level = 'fail';
      log ('fail', colorStr ('blue', test.label) + ': ' + typeStr (test.result) + ' is not ' + typeStr (test.expect));
    }

    if (test.level === 'warn' && test.result !== test.expect) {
      warnings++;
      level = level !== 'fail' && 'warn';
      log ('warn', colorStr ('blue', test.label) + ': ' + typeStr (test.result) + ' is not ' + typeStr (test.expect));
    }

    if (test.level === 'info') {
      log ('info', colorStr ('blue', test.label) + ': ' + typeStr (test.result));
    }
  }

  doNext ();
}

// module basics
queue.push (function () {
  doTest (null, 'Module', [
    ['fail', 'exports', typeof app, 'function'],
    ['fail', 'interface', typeof planetos, 'function']
  ]);
});

// error
queue.push (function () {
  planetos ('noaa_ww3_global_1.25x1d', {}, function (err, data) {
    doTest (null, 'API error', [
      ['fail', 'type', err instanceof Error, true],
      ['fail', 'data', !data, true],
      ['fail', '.message', err && err.message, 'API error'],
      ['warn', '.statusCode', err && err.statusCode !== 200, true],
      ['warn', '.body', err && typeof err.body, 'string']
    ]);
  });
});

// method
queue.push (function () {
  var params = {
    lon: -50.5,
    lat: 49.5,
    count: 1,
    context: 'reftime_time_lat_lon'
  };

  planetos ('noaa_ww3_global_1.25x1d', params, function (err, data) {
    doTest (err, 'NOAA example', [
      ['fail', 'type', data instanceof Object, true],
      ['warn', '.stats', data && data.stats instanceof Object, true],
      ['warn', '.entries', data && data.entries instanceof Array, true]
    ]);

    if (data) {
      console.log ();
      log ('note', 'JSON data:');
      console.dir (data, {
        depth: null,
        colors: true
      });
    }
  });
});

// Start the tests
log ('note', 'Running tests...\n');
log ('note', 'API endpoint:  ' + (config.endpoint || 'default'));
log ('note', 'Node.js:       ' + process.versions.node);
log ('note', 'Module:        ' + pkg.version);

doNext ();
<commit_msg>Test: switched to dotest dep<commit_after>/*
Name:           planetos - test.js
Source & docs:  https://github.com/fvdm/nodejs-planetos
Feedback:       https://github.com/fvdm/nodejs-planetos/issues
License:        Unlicense (public domain)
*/

var doTest = require ('dotest');
var app = require ('./');

var planetos;

// Setup
// set env PLANETOS_APIKEY  (CI tests)
var config = {
  apikey: process.env.PLANETOS_APIKEY || null,
  endpoint: process.env.PLANETOS_ENDPOINT || null,
  timeout: process.env.PLANETOS_TIMEOUT || 5000
};

planetos = app (config);

// module basics
doTest.add ('Module', function () {
  doTest.test ()
    .isFunction ('fail', 'app', app)
    .isFunction ('fail', 'planetos', planetos)
    .done ();
});

// error
doTest.add ('API error', function () {
  planetos ('noaa_ww3_global_1.25x1d', {}, function (err, data) {
    doTest.test ()
      .isError ('fail', 'err', err)
      .isUndefined ('fail', 'data', data)
      .isExactly ('fail', 'err.message', err && err.message, 'API error')
      .isExactly ('warn', 'err.statusCode', err && err.statusCode, 400)
      .isNotEmpty ('warn', 'err.body', err && err.body)
      .done ();
  });
});

// method
doTest.add ('NOAA example', function () {
  var params = {
    lon: -50.5,
    lat: 49.5,
    count: 1,
    context: 'reftime_time_lat_lon'
  };

  planetos ('noaa_ww3_global_1.25x1d', params, function (err, data) {
    doTest.test (err)
      .isObject ('fail', 'data', data)
      .isObject ('fail', 'data.stats', data && data.stats)
      .isArray ('fail', 'data.entries', data && data.entries)
      .done ();

    if (data) {
      console.log ();
      doTest.log ('note', 'JSON data:');
      console.dir (data, {
        depth: null,
        colors: true
      });
    }
  });
});

// Start the tests
doTest.run ();
<|endoftext|>


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

conn = new btle.Connection();

// Register an error callback
conn.on('error', function(err) {
  console.error("Connection error: %s", err);
  conn.close();
});

// Register a close callback
conn.on('close', function() {
  console.log("Got close");
});

// Our connection options
connect_opts = {
  destination: 'BC:6A:29:C3:52:A9',
  type: btle.BtIOType.BT_IO_L2CAP,
  sourceType: btle.BtAddrType.BDADDR_LE_PUBLIC,
  destType: btle.BtAddrType.BDADDR_LE_PUBLIC,
  securityLevel: btle.BtSecurityLevel.BT_SECURITY_LOW,
  cid: 4
}

// Connect
conn.connect(connect_opts, function(err) {
  console.log("Got connection, err = " + err);
  // Listen for notifications
  conn.addNotificationListener(0x25, function(buffer) {
    console.log("Temperature, " + buffer.readUInt16LE(0) + ", " + buffer.readUInt16LE(2));
  });

  conn.addNotificationListener(0x2D, function(buffer) {
    console.log("Accelerometer, " + buffer.readUInt8(0) + ", " + buffer.readUInt8(1) + ", " + buffer.readUInt8(2));
  });

  // Read from handle 0x25
  conn.readHandle(0x25, function(buffer) {
    console.log(buffer);

    // Write a 1 to handle 0x29 to turn on the thermometer
    buffer = new Buffer([1]);
    console.log(buffer);
    conn.writeCommand(0x29, buffer);

    // Wait for a second then read handle 0x25 again
    setTimeout(function() {
      conn.readHandle(0x25, function(buffer) {
	console.log(buffer);

	// Write 0100 to handle 0x26
	buffer = new Buffer([1, 0]);
	conn.writeCommand(0x26, buffer);

	conn.writeCommand(0x31, new Buffer([1])); // Turn on accelerometer
	conn.writeCommand(0x2E, buffer);
      });
    }, 1000);
  });
});
<commit_msg>Added ctrl-c handler<commit_after>var btle = require('./index');

conn = new btle.Connection();

// Register an error callback
conn.on('error', function(err) {
  console.error("Connection error: %s", err);
  conn.close();
});

// Register a close callback
conn.on('close', function() {
  console.log("Got close");
});

// Our connection options
connect_opts = {
  destination: 'BC:6A:29:C3:52:A9',
  type: btle.BtIOType.BT_IO_L2CAP,
  sourceType: btle.BtAddrType.BDADDR_LE_PUBLIC,
  destType: btle.BtAddrType.BDADDR_LE_PUBLIC,
  securityLevel: btle.BtSecurityLevel.BT_SECURITY_LOW,
  cid: 4
}

// Connect
conn.connect(connect_opts, function(err) {
  process.on('SIGINT', function() {
    conn.close();
  });

  // Listen for notifications
  conn.addNotificationListener(0x25, function(buffer) {
    console.log("Temperature, " + buffer.readUInt16LE(0) + ", " + buffer.readUInt16LE(2));
  });

  conn.addNotificationListener(0x2D, function(buffer) {
    console.log("Accelerometer, " + buffer.readUInt8(0) + ", " + buffer.readUInt8(1) + ", " + buffer.readUInt8(2));
  });

  // Read from handle 0x25
  conn.readHandle(0x25, function(buffer) {
    console.log(buffer);

    // Write a 1 to handle 0x29 to turn on the thermometer
    buffer = new Buffer([1]);
    console.log(buffer);
    conn.writeCommand(0x29, buffer);

    // Wait for a second then read handle 0x25 again
    setTimeout(function() {
      conn.readHandle(0x25, function(buffer) {
	console.log(buffer);

	// Write 0100 to handle 0x26
	buffer = new Buffer([1, 0]);
	conn.writeCommand(0x26, buffer);

	conn.writeCommand(0x31, new Buffer([1])); // Turn on accelerometer
	conn.writeCommand(0x2E, buffer);
      });
    }, 1000);
  });
});
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-6 00:50:07<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>'use strict';

var BinBuild = require('./');
var fs = require('fs');
var path = require('path');
var test = require('ava');

test('expose a constructor', function (t) {
	t.plan(1);
	t.assert(typeof BinBuild === 'function');
});

test('set source file', function (t) {
	t.plan(1);

	var build = new BinBuild()
		.src('src.tar.gz');

	t.assert(build._src === 'src.tar.gz');
});

test('add commands to run', function (t) {
	t.plan(2);

	var build = new BinBuild()
		.cmd('make')
		.cmd('make install');

	t.assert(build._cmd[0] === 'make');
	t.assert(build._cmd[1] === 'make install');
});

test('should download and build source', function (t) {
	t.plan(2);

	var tmp = path.join(__dirname, 'tmp');
	var build = new BinBuild()
		.src('http://www.lcdf.org/gifsicle/gifsicle-1.84.tar.gz')
		.cmd('./configure --disable-gifview --disable-gifdiff --prefix="' + tmp + '" --bindir="' + tmp + '"')
		.cmd('make install');

	build.build(function (err) {
		t.assert(!err);

		fs.exists(path.join(tmp, 'gifsicle'), function (exists) {
			t.assert(exists);
		});
	});
});
<commit_msg>Small improvement in tests<commit_after>'use strict';

var BinBuild = require('./');
var fs = require('fs');
var path = require('path');
var test = require('ava');

test('expose a constructor', function (t) {
	t.plan(1);
	t.assert(typeof BinBuild === 'function');
});

test('set source file', function (t) {
	t.plan(1);

	var build = new BinBuild()
		.src('src.tar.gz');

	t.assert(build._src === 'src.tar.gz');
});

test('add commands to run', function (t) {
	t.plan(2);

	var build = new BinBuild()
		.cmd('make')
		.cmd('make install');

	t.assert(build._cmd[0] === 'make');
	t.assert(build._cmd[1] === 'make install');
});

test('should download and build source', function (t) {
	t.plan(2);

	var tmp = path.join(__dirname, 'tmp');
	var cmd = [
		'./configure --disable-gifview --disable-gifdiff',
		'--prefix="' + tmp + '" --bindir="' + tmp + '"'
	].join(' ');

	var build = new BinBuild()
		.src('http://www.lcdf.org/gifsicle/gifsicle-1.84.tar.gz')
		.cmd('autoreconf -ivf')
		.cmd(cmd)
		.cmd('make install');

	build.build(function (err) {
		t.assert(!err);

		fs.exists(path.join(tmp, 'gifsicle'), function (exists) {
			t.assert(exists);
		});
	});
});
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-3 08:51:48<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-3 17:44:55<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var expect = require('chai').expect;

var ChirpRest = require('./');

describe("chirp-stream", function() {
    var twitter = ChirpRest({
        consumer: {
            public: process.env.TWITTER_CONSUMER_PUBLIC,
            secret: process.env.TWITTER_CONSUMER_SECRET
        },
        token: {
            public: process.env.TWITTER_TOKEN_PUBLIC,
            secret: process.env.TWITTER_TOKEN_SECRET
        }
    });

    describe("#get tweets", function() {
        it("should be return 20 tweets", function(done) {

            twitter.get('https://api.twitter.com/1.1/statuses/user_timeline.json', function(err, res, tweets) {

                expect(tweets).to.be.an('array').that.have.length(20);
                expect(tweets[0]).to.have.property('id');
                expect(tweets[0]).to.have.property('created_at');
                done();
            });
        });
    });

    describe("#get 5 tweets", function() {
        it("should be return 5 tweets", function(done) {

            twitter.get('https://api.twitter.com/1.1/statuses/user_timeline.json', {
                count: 5
            }, function(err, res, tweets) {

                expect(tweets).to.be.an('array').that.have.length(5);
                expect(tweets[0]).to.have.property('id');
                expect(tweets[0]).to.have.property('created_at');
                done();
            });
        });
    });

    var tweet_id;
    var message = 'Yay....!!!';

    describe("#post new tweet", function() {
        it("should create a new tweet", function(done) {

            twitter.post('https://api.twitter.com/1.1/statuses/update.json', {
                status: message
            }, function(err, res, tweet) {
                tweet_id = tweet.id_str;

                expect(tweet).to.have.property('id');
                expect(tweet).to.have.property('created_at');
                expect(tweet).to.have.property('text', message);
                done();
            });
        });
    });

    describe("#delete tweet", function() {
        it("should delete that new tweet", function(done) {

            twitter.post('https://api.twitter.com/1.1/statuses/destroy/' + tweet_id + '.json', function(err, res, tweet) {
                expect(tweet).to.have.property('id');
                expect(tweet).to.have.property('created_at');
                expect(tweet).to.have.property('text', message);
                done();
            });
        });
    });
});<commit_msg>update test<commit_after>var expect = require('chai').expect;

var ChirpRest = require('./');

describe("chirp-stream", function() {
    var twitter = ChirpRest({
        consumer: {
            public: process.env.TWITTER_CONSUMER_PUBLIC,
            secret: process.env.TWITTER_CONSUMER_SECRET
        },
        token: {
            public: process.env.TWITTER_TOKEN_PUBLIC,
            secret: process.env.TWITTER_TOKEN_SECRET
        }
    });

    describe("#get tweets", function() {
        it("should be return 20 tweets", function(done) {

            twitter.get('https://api.twitter.com/1.1/statuses/user_timeline.json', function(err, res, tweets) {

                expect(tweets).to.be.an('array').that.have.length(20);
                expect(tweets[0]).to.have.property('id');
                expect(tweets[0]).to.have.property('created_at');
                done();
            });
        });
    });

    describe("#get 5 tweets", function() {
        it("should be return 5 tweets", function(done) {

            twitter.get('https://api.twitter.com/1.1/statuses/user_timeline.json', {
                count: 5
            }, function(err, res, tweets) {

                expect(tweets).to.be.an('array').that.have.length(5);
                expect(tweets[0]).to.have.property('id');
                expect(tweets[0]).to.have.property('created_at');
                done();
            });
        });
    });

    var tweet_id;
    var message = 'Yay_-....!!!';

    describe("#post new tweet", function() {
        it("should create a new tweet", function(done) {

            twitter.post('https://api.twitter.com/1.1/statuses/update.json', {
                status: message
            }, function(err, res, tweet) {
                tweet_id = tweet.id_str;

                expect(tweet).to.have.property('id');
                expect(tweet).to.have.property('created_at');
                expect(tweet).to.have.property('text', message);
                done();
            });
        });
    });

    describe("#delete tweet", function() {
        it("should delete that new tweet", function(done) {

            twitter.post('https://api.twitter.com/1.1/statuses/destroy/' + tweet_id + '.json', function(err, res, tweet) {
                expect(tweet).to.have.property('id');
                expect(tweet).to.have.property('created_at');
                expect(tweet).to.have.property('text', message);
                done();
            });
        });
    });
});<|endoftext|>


<commit_before>/**
 * Written by Nathan Fritz and Lance Stout. Copyright © 2011 by &yet, LLC.
 * Released under the terms of the MIT License
 */

var EventEmitter = require("events").EventEmitter,
    uuid = require("node-uuid");

/**
 * A Thoonk feed is a collection of items ordered by publication date.
 *
 * The collection may either be bounded or unbounded in size. A bounded
 * feed is created by adding the field 'max_length' to the configuration
 * with a value greater than 0.
 *
 * Redis Keys Used:
 *     feed.ids:[feed]       -- A sorted set of item IDs.
 *     feed.items:[feed]     -- A hash table of items keyed by ID.
 *     feed.publish:[feed]   -- A pubsub channel for publication notices.
 *     feed.publishes:[feed] -- A counter for number of published items.
 *     feed.retract:[feed]   -- A pubsub channel for retraction notices.
 *     feed.config:[feed]    -- A JSON string of configuration data.
 *     feed.edit:[feed]      -- A pubsub channel for edit notices.
 *
 * Thoonk Standard API:
 *     get_ids  -- Return the IDs of all items in the feed.
 *     get_item -- Return a single item from the feed given its ID.
 *     get_all  -- Return all items in the feed.
 *     publish  -- Publish a new item to the feed, or edit an existing item.
 *     retract  -- Remove an item from the feed.
 */

/**
 * Create a new Feed object for a given Thoonk feed.
 *
 * Note: More than one Feed objects may be create for the same
 *       Thoonk feed, and creating a Feed object does not
 *       automatically generate the Thoonk feed itself.
 *
 * Arguments:
 *     thoonk -- The main Thoonk object.
 *     feed   -- The name of the feed.
 *     config -- Optional dictionary of configuration values.
 *     type   -- Internal use only.
 */
function Feed(thoonk, name, config, type) {
    EventEmitter.call(this);
    this.thoonk = thoonk;

    //local references
    this.mredis = this.thoonk.mredis;
    this.lredis = this.thoonk.lredis;
    this.bredis = this.thoonk.bredis;

    this.name = name;
    this.subscribed = false;
    this.thoonk.once("ready:" + name, this.ready.bind(this));
    this.thoonk.exists(name,
        //exists
        function(reply) {
            if(!config) {
                thoonk.update_config(this.name, this.ready.bind(this));
            } else {
                if(!type) { type = 'feed' }
                if(!config.hasOwnProperty('type')) { config.type = type; }
                this.thoonk.setConfig(this.name, config);
            }
        }.bind(this),
        //doesn't
        function(reply) {
            thoonk.create(name, config);
        }.bind(this)
    );

    this.publish = this.thoonk.lock.require(feedPublish, this);
    this.retract = this.thoonk.lock.require(feedRetract, this);
}

function feedReady() {
    this.lredis.once('idle', function() {
        this.emit('ready');
    }.bind(this));
    setTimeout(function() {
        this.emit('ready');
    }.bind(this), 100);
    this.lredis.subscribe("feed.publish:" + this.name);
    this.lredis.subscribe("feed.edit:" + this.name);
    this.lredis.subscribe("feed.retract:" + this.name);
    this.lredis.subscribe("feed.position:" + this.name);
    this.subscribed = true;
}

/**
 * Publish an item to the feed, or replace an existing item.
 *
 * Newly published items will be at the top of the feed, while
 * edited items will remain in their original order.
 *
 * If the feed has a max length, then the oldest entries will
 * be removed to maintain the maximum length.
 *
 * Arguments:
 *     item     -- The content of the item to add to the feed.
 *     id       -- Optional ID to use for the item, if the ID already
 *                 exists, the existing item will be replaced.
 *     callback -- Executed upon sucessful publish.
 *
 * Callback Arguments:
 *     item -- The conent of the published item.
 *     id   -- The ID assigned to the published item.
 */
function feedPublish(item, id, callback) {
    if(id == null) {
        id = uuid();
    }
    var max_length = this.thoonk.feeds[this.name]['max_length'];
    var pmulti = this.mredis.multi();
    if(max_length) {
        //attempt to publish, so long as feed.ids doesn't change
        var publish_attempt = function() {
            this.mredis.watch('feed.ids:' + this.name);
            this.mredis.zrange('feed.ids:' + this.name, 0, -max_length, function (err, reply) {
                var delete_ids = reply;
                delete_ids.forEach(function (delete_id, idx) {
                    pmulti.zrem('feed.ids:' + this.name, delete_id);
                    pmulti.hdel('feed.items:' + this.name, delete_id);
                    pmulti.publish('feed.retract:' + this.name, delete_id);
                }.bind(this));
                pmulti.zadd('feed.ids:' + this.name, Date.now(), id);
                pmulti.incr('feed.publishes:' + this.name);
                pmulti.hset('feed.items:' + this.name, id, item);
                pmulti.exec(function(err, reply) {
                    this.thoonk.lock.unlock();
                    if(!reply) {
                        publish_attempt();
                    } else {
                        if(reply.slice(-3,-2)[0]) {
                            this.mredis.publish('feed.publish:' + this.name, id + "\x00" + item);
                        } else {
                            this.mredis.publish('feed.edit:' + this.name, id + "\x00" + item);
                        }
                        if(callback !== undefined) { callback(item, id); }
                    }
                }.bind(this));
            }.bind(this));
        }.bind(this);
        publish_attempt();
    } else {
        pmulti.zadd('feed.ids:' + this.name, Date.now(), id);
        pmulti.incr('feed.publishes:' + this.name);
        pmulti.hset('feed.items:' + this.name, id, item);
        pmulti.exec(function(err,reply) {
            this.thoonk.lock.unlock();
            if(reply.slice(-3,-2)[0]) {
                this.mredis.publish('feed.publish:' + this.name, id + "\x00" + item);
            } else {
                this.mredis.publish('feed.edit:' + this.name, id + "\x00" + item);
            }
            if(callback !== undefined) { callback(item, id); }
        }.bind(this));
    }
}

/**
 * Remove an item from the feed.
 *
 * Arguments:
 *     id       -- The ID value of the item to remove.
 *     callback -- Executed on successful retraction.
 *
 * Callback Arguments:
 *     id -- ID of the removed item.
 *     err_msg -- A string or null.
 */
function feedRetract(id, callback) {
    this.mredis.watch('feed.ids:' + this.name, function(err, reply) {
        this.mredis.zrank('feed.ids:' + this.name, id, function(err, reply) {
            if(reply >= 0) {
                var rmulti = this.mredis.multi();
                rmulti.zrem('feed.ids:' + this.name, id);
                rmulti.hdel('feed.items:' + this.name, id);
                rmulti.publish('feed.retract:' + this.name, id);
                rmulti.exec(function(err, reply) {
                    this.thoonk.lock.unlock();
                    if(!reply) {
                        process.nextTick(function() {
                            this.retract(id, callback);
                        }.bind(this));
                    } else {
                        if(callback) { callback(id); }
                    }
                }.bind(this));
            } else {
                this.thoonk.lock.unlock();
                this.mredis.unwatch();
                callback(id, "Id does not exist.");
            }
        }.bind(this));
    }.bind(this));
}

/**
 * Return the set of IDs used by items in the feed."""
 *
 * Arguments:
 *     callback --
 *
 * Callback Arguments:
 *     error -- A string or null.
 *     reply -- The Redis reply object.
 */
function feedGetIds(callback) {
    return this.mredis.zrange("feed.ids:" + this.name, 0, -1, callback);
}

/**
 * Retrieve a single item from the feed.
 *
 * Arguments:
 *     id       -- The ID of the item to retrieve.
 *     callback --
 *
 * Callback Arguments:
 *     error -- A string or null.
 *     reply -- The Redis reply object.
 */
function feedGetItem(id, callback) {
    return this.mredis.hget("feed.items:" + this.name, id, callback);
}

/**
 * Retrieve all items from the feed.
 *
 * Arguments:
 *     callback --
 *
 * Callback Arguments:
 *     error -- A string or null.
 *     reply -- The Redis reply object.
 */
function feedGetAll(callback) {
    return this.mredis.hgetall("feed.items:" + this.name, callback);
}

/**
 * Subscribe to receive events from the feed.
 *
 * Events:
 *     publishes
 *     edits
 *     retractions
 *
 * Object Property Arguments:
 *     publish  -- Executed on an item publish event.
 *     edit     -- Executed on an item edited event.
 *     retract  -- Executed on an item removal event.
 *     position -- Placeholder for sorted feed item placement.
 *     done     -- Executed when subscription is completed.
 *
 * Publish and Edit Callback Arguments:
 *     name -- The name of the feed that changed.
 *     id   -- The ID of the published or edited item.
 *     item -- The content of the published or edited item.
 *
 * Retract Callback Arguments:
 *     name -- The name of the feed that changed.
 *     id   -- The ID of the retracted item.
 *
 * Done Callback Arguments: None
 */
function feedSubscribe(callbacks) {
    if(callbacks['publish']) {
        this.thoonk.on('publish:' + this.name, callbacks['publish']);
    }
    if(callbacks['edit']) {
        this.thoonk.on('edit:' + this.name, callbacks['edit']);
    }
    if(callbacks['retract']) {
        this.thoonk.on('retract:' + this.name, callbacks['retract']);
    }
    if(callbacks['position']) {
        this.thoonk.on('position:' + this.name, callbacks['position']);
    }
    if(!this.subscribed) {
        this.lredis.once('idle', callbacks['done']);
        this.lredis.subscribe("feed.publish:" + this.name);
        this.lredis.subscribe("feed.edit:" + this.name);
        this.lredis.subscribe("feed.retract:" + this.name);
        this.lredis.subscribe("feed.position:" + this.name);
        this.subscribed = true;
    } else {
        callbacks['done']();
    }
}

//extend Feed with EventEmitter
Feed.super_ = EventEmitter;
Feed.prototype = Object.create(EventEmitter.prototype, {
    constructor: {
        value: Feed,
        enumerable: false
    }
});

Feed.prototype.publish = feedPublish;
Feed.prototype.retract = feedRetract;
Feed.prototype.getIds = feedGetIds;
Feed.prototype.getItem = feedGetItem;
Feed.prototype.getAll = feedGetAll;
Feed.prototype.subscribe = feedSubscribe;
Feed.prototype.ready = feedReady;

exports.Feed = Feed;
<commit_msg>Add method for deleting a feed.<commit_after>/**
 * Written by Nathan Fritz and Lance Stout. Copyright © 2011 by &yet, LLC.
 * Released under the terms of the MIT License
 */

var EventEmitter = require("events").EventEmitter,
    uuid = require("node-uuid");

/**
 * A Thoonk feed is a collection of items ordered by publication date.
 *
 * The collection may either be bounded or unbounded in size. A bounded
 * feed is created by adding the field 'max_length' to the configuration
 * with a value greater than 0.
 *
 * Redis Keys Used:
 *     feed.ids:[feed]       -- A sorted set of item IDs.
 *     feed.items:[feed]     -- A hash table of items keyed by ID.
 *     feed.publish:[feed]   -- A pubsub channel for publication notices.
 *     feed.publishes:[feed] -- A counter for number of published items.
 *     feed.retract:[feed]   -- A pubsub channel for retraction notices.
 *     feed.config:[feed]    -- A JSON string of configuration data.
 *     feed.edit:[feed]      -- A pubsub channel for edit notices.
 *
 * Thoonk Standard API:
 *     get_ids  -- Return the IDs of all items in the feed.
 *     get_item -- Return a single item from the feed given its ID.
 *     get_all  -- Return all items in the feed.
 *     publish  -- Publish a new item to the feed, or edit an existing item.
 *     retract  -- Remove an item from the feed.
 */

/**
 * Create a new Feed object for a given Thoonk feed.
 *
 * Note: More than one Feed objects may be create for the same
 *       Thoonk feed, and creating a Feed object does not
 *       automatically generate the Thoonk feed itself.
 *
 * Arguments:
 *     thoonk -- The main Thoonk object.
 *     feed   -- The name of the feed.
 *     config -- Optional dictionary of configuration values.
 *     type   -- Internal use only.
 */
function Feed(thoonk, name, config, type) {
    EventEmitter.call(this);
    this.thoonk = thoonk;

    //local references
    this.mredis = this.thoonk.mredis;
    this.lredis = this.thoonk.lredis;
    this.bredis = this.thoonk.bredis;

    this.name = name;
    this.subscribed = false;
    this.thoonk.once("ready:" + name, this.ready.bind(this));
    this.thoonk.exists(name,
        //exists
        function(reply) {
            if(!config) {
                thoonk.update_config(this.name, this.ready.bind(this));
            } else {
                if(!type) { type = 'feed' }
                if(!config.hasOwnProperty('type')) { config.type = type; }
                this.thoonk.setConfig(this.name, config);
            }
        }.bind(this),
        //doesn't
        function(reply) {
            thoonk.create(name, config);
        }.bind(this)
    );

    this.publish = this.thoonk.lock.require(feedPublish, this);
    this.retract = this.thoonk.lock.require(feedRetract, this);
}

function feedReady() {
    this.lredis.once('idle', function() {
        this.emit('ready');
    }.bind(this));
    setTimeout(function() {
        this.emit('ready');
    }.bind(this), 100);
    this.lredis.subscribe("feed.publish:" + this.name);
    this.lredis.subscribe("feed.edit:" + this.name);
    this.lredis.subscribe("feed.retract:" + this.name);
    this.lredis.subscribe("feed.position:" + this.name);
    this.subscribed = true;
}

/**
 * Publish an item to the feed, or replace an existing item.
 *
 * Newly published items will be at the top of the feed, while
 * edited items will remain in their original order.
 *
 * If the feed has a max length, then the oldest entries will
 * be removed to maintain the maximum length.
 *
 * Arguments:
 *     item     -- The content of the item to add to the feed.
 *     id       -- Optional ID to use for the item, if the ID already
 *                 exists, the existing item will be replaced.
 *     callback -- Executed upon sucessful publish.
 *
 * Callback Arguments:
 *     item -- The conent of the published item.
 *     id   -- The ID assigned to the published item.
 */
function feedPublish(item, id, callback) {
    if(id == null) {
        id = uuid();
    }
    var max_length = this.thoonk.feeds[this.name]['max_length'];
    var pmulti = this.mredis.multi();
    if(max_length) {
        //attempt to publish, so long as feed.ids doesn't change
        var publish_attempt = function() {
            this.mredis.watch('feed.ids:' + this.name);
            this.mredis.zrange('feed.ids:' + this.name, 0, -max_length, function (err, reply) {
                var delete_ids = reply;
                delete_ids.forEach(function (delete_id, idx) {
                    pmulti.zrem('feed.ids:' + this.name, delete_id);
                    pmulti.hdel('feed.items:' + this.name, delete_id);
                    pmulti.publish('feed.retract:' + this.name, delete_id);
                }.bind(this));
                pmulti.zadd('feed.ids:' + this.name, Date.now(), id);
                pmulti.incr('feed.publishes:' + this.name);
                pmulti.hset('feed.items:' + this.name, id, item);
                pmulti.exec(function(err, reply) {
                    this.thoonk.lock.unlock();
                    if(!reply) {
                        publish_attempt();
                    } else {
                        if(reply.slice(-3,-2)[0]) {
                            this.mredis.publish('feed.publish:' + this.name, id + "\x00" + item);
                        } else {
                            this.mredis.publish('feed.edit:' + this.name, id + "\x00" + item);
                        }
                        if(callback !== undefined) { callback(item, id); }
                    }
                }.bind(this));
            }.bind(this));
        }.bind(this);
        publish_attempt();
    } else {
        pmulti.zadd('feed.ids:' + this.name, Date.now(), id);
        pmulti.incr('feed.publishes:' + this.name);
        pmulti.hset('feed.items:' + this.name, id, item);
        pmulti.exec(function(err,reply) {
            this.thoonk.lock.unlock();
            if(reply.slice(-3,-2)[0]) {
                this.mredis.publish('feed.publish:' + this.name, id + "\x00" + item);
            } else {
                this.mredis.publish('feed.edit:' + this.name, id + "\x00" + item);
            }
            if(callback !== undefined) { callback(item, id); }
        }.bind(this));
    }
}

/**
 * Remove an item from the feed.
 *
 * Arguments:
 *     id       -- The ID value of the item to remove.
 *     callback -- Executed on successful retraction.
 *
 * Callback Arguments:
 *     id -- ID of the removed item.
 *     err_msg -- A string or null.
 */
function feedRetract(id, callback) {
    this.mredis.watch('feed.ids:' + this.name, function(err, reply) {
        this.mredis.zrank('feed.ids:' + this.name, id, function(err, reply) {
            if(reply >= 0) {
                var rmulti = this.mredis.multi();
                rmulti.zrem('feed.ids:' + this.name, id);
                rmulti.hdel('feed.items:' + this.name, id);
                rmulti.publish('feed.retract:' + this.name, id);
                rmulti.exec(function(err, reply) {
                    this.thoonk.lock.unlock();
                    if(!reply) {
                        process.nextTick(function() {
                            this.retract(id, callback);
                        }.bind(this));
                    } else {
                        if(callback) { callback(id); }
                    }
                }.bind(this));
            } else {
                this.thoonk.lock.unlock();
                this.mredis.unwatch();
                callback(id, "Id does not exist.");
            }
        }.bind(this));
    }.bind(this));
}

/**
 * Return the set of IDs used by items in the feed."""
 *
 * Arguments:
 *     callback --
 *
 * Callback Arguments:
 *     error -- A string or null.
 *     reply -- The Redis reply object.
 */
function feedGetIds(callback) {
    return this.mredis.zrange("feed.ids:" + this.name, 0, -1, callback);
}

/**
 * Retrieve a single item from the feed.
 *
 * Arguments:
 *     id       -- The ID of the item to retrieve.
 *     callback --
 *
 * Callback Arguments:
 *     error -- A string or null.
 *     reply -- The Redis reply object.
 */
function feedGetItem(id, callback) {
    return this.mredis.hget("feed.items:" + this.name, id, callback);
}

/**
 * Retrieve all items from the feed.
 *
 * Arguments:
 *     callback --
 *
 * Callback Arguments:
 *     error -- A string or null.
 *     reply -- The Redis reply object.
 */
function feedGetAll(callback) {
    return this.mredis.hgetall("feed.items:" + this.name, callback);
}

/**
 * Subscribe to receive events from the feed.
 *
 * Events:
 *     publishes
 *     edits
 *     retractions
 *
 * Object Property Arguments:
 *     publish  -- Executed on an item publish event.
 *     edit     -- Executed on an item edited event.
 *     retract  -- Executed on an item removal event.
 *     position -- Placeholder for sorted feed item placement.
 *     done     -- Executed when subscription is completed.
 *
 * Publish and Edit Callback Arguments:
 *     name -- The name of the feed that changed.
 *     id   -- The ID of the published or edited item.
 *     item -- The content of the published or edited item.
 *
 * Retract Callback Arguments:
 *     name -- The name of the feed that changed.
 *     id   -- The ID of the retracted item.
 *
 * Done Callback Arguments: None
 */
function feedSubscribe(callbacks) {
    if(callbacks['publish']) {
        this.thoonk.on('publish:' + this.name, callbacks['publish']);
    }
    if(callbacks['edit']) {
        this.thoonk.on('edit:' + this.name, callbacks['edit']);
    }
    if(callbacks['retract']) {
        this.thoonk.on('retract:' + this.name, callbacks['retract']);
    }
    if(callbacks['position']) {
        this.thoonk.on('position:' + this.name, callbacks['position']);
    }
    if(!this.subscribed) {
        this.lredis.once('idle', callbacks['done']);
        this.lredis.subscribe("feed.publish:" + this.name);
        this.lredis.subscribe("feed.edit:" + this.name);
        this.lredis.subscribe("feed.retract:" + this.name);
        this.lredis.subscribe("feed.position:" + this.name);
        this.subscribed = true;
    } else {
        callbacks['done']();
    }
}

function feedDelete (callback) {
    var self = this;
    this.mredis.watch('feeds');
    this.mredis.sismember('feeds', this.name, function (error, reply) {
        if(reply) {
            var multi = this.mredis.multi();
            multi.srem('feeds', this.name);
            multi.del('feed.ids:' + this.name);
            multi.del('feed.items:' + this.name);
            multi.del('feed.publishes:' + this.name);
            multi.del('feed.retract:' + this.name);
            multi.del('feed.config:' + this.name);
            multi.del('feed.edit:' + this.name);
            multi.publish('delfeed', this.name + '\x00' + this.thoonk.instance);
            multi.exec(function(err, reply) {
                this.thoonk.lock.unlock();
                if(!reply) {
                    process.nextTick(function() {
                        this.del(callback);
                    }.bind(this));
                } else {
                    if(callback) {
                        callback('Success', this.name);
                    }
                }
            }.bind(this));
        } else {
            this.mredis.unwatch(function(err, reply) {
                this.thoonk.lock.unlock();
                if(callback) { callback('DoesNotExist'); }
            }.bind(this));
        }
    }.bind(this));
}

//extend Feed with EventEmitter
Feed.super_ = EventEmitter;
Feed.prototype = Object.create(EventEmitter.prototype, {
    constructor: {
        value: Feed,
        enumerable: false
    }
});

Feed.prototype.publish = feedPublish;
Feed.prototype.retract = feedRetract;
Feed.prototype.getIds = feedGetIds;
Feed.prototype.getItem = feedGetItem;
Feed.prototype.getAll = feedGetAll;
Feed.prototype.subscribe = feedSubscribe;
Feed.prototype.ready = feedReady;
Feed.prototype.del = feedDelete;

exports.Feed = Feed;
<|endoftext|>


<commit_before>/*!
 * set-value <https://github.com/jonschlinkert/set-value>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

require('mocha');
var assert = require('assert');
var should = require('should');
var set = require('./');

describe('set', function() {
  it('should return non-objects', function() {
    var res = set('foo', 'a.b', 'c');
    assert(res === 'foo');
  });

  it('should create a nested property if it does not already exist:', function() {
    var o = {};
    set(o, 'a.b', 'c');
    o.a.b.should.equal('c');
  });

  it('should extend an existing value:', function() {
    var o = {a: {b: {c: 'd'}}};
    set(o, 'a.b', {y: 'z'});
    o.a.b.should.eql({c: 'd', y: 'z'});
  });

  it('should update an object value:', function() {
    var o = {};
    set(o, 'a', {b: 'c'});
    set(o, 'a', {c: 'd'});
    assert.deepEqual(o, {a: {b: 'c', c: 'd'}});
    set(o, 'a', 'b');
    assert.equal(o.a, 'b');
  });

  it('should extend an array:', function() {
    var o = {a: []};
    set(o, 'a.0', {y: 'z'});
    assert(Array.isArray(o.a));
    o.a[0].should.eql({y: 'z'});
  });

  it('should extend an object in an array:', function() {
    var o = {a: [{}, {}, {}]};
    set(o, 'a.0.a', {y: 'z'});
    set(o, 'a.1.b', {y: 'z'});
    set(o, 'a.2.c', {y: 'z'});
    assert(Array.isArray(o.a));
    o.a[0].a.should.eql({y: 'z'});
    o.a[1].b.should.eql({y: 'z'});
    o.a[2].c.should.eql({y: 'z'});
  });

  it('should create a deeply nested property if it does not already exist:', function() {
    var o = {};
    set(o, 'a.b.c.d.e', 'c');
    o.a.b.c.d.e.should.equal('c');
  });

  it('should not create a nested property if it does already exist:', function() {
    var first = {name: 'Halle'};
    var o = {a: first };
    set(o, 'a.b', 'c');
    o.a.b.should.equal('c');
    o.a.should.equal(first);
    o.a.name.should.equal('Halle');
  });

  it('should support immediate properties:', function() {
    var o = {};
    set(o, 'a', 'b');
    o.a.should.equal('b');
  });

  it('should use property paths to set nested values from the source object.', function () {
    var o = {};
    set(o, 'a.locals.name', {first: 'Brian'});
    set(o, 'b.locals.name', {last: 'Woodward'});
    set(o, 'b.locals.name.last', 'Woodward');
    o.should.eql({ a: {locals: {name: { first: 'Brian' }} }, b: {locals: {name: { last: 'Woodward' }} }});
  });

  it('should add the property even if a value is not defined:', function () {
    var fixture = {};
    set(fixture, 'a.locals.name').should.eql({a: {locals: { name: undefined }}});
    set(fixture, 'b.locals.name').should.eql({b: {locals: { name: undefined }}, a: {locals: { name: undefined }}});
  });

  it('should set the specified property.', function () {
    set({a: 'aaa', b: 'b'}, 'a', 'bbb').should.eql({a: 'bbb', b: 'b'});
  });

  it('should support passing an array as the key', function () {
    var actual = set({a: 'a', b: {c: 'd'}}, ['b', 'c', 'd'], 'eee');
    actual.should.eql({a: 'a', b: {c: {d: 'eee'}}});
  });

  it('should set a deeply nested value.', function () {
    var actual = set({a: 'a', b: {c: 'd'}}, 'b.c.d', 'eee');
    actual.should.eql({a: 'a', b: {c: {d: 'eee'}}});
  });

  it('should return the entire object if no property is passed.', function () {
    set({a: 'a', b: {c: 'd'}}).should.eql({a: 'a', b: {c: 'd'}});
  });

  it('should set a value only.', function () {
    set({a: 'a', b: {c: 'd'}}, 'b.c').should.eql({a: 'a', b: {c: undefined}});
  });

  it('should set non-plain objects', function (done) {
    var o = {};

    set(o, 'a.b', new Date());
    var firstDate = o.a.b.getTime();

    setTimeout(function () {
      set(o, 'a.b', new Date());
      var secondDate = o.a.b.getTime();

      firstDate.should.not.eql(secondDate);
      done();
    }, 10);
  });
});

describe('escaping', function () {
  it('should recognize escaped dots:', function() {
    var o = {};
    set(o, 'a\\.b.c.d.e', 'c');
    o['a.b'].c.d.e.should.equal('c');
  });

  it('should work with multple escaped dots:', function() {
    var o = {};
    set(o, 'e\\.f\\.g', 1);
    o['e.f.g'].should.equal(1);
  });

  it('should work with multple escaped dots:', function() {
    var o = {};
    set(o, 'e\\.f.g\\.h\\.i.j', 1);
    o.should.eql({ 'e.f': { 'g.h.i': { j: 1 } } });
  });
});
<commit_msg>use assert<commit_after>/*!
 * set-value <https://github.com/jonschlinkert/set-value>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

require('mocha');
var assert = require('assert');
var set = require('./');

describe('set', function() {
  it('should return non-objects', function() {
    var res = set('foo', 'a.b', 'c');
    assert.equal(res, 'foo');
  });

  it('should create a nested property if it does not already exist:', function() {
    var o = {};
    set(o, 'a.b', 'c');
    assert.equal(o.a.b, 'c');
  });

  it('should extend an existing value:', function() {
    var o = {a: {b: {c: 'd'}}};
    set(o, 'a.b', {y: 'z'});
    assert.deepEqual(o.a.b, {c: 'd', y: 'z'});
  });

  it('should update an object value:', function() {
    var o = {};
    set(o, 'a', {b: 'c'});
    set(o, 'a', {c: 'd'});
    assert.deepEqual(o, {a: {b: 'c', c: 'd'}});
    set(o, 'a', 'b');
    assert.equal(o.a, 'b');
  });

  it('should extend an array:', function() {
    var o = {a: []};
    set(o, 'a.0', {y: 'z'});
    assert(Array.isArray(o.a));
    assert.deepEqual(o.a[0], {y: 'z'});
  });

  it('should extend an object in an array:', function() {
    var o = {a: [{}, {}, {}]};
    set(o, 'a.0.a', {y: 'z'});
    set(o, 'a.1.b', {y: 'z'});
    set(o, 'a.2.c', {y: 'z'});
    assert(Array.isArray(o.a));
    assert.deepEqual(o.a[0].a, {y: 'z'});
    assert.deepEqual(o.a[1].b, {y: 'z'});
    assert.deepEqual(o.a[2].c, {y: 'z'});
  });

  it('should create a deeply nested property if it does not already exist:', function() {
    var o = {};
    set(o, 'a.b.c.d.e', 'c');
    assert.equal(o.a.b.c.d.e, 'c');
  });

  it('should not create a nested property if it does already exist:', function() {
    var first = {name: 'Halle'};
    var o = {a: first };
    set(o, 'a.b', 'c');
    assert.equal(o.a.b, 'c');
    assert.equal(o.a, first);
    assert.equal(o.a.name, 'Halle');
  });

  it('should support immediate properties:', function() {
    var o = {};
    set(o, 'a', 'b');
    assert.equal(o.a, 'b');
  });

  it('should use property paths to set nested values from the source object.', function () {
    var o = {};
    set(o, 'a.locals.name', {first: 'Brian'});
    set(o, 'b.locals.name', {last: 'Woodward'});
    set(o, 'b.locals.name.last', 'Woodward');
    assert.deepEqual(o, { a: {locals: {name: { first: 'Brian' }} }, b: {locals: {name: { last: 'Woodward' }} }});
  });

  it('should add the property even if a value is not defined:', function () {
    var fixture = {};
    assert.deepEqual(set(fixture, 'a.locals.name'), {a: {locals: { name: undefined }}});
    assert.deepEqual(set(fixture, 'b.locals.name'), {b: {locals: { name: undefined }}, a: {locals: { name: undefined }}});
  });

  it('should set the specified property.', function () {
    assert.deepEqual(set({a: 'aaa', b: 'b'}, 'a', 'bbb'), {a: 'bbb', b: 'b'});
  });

  it('should support passing an array as the key', function () {
    var actual = set({a: 'a', b: {c: 'd'}}, ['b', 'c', 'd'], 'eee');
    assert.deepEqual(actual, {a: 'a', b: {c: {d: 'eee'}}});
  });

  it('should set a deeply nested value.', function () {
    var actual = set({a: 'a', b: {c: 'd'}}, 'b.c.d', 'eee');
    assert.deepEqual(actual, {a: 'a', b: {c: {d: 'eee'}}});
  });

  it('should return the entire object if no property is passed.', function () {
    assert.deepEqual(set({a: 'a', b: {c: 'd'}}), {a: 'a', b: {c: 'd'}});
  });

  it('should set a value only.', function () {
    assert.deepEqual(set({a: 'a', b: {c: 'd'}}, 'b.c'), {a: 'a', b: {c: undefined}});
  });

  it('should set non-plain objects', function (done) {
    var o = {};

    set(o, 'a.b', new Date());
    var firstDate = o.a.b.getTime();

    setTimeout(function () {
      set(o, 'a.b', new Date());
      var secondDate = o.a.b.getTime();

      assert.notDeepEqual(firstDate, secondDate);
      done();
    }, 10);
  });
});

describe('escaping', function () {
  it('should recognize escaped dots:', function() {
    var o = {};
    set(o, 'a\\.b.c.d.e', 'c');
    assert.equal(o['a.b'].c.d.e, 'c');
  });

  it('should work with multple escaped dots:', function() {
    var o = {};
    set(o, 'e\\.f\\.g', 1);
    assert.equal(o['e.f.g'], 1);
  });

  it('should work with multple escaped dots:', function() {
    var o = {};
    set(o, 'e\\.f.g\\.h\\.i.j', 1);
    assert.deepEqual(o, { 'e.f': { 'g.h.i': { j: 1 } } });
  });
});
<|endoftext|>


<commit_before>var feed = {}, async = require('async'),
	Twitter = require('mtwitter'),
	Instagram = require('instagram-node-lib'),
	GitHubApi = require("github");

if (process.env.NODE_ENV == 'development') require('./config')

var twitter = new Twitter({
  consumer_key: process.env.twitter_consumer_key,
  consumer_secret: process.env.twitter_consumer_secret,
  access_token_key: process.env.twitter_access_token_key,
  access_token_secret: process.env.twitter_access_token_secret
});

Instagram.set('client_id', process.env.instagram_client_id);
Instagram.set('client_secret', process.env.instagram_client_secret);
Instagram.set('access_token', process.env.instagram_access_token);

var github = new GitHubApi({
    version: "3.0.0",
    timeout: 5000
});

feed.cache = Array();
feed.lastUpdated = new Date();

feed.GithubMessage = function(item) {
	switch (item.type) {
		case 'PushEvent':
			return item.payload.commits[0].message + " in " + item.repo.name;
			break;
		case 'FollowEvent':
			return "Started following "+item.payload.target.login;
			break;
		default:
			return "No info"
			break;
	}
}

feed.GithubLink = function(item) {
	switch (item.type) {
		case 'PushEvent':
			return item.payload.commits[0].url;
			break;
		case 'FollowEvent':
			return item.payload.target.url;
			break;
		default:
			return "No info"
			break;
	}
}

feed.updateFeed = function() {
	console.log("Starting feed update.");
	feed.cache = new Array();
	async.parallel([
		function(callback) {
			twitter.get('statuses/user_timeline', {screen_name: 'nikolaiii', count: 15}, function(err, data) {
				var result = new Array();
				data.forEach(function(item) {
					result.push({
						score: (item.retweeted ? item.retweeted : 0) + (item.favorited ? item.favorited : 0),
						image: item.entities.media != null ? item.entities.media[0].media_url : null,
						text: item.text,
						date: new Date(item.created_at.replace(/^\w+ (\w+) (\d+) ([\d:]+) \+0000 (\d+)$/, "$1 $2 $4 $3 UTC")),
						type: 'twitter',
						link: item.url
					});
				});
				callback(err,result);
		 	});
		},
		function(callback) {
			Instagram.users.recent({
				user_id: 2296300,
				count: 15,
			 	complete: function(data, pagination) {
			 		var result = new Array();
					data.forEach(function(item) {
						result.push({
							score: item.likes.count,
							image: item.images.standard_resolution.url,
							text: item.caption ? item.caption.text : "",
							date: new Date(parseInt(item.created_time) * 1000),
							type: 'instagram',
							link: item.url
						});
					});
					callback(null, result);
				}
			});
		},
		function(callback) {
			github.events.getFromUser({
			    user: "nikolaia",
			    count: 15
			}, function(err, res) {
			    var result = new Array();
				res.forEach(function(item) {
					if (item.type == 'PushEvent') // TODO: Add all Github eventTypes and make support for them.
					result.push({
						score: 0,
						image: item.actor.avatar_url,
						text: feed.GithubMessage(item),
						date: new Date(item.created_at),
						type: 'github',
						link: feed.GithubLink(item)
					});
				});
				callback(null, result);
			});
		}
	],
	function(err, results) {
		if (err) console.log(err);

		feed.cache = results[0].concat(results[1]).concat(results[2]);

		function compare(a,b) {
		  if (a.date > b.date)
		     return -1;
		  if (a.date < b.date)
		    return 1;
		  return 0;
		}

		feed.cache.sort(compare);

		lastUpdated = new Date();

		console.log("Finished updating feed.");
	});
}

module.exports = feed;<commit_msg>Added some error handling<commit_after>var feed = {}, async = require('async'),
	Twitter = require('mtwitter'),
	Instagram = require('instagram-node-lib'),
	GitHubApi = require("github");

if (process.env.NODE_ENV == 'development') require('./config')

var twitter = new Twitter({
  consumer_key: process.env.twitter_consumer_key,
  consumer_secret: process.env.twitter_consumer_secret,
  access_token_key: process.env.twitter_access_token_key,
  access_token_secret: process.env.twitter_access_token_secret
});

Instagram.set('client_id', process.env.instagram_client_id);
Instagram.set('client_secret', process.env.instagram_client_secret);
Instagram.set('access_token', process.env.instagram_access_token);

var github = new GitHubApi({
    version: "3.0.0",
    timeout: 5000
});

feed.cache = Array();
feed.lastUpdated = new Date();

feed.GithubMessage = function(item) {
	switch (item.type) {
		case 'PushEvent':
			return item.payload.commits[0].message + " in " + item.repo.name;
			break;
		case 'FollowEvent':
			return "Started following "+item.payload.target.login;
			break;
		default:
			return "No info"
			break;
	}
}

feed.GithubLink = function(item) {
	switch (item.type) {
		case 'PushEvent':
			return item.payload.commits[0].url;
			break;
		case 'FollowEvent':
			return item.payload.target.url;
			break;
		default:
			return "No info"
			break;
	}
}

feed.updateFeed = function() {
	console.log("Starting feed update.");
	feed.cache = new Array();
	async.parallel([
		function(callback) {
			twitter.get('statuses/user_timeline', {screen_name: 'nikolaiii', count: 15}, function(err, data) {
				if (err) console.log(err);
				var result = new Array();
				data.forEach(function(item) {
					result.push({
						score: (item.retweeted ? item.retweeted : 0) + (item.favorited ? item.favorited : 0),
						image: item.entities.media != null ? item.entities.media[0].media_url : null,
						text: item.text,
						date: new Date(item.created_at.replace(/^\w+ (\w+) (\d+) ([\d:]+) \+0000 (\d+)$/, "$1 $2 $4 $3 UTC")),
						type: 'twitter',
						link: item.url
					});
				});
				callback(err,result);
		 	});
		},
		function(callback) {
			Instagram.users.recent({
				user_id: 2296300,
				count: 15,
			 	complete: function(data, pagination) {
			 		var result = new Array();
					data.forEach(function(item) {
						result.push({
							score: item.likes.count,
							image: item.images.standard_resolution.url,
							text: item.caption ? item.caption.text : "",
							date: new Date(parseInt(item.created_time) * 1000),
							type: 'instagram',
							link: item.url
						});
					});
					callback(null, result);
				},
				error: function(errorMessage, errorObject, caller){
			      console.log(errorMessage);
			      callback(errorMessage, errorObject);
			    }
			});
		},
		function(callback) {
			github.events.getFromUser({
			    user: "nikolaia",
			    count: 15
			}, function(err, res) {
			    var result = new Array();
				res.forEach(function(item) {
					if (item.type == 'PushEvent') // TODO: Add all Github eventTypes and make support for them.
					result.push({
						score: 0,
						image: item.actor.avatar_url,
						text: feed.GithubMessage(item),
						date: new Date(item.created_at),
						type: 'github',
						link: feed.GithubLink(item)
					});
				});
				callback(null, result);
			});
		}
	],
	function(err, results) {
		if (err) console.log(err);

		feed.cache = results[0].concat(results[1]).concat(results[2]);

		function compare(a,b) {
		  if (a.date > b.date)
		     return -1;
		  if (a.date < b.date)
		    return 1;
		  return 0;
		}

		feed.cache.sort(compare);

		lastUpdated = new Date();

		console.log("Finished updating feed.");
	});
}

module.exports = feed;<|endoftext|>


<commit_before>/*global atom:true, gravity:true, logger:true, process, require*/
atom = typeof atom === 'undefined' ? require('atom-js') : atom;
gravity = typeof gravity === 'undefined' ? require('./gravity.js') : gravity;
logger = (typeof logger !== 'undefined' && logger) || console.log;

var
	inBrowser = typeof document !== 'undefined',
	inNode = !inBrowser,
	argv = inNode && process.argv,
	arg2 = argv && argv.length > 2 && argv[2],
	verbose = inBrowser || arg2 === '-v',
	a = atom.create(),
	chain = a.chain,
	results = [],
	totals = { success: 0, fail: 0, total: 0 },
	fs = require('fs')
;

logger('Testing: gravity ' + gravity.VERSION);

function assert(msg, success) {
	totals.total++;
	if (success) {
		totals.success++;
		if (verbose) {
			logger(msg + '... success.');
		}
	} else {
		totals.fail++;
		logger(msg + '... FAIL!');
	}
}

assert('gravity.VERSION is a string', typeof gravity.VERSION === 'string');
assert('gravity.build() is a function', typeof gravity.build === 'function');
assert('gravity.list() is a function', typeof gravity.list === 'function');
assert('gravity.map() is a function', typeof gravity.map === 'function');
assert('gravity.pull() is a function', typeof gravity.pull === 'function');
assert('gravity.serve() is a function', typeof gravity.serve === 'function');

chain(function (next) {
	var
		base = 'test/proj-1',
		src = base + '/src',
		map = src + '/gravity.map'
	;
	gravity.list(src + '/gravity.map', src, function (err, list) {
		list.sort();
		assert(
			'gravity.list() correctly includes subdirectory contents, and omits ' +
				'temporary build targets',
			list + '' ===
				'enum/1.js,enum/2.js,out.js,subsubdir/3.js,word.png'
		);
		next();
	});
});

// File concatenation tests
(function () {
	var
		base = 'test/concat-1',
		src = base + '/src',
		map = src + '/gravity.map',
		build = base + '/build'
	;

	chain(function (next) {
		var
			file = 'two-files.js',
			preBuilt = fs.readFileSync(build + '/' + file) + ''
		;
		gravity.pull(map, src, file, function (err, content) {
			assert(
				'gravity.pull() of a 2-file concatenation works',
				content + '' === preBuilt
			);
			next();
		});
	});

	chain(function (next) {
		var
			file = 'two-literals.js',
			preBuilt = fs.readFileSync(build + '/' + file) + ''
		;
		gravity.pull(map, src, file, function (err, content) {
			assert(
				'gravity.pull() of a 2-literal concatenation works',
				content + '' === preBuilt
			);
			next();
		});
	});

	chain(function (next) {
		var
			file = 'file-temp-literal.js',
			preBuilt = fs.readFileSync(build + '/' + file) + ''
		;
		gravity.pull(map, src, file, function (err, content) {
			assert(
				'gravity.pull() works with a target composed of a file, a temporary ' +
					'build product, and a literal',
				content + '' === preBuilt
			);
			next();
		});
	});

	chain(function (next) {
		var
			file = 'line-hints.js',
			preBuilt = fs.readFileSync(build + '/' + file) + ''
		;
		gravity.pull(map, src, file, function (err, content) {
			assert(
				'gravity.pull() correctly adds line number hints to source files ' +
					'longer than 10 lines',
				content + '' === preBuilt
			);
			next();
		});
	});
}());

chain(function () {
	logger(totals);

	if (totals.fail && inNode) {
		process.exit(1);
	}
});
<commit_msg>Trailing whitespace<commit_after>/*global atom:true, gravity:true, logger:true, process, require*/
atom = typeof atom === 'undefined' ? require('atom-js') : atom;
gravity = typeof gravity === 'undefined' ? require('./gravity.js') : gravity;
logger = (typeof logger !== 'undefined' && logger) || console.log;

var
	inBrowser = typeof document !== 'undefined',
	inNode = !inBrowser,
	argv = inNode && process.argv,
	arg2 = argv && argv.length > 2 && argv[2],
	verbose = inBrowser || arg2 === '-v',
	a = atom.create(),
	chain = a.chain,
	results = [],
	totals = { success: 0, fail: 0, total: 0 },
	fs = require('fs')
;

logger('Testing: gravity ' + gravity.VERSION);

function assert(msg, success) {
	totals.total++;
	if (success) {
		totals.success++;
		if (verbose) {
			logger(msg + '... success.');
		}
	} else {
		totals.fail++;
		logger(msg + '... FAIL!');
	}
}

assert('gravity.VERSION is a string', typeof gravity.VERSION === 'string');
assert('gravity.build() is a function', typeof gravity.build === 'function');
assert('gravity.list() is a function', typeof gravity.list === 'function');
assert('gravity.map() is a function', typeof gravity.map === 'function');
assert('gravity.pull() is a function', typeof gravity.pull === 'function');
assert('gravity.serve() is a function', typeof gravity.serve === 'function');

chain(function (next) {
	var
		base = 'test/proj-1',
		src = base + '/src',
		map = src + '/gravity.map'
	;
	gravity.list(src + '/gravity.map', src, function (err, list) {
		list.sort();
		assert(
			'gravity.list() correctly includes subdirectory contents, and omits ' +
				'temporary build targets',
			list + '' ===
				'enum/1.js,enum/2.js,out.js,subsubdir/3.js,word.png'
		);
		next();
	});
});

// File concatenation tests
(function () {
	var
		base = 'test/concat-1',
		src = base + '/src',
		map = src + '/gravity.map',
		build = base + '/build'
	;

	chain(function (next) {
		var
			file = 'two-files.js',
			preBuilt = fs.readFileSync(build + '/' + file) + ''
		;
		gravity.pull(map, src, file, function (err, content) {
			assert(
				'gravity.pull() of a 2-file concatenation works',
				content + '' === preBuilt
			);
			next();
		});
	});

	chain(function (next) {
		var
			file = 'two-literals.js',
			preBuilt = fs.readFileSync(build + '/' + file) + ''
		;
		gravity.pull(map, src, file, function (err, content) {
			assert(
				'gravity.pull() of a 2-literal concatenation works',
				content + '' === preBuilt
			);
			next();
		});
	});

	chain(function (next) {
		var
			file = 'file-temp-literal.js',
			preBuilt = fs.readFileSync(build + '/' + file) + ''
		;
		gravity.pull(map, src, file, function (err, content) {
			assert(
				'gravity.pull() works with a target composed of a file, a temporary ' +
					'build product, and a literal',
				content + '' === preBuilt
			);
			next();
		});
	});

	chain(function (next) {
		var
			file = 'line-hints.js',
			preBuilt = fs.readFileSync(build + '/' + file) + ''
		;
		gravity.pull(map, src, file, function (err, content) {
			assert(
				'gravity.pull() correctly adds line number hints to source files ' +
					'longer than 10 lines',
				content + '' === preBuilt
			);
			next();
		});
	});
}());

chain(function () {
	logger(totals);

	if (totals.fail && inNode) {
		process.exit(1);
	}
});
<|endoftext|>


<commit_before>"use strict";

const {v4, v6} = require(".");
const {isIPv4, isIPv6} = require("net");
const {test, expect} = global;

test("v4 async", async () => {
  const result = await v4();
  expect(isIPv4(result.gateway)).toBe(true);
  expect(typeof result.interface).toBe("string");
});

test("v6 async", async () => {
  const result = await v6();
  expect(isIPv6(result.gateway)).toBe(true);
  expect(typeof result.interface).toBe("string");
});

test("v4 sync", () => {
  const result = v4.sync();
  expect(isIPv4(result.gateway)).toBe(true);
  expect(typeof result.interface).toBe("string");
});

test("v6 sync", () => {
  const result = v6.sync();
  expect(isIPv6(result.gateway)).toBe(true);
  expect(typeof result.interface).toBe("string");
});
<commit_msg>skip ipv6 on ci<commit_after>"use strict";

const {v4, v6} = require(".");
const {isIPv4, isIPv6} = require("net");
const {test, expect} = global;

test("v4 async", async () => {
  const result = await v4();
  expect(isIPv4(result.gateway)).toBe(true);
  expect(typeof result.interface).toBe("string");
});

if (!("CI" in process.env)) {
  test("v6 async", async () => {
    const result = await v6();
    expect(isIPv6(result.gateway)).toBe(true);
    expect(typeof result.interface).toBe("string");
  });
}

test("v4 sync", () => {
  const result = v4.sync();
  expect(isIPv4(result.gateway)).toBe(true);
  expect(typeof result.interface).toBe("string");
});

if (!("CI" in process.env)) {
  test("v6 sync", () => {
    const result = v6.sync();
    expect(isIPv6(result.gateway)).toBe(true);
    expect(typeof result.interface).toBe("string");
  });
}
<|endoftext|>