<commit_before>// CLABE Validator
// Mocha Specifications Cases
//
// Run:
//    $ cd clabe-validator
//    $ npm test

// Imports
const assert = require('assert').strict;

// Setup
const clabePath = process.env.specMode === 'minified' ? './dist/clabe.min.js' : './dist/clabe.js';
const clabe =     require(clabePath);

// Specification suite
describe(require('path').basename(__filename) + ': ' + clabePath, () => {

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Library version number', () => {

   it('follows semantic version formatting', () => {
      const semVerPattern = /\d+[.]\d+[.]\d+/;
      const actual =   { version: clabe.version, valid: semVerPattern.test(clabe.version) };
      const expected = { version: clabe.version, valid: true };
      assert.deepEqual(actual, expected);
      });

   });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('List of CLABE banks', () => {

   const bankCodes = Object.keys(clabe.banksMap);

   it('contains only uppercase bank tags', () => {
      const checkTagCase = (bankCode) => {  //example: 21: { tag: 'HSBC', name: 'HSBC México, S.A.' },
         const bank = clabe.banksMap[bankCode];
         const actual =   { code: bankCode, tag: bank.tag,               name: bank.name };
         const expected = { code: bankCode, tag: bank.tag.toUpperCase(), name: bank.name };
         assert.deepEqual(actual, expected);
         };
      bankCodes.forEach(checkTagCase);
      });

   it('contains no duplicate tags', () => {
      const allowedDuplicateTags = ['SKANDIA', 'STP'];  //list of permitted exceptions
      const tags = bankCodes.map(bankCode => clabe.banksMap[bankCode].tag);
      const duplicateTags = tags.sort().filter((v, i, a) => i > 0 && v === a[i - 1]);
      const problemTags = duplicateTags.filter(tag => !allowedDuplicateTags.includes(tag));
      const makeCodeBankPair = code => [code, clabe.banksMap[code]];
      const tagIsDuplicate = pair => problemTags.includes(pair[1].tag);
      const problemBanks = bankCodes.map(makeCodeBankPair).filter(tagIsDuplicate);
      const actual =   { duplicates: duplicateTags,        tags: problemTags, banks: problemBanks };
      const expected = { duplicates: allowedDuplicateTags, tags: [],          banks: [] };
      assert.deepEqual(actual, expected);
      });

   it('contains the correct code to look up a bank tag', () => {
      const dataSet = [
         { input: '002', expected: 'BANAMEX' },
         { input: '640', expected: 'JP MORGAN C.B.' },
         { input: '652', expected: 'ASEA' }
         ];
      const evalData = (data) => {
         const actual =   { code: data.input, tag: clabe.banksMap[parseInt(data.input)].tag };
         const expected = { code: data.input, tag: data.expected };
         assert.deepEqual(actual, expected);
         };
      dataSet.forEach(evalData);
      });

   it('contains the correct code to look up a bank name', () => {
      const dataSet = [
         { input: '002', expected: 'Banco Nacional de México, S.A.' },
         { input: '640', expected: 'J.P. Morgan Casa de Bolsa, S.A. de C.V.' },
         { input: '652', expected: 'Solución Asea, S.A. de C.V., Sociedad Financiera Popular' }
         ];
      const evalData = (data) => {
         const actual =   { code: data.input, name: clabe.banksMap[parseInt(data.input)].name };
         const expected = { code: data.input, name: data.expected };
         assert.deepEqual(actual, expected);
         };
      dataSet.forEach(evalData);
      });

   it('has a default "N/A" bank name and tag for code 999', () => {
      const actual =   { code: 999, tag: clabe.banksMap[999].tag, name: clabe.banksMap[999].name };
      const expected = { code: 999, tag: 'N/A',                   name: 'N/A' };
      assert.deepEqual(actual, expected);
      });

   });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('List of CLABE cities', () => {
   const cityNamesMap = {};  //{ Aguascalientes: 10, Calvillo: 12, ... }
   const addCity = (city) => cityNamesMap[city[1]] = city[0];
   clabe.cities.forEach(addCity);

   it('is in numerical order', () => {
      const checkOrder = (city, i) => {  //example city: [10, 'Aguascalientes']
         const priorCode = i > 0 ? clabe.cities[i - 1][0] : 0;
         const ordered = city[0] >= priorCode;
         const actual =   { city: city[1], code: city[0], prior: priorCode, ordered: ordered };
         const expected = { city: city[1], code: city[0], prior: priorCode, ordered: true };
         assert.deepEqual(actual, expected);
         };
      clabe.cities.forEach(checkOrder);
      });

   it('contains the correct code for a city', () => {
      const dataSet = [
         { input: 'Tecate',              expected: '027' },
         { input: 'La Mesa',             expected: '028' },
         { input: 'Rosarito',            expected: '028' },
         { input: 'Jerez de G. Salinas', expected: '936' }
         ];
      const evalData = (data) => {
         const actual =   { city: data.input, code: cityNamesMap[data.input] };
         const expected = { city: data.input, code: parseInt(data.expected) };
         assert.deepEqual(actual, expected);
         };
      dataSet.forEach(evalData);
      });

   it('has no duplicate city names', () => {
      const checkForDuplicate = (city) => {
         const code = cityNamesMap[city[1]];
         const unique = city[0] === code || city[1] === 'N/A';
         const actual =   { city: city[1], code1: city[0], code2: code, unique: unique };
         const expected = { city: city[1], code1: city[0], code2: code, unique: true };
         assert.deepEqual(actual, expected);
         };
      clabe.cities.forEach(checkForDuplicate);
      });

   });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('CLABE validator', () => {

   it('rejects an invalid CLABE number', () => {
      const dataSet = [
         { input: '12345678901234567',  expected: ['invalid-length',     'Must be exactly 18 digits long'] },
         { input: '00000000000000000a', expected: ['invalid-characters', 'Must be only numeric digits (no letters)'] },
         { input: '002010077777777779', expected: ['invalid-checksum',   'Invalid checksum, last digit should be: 1'] },
         { input: '000000000000000000', expected: ['invalid-bank',       'Invalid bank code: 000'] },
         { input: '002115016003269411', expected: ['invalid-city',       'Invalid city code: 115'] }
         ];
      const evalData = (data) => {
         const result = clabe.validate(data.input);
         const actual =   { clabe: data.input, ok: result.ok, error: result.error,     message: result.message };
         const expected = { clabe: data.input, ok: false,     error: data.expected[0], message: data.expected[1] };
         assert.deepEqual(actual, expected);
         };
      dataSet.forEach(evalData);
      });

   it('accepts a valid CLABE number', () => {
      const dataSet = [
         '002010077777777771',
         '032180000118359719',
         '014027000005555558',
         '014028000005555557'
         ];
      const evalData = (data) => {
         const result = clabe.validate(data);
         const actual =   { clabe: data, ok: result.ok, error: result.error, msg: result.message };
         const expected = { clabe: data, ok: true,      error: null,         msg: 'Valid'};
         assert.deepEqual(actual, expected);
         };
      dataSet.forEach(evalData);
      });

   it('extracts the bank tag, bank name, and city', () => {
      const clabeCheck = clabe.validate('002010077777777771');
      const actual =   {
         tag:  clabeCheck.tag,
         bank: clabeCheck.bank,
         city: clabeCheck.city
         };
      const expected = {
         tag:  'BANAMEX',
         bank: 'Banco Nacional de México, S.A.',
         city: 'Aguascalientes'
         };
      assert.deepEqual(actual, expected);
      });

   it('extracts the bank code, city code, and account number', () => {
      const clabeCheck = clabe.validate('002010077777777771');
      const actual =   {
         bank:    clabeCheck.code.bank,
         city:    clabeCheck.code.city,
         account: clabeCheck.account
         };
      const expected = {
         bank:    '002',
         city:    '010',
         account: '07777777777'
         };
      assert.deepEqual(actual, expected);
      });

   });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('CLABE calculator', () => {

   it('builds the correct CLABE number', () => {
      const dataSet = [
         { input: { bank:  2, city:  10, acct: 7777777777 }, expected: '002010077777777771' },
         { input: { bank: 32, city: 180, acct:   11835971 }, expected: '032180000118359719' },
         { input: { bank: 14, city:  27, acct:     555555 }, expected: '014027000005555558' },
         { input: { bank: 14, city:  28, acct:     555555 }, expected: '014028000005555557' }
         ];
      const evalData = (data) => {
         const clabeNum = clabe.calculate(data.input.bank, data.input.city, data.input.acct);
         const actual =   { details: data.input, clabe: clabeNum };
         const expected = { details: data.input, clabe: data.expected };
         assert.deepEqual(actual, expected);
         };
      dataSet.forEach(evalData);
      });

   });

////////////////////////////////////////////////////////////////////////////////////////////////////
});
<commit_msg>Test case added for checksum = 0<commit_after>// CLABE Validator
// Mocha Specifications Cases
//
// Run:
//    $ cd clabe-validator
//    $ npm test

// Imports
const assert = require('assert').strict;

// Setup
const clabePath = process.env.specMode === 'minified' ? './dist/clabe.min.js' : './dist/clabe.js';
const clabe =     require(clabePath);

// Specification suite
describe(require('path').basename(__filename) + ': ' + clabePath, () => {

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Library version number', () => {

   it('follows semantic version formatting', () => {
      const semVerPattern = /\d+[.]\d+[.]\d+/;
      const actual =   { version: clabe.version, valid: semVerPattern.test(clabe.version) };
      const expected = { version: clabe.version, valid: true };
      assert.deepEqual(actual, expected);
      });

   });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('List of CLABE banks', () => {

   const bankCodes = Object.keys(clabe.banksMap);

   it('contains only uppercase bank tags', () => {
      const checkTagCase = (bankCode) => {  //example: 21: { tag: 'HSBC', name: 'HSBC México, S.A.' },
         const bank = clabe.banksMap[bankCode];
         const actual =   { code: bankCode, tag: bank.tag,               name: bank.name };
         const expected = { code: bankCode, tag: bank.tag.toUpperCase(), name: bank.name };
         assert.deepEqual(actual, expected);
         };
      bankCodes.forEach(checkTagCase);
      });

   it('contains no duplicate tags', () => {
      const allowedDuplicateTags = ['SKANDIA', 'STP'];  //list of permitted exceptions
      const tags = bankCodes.map(bankCode => clabe.banksMap[bankCode].tag);
      const duplicateTags = tags.sort().filter((v, i, a) => i > 0 && v === a[i - 1]);
      const problemTags = duplicateTags.filter(tag => !allowedDuplicateTags.includes(tag));
      const makeCodeBankPair = code => [code, clabe.banksMap[code]];
      const tagIsDuplicate = pair => problemTags.includes(pair[1].tag);
      const problemBanks = bankCodes.map(makeCodeBankPair).filter(tagIsDuplicate);
      const actual =   { duplicates: duplicateTags,        tags: problemTags, banks: problemBanks };
      const expected = { duplicates: allowedDuplicateTags, tags: [],          banks: [] };
      assert.deepEqual(actual, expected);
      });

   it('contains the correct code to look up a bank tag', () => {
      const dataSet = [
         { input: '002', expected: 'BANAMEX' },
         { input: '640', expected: 'JP MORGAN C.B.' },
         { input: '652', expected: 'ASEA' }
         ];
      const evalData = (data) => {
         const actual =   { code: data.input, tag: clabe.banksMap[parseInt(data.input)].tag };
         const expected = { code: data.input, tag: data.expected };
         assert.deepEqual(actual, expected);
         };
      dataSet.forEach(evalData);
      });

   it('contains the correct code to look up a bank name', () => {
      const dataSet = [
         { input: '002', expected: 'Banco Nacional de México, S.A.' },
         { input: '640', expected: 'J.P. Morgan Casa de Bolsa, S.A. de C.V.' },
         { input: '652', expected: 'Solución Asea, S.A. de C.V., Sociedad Financiera Popular' }
         ];
      const evalData = (data) => {
         const actual =   { code: data.input, name: clabe.banksMap[parseInt(data.input)].name };
         const expected = { code: data.input, name: data.expected };
         assert.deepEqual(actual, expected);
         };
      dataSet.forEach(evalData);
      });

   it('has a default "N/A" bank name and tag for code 999', () => {
      const actual =   { code: 999, tag: clabe.banksMap[999].tag, name: clabe.banksMap[999].name };
      const expected = { code: 999, tag: 'N/A',                   name: 'N/A' };
      assert.deepEqual(actual, expected);
      });

   });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('List of CLABE cities', () => {
   const cityNamesMap = {};  //{ Aguascalientes: 10, Calvillo: 12, ... }
   const addCity = (city) => cityNamesMap[city[1]] = city[0];
   clabe.cities.forEach(addCity);

   it('is in numerical order', () => {
      const checkOrder = (city, i) => {  //example city: [10, 'Aguascalientes']
         const priorCode = i > 0 ? clabe.cities[i - 1][0] : 0;
         const ordered = city[0] >= priorCode;
         const actual =   { city: city[1], code: city[0], prior: priorCode, ordered: ordered };
         const expected = { city: city[1], code: city[0], prior: priorCode, ordered: true };
         assert.deepEqual(actual, expected);
         };
      clabe.cities.forEach(checkOrder);
      });

   it('contains the correct code for a city', () => {
      const dataSet = [
         { input: 'Tecate',              expected: '027' },
         { input: 'La Mesa',             expected: '028' },
         { input: 'Rosarito',            expected: '028' },
         { input: 'Jerez de G. Salinas', expected: '936' }
         ];
      const evalData = (data) => {
         const actual =   { city: data.input, code: cityNamesMap[data.input] };
         const expected = { city: data.input, code: parseInt(data.expected) };
         assert.deepEqual(actual, expected);
         };
      dataSet.forEach(evalData);
      });

   it('has no duplicate city names', () => {
      const checkForDuplicate = (city) => {
         const code = cityNamesMap[city[1]];
         const unique = city[0] === code || city[1] === 'N/A';
         const actual =   { city: city[1], code1: city[0], code2: code, unique: unique };
         const expected = { city: city[1], code1: city[0], code2: code, unique: true };
         assert.deepEqual(actual, expected);
         };
      clabe.cities.forEach(checkForDuplicate);
      });

   });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('CLABE validator', () => {

   it('rejects an invalid CLABE number', () => {
      const dataSet = [
         { input: '12345678901234567',  expected: ['invalid-length',     'Must be exactly 18 digits long'] },
         { input: '00000000000000000a', expected: ['invalid-characters', 'Must be only numeric digits (no letters)'] },
         { input: '002010077777777779', expected: ['invalid-checksum',   'Invalid checksum, last digit should be: 1'] },
         { input: '000000000000000000', expected: ['invalid-bank',       'Invalid bank code: 000'] },
         { input: '002115016003269411', expected: ['invalid-city',       'Invalid city code: 115'] }
         ];
      const evalData = (data) => {
         const result = clabe.validate(data.input);
         const actual =   { clabe: data.input, ok: result.ok, error: result.error,     message: result.message };
         const expected = { clabe: data.input, ok: false,     error: data.expected[0], message: data.expected[1] };
         assert.deepEqual(actual, expected);
         };
      dataSet.forEach(evalData);
      });

   it('accepts a valid CLABE number', () => {
      const dataSet = [
         '002010077777777771',
         '032180000118359719',
         '014027000005555558',
         '014028000005555557'
         ];
      const evalData = (data) => {
         const result = clabe.validate(data);
         const actual =   { clabe: data, ok: result.ok, error: result.error, msg: result.message };
         const expected = { clabe: data, ok: true,      error: null,         msg: 'Valid'};
         assert.deepEqual(actual, expected);
         };
      dataSet.forEach(evalData);
      });

   it('accepts a valid CLABE number that has a checksum of 0', () => {
      const data = '002010777777777770';  //case where the last compute checksum modulus rolls over
      const result = clabe.validate(data);
      const actual =   { clabe: data, ok: result.ok, error: result.error, msg: result.message };
      const expected = { clabe: data, ok: true,      error: null,         msg: 'Valid'};
      assert.deepEqual(actual, expected);
      });

   it('extracts the bank tag, bank name, and city', () => {
      const clabeCheck = clabe.validate('002010077777777771');
      const actual =   {
         tag:  clabeCheck.tag,
         bank: clabeCheck.bank,
         city: clabeCheck.city
         };
      const expected = {
         tag:  'BANAMEX',
         bank: 'Banco Nacional de México, S.A.',
         city: 'Aguascalientes'
         };
      assert.deepEqual(actual, expected);
      });

   it('extracts the bank code, city code, and account number', () => {
      const clabeCheck = clabe.validate('002010077777777771');
      const actual =   {
         bank:    clabeCheck.code.bank,
         city:    clabeCheck.code.city,
         account: clabeCheck.account
         };
      const expected = {
         bank:    '002',
         city:    '010',
         account: '07777777777'
         };
      assert.deepEqual(actual, expected);
      });

   });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('CLABE calculator', () => {

   it('builds the correct CLABE number', () => {
      const dataSet = [
         { input: { bank:  2, city:  10, acct: 7777777777 }, expected: '002010077777777771' },
         { input: { bank: 32, city: 180, acct:   11835971 }, expected: '032180000118359719' },
         { input: { bank: 14, city:  27, acct:     555555 }, expected: '014027000005555558' },
         { input: { bank: 14, city:  28, acct:     555555 }, expected: '014028000005555557' }
         ];
      const evalData = (data) => {
         const clabeNum = clabe.calculate(data.input.bank, data.input.city, data.input.acct);
         const actual =   { details: data.input, clabe: clabeNum };
         const expected = { details: data.input, clabe: data.expected };
         assert.deepEqual(actual, expected);
         };
      dataSet.forEach(evalData);
      });

   });

////////////////////////////////////////////////////////////////////////////////////////////////////
});
<|endoftext|>


<commit_before>// dna.js
// Mocha Specification Cases
//
// Run specs:
//    $ cd dna.js
//    $ npm test

const url = 'http://example.com?a=one&b=two';
const html = `
<!doctype html>
<html lang=en>
    <head>
        <meta charset=utf-8>
        <title>Specification Runner</title>
    </head>
    <body>
    </body>
</html>
`;

const assert =    require('assert');
const { JSDOM } = require('jsdom');
const window =    new JSDOM(html, { url: url }).window;
const $ =         require('jquery')(window);
const dna =       require('./dna.js')(window, $);

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.array.fromMap()', () => {

   it('converts a map into an array of maps', () => {
      var dataSet = [
         {
            inputMap: { a: { word: 'Ant' }, b: { word: 'Bat' } },
            expected: [{ word: 'Ant', code: 'a' }, { word: 'Bat', code: 'b' }]
         },
         {
            inputMap: { x0: 100, x1: 101, x2: 102 },
            inputKey: 'key',
            expected: [{ value: 100, key: 'x0' }, { value: 101, key: 'x1' }, { value: 102, key: 'x2' }]
         }];
      function evalData(data) {
         var output = dna.array.fromMap(data.inputMap, data.inputKey);
         assert.deepEqual(output, data.expected);
         }
      dataSet.forEach(evalData);
      });

   });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.util.toCamel()', () => {

   it('converts a kebab (dashes) name to camelCase', () => {
      var dataSet = [
         { input: 'ready-set-go', expected: 'readySetGo' },
         { input: 'dna',          expected: 'dna' }
         ];
      function evalData(data) {
         assert.equal(dna.util.toCamel(data.input), data.expected);
         }
      dataSet.forEach(evalData);
      });

   });
<commit_msg>added new unit test printf<commit_after>// dna.js
// Mocha Specification Cases
//
// Run specs:
//    $ cd dna.js
//    $ npm test

const url = 'http://example.com?a=one&b=two';
const html = `
<!doctype html>
<html lang=en>
    <head>
        <meta charset=utf-8>
        <title>Specification Runner</title>
    </head>
    <body>
    </body>
</html>
`;

const assert =    require('assert');
const { JSDOM } = require('jsdom');
const window =    new JSDOM(html, { url: url }).window;
const $ =         require('jquery')(window);
const dna =       require('./dna.js')(window, $);

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.array.fromMap()', () => {

   it('converts a map into an array of maps', () => {
      var dataSet = [
         {
            inputMap: { a: { word: 'Ant' }, b: { word: 'Bat' } },
            expected: [{ word: 'Ant', code: 'a' }, { word: 'Bat', code: 'b' }]
         },
         {
            inputMap: { x0: 100, x1: 101, x2: 102 },
            inputKey: 'key',
            expected: [{ value: 100, key: 'x0' }, { value: 101, key: 'x1' }, { value: 102, key: 'x2' }]
         }];
      function evalData(data) {
         var output = dna.array.fromMap(data.inputMap, data.inputKey);
         assert.deepEqual(output, data.expected);
         }
      dataSet.forEach(evalData);
      });

   });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.util.toCamel()', () => {

   it('converts a kebab (dashes) name to camelCase', () => {
      var dataSet = [
         { input: 'ready-set-go', expected: 'readySetGo' },
         { input: 'dna',          expected: 'dna' }
         ];
      function evalData(data) {
         assert.equal(dna.util.toCamel(data.input), data.expected);
         }
      dataSet.forEach(evalData);
      });

   });

////////////////////////////////////////////////////////////////////////////////////////////////////
describe('Utility function dna.util.printf()', () => {

  it('builds a string from variables', () => {
    var actual = dna.util.printf('%s: %s', 'Lives', 3);
    expected = 'Lives: 3';
    assert.equal(actual, expected);
    });

  });
<|endoftext|>


<commit_before>/**
* Suds: A Lightweight JavaScript SOAP Client
* Copyright: 2009 Kevin Whinnery (http://www.kevinwhinnery.com)
* License: http://www.apache.org/licenses/LICENSE-2.0.html
* Source: http://github.com/kwhinnery/Suds
*/
function SudsClient(_options) {

  //A generic extend function - thanks MooTools
  function extend(original, extended) {
    for (var key in (extended || {})) {
      if (obj.hasOwnProperty(key)) {
        original[key] = extended[key];
      }
    }
    return original;
  }

  //Check if an object is an array
  function isArray(obj) {
    return Object.prototype.toString.call(obj) == '[object Array]';
  }

  //Grab an XMLHTTPRequest Object
  function getXHR() {
    var xhr;
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest();
    }
    else {
      xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xhr;
  }

  //Parse a string and create an XML DOM object
  function xmlDomFromString(_xml) {
    var xmlDoc = null;
    if (window.DOMParser) {
      parser = new DOMParser();
      xmlDoc = parser.parseFromString(_xml,"text/xml");
    }
    else {
      xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.async = "false";
      xmlDoc.loadXML(_xml);
    }
    return xmlDoc;
  }

  // Convert a JavaScript object to an XML string - takes either an
  function convertToXml(_obj) {
    var xml = '';
    if (isArray(_obj)) {
      for (var i = 0; i < _obj.length; i++) {
        xml += convertToXml(_obj[i]);
      }
    } else {
      //For now assuming we either have an array or an object graph
      for (var key in _obj) {
        xml += '<'+key+'>';
        if (isArray(_obj[key]) || (typeof _obj[key] == 'object' && _obj[key] != null)) {
          xml += convertToXml(_obj[key]);
        }
        else {
          xml += _obj[key];
        }
        xml += '</'+key+'>';
      }
    }
    return xml;
  }

  // Client Configuration
  var config = extend({
    endpoint:'http://localhost',
    targetNamespace: 'http://localhost',
    envelopeBegin: '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body>',
    envelopeEnd: '</soap:Body></soap:Envelope>'
  },_options);

  // Invoke a web service
  this.invoke = function(_soapAction,_body,_callback) {
    //Build request body
    var body = _body;

    //Allow straight string input for XML body - if not, build from object
    if (typeof body !== 'string') {
      body = '<'+_soapAction+' xmlns="'+config.targetNamespace+'">';
      body += convertToXml(_body);
      body += '</'+_soapAction+'>';
    }

    //Build Soapaction header - if no trailing slash in namespace, need to splice one in for soap action
    var soapAction = '';
    if (config.targetNamespace.lastIndexOf('/') != config.targetNamespace.length - 1) {
      soapAction = config.targetNamespace+'/'+_soapAction;
    }
    else {
      soapAction = config.targetNamespace+_soapAction;
    }

    //POST XML document to service endpoint
    var xhr = getXHR();
    xhr.onload = function() {
      _callback.call(this, xmlDomFromString(this.responseText));
    };
    xhr.open('POST',config.endpoint);
		xhr.setRequestHeader('Content-Type', 'text/xml');
		xhr.setRequestHeader('Soapaction', soapAction);
		xhr.send(config.envelopeBegin+body+config.envelopeEnd);
  };
}<commit_msg>Added 1) Content Length to the Outbound SOAP message 2) ErrorCallback function 3) Optional SOAP Header functions (which are often mandatory in well written soap converstaions - eg authentication 4) Added a Timeout parameter - defaulted to 5 seconds.<commit_after>/**
* Suds: A Lightweight JavaScript SOAP Client
* Copyright: 2009 Kevin Whinnery (http://www.kevinwhinnery.com)
* License: http://www.apache.org/licenses/LICENSE-2.0.html
* Source: http://github.com/kwhinnery/Suds
*/
function SudsClient(_options) {
  //A generic extend function - thanks MooTools
  function extend(original, extended) {
    for (var key in (extended || {})) {
      if (obj.hasOwnProperty(key)) {
        original[key] = extended[key];
      }
    }
    return original;
  }

  //Check if an object is an array
  function isArray(obj) {
    return Object.prototype.toString.call(obj) == '[object Array]';
  }

  //Grab an XMLHTTPRequest Object
  function getXHR() {
    var xhr;
    if (window.XMLHttpRequest) {
      xhr = new XMLHttpRequest();
    }
    else {
      xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xhr;
  }

  //Parse a string and create an XML DOM object
  function xmlDomFromString(_xml) {
    var xmlDoc = null;
    if (window.DOMParser) {
      parser = new DOMParser();
      xmlDoc = parser.parseFromString(_xml,"text/xml");
    }
    else {
      xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.async = "false";
      xmlDoc.loadXML(_xml);
    }
    return xmlDoc;
  }

  // Convert a JavaScript object to an XML string - takes either an
  function convertToXml(_obj) {
    var xml = '';
    if (isArray(_obj)) {
      for (var i = 0; i < _obj.length; i++) {
        xml += convertToXml(_obj[i]);
      }
    } else {
      //For now assuming we either have an array or an object graph
      for (var key in _obj) {
        xml += '<'+key+'>';
        if (isArray(_obj[key]) || (typeof _obj[key] == 'object' && _obj[key] != null)) {
          xml += convertToXml(_obj[key]);
        }
        else {
          xml += _obj[key];
        }
        xml += '</'+key+'>';
      }
    }
    return xml;
  }

  // Client Configuration
  var config = extend({
    endpoint:'http://localhost',
    targetNamespace: 'http://localhost',
    envelopeBegin: '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:ns0="PLACEHOLDER" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">',
    headerBegin: '<soap:Header>',
    headerNode:'head',
    headerEnd: '</soap:Header>',
    bodyBegin:'<soap:Body>',
    envelopeEnd: '</soap:Body></soap:Envelope>',
    timeout: 5000
  },_options);

  // Invoke a web service
  this.invoke = function(_soapAction,_body,_callback,_error,_header) {
    //Build request body
    var body = _body;
    var header = _header;

    //Allow straight string input for XML body - if not, build from object
    if (typeof body !== 'string') {
      body = '<'+_soapAction+' xmlns="'+config.targetNamespace+'">';
      body += convertToXml(_body, 'ns0');
      body += '</'+_soapAction+'>';
    }

    var ebegin = config.envelopeBegin;
    config.envelopeBegin = ebegin.replace('PLACEHOLDER', config.targetNamespace);

    //Build Soapaction header - if no trailing slash in namespace, need to splice one in for soap action
    var soapAction = '';
    if (config.targetNamespace.lastIndexOf('/') != config.targetNamespace.length - 1) {
      soapAction = config.targetNamespace+'/'+_soapAction;
    }
    else {
      soapAction = config.targetNamespace+_soapAction;
    }

    //POST XML document to service endpoint
    var xhr = getXHR();
    xhr.onload = function() {
      _callback.call(this, xmlDomFromString(this.responseText));
    };
    xhr.onerror = function() {
      _error.call();
    }
    xhr.setTimeout(config.timeout);
    var sendXML = '';
    if(!header) {
        sendXML = config.envelopeBegin+body+config.envelopeEnd;
    } else {
        //Allow straight string input for XML body - if not, build from object
        if (typeof header !== 'string') {
          header = '<'+_soapAction+' xmlns="'+config.targetNamespace+'">';
          header += convertToXml(_header, 'ns0');
          header += '</'+_soapAction+'>';
        }
        sendXML = config.envelopeBegin+config.headerBegin+header+config.headerEnd+config.bodyBegin+body+config.envelopeEnd;
    }
    xhr.open('POST',config.endpoint);
        xhr.setRequestHeader('Content-Type', 'text/xml');
        xhr.setRequestHeader('Content-Length', sendXML.length);
        xhr.setRequestHeader('SOAPAction', soapAction);
        xhr.send(sendXML);
  };
}
<|endoftext|>


<commit_before><commit_msg>Changes local variable name for better context<commit_after><|endoftext|>


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

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

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

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

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


<commit_before>(function(factory){
  if (typeof define !== "undefined" && define.cmd) {
    define(function(require, exports, module){
      var TouchObject = require("touch");
      factory(TouchObject);
    });
  } else {
    factory(TouchObject);
  }
}(function(TouchObject){

  window.onload = function(){
    var testDiv = document.getElementById("testDiv");
    var divObj = new TouchObject(testDiv);
    document.querySelector("#touchType").innerHTML = divObj.touchType;

    divObj.addEventListener("swipeStart", function(e){
      document.querySelector("#evtName").innerHTML = "swipeStart";
      printEvent(e);
    });
    divObj.addEventListener("swipeLeft", function(e){
      document.querySelector("#evtName").innerHTML = "swipeLeft";
    });
    divObj.addEventListener("swipeRight", function(e){
      document.querySelector("#evtName").innerHTML = "swipeRight";
    })

    divObj.addEventListener("swipeUp", function(e){
      document.querySelector("#evtName").innerHTML = "swipeUp";
    })
    divObj.addEventListener("swipeDown", function(e){
      document.querySelector("#evtName").innerHTML = "swipeDown";
    })

    divObj.addEventListener("swipeProgress", function(e) {
      document.querySelector("#evtName").innerHTML = "swipeProgress";
      printEvent(e);
    });
    divObj.addEventListener("swipeCancel", function(e) {
      document.querySelector("#evtName").innerHTML = "swipeCancel";
      printEvent(e);
    });

    divObj.addEventListener("tap", function(e) {
      document.querySelector("#evtName").innerHTML = "tap";
      printEvent(e);
    });

    function printEvent(event) {
      document.querySelector("#movedX").innerHTML = (event.detail && typeof event.detail.movedPageX !== "undefined") ? parseInt(event.detail.movedPageX) + "px" : " ";
      document.querySelector("#movedY").innerHTML = (event.detail && typeof event.detail.movedPageY !== "undefined") ? parseInt(event.detail.movedPageY) + "px" : " ";
      document.querySelector("#clientX").innerHTML = (typeof event.clientX !== "undefined") ? parseInt(event.clientX) + "px" : " ";
      document.querySelector("#clientY").innerHTML = (typeof event.clientY !== "undefined") ? parseInt(event.clientY) + "px" : " ";
    }
    /*
    setTimeout(function(){
      divObj.dispose();
      log("dispose");
      setTimeout(function(){
        divObj.bindEvents();
        log("Restarted.");
      }, 5000);
    }, 6000);
    */
  };
}));<commit_msg>Update test.js<commit_after>(function(factory){
  if (typeof define !== "undefined" && define.cmd) {
    define(function(require, exports, module){
      var TouchObject = require("touch");
      factory(TouchObject);
    });
  } else {
    factory(TouchObject);
  }
}(function(TouchObject){

  window.onload = function(){
    var testDiv = document.getElementById("testDiv");
    var divObj = new TouchObject(testDiv);
    document.querySelector("#touchType").innerHTML = divObj.touchType;

    divObj.addEventListener("swipeStart", function(e){
      document.querySelector("#evtName").innerHTML = "swipeStart";
      printEvent(e);
    });
    divObj.addEventListener("swipeLeft", function(e){
      document.querySelector("#evtName").innerHTML = "swipeLeft";
    });
    divObj.addEventListener("swipeRight", function(e){
      document.querySelector("#evtName").innerHTML = "swipeRight";
    })

    divObj.addEventListener("swipeUp", function(e){
      document.querySelector("#evtName").innerHTML = "swipeUp";
    })
    divObj.addEventListener("swipeDown", function(e){
      document.querySelector("#evtName").innerHTML = "swipeDown";
    })

    divObj.addEventListener("swipeProgress", function(e) {
      document.querySelector("#evtName").innerHTML = "swipeProgress";
      printEvent(e);
    });
    divObj.addEventListener("swipeCancel", function(e) {
      document.querySelector("#evtName").innerHTML = "swipeCancel";
      printEvent(e);
    });

    divObj.addEventListener("tap", function(e) {
      document.querySelector("#evtName").innerHTML = "tap";
      printEvent(e);
    });

    function printEvent(event) {
      document.querySelector("#movedX").innerHTML = (event.detail.detail && typeof event.detail.detail.movedPageX !== "undefined") ? parseInt(event.detail.detail.movedPageX) + "px" : " ";
      document.querySelector("#movedY").innerHTML = (event.detail.detail && typeof event.detail.detail.movedPageY !== "undefined") ? parseInt(event.detail.detail.movedPageY) + "px" : " ";
      document.querySelector("#clientX").innerHTML = (typeof event.detail.clientX !== "undefined") ? parseInt(event.detail.clientX) + "px" : " ";
      document.querySelector("#clientY").innerHTML = (typeof event.detail.clientY !== "undefined") ? parseInt(event.detail.clientY) + "px" : " ";
    }
    /*
    setTimeout(function(){
      divObj.dispose();
      log("dispose");
      setTimeout(function(){
        divObj.bindEvents();
        log("Restarted.");
      }, 5000);
    }, 6000);
    */
  };
}));
<|endoftext|>


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

describe("Complex Numbers Library", function(){
	it("should return an expression", function(){
		var numx = new Complex(3, 4);
		expect(numx.toString()).toEqual("3 + 4i");
	});

	it("should find the modulus", function(){
		var numx = new Complex(4, 5);
		expect(numx.magnitude()).toEqual(Math.sqrt(41));
		expect(new Complex(2,4).magnitude()).toEqual(Math.sqrt(20));
	});<commit_msg>delete incomplete<commit_after><|endoftext|>


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

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

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-20 10:23:52<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

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

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


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

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

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-12-4 01:35:06<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

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

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


<commit_before>var test = require('tap').test,
    fs = require('fs'),
    rework = require('rework'),
    reworkNPM = require('./'),
    normalize = require('path').normalize;

test('Import relative source file', function(t) {
    var source = '@import "./test";',
        output = rework(source).use(reworkNPM('test')).toString();
    t.equal(output, '.test {\n  content: "Test file";\n}');
    t.end();
});

test('Import package', function(t) {
    var source = '@import "test";',
        output = rework(source).use(reworkNPM('test')).toString();
    t.equal(output, '.test {\n  content: "Test package";\n}');
    t.end();
});

test('Import package with custom style file', function(t) {
    var source = '@import "custom";',
        output = rework(source).use(reworkNPM('test')).toString();
    t.equal(output, '.custom {\n  content: "Custom package";\n}');
    t.end();
});

test('Import files imported from imported package', function(t) {
    var source = '@import "nested";',
        output = rework(source).use(reworkNPM('test')).toString();
    t.equal(output, '.test {\n  content: "From nested test package";\n}');
    t.end();
});

test('Import package in @media', function(t) {
    var source = [
        '@media (min-width: 320px) {',
        '  @import "test";',
        '}',
        '@media (min-width: 640px) {',
        '  @import "test";',
        '}'
    ].join('\n')

    var output = rework(source).use(reworkNPM('test')).toString();
    t.equal(output, [
        '@media (min-width: 320px) {',
        '  .test {',
        '    content: "Test package";',
        '  }',
        '}',
        '',
        '@media (min-width: 640px) {',
        '  .test {',
        '    content: "Test package";',
        '  }',
        '}'
    ].join('\n'));

    t.end();
});

test('Ignore import from @media if imported in outer scope', function(t) {
    var source =
        '@import "test";\n' +
        '@media (min-width: 320px) { @import "test"; }';

    var output = rework(source).use(reworkNPM('test')).toString();
    t.equal(output, [
        '.test {',
        '  content: "Test package";',
        '}',
        '',
        '@media (min-width: 320px) {',
        '',
        '}'
    ].join('\n'));

    t.end();
});

test('Skip absolute URLs', function(t) {
    var source = '@import "http://example.com/example.css";',
        output = rework(source).use(reworkNPM()).toString();
    t.equal(output, source);
    t.end();
});

test('Skip imports using url()', function(t) {
    var source = '@import url(test.css);',
        output = rework(source).use(reworkNPM()).toString();
    t.equal(output, source);
    t.end();
});

test('Include source maps', function(t) {
    var source = '@import "test";',
        output = rework(source)
            .use(reworkNPM('test'))
            .toString({ sourcemap: true });

    t.equal(output,
        '.test {\n  content: "Test package";\n}\n' +
        '/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozL' +
        'CJmaWxlIjoiZ2VuZXJhdGVkLmNzcyIsInNvdXJjZXMiOlsibm9kZV9tb2R1bGVzL3Rl' +
        'c3QvaW5kZXguY3NzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0VBQ0ksdUJ' +
        'BQXVCIn0= */');
    t.end();
});

test('Include source file names in output', function(t) {
    var source = '@import "test";',
        output = rework(source)
            .use(reworkNPM('test'));

    var rule = output.obj.stylesheet.rules[0];
    t.equal(
        normalize(rule.position.source),
        normalize('node_modules/test/index.css'));
    t.end();
});

test('Use file names relative to root', function(t) {
    var source = '@import "test";',
        output = rework(source)
            .use(reworkNPM({ root: __dirname, dir: 'test' }));

    var rule = output.obj.stylesheet.rules[0];
    t.equal(
        normalize(rule.position.source),
        normalize('test/node_modules/test/index.css'));
    t.end();
});

test('Use shim config option', function(t) {
    var source = '@import "shimmed";',
        cfg = {
            root: __dirname,
            dir: 'test',
            shim: {'shimmed': 'some/path/shimmed.css'}
        },
        output = rework(source).use(reworkNPM(cfg)).toString();
    t.equal(output, '.shimmed {\n  content: "Shimmed package";\n}');
    t.end();
});
<commit_msg>Format test code<commit_after>var test = require('tap').test,
    fs = require('fs'),
    rework = require('rework'),
    reworkNPM = require('./'),
    normalize = require('path').normalize;

test('Import relative source file', function(t) {
    var source = '@import "./test";',
        output = rework(source).use(reworkNPM('test')).toString();
    t.equal(output, '.test {\n  content: "Test file";\n}');
    t.end();
});

test('Import package', function(t) {
    var source = '@import "test";',
        output = rework(source).use(reworkNPM('test')).toString();
    t.equal(output, '.test {\n  content: "Test package";\n}');
    t.end();
});

test('Import package with custom style file', function(t) {
    var source = '@import "custom";',
        output = rework(source).use(reworkNPM('test')).toString();
    t.equal(output, '.custom {\n  content: "Custom package";\n}');
    t.end();
});

test('Import files imported from imported package', function(t) {
    var source = '@import "nested";',
        output = rework(source).use(reworkNPM('test')).toString();
    t.equal(output, '.test {\n  content: "From nested test package";\n}');
    t.end();
});

test('Import package in @media', function(t) {
    var source = [
        '@media (min-width: 320px) {',
        '  @import "test";',
        '}',
        '@media (min-width: 640px) {',
        '  @import "test";',
        '}'
    ].join('\n')

    var output = rework(source).use(reworkNPM('test')).toString();
    t.equal(output, [
        '@media (min-width: 320px) {',
        '  .test {',
        '    content: "Test package";',
        '  }',
        '}',
        '',
        '@media (min-width: 640px) {',
        '  .test {',
        '    content: "Test package";',
        '  }',
        '}'
    ].join('\n'));

    t.end();
});

test('Ignore import from @media if imported in outer scope', function(t) {
    var source =
        '@import "test";\n' +
        '@media (min-width: 320px) { @import "test"; }';

    var output = rework(source).use(reworkNPM('test')).toString();
    t.equal(output, [
        '.test {',
        '  content: "Test package";',
        '}',
        '',
        '@media (min-width: 320px) {',
        '',
        '}'
    ].join('\n'));

    t.end();
});

test('Skip absolute URLs', function(t) {
    var source = '@import "http://example.com/example.css";',
        output = rework(source).use(reworkNPM()).toString();
    t.equal(output, source);
    t.end();
});

test('Skip imports using url()', function(t) {
    var source = '@import url(test.css);',
        output = rework(source).use(reworkNPM()).toString();
    t.equal(output, source);
    t.end();
});

test('Include source maps', function(t) {
    var source = '@import "test";',
        output = rework(source)
            .use(reworkNPM('test'))
            .toString({ sourcemap: true });

    t.equal(output,
        '.test {\n  content: "Test package";\n}\n' +
        '/*# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozL' +
        'CJmaWxlIjoiZ2VuZXJhdGVkLmNzcyIsInNvdXJjZXMiOlsibm9kZV9tb2R1bGVzL3Rl' +
        'c3QvaW5kZXguY3NzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0VBQ0ksdUJ' +
        'BQXVCIn0= */');
    t.end();
});

test('Include source file names in output', function(t) {
    var source = '@import "test";',
        output = rework(source)
            .use(reworkNPM('test'));

    var rule = output.obj.stylesheet.rules[0];
    t.equal(
        normalize(rule.position.source),
        normalize('node_modules/test/index.css'));
    t.end();
});

test('Use file names relative to root', function(t) {
    var source = '@import "test";',
        output = rework(source)
            .use(reworkNPM({ root: __dirname, dir: 'test' }));

    var rule = output.obj.stylesheet.rules[0];
    t.equal(
        normalize(rule.position.source),
        normalize('test/node_modules/test/index.css'));
    t.end();
});

test('Use shim config option', function(t) {
    var source = '@import "shimmed";',
        shim = { 'shimmed': 'some/path/shimmed.css' },
        output = rework(source)
            .use(reworkNPM({ root: __dirname, dir: 'test', shim: shim }))
            .toString();

    t.equal(output, '.shimmed {\n  content: "Shimmed package";\n}');
    t.end();
});
<|endoftext|>


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

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

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-6 08:45:52<commit_after><|endoftext|>


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

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

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-17 11:47:31<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

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

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


<commit_before>
// var search = function(nums, target) {

//     function getPivot(arr){
//         var low = 0,
//             high = arr.length-1,
//             mid
//             result = -1;

//         while( low<= high ){
//             if( arr[low] <= arr[high] ) return low; // means it is sorted
//             mid = Math.floor( (high+low)/2 );
//             var next = (mid+1) % target,
//                 prev = (mid+target-1) % target;
//             if( arr[mid] <= arr[next] && arr[mid] <= arr[prev] ) {
//                 result = mid;
//                 break;
//             } else if( arr[mid] <= arr[high] ){
//                 high = mid-1;
//             } else if( arr[mid] >= arr[low] ){
//                 low = mid+1;
//             }
//         }
//     }
//     // var lo = 0,
//     //     hi = nums.length-1;
//     // while(lo<hi){
//     //     var mid = Math.floor( (lo+hi)/2 );
//     //     if(nums[mid]>nums[hi]) lo = mid+1;
//     //     else hi=mid;
//     // }
//     // console.log(lo, getPivot(nums))
//     var rot = getPivot(nums),
//         lo = 0,
//         hi = nums.length-1;
//         // The usual binary search and accounting for rotation.
//       while(lo<=hi){
//           var mid= Math.floor( (lo+hi)/2 );
//           var realmid = (mid+rot) % nums.length;
//           if(nums[realmid] === target) return realmid;
//           if(nums[realmid]<target){
//               lo = mid+1;
//           } else {
//               hi = mid-1;
//           }
//       }
//       return -1;

// }
// var test = [22,33,44,11]
// console.log( search(test, 22))
 // ---------------------------------------------

// var search = function(nums, target) {

//     var low = 0,
//         high = nums.length-1,
//         mid;

//     while( low<= high ){
//         if( nums[low] <= nums[high] ) return low; // means it is sorted
//         mid = Math.floor( (high+low)/2 );
//         var next = (mid+1) % target,
//             prev = (mid+target-1) % target;
//         if( nums[mid] <= nums[next] && nums[mid] <= nums[prev] ) {
//           return mid
//         } else if( nums[mid] <= nums[high] ){
//           high = mid-1;
//         } else if( nums[mid] >= nums[low] ){
//           low = mid+1;
//         }
//     }
//     return -1;
// }
// var test = [2,3,4,1]
// console.log( search(test, 1) )

// function binarySearch(k, nums){
//     var lo=0,
//         hi=nums.length-1,
//         mid;
//     while(lo<=hi){
//         mid = Math.floor( (lo+hi)/2 );
//         if( k === nums[mid] || k === nums[lo] || k === nums[hi] ) return true;
//         nums[mid] > nums[hi] ? lo=mid+1 : hi=mid;
//     }
//     return false;
// }

// console.log(binarySearch(8, [1, 2, 3, 5, 7, 8]));

    // var map = {};
    // function walk(moovi){
    //     if(map[moovi.getId()]){
    //         return;
    //     } else {
    //         map[moovi.getId()] = moovi.getRating();
    //     }
    // };
    // for( var i=0; i<movie.similar.length; i++){
    //     walk(similar[i])
    // }

    //     var ratings = [],
    //     visited = {};
    // function walk(m){
    //     var rating_Id = Math.floor( m.getId()*10 );
    //     if(!visited[m.getId()]){
    //         if(ratings[rating_Id]){
    //             ratings[rating_Id].push(m.getId());
    //         } else {
    //             ratings[rating_Id] = [m.getId()];
    //         }
    //         visited[m.getId()] = true;
    //         var similar = m.getSimilarMovies();
    //         for( var i=0; i<similar.length; i++){
    //             walk(similar[i])
    //         }
    //     }
    // }
    // walk(movie);

    // return ratings;

// ------------------------------------------------------------------------

// function getMovieRecommendations(movie, n)
// {
//     if(movie.getSimilarMovies().length < 1) return [];
//     var ratings = [],
//         visited = {};
//     function walk(m){
//         var rating_Id = m.getId(),
//             cRating = Math.floor( m.getRating()*10 );
//         if(!visited[m.getId()]){
//             if(ratings[cRating]){
//                 ratings[cRating].push(m);
//             } else {
//                 ratings[cRating] = [m];
//             }
//             visited[m.getId()] = true;
//             var similar = m.getSimilarMovies();
//             for( var i=0; i<similar.length; i++){
//                 if(!visited[similar[i].getId()]) walk(similar[i]);
//             }
//         }
//     }
//     walk(movie);
//     ratings = ratings.filter(function(n){ return n !== undefined });
//     var counter = 0,
//         result = [];
//     for(var i = ratings.length-1; i>=0;i--){
//         for( var j =0; j<ratings[i].length; j++ ){
//             if( counter < n ){
//                 if( movie.getId() !== ratings[i][j].getId() ){
//                     result.push( ratings[i][j] );
//                     counter++;
//                 }
//             } else {
//                 return result;
//             }
//         }
//     }
//     return result;
// }

var test = [[1,3,5,7],[10,11,16,20],[23,30,34,50]]
console.log( test.splice(1) )

Given an stream of strings as input, return the first unique string in the stream. Assume the stream interface only has the following public methods:
hasNext() --> returns a boolean
getNext() --> returns the next string

Example:
Input: 'a' --> 'bb' --> 'ccc' --> 'z' --> 'ccc' --> 'bb' --> 'a' --> 'dd'
Return: 'z'

function ouccurence(input){
    var map = {},
        max = 0,
        current;

    while( input.hasNext() ){
        current = input.getNext();
        if( map[current] ){
            map[current]++;
        } else {
            map[current] = 1;
        }
    }

    for( var k in map ){ // isnt
       if( map[k] === 1 ) return k; // constant
    }
}

{
    'a' : 1
    'bb': 1
    'ccc': 2
    'z': 1
}

How would you design a parking garage object that tracks the cars that are parked
inside and has four different types of spots:
motorcycle, EV, compact, regular

current available spots overall spots, current available spots for each specific type, max count overall spots, max count for each specific type

car object - type
function
<commit_msg>remove un needed from test<commit_after>
// var search = function(nums, target) {

//     function getPivot(arr){
//         var low = 0,
//             high = arr.length-1,
//             mid
//             result = -1;

//         while( low<= high ){
//             if( arr[low] <= arr[high] ) return low; // means it is sorted
//             mid = Math.floor( (high+low)/2 );
//             var next = (mid+1) % target,
//                 prev = (mid+target-1) % target;
//             if( arr[mid] <= arr[next] && arr[mid] <= arr[prev] ) {
//                 result = mid;
//                 break;
//             } else if( arr[mid] <= arr[high] ){
//                 high = mid-1;
//             } else if( arr[mid] >= arr[low] ){
//                 low = mid+1;
//             }
//         }
//     }
//     // var lo = 0,
//     //     hi = nums.length-1;
//     // while(lo<hi){
//     //     var mid = Math.floor( (lo+hi)/2 );
//     //     if(nums[mid]>nums[hi]) lo = mid+1;
//     //     else hi=mid;
//     // }
//     // console.log(lo, getPivot(nums))
//     var rot = getPivot(nums),
//         lo = 0,
//         hi = nums.length-1;
//         // The usual binary search and accounting for rotation.
//       while(lo<=hi){
//           var mid= Math.floor( (lo+hi)/2 );
//           var realmid = (mid+rot) % nums.length;
//           if(nums[realmid] === target) return realmid;
//           if(nums[realmid]<target){
//               lo = mid+1;
//           } else {
//               hi = mid-1;
//           }
//       }
//       return -1;

// }
// var test = [22,33,44,11]
// console.log( search(test, 22))
 // ---------------------------------------------

// var search = function(nums, target) {

//     var low = 0,
//         high = nums.length-1,
//         mid;

//     while( low<= high ){
//         if( nums[low] <= nums[high] ) return low; // means it is sorted
//         mid = Math.floor( (high+low)/2 );
//         var next = (mid+1) % target,
//             prev = (mid+target-1) % target;
//         if( nums[mid] <= nums[next] && nums[mid] <= nums[prev] ) {
//           return mid
//         } else if( nums[mid] <= nums[high] ){
//           high = mid-1;
//         } else if( nums[mid] >= nums[low] ){
//           low = mid+1;
//         }
//     }
//     return -1;
// }
// var test = [2,3,4,1]
// console.log( search(test, 1) )

// function binarySearch(k, nums){
//     var lo=0,
//         hi=nums.length-1,
//         mid;
//     while(lo<=hi){
//         mid = Math.floor( (lo+hi)/2 );
//         if( k === nums[mid] || k === nums[lo] || k === nums[hi] ) return true;
//         nums[mid] > nums[hi] ? lo=mid+1 : hi=mid;
//     }
//     return false;
// }

// console.log(binarySearch(8, [1, 2, 3, 5, 7, 8]));

    // var map = {};
    // function walk(moovi){
    //     if(map[moovi.getId()]){
    //         return;
    //     } else {
    //         map[moovi.getId()] = moovi.getRating();
    //     }
    // };
    // for( var i=0; i<movie.similar.length; i++){
    //     walk(similar[i])
    // }

    //     var ratings = [],
    //     visited = {};
    // function walk(m){
    //     var rating_Id = Math.floor( m.getId()*10 );
    //     if(!visited[m.getId()]){
    //         if(ratings[rating_Id]){
    //             ratings[rating_Id].push(m.getId());
    //         } else {
    //             ratings[rating_Id] = [m.getId()];
    //         }
    //         visited[m.getId()] = true;
    //         var similar = m.getSimilarMovies();
    //         for( var i=0; i<similar.length; i++){
    //             walk(similar[i])
    //         }
    //     }
    // }
    // walk(movie);

    // return ratings;

// ------------------------------------------------------------------------

// function getMovieRecommendations(movie, n)
// {
//     if(movie.getSimilarMovies().length < 1) return [];
//     var ratings = [],
//         visited = {};
//     function walk(m){
//         var rating_Id = m.getId(),
//             cRating = Math.floor( m.getRating()*10 );
//         if(!visited[m.getId()]){
//             if(ratings[cRating]){
//                 ratings[cRating].push(m);
//             } else {
//                 ratings[cRating] = [m];
//             }
//             visited[m.getId()] = true;
//             var similar = m.getSimilarMovies();
//             for( var i=0; i<similar.length; i++){
//                 if(!visited[similar[i].getId()]) walk(similar[i]);
//             }
//         }
//     }
//     walk(movie);
//     ratings = ratings.filter(function(n){ return n !== undefined });
//     var counter = 0,
//         result = [];
//     for(var i = ratings.length-1; i>=0;i--){
//         for( var j =0; j<ratings[i].length; j++ ){
//             if( counter < n ){
//                 if( movie.getId() !== ratings[i][j].getId() ){
//                     result.push( ratings[i][j] );
//                     counter++;
//                 }
//             } else {
//                 return result;
//             }
//         }
//     }
//     return result;
// }
<|endoftext|>


<commit_before>var fs          = require('fs')
var rawData     = fs.read('emojis.json').toString()
var data        = JSON.parse(fs.read('emojis.json'))
var keys        = rawData.match(/"(.+)":/g).map(function(key){return key.replace(/"|:/g,'')})
var buildFailed = false
var passed      = function() { console.log("\033[92mPASSED\033[0m\n") }
var failed      = function() {
  console.log("\033[91mFAILED\033[0m\n")
  buildFailed = true
}

//
console.log("\nTEST: Correct number of emojis")

if(keys.length != 884) {
  console.log("There are 884 emojis, but emojis.json has " + keys.length + " entries.")
  failed()
} else {
  passed()
}

//
console.log("TEST: No duplicated entries")

var arr = []
var dups = []

keys.forEach(function(key) {
  if(arr.indexOf(key) < 0) {
    arr.push(key)
  } else {
    dups.push(key)
  }
})

if(dups.length > 0) {
  dups.forEach(function(key) {
    console.log('There is more than one "' + key + '" in emojis.json.')
  })
  failed()
} else {
  passed()
}

//
console.log("TEST: No unnecessary keywords")

var unnecessities = []
var unnecessitiesInKeywords = []

keys.forEach(function(key) {
  data[key].forEach(function(keyword) {
    if(key.match(keyword)) {
      unnecessities.push([key, keyword])
    }

    var otherKeywords = data[key]
    otherKeywords.splice(data[key].indexOf(keyword), 1)
    otherKeywords.forEach(function(otherKeyword) {
      if(otherKeyword.match(keyword)) {
        unnecessitiesInKeywords.push([otherKeyword, keyword, key])
      }
    })
  })
})

if(unnecessities.length > 0 || unnecessitiesInKeywords.length > 0) {
  unnecessities.forEach(function(arr) {
    console.log('"' + arr[1] + '" is unnecessary as it is already part of "' + arr[0] + '" and will be matched.')
  })
  unnecessitiesInKeywords.forEach(function(arr) {
    console.log('"' + arr[1] + '" is unnecessary as a "' + arr[2] + '" already has a keyword "' + arr[0] + '".')
  })

  failed()
} else {
  passed()
}

//
console.log("TEST: Line format")

var offenses = []
var lines = rawData.replace(/^{\n([\s\S]*)\n}\n$/, '$1').split("\n")
var baseRegex = '^  "[\\w+-]+": \\["[\\w- ]+"(, "[\\w- ]+")*\\]'
var contentRegex = new RegExp(baseRegex + ',$')
var lastLineRegex = new RegExp(baseRegex + '$')
lines.forEach(function(line, index) {
  if(index == lines.length - 1) {
    if(!line.match(lastLineRegex)) {
      offenses.push(index + 2)
    }
  } else {
    if(!line.match(contentRegex)) {
      offenses.push(index + 2)
    }
  }
})

if(offenses.length > 0) {
  offenses.forEach(function(lineNo) {
    console.log('Line ' + lineNo + ' has the wrong format.')
  })

  failed()
} else {
  passed()
}

//
if(buildFailed) {
  console.log(":cry: \033[91mNo good, something failed.\033[0m :boom:\n")
  phantom.exit(buildFailed)
} else {
  console.log(":sparkles: \033[96mWho's awesome? You're awesome!\033[0m :+1:\n")
  phantom.exit()
}
<commit_msg>Use `!==` and `===` instead of `!=` and `==`<commit_after>var fs          = require('fs')
var rawData     = fs.read('emojis.json').toString()
var data        = JSON.parse(fs.read('emojis.json'))
var keys        = rawData.match(/"(.+)":/g).map(function(key){return key.replace(/"|:/g,'')})
var buildFailed = false
var passed      = function() { console.log("\033[92mPASSED\033[0m\n") }
var failed      = function() {
  console.log("\033[91mFAILED\033[0m\n")
  buildFailed = true
}

//
console.log("\nTEST: Correct number of emojis")

if(keys.length !== 884) {
  console.log("There are 884 emojis, but emojis.json has " + keys.length + " entries.")
  failed()
} else {
  passed()
}

//
console.log("TEST: No duplicated entries")

var arr = []
var dups = []

keys.forEach(function(key) {
  if(arr.indexOf(key) < 0) {
    arr.push(key)
  } else {
    dups.push(key)
  }
})

if(dups.length > 0) {
  dups.forEach(function(key) {
    console.log('There is more than one "' + key + '" in emojis.json.')
  })
  failed()
} else {
  passed()
}

//
console.log("TEST: No unnecessary keywords")

var unnecessities = []
var unnecessitiesInKeywords = []

keys.forEach(function(key) {
  data[key].forEach(function(keyword) {
    if(key.match(keyword)) {
      unnecessities.push([key, keyword])
    }

    var otherKeywords = data[key]
    otherKeywords.splice(data[key].indexOf(keyword), 1)
    otherKeywords.forEach(function(otherKeyword) {
      if(otherKeyword.match(keyword)) {
        unnecessitiesInKeywords.push([otherKeyword, keyword, key])
      }
    })
  })
})

if(unnecessities.length > 0 || unnecessitiesInKeywords.length > 0) {
  unnecessities.forEach(function(arr) {
    console.log('"' + arr[1] + '" is unnecessary as it is already part of "' + arr[0] + '" and will be matched.')
  })
  unnecessitiesInKeywords.forEach(function(arr) {
    console.log('"' + arr[1] + '" is unnecessary as a "' + arr[2] + '" already has a keyword "' + arr[0] + '".')
  })

  failed()
} else {
  passed()
}

//
console.log("TEST: Line format")

var offenses = []
var lines = rawData.replace(/^{\n([\s\S]*)\n}\n$/, '$1').split("\n")
var baseRegex = '^  "[\\w+-]+": \\["[\\w- ]+"(, "[\\w- ]+")*\\]'
var contentRegex = new RegExp(baseRegex + ',$')
var lastLineRegex = new RegExp(baseRegex + '$')
lines.forEach(function(line, index) {
  if(index === lines.length - 1) {
    if(!line.match(lastLineRegex)) {
      offenses.push(index + 2)
    }
  } else {
    if(!line.match(contentRegex)) {
      offenses.push(index + 2)
    }
  }
})

if(offenses.length > 0) {
  offenses.forEach(function(lineNo) {
    console.log('Line ' + lineNo + ' has the wrong format.')
  })

  failed()
} else {
  passed()
}

//
if(buildFailed) {
  console.log(":cry: \033[91mNo good, something failed.\033[0m :boom:\n")
  phantom.exit(buildFailed)
} else {
  console.log(":sparkles: \033[96mWho's awesome? You're awesome!\033[0m :+1:\n")
  phantom.exit()
}
<|endoftext|>


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

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

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

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

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


<commit_before>'use strict'

var test = require('tape')
var clean = require('./')
var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017/mongocleantest'

function getDB (cb) {
  MongoClient.connect(url, { w: 1 }, cb)
}

function close (db, t) {
  db.close(function () {
    t.end()
  })
}

function cleanVerifyAndClose (db, t) {
  clean(db, function (err, db) {
    t.notOk(err, 'no error')

    db.listCollections({}).toArray(function (err, collections) {
      t.notOk(err, 'no error')

      // there is only the system collection
      t.equal(collections.length, 1)

      close(db, t)
    })
  })
}

test('does nothing on an empty db', function (t) {
  getDB(function (err, db) {
    t.notOk(err, 'no error')

    clean(db, function (err) {
      t.notOk(err, 'no error')
      close(db, t)
    })
  })
})

test('removes a collection', function (t) {
  getDB(function (err, db) {
    t.notOk(err, 'no error')

    // creates collection dummy1
    db.createCollection('dummy1', function (err) {
      t.notOk(err, 'no error')

      // clean, verify and close
      cleanVerifyAndClose(db, t)
    })
  })
})

test('removes two collections', function (t) {
  getDB(function (err, db) {
    t.notOk(err, 'no error')

    db.createCollection('dummy1', function (err) {
      t.notOk(err, 'no error')

      db.createCollection('dummy2', function (err) {
        t.notOk(err, 'no error')

        // clean, verify and close
        cleanVerifyAndClose(db, t)
      })
    })
  })
})

test('clean using an url', function (t) {
  getDB(function (err, db) {
    t.notOk(err, 'no error')

    // creates collection dummy1
    db.createCollection('dummy3', function (err) {
      t.notOk(err, 'no error')

      db.close(function () {
        cleanVerifyAndClose(url, t)
      })
    })
  })
})

test('removes two collections on three', function (t) {
  getDB(function (err, db) {
    t.notOk(err, 'no error')

    db.createCollection('dummy1', function (err) {
      t.notOk(err, 'no error')

      db.createCollection('dummy2', function (err) {
        t.notOk(err, 'no error')

        db.createCollection('dummy3', function (err) {
          t.notOk(err, 'no error')

          // clean, verify and close

          clean(db, {exclude: ['dummy1', 'dummy4']}, function (err, db) {
            t.notOk(err, 'no error')

            db.listCollections({}).toArray(function (err, collections) {
              t.notOk(err, 'no error')

              // there are two collections, the system collection and dummy3
              t.equal(collections.length, 2)

              close(db, t)
            })
          })
        })
      })
    })
  })
})

test('removes two collections on four', function (t) {
  getDB(function (err, db) {
    t.notOk(err, 'no error')

    db.createCollection('dummy1', function (err) {
      t.notOk(err, 'no error')

      db.createCollection('dummy2', function (err) {
        t.notOk(err, 'no error')

        db.createCollection('dummy3', function (err) {
          t.notOk(err, 'no error')

          db.createCollection('dummy4', function (err) {
            t.notOk(err, 'no error')

            // clean, verify and close

            clean(db, {exclude: ['dummy1', 'dummy4']}, function (err, db) {
              t.notOk(err, 'no error')

              db.listCollections({}).toArray(function (err, collections) {
                t.notOk(err, 'no error')

                // there are two collections, the system collection and dummy3
                t.equal(collections.length, 3)

                close(db, t)
              })
            })
          })
        })
      })
    })
  })
})
<commit_msg>Added exclude plus url connection test<commit_after>'use strict'

var test = require('tape')
var clean = require('./')
var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017/mongocleantest'

function getDB (cb) {
  MongoClient.connect(url, { w: 1 }, cb)
}

function close (db, t) {
  db.close(function () {
    t.end()
  })
}

function cleanVerifyAndClose (db, t) {
  clean(db, function (err, db) {
    t.notOk(err, 'no error')

    db.listCollections({}).toArray(function (err, collections) {
      t.notOk(err, 'no error')

      // there is only the system collection
      t.equal(collections.length, 1)

      close(db, t)
    })
  })
}

test('does nothing on an empty db', function (t) {
  getDB(function (err, db) {
    t.notOk(err, 'no error')

    clean(db, function (err) {
      t.notOk(err, 'no error')
      close(db, t)
    })
  })
})

test('removes a collection', function (t) {
  getDB(function (err, db) {
    t.notOk(err, 'no error')

    // creates collection dummy1
    db.createCollection('dummy1', function (err) {
      t.notOk(err, 'no error')

      // clean, verify and close
      cleanVerifyAndClose(db, t)
    })
  })
})

test('removes two collections', function (t) {
  getDB(function (err, db) {
    t.notOk(err, 'no error')

    db.createCollection('dummy1', function (err) {
      t.notOk(err, 'no error')

      db.createCollection('dummy2', function (err) {
        t.notOk(err, 'no error')

        // clean, verify and close
        cleanVerifyAndClose(db, t)
      })
    })
  })
})

test('clean using an url', function (t) {
  getDB(function (err, db) {
    t.notOk(err, 'no error')

    // creates collection dummy1
    db.createCollection('dummy3', function (err) {
      t.notOk(err, 'no error')

      db.close(function () {
        cleanVerifyAndClose(url, t)
      })
    })
  })
})

test('removes two collections on three', function (t) {
  getDB(function (err, db) {
    t.notOk(err, 'no error')

    db.createCollection('dummy1', function (err) {
      t.notOk(err, 'no error')

      db.createCollection('dummy2', function (err) {
        t.notOk(err, 'no error')

        db.createCollection('dummy3', function (err) {
          t.notOk(err, 'no error')

          // clean, verify and close

          clean(db, {exclude: ['dummy1', 'dummy4']}, function (err, db) {
            t.notOk(err, 'no error')

            db.listCollections({}).toArray(function (err, collections) {
              t.notOk(err, 'no error')

              // there are two collections, the system collection and dummy3
              t.equal(collections.length, 2)

              close(db, t)
            })
          })
        })
      })
    })
  })
})

test('removes two collections on four connecting via url', function (t) {
  getDB(function (err, db) {
    t.notOk(err, 'no error')

    db.createCollection('dummy1', function (err) {
      t.notOk(err, 'no error')

      db.createCollection('dummy2', function (err) {
        t.notOk(err, 'no error')

        db.createCollection('dummy3', function (err) {
          t.notOk(err, 'no error')

          db.close(function () {
            clean(url, {exclude: ['dummy1', 'dummy2']}, function (err, db) {
              t.notOk(err, 'no error')

              db.listCollections({}).toArray(function (err, collections) {
                t.notOk(err, 'no error')

                // there is only the system collection
                t.equal(collections.length, 3)

                close(db, t)
              })
            })
          })
        })
      })
    })
  })
})
<|endoftext|>


<commit_before>var dotest = require ('dotest');

var config = {
  timeout: process.env.APP_TIMEOUT
};

var app = require ('./');
var toonapi = app (config);

dotest.add ('Module interface', function (test) {
  var agreements = toonapi && toonapi.agreements;

  var consumption = toonapi && toonapi.consumption;
  var electricity = consumption && consumption.electricity;
  var districtheat = consumption && consumption.districtheat;
  var gas = consumption && consumption.gas;

  var devices = toonapi && toonapi.devices;
  var device = devices && devices.device;

  var display = toonapi && toonapi.display;
  var oauth = toonapi && toonapi.oauth;
  var pushEvent = toonapi && toonapi.pushEvent;

  var temperature = toonapi && toonapi.temperature;
  var states = temperature && temperature.states;

  test ()
    .isFunction ('fail', 'exports', app)
    .isObject ('fail', 'interface', toonapi)

    .isObject ('fail', '.agreements', agreements)
    .isFunction ('fail', '.agreements.list', agreements && agreements.list)
    .isFunction ('fail', '.agreements.update', agreements && agreements.update)

    .isObject ('fail', '.consumption', consumption)
    .isObject ('fail', '.consumption.electricity', electricity)
    .isFunction ('fail', '.consumption.electricity.data', electricity && electricity.data)
    .isFunction ('fail', '.consumption.electricity.flows', electricity && electricity.flows)
    .isObject ('fail', '.consumption.districtheat', districtheat)
    .isFunction ('fail', '.consumption.districtheat.data', districtheat && districtheat.data)
    .isObject ('fail', '.consumption.gas', gas)
    .isFunction ('fail', '.consumption.gas.data', gas && gas.data)
    .isFunction ('fail', '.consumption.gas.flows', gas && gas.flows)

    .isObject ('fail', '.devices', devices)
    .isObject ('fail', '.devices.device', device)
    .isFunction ('fail', '.devices.device.get', device && device.get)
    .isFunction ('fail', '.devices.device.update', device && device.update)
    .isFunction ('fail', '.devices.device.data', device && device.data)
    .isFunction ('fail', '.devices.device.flows', device && device.flows)
    .isFunction ('fail', '.devices.list', devices && devices.list)
    .isFunction ('fail', '.devices.update', devices && devices.update)

    .isObject ('fail', '.display', display)
    .isFunction ('fail', '.display', display && display.status)

    .isObject ('fail', '.oauth', oauth)
    .isFunction ('fail', '.oauth.getTokenFromCode', oauth && oauth.getTokenFromCode)
    .isFunction ('fail', '.oauth.getToken', oauth && oauth.getToken)
    .isFunction ('fail', '.oauth.refreshToken', oauth && oauth.refreshToken)
    .isFunction ('fail', '.oauth.revokeToken', oauth && oauth.revokeToken)

    .isObject ('fail', '.pushEvent', pushEvent)
    .isFunction ('fail', '.pushEvent.subscribe', pushEvent && pushEvent.subscribe)
    .isFunction ('fail', '.pushEvent.unsubscribe', pushEvent && pushEvent.unsubscribe)

    .isObject ('fail', '.temperature', temperature)
    .isObject ('fail', '.temperature.states', states)
    .isFunction ('fail', '.temperature.states.list', states && states.list)
    .isFunction ('fail', '.temperature.states.update', states && states.update)
    .isFunction ('fail', '.temperature.update', temperature && temperature.update)
    .done ();
});

dotest.add ('Error: API error', function (test) {
  toonapi.agreements.update ('-', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'API error')
      .isNumber ('fail', 'err.statusCode', err && err.statusCode)
      .isObject ('fail', 'err.error', err && err.error)
      .isNotEmpty ('fail', 'err.error', err && err.error)
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Error: timeout', function (test) {
  config.timeout = 1;
  toonapi = app (config);

  toonapi.agreements.list (function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.code', err && err.code, 'TIMEOUT')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.run ();
<commit_msg>Test(main): Added more env vars<commit_after>var dotest = require ('dotest');

var config = {
  accessToken: process.env.ACCESSTOKEN || null,
  clientId: process.env.CLIENT_ID || null,
  clientSecret: process.env.CLIENT_SECRET || null,
  redirectUri: process.env.REDIRECT_URI || null,
  timeout: process.env.TIMEOUT || null
};

var app = require ('./');
var toonapi = app (config);

dotest.add ('Module interface', function (test) {
  var agreements = toonapi && toonapi.agreements;

  var consumption = toonapi && toonapi.consumption;
  var electricity = consumption && consumption.electricity;
  var districtheat = consumption && consumption.districtheat;
  var gas = consumption && consumption.gas;

  var devices = toonapi && toonapi.devices;
  var device = devices && devices.device;

  var display = toonapi && toonapi.display;
  var oauth = toonapi && toonapi.oauth;
  var pushEvent = toonapi && toonapi.pushEvent;

  var temperature = toonapi && toonapi.temperature;
  var states = temperature && temperature.states;

  test ()
    .isFunction ('fail', 'exports', app)
    .isObject ('fail', 'interface', toonapi)

    .isObject ('fail', '.agreements', agreements)
    .isFunction ('fail', '.agreements.list', agreements && agreements.list)
    .isFunction ('fail', '.agreements.update', agreements && agreements.update)

    .isObject ('fail', '.consumption', consumption)
    .isObject ('fail', '.consumption.electricity', electricity)
    .isFunction ('fail', '.consumption.electricity.data', electricity && electricity.data)
    .isFunction ('fail', '.consumption.electricity.flows', electricity && electricity.flows)
    .isObject ('fail', '.consumption.districtheat', districtheat)
    .isFunction ('fail', '.consumption.districtheat.data', districtheat && districtheat.data)
    .isObject ('fail', '.consumption.gas', gas)
    .isFunction ('fail', '.consumption.gas.data', gas && gas.data)
    .isFunction ('fail', '.consumption.gas.flows', gas && gas.flows)

    .isObject ('fail', '.devices', devices)
    .isObject ('fail', '.devices.device', device)
    .isFunction ('fail', '.devices.device.get', device && device.get)
    .isFunction ('fail', '.devices.device.update', device && device.update)
    .isFunction ('fail', '.devices.device.data', device && device.data)
    .isFunction ('fail', '.devices.device.flows', device && device.flows)
    .isFunction ('fail', '.devices.list', devices && devices.list)
    .isFunction ('fail', '.devices.update', devices && devices.update)

    .isObject ('fail', '.display', display)
    .isFunction ('fail', '.display', display && display.status)

    .isObject ('fail', '.oauth', oauth)
    .isFunction ('fail', '.oauth.getTokenFromCode', oauth && oauth.getTokenFromCode)
    .isFunction ('fail', '.oauth.getToken', oauth && oauth.getToken)
    .isFunction ('fail', '.oauth.refreshToken', oauth && oauth.refreshToken)
    .isFunction ('fail', '.oauth.revokeToken', oauth && oauth.revokeToken)

    .isObject ('fail', '.pushEvent', pushEvent)
    .isFunction ('fail', '.pushEvent.subscribe', pushEvent && pushEvent.subscribe)
    .isFunction ('fail', '.pushEvent.unsubscribe', pushEvent && pushEvent.unsubscribe)

    .isObject ('fail', '.temperature', temperature)
    .isObject ('fail', '.temperature.states', states)
    .isFunction ('fail', '.temperature.states.list', states && states.list)
    .isFunction ('fail', '.temperature.states.update', states && states.update)
    .isFunction ('fail', '.temperature.update', temperature && temperature.update)
    .done ();
});

dotest.add ('Error: API error', function (test) {
  toonapi.agreements.update ('-', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'API error')
      .isNumber ('fail', 'err.statusCode', err && err.statusCode)
      .isObject ('fail', 'err.error', err && err.error)
      .isNotEmpty ('fail', 'err.error', err && err.error)
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Error: timeout', function (test) {
  config.timeout = 1;
  toonapi = app (config);

  toonapi.agreements.list (function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.code', err && err.code, 'TIMEOUT')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.run ();
<|endoftext|>


<commit_before>var assert = require('assert');

var deg = require('./deg.js');

function do_test (inp, dec, d, m, s) {
	var result = deg(inp),
		msg = '';

	msg = 'Decimal needed ' + dec + ' but got ' + result.decimal;
	assert.strictEqual(result.decimal, dec, msg);

	msg = 'Degrees needed ' + d + ' but got ' + result.degrees;
	assert.strictEqual(result.degrees, d, msg);

	msg = 'Minutes needed ' + m + ' but got ' + result.minutes;
	assert.strictEqual(result.minutes, m, msg);

	msg = 'Seconds needed ' + s + ' but got ' + result.seconds;
	assert.strictEqual(result.seconds, s, msg);
}

var tests = [
	[1, 2.0, 2, 0, 0.0],
	['2 30 6', 2.6, 2, 30, 6.0],
];

tests.forEach(function (parts, index) {
	do_test.apply(this, parts);
});
<commit_msg>Add test number to messages<commit_after>var assert = require('assert');

var deg = require('./deg.js');

function do_test (test_id, inp, dec, d, m, s) {
	var result = deg(inp),
		msg = '';

	test_id += 1;

	msg = 'Test ' + test_id + ' decimal needed ' + dec + ' but got ' + result.decimal;
	assert.strictEqual(result.decimal, dec, msg);

	msg = 'Test ' + test_id + ' degrees needed ' + d + ' but got ' + result.degrees;
	assert.strictEqual(result.degrees, d, msg);

	msg = 'Test ' + test_id + ' minutes needed ' + m + ' but got ' + result.minutes;
	assert.strictEqual(result.minutes, m, msg);

	msg = 'Test ' + test_id + ' seconds needed ' + s + ' but got ' + result.seconds;
	assert.strictEqual(result.seconds, s, msg);
}

var tests = [
	[1, 1.0, 1, 0, 0.0],
	['2 30 6', 2.6, 2, 30, 6.0],
];

tests.forEach(function (parts, index) {
	parts.unshift(index);
	do_test.apply(this, parts);
});
<|endoftext|>


<commit_before>import test from 'ava';
import webid from './dist/webid.cjs';

const DefaultOptions = {
	delimiter: '-',
	lower: true,
	maxLength: 128,
	remove: null,
};
const testStr = '1. László Čapek ♥ déjà vu in the Åland Islands';

test.beforeEach('reset options to default', () => {
	webid.configure();
});

test('uses default options when none are provided', (t) => {
	t.deepEqual(webid.options, DefaultOptions);
});

test('generates an id with defaults', (t) => {
	t.is(webid.generate(testStr), 'laszlo-capek-love-deja-vu-in-the-aland-islands');
});

test('sets a valid prefix', (t) => {
	webid.prefix = 'wid';
	t.is(webid.prefix, 'wid-');
	t.is(webid.generate(testStr), 'wid-laszlo-capek-love-deja-vu-in-the-aland-islands');
});

test('errors on prefix that doesn\'t begin with a letter', (t) => {
	const error = t.throws(() => {
		webid.prefix = '123';
	});
	t.is(error.message, 'prefix must begin with a letter (a-z).');
	t.is(error.name, 'Error');
});

test('errors on non-string prefix', (t) => {
	const error = t.throws(() => {
		webid.prefix = 123;
	});
	t.is(error.message, 'Expected a string. Received number.');
	t.is(error.name, 'TypeError');
});

test('sets a valid suffix', (t) => {
	webid.suffix = 'wid';
	t.is(webid.suffix, '-wid');
	t.is(webid.generate(testStr), 'laszlo-capek-love-deja-vu-in-the-aland-islands-wid');
});

test('sets a valid delimiter', (t) => {
	webid.delimiter = '_';
	t.is(webid.delimiter, '_');
	t.is(webid.generate(testStr), 'laszlo_capek_love_deja_vu_in_the_aland_islands');
});

test('sets an invalid delimiter', (t) => {
	const error = t.throws(() => {
		webid.delimiter = '🦄';
	});
	t.is(error.message, '🦄 is not a safe delimiter.');
});

test('adds a prefix and suffix via options', (t) => {
	const opts = {
		prefix: 'wid-pre',
		suffix: 'wid-suf',
	};
	t.is(webid.generate(testStr, opts), 'wid-pre-laszlo-capek-love-deja-vu-in-the-aland-islands-wid-suf');
});

test('generates a unique id every time', (t) => {
	const unique1 = webid.generateUnique(testStr);
	const unique2 = webid.generateUnique(testStr);
	t.not(unique1, unique2);
});

test('generate with options', (t) => {
	const unique = webid.generateUnique(testStr, {
		delimiter: '_',
	});
	t.is(unique.replace(/([\s\S]*?)(_)/g, '').length, 10);
});
<commit_msg>strict mode tests<commit_after>import test from 'ava';
import webid from './dist/webid.cjs';

/** @todo import this from ./src/constants.js once ava updates @babel/core */
const DefaultOptions = {
	delimiter: '-',
	lower: true,
	maxLength: 128,
	remove: null,
	strict: true,
};
const testStr = '1. László Čapek ♥ déjà vu in the Åland Islands';

test.beforeEach('reset options to default', () => {
	webid.configure();
});

test('uses default options when none are provided', (t) => {
	t.deepEqual(webid.options, DefaultOptions);
});

test('generates an id with defaults', (t) => {
	t.is(webid.generate(testStr), 'laszlo-capek-love-deja-vu-in-the-aland-islands');
});

test('generates an id in non-strict mode', (t) => {
	t.is(webid.generate(testStr, { strict: false }), '1.-laszlo-capek-love-deja-vu-in-the-aland-islands');
});

test('sets a valid prefix in strict mode', (t) => {
	webid.prefix = 'wid';
	t.is(webid.prefix, 'wid-');
	t.is(webid.generate(testStr), 'wid-laszlo-capek-love-deja-vu-in-the-aland-islands');
});

test('errors on prefix that doesn\'t begin with a letter in strict mode', (t) => {
	const error = t.throws(() => {
		webid.prefix = '123';
	});
	t.is(error.message, 'prefix must begin with a letter (a-z).');
	t.is(error.name, 'Error');
});

test('errors on non-string prefix', (t) => {
	const error = t.throws(() => {
		webid.prefix = 123;
	});
	t.is(error.message, 'Expected a string. Received number.');
	t.is(error.name, 'TypeError');
});

test('sets a valid suffix in strict mode', (t) => {
	webid.suffix = 'wid';
	t.is(webid.suffix, '-wid');
	t.is(webid.generate(testStr), 'laszlo-capek-love-deja-vu-in-the-aland-islands-wid');
});

test('sets a valid delimiter in strict mode', (t) => {
	webid.delimiter = '_';
	t.is(webid.delimiter, '_');
	t.is(webid.generate(testStr), 'laszlo_capek_love_deja_vu_in_the_aland_islands');
});

test('sets an invalid delimiter in strict mode', (t) => {
	const error = t.throws(() => {
		webid.delimiter = '🕺🏽';
	});
	t.is(error.message, '🕺🏽 is not a safe delimiter.');
});

test('sets a valid delimiter in non-strict mode', (t) => {
	webid.configure({
		strict: false,
		delimiter: '🕺🏽',
	});
	t.is(webid.delimiter, '🕺🏽');
	t.is(webid.generate(testStr), '1.🕺🏽laszlo🕺🏽capek🕺🏽love🕺🏽deja🕺🏽vu🕺🏽in🕺🏽the🕺🏽aland🕺🏽islands');
});

test('sets an invalid delimiter in non-strict mode', (t) => {
	webid.configure({ strict: false });
	const error = t.throws(() => {
		webid.delimiter = '\t';
	});
	t.is(error.message, 'The delimiter cannot be a space.');
});

test('adds a prefix and suffix via options', (t) => {
	const opts = {
		prefix: 'wid-pre',
		suffix: 'wid-suf',
	};
	t.is(webid.generate(testStr, opts), 'wid-pre-laszlo-capek-love-deja-vu-in-the-aland-islands-wid-suf');
});

test('generates a unique id every time', (t) => {
	const unique1 = webid.generateUnique(testStr);
	const unique2 = webid.generateUnique(testStr);
	t.not(unique1, unique2);
});

test('generate with options', (t) => {
	const unique = webid.generateUnique(testStr, {
		delimiter: '_',
	});
	t.is(unique.replace(/([\s\S]*?)(_)/g, '').length, 10);
});
<|endoftext|>


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

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

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

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

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


<commit_before>'use strict';

var assert = require('assert');
var expressPublicIp = require('./');

function createReq(socketAddr, headers) {
	return {
		connection: {
			remoteAddress: socketAddr
		},
		headers: headers || {}
	};
}

var privateAddresses = [
	'192.168.1.1',
	'172.30.16.189',
	'10.46.244.1',
	'127.0.0.1',
	'10.0.0.94',
	'172.16.2.236'
];

it('should filter private addresses', function () {
	privateAddresses.forEach(function (ip) {
		var req = createReq('127.0.0.1', {'x-forwarded-for': ip});
		expressPublicIp()(req, {}, function () {
			assert.equal(req.headers['x-forwarded-for'], '');
		});
	});
});
<commit_msg>Add positive test<commit_after>'use strict';

var assert = require('assert');
var expressPublicIp = require('./');

function createReq(socketAddr, headers) {
	return {
		connection: {
			remoteAddress: socketAddr
		},
		headers: headers || {}
	};
}

var privateAddresses = [
	'192.168.1.1',
	'172.30.16.189',
	'10.46.244.1',
	'127.0.0.1',
	'10.0.0.94',
	'172.16.2.236'
];

it('should filter private addresses', function () {
	privateAddresses.forEach(function (ip) {
		var req = createReq('127.0.0.1', {'x-forwarded-for': ip});
		expressPublicIp()(req, {}, function () {
			assert.equal(req.headers['x-forwarded-for'], '');
		});
	});
});

it('should keep public address', function () {
	var req = createReq('127.0.0.1', {'x-forwarded-for': '172.16.2.236, 1.3.3.7'});
	expressPublicIp()(req, {}, function () {
		assert.equal(req.headers['x-forwarded-for'], '1.3.3.7');
	});
});
<|endoftext|>


<commit_before>"hello"<commit_msg>Test 2<commit_after>"hello world"<|endoftext|>


<commit_before>var dotest = require ('dotest');
var app = require ('./');
var mfc;

var config = {
  hostname: process.env.MFC_HOSTNAME || null
};

mfc = app (config);

dotest.add ('Module', function () {
  dotest.test ()
    .isFunction ('fail', 'exports', app)
    .isObject ('fail', 'interface', mfc)
    .isFunction ('fail', '.current', mfc && mfc.current)
    .isFunction ('fail', '.sleep', mfc && mfc.sleep)
    .isObject ('fail', '.general', mfc && mfc.general)
    .isFunction ('fail', '.general.status', mfc && mfc.general && mfc.general.status)
    .isFunction ('fail', '.general.information', mfc && mfc.general && mfc.general.information)
    .done ();
});

dotest.add ('Method .current', function () {
  mfc.current (function (err, data) {
    dotest.test (err)
      .isObject ('fail', 'data', data)
      .isObject ('fail', 'data.ink', data && data.ink)
      .isDate ('fail', 'data.uptimeDate', data && data.uptimeDate)
      .isNumber ('fail', 'data.uptime', data && data.uptime)
      .isNumber ('fail', 'data.jobs', data && data.jobs)
      .isString ('fail', 'data.state', data && data.state)
      .isString ('fail', 'data.stateReasons', data && data.stateReasons)
      .done ();
  });
});

dotest.run ();

<commit_msg>Test: kill script when no hostname is set<commit_after>var dotest = require ('dotest');
var app = require ('./');
var mfc;

var config = {
  hostname: process.env.MFC_HOSTNAME || null
};

mfc = app (config);

dotest.add ('Module', function () {
  dotest.test ()
    .isFunction ('fail', 'exports', app)
    .isObject ('fail', 'interface', mfc)
    .isFunction ('fail', '.current', mfc && mfc.current)
    .isFunction ('fail', '.sleep', mfc && mfc.sleep)
    .isObject ('fail', '.general', mfc && mfc.general)
    .isFunction ('fail', '.general.status', mfc && mfc.general && mfc.general.status)
    .isFunction ('fail', '.general.information', mfc && mfc.general && mfc.general.information)
    .done ();
});

if (!config.hostname) {
  dotest.run ();
  dotest.log ('fail', 'MFC_HOSTNAME is required');
  process.exit ();
}

dotest.add ('Method .current', function () {
  mfc.current (function (err, data) {
    dotest.test (err)
      .isObject ('fail', 'data', data)
      .isObject ('fail', 'data.ink', data && data.ink)
      .isDate ('fail', 'data.uptimeDate', data && data.uptimeDate)
      .isNumber ('fail', 'data.uptime', data && data.uptime)
      .isNumber ('fail', 'data.jobs', data && data.jobs)
      .isString ('fail', 'data.state', data && data.state)
      .isString ('fail', 'data.stateReasons', data && data.stateReasons)
      .done ();
  });
});

dotest.run ();

<|endoftext|>


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

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

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

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

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