<commit_before>var util = require ('util');
/*
Name:           bolcom - test.js
Description:    Module for node.js to access Bol.com Open API service
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-bolcom
Feedback:       https://github.com/fvdm/nodejs-bolcom/issues
License:        Unlicense (Public Domain, see LICENSE file)
                (https://github.com/fvdm/nodejs-bolcom/raw/develop/LICENSE)
*/

// Setup
// set env BOLCOM_APIKEY  (Travis CI)
var bol = require ('./') (
  process.env.BOLCOM_APIKEY || null,
  process.env.BOLCOM_TIMEOUT || null
);

// handle exits
var errors = 0;
process.on ('exit', function () {
  if (errors === 0) {
    console.log ('\n\033[1mDONE, no errors.\033[0m\n');
    process.exit (0);
  } else {
    console.log ('\n\033[1mFAIL, '+ errors +' error'+ (errors > 1 ? 's' : '') +' occurred!\033[0m\n');
    process.exit (1);
  }
});

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

// Queue to prevent flooding
var queue = [];
var next = 0;

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

// doTest( passErr, 'methods', [
//   ['feeds', typeof feeds === 'object']
// ])
function doTest (err, label, tests) {
  if (err instanceof Error) {
    console.error (label +': \033[1m\033[31mERROR\033[0m\n');
    console.error (util.inspect (err, {depth: 10, colors: true}));
    console.log ();
    console.error (err.stack);
    console.log ();
    errors++;
  } else {
    var testErrors = [];
    tests.forEach (function (test) {
      if (test[1] !== true) {
        testErrors.push (test[0]);
        errors++;
      }
    });

    if (testErrors.length === 0) {
      console.log (label +': \033[1m\033[32mok\033[0m');
    } else {
      console.error (label +': \033[1m\033[31mfailed\033[0m ('+ testErrors.join (', ') +')');
    }
  }

  doNext ();
}

// API ACCESS
queue.push (function () {
  bol.utils.ping (function (err, data) {
		if (err) {
			console.log ('utils.ping: failed  ('+ err.message +')');
			console.log ();
			console.log (err.stack);
			errors++;
			process.exit (1);
		} else {
			console.log ('utils.ping: \033[1m\033[32mok\033[0m');
			doNext ();
		}
  });
});

queue.push (function () {
  bol.account.sessions (function (err, data) {
    doTest (err, 'account.sessions', [
      ['sessionId', typeof data.sessionId === 'string']
    ]);
  });
});

queue.push (function () {
  bol.catalog.search ({q: 'node.js', limit: 1, includeattributes:true}, function (err, data) {
    doTest (err, 'catalog.search', [
      ['totalResultSize', data.totalResultSize >= 1],
      ['products array', data.products instanceof Array],
      ['products length', data.products.length >= 1],
      ['item type', data.products [0] instanceof Object],
      ['item id', typeof data.products [0] .id === 'string'],
      ['item attributes', data.products [0] .attributeGroups instanceof Object]
    ]);
  });
});

queue.push (function () {
  bol.catalog.products ('9200000023292527', function (err, data) {
    doTest (err, 'catalog.products', [
      ['item type', data.products [0] instanceof Object],
      ['item id', typeof data.products [0] .id === 'string']
    ]);
  });
});

queue.push (function () {
  bol.catalog.products ('9200000009223738', function (err, data) {
    doTest (err, 'incomplete product', [
      ['item images', data.products [0] .images === undefined],
      ['item id', typeof data.products [0] .id === 'string']
    ]);
  });
});

queue.push (function () {
  bol.catalog.lists ('', function (err, data) {
    doTest (err, 'catalog.lists', [
      ['totalResultSize', data.totalResultSize >= 1],
      ['list type', data.products instanceof Array],
      ['item type', typeof data.products [0] .id === 'string']
    ]);
  });
});

queue.push (function () {
  bol.catalog.offers ('9200000023292527', function (err, data) {
    doTest (err, 'catalog.offers', [
      ['offers type', data.offers instanceof Array],
      ['item id', typeof data.offers [0] .id === 'string']
    ]);
  });
});

queue.push (function () {
  bol.catalog.recommendations ('9200000023292527', function (err, data) {
    doTest (err, 'catalog.recommendations', [
      ['products type', data instanceof Array],
      ['item id', typeof data [0] .id === 'string']
    ]);
  });
});

queue.push (function () {
  bol.catalog.relatedproducts ('9200000010839998', function (err, data) {
    doTest (err, 'catalog.relatedproducts', [
      ['type', data instanceof Object],
      ['group type', data.BINDINGCODE instanceof Object],
      ['items type', data.BINDINGCODE.productFamilyMembers instanceof Object],
      ['productId', typeof data.BINDINGCODE.productFamilyMembers.Ebook.productId === 'string']
    ]);
  });
});

// Start the tests
queue [0] ();
<commit_msg>Test: updated test runner<commit_after>/*
Name:           bolcom - test.js
Description:    Module for node.js to access Bol.com Open API service
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-bolcom
Feedback:       https://github.com/fvdm/nodejs-bolcom/issues
License:        Unlicense (Public Domain, see LICENSE file)
                (https://github.com/fvdm/nodejs-bolcom/raw/develop/LICENSE)
*/

// Setup
// set env BOLCOM_APIKEY  (Travis CI)
var bol = require ('./') (
  process.env.BOLCOM_APIKEY || null,
  process.env.BOLCOM_TIMEOUT || null
);

// handle exits
var errors = 0;
process.on ('exit', function () {
  if (errors === 0) {
    console.log ('\n\033[1mDONE, no errors.\033[0m\n');
    process.exit (0);
  } else {
    console.log ('\n\033[1mFAIL, '+ errors +' error'+ (errors > 1 ? 's' : '') +' occurred!\033[0m\n');
    process.exit (1);
  }
});

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

// Queue to prevent flooding
var queue = [];
var next = 0;

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

// doTest( passErr, 'methods', [
//   ['feeds', typeof feeds === 'object']
// ])
function doTest (err, label, tests) {
  if (err instanceof Error) {
    console.error ('\033[1m\033[31mERROR\033[0m - '+ label +'\n');
    console.dir (err, { depth: null, colors: true });
    console.log ();
    console.error (err.stack);
    console.log ();
    errors++;
  } else {
    var testErrors = [];
    for (var i = 0; i < tests.length; i++) {
      if (tests [i] [1] !== true) {
        testErrors.push (tests [i] [0]);
        errors++;
      }
    }

    if(testErrors.length === 0) {
      console.log ('\033[1m\033[32mgood\033[0m - '+ label);
    } else {
      console.error ('\033[1m\033[31mFAIL\033[0m - '+ label +' ('+ testErrors.join (', ') +')');
    }
  }

  doNext ();
}

// API ACCESS
queue.push (function () {
  bol.utils.ping (function (err, data) {
    if (err) {
      console.log ('\033[1m\033[31mFAIL\033[0m - API access ('+ err.message +')');
      console.log (err.stack);
      errors++;
      process.exit (1);
    } else {
      console.log ('\033[1m\033[32mgood\033[0m - API access');
      doNext ();
    }
  });
});

queue.push (function () {
  bol.account.sessions (function (err, data) {
    doTest (err, 'account.sessions', [
      ['sessionId', typeof data.sessionId === 'string']
    ]);
  });
});

queue.push (function () {
  bol.catalog.search ({q: 'node.js', limit: 1, includeattributes:true}, function (err, data) {
    doTest (err, 'catalog.search', [
      ['totalResultSize', data.totalResultSize >= 1],
      ['products array', data.products instanceof Array],
      ['products length', data.products.length >= 1],
      ['item type', data.products [0] instanceof Object],
      ['item id', typeof data.products [0] .id === 'string'],
      ['item attributes', data.products [0] .attributeGroups instanceof Object]
    ]);
  });
});

queue.push (function () {
  bol.catalog.products ('9200000023292527', function (err, data) {
    doTest (err, 'catalog.products', [
      ['item type', data.products [0] instanceof Object],
      ['item id', typeof data.products [0] .id === 'string']
    ]);
  });
});

queue.push (function () {
  bol.catalog.products ('9200000009223738', function (err, data) {
    doTest (err, 'incomplete product', [
      ['item images', data.products [0] .images === undefined],
      ['item id', typeof data.products [0] .id === 'string']
    ]);
  });
});

queue.push (function () {
  bol.catalog.lists ('', function (err, data) {
    doTest (err, 'catalog.lists', [
      ['totalResultSize', data.totalResultSize >= 1],
      ['list type', data.products instanceof Array],
      ['item type', typeof data.products [0] .id === 'string']
    ]);
  });
});

queue.push (function () {
  bol.catalog.offers ('9200000023292527', function (err, data) {
    doTest (err, 'catalog.offers', [
      ['offers type', data.offers instanceof Array],
      ['item id', typeof data.offers [0] .id === 'string']
    ]);
  });
});

queue.push (function () {
  bol.catalog.recommendations ('9200000023292527', function (err, data) {
    doTest (err, 'catalog.recommendations', [
      ['products type', data instanceof Array],
      ['item id', typeof data [0] .id === 'string']
    ]);
  });
});

queue.push (function () {
  bol.catalog.relatedproducts ('9200000010839998', function (err, data) {
    doTest (err, 'catalog.relatedproducts', [
      ['type', data instanceof Object],
      ['group type', data.BINDINGCODE instanceof Object],
      ['items type', data.BINDINGCODE.productFamilyMembers instanceof Object],
      ['productId', typeof data.BINDINGCODE.productFamilyMembers.Ebook.productId === 'string']
    ]);
  });
});

// Start the tests
queue [0] ();
<|endoftext|>


<commit_before>import test from 'tape';
import setupArticle from './lib';
import {element, string} from 'deku';

test('embed', t => {
  t.plan(2);

  const Article = setupArticle({
    embeds: {
      twitter: tweet => {
        t.equal(tweet.id, 'twitter-id');
        return ;
      }
    }
  });
  const items = [{
    type: 'embed',
    embedType: 'twitter',
    id: 'twitter-id'
  }];
  const expected = string.render(

);
  const actual = string.render(
);

  t.equal(actual, expected);

  t.end();
});

test('unknown embed', t => {
  t.plan(1);

  const Article = setupArticle({ embeds: {} });

  const items = [{
    type: 'embed',
    embedType: 'unknown-embed'
  }];
  const expected = string.render(

);
  const actual = string.render(
);

  t.equal(actual, expected);
  t.end();
});

test('text elements', t => {
  const Article = setupArticle({ embeds: {} });

  const items = [
    {
      type: 'paragraph',
      children: [{content: 'foo bar', type: 'text'}]
    }, {
      type: `header1`,
      children: [{content: 'beep boop1', type: 'text'}]
    }, {
      type: `header2`,
      children: [{content: 'beep boop2', type: 'text'}]
    }, {
      type: `header3`,
      children: [{content: 'beep boop3', type: 'text'}]
    }, {
      type: `header4`,
      children: [{content: 'beep boop4', type: 'text'}]
    }, {
      type: `header5`,
      children: [{content: 'beep boop5', type: 'text'}]
    }, {
      type: `header6`,
      children: [{content: 'beep boop6', type: 'text'}]
    }
  ];

  const actual = string.render(
);
  const expected = string.render(

foo bar

beep boop1

beep boop2

beep boop3

beep boop4

beep boop5

beep boop6

)

  t.equal(actual, expected);
  t.end();
});
<commit_msg>test text formattings<commit_after>import test from 'tape';
import setupArticle from './lib';
import {element, string} from 'deku';

test('embed', t => {
  t.plan(2);

  const Article = setupArticle({
    embeds: {
      twitter: tweet => {
        t.equal(tweet.id, 'twitter-id');
        return ;
      }
    }
  });
  const items = [{
    type: 'embed',
    embedType: 'twitter',
    id: 'twitter-id'
  }];
  const expected = string.render(

);
  const actual = string.render(
);

  t.equal(actual, expected);

  t.end();
});

test('unknown embed', t => {
  t.plan(1);

  const Article = setupArticle({ embeds: {} });

  const items = [{
    type: 'embed',
    embedType: 'unknown-embed'
  }];
  const expected = string.render(

);
  const actual = string.render(
);

  t.equal(actual, expected);
  t.end();
});

test('text elements', t => {
  const Article = setupArticle({ embeds: {} });

  const items = [
    {
      type: 'paragraph',
      children: [{content: 'foo bar', type: 'text'}]
    }, {
      type: `header1`,
      children: [{content: 'beep boop1', type: 'text'}]
    }, {
      type: `header2`,
      children: [{content: 'beep boop2', type: 'text'}]
    }, {
      type: `header3`,
      children: [{content: 'beep boop3', type: 'text'}]
    }, {
      type: `header4`,
      children: [{content: 'beep boop4', type: 'text'}]
    }, {
      type: `header5`,
      children: [{content: 'beep boop5', type: 'text'}]
    }, {
      type: `header6`,
      children: [{content: 'beep boop6', type: 'text'}]
    }
  ];

  const actual = string.render(
);
  const expected = string.render(

foo bar

beep boop1

beep boop2

beep boop3

beep boop4

beep boop5

beep boop6

)

  t.equal(actual, expected);
  t.end();
});

test('text', t => {
  const Article = setupArticle({embeds: {}});
  const items = [
    {
      type: 'paragraph',
      children: [
        {type: 'text', content: 'foo'},
        {type: 'text', content: 'foz', href: 'http://disney.com'},
        {type: 'text', content: 'fez', italic: true},
        {type: 'text', content: 'fiz', bold: true},
        {type: 'text', content: 'faz', italic: true, bold: true, href: 'http://mic.com'}
      ]
    }
  ];
  const actual = string.render(
);
  const expected = string.render(

      foo
      foz
      fez
      fiz
      faz

);

  t.equal(actual, expected);
  t.end();
});
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var stream = require('stream');
var http = require('http');
var url = require('url');
var fh = require('./index');
var Request = fh.Request;

fh.agent = false; // opt out of connection pooling - makes the tests fail

describe('flowHttp.Request', function () {
  it('should be a duplex stream', function () {
    assert(Request.prototype instanceof stream.Duplex, 'The Request object should be an instance of stream.Duplex');
  });
});

describe('request', function () {
  var req;

  before(function () {
    req = new Request(url.parse('http://example.com'));
  });

  it('should have the reqular http.ClientRequest methods', function () {
    assert.strictEqual(typeof req.setHeader, 'function');
    assert.strictEqual(typeof req.getHeader, 'function');
    assert.strictEqual(typeof req.removeHeader, 'function');
  });
});

describe('flowHttp module', function () {
  it('shoud be a function', function () {
    assert.strictEqual(typeof fh, 'function');
  });

  it('should have functions for each REST HTTP method', function () {
    assert.strictEqual(typeof fh.get, 'function');
    assert.strictEqual(typeof fh.post, 'function');
    assert.strictEqual(typeof fh.put, 'function');
    assert.strictEqual(typeof fh.del, 'function');
  });

  it('should alias fh as fh.get', function () {
    assert.strictEqual(fh, fh.get);
  });
});

describe('flowHttp', function () {
  var url = 'http://localhost:5000';
  var server;

  before(function (done) {
    server = http.createServer(function (req, res) {
      res.end('server response');
    });
    server.listen(5000, done);
  });

  after(function () {
    server.close();
  });

  it('should return instances of Request', function () {
    assert(fh.request(url) instanceof Request, '.request() should return an instance of Request');
    assert(fh(url) instanceof Request, 'Implicit GET should return an instance of Request');
    assert(fh.get(url) instanceof Request, 'Explicit GET should return an instance of Request');
    assert(fh.post(url) instanceof Request, 'POST should return an instance of Request');
    assert(fh.put(url) instanceof Request, 'PUT should return an instance of Request');
    assert(fh.del(url) instanceof Request, 'DELETE should return an instance of Request');
  });

  ['get', 'del'].forEach(function (method) {
    describe('fh.' + method, function () {
      var response = false;
      before(function (done) {
        var req = fh[method](url).on('response', function (res) {
          response = true;
          done();
        });
        setTimeout(function () {
          if (!response) done(new Error('the response event was never emitted'));
        }, 100);
      });

      it('should autimatically send the request', function () {
        assert.ok(response);
      });
    });
  });

  ['request', 'post', 'put'].forEach(function (method) {
    describe('fh.' + method, function () {
      before(function (done) {
        var req = fh[method](url).on('response', function () {
          done(new Error('the response event should not have been emitted'));
        });
        setTimeout(done, 100);
      });

      it('should not autimatically send the request', function () {
        assert(true);
      });
    });
  });

  ['get', 'del'].forEach(function (method) {
    describe('fh.' + method, function () {
      var data = false, end = false, body = '';

      before(function (done) {
        fh[method](url)
          .on('data', function (chunk) {
            body += chunk;
            data = true;
          })
          .on('end', function () {
            end = true;
            done();
          });
        setTimeout(function () {
          if (!end) done(new Error('the end event was never fired'));
        }, 100);
      });

      it('should emit a data event', function () {
        assert.ok(data);
      });

      it('should emit an end event', function () {
        assert.ok(end);
      });

      it('should get expected body', function () {
        assert.equal(body, 'server response');
      });
    });
  });

  ['post', 'put'].forEach(function (method) {
    describe('Write to fh.' + method, function () {
      var data = false, end = false, body = '';

      before(function (done) {
        var req = fh[method](url)
          .on('data', function (chunk) {
            body += chunk;
            data = true;
          })
          .on('end', function () {
            end = true;
            done();
          });
        req.end('sending data...');
        setTimeout(function () {
          if (!end) done(new Error('the end event was never fired'));
        }, 100);
      });

      it('should emit a data event', function () {
        assert.ok(data);
      });

      it('should emit an end event', function () {
        assert.ok(end);
      });

      it('should get expected body', function () {
        assert.equal(body, 'server response');
      });
    });

    describe('Pipe to fh.' + method, function () {
      var data = false, end = false, body = '';

      before(function (done) {
        var readableStream = require('fs').createReadStream(__filename);
        readableStream.pipe(fh[method](url))
          .on('data', function (chunk) {
            body += chunk;
            data = true;
          })
          .on('end', function () {
            end = true;
            done();
          });
        setTimeout(function () {
          if (!end) done(new Error('the end event was never fired'));
        }, 100);
      });

      it('should emit a data event', function () {
        assert.ok(data);
      });

      it('should emit an end event', function () {
        assert.ok(end);
      });

      it('should get expected body', function () {
        assert.equal(body, 'server response');
      });
    });
  });
});
<commit_msg>Add test for validation of http.ClientRequest<commit_after>'use strict';

var assert = require('assert');
var stream = require('stream');
var http = require('http');
var url = require('url');
var fh = require('./index');
var Request = fh.Request;

fh.agent = false; // opt out of connection pooling - makes the tests fail

describe('flowHttp.Request', function () {
  it('should be a duplex stream', function () {
    assert(Request.prototype instanceof stream.Duplex, 'The Request object should be an instance of stream.Duplex');
  });
});

describe('request', function () {
  var req;

  before(function () {
    req = new Request(url.parse('http://example.com'));
  });

  it('should have the original http.ClientRequest object', function () {
    assert(req.req instanceof http.ClientRequest);
  });

  it('should have the reqular http.ClientRequest methods', function () {
    assert.strictEqual(typeof req.setHeader, 'function');
    assert.strictEqual(typeof req.getHeader, 'function');
    assert.strictEqual(typeof req.removeHeader, 'function');
  });
});

describe('flowHttp module', function () {
  it('shoud be a function', function () {
    assert.strictEqual(typeof fh, 'function');
  });

  it('should have functions for each REST HTTP method', function () {
    assert.strictEqual(typeof fh.get, 'function');
    assert.strictEqual(typeof fh.post, 'function');
    assert.strictEqual(typeof fh.put, 'function');
    assert.strictEqual(typeof fh.del, 'function');
  });

  it('should alias fh as fh.get', function () {
    assert.strictEqual(fh, fh.get);
  });
});

describe('flowHttp', function () {
  var url = 'http://localhost:5000';
  var server;

  before(function (done) {
    server = http.createServer(function (req, res) {
      res.end('server response');
    });
    server.listen(5000, done);
  });

  after(function () {
    server.close();
  });

  it('should return instances of Request', function () {
    assert(fh.request(url) instanceof Request, '.request() should return an instance of Request');
    assert(fh(url) instanceof Request, 'Implicit GET should return an instance of Request');
    assert(fh.get(url) instanceof Request, 'Explicit GET should return an instance of Request');
    assert(fh.post(url) instanceof Request, 'POST should return an instance of Request');
    assert(fh.put(url) instanceof Request, 'PUT should return an instance of Request');
    assert(fh.del(url) instanceof Request, 'DELETE should return an instance of Request');
  });

  ['get', 'del'].forEach(function (method) {
    describe('fh.' + method, function () {
      var response = false;
      before(function (done) {
        var req = fh[method](url).on('response', function (res) {
          response = true;
          done();
        });
        setTimeout(function () {
          if (!response) done(new Error('the response event was never emitted'));
        }, 100);
      });

      it('should autimatically send the request', function () {
        assert.ok(response);
      });
    });
  });

  ['request', 'post', 'put'].forEach(function (method) {
    describe('fh.' + method, function () {
      before(function (done) {
        var req = fh[method](url).on('response', function () {
          done(new Error('the response event should not have been emitted'));
        });
        setTimeout(done, 100);
      });

      it('should not autimatically send the request', function () {
        assert(true);
      });
    });
  });

  ['get', 'del'].forEach(function (method) {
    describe('fh.' + method, function () {
      var data = false, end = false, body = '';

      before(function (done) {
        fh[method](url)
          .on('data', function (chunk) {
            body += chunk;
            data = true;
          })
          .on('end', function () {
            end = true;
            done();
          });
        setTimeout(function () {
          if (!end) done(new Error('the end event was never fired'));
        }, 100);
      });

      it('should emit a data event', function () {
        assert.ok(data);
      });

      it('should emit an end event', function () {
        assert.ok(end);
      });

      it('should get expected body', function () {
        assert.equal(body, 'server response');
      });
    });
  });

  ['post', 'put'].forEach(function (method) {
    describe('Write to fh.' + method, function () {
      var data = false, end = false, body = '';

      before(function (done) {
        var req = fh[method](url)
          .on('data', function (chunk) {
            body += chunk;
            data = true;
          })
          .on('end', function () {
            end = true;
            done();
          });
        req.end('sending data...');
        setTimeout(function () {
          if (!end) done(new Error('the end event was never fired'));
        }, 100);
      });

      it('should emit a data event', function () {
        assert.ok(data);
      });

      it('should emit an end event', function () {
        assert.ok(end);
      });

      it('should get expected body', function () {
        assert.equal(body, 'server response');
      });
    });

    describe('Pipe to fh.' + method, function () {
      var data = false, end = false, body = '';

      before(function (done) {
        var readableStream = require('fs').createReadStream(__filename);
        readableStream.pipe(fh[method](url))
          .on('data', function (chunk) {
            body += chunk;
            data = true;
          })
          .on('end', function () {
            end = true;
            done();
          });
        setTimeout(function () {
          if (!end) done(new Error('the end event was never fired'));
        }, 100);
      });

      it('should emit a data event', function () {
        assert.ok(data);
      });

      it('should emit an end event', function () {
        assert.ok(end);
      });

      it('should get expected body', function () {
        assert.equal(body, 'server response');
      });
    });
  });
});
<|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-17 10:55:28<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 _format = require('./')
const test = require('ava')

const identity = (x) => x

const identityFormatter = {
  punctuation: identity,
  property: identity,
  literal: identity,
  number: identity,
  string: identity
}

const format = (obj, depth, offset) =>
  _format(obj, depth, identityFormatter, offset)

test('literals', (t) => {
  t.true(format({ obj: true }).includes('true'))
  t.true(format({ obj: false }).includes('false'))
  t.true(format({ obj: null }).includes('null'))
  t.true(format({ obj: undefined }).includes('undefined'))
})<commit_msg>add tests<commit_after>
const _format = require('./')
const test = require('ava')

const identity = (x) => x

const identityFormatter = {
  punctuation: identity,
  property: identity,
  literal: identity,
  number: identity,
  string: identity
}

const format = (obj, depth, offset) =>
  _format(obj, depth, identityFormatter, offset)

test('literals', (t) => {
  t.true(format({ val: true }).includes('true'))
  t.true(format({ val: false }).includes('false'))
  t.true(format({ val: null }).includes('null'))
  t.true(format({ val: undefined }).includes('undefined'))
})

test('strings', (t) => {
   t.true(format({ val: 'hello world' }).includes('"hello world"'))
})

test('numbers', (t) => {
  t.true(format({ val: 12 }).includes('12'))
  t.true(format({ val: 12e10 }).includes('120000000000'))
  t.true(format({ val: -200 }).includes('-200'))
  t.true(format({ val: Infinity }).includes('Infinity'))
})

test('functions', (t) => {
  const normalFn = format({ helloWorld: () => {} })
  t.true(normalFn.includes('[Function helloWorld]'))

  const genFn = format({ helloWorld: function *() {} })
  t.true(genFn.includes('[GeneratorFunction helloWorld]'))
})

test('depth', (t) => {
  const actual = {
    a: {
      b: true,
      c: {
        d: true
      }
    }
  }

  const fmtNoDepth = format(actual, 0)
  t.true(fmtNoDepth.includes('(collapsed)'))
  t.false(fmtNoDepth.includes('b: true'))
  t.false(fmtNoDepth.includes('d: true'))

  const fmtOneLevel = format(actual, 1)
  t.true(fmtOneLevel.includes('(collapsed)'))
  t.true(fmtOneLevel.includes('b: true'))
  t.false(fmtOneLevel.includes('d: true'))
})
<|endoftext|>


<commit_before>var data = [
    {Date: "2015-06-12", HighTemperature: 17, LowTemperature: 10, Rainfall: 1.4, HighWindGust:52, HighWindGustBearing: 236},
    {Date: "2015-06-13", HighTemperature: 16, LowTemperature: 13, Rainfall: 0, HighWindGust: 41,HighWindGustBearing: 240},
    {Date: "2015-06-14", HighTemperature: 16, LowTemperature: 12, Rainfall: 2.4, HighWindGust: 41,HighWindGustBearing: 233},
    {Date: "2015-06-15", HighTemperature: 16, LowTemperature: 10, Rainfall: 8.4, HighWindGust: 40,HighWindGustBearing: 261},
    {Date: "2015-06-16", HighTemperature: 12, LowTemperature: 4, Rainfall: 1, HighWindGust: 36,HighWindGustBearing: 229},
    {Date: "2015-06-17", HighTemperature: 14, LowTemperature: 4, Rainfall: 0, HighWindGust: 10,HighWindGustBearing: 74},
    {Date: "2015-06-18", HighTemperature: 15, LowTemperature: 11, Rainfall: 0, HighWindGust: 24,HighWindGustBearing: 321},
    {Date: "2015-06-19", HighTemperature: 18, LowTemperature: 12, Rainfall: 0, HighWindGust: 35, HighWindGustBearing: 340},
    {Date: "2015-06-20", HighTemperature: 17, LowTemperature: 15, Rainfall: 9.6, HighWindGust: 36, HighWindGustBearing: 302},
    {Date: "2015-06-21", HighTemperature: 15, LowTemperature: 9, Rainfall: 0.2, HighWindGust: 33, HighWindGustBearing: 238},
    {Date: "2015-06-22", HighTemperature: 14, LowTemperature: 4, Rainfall: 0.4, HighWindGust: 31, HighWindGustBearing: 218},
    {Date: "2015-06-23", HighTemperature: 11, LowTemperature: 1, Rainfall: 0, HighWindGust: 26, HighWindGustBearing: 222},
    {Date: "2015-06-24", HighTemperature: 11, LowTemperature: 0, Rainfall: 0, HighWindGust: 31, HighWindGustBearing: 213},
    {Date: "2015-06-25", HighTemperature: 13, LowTemperature: 4, Rainfall: 0, HighWindGust: 43, HighWindGustBearing: 241},
    {Date: "2015-06-26", HighTemperature: 16, LowTemperature: 9, Rainfall: 0.4, HighWindGust: 40, HighWindGustBearing: 230},
    {Date: "2015-06-27", HighTemperature: 15, LowTemperature: 10, Rainfall: 2.4, HighWindGust: 43, HighWindGustBearing: 250},
    {Date: "2015-06-28", HighTemperature: 16, LowTemperature: 9, Rainfall: 0.6, HighWindGust: 31, HighWindGustBearing: 240},
    {Date: "2015-06-29", HighTemperature: 16, LowTemperature: 10, Rainfall: 1.2, HighWindGust: 45, HighWindGustBearing: 250},
    {Date: "2015-06-30", HighTemperature: 16, LowTemperature: 11, Rainfall: 1.8, HighWindGust: 38, HighWindGustBearing: 228},
    {Date: "2015-07-01", HighTemperature: 16, LowTemperature: 9, Rainfall: 0.8, HighWindGust: 47, HighWindGustBearing: 250},
    {Date: "2015-07-02", HighTemperature: 14, LowTemperature: 7, Rainfall: 0.2, HighWindGust: 12, HighWindGustBearing :47},
    {Date: "2015-07-03", HighTemperature: 16, LowTemperature: 7, Rainfall: 1.2, HighWindGust: 29, HighWindGustBearing: 65},
    {Date: "2015-07-04", HighTemperature: 16, LowTemperature: 12, Rainfall: 5.6, HighWindGust: 22, HighWindGustBearing: 107},
    {Date: "2015-07-05", HighTemperature: 15, LowTemperature: 11, Rainfall: 0.2, HighWindGust: 47, HighWindGustBearing: 248},
    {Date: "2015-07-06", HighTemperature: 16, LowTemperature: 10, Rainfall: 1.8, HighWindGust: 28, HighWindGustBearing: 312},
    {Date: "2015-07-07", HighTemperature: 17, LowTemperature: 11, Rainfall: 41.4, HighWindGust: 33, HighWindGustBearing: 330},
    {Date: "2015-07-08", HighTemperature: 12, LowTemperature: 3, Rainfall: 0.8, HighWindGust: 31, HighWindGustBearing: 214},
    {Date: "2015-07-09", HighTemperature: 10, LowTemperature: 3, Rainfall: 0, HighWindGust: 45, HighWindGustBearing: 225},
    {Date: "2015-07-10", HighTemperature: 10, LowTemperature: 0, Rainfall: 0, HighWindGust: 28, HighWindGustBearing: 215},
    {Date: "2015-07-11", HighTemperature: 12, LowTemperature: 0, Rainfall: 0, HighWindGust: 33, HighWindGustBearing: 150}
];

var graph = new DailyWeatherGraph({

    data: data,
    container: d3.select('#test'),
    width: 900,
    height: 450,
    dateFormat: '%Y-%m-%d',
    units: 'metric',
    missingValue: -100,
    missingValueText: 'n/a',

});
<commit_msg>Remove invalid config property<commit_after>var data = [
    {Date: "2015-06-12", HighTemperature: 17, LowTemperature: 10, Rainfall: 1.4, HighWindGust:52, HighWindGustBearing: 236},
    {Date: "2015-06-13", HighTemperature: 16, LowTemperature: 13, Rainfall: 0, HighWindGust: 41,HighWindGustBearing: 240},
    {Date: "2015-06-14", HighTemperature: 16, LowTemperature: 12, Rainfall: 2.4, HighWindGust: 41,HighWindGustBearing: 233},
    {Date: "2015-06-15", HighTemperature: 16, LowTemperature: 10, Rainfall: 8.4, HighWindGust: 40,HighWindGustBearing: 261},
    {Date: "2015-06-16", HighTemperature: 12, LowTemperature: 4, Rainfall: 1, HighWindGust: 36,HighWindGustBearing: 229},
    {Date: "2015-06-17", HighTemperature: 14, LowTemperature: 4, Rainfall: 0, HighWindGust: 10,HighWindGustBearing: 74},
    {Date: "2015-06-18", HighTemperature: 15, LowTemperature: 11, Rainfall: 0, HighWindGust: 24,HighWindGustBearing: 321},
    {Date: "2015-06-19", HighTemperature: 18, LowTemperature: 12, Rainfall: 0, HighWindGust: 35, HighWindGustBearing: 340},
    {Date: "2015-06-20", HighTemperature: 17, LowTemperature: 15, Rainfall: 9.6, HighWindGust: 36, HighWindGustBearing: 302},
    {Date: "2015-06-21", HighTemperature: 15, LowTemperature: 9, Rainfall: 0.2, HighWindGust: 33, HighWindGustBearing: 238},
    {Date: "2015-06-22", HighTemperature: 14, LowTemperature: 4, Rainfall: 0.4, HighWindGust: 31, HighWindGustBearing: 218},
    {Date: "2015-06-23", HighTemperature: 11, LowTemperature: 1, Rainfall: 0, HighWindGust: 26, HighWindGustBearing: 222},
    {Date: "2015-06-24", HighTemperature: 11, LowTemperature: 0, Rainfall: 0, HighWindGust: 31, HighWindGustBearing: 213},
    {Date: "2015-06-25", HighTemperature: 13, LowTemperature: 4, Rainfall: 0, HighWindGust: 43, HighWindGustBearing: 241},
    {Date: "2015-06-26", HighTemperature: 16, LowTemperature: 9, Rainfall: 0.4, HighWindGust: 40, HighWindGustBearing: 230},
    {Date: "2015-06-27", HighTemperature: 15, LowTemperature: 10, Rainfall: 2.4, HighWindGust: 43, HighWindGustBearing: 250},
    {Date: "2015-06-28", HighTemperature: 16, LowTemperature: 9, Rainfall: 0.6, HighWindGust: 31, HighWindGustBearing: 240},
    {Date: "2015-06-29", HighTemperature: 16, LowTemperature: 10, Rainfall: 1.2, HighWindGust: 45, HighWindGustBearing: 250},
    {Date: "2015-06-30", HighTemperature: 16, LowTemperature: 11, Rainfall: 1.8, HighWindGust: 38, HighWindGustBearing: 228},
    {Date: "2015-07-01", HighTemperature: 16, LowTemperature: 9, Rainfall: 0.8, HighWindGust: 47, HighWindGustBearing: 250},
    {Date: "2015-07-02", HighTemperature: 14, LowTemperature: 7, Rainfall: 0.2, HighWindGust: 12, HighWindGustBearing :47},
    {Date: "2015-07-03", HighTemperature: 16, LowTemperature: 7, Rainfall: 1.2, HighWindGust: 29, HighWindGustBearing: 65},
    {Date: "2015-07-04", HighTemperature: 16, LowTemperature: 12, Rainfall: 5.6, HighWindGust: 22, HighWindGustBearing: 107},
    {Date: "2015-07-05", HighTemperature: 15, LowTemperature: 11, Rainfall: 0.2, HighWindGust: 47, HighWindGustBearing: 248},
    {Date: "2015-07-06", HighTemperature: 16, LowTemperature: 10, Rainfall: 1.8, HighWindGust: 28, HighWindGustBearing: 312},
    {Date: "2015-07-07", HighTemperature: 17, LowTemperature: 11, Rainfall: 41.4, HighWindGust: 33, HighWindGustBearing: 330},
    {Date: "2015-07-08", HighTemperature: 12, LowTemperature: 3, Rainfall: 0.8, HighWindGust: 31, HighWindGustBearing: 214},
    {Date: "2015-07-09", HighTemperature: 10, LowTemperature: 3, Rainfall: 0, HighWindGust: 45, HighWindGustBearing: 225},
    {Date: "2015-07-10", HighTemperature: 10, LowTemperature: 0, Rainfall: 0, HighWindGust: 28, HighWindGustBearing: 215},
    {Date: "2015-07-11", HighTemperature: 12, LowTemperature: 0, Rainfall: 0, HighWindGust: 33, HighWindGustBearing: 150}
];

var graph = new DailyWeatherGraph({

    data: data,
    container: d3.select('#test'),
    width: 900,
    height: 450,
    dateFormat: '%Y-%m-%d',
    missingValue: -100,
    missingValueText: 'n/a',

});
<|endoftext|>


<commit_before>!function(root) {
  function contains(str, needle) {
    return !!~str.indexOf(needle);
  }

  var common = typeof module != 'undefined' && !!module.exports
  var aok = common ? require('aok') : root.aok
  var eol = common ? require('./') : root.eol
  var isWindows = typeof process != 'undefined' && 'win32' === process.platform
  var meths = ['lf', 'cr', 'crlf', 'auto']
  var chars = ['\n', '\r', '\r\n', isWindows ? '\r\n' : '\n']
  var sample = ' ' + chars.join() + 'text' + chars.join()

  aok.prototype.fail = function() {
    throw new Error('FAILED TEST: ' + this.id)
  }

  aok('contains() sees contained text', contains('ab', 'a') === true)
  aok('sample contains newlines', contains(sample, '\n') && contains(sample, '\r'))
  aok('returns other strings as is', eol.auto('random') === 'random')
  aok('returns empty strings as is', eol.auto('') === '')
  aok('whitespace intact', eol.lf(' \t ') === ' \t ')
  aok('repeat newlines intact lf', eol.lf('\n\n\r\r') === '\n\n\n\n')
  aok('repeat newlines intact cr', eol.cr('\n\n\r\r') === '\r\r\r\r')
  aok('repeat newlines intact crlf', eol.crlf('\r\n\r\n') === '\r\n\r\n')

  aok.pass(meths, function(method, i) {
    var normalized = eol[method](sample)
    aok(method + ' retains', contains(normalized, chars[i]))
    aok(method + ' normalizes', !aok.fail(chars, function(c) {
      return contains(chars[i], c) === contains(normalized, c)
    }))

    return eol.auto(sample) === normalized
  })

  aok('auto is aware', eol[isWindows ? 'crlf' : 'lf'](sample) === eol.auto(sample))
  aok('auto matches only 1 and self', aok.pass(meths, function(method) {
    return eol.auto(sample) === eol[method](sample);
  }) === 2)

  aok.log('All tests passed =)')
}(this);
<commit_msg>reword repeat tests<commit_after>!function(root) {
  function contains(str, needle) {
    return !!~str.indexOf(needle);
  }

  var common = typeof module != 'undefined' && !!module.exports
  var aok = common ? require('aok') : root.aok
  var eol = common ? require('./') : root.eol
  var isWindows = typeof process != 'undefined' && 'win32' === process.platform
  var meths = ['lf', 'cr', 'crlf', 'auto']
  var chars = ['\n', '\r', '\r\n', isWindows ? '\r\n' : '\n']
  var sample = ' ' + chars.join() + 'text' + chars.join()

  aok.prototype.fail = function() {
    throw new Error('FAILED TEST: ' + this.id)
  }

  aok('contains() sees contained text', contains('ab', 'a') === true)
  aok('sample contains newlines', contains(sample, '\n') && contains(sample, '\r'))
  aok('returns other strings as is', eol.auto('random') === 'random')
  aok('returns empty strings as is', eol.auto('') === '')
  aok('whitespace intact', eol.lf(' \t ') === ' \t ')
  aok('lf repeat newlines intact', eol.lf('\n\n\r\r') === '\n\n\n\n')
  aok('cr repeat newlines intact', eol.cr('\n\n\r\r') === '\r\r\r\r')
  aok('crlf repeat newlines intact', eol.crlf('\r\n\r\n') === '\r\n\r\n')

  aok.pass(meths, function(method, i) {
    var normalized = eol[method](sample)
    aok(method + ' retains', contains(normalized, chars[i]))
    aok(method + ' normalizes', !aok.fail(chars, function(c) {
      return contains(chars[i], c) === contains(normalized, c)
    }))

    return eol.auto(sample) === normalized
  })

  aok('auto is aware', eol[isWindows ? 'crlf' : 'lf'](sample) === eol.auto(sample))
  aok('auto matches only 1 and self', aok.pass(meths, function(method) {
    return eol.auto(sample) === eol[method](sample);
  }) === 2)

  aok.log('All tests passed =)')
}(this);
<|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-17 09:34:28<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 Inform = require('./index');

var inform = new Inform();

inform.on('notification', function(notification) {

notification.readTitle( function(title) {
	notification.readMessage( function(message) {
		console("Notification: " + notification);
	});
});

});<commit_msg>silly error<commit_after>var Inform = require('./index');

var inform = new Inform();

inform.on('notification', function(notification) {

notification.readTitle( function(title) {
	notification.readMessage( function(message) {
		console.log("Notification: " + notification);
	});
});

});<|endoftext|>


<commit_before>var test = require('tape');
var multilinestring = require('./')

test('point', function(t){
  t.deepEqual(multilinestring([[[0,0],[10,10]], [[5,0],[15,8]]]), {
    "type": "Feature",
    "properties": {},
    "geometry": {
      "type": "MultiLineString",
      "coordinates": [[[0,0],[10,10]], [[5,0],[15,8]]]
    }
  }, 'takes coordinates');

  t.deepEqual(multilinestring([[[0,0],[10,10]], [[5,0],[15,8]]], {test: 23}), {
    "type": "Feature",
    "properties": {
      test: 23
    },
    "geometry": {
      "type": "MultiLineString",
      "coordinates": [[[0,0],[10,10]], [[5,0],[15,8]]]
    }
  }, 'takes properties');

  t.throws(function(err){
    multilinestring();
  }, 'throws error with no coordinates');

  t.end();
});
<commit_msg>v1.0.0<commit_after>var test = require('tape');
var multilinestring = require('./')

test('multilinestring', function(t){
  t.deepEqual(multilinestring([[[0,0],[10,10]], [[5,0],[15,8]]]), {
    "type": "Feature",
    "properties": {},
    "geometry": {
      "type": "MultiLineString",
      "coordinates": [[[0,0],[10,10]], [[5,0],[15,8]]]
    }
  }, 'takes coordinates');

  t.deepEqual(multilinestring([[[0,0],[10,10]], [[5,0],[15,8]]], {test: 23}), {
    "type": "Feature",
    "properties": {
      test: 23
    },
    "geometry": {
      "type": "MultiLineString",
      "coordinates": [[[0,0],[10,10]], [[5,0],[15,8]]]
    }
  }, 'takes properties');

  t.throws(function(err){
    multilinestring();
  }, 'throws error with no coordinates');

  t.end();
});
<|endoftext|>


<commit_before>/////////////////
// Test script //
/////////////////

earhorn$(this, 'phoria.js', function() {

   var canvas = document.getElementById('canvas');

   var scene = new Phoria.Scene();
   scene.camera.position = {x:0.0, y:2.0, z:-6.0};
   scene.perspective.aspect = canvas.width / canvas.height;
   scene.viewport.width = canvas.width;
   scene.viewport.height = canvas.height;

   var renderer = new Phoria.CanvasRenderer(canvas);

   var c = Phoria.Util.generateUnitCube();
   var cube = Phoria.Entity.create({
      points: c.points,
      edges: c.edges,
      polygons: c.polygons,
      style: {
        color: [0, 0, 0],
        linewidth: 3,
        drawmode: 'wireframe'
      }
   });
   scene.graph.push(cube);
   scene.graph.push(new Phoria.DistantLight());

   var fnAnimate = function() {

     cube.rotateY(0.01);

     // Phoria uses this matrix of elements to render the cube
     cube.matrix[0]
     cube.matrix[1]
     cube.matrix[2]

     scene.modelView();
     renderer.render(scene);

     requestAnimationFrame(fnAnimate);
   };

   console.log(cube);

   requestAnimationFrame(fnAnimate);
})

<commit_msg>Add polyfill for request animation from.<commit_after>/////////////////
// Test script //
/////////////////

earhorn$(this, 'phoria.js', function() {

  var requestAnimationFrame =
    window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(c) { window.setTimeout(c, 15) }

   var canvas = document.getElementById('canvas');

   var scene = new Phoria.Scene();
   scene.camera.position = {x:0.0, y:2.0, z:-6.0};
   scene.perspective.aspect = canvas.width / canvas.height;
   scene.viewport.width = canvas.width;
   scene.viewport.height = canvas.height;

   var renderer = new Phoria.CanvasRenderer(canvas);

   var c = Phoria.Util.generateUnitCube();
   var cube = Phoria.Entity.create({
      points: c.points,
      edges: c.edges,
      polygons: c.polygons,
      style: {
        color: [0, 0, 0],
        linewidth: 3,
        drawmode: 'wireframe'
      }
   });
   scene.graph.push(cube);
   scene.graph.push(new Phoria.DistantLight());

   function animate() {

     cube.rotateY(0.01);

     // Phoria uses this matrix of elements to render the cube
     cube.matrix[0]
     cube.matrix[1]
     cube.matrix[2]

     scene.modelView();
     renderer.render(scene);

     requestAnimationFrame(animate);
   }

   requestAnimationFrame(animate);
})

<|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-12-3 21:48: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>var sinon = require('sinon');
var chai = require('chai');

var should = chai.should();
chai.Assertion.includeStack = true;
chai.use(require('sinon-chai'));

var bddflow = require('./dist/bdd-flow');
var Bddflow = bddflow.Bddflow;
var requireComponent = bddflow.require;

requireComponent('sinon-doublist')(sinon, 'mocha');

describe('bddflow', function() {
  describe('Bddflow', function() {
    beforeEach(function() {
      this.bddflow = new Bddflow();
      this.bddflow
        .set('nativeRequire', require)
        .init();

      this.resOK = {code: 0};
    });

    it('should do something', function() {
      console.log('\x1B[33m<---------- INCOMPLETE');
    });
  });
});
<commit_msg>Add legacy test using updated API<commit_after>var sinon = require('sinon');
var chai = require('chai');

var should = chai.should();
chai.Assertion.includeStack = true;
chai.use(require('sinon-chai'));

var bddflow = require('./dist/bdd-flow');
var Bddflow = bddflow.Bddflow;

describe('bddflow', function() {
  it('should follow correct execution order', function(testDone) {
    function initDescribe() {
      this.before(function(done) { log.call(this, 'fb'); done(); });
      this.after(function(done) { log.call(this, 'fa'); actualOrder = this.shared; done(); });
      this.beforeEach(function(done) { log.call(this, 'fbe'); done(); });
      this.afterEach(function(done) { log.call(this, 'fae'); done(); });
      this.it('fi1', function(testDone) { log.call(this, 'fi1'); testDone(); });
      this.it('fi2', function(testDone) { log.call(this, 'fi2'); testDone(); });
      this.describe('d1', function() {
        this.before(function(done) { log.call(this, 'd1b'); done(); });
        this.after(function(done) { log.call(this, 'd1a'); done(); });
        this.beforeEach(function(done) { log.call(this, 'd1be'); done(); });
        this.afterEach(function(done) { log.call(this, 'd1ae'); done(); });
        this.it('d1i1', function(testDone) { log.call(this, 'd1i1'); testDone(); });
        this.it('d1i2', function(testDone) { log.call(this, 'd1i2'); testDone(); });
        this.describe('d1a', function() {
          this.it('d1ai1', function(testDone) { log.call(this, 'd1ai1'); testDone(); });
        });
      });
    }

    function done() {
      actualOrder.should.deep.equal(expectedOrder);
      testDone();
    }

    function log(loc) {
      this.shared = this.shared || [];
      this.shared.push(loc);
    }

    var expectedOrder = [
      'fb',
      'fbe',
      'fi1',
      'fae',
      'fbe',
      'fi2',
      'fae',
      'd1b',
      'd1be',
      'd1i1',
      'd1ae',
      'd1be',
      'd1i2',
      'd1ae',
      'd1ai1',
      'd1a',
      'fa'
    ];
    var actualOrder;

    var flow = new Bddflow();
    flow
      .set('name', 'f')
      .set('done', done)
      .set('initDescribe', initDescribe)
      .run();
  });
});
<|endoftext|>


<commit_before>var tape = require("tape")
var async = require("async")
var Router = require("./router")
var JSONFileStorage = require("./storage/jsonfile")
var path = require("path")
var http = require("http")
var from2 = require("from2-string")
var hyperquest = require("hyperquest")
var hyperrequest = require("hyperrequest")
var concat = require("concat-stream")

var jenca_user_id = "banana-man"
var testing_port = 8060
var subject_project_index = 5

/*

  boot a test server for each test so the state from one
  does not affect another test

*/
function createServer(done){
  var router = Router({})
  var server = http.createServer(router.handler)
  server.listen(testing_port, function(err){
    done(err, server)
  })
}

/*

  make a list of N projects

*/
function getProjectData(count){

  count = count || 10;

  var projectData = []
  for(i=1;i<=count;i++){
    projectData.push({
      name:"Testing Project "+i
    })
  }
  return projectData
}

/*

  post 10 projects to the test server
  return an array of the 10 projects as they exist on the server

*/
function populateData(projects, done){
  var projectData = []
  /*

    map the array of names onto an array of functions
    that will POST a project with that name

  */
  var createFunctions = projects.map(function(data){

    /*

      this is the async function that will run via async.series

    */
    return function(next){
      hyperrequest({
        url: "http://127.0.0.1:"+ testing_port +"/v1/projects",
        method: "POST",
        json: data,
        headers: {
            "x-jenca-user":jenca_user_id
        }
      }, function(err, resp){

        // always return errors so parent code is notified
        if(err) return next(err.toString())

        projectData.push(resp.body)

        next()
      })
    }
  })

  /*

    run over the project creation
    return the array of returned project data

  */
  async.series(createFunctions, function(err){
    if(err) return done(err)
    done(null, projectData)
  })
}

/*
  Test that the version of the module returns the correct string
*/
tape("GET /v1/version", function (t) {

  var config = require(path.join(__dirname, "package.json"))
  var server;

  async.series([

    // create the server
    function(next){
      createServer(function(err, s){
        if(err) return next(err)
        server = s
        next()
      })
    },

    // read the version from the API
    function(next){
      var req = hyperquest("http://127.0.0.1:"+testing_port+"/v1/version", {
        method:"GET",
        headers:{
          "x-jenca-user":jenca_user_id
        }
      })

      var destStream = concat(function(result){

        t.equal(result.toString(), config.version.toString(), "the version is correct")

        next()
      })

      req.pipe(destStream)

      req.on("response", function(res){
        t.equal(res.statusCode, 200, "The status code == 200")
      })

      req.on("error", function(err){
        next(err.toString())
      })
    },
  ], function(err){
    if(err){
      t.error(err)
      server.close()
      t.end()
      return
    }
    server.close()
    t.end()
  })

})

/*

  Query the api to check the projects we have saved are actually there

*/

tape("GET /v1/projects", function (t) {

  var projects;
  var server;

  async.series([

    // create the server
    function(next){
      createServer(function(err, s){
        if(err) return next(err)
        server = s
        next()
      })
    },

    // populate some projects
    function(next){
      var rawData = getProjectData(10)
      populateData(rawData, function(err, projectsReturned){
        if(err) return next(err)
        projects = projectsReturned;
        next()
      })
    },

    // test the length of projects matches
    function(next){
      hyperrequest({
        "url":"http://127.0.0.1:"+ testing_port +"/v1/projects",
        method:"GET",
        headers:{
          "x-jenca-user":jenca_user_id
        }
      }, function(err, resp){
        if(err) return next(err)
        t.equal(resp.statusCode, 200, "The status code == 200")
        t.equal(resp.body.length, projects.length, "the number of projects matches")

        next()
      })

    },
  ], function(err){
    if(err){
      t.error(err)
      server.close()
      t.end()
      return
    }
    server.close()
    t.end()
  })

})

/*

  seed the system with projects and retrieve one to check it's attributes

*/
tape("GET /v1/projects/:projectid", function (t) {

  var server;
  async.series([

    // create the server
    function(next){
      createServer(function(err, s){
        if(err) return next(err)
        server = s
        next()
      })
    },

    // populate some projects
    function(next){
      var rawData = getProjectData(10)
      populateData(rawData, function(err, projectsReturned){
        if(err) return next(err)
        projects = projectsReturned;
        next()
      })
    },

    // get a single project
    function(next){

      hyperrequest({
        "url": "http://127.0.0.1:"+testing_port+"/v1/projects/"+ projects[subject_project_index].id,
        method:"GET",
        headers:{
          "x-jenca-user":jenca_user_id
        }
      }, function(err, resp){
        if(err) return subnext(err)

        t.equal(resp.statusCode, 200, "The status code == 200")
        t.equal(resp.body.name, projects[subject_project_index].name, "the requested project's name matches")

        next()
      })
    }
  ], function(err){
    if(err){
      t.error(err)
      server.close()
      t.end()
      return
    }
    server.close()
    t.end()
  })

})

/*

  seed the system with projects and update one with known data to check it is updated

*/
tape("PUT /v1/projects/:projectid", function (t) {

  var projects;
  var server;

  async.series([

    // create the server
    function(next){
      createServer(function(err, s){
        if(err) return next(err)
        server = s
        next()
      })
    },

    // populate some projects
    function(next){
      var rawData = getProjectData(10)
      populateData(rawData, function(err, projectsReturned){
        if(err) return next(err)
        projects = projectsReturned;
        next()
      })
    },

    function(next){

      projects[subject_project_index].name = "A totally different name"

      var req = hyperrequest({
        "url":"http://127.0.0.1:"+testing_port+"/v1/projects/"+ projects[subject_project_index].id,
        method:"PUT",
        json:projects[subject_project_index],
        headers:{
          "x-jenca-user":jenca_user_id
        }
      }, function(err, resp){
        if(err) return subnext(err)

        t.equal(resp.statusCode, 200, "The status code == 200")
        t.equal(resp.body.name, projects[subject_project_index].name, "the requested project's name matches")

        next()
      });

    },

    function(next){
      var req = hyperrequest({
        "url":"http://127.0.0.1:"+testing_port+"/v1/projects/"+ projects[subject_project_index].id,
        method:"GET",
        headers:{
          "x-jenca-user":jenca_user_id
        }
      }, function(err, resp){
        if(err) return subnext(err)

        t.equal(resp.statusCode, 200, "The status code == 200")
        t.equal(resp.body.name, projects[subject_project_index].name, "the requested project's name matches")

        next()
      });

    }
  ], function(err){
    if(err){
      t.error(err)
      server.close()
      t.end()
      return
    }
    server.close()
    t.end()
  })

})

// seed the system with projects and delete one
tape("DELETE /v1/projects/:projectid", function (t) {

  var projects;
  var server;

  async.series([

    // create the server
    function(next){
      createServer(function(err, s){
        if(err) return next(err)
        server = s
        next()
      })
    },

    // populate some projects
    function(next){
      var rawData = getProjectData(10)
      populateData(rawData, function(err, projectsReturned){
        if(err) return next(err)
        projects = projectsReturned;
        next()
      })
    },

    function(next){

      var req = hyperrequest({
        "url":"http://127.0.0.1:"+testing_port+"/v1/projects/"+ projects[subject_project_index].id,
        method:"DELETE",
        headers:{
          "x-jenca-user":jenca_user_id
        }
      }, function(err, resp){
        if(err) return subnext(err)

        t.equal(resp.statusCode, 200, "The status code == 200")
        next()
      });

    },

    function(next){
      hyperrequest({
        "url":"http://127.0.0.1:"+ testing_port +"/v1/projects",
        method:"GET",
        headers:{
          "x-jenca-user":jenca_user_id
        }
      }, function(err, resp){
        if(err) return next(err)

        t.equal(resp.statusCode, 200, "The status code == 200")
        t.equal(resp.body.length, (projects.length-1), "the number of projects is less one")

        next()
      })

    }
  ], function(err){
    if(err){
      t.error(err)
      server.close()
      t.end()
      return
    }
    server.close()
    t.end()
  })

})

/*

  unit test for the storage mechanism

*/
tape("jsonfile: create project", function(t){

  // create a project
  storage.create_project(jenca_user_id, {
    apples:10
  }, function(err){
    if(err) t.err(err.toString())
    var state = storage.get_state()

    var project_keys = Object.keys(state.users[jenca_user_id].projects)
    t.equal(project_keys.length, (projects.length+1), "there are "+ (projects.length+1)+" projects")

    var project_id = project_keys.pop()
    var project = state.users[jenca_user_id].projects[project_id]

    t.equal(project.apples, 10, "the project setting is set")
    t.deepEqual(project.containers, [], "there is an empty list of containers")

    t.end()
    server.close()
  })
})<commit_msg>update the unit test for storage now we have isolated the storage object from the rest of the tests<commit_after>var tape = require("tape")
var async = require("async")
var Router = require("./router")
var JSONFileStorage = require("./storage/jsonfile")
var path = require("path")
var http = require("http")
var from2 = require("from2-string")
var hyperquest = require("hyperquest")
var hyperrequest = require("hyperrequest")
var concat = require("concat-stream")

var jenca_user_id = "banana-man"
var testing_port = 8060
var subject_project_index = 5

/*

  boot a test server for each test so the state from one
  does not affect another test

*/
function createServer(done){

  // keep the storage in memory for the tests
  var router = Router({
    memory:true
  })
  var server = http.createServer(router.handler)
  server.listen(testing_port, function(err){
    done(err, server)
  })
}

/*

  make a list of N projects

*/
function getProjectData(count){

  count = count || 10;

  var projectData = []
  for(i=1;i<=count;i++){
    projectData.push({
      name:"Testing Project "+i
    })
  }
  return projectData
}

/*

  post 10 projects to the test server
  return an array of the 10 projects as they exist on the server

*/
function populateData(projects, done){
  var projectData = []
  /*

    map the array of names onto an array of functions
    that will POST a project with that name

  */
  var createFunctions = projects.map(function(data){

    /*

      this is the async function that will run via async.series

    */
    return function(next){
      hyperrequest({
        url: "http://127.0.0.1:"+ testing_port +"/v1/projects",
        method: "POST",
        json: data,
        headers: {
            "x-jenca-user":jenca_user_id
        }
      }, function(err, resp){

        // always return errors so parent code is notified
        if(err) return next(err.toString())

        projectData.push(resp.body)

        next()
      })
    }
  })

  /*

    run over the project creation
    return the array of returned project data

  */
  async.series(createFunctions, function(err){
    if(err) return done(err)
    done(null, projectData)
  })
}

/*
  Test that the version of the module returns the correct string
*/
tape("GET /v1/version", function (t) {

  var config = require(path.join(__dirname, "package.json"))
  var server;

  async.series([

    // create the server
    function(next){
      createServer(function(err, s){
        if(err) return next(err)
        server = s
        next()
      })
    },

    // read the version from the API
    function(next){
      var req = hyperquest("http://127.0.0.1:"+testing_port+"/v1/version", {
        method:"GET",
        headers:{
          "x-jenca-user":jenca_user_id
        }
      })

      var destStream = concat(function(result){

        t.equal(result.toString(), config.version.toString(), "the version is correct")

        next()
      })

      req.pipe(destStream)

      req.on("response", function(res){
        t.equal(res.statusCode, 200, "The status code == 200")
      })

      req.on("error", function(err){
        next(err.toString())
      })
    },
  ], function(err){
    if(err){
      t.error(err)
      server.close()
      t.end()
      return
    }
    server.close()
    t.end()
  })

})

/*

  Query the api to check the projects we have saved are actually there

*/

tape("GET /v1/projects", function (t) {

  var projects;
  var server;

  async.series([

    // create the server
    function(next){
      createServer(function(err, s){
        if(err) return next(err)
        server = s
        next()
      })
    },

    // populate some projects
    function(next){
      var rawData = getProjectData(10)
      populateData(rawData, function(err, projectsReturned){
        if(err) return next(err)
        projects = projectsReturned;
        next()
      })
    },

    // test the length of projects matches
    function(next){
      hyperrequest({
        "url":"http://127.0.0.1:"+ testing_port +"/v1/projects",
        method:"GET",
        headers:{
          "x-jenca-user":jenca_user_id
        }
      }, function(err, resp){
        if(err) return next(err)
        t.equal(resp.statusCode, 200, "The status code == 200")
        t.equal(resp.body.length, projects.length, "the number of projects matches")

        next()
      })

    },
  ], function(err){
    if(err){
      t.error(err)
      server.close()
      t.end()
      return
    }
    server.close()
    t.end()
  })

})

/*

  seed the system with projects and retrieve one to check it's attributes

*/
tape("GET /v1/projects/:projectid", function (t) {

  var server;
  async.series([

    // create the server
    function(next){
      createServer(function(err, s){
        if(err) return next(err)
        server = s
        next()
      })
    },

    // populate some projects
    function(next){
      var rawData = getProjectData(10)
      populateData(rawData, function(err, projectsReturned){
        if(err) return next(err)
        projects = projectsReturned;
        next()
      })
    },

    // get a single project
    function(next){

      hyperrequest({
        "url": "http://127.0.0.1:"+testing_port+"/v1/projects/"+ projects[subject_project_index].id,
        method:"GET",
        headers:{
          "x-jenca-user":jenca_user_id
        }
      }, function(err, resp){
        if(err) return subnext(err)

        t.equal(resp.statusCode, 200, "The status code == 200")
        t.equal(resp.body.name, projects[subject_project_index].name, "the requested project's name matches")

        next()
      })
    }
  ], function(err){
    if(err){
      t.error(err)
      server.close()
      t.end()
      return
    }
    server.close()
    t.end()
  })

})

/*

  seed the system with projects and update one with known data to check it is updated

*/
tape("PUT /v1/projects/:projectid", function (t) {

  var projects;
  var server;

  async.series([

    // create the server
    function(next){
      createServer(function(err, s){
        if(err) return next(err)
        server = s
        next()
      })
    },

    // populate some projects
    function(next){
      var rawData = getProjectData(10)
      populateData(rawData, function(err, projectsReturned){
        if(err) return next(err)
        projects = projectsReturned;
        next()
      })
    },

    function(next){

      projects[subject_project_index].name = "A totally different name"

      var req = hyperrequest({
        "url":"http://127.0.0.1:"+testing_port+"/v1/projects/"+ projects[subject_project_index].id,
        method:"PUT",
        json:projects[subject_project_index],
        headers:{
          "x-jenca-user":jenca_user_id
        }
      }, function(err, resp){
        if(err) return subnext(err)

        t.equal(resp.statusCode, 200, "The status code == 200")
        t.equal(resp.body.name, projects[subject_project_index].name, "the requested project's name matches")

        next()
      });

    },

    function(next){
      var req = hyperrequest({
        "url":"http://127.0.0.1:"+testing_port+"/v1/projects/"+ projects[subject_project_index].id,
        method:"GET",
        headers:{
          "x-jenca-user":jenca_user_id
        }
      }, function(err, resp){
        if(err) return subnext(err)

        t.equal(resp.statusCode, 200, "The status code == 200")
        t.equal(resp.body.name, projects[subject_project_index].name, "the requested project's name matches")

        next()
      });

    }
  ], function(err){
    if(err){
      t.error(err)
      server.close()
      t.end()
      return
    }
    server.close()
    t.end()
  })

})

// seed the system with projects and delete one
tape("DELETE /v1/projects/:projectid", function (t) {

  var projects;
  var server;

  async.series([

    // create the server
    function(next){
      createServer(function(err, s){
        if(err) return next(err)
        server = s
        next()
      })
    },

    // populate some projects
    function(next){
      var rawData = getProjectData(10)
      populateData(rawData, function(err, projectsReturned){
        if(err) return next(err)
        projects = projectsReturned;
        next()
      })
    },

    function(next){

      var req = hyperrequest({
        "url":"http://127.0.0.1:"+testing_port+"/v1/projects/"+ projects[subject_project_index].id,
        method:"DELETE",
        headers:{
          "x-jenca-user":jenca_user_id
        }
      }, function(err, resp){
        if(err) return subnext(err)

        t.equal(resp.statusCode, 200, "The status code == 200")
        next()
      });

    },

    function(next){
      hyperrequest({
        "url":"http://127.0.0.1:"+ testing_port +"/v1/projects",
        method:"GET",
        headers:{
          "x-jenca-user":jenca_user_id
        }
      }, function(err, resp){
        if(err) return next(err)

        t.equal(resp.statusCode, 200, "The status code == 200")
        t.equal(resp.body.length, (projects.length-1), "the number of projects is less one")

        next()
      })

    }
  ], function(err){
    if(err){
      t.error(err)
      server.close()
      t.end()
      return
    }
    server.close()
    t.end()
  })

})

/*

  unit test for the storage mechanism

*/
tape("jsonfile: create project", function(t){

  var storage = JSONFileStorage({
    memory:true
  })

  // create a project
  storage.create_project(jenca_user_id, {
    apples:10
  }, function(err){
    if(err) t.err(err.toString())
    var state = storage.get_state()

    var project_keys = Object.keys(state.users[jenca_user_id].projects)
    t.equal(project_keys.length, 1, "there is 1 project")

    var project_id = project_keys.pop()
    var project = state.users[jenca_user_id].projects[project_id]

    t.equal(project.apples, 10, "the project setting is set")
    t.deepEqual(project.containers, [], "there is an empty list of containers")

    t.end()
  })
})<|endoftext|>


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

const {
  DomTransformer,
  TRANSFORMATIONS_AMP_FIRST,
  TRANSFORMATIONS_PAIRED_AMP,
  DEFAULT_CONFIG,
} = require('./lib/DomTransformer.js');

module.exports = {
  create: (config=DEFAULT_CONFIG) => new DomTransformer(config),
  TRANSFORMATIONS_AMP_FIRST,
  TRANSFORMATIONS_PAIRED_AMP,
  DEFAULT_CONFIG,
};
<commit_msg>export NodeUtils<commit_after>/**
 * Copyright 2017 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

const {
  DomTransformer,
  TRANSFORMATIONS_AMP_FIRST,
  TRANSFORMATIONS_PAIRED_AMP,
  DEFAULT_CONFIG,
} = require('./lib/DomTransformer.js');
const NodeUtils = require('./lib/NodeUtils.js');

module.exports = {
  create: (config=DEFAULT_CONFIG) => new DomTransformer(config),
  TRANSFORMATIONS_AMP_FIRST,
  TRANSFORMATIONS_PAIRED_AMP,
  DEFAULT_CONFIG,
  NodeUtils,
};
<|endoftext|>


<commit_before>//
//  CSVParser.js
//  Mr-Data-Converter
//
//  Input CSV or Tab-delimited data and this will parse it into a Data Grid Javascript object
//
//  CSV Parsing Function from Ben Nadel, http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm

var CSVParser = {

  //---------------------------------------
  // UTILS
  //---------------------------------------

  isNumber: function(string) {
    if( (string == null) || isNaN( new Number(string) ) ) {
      return false;
    }
    return true;
  },

  //---------------------------------------
  // PARSE
  //---------------------------------------
  //var parseOutput = CSVParser.parse(this.inputText, this.headersProvided, this.delimiter, this.downcaseHeaders, this.upcaseHeaders);

  parse: function (input, headersIncluded, delimiterType, downcaseHeaders, upcaseHeaders) {

    var dataArray = [];

    var errors = [];

    //test for delimiter
    //count the number of commas
    var RE = new RegExp("[^,]", "gi");
    var numCommas = input.replace(RE, "").length;

    //count the number of tabs
    RE = new RegExp("[^\t]", "gi");
    var numTabs = input.replace(RE, "").length;

    var rowDelimiter = "\n";
    //set delimiter
    var columnDelimiter = ",";
    if (numTabs > numCommas) {
      columnDelimiter = "\t"
    };

    if (delimiterType === "comma") {
      columnDelimiter = ","
    } else if (delimiterType === "tab") {
      columnDelimiter = "\t"
    }

    // kill extra empty lines
    RE = new RegExp("^" + rowDelimiter + "+", "gi");
    input = input.replace(RE, "");
    RE = new RegExp(rowDelimiter + "+$", "gi");
    input = input.replace(RE, "");

    // var arr = input.split(rowDelimiter);
    //
    // for (var i=0; i < arr.length; i++) {
    //   dataArray.push(arr[i].split(columnDelimiter));
    // };

    // dataArray = jQuery.csv(columnDelimiter)(input);
    dataArray = this.CSVToArray(input, columnDelimiter);

    //escape out any tabs or returns or new lines
    for (var i = dataArray.length - 1; i >= 0; i--){
      for (var j = dataArray[i].length - 1; j >= 0; j--){
        dataArray[i][j] = dataArray[i][j].replace("\t", "\\t");
        dataArray[i][j] = dataArray[i][j].replace("\n", "\\n");
        dataArray[i][j] = dataArray[i][j].replace("\r", "\\r");
      };
    };

    var headerNames = [];
    var headerTypes = [];
    var numColumns = dataArray[0].length;
    var numRows = dataArray.length;
    if (headersIncluded) {

      //remove header row
      headerNames = dataArray.splice(0,1)[0];
      numRows = dataArray.length;

    } else { //if no headerNames provided

      //create generic property names
      for (var i=0; i < numColumns; i++) {
        headerNames.push("val"+String(i));
        headerTypes.push("");
      };

    }

    if (upcaseHeaders) {
      for (var i = headerNames.length - 1; i >= 0; i--){
        headerNames[i] = headerNames[i].toUpperCase();
      };
    };
    if (downcaseHeaders) {
      for (var i = headerNames.length - 1; i >= 0; i--){
        headerNames[i] = headerNames[i].toLowerCase();
      };
    };

    //test all the rows for proper number of columns.
    for (var i=0; i < dataArray.length; i++) {
      var numValues = dataArray[i].length;
      if (numValues != numColumns) {this.log("Error parsing row "+String(i)+". Wrong number of columns.")};
    };

    //test columns for number data type
    var numRowsToTest = numColumns;
    var threshold = 0.5;
    for (var i=0; i < headerNames.length; i++) {
      var numFloats = 0;
      var numInts = 0;
      for (var r=0; r < numRowsToTest; r++) {
        if (dataArray[r]) {
          if (CSVParser.isNumber(dataArray[r][i])) {
            numInts++
            if (String(dataArray[r][i]).indexOf(".") > 0) {
              numFloats++
            }
          };
        };

      };

      if ((numInts / numRowsToTest) > threshold){
        if (numFloats > 0) {
          headerTypes[i] = "float"
        } else {
          headerTypes[i] = "int"
        }
      } else {
        headerTypes[i] = "string"
      }
    }

    return {'dataGrid':dataArray, 'headerNames':headerNames, 'headerTypes':headerTypes, 'errors':this.getLog()}

  },

  //---------------------------------------
  // ERROR LOGGING
  //---------------------------------------
  errorLog:[],

  resetLog: function() {
    this.errorLog = [];
  },

  log: function(l) {
    this.errorLog.push(l);
  },

  getLog: function() {
    var out = "";
    if (this.errorLog.length > 0) {
      for (var i=0; i < this.errorLog.length; i++) {
        out += ("!!"+this.errorLog[i] + "!!\n");
      };
      out += "\n"
    };

    return out;
  },

  //---------------------------------------
  // UTIL
  //---------------------------------------

    // This Function from Ben Nadel, http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
    // This will parse a delimited string into an array of
    // arrays. The default delimiter is the comma, but this
    // can be overriden in the second argument.
    CSVToArray: function( strData, strDelimiter ){
      // Check to see if the delimiter is defined. If not,
      // then default to comma.
      strDelimiter = (strDelimiter || ",");

      // Create a regular expression to parse the CSV values.
      var objPattern = new RegExp(
        (
          // Delimiters.
          "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

          // Quoted fields.
          "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

          // Standard fields.
          "([^\"\\" + strDelimiter + "\\r\\n]*))"
        ),
        "gi"
        );

      // Create an array to hold our data. Give the array
      // a default empty first row.
      var arrData = [[]];

      // Create an array to hold our individual pattern
      // matching groups.
      var arrMatches = null;

      // Keep looping over the regular expression matches
      // until we can no longer find a match.
      while (arrMatches = objPattern.exec( strData )){

        // Get the delimiter that was found.
        var strMatchedDelimiter = arrMatches[ 1 ];

        // Check to see if the given delimiter has a length
        // (is not the start of string) and if it matches
        // field delimiter. If id does not, then we know
        // that this delimiter is a row delimiter.
        if (
          strMatchedDelimiter.length &&
          (strMatchedDelimiter != strDelimiter)
          ){

          // Since we have reached a new row of data,
          // add an empty row to our data array.
          arrData.push( [] );

        }

        // Now that we have our delimiter out of the way,
        // let's check to see which kind of value we
        // captured (quoted or unquoted).
        if (arrMatches[ 2 ]){

          // We found a quoted value. When we capture
          // this value, unescape any double quotes.
          var strMatchedValue = arrMatches[ 2 ].replace(
            new RegExp( "\"\"", "g" ),
            "\""
            );

        } else {

          // We found a non-quoted value.
          var strMatchedValue = arrMatches[ 3 ];

        }

        // Now that we have our value string, let's add
        // it to the data array.
        arrData[ arrData.length - 1 ].push( strMatchedValue );
      }

      // Return the parsed data.
      return( arrData );
    }

}<commit_msg>more rigorous testing of nums<commit_after>//
//  CSVParser.js
//  Mr-Data-Converter
//
//  Input CSV or Tab-delimited data and this will parse it into a Data Grid Javascript object
//
//  CSV Parsing Function from Ben Nadel, http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm

var CSVParser = {

  //---------------------------------------
  // UTILS
  //---------------------------------------

  isNumber: function(string) {
    if( (string == null) || isNaN( new Number(string) ) ) {
      return false;
    }
    return true;
  },

  //---------------------------------------
  // PARSE
  //---------------------------------------
  //var parseOutput = CSVParser.parse(this.inputText, this.headersProvided, this.delimiter, this.downcaseHeaders, this.upcaseHeaders);

  parse: function (input, headersIncluded, delimiterType, downcaseHeaders, upcaseHeaders) {

    var dataArray = [];

    var errors = [];

    //test for delimiter
    //count the number of commas
    var RE = new RegExp("[^,]", "gi");
    var numCommas = input.replace(RE, "").length;

    //count the number of tabs
    RE = new RegExp("[^\t]", "gi");
    var numTabs = input.replace(RE, "").length;

    var rowDelimiter = "\n";
    //set delimiter
    var columnDelimiter = ",";
    if (numTabs > numCommas) {
      columnDelimiter = "\t"
    };

    if (delimiterType === "comma") {
      columnDelimiter = ","
    } else if (delimiterType === "tab") {
      columnDelimiter = "\t"
    }

    // kill extra empty lines
    RE = new RegExp("^" + rowDelimiter + "+", "gi");
    input = input.replace(RE, "");
    RE = new RegExp(rowDelimiter + "+$", "gi");
    input = input.replace(RE, "");

    // var arr = input.split(rowDelimiter);
    //
    // for (var i=0; i < arr.length; i++) {
    //   dataArray.push(arr[i].split(columnDelimiter));
    // };

    // dataArray = jQuery.csv(columnDelimiter)(input);
    dataArray = this.CSVToArray(input, columnDelimiter);

    //escape out any tabs or returns or new lines
    for (var i = dataArray.length - 1; i >= 0; i--){
      for (var j = dataArray[i].length - 1; j >= 0; j--){
        dataArray[i][j] = dataArray[i][j].replace("\t", "\\t");
        dataArray[i][j] = dataArray[i][j].replace("\n", "\\n");
        dataArray[i][j] = dataArray[i][j].replace("\r", "\\r");
      };
    };

    var headerNames = [];
    var headerTypes = [];
    var numColumns = dataArray[0].length;
    var numRows = dataArray.length;
    if (headersIncluded) {

      //remove header row
      headerNames = dataArray.splice(0,1)[0];
      numRows = dataArray.length;

    } else { //if no headerNames provided

      //create generic property names
      for (var i=0; i < numColumns; i++) {
        headerNames.push("val"+String(i));
        headerTypes.push("");
      };

    }

    if (upcaseHeaders) {
      for (var i = headerNames.length - 1; i >= 0; i--){
        headerNames[i] = headerNames[i].toUpperCase();
      };
    };
    if (downcaseHeaders) {
      for (var i = headerNames.length - 1; i >= 0; i--){
        headerNames[i] = headerNames[i].toLowerCase();
      };
    };

    //test all the rows for proper number of columns.
    for (var i=0; i < dataArray.length; i++) {
      var numValues = dataArray[i].length;
      if (numValues != numColumns) {this.log("Error parsing row "+String(i)+". Wrong number of columns.")};
    };

    //test columns for number data type
    var numRowsToTest = dataArray.length;
    var threshold = 0.9;
    for (var i=0; i < headerNames.length; i++) {
      var numFloats = 0;
      var numInts = 0;
      for (var r=0; r < numRowsToTest; r++) {
        if (dataArray[r]) {
          if (CSVParser.isNumber(dataArray[r][i])) {
            numInts++
            if (String(dataArray[r][i]).indexOf(".") > 0) {
              numFloats++
            }
          };
        };

      };

      if ((numInts / numRowsToTest) > threshold){
        if (numFloats > 0) {
          headerTypes[i] = "float"
        } else {
          headerTypes[i] = "int"
        }
      } else {
        headerTypes[i] = "string"
      }
    }

    return {'dataGrid':dataArray, 'headerNames':headerNames, 'headerTypes':headerTypes, 'errors':this.getLog()}

  },

  //---------------------------------------
  // ERROR LOGGING
  //---------------------------------------
  errorLog:[],

  resetLog: function() {
    this.errorLog = [];
  },

  log: function(l) {
    this.errorLog.push(l);
  },

  getLog: function() {
    var out = "";
    if (this.errorLog.length > 0) {
      for (var i=0; i < this.errorLog.length; i++) {
        out += ("!!"+this.errorLog[i] + "!!\n");
      };
      out += "\n"
    };

    return out;
  },

  //---------------------------------------
  // UTIL
  //---------------------------------------

    // This Function from Ben Nadel, http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-Javascript-Exec-Regular-Expression-Command.htm
    // This will parse a delimited string into an array of
    // arrays. The default delimiter is the comma, but this
    // can be overriden in the second argument.
    CSVToArray: function( strData, strDelimiter ){
      // Check to see if the delimiter is defined. If not,
      // then default to comma.
      strDelimiter = (strDelimiter || ",");

      // Create a regular expression to parse the CSV values.
      var objPattern = new RegExp(
        (
          // Delimiters.
          "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +

          // Quoted fields.
          "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +

          // Standard fields.
          "([^\"\\" + strDelimiter + "\\r\\n]*))"
        ),
        "gi"
        );

      // Create an array to hold our data. Give the array
      // a default empty first row.
      var arrData = [[]];

      // Create an array to hold our individual pattern
      // matching groups.
      var arrMatches = null;

      // Keep looping over the regular expression matches
      // until we can no longer find a match.
      while (arrMatches = objPattern.exec( strData )){

        // Get the delimiter that was found.
        var strMatchedDelimiter = arrMatches[ 1 ];

        // Check to see if the given delimiter has a length
        // (is not the start of string) and if it matches
        // field delimiter. If id does not, then we know
        // that this delimiter is a row delimiter.
        if (
          strMatchedDelimiter.length &&
          (strMatchedDelimiter != strDelimiter)
          ){

          // Since we have reached a new row of data,
          // add an empty row to our data array.
          arrData.push( [] );

        }

        // Now that we have our delimiter out of the way,
        // let's check to see which kind of value we
        // captured (quoted or unquoted).
        if (arrMatches[ 2 ]){

          // We found a quoted value. When we capture
          // this value, unescape any double quotes.
          var strMatchedValue = arrMatches[ 2 ].replace(
            new RegExp( "\"\"", "g" ),
            "\""
            );

        } else {

          // We found a non-quoted value.
          var strMatchedValue = arrMatches[ 3 ];

        }

        // Now that we have our value string, let's add
        // it to the data array.
        arrData[ arrData.length - 1 ].push( strMatchedValue );
      }

      // Return the parsed data.
      return( arrData );
    }

}<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

sap.ui.define(['./library', 'sap/ui/core/Element'],
	function(library, Element) {
	"use strict";

	/**
	 * Constructor for a new SplitPane.
	 *
	 * @param {string} [sId] ID for the new control, generated automatically if no ID is given
	 * @param {object} [mSettings] Initial settings for the new control
	 *
	 * @class
	 * SplitPane is a container of a single control in a responsive splitter.
	 * Could be used as an aggregation of a {@link sap.ui.layout.PaneContainer PaneContainer}.
	 *
	 * The behavior of the Split Panes is handled by the following properties:
	 *

	 *
requiredParentWidth - determines the minimum width of the parent container (in pixels). When it is reached, the pane will be hidden from the screen.

	 *
demandPane - determines if the pane is reachable via the pagination bar after it has been hidden from the screen.

	 * </ul
	 * @extends sap.ui.core.Element
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @since 1.38
	 * @alias sap.ui.layout.SplitPane
	 */
	var SplitPane = Element.extend("sap.ui.layout.SplitPane", { metadata : {

		library : "sap.ui.layout",
		properties : {

			/**
			 * Determines whether the pane will be moved to the pagination
			*/
			demandPane: { type : "boolean", group : "Behavior", defaultValue : true },

			/**
			 * Determines the minimum width of the ResponsiveSplitter(in pixels). When it is reached the pane will be hidden from the screen.
			*/
			requiredParentWidth: { type : "int", defaultValue : 800}
		},
		defaultAggregation : "content",
		aggregations : {
			/**
			 * Content of the SplitPane
			*/
			content: { type : "sap.ui.core.Control", multiple : false, singularName : "content" }
		}
	}});

	SplitPane.prototype.setLayoutData = function(oLayoutdata) {
		var oContent = this.getContent();
		if (oContent) {
			return oContent.setLayoutData(oLayoutdata);
		} else {
			this._oLayoutData = oLayoutdata;
			return this;
		}
	};

	// overrides the default set method in order to apply layout data that is provided before content
	SplitPane.prototype.setContent = function (oContent) {
		if (this._oLayoutData) {
			oContent.setLayoutData(this._oLayoutData);
			this._oLayoutData = null;
		}

		return this.setAggregation("content", oContent);
	};

	SplitPane.prototype.onLayoutDataChange = function() {
		var oParent = this.getParent();
		if (oParent) {
			oParent._oSplitter._delayedResize();
		}
	};

	SplitPane.prototype._isInInterval = function (iFrom) {
		return this.getRequiredParentWidth() <= iFrom;
	};

	return SplitPane;
});
<commit_msg>[INTERNAL] sap.ui.layout.SplitPane: Improve documentation for requiredParentWidth<commit_after>/*!
 * ${copyright}
 */

sap.ui.define(['./library', 'sap/ui/core/Element'],
	function(library, Element) {
	"use strict";

	/**
	 * Constructor for a new SplitPane.
	 *
	 * @param {string} [sId] ID for the new control, generated automatically if no ID is given
	 * @param {object} [mSettings] Initial settings for the new control
	 *
	 * @class
	 * SplitPane is a container of a single control in a responsive splitter.
	 * Could be used as an aggregation of a {@link sap.ui.layout.PaneContainer PaneContainer}.
	 *
	 * The behavior of the Split Panes is handled by the following properties:
	 *

	 *
requiredParentWidth - determines the minimum width of the parent container (in pixels). When it is reached, the pane will be hidden from the screen.

	 *
demandPane - determines if the pane is reachable via the pagination bar after it has been hidden from the screen.

	 * </ul
	 * @extends sap.ui.core.Element
	 *
	 * @author SAP SE
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @since 1.38
	 * @alias sap.ui.layout.SplitPane
	 */
	var SplitPane = Element.extend("sap.ui.layout.SplitPane", { metadata : {

		library : "sap.ui.layout",
		properties : {

			/**
			 * Determines whether the pane will be moved to the pagination
			*/
			demandPane: { type : "boolean", group : "Behavior", defaultValue : true },

			/**
			 * Determines the minimum width of the ResponsiveSplitter(in pixels). When it is reached the pane will be hidden from the screen.
			 *
			 * When you are calculating the required parent width to fit your panes, you should also include the width of all split bars between these panes.
			*/
			requiredParentWidth: { type : "int", defaultValue : 800}
		},
		defaultAggregation : "content",
		aggregations : {
			/**
			 * Content of the SplitPane
			*/
			content: { type : "sap.ui.core.Control", multiple : false, singularName : "content" }
		}
	}});

	SplitPane.prototype.setLayoutData = function(oLayoutdata) {
		var oContent = this.getContent();
		if (oContent) {
			return oContent.setLayoutData(oLayoutdata);
		} else {
			this._oLayoutData = oLayoutdata;
			return this;
		}
	};

	// overrides the default set method in order to apply layout data that is provided before content
	SplitPane.prototype.setContent = function (oContent) {
		if (this._oLayoutData) {
			oContent.setLayoutData(this._oLayoutData);
			this._oLayoutData = null;
		}

		return this.setAggregation("content", oContent);
	};

	SplitPane.prototype.onLayoutDataChange = function() {
		var oParent = this.getParent();
		if (oParent) {
			oParent._oSplitter._delayedResize();
		}
	};

	SplitPane.prototype._isInInterval = function (iFrom) {
		return this.getRequiredParentWidth() <= iFrom;
	};

	return SplitPane;
});
<|endoftext|>


<commit_before>
'use strict';

var testArray = require('../lib/testArray');

module.exports = function(app) {
  app.controller('mapController', ['$scope', '$http', function($scope, $http){
    $scope.test = 'hello';
    $scope.trucks = testArray;
    $scope.markersShown = [];

    $scope.map;

    //initialize map with all markers for that area
    $scope.initialize = function() {

      var mapCanvas = document.getElementById('map-canvas');
      var mapOptions = {
        center: new google.maps.LatLng(47.620171, -122.337062),
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

      $scope.map = new google.maps.Map(mapCanvas, mapOptions);

      for(var i = 0; i < $scope.trucks.length; i++) {

        var marker = new google.maps.Marker({
          position: new google.maps.LatLng($scope.trucks[i].lat, $scope.trucks[i].long),
          title: $scope.trucks[i].name
        });
        $scope.markersShown.push(marker);
        marker.setMap($scope.map);
        attachContent(marker, i);
      };

      function attachContent(marker, num) {
        var infowindow = new google.maps.InfoWindow({
          content: $scope.markersShown[num].title
        });

        google.maps.event.addListener(marker, 'click', function() {
          infowindow.open($scope.map, marker);
        });
      }
    };

    google.maps.event.addDomListener(window, 'load', $scope.initialize);

    $scope.getAllTrucks = function() {
      $http({
        method: 'GET',
        url: '/INSERT ROUTE HERE'
      })
      .success(function(data) {
        $scope.trucks = data;
      })
      .error(function(data) {
        console.log(data);
      });
    };

    $scope.filterMarkersByType = function(foodType) {

      var infowindow = new google.maps.InfoWindow({});

      for(var i = 0; i < $scope.markersShown.length; i++) {
        console.log('marker removed');
        $scope.markersShown[i].setMap(null);
      };

      $scope.markersShown = [];

      for(var i = 0; i < $scope.trucks.length; i++) {
        if ($scope.trucks[i].type == foodType) {
          var marker = new google.maps.Marker({
            position: new google.maps.LatLng($scope.trucks[i].lat, $scope.trucks[i].long),
            title: $scope.trucks[i].name
          });
          marker.setMap($scope.map);
          $scope.markersShown.push(marker);

          google.maps.event.addListener(marker, 'click', (function(marker) {
            return function() {
              infowindow.setContent(this.title);
              infowindow.open($scope.map, marker);
            }
          })(marker));
        }
      };
    };
  }]);
};
<commit_msg>fixed filter removal<commit_after>
'use strict';

var testArray = require('../lib/testArray');

module.exports = function(app) {
  app.controller('mapController', ['$scope', '$http', function($scope, $http){
    $scope.test = 'hello';
    $scope.trucks = testArray;
    $scope.markersShown = [];

    $scope.map;

    //initialize map with all markers for that area
    $scope.initialize = function() {

      var mapCanvas = document.getElementById('map-canvas');
      var mapOptions = {
        center: new google.maps.LatLng(47.620171, -122.337062),
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

      $scope.map = new google.maps.Map(mapCanvas, mapOptions);

      for(var i = 0; i < $scope.trucks.length; i++) {

        var marker = new google.maps.Marker({
          position: new google.maps.LatLng($scope.trucks[i].lat, $scope.trucks[i].long),
          title: $scope.trucks[i].name
        });
        $scope.markersShown.push(marker);
        marker.setMap($scope.map);
        attachContent(marker, i);
      };

      function attachContent(marker, num) {
        var infowindow = new google.maps.InfoWindow({
          content: $scope.markersShown[num].title
        });

        google.maps.event.addListener(marker, 'click', function() {
          infowindow.open($scope.map, marker);
        });
      }
    };

    google.maps.event.addDomListener(window, 'load', $scope.initialize);

    $scope.getAllTrucks = function() {
      $http({
        method: 'GET',
        url: '/INSERT ROUTE HERE'
      })
      .success(function(data) {
        $scope.trucks = data;
      })
      .error(function(data) {
        console.log(data);
      });
    };

    $scope.filterMarkersByType = function(foodType) {

      var infowindow = new google.maps.InfoWindow({});

      for(var i = 0; i < $scope.markersShown.length; i++) {
        console.log('marker removed');
        $scope.markersShown[i].setMap(null);
      };

      $scope.markersShown = [];

      for(var i = 0; i < $scope.trucks.length; i++) {
        if ($scope.trucks[i].type == foodType) {
          var marker = new google.maps.Marker({
            position: new google.maps.LatLng($scope.trucks[i].lat, $scope.trucks[i].long),
            title: $scope.trucks[i].name
          });
          marker.setMap($scope.map);
          $scope.markersShown.push(marker);

          google.maps.event.addListener(marker, 'click', (function(marker) {
            return function() {
              infowindow.setContent(this.title);
              infowindow.open($scope.map, marker);
            }
          })(marker));
        }
      };
    };

    $scope.filterMarkersByName = function(foodName) {
      for(var i = 0; i < $scope.markersShown.length; i++) {
        $scope.markersShown[i].setMap(null);
      };

      $scope.markersShown = [];

      for(i = 0; i < $scope.trucks.length; i++) {
        if ($scope.trucks[i].name == foodName) {
          var marker = new google.maps.Marker({
            position: new google.maps.LatLng($scope.trucks[i].lat, $scope.trucks[i].long),
            title: $scope.trucks[i].name
          });
          marker.setMap($scope.map);
          $scope.markersShown.push(marker);
        }
      };
    };
  }]);
};
<|endoftext|>


<commit_before>
var Check = require ('Check');
var QueryParamException = require ('./grokible.queryParamException');

var getDefault = function (opt) {
    var v;
    if ('default' in opt)
        v = opt ['default'];
    return v;
}

exports.getInteger = function getInteger (query, name, opt) {
    var v = getDefault (opt);

    var orig_v;
    if (name in query) {
	orig_v = query [name];
	v = parseInt (orig_v);
    }

    Check.isInteger (v, { exception: QueryParamException,
        message: "Expected query param '" + name + "=" + orig_v +
            "' to be an integer." });

    return v;
};

exports.exists = function exists (query, name, opt) {
    return name in query;
};

<commit_msg>removed param<commit_after><|endoftext|>