<commit_before>var _; //globals

describe("About Applying What We Have Learnt", function() {

  var products;

  beforeEach(function () {
    products = [
       { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
       { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
       { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
       { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
       { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
    ];
  });

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

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () {

    var i,j,hasMushrooms, productsICanEat = [];

    for (i = 0; i < products.length; i+=1) {
        if (products[i].containsNuts === false) {
            hasMushrooms = false;
            for (j = 0; j < products[i].ingredients.length; j+=1) {
               if (products[i].ingredients[j] === "mushrooms") {
                  hasMushrooms = true;
               }
            }
            if (!hasMushrooms) productsICanEat.push(products[i]);
        }
    }

    expect(productsICanEat.length).toBe(1);
  });

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {

      var productsICanEat = [];

      /* solve using filter() & all() / any() */

      productsICanEat = (products.filter(function(each){
        return !each.containsNuts && _(each.ingredients).all(function(ingredient){
          return ingredient !== 'mushrooms'
        });
      }));

      expect(productsICanEat.length).toBe(1);
  });

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

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () {

    var sum = 0;
    for(var i=1; i<1000; i+=1) {
      if (i % 3 === 0 || i % 5 === 0) {
        sum += i;
      }
    }

    expect(sum).toBe(233168);
  });

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () {

    var sum = _(_.range(1000)).chain()
                            .filter(function (x) { return ((x % 5 == 0) || (x % 3 == 0)) })
                            .reduce(function (total, x) { return total + x })
                            .value();

    expect(233168).toBe(sum);
  });

  /*********************************************************************************/
   it("should count the ingredient occurrence (imperative)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    for (i = 0; i < products.length; i+=1) {
        for (j = 0; j < products[i].ingredients.length; j+=1) {
            ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1;
        }
    }

    expect(ingredientCount['mushrooms']).toBe(2);
  });

  it("should count the ingredient occurrence (functional)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    var ingredientCount = _(products).chain()
                                 .map(function(x) { return x.ingredients })
                                 .flatten()
                                 .reduce(function(list, x) {
                                    list[x] = (list[x] || 0) + 1;
                                    return list;
                                  }, {})
                                 .value();

    /* chain() together map(), flatten() and reduce() */

    expect(ingredientCount['mushrooms']).toBe(2);
  });

  /*********************************************************************************/
  /* UNCOMMENT FOR EXTRA CREDIT */

  it("should find the largest prime factor of a composite number", function () {

    var largestPrimeFactor = function(num) {
      var remainder = num;
      var test = 2;
      while (test <= remainder) {
        if (remainder % test == 0) {
          remainder = remainder / test;
        }
        else {
          test += 1;
        }
      }
      return test;
    };
    expect(largestPrimeFactor(22530200)).toBe(19);
  });

  it("should find the largest palindrome made from the product of two 3 digit numbers", function () {

    var palindrome = function(num) {
      chars = num.toString();
      chars = chars.split('');
      charsb = chars.slice().reverse();
      chars = chars.join()
      charsb = charsb.join()
      if (chars == charsb) {
        return true;
      }
      else {
        return false;
      }
    }

    var largestPalindrome= function() {
      var i;
      var j;
      var largest = 0;
      for (i = 100; i < 1000; i++) {
        for (j = 100; j < 1000; j++) {
          if ((palindrome(i*j)) && (largest < (i*j))) {
            largest = i*j;
          }
        }
      }
      return largest;

    }
    expect(largestPalindrome()).toBe(906609);

  });

  it("should find the smallest number divisible by each of the numbers 1 to 20", function () {

    var conversion = function (x) {
      var remainder = x;
      var i = 2;
      list = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
      while (i <= remainder) {
        if (remainder % i == 0) {
          list[i] = (list[i] += 1);
          remainder = remainder / i;
        }
        else {
          i += 1;
        }
      }
      return list;
    };

    var smallestMultiple = function () {
      var i;
      var j;
      var z;
      var num = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
      var smallest = 1;
      for (i = 0; i <= 20; i++) {
        for (j= 1; j <= 20; j++) {
          if (conversion(i)[j] > num[j]) {
            num[j] = conversion(i)[j];
          }
        }
      }
      for (z = 1; z <= 20; z++) {
        while (num[z] >= 1) {
          smallest *= z;
          num[z] -= 1;
        }

      }
      return smallest;

    };

    expect(smallestMultiple()).toBe(232792560);
  });

  it("should find the difference between the sum of the squares and the square of the sums", function () {
    /* presuming that this is a shortened statement of the Euler problem
    requiring the difference between sum of squares of the first natural numbers,
    I've tested it with the first 10 natural numbers but it should work with any. */
    var sumSquares = function (nums) {
      var i;
      var sum = 0;
      for (i = 0; i < nums.length; i++) {
        sum += (nums[i]*nums[i]);
      }
      return sum;
    };

    var squareSum = function (nums) {
      var sum = nums.reduce(function (sum, x) { return sum + x});
      var sum = sum * sum;
      return sum;
    };

    var difference = function (nums) {
      return squareSum(nums) - sumSquares(nums);
    };

    expect(squareSum([1,2,3,4,5,6,7,8,9,10])).toBe(3025);
    expect(sumSquares([1,2,3,4,5,6,7,8,9,10])).toBe(385);
    expect(difference([1,2,3,4,5,6,7,8,9,10])).toBe(2640);
    expect(difference(_.range(1,101))).toBe(25164150);

  });

  it("should find the 10001st prime", function () {

  });

});
<commit_msg>AboutApplyingWhatWeHaveLearnt - Fixed finding the 10001st prime number!<commit_after>var _; //globals

describe("About Applying What We Have Learnt", function() {

  var products;

  beforeEach(function () {
    products = [
       { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
       { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false },
       { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false },
       { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true },
       { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true }
    ];
  });

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

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () {

    var i,j,hasMushrooms, productsICanEat = [];

    for (i = 0; i < products.length; i+=1) {
        if (products[i].containsNuts === false) {
            hasMushrooms = false;
            for (j = 0; j < products[i].ingredients.length; j+=1) {
               if (products[i].ingredients[j] === "mushrooms") {
                  hasMushrooms = true;
               }
            }
            if (!hasMushrooms) productsICanEat.push(products[i]);
        }
    }

    expect(productsICanEat.length).toBe(1);
  });

  it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {

      var productsICanEat = [];

      /* solve using filter() & all() / any() */

      productsICanEat = (products.filter(function(each){
        return !each.containsNuts && _(each.ingredients).all(function(ingredient){
          return ingredient !== 'mushrooms'
        });
      }));

      expect(productsICanEat.length).toBe(1);
  });

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

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () {

    var sum = 0;
    for(var i=1; i<1000; i+=1) {
      if (i % 3 === 0 || i % 5 === 0) {
        sum += i;
      }
    }

    expect(sum).toBe(233168);
  });

  it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () {

    var sum = _(_.range(1000)).chain()
                            .filter(function (x) { return ((x % 5 == 0) || (x % 3 == 0)) })
                            .reduce(function (total, x) { return total + x })
                            .value();

    expect(233168).toBe(sum);
  });

  /*********************************************************************************/
   it("should count the ingredient occurrence (imperative)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    for (i = 0; i < products.length; i+=1) {
        for (j = 0; j < products[i].ingredients.length; j+=1) {
            ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1;
        }
    }

    expect(ingredientCount['mushrooms']).toBe(2);
  });

  it("should count the ingredient occurrence (functional)", function () {
    var ingredientCount = { "{ingredient name}": 0 };

    var ingredientCount = _(products).chain()
                                 .map(function(x) { return x.ingredients })
                                 .flatten()
                                 .reduce(function(list, x) {
                                    list[x] = (list[x] || 0) + 1;
                                    return list;
                                  }, {})
                                 .value();

    /* chain() together map(), flatten() and reduce() */

    expect(ingredientCount['mushrooms']).toBe(2);
  });

  /*********************************************************************************/
  /* UNCOMMENT FOR EXTRA CREDIT */

  it("should find the largest prime factor of a composite number", function () {

    var largestPrimeFactor = function(num) {
      var remainder = num;
      var test = 2;
      while (test <= remainder) {
        if (remainder % test == 0) {
          remainder = remainder / test;
        }
        else {
          test += 1;
        }
      }
      return test;
    };
    expect(largestPrimeFactor(22530200)).toBe(19);
  });

  it("should find the largest palindrome made from the product of two 3 digit numbers", function () {

    var palindrome = function(num) {
      chars = num.toString();
      chars = chars.split('');
      charsb = chars.slice().reverse();
      chars = chars.join()
      charsb = charsb.join()
      if (chars == charsb) {
        return true;
      }
      else {
        return false;
      }
    }

    var largestPalindrome= function() {
      var i;
      var j;
      var largest = 0;
      for (i = 100; i < 1000; i++) {
        for (j = 100; j < 1000; j++) {
          if ((palindrome(i*j)) && (largest < (i*j))) {
            largest = i*j;
          }
        }
      }
      return largest;

    }
    expect(largestPalindrome()).toBe(906609);

  });

  it("should find the smallest number divisible by each of the numbers 1 to 20", function () {

    var conversion = function (x) {
      var remainder = x;
      var i = 2;
      list = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
      while (i <= remainder) {
        if (remainder % i == 0) {
          list[i] = (list[i] += 1);
          remainder = remainder / i;
        }
        else {
          i += 1;
        }
      }
      return list;
    };

    var smallestMultiple = function () {
      var i;
      var j;
      var z;
      var num = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
      var smallest = 1;
      for (i = 0; i <= 20; i++) {
        for (j= 1; j <= 20; j++) {
          if (conversion(i)[j] > num[j]) {
            num[j] = conversion(i)[j];
          }
        }
      }
      for (z = 1; z <= 20; z++) {
        while (num[z] >= 1) {
          smallest *= z;
          num[z] -= 1;
        }

      }
      return smallest;

    };

    expect(smallestMultiple()).toBe(232792560);
  });

  it("should find the difference between the sum of the squares and the square of the sums", function () {
    /* presuming that this is a shortened statement of the Euler problem
    requiring the difference between sum of squares of the first natural numbers,
    I've tested it with the first 10 natural numbers but it should work with any. */
    var sumSquares = function (nums) {
      var i;
      var sum = 0;
      for (i = 0; i < nums.length; i++) {
        sum += (nums[i]*nums[i]);
      }
      return sum;
    };

    var squareSum = function (nums) {
      var sum = nums.reduce(function (sum, x) { return sum + x});
      var sum = sum * sum;
      return sum;
    };

    var difference = function (nums) {
      return squareSum(nums) - sumSquares(nums);
    };

    expect(squareSum([1,2,3,4,5,6,7,8,9,10])).toBe(3025);
    expect(sumSquares([1,2,3,4,5,6,7,8,9,10])).toBe(385);
    expect(difference([1,2,3,4,5,6,7,8,9,10])).toBe(2640);
    expect(difference(_.range(1,101))).toBe(25164150);

  });

  it("should find the 10001st prime", function () {

    function isPrime (x) {
      var fail = 0;
      for (var i = 2; i < x; i++) {
        if (x % i == 0) {
          fail++;
        }
      }
      return fail == 0;
    }

    function primeList (x) {
      var list = [2];
      current = 3;
      while (list.length < x) {
        if (isPrime(current)) {
          list.push(current)
        }
        current++;
      }
      return list[x-1];
    }

    expect(isPrime(19)).toBe(true);
    expect(primeList(10001)).toBe(104743);
  });

});
<|endoftext|>


<commit_before>/*
 * 0xtrades.info
 * https://github.com/vsergeev/0xtrades.info
 *
 * Copyright (c) 2017 Ivan (Vanya) A. Sergeev
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/******************************************************************************/
/* Constants */
/******************************************************************************/

var ZEROEX_GENESIS_BLOCK = {
  1: 4145578,
  42: 4145578,
};

var ZEROEX_RELAY_ADDRESSES = {
  1: {
    "0xa258b39954cef5cb142fd567a46cddb31a670124": "Radar Relay",
    "0xeb71bad396acaa128aeadbc7dbd59ca32263de01": "Kin Alpha",
    "0xc22d5b2951db72b44cfb8089bb8cd374a3c354ea": "OpenRelay",
  },
  42: {
    "0xa258b39954cef5cb142fd567a46cddb31a670124": "Radar Relay",
  },
};

/* Populated by model */
var ZEROEX_TOKEN_INFOS = {
    /* Pre-load some newer token infos */
    "0x8f8221afbb33998d8584a2b05749ba73c37a938a": {
      name: "Request",
      symbol: "REQ",
      decimals: 18,
    },
};

/* Populated by model */
var ZEROEX_EXCHANGE_ADDRESS = null;

/* Populated by model */
var ZEROEX_TOKEN_ADDRESS = null;

var NETWORK_NAME = {
  1: "Mainnet",
  3: "Ropsten",
  4: "Rinkeby",
  42: "Kovan",
};

var NETWORK_BLOCK_EXPLORER = {
  1: "https://etherscan.io",
  3: "https://ropsten.etherscan.io",
  4: "https://rinkeby.etherscan.io",
  42: "https://kovan.etherscan.io",
};

var PRICE_API_URL = function (symbols, base) {
  return "https://min-api.cryptocompare.com/data/pricemulti?fsyms=" + symbols.join(',') + "&tsyms=" + base;
};

var INFURA_API_URL = "https://mainnet.infura.io/rdkuEWbeKAjSR9jZ6P1h";

var STATISTICS_TIME_WINDOW = 86400; /* 24 hours */

var BLOCK_FETCH_COUNT = Math.ceil(STATISTICS_TIME_WINDOW/17);

var BLOCK_INFO_RETRY_TIMEOUT = 15*1000;

var PRICE_UPDATE_TIMEOUT = 5*60*1000;

var PRICE_CHART_DEFAULT_PAIR = "ZRX/WETH";

var CHART_DEFAULT_COLORS = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a',
                            '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94',
                            '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d',
                            '#17becf', '#9edae5'];

var CHART_DEFAULT_TOOLTIP_CALLBACK = function (item, data) {
  var label = data.labels[item.index];
  var value = data.datasets[item.datasetIndex].tooltips[item.index] || data.datasets[item.datasetIndex].data[item.index];
  return label + ": " + value;
};

/* From http://www.localeplanet.com/api/auto/currencymap.json */
var FIAT_CURRENCY_MAP = {
  "USD": {
    "symbol": "$",
    "symbol_native": "$",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "USD"
  },
  "EUR": {
    "symbol": "€",
    "symbol_native": "€",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "EUR"
  },
  "GBP": {
    "symbol": "£",
    "symbol_native": "£",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "GBP"
  },
  "JPY": {
    "symbol": "¥",
    "symbol_native": "￥",
    "decimal_digits": 0,
    "rounding": 0,
    "code": "JPY"
  },
  "KRW": {
    "symbol": "₩",
    "symbol_native": "₩",
    "decimal_digits": 0,
    "rounding": 0,
    "code": "KRW"
  },
};

var FIAT_CURRENCY_DEFAULT = "USD";

/******************************************************************************/
/* Logger */
/******************************************************************************/

Logger = {
  enable: function () { Logger.log = Logger._log_console; },
  disable: function () { Logger.log = Logger._log_null; },

  _log_console: console.log.bind(window.console),
  _log_null: function (s) { },

  log: null,
  error: console.error.bind(window.console),
};
<commit_msg>constants: add PPT token to token infos<commit_after>/*
 * 0xtrades.info
 * https://github.com/vsergeev/0xtrades.info
 *
 * Copyright (c) 2017 Ivan (Vanya) A. Sergeev
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/******************************************************************************/
/* Constants */
/******************************************************************************/

var ZEROEX_GENESIS_BLOCK = {
  1: 4145578,
  42: 4145578,
};

var ZEROEX_RELAY_ADDRESSES = {
  1: {
    "0xa258b39954cef5cb142fd567a46cddb31a670124": "Radar Relay",
    "0xeb71bad396acaa128aeadbc7dbd59ca32263de01": "Kin Alpha",
    "0xc22d5b2951db72b44cfb8089bb8cd374a3c354ea": "OpenRelay",
  },
  42: {
    "0xa258b39954cef5cb142fd567a46cddb31a670124": "Radar Relay",
  },
};

/* Populated by model */
var ZEROEX_TOKEN_INFOS = {
    /* Pre-load some newer token infos */
    "0x8f8221afbb33998d8584a2b05749ba73c37a938a": {
      name: "Request",
      symbol: "REQ",
      decimals: 18,
    },
    "0xd4fa1460f537bb9085d22c7bccb5dd450ef28e3a": {
      name: "Populous Platform",
      symbol: "PPT",
      decimals: 8,
    },
};

/* Populated by model */
var ZEROEX_EXCHANGE_ADDRESS = null;

/* Populated by model */
var ZEROEX_TOKEN_ADDRESS = null;

var NETWORK_NAME = {
  1: "Mainnet",
  3: "Ropsten",
  4: "Rinkeby",
  42: "Kovan",
};

var NETWORK_BLOCK_EXPLORER = {
  1: "https://etherscan.io",
  3: "https://ropsten.etherscan.io",
  4: "https://rinkeby.etherscan.io",
  42: "https://kovan.etherscan.io",
};

var PRICE_API_URL = function (symbols, base) {
  return "https://min-api.cryptocompare.com/data/pricemulti?fsyms=" + symbols.join(',') + "&tsyms=" + base;
};

var INFURA_API_URL = "https://mainnet.infura.io/rdkuEWbeKAjSR9jZ6P1h";

var STATISTICS_TIME_WINDOW = 86400; /* 24 hours */

var BLOCK_FETCH_COUNT = Math.ceil(STATISTICS_TIME_WINDOW/17);

var BLOCK_INFO_RETRY_TIMEOUT = 15*1000;

var PRICE_UPDATE_TIMEOUT = 5*60*1000;

var PRICE_CHART_DEFAULT_PAIR = "ZRX/WETH";

var CHART_DEFAULT_COLORS = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a',
                            '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94',
                            '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d',
                            '#17becf', '#9edae5'];

var CHART_DEFAULT_TOOLTIP_CALLBACK = function (item, data) {
  var label = data.labels[item.index];
  var value = data.datasets[item.datasetIndex].tooltips[item.index] || data.datasets[item.datasetIndex].data[item.index];
  return label + ": " + value;
};

/* From http://www.localeplanet.com/api/auto/currencymap.json */
var FIAT_CURRENCY_MAP = {
  "USD": {
    "symbol": "$",
    "symbol_native": "$",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "USD"
  },
  "EUR": {
    "symbol": "€",
    "symbol_native": "€",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "EUR"
  },
  "GBP": {
    "symbol": "£",
    "symbol_native": "£",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "GBP"
  },
  "JPY": {
    "symbol": "¥",
    "symbol_native": "￥",
    "decimal_digits": 0,
    "rounding": 0,
    "code": "JPY"
  },
  "KRW": {
    "symbol": "₩",
    "symbol_native": "₩",
    "decimal_digits": 0,
    "rounding": 0,
    "code": "KRW"
  },
};

var FIAT_CURRENCY_DEFAULT = "USD";

/******************************************************************************/
/* Logger */
/******************************************************************************/

Logger = {
  enable: function () { Logger.log = Logger._log_console; },
  disable: function () { Logger.log = Logger._log_null; },

  _log_console: console.log.bind(window.console),
  _log_null: function (s) { },

  log: null,
  error: console.error.bind(window.console),
};
<|endoftext|>


<commit_before>/**
 * Karma Configuration: Base.
 */
var path = require("path");
var baseCfg = require("./karma.conf");

// Sauce labs environments.
var SAUCE_ENVS = {
  "chrome-mac": {
    base: "SauceLabs",
    browserName: "chrome",
    platform: "OS X 10.9"
  },
  "safari-mac": {
    base: "SauceLabs",
    browserName: "safari",
    platform: "OS X 10.9"
  },
  // TODO: Appears to fail conversion tests.
  // "ie9-win7": {
  //   base: "SauceLabs",
  //   browserName: "internet explorer",
  //   platform: "Windows 7",
  //   version: "9"
  // },
  "ie10-win7": {
    base: "SauceLabs",
    browserName: "internet explorer",
    platform: "Windows 7",
    version: "10"
  },
  "ie11-win7": {
    base: "SauceLabs",
    browserName: "internet explorer",
    platform: "Windows 7",
    version: "11"
  }
};

// Optionally filter browsers from environment or "all browsers"
var BROWSERS = (process.env.BROWSERS || "")
  .split(",")
  .filter(function (x) { return x; });
if (!BROWSERS.length) {
  BROWSERS = Object.keys(SAUCE_ENVS);
}

// SauceLabs tag.
var SAUCE_BRANCH = process.env.TRAVIS_BRANCH || "local";
var SAUCE_TAG = process.env.SAUCE_USERNAME + "@" + SAUCE_BRANCH;

module.exports = function(config) {
  baseCfg(config);
  config.set({
    reporters: ["spec", "saucelabs"],
    sauceLabs: {
      testName: "full-stack-testing - Frontend Unit Tests",
      tags: [SAUCE_TAG],
      public: "public"
    },
    // Timeouts: Allow "n" minutes before saying "good enough". See also:
    // https://github.com/angular/angular.js/blob/master/karma-shared.conf.js
    captureTimeout: 0, // Pass through to SL.
    customLaunchers: SAUCE_ENVS,
    browsers: BROWSERS
  });
};
<commit_msg>SL: Remove BROWSERS env var in favor of first class --browsers<commit_after>/**
 * Karma Configuration: Base.
 */
var path = require("path");
var baseCfg = require("./karma.conf");

// Sauce labs environments.
//
// These are custom definitions that we can later invoke specifically on the
// command line with `--browsers KEY1,KEY2`, etc.
var SAUCE_ENVS = {
  "sl-chrome-mac": {
    base: "SauceLabs",
    browserName: "chrome",
    platform: "OS X 10.9"
  },
  "sl-safari-mac": {
    base: "SauceLabs",
    browserName: "safari",
    platform: "OS X 10.9"
  },
  // TODO: Appears to fail conversion tests.
  // "sl-ie9-win7": {
  //   base: "SauceLabs",
  //   browserName: "internet explorer",
  //   platform: "Windows 7",
  //   version: "9"
  // },
  "sl-ie10-win7": {
    base: "SauceLabs",
    browserName: "internet explorer",
    platform: "Windows 7",
    version: "10"
  },
  "sl-ie11-win7": {
    base: "SauceLabs",
    browserName: "internet explorer",
    platform: "Windows 7",
    version: "11"
  }
};

// SauceLabs tag.
var SAUCE_BRANCH = process.env.TRAVIS_BRANCH || "local";
var SAUCE_TAG = process.env.SAUCE_USERNAME + "@" + SAUCE_BRANCH;

module.exports = function(config) {
  baseCfg(config);
  config.set({
    reporters: ["spec", "saucelabs"],
    sauceLabs: {
      testName: "full-stack-testing - Frontend Unit Tests",
      tags: [SAUCE_TAG],
      public: "public"
    },
    // Timeouts: Allow "n" minutes before saying "good enough". See also:
    // https://github.com/angular/angular.js/blob/master/karma-shared.conf.js
    captureTimeout: 0, // Pass through to SL.
    customLaunchers: SAUCE_ENVS,
    browsers: Object.keys(SAUCE_ENVS)
  });
};
<|endoftext|>


<commit_before>export var pi = 'π';<commit_msg>remove unused test file<commit_after><|endoftext|>


<commit_before>'use strict';

var restify = require('restify');

var configuration = require('../../config/configuration.js');

/**
 * @return A tiny restify server used to emulate the behavior of
 *         the `/oauth/access_token` of `manager.anyfetch.com`
 */
module.exports = function createServer() {
  var server = restify.createServer();
  server.use(restify.bodyParser());

  server.post('/oauth/access_token', function(req, res) {
    var expected = [
      'client_id',
      'client_secret',
      'code',
      'grant_type'
    ];

    if(req.params.client_id !== configuration.test.fakeAppId) {
      return res.send(404, 'Application ' + req.params.client_id + ' not found.');
    }
    expected.forEach(function(param) {
      if(!req.params[param]) {
        return res.send(409, 'Missing parameter ' + param);
      }
    });

    var body = {
      token_type: 'bearer',
      access_token: configuration.test.fakeAccessToken
    };
    res.send(200, body);
  });

  return server;
};<commit_msg>Use `restify` built-in errors<commit_after>'use strict';

var restify = require('restify');

var configuration = require('../../config/configuration.js');

/**
 * @return A tiny restify server used to emulate the behavior of
 *         the `/oauth/access_token` of `manager.anyfetch.com`
 */
module.exports = function createServer() {
  var server = restify.createServer();
  server.use(restify.bodyParser());

  server.post('/oauth/access_token', function(req, res) {
    var expected = [
      'client_id',
      'client_secret',
      'code',
      'grant_type'
    ];

    if(req.params.client_id !== configuration.test.fakeAppId) {
      return res.send(new restify.ResourceNotFoundError('Application ' + req.params.client_id + ' not found.'));
    }
    expected.forEach(function(param) {
      if(!req.params[param]) {
        return res.send(new restify.MissingParameterError('Missing parameter ' + param));
      }
    });

    var body = {
      token_type: 'bearer',
      access_token: configuration.test.fakeAccessToken
    };
    res.send(200, body);
  });

  return server;
};<|endoftext|>


<commit_before>import should from 'should/as-function';
import Promise from 'bluebird';
import _ from 'lodash';
import Syncano from '../../src/syncano';
import {ValidationError} from '../../src/errors';
import {suffix, credentials} from './utils';

describe('Dataobject', function() {
  this.timeout(15000);

  let connection = null;
  let Class = null;
  let Instance = null;
  let DataObject = null;
  const schema = [
    { name: 'title', type: 'string'}
  ];
  const instanceName = suffix.get('instance');
  const className = suffix.get('class');
  const data = {
    name: className,
    instanceName: instanceName,
    description: suffix.get('description')
  };

  before(function() {
    connection = Syncano(credentials.getCredentials());
    Instance = connection.Instance;
    Class = connection.Class;
    DataObject = connection.DataObject;

    return Instance.please().create({name: instanceName});
  });

  after(function() {
    return Instance.please().delete({name: instanceName});
  });

  beforeEach(function() {
    return Class.please().create(data);
  });

  afterEach(function(done) {
    return Class.please().delete({
      instanceName: instanceName,
      name: className
    })
    .then(() => done())
    .catch(() => done());
  });

  it('should be validated', function() {
    should(DataObject().save()).be.rejectedWith(ValidationError);
  });

  it('should require "instanceName"', function() {
    should(DataObject({className: className}).save()).be.rejectedWith(/instanceName/);
  });

  it('should require "className"', function() {
    should(DataObject({instanceName: instanceName}).save()).be.rejectedWith(/className/);
  });

});
<commit_msg>[LIB-392] DataObject save and update via instance tests<commit_after>import should from 'should/as-function';
import Promise from 'bluebird';
import _ from 'lodash';
import Syncano from '../../src/syncano';
import {ValidationError} from '../../src/errors';
import {suffix, credentials} from './utils';

describe('Dataobject', function() {
  this.timeout(15000);

  let connection = null;
  let Class = null;
  let Instance = null;
  let DataObject = null;
  const instanceName = suffix.get('instance');
  const className = suffix.get('class');
  const data = {
    name: className,
    instanceName: instanceName,
    description: suffix.get('description'),
    schema: [
      { name: "title", type: "string" },
      { name: "author", type: "string" }
    ]
  };

  before(function() {
    connection = Syncano(credentials.getCredentials());
    Instance = connection.Instance;
    Class = connection.Class;
    DataObject = connection.DataObject;

    return Instance.please().create({name: instanceName});
  });

  after(function() {
    return Instance.please().delete({name: instanceName});
  });

  beforeEach(function() {
    return Class.please().create(data);
  });

  afterEach(function(done) {
    return Class.please().delete({
      instanceName: instanceName,
      name: className
    })
    .then(() => done())
    .catch(() => done());
  });

  it('should be validated', function() {
    should(DataObject().save()).be.rejectedWith(ValidationError);
  });

  it('should require "instanceName"', function() {
    should(DataObject({className: className}).save()).be.rejectedWith(/instanceName/);
  });

  it('should require "className"', function() {
    should(DataObject({instanceName: instanceName}).save()).be.rejectedWith(/className/);
  });

  it('should be able to save via model instance', function() {
    const dataobj = {
      title: "Pulp",
      author: "Bukowski",
      className: className,
      instanceName: instanceName
    };

    return DataObject(dataobj).save()
      .then((dataobj) => {
        should(dataobj).be.a.Object();
        should(dataobj).have.property('id').which.is.Number();
        should(dataobj).have.property('instanceName').which.is.String().equal(data.instanceName);
        should(dataobj).have.property('created_at').which.is.String();
        should(dataobj).have.property('updated_at').which.is.String();
        should(dataobj).have.property('links').which.is.Object();
        should(dataobj).have.property('channel').which.is.Null();
        should(dataobj).have.property('owner').which.is.Null();
        should(dataobj).have.property('group_permissions').which.is.String().equal('none');
        should(dataobj).have.property('other_permissions').which.is.String().equal('none');
        should(dataobj).have.property('owner_permissions').which.is.String().equal('full');
        should(dataobj).have.property('title').which.is.String().equal('Pulp');
        should(dataobj).have.property('author').which.is.String().equal('Bukowski');
      });
  });

  it('should be able to update via model instance', function() {
    const dataobj = {
      title: "Pulp",
      author: "Bukowski",
      className: className,
      instanceName: instanceName
    };

    return DataObject(dataobj).save()
      .then((dataobj) => {
        should(dataobj).have.property('instanceName').which.is.String().equal(data.instanceName);
        should(dataobj).have.property('title').which.is.String().equal('Pulp');
        should(dataobj).have.property('author').which.is.String().equal('Bukowski');

        dataobj.title = "Brave New World";
        dataobj.author = "Aldous Huxley";
        return dataobj.save();
      })
      .then((dataobj) => {
        should(dataobj).have.property('instanceName').which.is.String().equal(data.instanceName);
        should(dataobj).have.property('title').which.is.String().equal('Brave New World');
        should(dataobj).have.property('author').which.is.String().equal('Aldous Huxley');
      })
  });

});
<|endoftext|>


<commit_before>/*globals THREE, requestAnimationFrame*/
(function( window, document, undefined ) {
  'use strict';

  var container;

  var scene, camera, renderer;
  var projector;

  var planeGeometry, planeMaterial, plane;
  var sphereGeometry, sphereMaterial, sphere;

  var ikGeometry, ikMaterial, ik;
  var ikLengths = [ 80, 30, 50, 70, 40 ];

  var EPSILON = 1e-2;

  function ikGeometryFromArray( lengths ) {
    var geometry = new THREE.Geometry();

    // Creates a vertical line pointing up from its local origin.
    geometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
    lengths.reduce(function( z, length ) {
      z -= length;
      geometry.vertices.push( new THREE.Vector3( 0, 0, z ) );
      return z;
    }, 0 );

    return geometry;
  }

  function ikSet( point, line, lengths ) {
    point = new THREE.Vector3().copy( point );

    var geometry = line.geometry;
    var distance = line.position.distanceTo( point );

    var totalLength = lengths.reduce(function( sum, length ) {
      return sum + length;
    });

    // Enter line coordinate space.
    point.sub( line.position );

    var vertices = geometry.vertices;
    var count = vertices.length;
    var temp = new THREE.Vector3();
    var vi, vj, vf;
    var di, dj, df;
    var t;
    var i, il;
    // Not reachable.
    if ( distance > totalLength ) {
      for ( i = 0, il = count - 1; i < il; i++ ) {
        vi = vertices[i];
        vj = vertices[ i + 1 ];

        di = vi.distanceTo( point );
        t = lengths[i] / di;

        temp.copy( vi ).lerp( point, t );
        vj.copy( temp );
      }
    }
    // Reachable.
    else {
      vf = vertices[ count - 1 ];
      df = vf.distanceTo( point );

      while ( df > EPSILON ) {
        // Set end effector to target.
        vf.copy( point );

        // Stage 1: Forward reaching.
        for ( i = count - 2; i >= 0; i-- ) {
          vi = vertices[i];
          vj = vertices[ i + 1 ];

          dj = vi.distanceTo( vj );
          t = lengths[i] / dj;

          temp.copy( vj ).lerp( vi, t );
          vi.copy( temp );
        }

        // Move first vertex back to origin.
        vertices[0].set( 0, 0, 0 );

        // Stage 2: Backward reaching.
        for ( i = 0; i < count - 1; i++ ) {
          vi = vertices[i];
          vj = vertices[ i + 1 ];

          dj = vi.distanceTo( vj );
          t = lengths[i] / dj;

          temp.copy( vi ).lerp( vj, t );
          vj.copy( temp );
        }

        df = vf.distanceTo( point );
      }
    }

    ik.geometry.verticesNeedUpdate = true;
  }

  function init() {
    container = document.createElement( 'div' );
    document.body.appendChild( container );

    renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild( renderer.domElement );

    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );

    camera.position.set( 0, -400, 200 );
    camera.rotation.x = THREE.Math.degToRad( 60 );

    scene.add( camera );

    // Projector.
    projector = new THREE.Projector();

    // Fog.
    scene.fog = new THREE.Fog( 0x00000 );

    // Plane.
    planeGeometry = new THREE.PlaneGeometry( 500, 500, 20, 20 );
    planeMaterial = new THREE.MeshBasicMaterial({
      wireframe: true
    });
    plane = new THREE.Mesh( planeGeometry, planeMaterial );
    scene.add( plane );

    // Sphere.
    sphereGeometry = new THREE.SphereGeometry( 10 );
    sphereMaterial = new THREE.MeshBasicMaterial({
      color: 0x00ff00,
      wireframe: true
    });
    sphere = new THREE.Mesh( sphereGeometry, sphereMaterial );
    scene.add( sphere );

    // IK.
    ikGeometry = ikGeometryFromArray( ikLengths );
    ikMaterial = new THREE.LineBasicMaterial({
      color: '#f43',
      linewidth: 5
    });
    ik = new THREE.Line( ikGeometry, ikMaterial );
    ik.position.z = 100;
    scene.add( ik );
  }

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

  init();
  animate();

  window.addEventListener( 'mousemove', function( event ) {
    // Calculate intersection.
    var vector = new THREE.Vector3(
      ( event.pageX / window.innerWidth ) * 2 - 1,
      -( event.pageY / window.innerHeight ) * 2 + 1,
      0
    );

    projector.unprojectVector( vector, camera );

    var raycaster = new THREE.Raycaster(
      camera.position,
      vector.sub( camera.position ).normalize()
    );

    var intersections = raycaster.intersectObject( plane );
    if ( intersections[0] ) {
      sphere.position.copy( intersections[0].point );
      ikSet( sphere.position, ik, ikLengths );
    }
  });

  window.addEventListener( 'wheel', function( event ) {
    if ( !event.deltaY ) {
      return;
    }

    event.preventDefault();
    plane.position.z += event.deltaY;
    sphere.position.z = plane.position.z;
    ikSet( sphere.position, ik, ikLengths );
  });

}) ( window, document );
<commit_msg>ik: Only render on input.<commit_after>/*globals THREE, requestAnimationFrame*/
(function( window, document, undefined ) {
  'use strict';

  var container;

  var scene, camera, renderer;
  var projector;

  var planeGeometry, planeMaterial, plane;
  var sphereGeometry, sphereMaterial, sphere;

  var ikGeometry, ikMaterial, ik;
  var ikLengths = [ 80, 30, 50, 70, 40 ];

  var EPSILON = 1e-2;

  function ikGeometryFromArray( lengths ) {
    var geometry = new THREE.Geometry();

    // Creates a vertical line pointing up from its local origin.
    geometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
    lengths.reduce(function( z, length ) {
      z -= length;
      geometry.vertices.push( new THREE.Vector3( 0, 0, z ) );
      return z;
    }, 0 );

    return geometry;
  }

  function ikSet( point, line, lengths ) {
    point = new THREE.Vector3().copy( point );

    var geometry = line.geometry;
    var distance = line.position.distanceTo( point );

    var totalLength = lengths.reduce(function( sum, length ) {
      return sum + length;
    });

    // Enter line coordinate space.
    point.sub( line.position );

    var vertices = geometry.vertices;
    var count = vertices.length;
    var temp = new THREE.Vector3();
    var vi, vj, vf;
    var di, dj, df;
    var t;
    var i, il;
    // Not reachable.
    if ( distance > totalLength ) {
      for ( i = 0, il = count - 1; i < il; i++ ) {
        vi = vertices[i];
        vj = vertices[ i + 1 ];

        di = vi.distanceTo( point );
        t = lengths[i] / di;

        temp.copy( vi ).lerp( point, t );
        vj.copy( temp );
      }
    }
    // Reachable.
    else {
      vf = vertices[ count - 1 ];
      df = vf.distanceTo( point );

      while ( df > EPSILON ) {
        // Set end effector to target.
        vf.copy( point );

        // Stage 1: Forward reaching.
        for ( i = count - 2; i >= 0; i-- ) {
          vi = vertices[i];
          vj = vertices[ i + 1 ];

          dj = vi.distanceTo( vj );
          t = lengths[i] / dj;

          temp.copy( vj ).lerp( vi, t );
          vi.copy( temp );
        }

        // Move first vertex back to origin.
        vertices[0].set( 0, 0, 0 );

        // Stage 2: Backward reaching.
        for ( i = 0; i < count - 1; i++ ) {
          vi = vertices[i];
          vj = vertices[ i + 1 ];

          dj = vi.distanceTo( vj );
          t = lengths[i] / dj;

          temp.copy( vi ).lerp( vj, t );
          vj.copy( temp );
        }

        df = vf.distanceTo( point );
      }
    }

    ik.geometry.verticesNeedUpdate = true;
  }

  function init() {
    container = document.createElement( 'div' );
    document.body.appendChild( container );

    renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild( renderer.domElement );

    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 1000 );

    camera.position.set( 0, -400, 200 );
    camera.rotation.x = THREE.Math.degToRad( 60 );

    scene.add( camera );

    // Projector.
    projector = new THREE.Projector();

    // Fog.
    scene.fog = new THREE.Fog( 0x00000 );

    // Plane.
    planeGeometry = new THREE.PlaneGeometry( 500, 500, 20, 20 );
    planeMaterial = new THREE.MeshBasicMaterial({
      wireframe: true
    });
    plane = new THREE.Mesh( planeGeometry, planeMaterial );
    scene.add( plane );

    // Sphere.
    sphereGeometry = new THREE.SphereGeometry( 10 );
    sphereMaterial = new THREE.MeshBasicMaterial({
      color: 0x00ff00,
      wireframe: true
    });
    sphere = new THREE.Mesh( sphereGeometry, sphereMaterial );
    scene.add( sphere );

    // IK.
    ikGeometry = ikGeometryFromArray( ikLengths );
    ikMaterial = new THREE.LineBasicMaterial({
      color: '#f43',
      linewidth: 5
    });
    ik = new THREE.Line( ikGeometry, ikMaterial );
    ik.position.z = 100;
    scene.add( ik );
  }

  function animate() {
    renderer.render( scene, camera );
  }

  init();
  animate();

  window.addEventListener( 'mousemove', function( event ) {
    // Calculate intersection.
    var vector = new THREE.Vector3(
      ( event.pageX / window.innerWidth ) * 2 - 1,
      -( event.pageY / window.innerHeight ) * 2 + 1,
      0
    );

    projector.unprojectVector( vector, camera );

    var raycaster = new THREE.Raycaster(
      camera.position,
      vector.sub( camera.position ).normalize()
    );

    var intersections = raycaster.intersectObject( plane );
    if ( intersections[0] ) {
      sphere.position.copy( intersections[0].point );
      ikSet( sphere.position, ik, ikLengths );
    }

    requestAnimationFrame( animate );
  });

  window.addEventListener( 'wheel', function( event ) {
    if ( !event.deltaY ) {
      return;
    }

    event.preventDefault();
    plane.position.z += event.deltaY;
    sphere.position.z = plane.position.z;
    ikSet( sphere.position, ik, ikLengths );

    requestAnimationFrame( animate );
  });

}) ( window, document );
<|endoftext|>


<commit_before>describe('lib/rules/disallow-objectcontroller', function () {
    var checker = global.checker({
        plugins: ['./lib/index']
    });

    describe('not configured', function() {

      it('should report with undefined', function() {
        global.expect(function() {
          checker.configure({disallowCoreView: undefined});
        }).to.throws(/requires a true value/i);
      });

      it('should report with an object', function() {
        global.expect(function() {
          checker.configure({disallowCoreView: {}});
        }).to.throws(/requires a true value/i);
      });

    });

    describe('with true', function() {
      checker.rules({disallowCoreView: true});

      checker.cases([
        /* jshint ignore:start */
        {
          it: 'should not report',
          code: function() {
            Ember.View.extend({

            });
          }
        }, {
          it: 'should not report',
          code: function() {
            var foo = Ember.CoreView;
          }
        }, {
          it: 'should not report',
          code: function() {
            Ember.CoreView.foo();
          }
        }, {
          it: 'should report deprecated use',
          errors: 1,
          code: function() {
            Ember.CoreView.extend({

            });
          },
          errors: [{
            column: 6, line: 1, filename: 'input', rule: 'disallowCoreView', fixed: undefined,
            message: 'CoreView is deprecated in Ember 1.12'
          }]
        }, {
          it: 'should report deprecated use',
          errors: 1,
          code: function() {
            var foo = Ember.CoreView.create({

            });
          },
          errors: [{
            column: 16, line: 1, filename: 'input', rule: 'disallowCoreView', fixed: undefined,
            message: 'CoreView is deprecated in Ember 1.12'
          }]
        }
        /* jshint ignore:end */
      ]);
    });
});
<commit_msg>disallowCoreView test should describe the correct rule<commit_after>describe('lib/rules/disallow-coreview', function () {
    var checker = global.checker({
        plugins: ['./lib/index']
    });

    describe('not configured', function() {

      it('should report with undefined', function() {
        global.expect(function() {
          checker.configure({disallowCoreView: undefined});
        }).to.throws(/requires a true value/i);
      });

      it('should report with an object', function() {
        global.expect(function() {
          checker.configure({disallowCoreView: {}});
        }).to.throws(/requires a true value/i);
      });

    });

    describe('with true', function() {
      checker.rules({disallowCoreView: true});

      checker.cases([
        /* jshint ignore:start */
        {
          it: 'should not report',
          code: function() {
            Ember.View.extend({

            });
          }
        }, {
          it: 'should not report',
          code: function() {
            var foo = Ember.CoreView;
          }
        }, {
          it: 'should not report',
          code: function() {
            Ember.CoreView.foo();
          }
        }, {
          it: 'should report deprecated use',
          errors: 1,
          code: function() {
            Ember.CoreView.extend({

            });
          },
          errors: [{
            column: 6, line: 1, filename: 'input', rule: 'disallowCoreView', fixed: undefined,
            message: 'CoreView is deprecated in Ember 1.12'
          }]
        }, {
          it: 'should report deprecated use',
          errors: 1,
          code: function() {
            var foo = Ember.CoreView.create({

            });
          },
          errors: [{
            column: 16, line: 1, filename: 'input', rule: 'disallowCoreView', fixed: undefined,
            message: 'CoreView is deprecated in Ember 1.12'
          }]
        }
        /* jshint ignore:end */
      ]);
    });
});
<|endoftext|>


<commit_before>var helper = require("../helper");
var MachineManager = require("../../src/managers/master/machine-manager");
var instanceManager = null;
var UnitUtil = require('../data-util/master/unit-data-util');
require("should");

function getData() {
    return Promise.resolve(UnitUtil.getTestData())
        .then(unit => {
            var Machine = require('dl-models').master.Machine;
            var machine = new Machine();

            var now = new Date();
            var stamp = now / 1000 | 0;
            var code = stamp.toString(36);

            machine.name = `name [${code}]`;
            machine.unitId = unit._id;
            machine.unit = unit;
            machine.process = `subdivision [${code}]`;
            machine.manufacture=`manufacture [${code}]`;
            machine.year = now.getFullYear();
            machine.condition=`condition [${code}]`;

            return machine;
        });
}

before('#00. connect db', function (done) {
    helper.getDb()
        .then(db => {
            instanceManager = new MachineManager(db, {
                username: 'unit-test'
            });
            done();
        })
        .catch(e => {
            done(e);
        })
});

it('#01. should success when read data', function (done) {
    instanceManager.read()
        .then(documents => {
            //process documents
            documents.data.should.be.instanceof(Array);
            done();
        })
        .catch(e => {
            done(e);
        })
});

var createdId;
it('#02. should success when create new data', function (done) {
    var data = getData();
    instanceManager.create(data)
        .then(id => {
            id.should.be.Object();
            createdId = id;
            done();
        })
        .catch(e => {
            done(e);
        })
});

var createdData;
it(`#03. should success when get created data with id`, function (done) {
    instanceManager.getSingleByQuery({ _id: createdId })
        .then(data => {
            // validate.product(data);
            data.should.instanceof(Object);
            createdData = data;
            done();
        })
        .catch(e => {
            done(e);
        })
});

it(`#04. should success when update created data`, function (done) {

    createdData.name += '[updated]';
    createdData.process += '[updated]';
    createdData.manufacture += '[updated]';
    createdData.year += '[updated]';
    createdData.condition += '[updated]';

    instanceManager.update(createdData)
        .then(id => {
            createdId.toString().should.equal(id.toString());
            done();
        })
        .catch(e => {
            done(e);
        });
});

it(`#05. should success when get updated data with id`, function (done) {
    instanceManager.getSingleByQuery({ _id: createdId })
        .then(data => {
            // validate.product(data);
            data.name.should.equal(createdData.name);
            data.process.should.equal(createdData.process);
            data.manufacture.should.equal(createdData.manufacture);
            data.year.should.equal(createdData.year);
            data.condition.should.equal(createdData.condition);
            done();
        })
        .catch(e => {
            done(e);
        })
});

it(`#06. should success when delete data`, function (done) {
    instanceManager.delete(createdData)
        .then(id => {
            createdId.toString().should.equal(id.toString());
            done();
        })
        .catch(e => {
            done(e);
        });
});

it(`#07. should _deleted=true`, function (done) {
    instanceManager.getSingleByQuery({ _id: createdId })
        .then(data => {
            // validate.product(data);
            data._deleted.should.be.Boolean();
            data._deleted.should.equal(true);
            done();
        })
        .catch(e => {
            done(e);
        })
});<commit_msg>fix getData<commit_after>var helper = require("../helper");
var MachineManager = require("../../src/managers/master/machine-manager");
var instanceManager = null;
var UnitUtil = require('../data-util/master/unit-data-util');
require("should");

function getData() {
    return Promise.resolve(UnitUtil.getTestData())
        .then(unit => {
            var Machine = require('dl-models').master.Machine;
            var machine = new Machine();

            var now = new Date();
            var stamp = now / 1000 | 0;
            var code = stamp.toString(36);

            machine.name = `name [${code}]`;
            machine.unitId = unit._id;
            machine.unit = unit;
            machine.process = `subdivision [${code}]`;
            machine.manufacture=`manufacture [${code}]`;
            machine.year = now.getFullYear();
            machine.condition=`condition [${code}]`;

            return machine;
        });
}

before('#00. connect db', function (done) {
    helper.getDb()
        .then(db => {
            instanceManager = new MachineManager(db, {
                username: 'unit-test'
            });
            done();
        })
        .catch(e => {
            done(e);
        })
});

it('#01. should success when read data', function (done) {
    instanceManager.read()
        .then(documents => {
            //process documents
            documents.data.should.be.instanceof(Array);
            done();
        })
        .catch(e => {
            done(e);
        })
});

var createdId;
it('#02. should success when create new data', function (done) {
    getData().then(data => {
            instanceManager.create(data)
                .then(id => {
                    id.should.be.Object();
                    createdId = id;
                    done();
                })
                .catch(e => {
                    done(e);
                });
        })
        .catch(e => {
            done(e);
        });
});

var createdData;
it(`#03. should success when get created data with id`, function (done) {
    instanceManager.getSingleByQuery({ _id: createdId })
        .then(data => {
            // validate.product(data);
            data.should.instanceof(Object);
            createdData = data;
            done();
        })
        .catch(e => {
            done(e);
        })
});

it(`#04. should success when update created data`, function (done) {

    createdData.name += '[updated]';
    createdData.process += '[updated]';
    createdData.manufacture += '[updated]';
    createdData.year += '[updated]';
    createdData.condition += '[updated]';

    instanceManager.update(createdData)
        .then(id => {
            createdId.toString().should.equal(id.toString());
            done();
        })
        .catch(e => {
            done(e);
        });
});

it(`#05. should success when get updated data with id`, function (done) {
    instanceManager.getSingleByQuery({ _id: createdId })
        .then(data => {
            // validate.product(data);
            data.name.should.equal(createdData.name);
            data.process.should.equal(createdData.process);
            data.manufacture.should.equal(createdData.manufacture);
            data.year.should.equal(createdData.year);
            data.condition.should.equal(createdData.condition);
            done();
        })
        .catch(e => {
            done(e);
        })
});

it(`#06. should success when delete data`, function (done) {
    instanceManager.delete(createdData)
        .then(id => {
            createdId.toString().should.equal(id.toString());
            done();
        })
        .catch(e => {
            done(e);
        });
});

it(`#07. should _deleted=true`, function (done) {
    instanceManager.getSingleByQuery({ _id: createdId })
        .then(data => {
            // validate.product(data);
            data._deleted.should.be.Boolean();
            data._deleted.should.equal(true);
            done();
        })
        .catch(e => {
            done(e);
        })
});<|endoftext|>


<commit_before>/**
 * Logic for translating a given Objective-C "type" encoding into a node-ffi
 * type.
 *
 * Reference: http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
 * node-ffi Type List: https://github.com/rbranson/node-ffi/wiki/Node-FFI-Tutorial#wiki-type-list
 */

exports.map = translate
exports.mapArray = mapArray
exports.parse = parse

var struct = require('./struct')

var map = {
    'c': 'char'
  , 'i': 'int32'
  , 's': 'short'
  , 'l': 'long'
  , 'q': 'longlong'
  , 'C': 'uchar'
  , 'I': 'uint32'
  , 'S': 'ushort'
  , 'L': 'ulong'
  , 'Q': 'ulonglong'
  , 'f': 'float'
  , 'd': 'double'
  , 'B': 'int8'
  , 'v': 'void'
  , '*': 'string'   // String
  , '@': 'pointer'  // id
  , '#': 'pointer'  // Class
  , ':': 'pointer'  // SEL
  , '?': 'pointer'  // Unknown, used for function pointers
};

/**
 * Translates a single Obj-C 'type' into a valid node-ffi type.
 * This mapping logic is kind of a mess...
 */
function translate (type) {
  if (!type) throw new Error('got falsey "type" to map ('+type+'). this should NOT happen!');
  if (type.type) type = type.type
  if (struct.isStruct(type)) return struct.getStruct(type);
  var rtn = map[type];
  if (rtn) return rtn;
  if (type[0] === '^') return 'pointer';
  rtn = map[type[type.length-1]];
  if (rtn) return rtn;
  throw new Error('Could not convert type: ' + type);
}

/**
 * Accepts an Array of ObjC return type and argument types (i.e. the result of
 * parse() below), and returns a new Array with the values mapped to valid ffi
 * types.
 */
function mapArray (types) {
  return types.map(function (type) {
    return Array.isArray(type) ? exports.convert(type) : exports.map(type);
  });
}

/**
 * Parses a "types string" (i.e. "v@:") and returns a "types Array", where the
 * return type is the first array value, and an Array of argument types is the
 * array second value.
 */
function parse (types) {
  if (types[1] !== '@' || types[2] !== ':')
    throw new Error('Invalid types string: '+types)
  return [ types[0], types.substring(1).split('') ]
}
<commit_msg>convert() has been renamed to mapArray().<commit_after>/**
 * Logic for translating a given Objective-C "type" encoding into a node-ffi
 * type.
 *
 * Reference: http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
 * node-ffi Type List: https://github.com/rbranson/node-ffi/wiki/Node-FFI-Tutorial#wiki-type-list
 */

exports.map = translate
exports.mapArray = mapArray
exports.parse = parse

var struct = require('./struct')

var map = {
    'c': 'char'
  , 'i': 'int32'
  , 's': 'short'
  , 'l': 'long'
  , 'q': 'longlong'
  , 'C': 'uchar'
  , 'I': 'uint32'
  , 'S': 'ushort'
  , 'L': 'ulong'
  , 'Q': 'ulonglong'
  , 'f': 'float'
  , 'd': 'double'
  , 'B': 'int8'
  , 'v': 'void'
  , '*': 'string'   // String
  , '@': 'pointer'  // id
  , '#': 'pointer'  // Class
  , ':': 'pointer'  // SEL
  , '?': 'pointer'  // Unknown, used for function pointers
};

/**
 * Translates a single Obj-C 'type' into a valid node-ffi type.
 * This mapping logic is kind of a mess...
 */
function translate (type) {
  if (!type) throw new Error('got falsey "type" to map ('+type+'). this should NOT happen!');
  if (type.type) type = type.type
  if (struct.isStruct(type)) return struct.getStruct(type);
  var rtn = map[type];
  if (rtn) return rtn;
  if (type[0] === '^') return 'pointer';
  rtn = map[type[type.length-1]];
  if (rtn) return rtn;
  throw new Error('Could not convert type: ' + type);
}

/**
 * Accepts an Array of ObjC return type and argument types (i.e. the result of
 * parse() below), and returns a new Array with the values mapped to valid ffi
 * types.
 */
function mapArray (types) {
  return types.map(function (type) {
    return Array.isArray(type) ? exports.mapArray(type) : exports.map(type);
  });
}

/**
 * Parses a "types string" (i.e. "v@:") and returns a "types Array", where the
 * return type is the first array value, and an Array of argument types is the
 * array second value.
 */
function parse (types) {
  if (types[1] !== '@' || types[2] !== ':')
    throw new Error('Invalid types string: '+types)
  return [ types[0], types.substring(1).split('') ]
}
<|endoftext|>


<commit_before>// When an error occurs
function errorFn(msg, trace) {
  // Log the error and trace
  console.error(msg);
  trace.forEach(function(item) {
      console.error('  ', item.file, ':', item.line);
  });

  // Leave with a bad exit code
  phantom.exit(1);
}
phantom.onError = errorFn;

// Load in modules
var system = require('system'),
    webpage = require('webpage');

// Grab the arguments
var url = system.args[1],
    imgDest = system.args[2];

// If there is no url, throw an error
if (!url) {
  throw new Error('No url was specified.');
}

// if there is no image destination, throw an error
if (!imgDest) {
  throw new Error('No img destination was specified.');
}

// Create helper function to retry
function retry(fn, times, cb) {
  var i = 0;
  function retryFn() {
    if (fn()) {
      cb();
    } else if (i > times) {
      cb(new Error('Retry exceeded ' + times));
    } else {
      i += 1;
      console.log('retrying');
      setTimeout(retryFn, 100);
    }
  }
  retryFn();
}

// Load the compose webpage
var page = webpage.create();
page.onError = errorFn;
page.open(url, function (status) {
  // If the status is bad, throw an error
  if (status !== 'success') {
    throw new Error('"' + url + '" opened with bad status: "' + status + '"');
  }

  // Wait for render to work
  retry(function renderPage () {
    return page.render(imgDest);
  }, 10, function handleError (err) {
    // If there was an error, throw it
    if (err) {
      throw err;
    }

    // Leave the program
    phantom.exit();
  });
});
<commit_msg>Removing console.log<commit_after>// When an error occurs
function errorFn(msg, trace) {
  // Log the error and trace
  console.error(msg);
  trace.forEach(function(item) {
      console.error('  ', item.file, ':', item.line);
  });

  // Leave with a bad exit code
  phantom.exit(1);
}
phantom.onError = errorFn;

// Load in modules
var system = require('system'),
    webpage = require('webpage');

// Grab the arguments
var url = system.args[1],
    imgDest = system.args[2];

// If there is no url, throw an error
if (!url) {
  throw new Error('No url was specified.');
}

// if there is no image destination, throw an error
if (!imgDest) {
  throw new Error('No img destination was specified.');
}

// Create helper function to retry
function retry(fn, times, cb) {
  var i = 0;
  function retryFn() {
    if (fn()) {
      cb();
    } else if (i > times) {
      cb(new Error('Retry exceeded ' + times));
    } else {
      i += 1;
      setTimeout(retryFn, 100);
    }
  }
  retryFn();
}

// Load the compose webpage
var page = webpage.create();
page.onError = errorFn;
page.open(url, function (status) {
  // If the status is bad, throw an error
  if (status !== 'success') {
    throw new Error('"' + url + '" opened with bad status: "' + status + '"');
  }

  // Wait for render to work
  retry(function renderPage () {
    return page.render(imgDest);
  }, 10, function handleError (err) {
    // If there was an error, throw it
    if (err) {
      throw err;
    }

    // Leave the program
    phantom.exit();
  });
});
<|endoftext|>


<commit_before>
"use strict";

var unifi = require('node-unifi');

class UnifiApi {
	constructor(host, port, user, pass) {
		this.host = host;
		this.port = port;

		this.ctrl = new unifi.Controller(host, port);

		this.user = user;
		this.pass = pass;
	}
	login(user, pass) {
		return this._wrap("login", user, pass);
	}
	adopt(mac, site) {
		return this._wrap("adoptDevice", site, mac);
	}
	_wrap(fn) {
		var func = this.ctrl[fn];
		var args = new Array(arguments.length);
		for(var i=0; i<args.length - 1; i++) {
			args[i] = arguments[i+1];
		}

		var defered = Promise.defer();
		args[args.length-1] = function(err) {
			if(err) {
				defered.reject(err);
			} else {
				defered.resolve();
			}
		};
		func.apply(this.ctrl, args);
		return defered.promise;
	}
}

module.exports = function(host, port, user, pass) {
	return new UnifiApi(host, port, user, pass);
};
<commit_msg>cleaning<commit_after>
"use strict";

var unifi = require('node-unifi');

class UnifiApi {
	constructor(host, port) {
		this.host = host;
		this.port = port;

		this.ctrl = new unifi.Controller(host, port);
	}
	login(user, pass) {
		return this._wrap("login", user, pass);
	}
	adopt(mac, site) {
		return this._wrap("adoptDevice", site, mac);
	}
	_wrap(fn) {
		var func = this.ctrl[fn];
		var args = new Array(arguments.length);
		for(var i=0; i<args.length - 1; i++) {
			args[i] = arguments[i+1];
		}

		var defered = Promise.defer();
		args[args.length-1] = function(err) {
			if(err) {
				defered.reject(err);
			} else {
				defered.resolve();
			}
		};
		func.apply(this.ctrl, args);
		return defered.promise;
	}
}

module.exports = (host, port) => new UnifiApi(host, port);
<|endoftext|>


<commit_before>var SiteMap = require('sitemap.js').SiteMap;
var Doc = require('ngdoc.js').Doc;

describe('sitemap', function(){
  it('should render empty sitemap', function(){
    var map = new SiteMap([]);
    expect(map.render()).toEqual([
      '<?xml version="1.0" encoding="UTF-8"?>',
      '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
      '</urlset>', ''].join('\n'));
  });

  it('should render ngdoc url', function(){
    var map = new SiteMap([new Doc({name: 'a.b.c<>\'"&'})]);
    expect(map.render()).toContain([
      ' <url>',
      '<loc>http://docs.angularjs.org/#!a.b.c<>'"&</loc>',
      '<changefreq>weekly</changefreq>',
      '</url>'].join(''));

  });
});
<commit_msg>Fix sitemap include (to work on case sensitive linux)<commit_after>var SiteMap = require('SiteMap.js').SiteMap;
var Doc = require('ngdoc.js').Doc;

describe('sitemap', function(){
  it('should render empty sitemap', function(){
    var map = new SiteMap([]);
    expect(map.render()).toEqual([
      '<?xml version="1.0" encoding="UTF-8"?>',
      '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
      '</urlset>', ''].join('\n'));
  });

  it('should render ngdoc url', function(){
    var map = new SiteMap([new Doc({name: 'a.b.c<>\'"&'})]);
    expect(map.render()).toContain([
      ' <url>',
      '<loc>http://docs.angularjs.org/#!a.b.c<>'"&</loc>',
      '<changefreq>weekly</changefreq>',
      '</url>'].join(''));

  });
});
<|endoftext|>


<commit_before>/*!
 * This basic example shows how to fetch some deals
 * matching a specific filter from Pipedrive account.
 *
 * It starts by fetching the first deals filter from the
 * account, it then fetches 5 deals matching to this
 * filter.
 *
 * It will then display a list of found deals along
 * with the values and with how many activities they are
 * associated with.
 *
 * Usage:
 * node list-deals.js APITOKEN
**/

if (!process.argv[2]) {
	process.stderr.write('Please provide API token!' + "\n");
	process.exit();
}

var Pipedrive = require(__dirname + '/../index');
var pipedrive = new Pipedrive.Client(process.argv[2]);
var _ = require('lodash');

pipedrive.Files.add({ name: 'test.js' }, { data: __dirname + '/add-file.js' }, function(addFileErr, addFileData) {
	if (addFileErr) throw addFileErr;
	console.log(addFileData);
});<commit_msg>remove unnecessary file<commit_after><|endoftext|>


<commit_before>Tiamat = require("tiamat/server.js").Tiamat;
Daemon = require("tiamat/daemon.js");
Config = require("tiamat/config.js").ConfigLoader;
<commit_msg>make this file useful<commit_after>module.exports = {
  server: require("tiamat/server.js").Tiamat,
  daemon: require("tiamat/daemon.js"),
  config: require("tiamat/config_loader.js").ConfigLoader
}
<|endoftext|>


<commit_before>'use strict';

var request = require('request');

// Tradable assets from https://api.kraken.com/0/public/AssetPairs
var assetNames = {
    'EUR': 'XXBTZEUR',
    'USD': 'XXBTZUSD'
};
var KrakenAPIURL = 'https://api.kraken.com/0/public/Ticker';

var KrakenTicker = function () {

};

KrakenTicker.factory = function factory() {
    return new KrakenTicker();
};

KrakenTicker.prototype.ticker = function ticker(currencies, callback) {
    if (currencies.length === 0) {
	return callback(new Error('No currency specified.'));
    };

    var queryArray = [];
    for (var i = 0; i < currencies.length; i++) {
	var currency = currencies[i];
	if (currency in assetNames) {
	    queryArray.push(assetNames[currency]);
	} else {
	    return callback(new Error('Unsupported currencies.'));
	}
    }

    var queryOptions = {
	url: KrakenAPIURL,
	headers: {
            'User-Agent': 'lamassu-kraken'
	},
	qs: {
	    'pair': queryArray.join(",")
	}
    };

    request(queryOptions, function(error, response, body) {
	if (error) {
	    return callback(error);
	}
	try {
	    var responseJSON = JSON.parse(body);
	} catch(e) {
	    return callback(new Error('Can\'t parse response data.'));
	}
	if ('result' in responseJSON) {
	    var result = responseJSON['result'];
	    var tickerResponse = {}
	    for (var i = 0; i < currencies.length; i++) {
		var currency = currencies[i];
		var assetName = assetNames[currency];
		if (assetName in result) {
		    // add the "ask" price of the given currency to the ticker data
		    tickerResponse[currency] = {'currency': currency, 'rate': result[assetName].a[0]}
		} else {
		    return callback(new Error('Wrong response data.'));
		}
	    }
	    return callback(null, tickerResponse);
	} else {  // result object not in response
	    return callback(new Error('Can\'t find required parts in response data.'));
	}
    });
};

module.exports = KrakenTicker;
<commit_msg>ticker: move over to the kraken API lib, closes #1<commit_after>'use strict';

// Tradable assets from https://api.kraken.com/0/public/AssetPairs
var assetNames = {
    'EUR': 'XXBTZEUR',
    'USD': 'XXBTZUSD'
};

var KrakenClient = require('kraken-api');

var KrakenTicker = function () {
    this.client = new KrakenClient();
};

KrakenTicker.factory = function factory() {
    return new KrakenTicker();
};

KrakenTicker.prototype.ticker = function ticker(currencies, callback) {

    if (currencies.length === 0) {
	return callback(new Error('No currency specified.'));
    };

    var queryArray = [];
    for (var i = 0; i < currencies.length; i++) {
	var currency = currencies[i];
	if (currency in assetNames) {
	    queryArray.push(assetNames[currency]);
	} else {
	    return callback(new Error('Unsupported currencies.'));
	}
    }
    var query= { 'pair': queryArray.join(",") };

    this.client.api('Ticker', query, function(error, response) {
	if (error) {
	    return callback(error);
	} else {
	    if ('result' in response) {
		var result = response['result'];
		var tickerResponse = {}
		for (var i = 0; i < currencies.length; i++) {
		    var currency = currencies[i];
		    var assetName = assetNames[currency];
		    if (assetName in result) {
			// add the "ask" price of the given currency to the ticker data
			tickerResponse[currency] = {'currency': currency, 'rate': result[assetName].a[0]}
		    } else {
			return callback(new Error('Wrong response data.'));
		    }
		}
		return callback(null, tickerResponse);
	    } else {  // result object not in response
		return callback(new Error('Can\'t find required parts in response data.'));
	    }
	}
    });
};

module.exports = KrakenTicker;
<|endoftext|>


<commit_before>/*
 * CometJS / ticker.js
 * copyright (c) 2014 Susisu
 */

 "use strict";

function end () {
    module.exports = Object.freeze({
        "Ticker"     : Ticker,
        "TickerEvent": TickerEvent
    });
}

var ev = require("electronvolt");

function Ticker(interval) {
    ev.EventDispatcher.call(this);
    this.interval = interval;
}

Ticker.prototype = Object.create(ev.EventDispatcher.prototype, {
    "constructor": {
        "value"       : Ticker,
        "writable"    : true,
        "configurable": true
    }
});

Object.defineProperties(Ticker.prototype, {
    "start": {
        "value": function () {
            throw Error("not implemented");
        }
    },
    "stop": {
        "value": function () {
            throw Error("not implemented");
        }
    }
});

function TickerEvent(type, bubbles, cancelable) {
    ev.Event.call(this, type, bubbles, cancelable);
}

TickerEvent.prototype = Object.create(ev.Event.prototype, {
    "constructor": {
        "value"       : TickerEvent,
        "writable"    : true,
        "configurable": true
    }
});

Object.defineProperties(TickerEvent, {
    "TICK": {
        "value": "tick"
    }
});

end();
<commit_msg>Fix missing 'new'<commit_after>/*
 * CometJS / ticker.js
 * copyright (c) 2014 Susisu
 */

 "use strict";

function end () {
    module.exports = Object.freeze({
        "Ticker"     : Ticker,
        "TickerEvent": TickerEvent
    });
}

var ev = require("electronvolt");

function Ticker(interval) {
    ev.EventDispatcher.call(this);
    this.interval = interval;
}

Ticker.prototype = Object.create(ev.EventDispatcher.prototype, {
    "constructor": {
        "value"       : Ticker,
        "writable"    : true,
        "configurable": true
    }
});

Object.defineProperties(Ticker.prototype, {
    "start": {
        "value": function () {
            throw new Error("not implemented");
        }
    },
    "stop": {
        "value": function () {
            throw new Error("not implemented");
        }
    }
});

function TickerEvent(type, bubbles, cancelable) {
    ev.Event.call(this, type, bubbles, cancelable);
}

TickerEvent.prototype = Object.create(ev.Event.prototype, {
    "constructor": {
        "value"       : TickerEvent,
        "writable"    : true,
        "configurable": true
    }
});

Object.defineProperties(TickerEvent, {
    "TICK": {
        "value": "tick"
    }
});

end();
<|endoftext|>


<commit_before>/*
 ******************************************************************************
 * @file lib/tinker.js
 * @company Spark ( https://www.spark.io/ )
 * @source https://github.com/spark/sparkjs
 *
 * @Contributors
 *    David Middlecamp (david@spark.io)
 *    Edgar Silva (https://github.com/edgarsilva)
 *    Javier Cervantes (https://github.com/solojavier)
 *
 * @brief Basic API wrapper module
 ******************************************************************************
  Copyright (c) 2014 Spark Labs, Inc.  All rights reserved.

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation, either
  version 3 of the License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this program; if not, see <http://www.gnu.org/licenses/>.
  ******************************************************************************
 */

/*jslint node: true */
'use strict';

/**
 * Creates a new Tinker obj
 * @constructor {Tinker}
 */
var Tinker = function(coreId, spark) {
  this.coreId = coreId;
  this.spark = spark;
};

Tinker.prototype.digitalWrite = function(pin, param, callback) {
  this.spark.callFunction(this.coreId, 'digitalWrite', pin + ':' + param, callback);
};

Tinker.prototype.digitalRead = function(pin, param, callback) {
  this.spark.callFunction(this.coreId, 'analogRead', pin + ':' + param, callback);
};

Tinker.prototype.analogRead = function(pin, param, callback) {
  this.spark.callFunction(this.coreId, 'analogRead', pin + ':' + param, callback);
};

Tinker.prototype.analogWrite = function(pin, param, callback) {
  this.spark.callFunction(this.coreId, 'analogWrite', pin + ':' + param, callback);
};

Tinker.prototype.flash = function(callback) {
  this.spark.flashTinker(this.coreId, callback);
};

/*
// Flash a custom binary to the spark core
Tinker.prototype.flash = function(callback) {
  this.spark.flashCore(this.coreId, './firmware/Tinker', callback);
};
*/

module.exports = Tinker;
<commit_msg>Fix plugin function calls and added flash function.<commit_after>/*
 ******************************************************************************
 * @file lib/tinker.js
 * @company Spark ( https://www.spark.io/ )
 * @source https://github.com/spark/sparkjs
 *
 * @Contributors
 *    David Middlecamp (david@spark.io)
 *    Edgar Silva (https://github.com/edgarsilva)
 *    Javier Cervantes (https://github.com/solojavier)
 *
 * @brief Basic API wrapper module
 ******************************************************************************
  Copyright (c) 2014 Spark Labs, Inc.  All rights reserved.

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation, either
  version 3 of the License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this program; if not, see <http://www.gnu.org/licenses/>.
  ******************************************************************************
 */

/*jslint node: true */
'use strict';

/**
 * Creates a new Tinker obj
 * @constructor {Tinker}
 */
var Tinker = function(coreId, spark) {
  this.coreId = coreId;
  this.spark = spark;
};

Tinker.prototype.digitalWrite = function(pin, value, callback) {
  console.log('pin:', pin);
  console.log('value:', value);
  console.log('param:', pin + ',' + value);
  this.spark.callFunction(this.coreId, 'digitalwrite', pin + ',' + value, callback);
};

Tinker.prototype.digitalRead = function(pin, value, callback) {
  this.spark.callFunction(this.coreId, 'digitalread', pin + ',' + value, callback);
};

Tinker.prototype.analogRead = function(pin, value, callback) {
  this.spark.callFunction(this.coreId, 'analogread', pin + ',' + value, callback);
};

Tinker.prototype.analogWrite = function(pin, value, callback) {
  this.spark.callFunction(this.coreId, 'analogwrite', pin + ',' + value, callback);
};

Tinker.prototype.flash = function(callback) {
  this.spark.flashTinker(this.coreId, callback);
};

/*
// Flash a custom binary to the spark core
Tinker.prototype.flash = function(callback) {
  this.spark.flashCore(this.coreId, './firmware/Tinker', callback);
};
*/

module.exports = Tinker;
<|endoftext|>


<commit_before>//
//  Module: Tweets
//  ==============
//
//  Convenience methods for Tweets actions directly from [Twitter's API 1.1](https://dev.twitter.com/docs/api/1.1#111).
//
//  + [Retweets](#retweets)
//
var Tweets,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

module.exports = Tweets = (function() {

  //
  //
  //  Constructor
  //  -----------
  //
  function Tweets(uri, opts) {
    this.uri = uri;
    this.opts = opts;

    var tt = require('twitter-rest-lite');

    this.api = tt.API(this.opts);

    /* bindings */
    this.retweets = __bind(this.retweets, this);
    this.show = __bind(this.show, this);
    this.destroy = __bind(this.destroy, this);
    this.update = __bind(this.update, this);
    this.retweet = __bind(this.retweet, this);
    this.updateWithMedia = __bind(this.updateWithMedia, this);
    this.oembed = __bind(this.oembed, this);
    this.retweeters = __bind(this.retweeters, this);
  };

  //
  //
  //  Public: returns a collection of the 100 most recent retweets on specified tweet
  //  ----------------------------------------------------
  //
  //  ### Arguments
  //
  //  + **id**: Status ID
  //  + **params**: Object with params:
  //    - **count**
  //    - **trim_user**
  //  + **callback**: Callback Function
  //
  //### Returns
  //  A callback with an Error object as first parameter if there was any
  //  (otherwise just `null`) and an Array with tweets as second parameter.
  //
  Tweets.prototype.retweets = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.retweets() requires an ID to be provided'
      ));
    }

    self.api.get('/statuses/retweets/' + id + '.json', params, callback);
  };

  //
  //
  //  Public: returns a single tweet
  //  ------------------------------
  //
  //  ### Arguments
  //
  //  id                  - Status ID
  //  params              - Object with params:
  //  - trim_user
  //  - include_my_retweet
  //  - include_entities
  //  callback            - Callback Function
  //
  //### Returns
  //  Returns a callback with an Error object as first parameter if there was any
  //  (otherwise just `null`) and a Tweet object as second parameter.
  //
  Tweets.prototype.show = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.show() requires and ID to be provided'
      ));
    }

    self.api.get('/statuses/show/' + id + '.json', params, callback);
  };

  //
  //
  //  Public: destroy a single tweet
  //  ------------------------------
  //
  //  This only works with `oauth_token` from the same user.
  //
  //  id                  - Status ID
  //  params              - Object with params:
  //  - trim_user
  //  callback            - Callback Function
  //
  //  Returns a callback with an Error object as first parameter if there was any
  //  (otherwise just `null`) and a Tweet object of the removed status as second
  //  parameter.
  //
  Tweets.prototype.destroy = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.destroy() requires an ID to be provided'
      ));
    }

    self.api.post('/statuses/destroy/' + id + '.json', params, callback);
  };

  //
  //
  //  Public: creates a tweet
  //  -----------------------
  //
  //  This only works with `oauth_token` from the same user.
  //
  //  params              - Object with params:
  //  - status: [Required]
  //  callback            - Callback Function
  //
  Tweets.prototype.update = function(params, callback) {
    var self = this;

    if ((params == null) || (params.status == null) || (params.status === '')) {
      return callback(new Error(
        'Twitter:Tweets.update() requires params.status to be defined'
      ));
    }

    if (params.status.length > 140) {
      return callback(new Error(
        'Twitter:Tweets.update(): status is longer than 140 characters'
      ));
    }

    self.api.post('/statuses/update.json', params, callback);
  };

  //
  //
  //  Public: retweets an status
  //  --------------------------
  //
  //  id                    - ID of the status to be retweeted
  //  params                - Object with params:
  //  callback              - Callback Function
  //
  Tweets.prototype.retweet = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.retweet() requires an ID to be provided'
      ));
    }

    self.api.post('/statuses/retweet/' + id + '.json', params, callback);
  };

  //
  //
  //  TODO: Public: update with media
  //  -------------------------------
  //
  Tweets.prototype.updateWithMedia = function() {
    var self = this;

    /* FIXME: IMPLEMENT! */
  };

  //
  //
  //  Public: returns HTML for embedding tweets in websites
  //  -----------------------------------------------------
  //
  //  params                  - Object with params:
  //  id: [Required if `url` is not given]
  //  url: [Required if `id` is not given]
  //  callback                - Callback Function
  //
  Tweets.prototype.oembed = function(params, callback) {
    var self = this;

    if ((params.id == null) && (params.url == null)) {
      return callback(new Error(
        'Twitter:Tweets.oembed() requires either id or url on the params'
      ));
    }

    self.api.get('/statuses/oembed.json', params, callback);
  };

  //
  //
  //  Public: get a list of retweeters by ID
  //  --------------------------------------
  //
  //  params                    - Object with params:
  //  id
  //  callback                  - Callback Function
  //
  Tweets.prototype.retweeters = function(params, callback) {
    var self = this;

    if (params.id == null) {
      return callback(new Error(
        'Twitter:Tweets.retweeters() requires an id on the params'
      ));
    }

    self.api.get('/statuses/retweeters/ids.json', params, callback);
  };

  return Tweets;
})();
<commit_msg>lib/tweets: better docs<commit_after>'use strict';
//
// Module: Tweets
// ==============
//
// Convenience methods for Tweets actions directly from [Twitter's API 1.1](https://dev.twitter.com/docs/api/1.1#111).
//
// + [Show](#show)
// + [Destroy](#destroy)
// + [Update](#update)
// + [retweet](#retweet)
// + [Update with Media](#updateWithMedia)
// + [O Embed](#oembed)
// + [Retweeters](#retweeters)
//
// #### Code
var Tweets;

module.exports = Tweets = (function() {

  //
  //
  // Constructor
  // -----------
  //
  // #### Code
  function Tweets(uri, opts) {
    this.uri = uri;
    this.opts = opts;

    var tt = require('twitter-rest-lite');

    this.api = tt.API(this.opts);
  }

  //
  //
  // Public: returns a collection of the 100 most recent retweets on specified tweet
  // ----------------------------------------------------
  //
  // #### Parameters
  //
  // + **id**: Status ID
  // + **params**: Object with params:
  //   - **count**
  //   - **trim_user**
  // + **callback**: Callback Function
  //
  // #### Returns
  //
  // A callback with an Error object as first parameter if there was any
  // (otherwise just `null`) and an Array with tweets as second parameter.
  //
  // #### Code
  Tweets.prototype.retweets = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.retweets() requires an ID to be provided'
      ));
    }

    self.api.get('/statuses/retweets/' + id + '.json', params, callback);
  };

  //
  //
  // Public: returns a single tweet
  // ------------------------------
  //
  // #### Parameters
  //
  // + id                  - Status ID
  // + params              - Object with params:
  //   - trim_user
  //   - include_my_retweet
  //   - include_entities
  // + callback            - Callback Function
  //
  // #### Returns
  // Returns a callback with an Error object as first parameter if there was any
  // (otherwise just `null`) and a Tweet object as second parameter.
  //
  // #### Code
  Tweets.prototype.show = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.show() requires and ID to be provided'
      ));
    }

    self.api.get('/statuses/show/' + id + '.json', params, callback);
  };

  //
  //
  // Public: destroy a single tweet
  // ------------------------------
  //
  // This only works with `oauth_token` from the same user.
  //
  // #### Parameters
  //
  // + id                  - Status ID
  // + params              - Object with params:
  //   - trim_user
  // + callback            - Callback Function
  //
  // #### Returns
  //
  // Returns a callback with an Error object as first parameter if there was any
  // (otherwise just `null`) and a Tweet object of the removed status as second
  // parameter.
  //
  // #### Code
  Tweets.prototype.destroy = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.destroy() requires an ID to be provided'
      ));
    }

    self.api.post('/statuses/destroy/' + id + '.json', params, callback);
  };

  //
  //
  // Public: creates a tweet
  // -----------------------
  //
  // This only works with `oauth_token` from the same user.
  //
  // #### Parameters
  //
  // + params              - Object with params:
  //   - status: [Required]
  // + callback            - Callback Function
  //
  // #### Code
  Tweets.prototype.update = function(params, callback) {
    var self = this;

    if ((params == null) || (params.status == null) || (params.status === '')) {
      return callback(new Error(
        'Twitter:Tweets.update() requires params.status to be defined'
      ));
    }

    if (params.status.length > 140) {
      return callback(new Error(
        'Twitter:Tweets.update(): status is longer than 140 characters'
      ));
    }

    self.api.post('/statuses/update.json', params, callback);
  };

  //
  //
  // Public: retweets an status
  // --------------------------
  //
  // #### Parameters
  //
  // + id                    - ID of the status to be retweeted
  // + params                - Object with params:
  // + callback              - Callback Function
  //
  // #### Code
  Tweets.prototype.retweet = function(id, params, callback) {
    var self = this;

    if (id == null) {
      return callback(new Error(
        'Twitter:Tweets.retweet() requires an ID to be provided'
      ));
    }

    self.api.post('/statuses/retweet/' + id + '.json', params, callback);
  };

  //
  //
  // TODO: Public: update with media
  // -------------------------------
  //
  // #### Code
  Tweets.prototype.updateWithMedia = function() {
    var self = this;

    /* FIXME: IMPLEMENT! */
  };

  //
  //
  // Public: returns HTML for embedding tweets in websites
  // -----------------------------------------------------
  //
  // + `params`                  - Object with params:
  //   - `id`: [Required if `url` is not given]
  //   - `url`: [Required if `id` is not given]
  // + `callback`                - Callback Function
  //
  // #### Code
  Tweets.prototype.oembed = function(params, callback) {
    var self = this;

    if ((params.id == null) && (params.url == null)) {
      return callback(new Error(
        'Twitter:Tweets.oembed() requires either id or url on the params'
      ));
    }

    self.api.get('/statuses/oembed.json', params, callback);
  };

  //
  //
  // Public: get a list of retweeters by ID
  // --------------------------------------
  //
  // + `params`                    - Object with params:
  //   - `id`
  // + `callback`                  - Callback Function
  //
  // #### Code
  Tweets.prototype.retweeters = function(params, callback) {
    var self = this;

    if (params.id == null) {
      return callback(new Error(
        'Twitter:Tweets.retweeters() requires an id on the params'
      ));
    }

    self.api.get('/statuses/retweeters/ids.json', params, callback);
  };

  return Tweets;
})();
<|endoftext|>