<commit_before>(function(window) {

// Airbrake shim that stores exceptions until Airbrake notifier is loaded.
window.Airbrake = [];

// Wraps passed function and returns new function that catches and
// reports unhandled exceptions.
Airbrake.wrap = function(fn) {
  var airbrakeWrapper = function() {
    try {
      return fn.apply(this, arguments);
    } catch (exc) {
      args = Array.prototype.slice.call(arguments);
      Airbrake.push({error: exc, params: {arguments: args}});
    }
  }
  if (fn.guid) {
    airbrakeWrapper.guid = fn.guid;
  }
  return airbrakeWrapper;
}

// Reports unhandled exceptions.
window.onerror = function(message, file, line) {
  Airbrake.push({error: {message: message, fileName: file, lineNumber: line}});
}

var loadAirbrakeNotifier = function() {
  var script = document.createElement('script'),
      sibling = document.getElementsByTagName('script')[0];
  script.src = 'https://ssljscdn.airbrake.io/0.3/airbrake.min.js';
  sibling.parentNode.insertBefore(script, sibling);
}

// Asynchronously loads Airbrake notifier.
if (window.addEventListener) {
  window.addEventListener('load', loadAirbrakeNotifier, false);
} else {
  window.attachEvent('onload', loadAirbrakeNotifier);
}

// Reports exceptions thrown in jQuery event handlers.
var jqEventAdd = jQuery.event.add;
jQuery.event.add = function(elem, types, handler, data, selector) {
  if (handler.handler) {
    if (!handler.handler.guid) {
      handler.handler.guid = jQuery.guid++;
    }
    handler.handler = Airbrake.wrap(handler.handler);
  } else {
    if (!handler.guid) {
      handler.guid = jQuery.guid++;
    }
    handler = Airbrake.wrap(handler);
  }
  return jqEventAdd(elem, types, handler, data, selector);
}

// Reports exceptions thrown in jQuery callbacks.
var jqCallbacks = jQuery.Callbacks;
jQuery.Callbacks = function(options) {
  var cb = jqCallbacks(options),
      cbAdd = cb.add;
  cb.add = function() {
    var fns = arguments;
    jQuery.each(fns, function(i, fn) {
      if (jQuery.isFunction(fn)) {
        fns[i] = Airbrake.wrap(fn);
      }
    });
    return cbAdd.apply(this, fns);
  }
  return cb;
}

// Reports exceptions thrown in jQuery ready callbacks.
var jqReady = jQuery.fn.ready;
jQuery.fn.ready = function(fn) {
  return jqReady(Airbrake.wrap(fn));
}

})(window);
<commit_msg>shim: async load Airbrake notifier.<commit_after>(function(window) {

// Airbrake shim that stores exceptions until Airbrake notifier is loaded.
window.Airbrake = [];

// Wraps passed function and returns new function that catches and
// reports unhandled exceptions.
Airbrake.wrap = function(fn) {
  var airbrakeWrapper = function() {
    try {
      return fn.apply(this, arguments);
    } catch (exc) {
      args = Array.prototype.slice.call(arguments);
      Airbrake.push({error: exc, params: {arguments: args}});
    }
  }
  if (fn.guid) {
    airbrakeWrapper.guid = fn.guid;
  }
  return airbrakeWrapper;
}

// Reports unhandled exceptions.
window.onerror = function(message, file, line) {
  Airbrake.push({error: {message: message, fileName: file, lineNumber: line}});
}

var loadAirbrakeNotifier = function() {
  var script = document.createElement('script'),
      sibling = document.getElementsByTagName('script')[0];
  script.src = 'https://ssljscdn.airbrake.io/0.3/airbrake.min.js';
  script.async = true;
  sibling.parentNode.insertBefore(script, sibling);
}

// Asynchronously loads Airbrake notifier.
if (window.addEventListener) {
  window.addEventListener('load', loadAirbrakeNotifier, false);
} else {
  window.attachEvent('onload', loadAirbrakeNotifier);
}

// Reports exceptions thrown in jQuery event handlers.
var jqEventAdd = jQuery.event.add;
jQuery.event.add = function(elem, types, handler, data, selector) {
  if (handler.handler) {
    if (!handler.handler.guid) {
      handler.handler.guid = jQuery.guid++;
    }
    handler.handler = Airbrake.wrap(handler.handler);
  } else {
    if (!handler.guid) {
      handler.guid = jQuery.guid++;
    }
    handler = Airbrake.wrap(handler);
  }
  return jqEventAdd(elem, types, handler, data, selector);
}

// Reports exceptions thrown in jQuery callbacks.
var jqCallbacks = jQuery.Callbacks;
jQuery.Callbacks = function(options) {
  var cb = jqCallbacks(options),
      cbAdd = cb.add;
  cb.add = function() {
    var fns = arguments;
    jQuery.each(fns, function(i, fn) {
      if (jQuery.isFunction(fn)) {
        fns[i] = Airbrake.wrap(fn);
      }
    });
    return cbAdd.apply(this, fns);
  }
  return cb;
}

// Reports exceptions thrown in jQuery ready callbacks.
var jqReady = jQuery.fn.ready;
jQuery.fn.ready = function(fn) {
  return jqReady(Airbrake.wrap(fn));
}

})(window);
<|endoftext|>


<commit_before>(function(window) {
    var debug = {'features': ['nodes'], 'wireframe': false};
    var conf = {'group_styles': {'pov': {'stroke-width': 3}},
                'debug': debug};
    var chart = new NChart('paper', asoiaf.characters, asoiaf.layers, conf).calc().plot().draw();
})(window);
<commit_msg>remove debug nodes<commit_after>(function(window) {
    var debug = null; //{'features': ['nodes'], 'wireframe': false};
    var conf = {'group_styles': {'pov': {'stroke-width': 3}},
                'debug': debug};
    var chart = new NChart('paper', asoiaf.characters, asoiaf.layers, conf).calc().plot().draw();
})(window);
<|endoftext|>


<commit_before>/*!
 * apiai
 * Copyright(c) 2015 http://api.ai/
 * Apache 2.0 Licensed
 */

'use strict';

var util = require('util');
// var apiai = require("../module/apiai");
var apiai = require("apiai");

var options = {
    // hostname: 'eap.api.ai',
};

var app = apiai("<YOUR_ACCESS_TOKEN>", options);

var event = {
    name: "network.connect",
    data: {
        param1: "param1 value",
    }
};

var options = {
    sessionId: '<UNIQE SESSION ID>'
};

var request = app.eventRequest(event, options);

request.on('response', function(response) {
    console.log(util.inspect(response, false, null));
});

request.on('error', function(error) {
    console.log(error);
});

request.end();
<commit_msg>Update event_request.js<commit_after>/*!
 * apiai
 * Copyright(c) 2015 http://api.ai/
 * Apache 2.0 Licensed
 */

'use strict';

var util = require('util');
// var apiai = require("../module/apiai");
var apiai = require("apiai");

var options = {
    // hostname: 'eap.api.ai',
};

var app = apiai("wnSEoGyt8FGC6wpwEs5Mnb3xqeuKLWbtr1tNtEEiyTjf0cm/rIrjAff3JzZkMDY8Di87XAMMZlbGKHym/DvJxBMbTgfMx6Kvg9itSXDrmMhz4J1VUu5nA5y3xB4n1IcRHf4F3OLqe21tMeRuLs167QdB04t89/1O/w1cDnyilFU=", options);

var event = {
    name: "network.connect",
    data: {
        param1: "param1 value",
    }
};

var options = {
    sessionId: ' 	1503638187'
};

var request = app.eventRequest(event, options);

request.on('response', function(response) {
    console.log(util.inspect(response, false, null));
});

request.on('error', function(error) {
    console.log(error);
});

request.end();
<|endoftext|>


<commit_before>const vmSystemOperationsTest = require('ethereum-tests'),  // TODO this becomes StateTests
  async = require('async'),
  VM = require('../../../lib/vm'),
  ERROR = require('../../../lib/vm/constants').ERROR,
  Account = require('../../../lib/account.js'),
  bignum = require('bignum'),
  assert = require('assert'),
  testUtils = require('../../testUtils'),
  Trie = require('merkle-patricia-tree');

// for SUICIDE tests, this is temporarily added to avoid negative balances
const TMP_BAL_AVOID_NEG = '13333337';

function expectError(testKey, error) {
  if (testKey.match(
    /^CallToNameRegistratorTooMuchMemory|createNameRegistratorOutOfMemoryBonds/)) {
    assert.strictEqual(error, ERROR.OUT_OF_GAS);
    return true;
  } else if (testKey.match(
    /(^createNameRegistratorValueTooHigh$)/)) {
    assert.strictEqual(error, ERROR.STACK_UNDERFLOW);
    return true;
  }

  return false;
}

describe.skip('[Common]: vmSystemOperationsTest', function() {
  var suicide0 = vmSystemOperationsTest.suicide0;
  var suicideNotExistingAccount = vmSystemOperationsTest.suicideNotExistingAccount;
  var suicideSendEtherToMe = vmSystemOperationsTest.suicideSendEtherToMe;

  delete vmSystemOperationsTest.suicide0;
  delete vmSystemOperationsTest.suicideNotExistingAccount;
  delete vmSystemOperationsTest.suicideSendEtherToMe;

  var tests = Object.keys(vmSystemOperationsTest);
  // TODO add tests
  // tests = ['CallToNameRegistrator0'];
  tests = [];
  tests.forEach(function(testKey) {
    var state = new Trie();
    var testData = vmSystemOperationsTest[testKey];

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run code', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        acctData,
        account,
        runCodeData,
        vm = new VM(state);

      // vm.onStepZZZ = function(info, done) {
      //   console.log('vm', bignum(info.pc).toString(16) + ' Opcode: ' + info.opcode + ' Gas: ' + info.gasLeft.toString());

      //   var stream = vm.trie.createReadStream();
      //   stream.on("data", function(data) {
      //     var account = new Account(data.value);
      //     console.log("key: " + data.key.toString("hex"));
      //     //console.log(data.value.toString('hex'));
      //     console.log('decoded:' + bignum.fromBuffer(account.balance).toString() + '\n');
      //   });

      //   stream.on('end', done);

      //   // info.stack.reverse();
      //   // info.stack.forEach(function (item) {
      //   //   console.log('vm', '    ' + item.toString('hex'));
      //   // });
      //   // info.stack.reverse();

      // };

      acctData = testData.pre[testData.exec.address];
      account = new Account();
      account.nonce = testUtils.fromDecimal(acctData.nonce);
      account.balance = testUtils.fromDecimal(acctData.balance);
      account.codeHash = testUtils.toCodeHash(testData.exec.code);

      runCodeData = testUtils.makeRunCodeData(testData.exec, account, block);
      vm.runCode(runCodeData, function(err, results) {
        if (expectError(testKey, err)) {
          done();
          return;
        }

        assert(!err);

        // console.log('gas: ', results.gasUsed.toNumber(), 'exp: ',  testData.exec.gas - testData.gas)
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        async.series([
          // function(cb) {
          //   var stream = state.createReadStream();
          //   stream.on("data", function(data) {
          //     var account = new Account(data.value);
          //     console.log("key: " + data.key.toString("hex"));
          //     //console.log(data.value.toString('hex'));
          //     console.log('decoded:' + bignum.fromBuffer(account.balance).toString() + '\n');
          //   });
          //
          //   stream.on('end', cb);
          // },

//           function(cb) {
//             // cb()
//             // return

//             account = results.account;
//             acctData = testData.post[testData.exec.address];
//             testUtils.verifyAccountPostConditions(state, account, acctData, cb);
//           },

          function() {
            // validate the postcondition of other accounts
            // delete testData.post[testData.exec.address];
            var keysOfPost = Object.keys(testData.post);
            async.eachSeries(keysOfPost, function(key, cb) {
              state.get(new Buffer(key, 'hex'), function(err, raw) {
                assert(!err);

                account = new Account(raw);
                acctData = testData.post[key];
                testUtils.verifyAccountPostConditions(state, account, acctData, cb);
              });
            }, done);
          }
        ]);
      });
    });
  });

  describe('.', function() {
    var testKey = 'ABAcalls0',
      state = new Trie(),
      testData = vmSystemOperationsTest.ABAcalls0;

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run code', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        acctData,
        account,
        runCodeData,
        vm = new VM(state);

      acctData = testData.pre[testData.exec.address];
      account = new Account();
      account.nonce = testUtils.fromDecimal(acctData.nonce);
      account.balance = testUtils.fromDecimal(acctData.balance);
      account.codeHash = testUtils.toCodeHash(testData.exec.code);

      runCodeData = testUtils.makeRunCodeData(testData.exec, account, block);
      vm.runCode(runCodeData, function(err, results) {
        assert(!err, err);
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        var keysOfPost = Object.keys(testData.post);
        async.eachSeries(keysOfPost, function(key, cb) {
          state.get(new Buffer(key, 'hex'), function(err, raw) {
            assert(!err);

            account = new Account(raw);
            acctData = testData.post[key];
            testUtils.verifyAccountPostConditions(state, account, acctData, cb);
          });
        }, done);
      });
    });
  });

  describe('.', function() {
    var testKey = 'ABAcalls1',
      state = new Trie(),
      testData = vmSystemOperationsTest.ABAcalls1;

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run code', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        acctData,
        account,
        runCodeData,
        vm = new VM(state);

      // vm.onStepZZZ = function(info, done) {
      //   console.log('vm', bignum(info.pc).toString(16) + ' Opcode: ' + info.opcode + ' Gas: ' + info.gasLeft.toString());

      //   // var stream = vm.trie.createReadStream();
      //   // stream.on("data", function(data) {
      //   //   var account = new Account(data.value);
      //   //   console.log("key: " + data.key.toString("hex"));
      //   //   //console.log(data.value.toString('hex'));
      //   //   console.log('decoded:' + bignum.fromBuffer(account.balance).toString() + '\n');
      //   // });
      //   // stream.on('end', done);

      //   info.stack.reverse();
      //   info.stack.forEach(function (item) {
      //     console.log('vm', '    ' + item.toString('hex'));
      //   });
      //   info.stack.reverse();
      //   done();
      // };

      acctData = testData.pre[testData.exec.address];
      account = new Account();
      account.nonce = testUtils.fromDecimal(acctData.nonce);
      account.balance = testUtils.fromDecimal(acctData.balance);
      account.codeHash = testUtils.toCodeHash(testData.exec.code);

      runCodeData = testUtils.makeRunCodeData(testData.exec, account, block);
      vm.runCode(runCodeData, function(err, results) {
        assert(!err, err);

console.log('gas: ', results.gasUsed.toNumber(), 'exp: ',  testData.exec.gas - testData.gas);

        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        var keysOfPost = Object.keys(testData.post);
        async.eachSeries(keysOfPost, function(key, cb) {
          state.get(new Buffer(key, 'hex'), function(err, raw) {
            assert(!err);

            account = new Account(raw);
            acctData = testData.post[key];
            testUtils.verifyAccountPostConditions(state, account, acctData, cb);
          });
        }, done);
      });
    });
  });

  describe('.', function() {

    var testKey = 'CallRecursiveBomb3',
      state = new Trie(),
      testData = vmSystemOperationsTest.CallRecursiveBomb3;

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run code', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        acctData,
        account,
        runCodeData,
        vm = new VM(state);

      vm.onStepZZZ = function(info, done) {
        console.log('vm', info.depth ,  bignum(info.pc).toString(16) + ' Opcode: ' + info.opcode + ' Gas: ' + info.gasLeft.toString());

        // var stream = vm.trie.createReadStream();
        // stream.on("data", function(data) {
        //   var account = new Account(data.value);
        //   console.log("key: " + data.key.toString("hex"));
        //   //console.log(data.value.toString('hex'));
        //   console.log('decoded:' + bignum.fromBuffer(account.balance).toString() + '\n');
        // });
        // stream.on('end', done);

        info.stack.reverse();
        info.stack.forEach(function (item) {
          console.log('vm', '    ' + item.toString('hex'));
        });
        info.stack.reverse();
        done();
      };

      acctData = testData.pre[testData.exec.address];
      account = new Account();
      account.nonce = testUtils.fromDecimal(acctData.nonce);
      account.balance = testUtils.fromDecimal(acctData.balance);
      account.codeHash = testUtils.toCodeHash(testData.exec.code);

      runCodeData = testUtils.makeRunCodeData(testData.exec, account, block);
      vm.runCode(runCodeData, function(err, results) {
        assert(!err, err);

console.log('gas: ', results.gasUsed.toNumber(), 'exp: ',  testData.exec.gas - testData.gas);
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        var keysOfPost = Object.keys(testData.post);
        async.eachSeries(keysOfPost, function(key, cb) {
          state.get(new Buffer(key, 'hex'), function(err, raw) {
            assert(!err);

            account = new Account(raw);
            acctData = testData.post[key];
            testUtils.verifyAccountPostConditions(state, account, acctData, cb);
          });
        }, done);
      });
    });
  });

  describe.skip('.', function() {
    var testKey = 'ABAcallsSuicide0',
      state = new Trie(),
      testData = vmSystemOperationsTest.ABAcallsSuicide0;

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run code', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        acctData,
        account,
        runCodeData,
        vm = new VM(state);

// var stream = vm.trie.createReadStream();
// stream.on("data", function(data) {
//   var account = new Account(data.value);
//   console.log("key: " + data.key.toString("hex"));
//   //console.log(data.value.toString('hex'));
//   console.log('balance:' + bignum.fromBuffer(account.balance).toString());
//   console.log('codeHash:' + bignum.fromBuffer(account.codeHash).toString() + '\n');
// });
//
// stream.on('end', done);
// return

vm.onStepZZZ = function(info, done) {
  console.log('\n\nvm', bignum(info.pc).toString(16) + ' Opcode: ' + info.opcode + ' Gas: ' + info.gasLeft.toString());

  // var stream = vm.trie.createReadStream();
  // stream.on("data", function(data) {
  //   var account = new Account(data.value);
  //   console.log("@@@ key: " + data.key.toString("hex"));
  //   //console.log(data.value.toString('hex'));
  //   console.log('decoded:' + bignum.fromBuffer(account.balance).toString());
  //   console.log('codeHash:' + bignum.fromBuffer(account.codeHash).toString());
  // });
  //
  // stream.on('end', done);

  info.stack.reverse();
  info.stack.forEach(function (item) {
    console.log('vm', '    ' + item.toString('hex'));
  });
  info.stack.reverse();
  done();
};

      acctData = testData.pre[testData.exec.address];
      account = new Account();
      account.nonce = testUtils.fromDecimal(acctData.nonce);
      account.balance = testUtils.fromDecimal(acctData.balance);
      account.codeHash = testUtils.toCodeHash(testData.exec.code);

      runCodeData = testUtils.makeRunCodeData(testData.exec, account, block);
      vm.runCode(runCodeData, function(err, results) {
        assert(!err, err);

        //console.log('gas: ', results.gasUsed.toNumber(), 'exp: ',  testData.exec.gas - testData.gas)
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        var suicideTo = results.suicideTo.toString('hex'),
          keysOfPost = Object.keys(testData.post);
        assert.strictEqual(keysOfPost.length, 1, '#post mismatch');
        assert.strictEqual(suicideTo, keysOfPost[0], 'suicideTo mismatch');

        state.get(new Buffer(suicideTo, 'hex'), function(err, acct) {
          assert(!err);
          var account = new Account(acct),
            acctData = testData.post[suicideTo];
          // account.balance = bignum.fromBuffer(account.balance).sub(TMP_BAL_AVOID_NEG).toBuffer();

          testUtils.verifyAccountPostConditions(state, account, acctData, done);
        });
      });
    });
  });

  describe('.', function() {

    var testKey = 'callstatelessToNameRegistrator0',
      state = new Trie(),
      testData = vmSystemOperationsTest.callstatelessToNameRegistrator0;

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run code', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        acctData,
        account,
        runCodeData,
        vm = new VM(state);

      vm.onStepZZZ = function(info, done) {
        console.log('vm', info.depth ,  bignum(info.pc).toString(16) + ' Opcode: ' + info.opcode + ' Gas: ' + info.gasLeft.toString());

        // var stream = vm.trie.createReadStream();
        // stream.on("data", function(data) {
        //   var account = new Account(data.value);
        //   console.log("key: " + data.key.toString("hex"));
        //   //console.log(data.value.toString('hex'));
        //   console.log('decoded:' + bignum.fromBuffer(account.balance).toString() + '\n');
        // });
        // stream.on('end', done);

        info.stack.reverse();
        info.stack.forEach(function (item) {
          console.log('vm', '    ' + item.toString('hex'));
        });
        info.stack.reverse();
        done();
      };

      acctData = testData.pre[testData.exec.address];
      account = new Account();
      account.nonce = testUtils.fromDecimal(acctData.nonce);
      account.balance = testUtils.fromDecimal(acctData.balance);
      account.codeHash = testUtils.toCodeHash(testData.exec.code);

      runCodeData = testUtils.makeRunCodeData(testData.exec, account, block);
      vm.runCode(runCodeData, function(err, results) {
        assert(!err, err);
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        var keysOfPost = Object.keys(testData.post);
        async.eachSeries(keysOfPost, function(key, cb) {
          state.get(new Buffer(key, 'hex'), function(err, raw) {
            assert(!err);

            account = new Account(raw);
            acctData = testData.post[key];
            testUtils.verifyAccountPostConditions(state, account, acctData, cb);
          });
        }, done);
      });
    });
  });

  describe('.', function() {

    var testKey = 'callstatelessToReturn1',
      state = new Trie(),
      testData = vmSystemOperationsTest.callstatelessToReturn1;

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run code', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        acctData,
        account,
        runCodeData,
        vm = new VM(state);

      vm.onStepZZZ = function(info, done) {
        console.log('vm', info.depth ,  bignum(info.pc).toString(16) + ' Opcode: ' + info.opcode + ' Gas: ' + info.gasLeft.toString());

        // var stream = vm.trie.createReadStream();
        // stream.on("data", function(data) {
        //   var account = new Account(data.value);
        //   console.log("key: " + data.key.toString("hex"));
        //   //console.log(data.value.toString('hex'));
        //   console.log('decoded:' + bignum.fromBuffer(account.balance).toString() + '\n');
        // });
        // stream.on('end', done);

        info.stack.reverse();
        info.stack.forEach(function (item) {
          console.log('vm', '    ' + item.toString('hex'));
        });
        info.stack.reverse();
        done();
      };

      acctData = testData.pre[testData.exec.address];
      account = new Account();
      account.nonce = testUtils.fromDecimal(acctData.nonce);
      account.balance = testUtils.fromDecimal(acctData.balance);
      account.codeHash = testUtils.toCodeHash(testData.exec.code);

      runCodeData = testUtils.makeRunCodeData(testData.exec, account, block);
      vm.runCode(runCodeData, function(err, results) {
        assert(!err, err);
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        var keysOfPost = Object.keys(testData.post);
        async.eachSeries(keysOfPost, function(key, cb) {
          state.get(new Buffer(key, 'hex'), function(err, raw) {
            assert(!err);

            account = new Account(raw);
            acctData = testData.post[key];
            testUtils.verifyAccountPostConditions(state, account, acctData, cb);
          });
        }, done);
      });
    });
  });

  describe('.', function() {
    var testKey = 'suicide0',
      state = new Trie(),
      testData = suicide0;

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run call', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        account = new Account([
          new Buffer([0]),
          bignum(testData.pre[testData.exec.caller].balance)
            .add(TMP_BAL_AVOID_NEG).toBuffer()
        ]),
        runData = testUtils.makeRunCallDataWithAccount(testData, account, block),
        vm = new VM(state);

      vm.runCall(runData, function(err, results) {
        assert(!err);
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        var suicideTo = results.vm.suicideTo.toString('hex'),
          keysOfPost = Object.keys(testData.post);
        assert.strictEqual(keysOfPost.length, 1, '#post mismatch');
        assert.strictEqual(suicideTo, keysOfPost[0], 'suicideTo mismatch');

        state.get(new Buffer(suicideTo, 'hex'), function(err, acct) {
          assert(!err);
          var account = new Account(acct),
            acctData = testData.post[suicideTo];
          account.balance = bignum.fromBuffer(account.balance).sub(TMP_BAL_AVOID_NEG).toBuffer();

          testUtils.verifyAccountPostConditions(state, account, acctData, done);
        });
      });
    });
  });

  describe('.', function() {
    var testKey = 'suicideNotExistingAccount',
      state = new Trie(),
      testData = suicideNotExistingAccount;

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run call', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        account = new Account([
          new Buffer([0]),
          bignum(testData.pre[testData.exec.caller].balance)
            .add(TMP_BAL_AVOID_NEG).toBuffer()
        ]),
        runData = testUtils.makeRunCallDataWithAccount(testData, account, block),
        vm = new VM(state);

      vm.runCall(runData, function(err, results) {
        assert(!err);
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        async.series([
          function(cb) {
            state.get(new Buffer(testData.exec.address, 'hex'), function(err, raw) {
              assert(!err);
              assert(!raw, 'contract should have been deleted by SUICIDE');
              cb();
            });
          },
          function() {
            var keysOfPost = Object.keys(testData.post),
              suicideCreated = testData.exec.code.substr(4, 20 * 2);
            assert(keysOfPost.length === 2, 'post should only have caller and suicideCreated');
            assert(keysOfPost.indexOf(suicideCreated) !== -1, 'suicideCreated not in post');

            async.each(keysOfPost, function(key, cb) {
              state.get(new Buffer(key, 'hex'), function(err, raw) {
                assert(!err);
                var account = new Account(raw),
                  acctData = testData.post[key];

                if (key === testData.exec.caller) {
                  account.balance = bignum.fromBuffer(account.balance)
                    .add(testData.exec.value)
                    .sub(TMP_BAL_AVOID_NEG).toBuffer();
                } else if (key === suicideCreated) {
                  // console.log('@@@@@@@@ val: ', testData.exec.value)
                  account.balance = bignum.fromBuffer(account.balance).sub(testData.exec.value).toBuffer();
                }

                testUtils.verifyAccountPostConditions(state, account, acctData, cb);
              });
            }, done);
          }
        ]);
      });
    });
  });

  describe('.', function() {
    var testKey = 'suicideSendEtherToMe',
      state = new Trie(),
      testData = suicideSendEtherToMe;

    it(testKey + ' setup the trie', function(done) {
      testUtils.setupPreConditions(state, testData, done);
    });

    it(testKey + ' run call', function(done) {
      var env = testData.env,
        block = testUtils.makeBlockFromEnv(env),
        account = new Account([
          new Buffer([0]),
          bignum(testData.pre[testData.exec.caller].balance)
            .add(TMP_BAL_AVOID_NEG).toBuffer()
        ]),
        runData = testUtils.makeRunCallDataWithAccount(testData, account, block),
        vm = new VM(state);

      vm.runCall(runData, function(err, results) {
        assert(!err);
        assert.strictEqual(results.gasUsed.toNumber(),
          testData.exec.gas - testData.gas, 'gas used mismatch');

        var suicideTo = results.vm.suicideTo.toString('hex'),
          keysOfPost = Object.keys(testData.post);
        assert.strictEqual(keysOfPost.length, 1, '#post mismatch');
        assert.notStrictEqual(suicideTo, keysOfPost[0], 'suicideTo should not exist');

        async.series([
          function(cb) {
            state.get(new Buffer(suicideTo, 'hex'), function(err, acct) {
              assert(!err);
              assert(!acct, 'suicide account should be gone');
              cb();
            });
          },
          function() {
            state.get(new Buffer(keysOfPost[0], 'hex'), function(err, acct) {
              assert(!err);
              var account = new Account(acct),
                acctData = testData.post[keysOfPost[0]];
              account.balance = bignum.fromBuffer(account.balance)
                .add(testData.exec.value)
                .sub(TMP_BAL_AVOID_NEG).toBuffer();
              testUtils.verifyAccountPostConditions(state, account, acctData, done);
            });
          }
        ], done);
      });
    });
  });
});
<commit_msg>vm sysops tests are now StateTests<commit_after><|endoftext|>


<commit_before>'use strict';
var sane = require('../index.js');
sane.init();

console.log('Finding scanners synchronously...');
var devices = sane.getDevicesSync(true);
console.log(devices);

console.log('Finding scanners asynchronously...');
sane.getDevices(true, function (devices) {
  console.log(devices);
});

/*
sane.open('test:0', function (device) {
  var i = 0;
  var options;
  while (options = sane.getOptionDescriptor(device.handle, i)) {
    console.log(options);
    i++;
  }
});
*/
<commit_msg>Removed leftover comment.<commit_after>'use strict';
var sane = require('../index.js');
sane.init();

console.log('Finding scanners synchronously...');
var devices = sane.getDevicesSync(true);
console.log(devices);

console.log('Finding scanners asynchronously...');
sane.getDevices(true, function (devices) {
  console.log(devices);
});

<|endoftext|>


<commit_before>'use strict';

define(['ol', 'dc', 'toolbar', 'layermanager', 'SparqlJson', 'query', 'search', 'print', 'permalink', 'measure', 'geolocation', 'feature-crossfilter', 'legend', 'panoramio', 'bootstrap'],

    function(ol, dc, toolbar, layermanager, SparqlJson) {
        var module = angular.module('hs', [
            'hs.toolbar',
            'hs.layermanager',
            'hs.query',
            'hs.search', 'hs.print', 'hs.permalink',
            'hs.geolocation',
            'hs.legend',
            'hs.feature_crossfilter', 'hs.panoramio'
        ]);

        module.directive('hs', ['Core', function(Core) {
            return {
                templateUrl: hsl_path + 'hslayers.html',
                link: function(scope, element) {
                    Core.fullscreenMap(element);
                }
            };
        }]);

        module.value('box_layers', [{
            id: 'base',
            'img': 'osm.png',
            title: 'Base layer'
        }, {
            id: 'tourismus',
            'img': 'bicycle-128.png',
            title: 'Tourist info'
        }, {
            id: 'weather',
            'img': 'partly_cloudy.png',
            title: 'Weather'
        }]);

        var style = function(feature, resolution) {
            if (typeof feature.get('visible') === 'undefined' || feature.get('visible') == true) {
                var s = feature.get('http://gis.zcu.cz/poi#category_osm');
                if (typeof s === 'undefined') return;
                s = s.split(".")[1];
                return [new ol.style.Style({
                        image: new ol.style.Circle({
                            fill: new ol.style.Fill({
                                color: feature.color ? feature.color : [242, 121, 0, 0.7]
                            }),
                            stroke: new ol.style.Stroke({
                                color: [0x33, 0x33, 0x33, 0.9]
                            }),
                            radius: 3
                        }),
                        fill: new ol.style.Fill({
                            color: "rgba(139, 189, 214, 0.3)",
                        }),
                        stroke: new ol.style.Stroke({
                            color: "rgba(139, 189, 214, 0.7)",
                        })
                    }),
                    new ol.style.Style({
                        image: new ol.style.Icon({
                            src: 'symbols/' + s + '.svg',
                            crossOrigin: 'anonymous'
                        })
                    })

                ]
            } else {
                return [];
            }
        }

        var route_style = function(feature, resolution) {
            return [new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: "rgba(242, 78, 60, 0.9)",
                    width: 2
                })
            })]
        }

        module.value('default_layers', [
            new ol.layer.Tile({
                source: new ol.source.OSM(),
                title: "OpenStreetMap",
                box_id: 'base',
                base: true,
                visible: false
            }),
            new ol.layer.Tile({
                title: "OpenCycleMap",
                box_id: 'base',
                visible: true,
                source: new ol.source.OSM({
                    url: 'http://{a-c}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png'
                })
            }),
            new ol.layer.Vector({
                title: "Points of interest",
                box_id: 'tourismus',
                maxResolution: 70,
                source: new SparqlJson({
                    url: 'http://ha.isaf2014.info:8890/sparql?default-graph-uri=&query=SELECT+%3Fo+%3Fp+%3Fs%0D%0AFROM+<http%3A%2F%2Fgis.zcu.cz%2Fpoi.rdf>%0D%0AWHERE+%0D%0A%09%7B%3Fo+<http%3A%2F%2Fwww.w3.org%2F2003%2F01%2Fgeo%2Fwgs84_pos%23lat>+%3Flat.+%3Fo+<http%3A%2F%2Fwww.w3.org%2F2003%2F01%2Fgeo%2Fwgs84_pos%23long>+%3Flon.+%0D%0A%09+<extent>%0D%0A%09%3Fo+%3Fp+%3Fs+%0D%0A%09%7D%0D%0AORDER+BY+%3Fo&should-sponge=&format=application%2Fsparql-results%2Bjson&timeout=0&debug=on',
                    category_field: 'http://gis.zcu.cz/poi#category_osm',
                    projection: 'EPSG:3857'
                }),
                style: style
            }),
            new ol.layer.Tile({
                title: "OpenWeatherMap cloud cover",
                box_id: 'weather',
                source: new ol.source.XYZ({
                    url: "http://{a-c}.tile.openweathermap.org/map/clouds/{z}/{x}/{y}.png"
                }),
                visible: false,
                opacity: 0.7
            }),
            new ol.layer.Tile({
                title: "OpenWeatherMap precipitation",
                box_id: 'weather',
                source: new ol.source.XYZ({
                    url: "http://{a-c}.tile.openweathermap.org/map/precipitation/{z}/{x}/{y}.png"
                }),
                visible: false,
                opacity: 0.7
            }),
            new ol.layer.Tile({
                title: "OpenWeatherMap temperature",
                box_id: 'weather',
                source: new ol.source.XYZ({
                    url: "http://{a-c}.tile.openweathermap.org/map/temp/{z}/{x}/{y}.png"
                }),
                visible: false,
                opacity: 0.7
            }),
            new ol.layer.Vector({
                title: "Cycling routes Plzen",
                box_id: 'tourismus',
                source: new ol.source.GeoJSON({
                    url: 'plzensky_kraj.geojson'
                }),
                style: route_style
            }),
            new ol.layer.Vector({
                title: "Cycling routes Zemgale",
                box_id: 'tourismus',
                source: new ol.source.GeoJSON({
                    url: 'zemgale.geojson'
                }),
                style: route_style
            }),
            new ol.layer.Vector({
                title: "Tour de LatEst",
                box_id: 'tourismus',
                source: new ol.source.GeoJSON({
                    url: 'teourdelatest.geojson'
                }),
                style: route_style
            }),
            new ol.layer.Image({
                title: "Forest roads",
                box_id: 'tourismus',
                BoundingBox: [{
                    crs: "EPSG:3857",
                    extent: [1405266, 6146786, 2073392, 6682239]
                }],
                source: new ol.source.ImageWMS({
                    url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/ovnis/sdi4aps_forest_roads.map',
                    params: {
                        LAYERS: 'forest_roads,haul_roads',
                        INFO_FORMAT: "application/vnd.ogc.gml",
                        FORMAT: "image/png; mode=8bit"
                    },
                    crossOrigin: null
                })
            })
        ]);

        module.value('crossfilterable_layers', [{
            layer_ix: 2,
            attributes: ["http://gis.zcu.cz/poi#category_osm"]
        }]);

        module.value('default_view', new ol.View({
            center: [1490321.6967438285, 6400602.013496143], //Latitude longitude    to Spherical Mercator
            zoom: 14,
            units: "m"
        }));

        module.controller('Main', ['$scope', '$filter', 'Core', 'OlMap', 'InfoPanelService', 'feature_crossfilter',
            function($scope, $filter, Core, OlMap, InfoPanelService, feature_crossfilter) {
                if (console) console.log("Main called");
                $scope.hsl_path = hsl_path; //Get this from hslayers.js file
                $scope.Core = Core;

                $scope.$on('infopanel.updated', function(event) {});

                var pop_div = document.createElement('div');
                document.getElementsByTagName('body')[0].appendChild(pop_div);
                var popup = new ol.Overlay({
                    element: pop_div
                });
                OlMap.map.addOverlay(popup);

                $scope.$on('map_clicked', function(event, data) {
                    var coordinate = data.coordinate;
                    var lon_lat = ol.proj.transform(
                        coordinate, 'EPSG:3857', 'EPSG:4326');
                    var p = "http://api.openweathermap.org/data/2.5/weather?lat=" + lon_lat[1] + "&lon=" + lon_lat[0];
                    var url = "/cgi-bin/hsproxy.cgi?toEncoding=utf-8&url=" + window.escape(p);

                    $.ajax({
                            url: url
                        })
                        .done(function(response) {
                            if (console) console.log(response);
                            var element = popup.getElement();

                            var hdms = ol.coordinate.toStringHDMS(ol.proj.transform(
                                coordinate, 'EPSG:3857', 'EPSG:4326'));
                            $(element).popover('destroy');
                            var content = 'No weather info';
                            if (response.weather) {
                                var wind_row = 'Wind: ' + response.wind.speed + 'm/s' + (response.wind.gust ? ' Gust: ' + response.wind.gust + 'm/s' : '');
                                var close_button = '<button type="button" class="close">×Close</button>';
                                var weather = response.weather[0];
                                var cloud = '' + weather.description;
                                var temp_row = 'Temperature: ' + (response.main.temp - 273.15).toFixed(1) + ' °C';
                                var date_row = $filter('date')(new Date(response.dt * 1000), 'dd.MM.yyyy HH:mm');
                                content = close_button + '
' + response.name + '
 at ' + date_row + '
' + cloud + '
' + temp_row + '
' + wind_row;
                            }
                            $(element).popover({
                                'placement': 'top',
                                'animation': false,
                                'html': true,
                                'content': content
                            });

                            popup.setPosition(coordinate);
                            $(element).popover('show');
                            $('.close', element.nextElementSibling).click(function() {
                                $(element).popover('hide')
                            });
                        });

                });
            }
        ]);

        return module;
    });
<commit_msg>A1 cycling rout in Prague<commit_after>'use strict';

define(['ol', 'dc', 'toolbar', 'layermanager', 'SparqlJson', 'query', 'search', 'print', 'permalink', 'measure', 'geolocation', 'feature-crossfilter', 'legend', 'panoramio', 'bootstrap'],

    function(ol, dc, toolbar, layermanager, SparqlJson) {
        var module = angular.module('hs', [
            'hs.toolbar',
            'hs.layermanager',
            'hs.query',
            'hs.search', 'hs.print', 'hs.permalink',
            'hs.geolocation',
            'hs.legend',
            'hs.feature_crossfilter', 'hs.panoramio'
        ]);

        module.directive('hs', ['Core', function(Core) {
            return {
                templateUrl: hsl_path + 'hslayers.html',
                link: function(scope, element) {
                    Core.fullscreenMap(element);
                }
            };
        }]);

        module.value('box_layers', [{
            id: 'base',
            'img': 'osm.png',
            title: 'Base layer'
        }, {
            id: 'tourismus',
            'img': 'bicycle-128.png',
            title: 'Tourist info'
        }, {
            id: 'weather',
            'img': 'partly_cloudy.png',
            title: 'Weather'
        }]);

        var style = function(feature, resolution) {
            if (typeof feature.get('visible') === 'undefined' || feature.get('visible') == true) {
                var s = feature.get('http://gis.zcu.cz/poi#category_osm');
                if (typeof s === 'undefined') return;
                s = s.split(".")[1];
                return [new ol.style.Style({
                        image: new ol.style.Circle({
                            fill: new ol.style.Fill({
                                color: feature.color ? feature.color : [242, 121, 0, 0.7]
                            }),
                            stroke: new ol.style.Stroke({
                                color: [0x33, 0x33, 0x33, 0.9]
                            }),
                            radius: 3
                        }),
                        fill: new ol.style.Fill({
                            color: "rgba(139, 189, 214, 0.3)",
                        }),
                        stroke: new ol.style.Stroke({
                            color: "rgba(139, 189, 214, 0.7)",
                        })
                    }),
                    new ol.style.Style({
                        image: new ol.style.Icon({
                            src: 'symbols/' + s + '.svg',
                            crossOrigin: 'anonymous'
                        })
                    })

                ]
            } else {
                return [];
            }
        }

        var route_style = function(feature, resolution) {
            return [new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: "rgba(242, 78, 60, 0.9)",
                    width: 2
                })
            })]
        }

        module.value('default_layers', [
            new ol.layer.Tile({
                source: new ol.source.OSM(),
                title: "OpenStreetMap",
                box_id: 'base',
                base: true,
                visible: false
            }),
            new ol.layer.Tile({
                title: "OpenCycleMap",
                box_id: 'base',
                visible: true,
                source: new ol.source.OSM({
                    url: 'http://{a-c}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png'
                })
            }),
            new ol.layer.Vector({
                title: "Points of interest",
                box_id: 'tourismus',
                maxResolution: 70,
                source: new SparqlJson({
                    url: 'http://ha.isaf2014.info:8890/sparql?default-graph-uri=&query=SELECT+%3Fo+%3Fp+%3Fs%0D%0AFROM+<http%3A%2F%2Fgis.zcu.cz%2Fpoi.rdf>%0D%0AWHERE+%0D%0A%09%7B%3Fo+<http%3A%2F%2Fwww.w3.org%2F2003%2F01%2Fgeo%2Fwgs84_pos%23lat>+%3Flat.+%3Fo+<http%3A%2F%2Fwww.w3.org%2F2003%2F01%2Fgeo%2Fwgs84_pos%23long>+%3Flon.+%0D%0A%09+<extent>%0D%0A%09%3Fo+%3Fp+%3Fs+%0D%0A%09%7D%0D%0AORDER+BY+%3Fo&should-sponge=&format=application%2Fsparql-results%2Bjson&timeout=0&debug=on',
                    category_field: 'http://gis.zcu.cz/poi#category_osm',
                    projection: 'EPSG:3857'
                }),
                style: style
            }),
            new ol.layer.Tile({
                title: "OpenWeatherMap cloud cover",
                box_id: 'weather',
                source: new ol.source.XYZ({
                    url: "http://{a-c}.tile.openweathermap.org/map/clouds/{z}/{x}/{y}.png"
                }),
                visible: false,
                opacity: 0.7
            }),
            new ol.layer.Tile({
                title: "OpenWeatherMap precipitation",
                box_id: 'weather',
                source: new ol.source.XYZ({
                    url: "http://{a-c}.tile.openweathermap.org/map/precipitation/{z}/{x}/{y}.png"
                }),
                visible: false,
                opacity: 0.7
            }),
            new ol.layer.Tile({
                title: "OpenWeatherMap temperature",
                box_id: 'weather',
                source: new ol.source.XYZ({
                    url: "http://{a-c}.tile.openweathermap.org/map/temp/{z}/{x}/{y}.png"
                }),
                visible: false,
                opacity: 0.7
            }),
            new ol.layer.Vector({
                title: "Cycling routes Plzen",
                box_id: 'tourismus',
                source: new ol.source.GeoJSON({
                    url: 'plzensky_kraj.geojson'
                }),
                style: route_style
            }),
            new ol.layer.Vector({
                title: "Cycling routes Zemgale",
                box_id: 'tourismus',
                source: new ol.source.GeoJSON({
                    url: 'zemgale.geojson'
                }),
                style: route_style
            }),
            new ol.layer.Vector({
                title: "Tour de LatEst",
                box_id: 'tourismus',
                source: new ol.source.GeoJSON({
                    url: 'teourdelatest.geojson'
                }),
                style: route_style
            }),
            new ol.layer.Vector({
                title: "A1: the Vltava left-bank cycle route",
                box_id: 'tourismus',
                source: new ol.source.GeoJSON({
                    url: 'prague.geojson'
                }),
                style: route_style
            }),
            new ol.layer.Image({
                title: "Forest roads",
                box_id: 'tourismus',
                BoundingBox: [{
                    crs: "EPSG:3857",
                    extent: [1405266, 6146786, 2073392, 6682239]
                }],
                source: new ol.source.ImageWMS({
                    url: 'http://gis.lesprojekt.cz/cgi-bin/mapserv?map=/home/ovnis/sdi4aps_forest_roads.map',
                    params: {
                        LAYERS: 'forest_roads,haul_roads',
                        INFO_FORMAT: "application/vnd.ogc.gml",
                        FORMAT: "image/png; mode=8bit"
                    },
                    crossOrigin: null
                })
            })
        ]);

        module.value('crossfilterable_layers', [{
            layer_ix: 2,
            attributes: ["http://gis.zcu.cz/poi#category_osm"]
        }]);

        module.value('default_view', new ol.View({
            center: [1490321.6967438285, 6400602.013496143], //Latitude longitude    to Spherical Mercator
            zoom: 14,
            units: "m"
        }));

        module.controller('Main', ['$scope', '$filter', 'Core', 'OlMap', 'InfoPanelService', 'feature_crossfilter',
            function($scope, $filter, Core, OlMap, InfoPanelService, feature_crossfilter) {
                if (console) console.log("Main called");
                $scope.hsl_path = hsl_path; //Get this from hslayers.js file
                $scope.Core = Core;

                $scope.$on('infopanel.updated', function(event) {});

                var pop_div = document.createElement('div');
                document.getElementsByTagName('body')[0].appendChild(pop_div);
                var popup = new ol.Overlay({
                    element: pop_div
                });
                OlMap.map.addOverlay(popup);

                $scope.$on('map_clicked', function(event, data) {
                    var coordinate = data.coordinate;
                    var lon_lat = ol.proj.transform(
                        coordinate, 'EPSG:3857', 'EPSG:4326');
                    var p = "http://api.openweathermap.org/data/2.5/weather?lat=" + lon_lat[1] + "&lon=" + lon_lat[0];
                    var url = "/cgi-bin/hsproxy.cgi?toEncoding=utf-8&url=" + window.escape(p);

                    $.ajax({
                            url: url
                        })
                        .done(function(response) {
                            if (console) console.log(response);
                            var element = popup.getElement();

                            var hdms = ol.coordinate.toStringHDMS(ol.proj.transform(
                                coordinate, 'EPSG:3857', 'EPSG:4326'));
                            $(element).popover('destroy');
                            var content = 'No weather info';
                            if (response.weather) {
                                var wind_row = 'Wind: ' + response.wind.speed + 'm/s' + (response.wind.gust ? ' Gust: ' + response.wind.gust + 'm/s' : '');
                                var close_button = '<button type="button" class="close">×Close</button>';
                                var weather = response.weather[0];
                                var cloud = '' + weather.description;
                                var temp_row = 'Temperature: ' + (response.main.temp - 273.15).toFixed(1) + ' °C';
                                var date_row = $filter('date')(new Date(response.dt * 1000), 'dd.MM.yyyy HH:mm');
                                content = close_button + '
' + response.name + '
 at ' + date_row + '
' + cloud + '
' + temp_row + '
' + wind_row;
                            }
                            $(element).popover({
                                'placement': 'top',
                                'animation': false,
                                'html': true,
                                'content': content
                            });

                            popup.setPosition(coordinate);
                            $(element).popover('show');
                            $('.close', element.nextElementSibling).click(function() {
                                $(element).popover('hide')
                            });
                        });

                });
            }
        ]);

        return module;
    });
<|endoftext|>


<commit_before>'use strict';
const complement = require('../../src/distribution-functions/complement');

describe('Complement function', ()=>{

it('should create an array with 2 element if no arguments are passed', ()=>{
  let result = complement();
  expect(result.length).toBe(2);
  expect(result[1]).toBe(0.5);
});

it('should create an array with 3 complements', ()=>{
  let count = 3,
      result = complement(count);
  expect(result.length).toBe(count + 1); // 3 ccomplements + 1 base value
  expect(result[1]).toBe(0.5);
  expect(result[2]).toBe(0.5 + Math.pow(0.3, 3));
});

it('should accept a configuration object', ()=>{
  let count = 3,
      config = {
        dist: 0.2
      },
      result = complement(count, config);
  expect(result.length).toBe(count + 1);
  expect(result[0]).toBe(0);
  expect(result[1]).toBe(0.5);
  expect(result[2]).toBe(0.5 + config.dist);
  expect(result[3]).toBe(0.5 - config.dist);
});

it('should accept a configuration object with a invert property', ()=>{
  let count = 3,
      config = {
        dist: 0.2,
        invert: true,
      },
      result = complement(count, config);
      expect(result.length).toBe(count + 1);
      expect(result[0]).toBe(0);
      expect(result[1]).toBe(0.5);
      expect(result[2]).toBe(0.5 - config.dist);
      expect(result[3]).toBe(0.5 + config.dist);
});

it('should accept a configuration object with a function as distance property', ()=>{
  let count = 3,
      index = 2,
      config = {
        dist: {
          fn: (a)=>{
            return a/2;
          },
          params: [0.5]
        },
      },
      result = complement(count, config);
  expect(result.length).toBe(count + 1);
  expect(result[index]).toBe(0.5 + Math.pow(config.dist.fn(config.dist.params[0]), count-index));
});

it('should not allow for values greather than 1', ()=>{
  let count = 1,
      dist = 3;

  expect(()=>{
    complement(count, {dist: dist});
  }).toThrow();
});

it('should not allow for values lesser than 0', ()=>{
  let count = 1,
      dist = -1;

  expect(()=>{
    complement(count, {dist: dist});
  }).toThrow();
});

});
<commit_msg>update unit test to new settings<commit_after>'use strict';
const complement = require('../../src/distribution-functions/complement');

describe('Complement function', ()=>{

it('should create an array with 2 element if no arguments are passed', ()=>{
  let result = complement();
  expect(result.length).toBe(2);
  expect(result[1]).toBe(0.5);
});

it('should create an array with 3 complements', ()=>{
  let count = 3,
      result = complement(count);
  expect(result.length).toBe(count + 1); // 3 ccomplements + 1 base value
  expect(result[1]).toBe(0.5);
  expect(result[2]).toBe(0.5 + Math.pow(0.35, 3));
});

it('should accept a configuration object', ()=>{
  let count = 3,
      config = {
        dist: 0.2
      },
      result = complement(count, config);
  expect(result.length).toBe(count + 1);
  expect(result[0]).toBe(0);
  expect(result[1]).toBe(0.5);
  expect(result[2]).toBe(0.5 + config.dist);
  expect(result[3]).toBe(0.5 - config.dist);
});

it('should accept a configuration object with a invert property', ()=>{
  let count = 3,
      config = {
        dist: 0.2,
        invert: true,
      },
      result = complement(count, config);
      expect(result.length).toBe(count + 1);
      expect(result[0]).toBe(0);
      expect(result[1]).toBe(0.5);
      expect(result[2]).toBe(0.5 - config.dist);
      expect(result[3]).toBe(0.5 + config.dist);
});

it('should accept a configuration object with a function as distance property', ()=>{
  let count = 3,
      index = 2,
      config = {
        dist: {
          fn: (a)=>{
            return a/2;
          },
          params: [0.5]
        },
      },
      result = complement(count, config);
  expect(result.length).toBe(count + 1);
  expect(result[index]).toBe(0.5 + Math.pow(config.dist.fn(config.dist.params[0]), count-index));
});

it('should not allow for values greather than 1', ()=>{
  let count = 1,
      dist = 3;

  expect(()=>{
    complement(count, {dist: dist});
  }).toThrow();
});

it('should not allow for values lesser than 0', ()=>{
  let count = 1,
      dist = -1;

  expect(()=>{
    complement(count, {dist: dist});
  }).toThrow();
});

});
<|endoftext|>


<commit_before>import { combineReducers } from 'redux'
import ElectronConfig from 'electron-config'
import GitHub from '../models/GitHub'

const configName = process.env.NODE_ENV === 'test' ? 'config-test' : 'config'
const storage = new ElectronConfig({ name: configName })
const SNOOZED_KEY = 'snoozed'
const ARCHIVED_KEY = 'archived'
const IGNORED_KEY = 'ignored'

// Fetch from the JSON storage file the task IDs saved under the given key.
function getSavedTaskKeys(key) {
  return storage.has(key) ? storage.get(key) : []
}

// Persist the given tasks under the given key in the JSON storage file.
function writeChanges(tasks, typeKey) {
  const existingTaskKeys = getSavedTaskKeys(typeKey)
  const newTaskKeys = tasks.map(task => task.storageKey)
  console.info(typeKey, newTaskKeys)
  const allTaskKeys = []
  existingTaskKeys.concat(newTaskKeys).forEach(key => {
    if (allTaskKeys.indexOf(key) < 0) {
      allTaskKeys.push(key)
    }
  })
  storage.set(typeKey, allTaskKeys)
}

function notificationsBySubject(notifications) {
  const result = {}
  if (typeof notifications === 'undefined') {
    return result
  }
  notifications.forEach(notification => {
    result[notification.subject.url] = notification.url
  })
  return result
}

// Remove the given tasks from the given key in the JSON storage file.
function removeTasks(tasks, typeKey) {
  const existingTaskKeys = getSavedTaskKeys(typeKey)
  const keysToRemove = tasks.map(task => task.storageKey)
  const allTaskKeys = []
  existingTaskKeys.forEach(key => {
    if (keysToRemove.indexOf(key) < 0) {
      allTaskKeys.push(key)
    }
  })
  storage.set(typeKey, allTaskKeys)
}

function updateTasks(tasks, action) {
  const tasksByKey = {}
  const snoozedTasks = getSavedTaskKeys(SNOOZED_KEY)
  const archivedTasks = getSavedTaskKeys(ARCHIVED_KEY)
  const ignoredTasks = getSavedTaskKeys(IGNORED_KEY)
  const notificationUrls = notificationsBySubject(action.notifications)

  // Add the existing tasks
  tasks.forEach(task => (tasksByKey[task.storageKey] = task))

  // Update tasks with new values and add new tasks
  action.tasks.forEach(task => {
    const updatedTask = Object.assign({}, tasksByKey[task.storageKey], task)
    const notificationUrl = notificationUrls[task.apiUrl]
    if (notificationUrl) {
      updatedTask.notificationUrl = notificationUrl
    }
    tasksByKey[task.storageKey] = updatedTask
  })

  const updatedTasks = Object.keys(tasksByKey).map(key => {
    const task = tasksByKey[key]
    if (snoozedTasks.indexOf(key) > -1) {
      task.snoozedAt = storage.get(key)
    }
    if (archivedTasks.indexOf(key) > -1) {
      task.archivedAt = storage.get(key)
    }
    if (ignoredTasks.indexOf(key) > -1) {
      task.ignore = true
    }
    return task
  })

  return updatedTasks
}

function selectTasks(tasks, action) {
  const selectedTasks = []
  const updatedTasks = tasks.map(task => {
    if (task.storageKey === action.task.storageKey) {
      selectedTasks.push(task)
      return Object.assign({}, task, { isSelected: true })
    }
    return task
  })
  console.info('select', selectedTasks.map(task => task.storageKey))
  return updatedTasks
}

function deselectTasks(tasks, action) {
  const deselectedTasks = []
  const updatedTasks = tasks.map(task => {
    if (task.storageKey === action.task.storageKey) {
      deselectedTasks.push(task)
      return Object.assign({}, task, { isSelected: false })
    }
    return task
  })
  console.info('deselect', deselectedTasks.map(task => task.storageKey))
  return updatedTasks
}

function currentTimeString() {
  const date = new Date()
  return date.toISOString()
}

function clearNotifications(tasks) {
  const withNotification = tasks.filter(task => {
    return typeof task.notificationUrl === 'string'
  })
  const github = new GitHub()
  withNotification.forEach(task => {
    github.markAsRead(task.notificationUrl).catch(err => {
      console.error('failed to mark notification as read', err, task)
    })
  })
}

function snoozeTasks(tasks) {
  const snoozedTasks = []
  const updatedTasks = tasks.map(task => {
    if (task.isSelected) {
      const snoozedAt = currentTimeString()
      storage.set(task.storageKey, snoozedAt)
      snoozedTasks.push(task)
      return Object.assign({}, task, {
        snoozedAt,
        archivedAt: null,
        isSelected: false,
        ignore: false,
      })
    }
    return task
  })
  clearNotifications(snoozedTasks)
  writeChanges(snoozedTasks, SNOOZED_KEY)
  return updatedTasks
}

function ignoreTasks(tasks) {
  const ignoredTasks = []
  const updatedTasks = tasks.map(task => {
    if (task.isSelected) {
      ignoredTasks.push(task)
      if (storage.has(task.storageKey)) {
        storage.delete(task.storageKey)
      }
      return Object.assign({}, task, {
        ignore: true,
        isSelected: false,
        snoozedAt: null,
        archivedAt: null,
      })
    }
    return task
  })
  clearNotifications(ignoredTasks)
  writeChanges(ignoredTasks, IGNORED_KEY)
  return updatedTasks
}

function archiveTasks(tasks) {
  const archivedTasks = []
  const updatedTasks = tasks.map(task => {
    if (task.isSelected) {
      const archivedAt = currentTimeString()
      storage.set(task.storageKey, archivedAt)
      archivedTasks.push(task)
      return Object.assign({}, task, {
        archivedAt,
        snoozedAt: null,
        isSelected: false,
        ignore: false,
      })
    }
    return task
  })
  clearNotifications(archivedTasks)
  writeChanges(archivedTasks, ARCHIVED_KEY)
  return updatedTasks
}

function restoreTasks(tasks) {
  const restoredTasks = []
  const updatedTasks = tasks.map(task => {
    if (task.isSelected) {
      storage.delete(task.storageKey)
      restoredTasks.push(task)
      return Object.assign({}, task, {
        archivedAt: null,
        ignore: false,
        snoozedAt: null,
        isSelected: false,
      })
    }
    return task
  })
  console.info('restore', restoredTasks.map(task => task.storageKey))
  removeTasks(restoredTasks, ARCHIVED_KEY)
  removeTasks(restoredTasks, SNOOZED_KEY)
  removeTasks(restoredTasks, IGNORED_KEY)
  return updatedTasks
}

function tasksReducer(tasks = [], action) {
  switch (action.type) {
    case 'TASKS_EMPTY':
      return []
    case 'TASKS_UPDATE':
      return updateTasks(tasks, action)
    case 'TASKS_SELECT':
      return selectTasks(tasks, action)
    case 'TASKS_DESELECT':
      return deselectTasks(tasks, action)
    case 'TASKS_SNOOZE':
      return snoozeTasks(tasks)
    case 'TASKS_ARCHIVE':
      return archiveTasks(tasks)
    case 'TASKS_IGNORE':
      return ignoreTasks(tasks)
    case 'TASKS_RESTORE':
      return restoreTasks(tasks)
    default:
      return tasks
  }
}

module.exports = combineReducers({
  tasks: tasksReducer,
})
<commit_msg>Rename function, variable for clarity<commit_after>import { combineReducers } from 'redux'
import ElectronConfig from 'electron-config'
import GitHub from '../models/GitHub'

const configName = process.env.NODE_ENV === 'test' ? 'config-test' : 'config'
const storage = new ElectronConfig({ name: configName })
const SNOOZED_KEY = 'snoozed'
const ARCHIVED_KEY = 'archived'
const IGNORED_KEY = 'ignored'

// Fetch from the JSON storage file the task IDs saved under the given key.
function getSavedTaskKeys(key) {
  return storage.has(key) ? storage.get(key) : []
}

// Persist the given tasks under the given key in the JSON storage file.
function writeChanges(tasks, typeKey) {
  const existingTaskKeys = getSavedTaskKeys(typeKey)
  const newTaskKeys = tasks.map(task => task.storageKey)
  console.info(typeKey, newTaskKeys)
  const allTaskKeys = []
  existingTaskKeys.concat(newTaskKeys).forEach(key => {
    if (allTaskKeys.indexOf(key) < 0) {
      allTaskKeys.push(key)
    }
  })
  storage.set(typeKey, allTaskKeys)
}

function notificationsBySubject(notifications) {
  const result = {}
  if (typeof notifications === 'undefined') {
    return result
  }
  notifications.forEach(notification => {
    result[notification.subject.url] = notification.url
  })
  return result
}

// Remove the given tasks from the given key in the JSON storage file.
function removeTasks(tasks, typeKey) {
  const existingTaskKeys = getSavedTaskKeys(typeKey)
  const keysToRemove = tasks.map(task => task.storageKey)
  const allTaskKeys = []
  existingTaskKeys.forEach(key => {
    if (keysToRemove.indexOf(key) < 0) {
      allTaskKeys.push(key)
    }
  })
  storage.set(typeKey, allTaskKeys)
}

function updateTasks(tasks, action) {
  const tasksByKey = {}
  const snoozedTasks = getSavedTaskKeys(SNOOZED_KEY)
  const archivedTasks = getSavedTaskKeys(ARCHIVED_KEY)
  const ignoredTasks = getSavedTaskKeys(IGNORED_KEY)
  const notificationUrls = notificationsBySubject(action.notifications)

  // Add the existing tasks
  tasks.forEach(task => (tasksByKey[task.storageKey] = task))

  // Update tasks with new values and add new tasks
  action.tasks.forEach(task => {
    const updatedTask = Object.assign({}, tasksByKey[task.storageKey], task)
    const notificationUrl = notificationUrls[task.apiUrl]
    if (notificationUrl) {
      updatedTask.notificationUrl = notificationUrl
    }
    tasksByKey[task.storageKey] = updatedTask
  })

  const updatedTasks = Object.keys(tasksByKey).map(key => {
    const task = tasksByKey[key]
    if (snoozedTasks.indexOf(key) > -1) {
      task.snoozedAt = storage.get(key)
    }
    if (archivedTasks.indexOf(key) > -1) {
      task.archivedAt = storage.get(key)
    }
    if (ignoredTasks.indexOf(key) > -1) {
      task.ignore = true
    }
    return task
  })

  return updatedTasks
}

function selectTasks(tasks, action) {
  const selectedTasks = []
  const updatedTasks = tasks.map(task => {
    if (task.storageKey === action.task.storageKey) {
      selectedTasks.push(task)
      return Object.assign({}, task, { isSelected: true })
    }
    return task
  })
  console.info('select', selectedTasks.map(task => task.storageKey))
  return updatedTasks
}

function deselectTasks(tasks, action) {
  const deselectedTasks = []
  const updatedTasks = tasks.map(task => {
    if (task.storageKey === action.task.storageKey) {
      deselectedTasks.push(task)
      return Object.assign({}, task, { isSelected: false })
    }
    return task
  })
  console.info('deselect', deselectedTasks.map(task => task.storageKey))
  return updatedTasks
}

function currentTimeString() {
  const date = new Date()
  return date.toISOString()
}

function markNotificationsAsRead(tasks) {
  const tasksWithNotifications = tasks.filter(task => {
    return typeof task.notificationUrl === 'string'
  })
  const github = new GitHub()
  tasksWithNotifications.forEach(task => {
    github.markAsRead(task.notificationUrl).catch(err => {
      console.error('failed to mark notification as read', err, task)
    })
  })
}

function snoozeTasks(tasks) {
  const snoozedTasks = []
  const updatedTasks = tasks.map(task => {
    if (task.isSelected) {
      const snoozedAt = currentTimeString()
      storage.set(task.storageKey, snoozedAt)
      snoozedTasks.push(task)
      return Object.assign({}, task, {
        snoozedAt,
        archivedAt: null,
        isSelected: false,
        ignore: false,
      })
    }
    return task
  })
  markNotificationsAsRead(snoozedTasks)
  writeChanges(snoozedTasks, SNOOZED_KEY)
  return updatedTasks
}

function ignoreTasks(tasks) {
  const ignoredTasks = []
  const updatedTasks = tasks.map(task => {
    if (task.isSelected) {
      ignoredTasks.push(task)
      if (storage.has(task.storageKey)) {
        storage.delete(task.storageKey)
      }
      return Object.assign({}, task, {
        ignore: true,
        isSelected: false,
        snoozedAt: null,
        archivedAt: null,
      })
    }
    return task
  })
  markNotificationsAsRead(ignoredTasks)
  writeChanges(ignoredTasks, IGNORED_KEY)
  return updatedTasks
}

function archiveTasks(tasks) {
  const archivedTasks = []
  const updatedTasks = tasks.map(task => {
    if (task.isSelected) {
      const archivedAt = currentTimeString()
      storage.set(task.storageKey, archivedAt)
      archivedTasks.push(task)
      return Object.assign({}, task, {
        archivedAt,
        snoozedAt: null,
        isSelected: false,
        ignore: false,
      })
    }
    return task
  })
  markNotificationsAsRead(archivedTasks)
  writeChanges(archivedTasks, ARCHIVED_KEY)
  return updatedTasks
}

function restoreTasks(tasks) {
  const restoredTasks = []
  const updatedTasks = tasks.map(task => {
    if (task.isSelected) {
      storage.delete(task.storageKey)
      restoredTasks.push(task)
      return Object.assign({}, task, {
        archivedAt: null,
        ignore: false,
        snoozedAt: null,
        isSelected: false,
      })
    }
    return task
  })
  console.info('restore', restoredTasks.map(task => task.storageKey))
  removeTasks(restoredTasks, ARCHIVED_KEY)
  removeTasks(restoredTasks, SNOOZED_KEY)
  removeTasks(restoredTasks, IGNORED_KEY)
  return updatedTasks
}

function tasksReducer(tasks = [], action) {
  switch (action.type) {
    case 'TASKS_EMPTY':
      return []
    case 'TASKS_UPDATE':
      return updateTasks(tasks, action)
    case 'TASKS_SELECT':
      return selectTasks(tasks, action)
    case 'TASKS_DESELECT':
      return deselectTasks(tasks, action)
    case 'TASKS_SNOOZE':
      return snoozeTasks(tasks)
    case 'TASKS_ARCHIVE':
      return archiveTasks(tasks)
    case 'TASKS_IGNORE':
      return ignoreTasks(tasks)
    case 'TASKS_RESTORE':
      return restoreTasks(tasks)
    default:
      return tasks
  }
}

module.exports = combineReducers({
  tasks: tasksReducer,
})
<|endoftext|>


<commit_before>/*

Experimental...

*/
var net = require('net')
  , mingy = require('../../lib/mingy')
  , Client = mingy.Client
  , Parser = mingy.Parser
  , Command = mingy.Command
  , argv = require('optimist').argv

var parser = new Parser()

parser.addCommand('set')
.set('syntax', ['set <key> <value>'])
.set('logic', function(args, env, system) {

  system.server.write('set ' + args.key + ' ' + args.value)
  return "Attempting set..."
})

// when server has stored value, send command to get value
parser.addCommand('stored')
.set('syntax', ['stored'])
.set('logic', function(args, env) {
  return 'Set succeeded.'
})

var client = new Client(parser)
client.set('port', 8888).start(argv)
<commit_msg>Minor tweaks.<commit_after>/*

Experimental...

*/
var net = require('net')
  , mingy = require('../../lib/mingy')
  , Client = mingy.Client
  , Parser = mingy.Parser
  , Command = mingy.Command
  , argv = require('optimist').argv

var parser = new Parser()

// send command to server to set key to value
parser.addCommand('set')
.set('syntax', ['set <key> <value>'])
.set('logic', function(args, env, system) {

  system.server.write('set ' + args.key + ' ' + args.value)

  return "Attempting set..."
})

// when server has stored value, report success
parser.addCommand('stored')
.set('syntax', ['stored'])
.set('logic', function(args, env) {

  return 'Set succeeded.'
})

var client = new Client(parser)

console.log(client.set('port', 8888).start(argv))
<|endoftext|>


<commit_before>/* global describe, it */
var expect = require('expect.js');

describe('bootcode dependencies', function () {
    this.timeout(60 * 1000);

    var env = require('../../lib/environment'),
        Bundle = require('../../lib/bundle'),
        currentDependencies;

    before(function (done) {
        process && process.stdout.write('  -- building dependencies, please wait... ');
        Bundle.load(env).listDependencies(function (err, dependencies) {
            currentDependencies = dependencies;
            console.log(err ? 'failed' : 'done');
            return done(err);
        });
    });

    it('should not change', function () {
        expect(currentDependencies).to.be.eql([
            'array-uniq',
            'assert',
            'assertion-error',
            'atob',
            'backbone',
            'base64-js',
            'boolbase',
            'btoa',
            'buffer',
            'chai',
            'chai-postman',
            'charset',
            'check-error',
            'cheerio',
            'core-util-is',
            'crypto-js',
            'css-select',
            'css-what',
            'csv-parse',
            'deep-eql',
            'dom-serializer',
            'domelementtype',
            'domhandler',
            'domutils',
            'entities',
            'escape-html',
            'events',
            'file-type',
            'get-func-name',
            'htmlparser2',
            'http-reasons',
            'iconv-lite',
            'ieee754',
            'inherits',
            'isarray',
            'jquery',
            'liquid-json',
            'lodash',
            'lodash.assignin',
            'lodash.bind',
            'lodash.defaults',
            'lodash.escaperegexp',
            'lodash.filter',
            'lodash.flatten',
            'lodash.foreach',
            'lodash.map',
            'lodash.merge',
            'lodash.pick',
            'lodash.reduce',
            'lodash.reject',
            'lodash.some',
            'lodash3',
            'marked',
            'mime-db',
            'mime-format',
            'mime-types',
            'moment',
            'nth-check',
            'number-is-nan',
            'path-browserify',
            'pathval',
            'postman-collection',
            'postman-sandbox',
            'postman-url-encoder',
            'process',
            'process-nextick-args',
            'punycode',
            'querystring-es3',
            'readable-stream',
            'safe-buffer',
            'sanitize-html',
            'sax',
            'semver',
            'srcset',
            'stream-browserify',
            'string_decoder',
            'timers-browserify',
            'tv4',
            'type-detect',
            'underscore',
            'uniscope',
            'url',
            'util',
            'util-deprecate',
            'uuid',
            'xml2js',
            'xmlbuilder',
            'xtend'
        ]);
    });
});
<commit_msg>Update bootcode dependencies tests<commit_after>/* global describe, it */
var expect = require('expect.js');

describe('bootcode dependencies', function () {
    this.timeout(60 * 1000);

    var env = require('../../lib/environment'),
        Bundle = require('../../lib/bundle'),
        currentDependencies;

    before(function (done) {
        process && process.stdout.write('  -- building dependencies, please wait... ');
        Bundle.load(env).listDependencies(function (err, dependencies) {
            currentDependencies = dependencies;
            console.log(err ? 'failed' : 'done');
            return done(err);
        });
    });

    it('should not change', function () {
        expect(currentDependencies).to.be.eql([
            'ansi-styles',
            'array-uniq',
            'assert',
            'assertion-error',
            'atob',
            'backbone',
            'base64-js',
            'boolbase',
            'btoa',
            'buffer',
            'chai',
            'chai-postman',
            'chalk',
            'charset',
            'check-error',
            'cheerio',
            'color-convert',
            'color-name',
            'core-util-is',
            'crypto-js',
            'css-select',
            'css-what',
            'csv-parse',
            'deep-eql',
            'dom-serializer',
            'domelementtype',
            'domhandler',
            'domutils',
            'entities',
            'escape-html',
            'escape-string-regexp',
            'events',
            'file-type',
            'get-func-name',
            'has-flag',
            'htmlparser2',
            'http-reasons',
            'iconv-lite',
            'ieee754',
            'inherits',
            'isarray',
            'jquery',
            'liquid-json',
            'lodash',
            'lodash.assignin',
            'lodash.bind',
            'lodash.clonedeep',
            'lodash.defaults',
            'lodash.escaperegexp',
            'lodash.filter',
            'lodash.flatten',
            'lodash.foreach',
            'lodash.isplainobject',
            'lodash.isstring',
            'lodash.map',
            'lodash.merge',
            'lodash.mergewith',
            'lodash.pick',
            'lodash.reduce',
            'lodash.reject',
            'lodash.some',
            'lodash3',
            'marked',
            'mime-db',
            'mime-format',
            'mime-types',
            'moment',
            'nth-check',
            'number-is-nan',
            'path-browserify',
            'pathval',
            'postcss',
            'postman-collection',
            'postman-sandbox',
            'postman-url-encoder',
            'process',
            'process-nextick-args',
            'punycode',
            'querystring-es3',
            'readable-stream',
            'safe-buffer',
            'safer-buffer',
            'sanitize-html',
            'sax',
            'semver',
            'source-map',
            'srcset',
            'stream-browserify',
            'string_decoder',
            'supports-color',
            'timers-browserify',
            'tv4',
            'type-detect',
            'underscore',
            'uniscope',
            'url',
            'util',
            'util-deprecate',
            'uuid',
            'xml2js',
            'xmlbuilder',
            'xtend'
        ]);
    });
});
<|endoftext|>


<commit_before>'use strict';

/**
 * Requirements
 */
const CoreMediaRenderer = require(SOURCE_ROOT + '/transformer/CoreMediaRenderer.js').CoreMediaRenderer;
const Parser = require(SOURCE_ROOT + '/transformer/Parser.js').Parser;
const baseRendererSpec = require(TEST_ROOT + '/transformer/BaseRendererShared.js');
const glob = require('glob');
const fs = require('fs');
const co = require('co');

/**
 * Spec
 */
describe(CoreMediaRenderer.className, function()
{
    /**
     * Base Test
     */
    baseRendererSpec(CoreMediaRenderer, 'transformer/CoreMediaRenderer');

    /**
     * CoreMediaRenderer Test
     */
    function testFixture(name)
    {
        const promise = co(function*()
        {
            const rootPath = FIXTURES_ROOT + '/Transformer/';
            const input = fs.readFileSync(rootPath + name + '.input.j2', { encoding: 'utf8' }).replace(/\r/g, '');
            const expected = fs.readFileSync(rootPath + 'CoreMediaRenderer/' + name + '.expected.jsp', { encoding: 'utf8' }).replace(/\r/g, '');
            const parser = new Parser();
            const nodes = yield parser.parse(input);
            const testee = new CoreMediaRenderer();
            const jsp = yield testee.render(nodes);
            try
            {
                expect(jsp.trim()).to.be.deep.equal(expected.trim());
            }
            catch(e)
            {
                console.log('Parsed:');
                console.log(JSON.stringify(nodes.serialize(), null, 4));
                console.log('Rendered:');
                console.log(jsp);
                throw e;
            }
        });
        return promise;
    }

    xdescribe('#render()', function()
    {
        it('should render embedded variables', function()
        {
            return testFixture('variables');
        });

        it('should render set tags', function()
        {
            return testFixture('set');
        });

        it('should render filters', function()
        {
            return testFixture('filter');
        });

        it('should render macro calls', function()
        {
            return testFixture('calls');
        });

        it('should render flow tags (if, for)', function()
        {
            return testFixture('flow');
        });

        it('should render conditions', function()
        {
            return testFixture('condition');
        });

        it('should render macros', function()
        {
            return testFixture('macro');
        });

        it('should render translate filters', function()
        {
            return testFixture('translate');
        });
    });
});
<commit_msg>test(transformer): enabled tests<commit_after>'use strict';

/**
 * Requirements
 */
const CoreMediaRenderer = require(SOURCE_ROOT + '/transformer/CoreMediaRenderer.js').CoreMediaRenderer;
const Parser = require(SOURCE_ROOT + '/transformer/Parser.js').Parser;
const baseRendererSpec = require(TEST_ROOT + '/transformer/BaseRendererShared.js');
const glob = require('glob');
const fs = require('fs');
const co = require('co');

/**
 * Spec
 */
describe(CoreMediaRenderer.className, function()
{
    /**
     * Base Test
     */
    baseRendererSpec(CoreMediaRenderer, 'transformer/CoreMediaRenderer');

    /**
     * CoreMediaRenderer Test
     */
    function testFixture(name)
    {
        const promise = co(function*()
        {
            const rootPath = FIXTURES_ROOT + '/Transformer/';
            const input = fs.readFileSync(rootPath + name + '.input.j2', { encoding: 'utf8' }).replace(/\r/g, '');
            const expected = fs.readFileSync(rootPath + 'CoreMediaRenderer/' + name + '.expected.jsp', { encoding: 'utf8' }).replace(/\r/g, '');
            const parser = new Parser();
            const nodes = yield parser.parse(input);
            const testee = new CoreMediaRenderer();
            const jsp = yield testee.render(nodes);
            try
            {
                expect(jsp.trim()).to.be.deep.equal(expected.trim());
            }
            catch(e)
            {
                console.log('Parsed:');
                console.log(JSON.stringify(nodes.serialize(), null, 4));
                console.log('Rendered:');
                console.log(jsp);
                throw e;
            }
        });
        return promise;
    }

    describe('#render()', function()
    {
        it('should render embedded variables', function()
        {
            return testFixture('variables');
        });

        it('should render set tags', function()
        {
            return testFixture('set');
        });

        it('should render filters', function()
        {
            return testFixture('filter');
        });

        it('should render macro calls', function()
        {
            return testFixture('calls');
        });

        it('should render flow tags (if, for)', function()
        {
            return testFixture('flow');
        });

        it('should render conditions', function()
        {
            return testFixture('condition');
        });

        it('should render macros', function()
        {
            return testFixture('macro');
        });

        it('should render translate filters', function()
        {
            return testFixture('translate');
        });
    });
});
<|endoftext|>


<commit_before>"use strict";

module.exports = {
    "wires.json": {
        "path": `./lib`,
        "cmdPath": `>/lib`,
        ":cmdPath": `>/lib/nodeVersion`,
        ":resolvedRoute": `./lib/test.js`,
        "indirectResolvedRoute": `./lib/test.js`,
        ":indirectResolvedRoute": `{#indirectResolvedRoute}`,
        ":homeRoute": `~/--wires-does-not-exist.js`,
    },
    "resolved_path.unit.js"() {
        const { resolve } = require( `path` );
        module.exports = {
            async test( __ ) {
                __.plan( 11 );
                __.strictEqual( require.resolve( `:cmdPath` ), resolve( process.cwd(), `lib/nodeVersion.js` ) );
                await Promise.allSettled( [
                    importAndRequire.all( [
                        [ `#path`, `./lib` ],
                        [ `#cmdPath`, `>/lib` ],
                        [ `:resolvedRoute`, `lib/test` ],
                        [ `:indirectResolvedRoute`, `lib/test` ],
                    ] ).strictEqual(),
                    importAndRequire( `:homeRoute` ).throws( / Cannot find module / ),
                ] );
            },
        };
    },
    "/lib": {
        "wires.json": {
            ":backResolvedRoute": `../lib/test.js`,
        },
        "test.js"() {
            module.exports = `lib/test`;
        },
        "resolved_path_sub.unit.js"() {
            const { resolve } = require( `path` );
            module.exports = {
                async test( __ ) {
                    __.plan( 13 );
                    __.strictEqual( require.resolve( `:cmdPath` ), resolve( process.cwd(), `lib/nodeVersion.js` ) );
                    await Promise.allSettled( [
                        importAndRequire.all( [
                            [ `#path`, `./lib` ],
                            [ `#cmdPath`, `>/lib` ],
                            [ `:resolvedRoute`, `lib/test` ],
                            [ `:backResolvedRoute`, `lib/test` ],
                            [ `:indirectResolvedRoute`, `lib/test` ],
                        ] ).strictEqual(),
                        importAndRequire( `:homeRoute` ).throws( / Cannot find module / ),
                    ] );
                },
            };
        },
    },
};
<commit_msg>Simplifies test.<commit_after>"use strict";

module.exports = {
    "wires.json": {
        "path": `./lib`,
        "cmdPath": `>/lib`,
        ":cmdPath": `>/lib/nodeVersion.js`,
        ":resolvedRoute": `./lib/test.js`,
        "indirectResolvedRoute": `./lib/test.js`,
        ":indirectResolvedRoute": `{#indirectResolvedRoute}`,
        ":homeRoute": `~/--wires-does-not-exist.js`,
    },
    "resolved_path.unit.js"() {
        const { resolve } = require( `path` );
        module.exports = {
            async test( __ ) {
                __.plan( 12 );
                await Promise.allSettled( [
                    importAndRequire( `:cmdPath` ).sameAs( resolve( process.cwd(), `lib/nodeVersion.js` ) ),
                    importAndRequire.all( [
                        [ `#path`, `./lib` ],
                        [ `#cmdPath`, `>/lib` ],
                        [ `:resolvedRoute`, `lib/test` ],
                        [ `:indirectResolvedRoute`, `lib/test` ],
                    ] ).strictEqual(),
                    importAndRequire( `:homeRoute` ).throws( / Cannot find module / ),
                ] );
            },
        };
    },
    "/lib": {
        "wires.json": {
            ":backResolvedRoute": `../lib/test.js`,
        },
        "test.js"() {
            module.exports = `lib/test`;
        },
        "resolved_path_sub.unit.js"() {
            const { resolve } = require( `path` );
            module.exports = {
                async test( __ ) {
                    __.plan( 14 );
                    await Promise.allSettled( [
                        importAndRequire( `:cmdPath` ).sameAs( resolve( process.cwd(), `lib/nodeVersion.js` ) ),
                        importAndRequire.all( [
                            [ `#path`, `./lib` ],
                            [ `#cmdPath`, `>/lib` ],
                            [ `:resolvedRoute`, `lib/test` ],
                            [ `:backResolvedRoute`, `lib/test` ],
                            [ `:indirectResolvedRoute`, `lib/test` ],
                        ] ).strictEqual(),
                        importAndRequire( `:homeRoute` ).throws( / Cannot find module / ),
                    ] );
                },
            };
        },
    },
};
<|endoftext|>