<commit_before>/* eslint-env mocha */
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

describe('generator-underhood:app', function describe() {
  before(function before(done) {
    helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        underhoodName: 'yo',
        underhoodDesc: 'best yo from the yoest',
        underhoodSite: 'yo.ru',
        githubUser: 'uhs',
        githubRepo: 'yo',
        curatorEmail: 'curator@ema.il',
        curatorTwitter: 'curator',
      })
      .on('end', done);
  });

  it('creates files', function it() {
    assert.file([
      '.underhoodrc.json',
      'css/styles.css',
      'js/index.js',
      'static/CNAME',
      'static/.nojekyll',
      'dump/index.js',
      'helpers/author-render.js',
      'helpers/bust.js',
      'helpers/ensure-author-files.js',
      'helpers/get-author-area.js',
      'helpers/get-links.js',
      'helpers/last-updated.js',
      'helpers/log.js',
      'helpers/save-author-area.js',
      'helpers/save-media.js',
      'helpers/save.js',
      'helpers/ungroup-into.js',
      'layouts/article.jade',
      'layouts/author.jade',
      'layouts/footer.jade',
      'layouts/gauges.jade',
      'layouts/head.jade',
      'layouts/header.jade',
      'layouts/index.jade',
      'layouts/menu.jade',
      'layouts/page.jade',
      'layouts/share-text.jade',
      'layouts/share.jade',
      'layouts/stats.jade',
      'pages/about.md',
      'pages/authoring.md',
      'pages/instruction.md',
      '.editorconfig',
      '.eslintignore',
      '.eslintrc',
      '.gitignore',
      '.travis.yml',
      'authors.js',
      'gulpfile.babel.js',
      'README.md',
      'stats.js',
      'test.js',
      'update.js',
      'webpack.config.babel.js',
      'package.json',
      '.git',
      'migration.js',
      'CHANGELOG.md',
      'ROADMAP.md',
    ]);
  });

  it('creates files with proper extrapolation', function it() {
    assert.fileContent('static/CNAME', 'yo.ru');
    assert.fileContent('./pages/about.md', 'yo');
    assert.fileContent('pages/about.md', 'best yo from the yoest');
    assert.fileContent('pages/about.md', 'https://twitter.com/yo');
    assert.fileContent('pages/authoring.md', 'https://twitter.com/yo');
    assert.fileContent('pages/authoring.md', 'curator@ema.il');
    assert.fileContent('deploy.sh', 'git remote add origin https://uhs:${GITHUB_TOKEN}@github.com/uhs/yo.git');
    assert.fileContent('README.md', 'best yo from the yoest');
    assert.fileContent('README.md', 'yo.ru');
    assert.fileContent('layouts/gauges.jade', '568823b84b2ffa534600335e');
  });
});

describe('underhood:app with alredy existing .underhoodrc.json', function () {
  before(function before(done) {
    helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        underhoodDesc: 'best yo from the yoest',
        underhoodSite: 'yo.ru',
        githubUser: 'uhs',
        githubRepo: 'yo',
        curatorEmail: 'curator@ema.il',
        curatorTwitter: 'curator',
      })
      .on('ready', function onReady(gen) {
        gen.fs.write(gen.destinationPath('.underhoodrc.json'), '{ "underhood": "yay" }');
      }.bind(this))
      .on('end', done);
  });

  it('creates files with proper extrapolation', function it() {
    assert.fileContent('.underhoodrc.json', 'yay');
  });
});
<commit_msg>fix shadowing<commit_after>/* eslint-env mocha */
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

describe('generator-underhood:app', function _describe() {
  before(function _before(done) {
    helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        underhoodName: 'yo',
        underhoodDesc: 'best yo from the yoest',
        underhoodSite: 'yo.ru',
        githubUser: 'uhs',
        githubRepo: 'yo',
        curatorEmail: 'curator@ema.il',
        curatorTwitter: 'curator',
      })
      .on('end', done);
  });

  it('creates files', function _it() {
    assert.file([
      '.underhoodrc.json',
      'css/styles.css',
      'js/index.js',
      'static/CNAME',
      'static/.nojekyll',
      'dump/index.js',
      'helpers/author-render.js',
      'helpers/bust.js',
      'helpers/ensure-author-files.js',
      'helpers/get-author-area.js',
      'helpers/get-links.js',
      'helpers/last-updated.js',
      'helpers/log.js',
      'helpers/save-author-area.js',
      'helpers/save-media.js',
      'helpers/save.js',
      'helpers/ungroup-into.js',
      'layouts/article.jade',
      'layouts/author.jade',
      'layouts/footer.jade',
      'layouts/gauges.jade',
      'layouts/head.jade',
      'layouts/header.jade',
      'layouts/index.jade',
      'layouts/menu.jade',
      'layouts/page.jade',
      'layouts/share-text.jade',
      'layouts/share.jade',
      'layouts/stats.jade',
      'pages/about.md',
      'pages/authoring.md',
      'pages/instruction.md',
      '.editorconfig',
      '.eslintignore',
      '.eslintrc',
      '.gitignore',
      '.travis.yml',
      'authors.js',
      'gulpfile.babel.js',
      'README.md',
      'stats.js',
      'test.js',
      'update.js',
      'webpack.config.babel.js',
      'package.json',
      '.git',
      'migration.js',
      'CHANGELOG.md',
      'ROADMAP.md',
    ]);
  });

  it('creates files with proper extrapolation', function _it() {
    assert.fileContent('static/CNAME', 'yo.ru');
    assert.fileContent('./pages/about.md', 'yo');
    assert.fileContent('pages/about.md', 'best yo from the yoest');
    assert.fileContent('pages/about.md', 'https://twitter.com/yo');
    assert.fileContent('pages/authoring.md', 'https://twitter.com/yo');
    assert.fileContent('pages/authoring.md', 'curator@ema.il');
    assert.fileContent('deploy.sh', 'git remote add origin https://uhs:${GITHUB_TOKEN}@github.com/uhs/yo.git');
    assert.fileContent('README.md', 'best yo from the yoest');
    assert.fileContent('README.md', 'yo.ru');
    assert.fileContent('layouts/gauges.jade', '568823b84b2ffa534600335e');
  });
});

describe('generator-underhood:app with existing .underhoodrc.json', function _describe() {
  before(function _before(done) {
    helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        underhoodDesc: 'best yo from the yoest',
        underhoodSite: 'yo.ru',
        githubUser: 'uhs',
        githubRepo: 'yo',
        curatorEmail: 'curator@ema.il',
        curatorTwitter: 'curator',
      })
      .on('ready', function onReady(gen) {
        gen.fs.write(gen.destinationPath('.underhoodrc.json'), '{ "underhood": "yay" }');
      }.bind(this))
      .on('end', done);
  });

  it('creates files with proper extrapolation', function _it() {
    assert.fileContent('.underhoodrc.json', 'yay');
  });
});
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-generator').test;

describe('generator-hubot-script-babel:app', function () {
  before(function (done) {
    helpers.run(path.join(__dirname, '../generators/app'))
      .withOptions({someOption: true})
      .withPrompts({someAnswer: true})
      .on('end', done);
  });

  it('creates files', function () {
    assert.file([
      'dummyfile.txt'
    ]);
  });
});
<commit_msg>Updated tests<commit_after>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-generator').test;

describe('generator-hubot-script-babel:app', function () {
  before(function (done) {
    helpers.run(path.join(__dirname, '../generators/app'))
      .withPrompts({
        name: 'script-test',
        description: 'script description'
      })
      .on('end', done);
  });

  it('creates files', function () {
    assert.file([
      'package.json',
      'webpack.config.js',
      'test/index.js',
      'src/index.js'
    ]);
  });
});
<|endoftext|>


<commit_before>var Ebets = artifacts.require('ebets');
var Bet = artifacts.require('Bet');
var BigNumber = require('bignumber.js');

contract('ebets', accounts => {
  var newBet;
  it('Should make a bet', () => {
    return Ebets.new({from: accounts[0]})
    .then(instance => {
      var now = Math.floor(Date.now() / 1000);
      var array = [now + 100000, now + 200000, now + 300000, now + 400000];

      return instance.create_bet('A', 'B', 'LOL', 'AID', 'BID',
        array, 'asdasdas', {gas: 4300000, from: accounts[0]});
    })
    .then(events => {
      console.log(events);
      var addr = events.logs[0].args.bet_addr;
      var new_bet = Bet.at(addr);
      newBet = new_bet;
      return new_bet;
    })
    .then(toggled => {
      return newBet.is_featured();
    })
    .then(featured_bet => {
      console.log(featured_bet);
    });
  });
});

<commit_msg>bet tests<commit_after>const Ebets = artifacts.require('ebets');
const Bet = artifacts.require('Bet');
const Monarchy = artifacts.require('Monarchy');
const BigNumber = require('bignumber.js');

const increaseTime = (time) => {
  return new Promise((resolve, reject) => {
    web3.currentProvider.sendAsync({
      jsonrpc: "2.0",
      method: "evm_increaseTime",
      params: [time], // time in seconds
      id: 1231231231231
    }, (err, success) => {
    if (err) reject(err);
    else resolve(success);
    });
  });
}

const getBalancePromise = (address) => {
  return new Promise((resolve, reject) => {
    web3.eth.getBalance(address, (err, result) => {
      if (err) reject(err);
      else resolve(result);
    });
  });
}

contract('ebets', accounts => {
  var arbiterInstance;
  var createdBet;
  before((done) => {
    Monarchy.new({from: accounts[0]})
    .then(instance => {
      arbiterInstance = instance;
    })
    .then(() => {
      return Ebets.new({from: accounts[0]})
    })
    .then(betInstance => {
      const now = Math.floor(Date.now() / 1000);
      const beginMatch = now + 1010;
      const endMatch = beginMatch + 50;
      const arbiterDeadline = endMatch + 50000;
      const terminateDeadline = arbiterDeadline + 50000;

      var timestamps = [beginMatch, endMatch, arbiterDeadline, terminateDeadline];

      return betInstance.createBet(arbiterInstance.address, 'A', 'B', 'LOL',
        timestamps,{gas: 4300000, from: accounts[0]});
    })
    .then(events => {
      var addr = events.logs[0].args.betAddr;
      createdBet = Bet.at(addr);
      done();
    })
  });

  it('Bet should start open', (done) => {
    createdBet.betState()
    .then(betState => {
      assert(betState.equals(new BigNumber(0)));
      done();
    });
  });

  it('Check bet teams', (done) => {
    createdBet.team0Name()
    .then(team0Name => {
      assert(team0Name === 'A');
    });
    createdBet.team1Name()
    .then(team1Name => {
      assert(team1Name === 'B');
      done();
    });
  });

  it('Arbiter should not bet!', (done) => {
    createdBet.bet(false, {from: accounts[0]})
    .then()
    .catch(err => {
      assert(true);
      done();
    });
  });

  it('Bet on team A', (done) => {
    createdBet.bet(false, {from: accounts[1], value: `0x${(1e18).toString(16)}`})
    .then(receipt => {
      assert(receipt.logs[0].event === 'NewBet');
      done();
    });
  });

  it('Cannot bet on team A and B afterwards', (done) => {
    createdBet.bet(true, {from: accounts[1], value: 1e18})
    .then()
    .catch(err => {
      assert(true);
      done();
    });
  });

  it('Bet on team B', (done) => {
     createdBet.bet(true, {from: accounts[2], value: `0x${(1e18).toString(16)}`})
    .then(receipt => {
      assert(receipt.logs[0].event === 'NewBet');
      done();
    });
  })

  it('Calls the resolver', (done) => {
    createdBet.updateResult()
    .then(receipt => {
      done();
    });
  });

  it('Only arbiter can vote', (done) => {
    // Cast so team 0 won
    arbiterInstance.castVote(createdBet.address, 1, {from: accounts[3]})
    .then(() => {
      assert(false);
    })
    .catch(() => {
      assert(true);
      done();
    });
  });

  it('Resolve the bet to team 0', (done) => {
    // Cast so team 0 won
    arbiterInstance.castVote(createdBet.address, 1)
    .then(receipt => {
      return createdBet.betState()
    })
    .then(betState => {
      assert(betState.toNumber() == 1);
      done();
    });
  });

  it('Withdraws accounts[1]', (done) => {
    // Cast so team A won
    var previousBalance;
    getBalancePromise(accounts[1])
    .then(balance => {
      previousBalance = balance;
      return createdBet.withdraw({from: accounts[1]})
    })
    .then(receipt => {
      return getBalancePromise(accounts[1]);
    })
    .then(balance => {
      assert(previousBalance.lessThan(balance));
      done();
    })
  });

})

<|endoftext|>


<commit_before>var path     = require('path');
var should   = require('chai').should();
var expect   = require('chai').expect;
var avisynth = require('../main');
var system   = require('../code/system');
var my       = require('../package.json');

// Since testing a command line script is a bunch of boilerplate, I'll abstract it.
function testCli(doneCallback, args, stdin, expectedCode, expectedOut, expectedErr) {
    // Note that while we use a shebang in the cli script and npm can wrap it in
    // shell scripts automatically, in this case we're running it by itself and
    // in Windows shebangs don't count. So we must explicitely run it through node.
    var cli = path.resolve(__dirname, '../cli.js');
    var args = [cli].concat(args);
    // Also note that we're reusing system's spawn because we're not masochists.
    system.spawn('node', args, __dirname, true, function(returnCode, stdout, stderr) {
        expect(returnCode).to.equal(expectedCode);
        // Note how expectedOut and expectedErr can be strings or validator functions.
        if (typeof expectedOut === 'string') {
            expect(stdout).to.equal(expectedOut);
        } else {
            expect(expectedOut(stdout)).to.equal(true);
        }
        if (typeof expectedErr === 'string') {
            expect(stderr).to.equal(expectedErr);
        } else {
            expect(expectedErr(stderr)).to.equal(true);
        }

        doneCallback();
    });
}

describe('Command-line interface', function() {
    this.timeout(10000); // All tests here shouldn't fail because of timeouts.

    describe('avisynth-js version', function() {
        it('should print the version number', function(done) {
            testCli(done, ['version'], null, 0, my.version + '\n', '');
        });
    });

    describe('avisynth-js help', function() {
        it('should print the help without warnings', function(done) {
            testCli(done, ['help'], null, 0, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                lines.forEach(function(line) {
                    if (/^Bad argument: /.test(line)) ok = false;
                });
                if (!/^Usage: /.test(lines[4])) ok = false;
                return ok;
            }, '');
        });

        it('should print help with warnings when a bad command is used', function(done) {
            testCli(done, ['feminism'], null, 1, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                if (lines[4] !== 'Bad argument: "feminism"') ok = false;
                if (!/^Usage: /.test(lines[6])) ok = false;
                return ok;
            }, '');
        });

        it('should print help without warnings when no command is used', function(done) {
            testCli(done, [], null, 0, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                lines.forEach(function(line) {
                    if (/^Bad argument: /.test(line)) ok = false;
                });
                if (!/^Usage: /.test(lines[4])) ok = false;
                return ok;
            }, '');
        });
    });

    describe('avisynth-js info', function() {
    });

    describe('avisynth-js info', function() {
        it('should return expected info (NTSC broadcast example)', function(done) {
            // Let's cook up a NTSC broadcast example.
            var script = new avisynth.Script();
            script.colorBarsHD(640, 480);
            script.assumeFPS('ntsc_film');
            script.trim(1, 1438);
            script.code('AudioDub(Tone(54.321, 432, 44056, 1))');
            script.convertAudioTo16bit();
            script.convertToYV12();
            script.assumeFieldBased();
            script.assumeTFF();

            var info = {
                width         : 640,
                height        : 480,
                ratio         : '4:3',
                fps           : 23.976,
                fpsFraction   : '24000/1001',
                videoTime     : 59.9766,
                frameCount    : 1438,
                colorspace    : 'YV12',
                bitsPerPixel  : 12,
                interlaceType : 'field-based',
                fieldOrder    : 'TFF',
                channels      : 1,
                bitsPerSample : 16,
                sampleType    : 'int',
                audioTime     : 54.321,
                samplingRate  : 44056,
                sampleCount   : 2393166,
                blockSize     : 2
            };

            var args = ['info', script.getPath()];
            var infoJson = JSON.stringify(info, undefined, 4);
            testCli(done, args, null, 0, infoJson + '\n', '');
        });

        it('should return expected info (1080p production example)', function(done) {
            // Let's cook up a 1080p "production-grade" example.
            var script = new avisynth.Script();
            script.colorBarsHD(1920, 1080);
            script.assumeFPS(60);
            script.trim(1, 3600);
            script.code('AudioDub(Tone(60, 528, 48000, 6))');
            script.convertAudioToFloat();
            script.convertToYUY2();
            script.assumeFrameBased();

            var info = {
                width         : 1920,
                height        : 1080,
                ratio         : '16:9',
                fps           : 60,
                fpsFraction   : '60/1',
                videoTime     : 60,
                frameCount    : 3600,
                colorspace    : 'YUY2',
                bitsPerPixel  : 16,
                interlaceType : 'frame-based',
                fieldOrder    : 'BFF',
                channels      : 6,
                bitsPerSample : 32,
                sampleType    : 'float',
                audioTime     : 60,
                samplingRate  : 48000,
                sampleCount   : 2880000,
                blockSize     : 24
            };

            var args = ['info', script.getPath()];
            var infoJson = JSON.stringify(info, undefined, 4);
            testCli(done, args, null, 0, infoJson + '\n', '');
        });

        it('should return an error when no script is provided', function(done) {
            var args = ['info'];
            var msg = 'An Avisynth script path must be provided.\n';
            testCli(done, args, null, 2, msg, '');
        });

        it('should return an error when script does not exist', function(done) {
            var args = ['info', 'C:/miss1ng5cript.avs'];
            var msg = 'Script not found: "C:/miss1ng5cript.avs"\n';
            testCli(done, args, null, 3, msg, '');
        });

        it('should return an error when script has code errors', function(done) {
            var script = new avisynth.Script('Egalitarianism');
            var args = ['info', script.getPath()];
            testCli(done, args, null, 4, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                if (lines[0] !== 'Avisynth script could not be processed:') ok = false;
                if (lines[1] !== "I don't know what 'Egalitarianism' means.") ok = false;
                return ok;
            }, '');
        });
    });

    describe('avisynth-js lint', function() {
        it('should return valid status for a valid script', function(done) {
            // Same NTSC broadcast example from before.
            var script = new avisynth.Script();
            script.colorBarsHD(640, 480);
            script.assumeFPS('ntsc_film');
            script.trim(1, 1438);
            script.code('AudioDub(Tone(54.321, 432, 44056, 1))');
            script.convertAudioTo16bit();
            script.convertToYV12();
            script.assumeFieldBased();
            script.assumeTFF();

            var args = ['lint', script.getPath()];
            var json = JSON.stringify({valid: true, message: null}, undefined, 4);
            testCli(done, args, null, 0, json + '\n', '');
        });
    });
});
<commit_msg>Test for returning error when no script is provided.<commit_after>var path     = require('path');
var should   = require('chai').should();
var expect   = require('chai').expect;
var avisynth = require('../main');
var system   = require('../code/system');
var my       = require('../package.json');

// Since testing a command line script is a bunch of boilerplate, I'll abstract it.
function testCli(doneCallback, args, stdin, expectedCode, expectedOut, expectedErr) {
    // Note that while we use a shebang in the cli script and npm can wrap it in
    // shell scripts automatically, in this case we're running it by itself and
    // in Windows shebangs don't count. So we must explicitely run it through node.
    var cli = path.resolve(__dirname, '../cli.js');
    var args = [cli].concat(args);
    // Also note that we're reusing system's spawn because we're not masochists.
    system.spawn('node', args, __dirname, true, function(returnCode, stdout, stderr) {
        expect(returnCode).to.equal(expectedCode);
        // Note how expectedOut and expectedErr can be strings or validator functions.
        if (typeof expectedOut === 'string') {
            expect(stdout).to.equal(expectedOut);
        } else {
            expect(expectedOut(stdout)).to.equal(true);
        }
        if (typeof expectedErr === 'string') {
            expect(stderr).to.equal(expectedErr);
        } else {
            expect(expectedErr(stderr)).to.equal(true);
        }

        doneCallback();
    });
}

describe('Command-line interface', function() {
    this.timeout(10000); // All tests here shouldn't fail because of timeouts.

    describe('avisynth-js version', function() {
        it('should print the version number', function(done) {
            testCli(done, ['version'], null, 0, my.version + '\n', '');
        });
    });

    describe('avisynth-js help', function() {
        it('should print the help without warnings', function(done) {
            testCli(done, ['help'], null, 0, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                lines.forEach(function(line) {
                    if (/^Bad argument: /.test(line)) ok = false;
                });
                if (!/^Usage: /.test(lines[4])) ok = false;
                return ok;
            }, '');
        });

        it('should print help with warnings when a bad command is used', function(done) {
            testCli(done, ['feminism'], null, 1, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                if (lines[4] !== 'Bad argument: "feminism"') ok = false;
                if (!/^Usage: /.test(lines[6])) ok = false;
                return ok;
            }, '');
        });

        it('should print help without warnings when no command is used', function(done) {
            testCli(done, [], null, 0, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                lines.forEach(function(line) {
                    if (/^Bad argument: /.test(line)) ok = false;
                });
                if (!/^Usage: /.test(lines[4])) ok = false;
                return ok;
            }, '');
        });
    });

    describe('avisynth-js info', function() {
    });

    describe('avisynth-js info', function() {
        it('should return expected info (NTSC broadcast example)', function(done) {
            // Let's cook up a NTSC broadcast example.
            var script = new avisynth.Script();
            script.colorBarsHD(640, 480);
            script.assumeFPS('ntsc_film');
            script.trim(1, 1438);
            script.code('AudioDub(Tone(54.321, 432, 44056, 1))');
            script.convertAudioTo16bit();
            script.convertToYV12();
            script.assumeFieldBased();
            script.assumeTFF();

            var info = {
                width         : 640,
                height        : 480,
                ratio         : '4:3',
                fps           : 23.976,
                fpsFraction   : '24000/1001',
                videoTime     : 59.9766,
                frameCount    : 1438,
                colorspace    : 'YV12',
                bitsPerPixel  : 12,
                interlaceType : 'field-based',
                fieldOrder    : 'TFF',
                channels      : 1,
                bitsPerSample : 16,
                sampleType    : 'int',
                audioTime     : 54.321,
                samplingRate  : 44056,
                sampleCount   : 2393166,
                blockSize     : 2
            };

            var args = ['info', script.getPath()];
            var infoJson = JSON.stringify(info, undefined, 4);
            testCli(done, args, null, 0, infoJson + '\n', '');
        });

        it('should return expected info (1080p production example)', function(done) {
            // Let's cook up a 1080p "production-grade" example.
            var script = new avisynth.Script();
            script.colorBarsHD(1920, 1080);
            script.assumeFPS(60);
            script.trim(1, 3600);
            script.code('AudioDub(Tone(60, 528, 48000, 6))');
            script.convertAudioToFloat();
            script.convertToYUY2();
            script.assumeFrameBased();

            var info = {
                width         : 1920,
                height        : 1080,
                ratio         : '16:9',
                fps           : 60,
                fpsFraction   : '60/1',
                videoTime     : 60,
                frameCount    : 3600,
                colorspace    : 'YUY2',
                bitsPerPixel  : 16,
                interlaceType : 'frame-based',
                fieldOrder    : 'BFF',
                channels      : 6,
                bitsPerSample : 32,
                sampleType    : 'float',
                audioTime     : 60,
                samplingRate  : 48000,
                sampleCount   : 2880000,
                blockSize     : 24
            };

            var args = ['info', script.getPath()];
            var infoJson = JSON.stringify(info, undefined, 4);
            testCli(done, args, null, 0, infoJson + '\n', '');
        });

        it('should return an error when no script is provided', function(done) {
            var args = ['info'];
            var msg = 'An Avisynth script path must be provided.\n';
            testCli(done, args, null, 2, msg, '');
        });

        it('should return an error when script does not exist', function(done) {
            var args = ['info', 'C:/miss1ng5cript.avs'];
            var msg = 'Script not found: "C:/miss1ng5cript.avs"\n';
            testCli(done, args, null, 3, msg, '');
        });

        it('should return an error when script has code errors', function(done) {
            var script = new avisynth.Script('Egalitarianism');
            var args = ['info', script.getPath()];
            testCli(done, args, null, 4, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                if (lines[0] !== 'Avisynth script could not be processed:') ok = false;
                if (lines[1] !== "I don't know what 'Egalitarianism' means.") ok = false;
                return ok;
            }, '');
        });
    });

    describe('avisynth-js lint', function() {
        it('should return valid status for a valid script', function(done) {
            // Same NTSC broadcast example from before.
            var script = new avisynth.Script();
            script.colorBarsHD(640, 480);
            script.assumeFPS('ntsc_film');
            script.trim(1, 1438);
            script.code('AudioDub(Tone(54.321, 432, 44056, 1))');
            script.convertAudioTo16bit();
            script.convertToYV12();
            script.assumeFieldBased();
            script.assumeTFF();

            var args = ['lint', script.getPath()];
            var json = JSON.stringify({valid: true, message: null}, undefined, 4);
            testCli(done, args, null, 0, json + '\n', '');
        });

        it('should return an error when no script is provided', function(done) {
            var args = ['lint'];
            var msg = 'An Avisynth script path must be provided.\n';
            testCli(done, args, null, 2, msg, '');
        });
    });
});
<|endoftext|>


<commit_before>// Functions for appending size information on a URL
resize = function(url, width, height) {
    var filenameStart = Math.max(url.lastIndexOf("/"), 0);
    var path = url.substring(0, filenameStart);
    var filename = url.substring(filenameStart);
    console.info(filename)
    var extensionStart = filename.lastIndexOf(".");
    if (extensionStart == -1) {
        extensionStart = filename.length;
    }
    var extension = filename.substring(extensionStart);
    console.info(extension)
    var filenameWithoutExtension = filename.substring(0, extensionStart);
    return path + filenameWithoutExtension + "." + width.toString() +
           "x" + height.toString() + extension;
}<commit_msg>Removed javascript console logging<commit_after>// Functions for appending size information on a URL
resize = function(url, width, height) {
    var filenameStart = Math.max(url.lastIndexOf("/"), 0);
    var path = url.substring(0, filenameStart);
    var filename = url.substring(filenameStart);
    var extensionStart = filename.lastIndexOf(".");
    if (extensionStart == -1) {
        extensionStart = filename.length;
    }
    var extension = filename.substring(extensionStart);
    var filenameWithoutExtension = filename.substring(0, extensionStart);
    return path + filenameWithoutExtension + "." + width.toString() +
           "x" + height.toString() + extension;
}<|endoftext|>


<commit_before>var fs = require('fs');
var zlib = require('zlib');
var async = require('async');
var _ = require('lodash');
var CSVStore = require('../csv-interface.js');

var TMPDIR = "./tmp/";
var CSVNAME = "test.csv";
var CSVGEN = "gen.csv";
var CSVFILE = TMPDIR + CSVNAME;
var CSVGENFILE = TMPDIR + CSVGEN;
var CANDLES = [{s:1 ,o:2 ,h:3 ,l:4 ,c:5 ,p:6},
	       {s:10,o:20,h:30,l:40,c:50,p:60}];
var DATA = "1,2,3,4,5,6\n"
           + "10,20,30,40,50,60";

function deflate(file, data, next) {
    zlib.deflate(data, function(err, buffer) { next(err, file, buffer) });
}

function save(file, buffer, next) {
    fs.writeFile(file, buffer, function(err) { next(err); });
}

function cleanUp(path, next) {
    if( fs.existsSync(path) ) {
        var files = [];
        files = fs.readdirSync(path);
        files.forEach(function(file,index){
            var curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()) {
		// recurse
                cleanUp(curPath);
            } else {
		// delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
    next(null, path);
}

function buffersEqual(a, b) {
    if (!Buffer.isBuffer(a)) return undefined;
    if (!Buffer.isBuffer(b)) return undefined;
    if (a.length !== b.length) return false;
    for (var i = 0; i < a.length; i++) {
        if (a[i] !== b[i]) return false;
    }
    return true;
};

Function.prototype.trycatch = function(catcher) {
    return _.wrap(this, function(func) {
	try {
	    func.apply('a', arguments);
	} catch(e) {
	    catcher(e);
	}
    });
}

module.exports = {
    setUp: function(done) {
        fs.existsSync(TMPDIR) || fs.mkdirSync(TMPDIR);
	async.compose(save, deflate)(CSVFILE, DATA, done);
    },
    tearDown: function(done) {
        fs.existsSync(TMPDIR) && cleanUp(TMPDIR, done);
    },
    test_loadFile: function(test) {
        var csv = new CSVStore({history: {directory: TMPDIR}});
        csv.read(CSVNAME, function(candles) {
            test.deepEqual(candles, CANDLES, "Loaded candles seem corrupt");
            test.done();
        });
    },
    test_saveFile: function(test) {
        var csv = new CSVStore({history: {directory: TMPDIR}});
        csv.write(CSVGEN, CANDLES, function(candles) {
	    fs.readFile(CSVGENFILE, function(err, buffer) {
		if(err) throw err;
		zlib.deflate(DATA, function(err, databuf) {
		    try {
			test.ok(buffersEqual(buffer, databuf), "Persisted candles seem corrupt");
			test.done();
		    } catch(e) {
			console.log(e);
		    }
		});
	    });
	});
    }
};
<commit_msg>Added testcase for saving and loading the whle day and also a type-checking testcase.<commit_after>var fs = require('fs');
var zlib = require('zlib');
var async = require('async');
var _ = require('lodash');
var CSVStore = require('../csv-interface.js');

var TMPDIR = "./tmp/";
var CSVNAME = "test.csv";
var CSVGEN = "gen.csv";
var DAY_FILE = "day.csv";
var CSVFILE = TMPDIR + CSVNAME;
var CSVGENFILE = TMPDIR + CSVGEN;
var DAY_PATH = TMPDIR + DAY_FILE;
var CANDLES = [{s:1 ,o:2 ,h:3 ,l:4 ,c:5 ,p:6},
	       {s:10,o:20,h:30,l:40,c:50,p:60}];
var DATA = "1,2,3,4,5,6\n"
           + "10,20,30,40,50,60";
var GEN_CANDLES = 1440;
var CANDLES_DAY = _.map(_.range(GEN_CANDLES), function(d) {
    //TODO(yin): Randomness in test is bad, figure out a static seed
    var rnd = function () { return Math.random() * 1000 }
    return {
	s: d,
	o: rnd().toString(),
	h: rnd().toString(),
	l: rnd().toString(),
	c: rnd().toString(),
	p: rnd().toString()
    };
 });

var timer;
var csv;

function deflate(file, data, next) {
    zlib.deflate(data, function(err, buffer) { next(err, file, buffer) });
}

function save(file, buffer, next) {
    fs.writeFile(file, buffer, function(err) { next(err); });
}

function cleanUp(path, next) {
    if( fs.existsSync(path) ) {
        var files = [];
        files = fs.readdirSync(path);
        files.forEach(function(file,index){
            var curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()) {
		// recurse
                cleanUp(curPath);
            } else {
		// delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
    next(null, path);
}

function buffersEqual(a, b) {
    if (!Buffer.isBuffer(a)) return undefined;
    if (!Buffer.isBuffer(b)) return undefined;
    if (a.length !== b.length) return false;
    for (var i = 0; i < a.length; i++) {
        if (a[i] !== b[i]) return false;
    }
    return true;
};

var Timer = function() {
    this.precision = 3;
    this.checkpoints = [];
    this.time_now = function(note) {
	var elapsed;
	var cp_count = this.checkpoints.length;

	if (cp_count > 0) {
            var last = this.checkpoints[cp_count - 1];
            var diff = process.hrtime(last);
            elapsed = diff[0] * 1000 + diff[1] / 100000;
            console.log("Elapsed: " + elapsed.toFixed(this.precision) + " ms - " + note);
	}
	this.checkpoints.push(process.hrtime());
    }
}

module.exports = {
    // runs before each test method invocation
    setUp: function(done) {
        fs.existsSync(TMPDIR) || fs.mkdirSync(TMPDIR);
	async.compose(save, deflate)(CSVFILE, DATA, done);
	timer = new Timer();
        csv = new CSVStore({history: {directory: TMPDIR}});
    },
    // runs after each test method invocation
    tearDown: function(done) {
	fs.existsSync(TMPDIR) && cleanUp(TMPDIR, done);
	timer = null;
    },
    test_loadFile: function(test) {
	timer.time_now();
        csv.read(CSVNAME, function(candles) {
	    timer.time_now('candles parsed');
	    // we must catch failed asserts and print ourself
	    try {
		test.deepEqual(candles, CANDLES, "Loaded candles seem corrupt");
		test.done();
	    } catch(err) {
		console.log(err);
		throw err;
	    }
        });
    },
    test_saveFile: function(test) {
	timer.time_now();
	//TODO(yin):Mock the fs.
        csv.write(CSVGEN, CANDLES, function(candles) {
	    timer.time_now("candles written");
	    fs.readFile(CSVGENFILE, function(err, buffer) {
		if(err) throw err;
		zlib.deflate(DATA, function(err, databuf) {
		    // ensure assertion's are printed
		    try {
			test.ok(buffersEqual(buffer, databuf), "Persisted candles seem corrupt");
			test.done();
		    } catch(err) {
			console.log(err);
			throw err;
		    }
		});
	    });
	});
    },
    test_saveLoadDay: function(test) {
	timer.time_now();
	//TODO(yin):Mock the fs.
        csv.write(DAY_FILE, CANDLES_DAY, function(candles) {
	    timer.time_now("candles written");
	    csv.read(DAY_FILE, function(candles) {
		timer.time_now('candles parsed');
		// we must catch failed asserts and print ourself
		try {
		    test.deepEqual(candles, CANDLES_DAY);
		    test.done();
		} catch(err) {
		    // unlike junit, nodeunit agregatess all assert messages
		    // too much output would be generated
		    throw err;
		}
	    });
	});
    },
    test_candlesAreNumbers: function(test) {
	timer.time_now();
        csv.read(CSVNAME, function(candles) {
	    timer.time_now('candles parsed');
	    try {
		_.each(candles, function(c) {
		    //TODO(yin): This generates also too much output
		    test.equals(typeof(c.s), 'number');
		    test.equals(typeof(c.o), 'number');
		    test.equals(typeof(c.h), 'number');
		    test.equals(typeof(c.l), 'number');
		    test.equals(typeof(c.p), 'number');
		});
		test.done();
	    } catch(err) {
		throw err;
	    }
        });
    }
};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { withRouter } from 'react-router-dom';
import { get } from 'lodash';

import {
  Button,
  IconButton,
  Dropdown,
  DropdownMenu,
} from '@folio/stripes/components';
import {
  stripesShape,
  IfPermission,
} from '@folio/stripes/core';

import {
  getChargeFineToLoanPath,
  getOpenRequestsPath,
} from '../../../../util';

class ActionsDropdown extends React.Component {
  static propTypes = {
    stripes: stripesShape.isRequired,
    loan: PropTypes.object.isRequired,
    requestQueue: PropTypes.bool.isRequired,
    handleOptionsChange: PropTypes.func.isRequired,
    disableFeeFineDetails: PropTypes.bool,
  };

  renderMenu = ({ onToggle }) => {
    const {
      loan,
      handleOptionsChange,
      requestQueue,
      stripes,
      disableFeeFineDetails,
      match: { params },
    } = this.props;

    const itemDetailsLink = `/inventory/view/${loan.item.instanceId}/${loan.item.holdingsRecordId}/${loan.itemId}`;
    const loanPolicyLink = `/settings/circulation/loan-policies/${loan.loanPolicyId}`;
    const buttonDisabled = !stripes.hasPerm('ui-users.feesfines.actions.all');

    return (
      <DropdownMenu data-role="menu">
        <IfPermission perm="inventory.items.item.get">
          <Button
            buttonStyle="dropdownItem"
            to={itemDetailsLink}
          >
            <FormattedMessage id="ui-users.itemDetails" />
          </Button>
        </IfPermission>
        <IfPermission perm="ui-users.loans.renew">
          <Button
            buttonStyle="dropdownItem"
            data-test-dropdown-content-renew-button
            onClick={(e) => {
              handleOptionsChange({ loan, action: 'renew' });
              onToggle(e);
            }}
          >
            <FormattedMessage id="ui-users.renew" />
          </Button>
        </IfPermission>
        <IfPermission perm="ui-users.loans.edit">
          <Button
            buttonStyle="dropdownItem"
            data-test-dropdown-content-change-due-date-button
            onClick={(e) => {
              handleOptionsChange({ loan, action:'changeDueDate' });
              onToggle(e);
            }}
          >
            <FormattedMessage id="stripes-smart-components.cddd.changeDueDate" />
          </Button>
        </IfPermission>
        { get(loan, ['item', 'status', 'name']) !== 'Declared lost' &&
          <Button
            buttonStyle="dropdownItem"
            data-test-dropdown-content-declare-lost-button
            onClick={(e) => {
              handleOptionsChange({ loan, action:'declareLost' });
              onToggle(e);
            }}
          >
            <FormattedMessage id="ui-users.loans.declareLost" />
          </Button>
        }
        <IfPermission perm="circulation-storage.loan-policies.item.get">
          <Button
            buttonStyle="dropdownItem"
            to={loanPolicyLink}
          >
            <FormattedMessage id="ui-users.loans.details.loanPolicy" />
          </Button>
        </IfPermission>
        <Button
          buttonStyle="dropdownItem"
          disabled={buttonDisabled}
          to={getChargeFineToLoanPath(params.id, loan.id)}
        >
          <FormattedMessage id="ui-users.loans.newFeeFine" />
        </Button>
        <Button
          buttonStyle="dropdownItem"
          disabled={disableFeeFineDetails}
          onClick={() => {
            handleOptionsChange({ loan, action: 'feefineDetails' });
          }}
        >
          <FormattedMessage id="ui-users.loans.feeFineDetails" />
        </Button>
        {requestQueue && stripes.hasPerm('ui-requests.all') &&
          <Button
            buttonStyle="dropdownItem"
            data-test-dropdown-content-request-queue
            to={getOpenRequestsPath(get(loan, ['item', 'barcode']))}
          >
            <FormattedMessage id="ui-users.loans.details.requestQueue" />
          </Button>
        }
      </DropdownMenu>
    );
  };

  render() {
    return (
      <Dropdown
        renderTrigger={({ getTriggerProps }) => (
          <IconButton
            {...getTriggerProps()}
            icon="ellipsis"
          />
        )}
        renderMenu={this.renderMenu}
      />
    );
  }
}

export default withRouter(ActionsDropdown);
<commit_msg>Don't show change due date option for lost items (UIU-1207)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { withRouter } from 'react-router-dom';
import { get } from 'lodash';

import {
  Button,
  IconButton,
  Dropdown,
  DropdownMenu,
} from '@folio/stripes/components';
import {
  stripesShape,
  IfPermission,
} from '@folio/stripes/core';

import {
  getChargeFineToLoanPath,
  getOpenRequestsPath,
} from '../../../../util';

class ActionsDropdown extends React.Component {
  static propTypes = {
    stripes: stripesShape.isRequired,
    loan: PropTypes.object.isRequired,
    requestQueue: PropTypes.bool.isRequired,
    handleOptionsChange: PropTypes.func.isRequired,
    disableFeeFineDetails: PropTypes.bool,
  };

  renderMenu = ({ onToggle }) => {
    const {
      loan,
      handleOptionsChange,
      requestQueue,
      stripes,
      disableFeeFineDetails,
      match: { params },
    } = this.props;

    const itemDetailsLink = `/inventory/view/${loan.item.instanceId}/${loan.item.holdingsRecordId}/${loan.itemId}`;
    const loanPolicyLink = `/settings/circulation/loan-policies/${loan.loanPolicyId}`;
    const buttonDisabled = !stripes.hasPerm('ui-users.feesfines.actions.all');

    return (
      <DropdownMenu data-role="menu">
        <IfPermission perm="inventory.items.item.get">
          <Button
            buttonStyle="dropdownItem"
            to={itemDetailsLink}
          >
            <FormattedMessage id="ui-users.itemDetails" />
          </Button>
        </IfPermission>
        <IfPermission perm="ui-users.loans.renew">
          <Button
            buttonStyle="dropdownItem"
            data-test-dropdown-content-renew-button
            onClick={(e) => {
              handleOptionsChange({ loan, action: 'renew' });
              onToggle(e);
            }}
          >
            <FormattedMessage id="ui-users.renew" />
          </Button>
        </IfPermission>
        <IfPermission perm="ui-users.loans.edit">
          { get(loan, ['item', 'status', 'name']) !== 'Declared lost' &&
            <Button
              buttonStyle="dropdownItem"
              data-test-dropdown-content-change-due-date-button
              onClick={(e) => {
                handleOptionsChange({ loan, action:'changeDueDate' });
                onToggle(e);
              }}
            >
              <FormattedMessage id="stripes-smart-components.cddd.changeDueDate" />
            </Button>
          }
        </IfPermission>
        { get(loan, ['item', 'status', 'name']) !== 'Declared lost' &&
          <Button
            buttonStyle="dropdownItem"
            data-test-dropdown-content-declare-lost-button
            onClick={(e) => {
              handleOptionsChange({ loan, action:'declareLost' });
              onToggle(e);
            }}
          >
            <FormattedMessage id="ui-users.loans.declareLost" />
          </Button>
        }
        <IfPermission perm="circulation-storage.loan-policies.item.get">
          <Button
            buttonStyle="dropdownItem"
            to={loanPolicyLink}
          >
            <FormattedMessage id="ui-users.loans.details.loanPolicy" />
          </Button>
        </IfPermission>
        <Button
          buttonStyle="dropdownItem"
          disabled={buttonDisabled}
          to={getChargeFineToLoanPath(params.id, loan.id)}
        >
          <FormattedMessage id="ui-users.loans.newFeeFine" />
        </Button>
        <Button
          buttonStyle="dropdownItem"
          disabled={disableFeeFineDetails}
          onClick={() => {
            handleOptionsChange({ loan, action: 'feefineDetails' });
          }}
        >
          <FormattedMessage id="ui-users.loans.feeFineDetails" />
        </Button>
        {requestQueue && stripes.hasPerm('ui-requests.all') &&
          <Button
            buttonStyle="dropdownItem"
            data-test-dropdown-content-request-queue
            to={getOpenRequestsPath(get(loan, ['item', 'barcode']))}
          >
            <FormattedMessage id="ui-users.loans.details.requestQueue" />
          </Button>
        }
      </DropdownMenu>
    );
  };

  render() {
    return (
      <Dropdown
        renderTrigger={({ getTriggerProps }) => (
          <IconButton
            {...getTriggerProps()}
            icon="ellipsis"
          />
        )}
        renderMenu={this.renderMenu}
      />
    );
  }
}

export default withRouter(ActionsDropdown);
<|endoftext|>


<commit_before>/** @author Michael Murphy */

var mongoose = require('mongoose');
var _ = require('underscore');

var MissingRoleException =  Error.bind(null, "No such role exception.");

function _findUserRoles(roles, user) {
   console.log('in _find user roles')
   console.dir(roles);
   throw new Error();
   var userId = user.id;
   function isMember(role) {
      return _.contains(role.users.map(String), userId);
   }
   return roles.filter(isMember);
}

function _findPermissionSet(roles) {
   function toPerms(role) {
      return role.permissions;
   }
   return _.union.apply(_, roles.map(toPerms));
}

function _getRole(roles, roleName) {
   return _.find(roles, function(role) {
      return role.name === roleName;
   });
}

var roleManagerSchema = mongoose.Schema({
   roles: [{
      name: String,
      permissions: [String],
      users: [{'type': mongoose.Schema.Types.ObjectId, 'ref': 'User'}]
   }]
}, {save: {w:1}});

roleManagerSchema.method('findAllUserIds', function() {
   function toUsers(role) {
      return role.users;
   }
   return _.uniq(_.flatten(this.roles.map(toUsers)).map(String), false);
});

roleManagerSchema.method('findUserIds', function(roleName) {
   var role = _getRole(this.roles, roleName);
   if (role) {
      return role.users;
   }
   return null;
});

roleManagerSchema.method('findUserRoles', function(user) {
   return _findUserRoles(this.roles, user).sort();
});

roleManagerSchema.method('findUserPermissions', function(user) {
   return _findPermissionSet(_findUserRoles(this.roles, user));
});

roleManagerSchema.method('findRolePermissions', function(roleName) {
   var role = _getRole(this.roles, roleName);
   if (role) {
      return role.permissions;
   }
   return null;
});

roleManagerSchema.method('isUserPermitted', function(user, perm) {
   var userRoles = _findUserRoles(this.roles, user);
   return _.contains(_findPermissionSet(userRoles), perm);
});

roleManagerSchema.method('grantRolePermission', function(roleName, perm) {
   var role = _getRole(this.roles, roleName);
   if (role) {
      role.permissions.addToSet(perm);
      return this;
   }
   throw new MissingRoleException();
});

roleManagerSchema.method('revokeRolePermission', function(roleName, perm) {
   var role = _getRole(this.roles, roleName);
   if (role) {
      role.permissions.remove(perm);
      return this;
   }
   throw new MissingRoleException();
});

roleManagerSchema.method('assignRole', function(roleName, user) {
   var role = _getRole(this.roles, roleName);
   if (role) {
      role.users.addToSet(user);
      return this;
   }
   throw new MissingRoleException();
});

roleManagerSchema.method('revokeRole', function(roleName, user) {
   var role = _getRole(this.roles, roleName);
   if (role) {
      role.users.remove(user.id);
      return this;
   }
   throw new MissingRoleException();
});

roleManagerSchema.method('addRole', function(roleName) {
   this.roles.addToSet({name: roleName});
   return this;
});

roleManagerSchema.method('removeRole', function(roleName) {
   this.roles.remove({name: roleName});
   return this;
});

module.exports = roleManagerSchema;
<commit_msg>added JSDocs comments to role-manager.js<commit_after>/**
 * Roll manager
 * @author Michael Murphy
 * @author Mike Ryu (JSDocs comments only)
 */

var mongoose = require('mongoose');
var _ = require('underscore');
var MissingRoleException =  Error.bind(null, "No such role exception.");

/**
 * Given the roles and the user, returns the roles the user has.
 * @param roles roles
 * @param user user to find its assigned roles from
 * @returns {*}
 * @private
 */
function _findUserRoles(roles, user) {
   console.log('in _find user roles');
   console.dir(roles);
   throw new Error();
   var userId = user.id;

   /**
    * Returns <cc>true</cc> if the given user has
    * the given role, and <cc>false</cc> otherwise.
    * @param role role to check the user with
    */
   function isMember(role) {
      return _.contains(role.users.map(String), userId);
   }

   return roles.filter(isMember);
}

/**
 * Given the roles, finds the set of permissions assigned to the given roles.
 * @param roles roles to find the associated permissions from.
 * @private
 */
function _findPermissionSet(roles) {

   /**
    * Returns the array of permissions a given role has.
    * @param role role to find the set of permissions from
    * @returns {Array|Document.permissions}
    */
   function toPerms(role) {
      return role.permissions;
   }

   return _.union.apply(_, roles.map(toPerms));
}

function _getRole(roles, roleName) {
   return _.find(roles, function(role) {
      return role.name === roleName;
   });
}

var roleManagerSchema = mongoose.Schema({
   roles: [{
      name: String,
      permissions: [String],
      users: [{'type': mongoose.Schema.Types.ObjectId, 'ref': 'User'}]
   }]
}, {save: {w:1}});

roleManagerSchema.method('findAllUserIds', function() {
   function toUsers(role) {
      return role.users;
   }
   return _.uniq(_.flatten(this.roles.map(toUsers)).map(String), false);
});

roleManagerSchema.method('findUserIds', function(roleName) {
   var role = _getRole(this.roles, roleName);
   if (role) {
      return role.users;
   }
   return null;
});

roleManagerSchema.method('findUserRoles', function(user) {
   return _findUserRoles(this.roles, user).sort();
});

roleManagerSchema.method('findUserPermissions', function(user) {
   return _findPermissionSet(_findUserRoles(this.roles, user));
});

roleManagerSchema.method('findRolePermissions', function(roleName) {
   var role = _getRole(this.roles, roleName);
   if (role) {
      return role.permissions;
   }
   return null;
});

roleManagerSchema.method('isUserPermitted', function(user, perm) {
   var userRoles = _findUserRoles(this.roles, user);
   return _.contains(_findPermissionSet(userRoles), perm);
});

roleManagerSchema.method('grantRolePermission', function(roleName, perm) {
   var role = _getRole(this.roles, roleName);
   if (role) {
      role.permissions.addToSet(perm);
      return this;
   }
   throw new MissingRoleException();
});

roleManagerSchema.method('revokeRolePermission', function(roleName, perm) {
   var role = _getRole(this.roles, roleName);
   if (role) {
      role.permissions.remove(perm);
      return this;
   }
   throw new MissingRoleException();
});

roleManagerSchema.method('assignRole', function(roleName, user) {
   var role = _getRole(this.roles, roleName);
   if (role) {
      role.users.addToSet(user);
      return this;
   }
   throw new MissingRoleException();
});

roleManagerSchema.method('revokeRole', function(roleName, user) {
   var role = _getRole(this.roles, roleName);
   if (role) {
      role.users.remove(user.id);
      return this;
   }
   throw new MissingRoleException();
});

roleManagerSchema.method('addRole', function(roleName) {
   this.roles.addToSet({name: roleName});
   return this;
});

roleManagerSchema.method('removeRole', function(roleName) {
   this.roles.remove({name: roleName});
   return this;
});

module.exports = roleManagerSchema;
<|endoftext|>


<commit_before>var fs = require('fs')
var JSONStream = require('../')
var file = process.argv[2] || '/tmp/JSONStream-test-large.json'
var size = Number(process.argv[3] || 100000)
var tape = require('tape')
// if (process.title !== 'browser') {
  tape('out of mem', function (t) {
    t.plan(1)
    //////////////////////////////////////////////////////
    // Produces a random number between arg1 and arg2
    //////////////////////////////////////////////////////
    var randomNumber = function (min, max) {
      var number = Math.floor(Math.random() * (max - min + 1) + min);
      return number;
    };

    //////////////////////////////////////////////////////
    // Produces a random string of a length between arg1 and arg2
    //////////////////////////////////////////////////////
    var randomString = function (min, max) {

      // add several spaces to increase chanses of creating 'words'
      var chars = '      0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
      var result = '';

      var randomLength = randomNumber(min, max);

      for (var i = randomLength; i > 0; --i) {
        result += chars[Math.round(Math.random() * (chars.length - 1))];
      }
      return result;
    };

    //////////////////////////////////////////////////////
    // Produces a random JSON document, as a string
    //////////////////////////////////////////////////////
    var randomJsonDoc = function () {

      var doc = {
        "CrashOccurenceID": randomNumber(10000, 50000),
        "CrashID": randomNumber(1000, 10000),
        "SiteName": randomString(10, 25),
        "MachineName": randomString(10, 25),
        "Date": randomString(26, 26),
        "ProcessDuration": randomString(18, 18),
        "ThreadIdentityName": null,
        "WindowsIdentityName": randomString(15, 40),
        "OperatingSystemName": randomString(35, 65),
        "DetailedExceptionInformation": randomString(100, 800)
      };

      doc = JSON.stringify(doc);
      doc = doc.replace(/\,/g, ',\n'); // add new lines after each attribute
      return doc;
    };

    //////////////////////////////////////////////////////
    // generates test data
    //////////////////////////////////////////////////////
    var generateTestData = function (cb) {

      console.log('generating large data file...');

      var stream = fs.createWriteStream(file, {
        encoding: 'utf8'
      });

      var i = 0;
      var max = size;
      var writing = false
      var split = ',\n';
      var doc = randomJsonDoc();
      stream.write('[');

      function write () {
        if(writing) return
        writing = true
        while(++i < max) {
          if(Math.random() < 0.001)
            console.log('generate..', i + ' / ' + size)
          if(!stream.write(doc + split)) {
            writing = false
            return stream.once('drain', write)
          }
        }
        stream.write(doc + ']')
        stream.end();
        console.log('END')
      }
      write()
      stream.on('close', cb)
    };

    //////////////////////////////////////////////////////
    // Shows that parsing 100000 instances using JSONStream fails
    //
    // After several seconds, you will get this crash
    //     FATAL ERROR: JS Allocation failed - process out of memory
    //////////////////////////////////////////////////////
    var testJSONStreamParse_causesOutOfMem = function (done) {
      var items = 0
      console.log('parsing data files using JSONStream...');

      var parser = JSONStream.parse([true]);
      var stream = fs.createReadStream(file);
      stream.pipe(parser);

      parser.on('data', function (data) {
        items++
        if(Math.random() < 0.01) console.log(items, '...')
      });

      parser.on('end', function () {
        t.equal(items, size)
      });

    };

    //////////////////////////////////////////////////////
    // main
    //////////////////////////////////////////////////////

    fs.stat(file, function (err, stat) {
      console.log(stat)
      if(err)
        generateTestData(testJSONStreamParse_causesOutOfMem);
      else
        testJSONStreamParse_causesOutOfMem()
    })

  })

// }
<commit_msg>disable broken test for now<commit_after>return // dont run this test for now since tape is weird and broken on 0.10

var fs = require('fs')
var JSONStream = require('../')
var file = process.argv[2] || '/tmp/JSONStream-test-large.json'
var size = Number(process.argv[3] || 100000)
var tape = require('tape')
// if (process.title !== 'browser') {
  tape('out of mem', function (t) {
    t.plan(1)
    //////////////////////////////////////////////////////
    // Produces a random number between arg1 and arg2
    //////////////////////////////////////////////////////
    var randomNumber = function (min, max) {
      var number = Math.floor(Math.random() * (max - min + 1) + min);
      return number;
    };

    //////////////////////////////////////////////////////
    // Produces a random string of a length between arg1 and arg2
    //////////////////////////////////////////////////////
    var randomString = function (min, max) {

      // add several spaces to increase chanses of creating 'words'
      var chars = '      0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
      var result = '';

      var randomLength = randomNumber(min, max);

      for (var i = randomLength; i > 0; --i) {
        result += chars[Math.round(Math.random() * (chars.length - 1))];
      }
      return result;
    };

    //////////////////////////////////////////////////////
    // Produces a random JSON document, as a string
    //////////////////////////////////////////////////////
    var randomJsonDoc = function () {

      var doc = {
        "CrashOccurenceID": randomNumber(10000, 50000),
        "CrashID": randomNumber(1000, 10000),
        "SiteName": randomString(10, 25),
        "MachineName": randomString(10, 25),
        "Date": randomString(26, 26),
        "ProcessDuration": randomString(18, 18),
        "ThreadIdentityName": null,
        "WindowsIdentityName": randomString(15, 40),
        "OperatingSystemName": randomString(35, 65),
        "DetailedExceptionInformation": randomString(100, 800)
      };

      doc = JSON.stringify(doc);
      doc = doc.replace(/\,/g, ',\n'); // add new lines after each attribute
      return doc;
    };

    //////////////////////////////////////////////////////
    // generates test data
    //////////////////////////////////////////////////////
    var generateTestData = function (cb) {

      console.log('generating large data file...');

      var stream = fs.createWriteStream(file, {
        encoding: 'utf8'
      });

      var i = 0;
      var max = size;
      var writing = false
      var split = ',\n';
      var doc = randomJsonDoc();
      stream.write('[');

      function write () {
        if(writing) return
        writing = true
        while(++i < max) {
          if(Math.random() < 0.001)
            console.log('generate..', i + ' / ' + size)
          if(!stream.write(doc + split)) {
            writing = false
            return stream.once('drain', write)
          }
        }
        stream.write(doc + ']')
        stream.end();
        console.log('END')
      }
      write()
      stream.on('close', cb)
    };

    //////////////////////////////////////////////////////
    // Shows that parsing 100000 instances using JSONStream fails
    //
    // After several seconds, you will get this crash
    //     FATAL ERROR: JS Allocation failed - process out of memory
    //////////////////////////////////////////////////////
    var testJSONStreamParse_causesOutOfMem = function (done) {
      var items = 0
      console.log('parsing data files using JSONStream...');

      var parser = JSONStream.parse([true]);
      var stream = fs.createReadStream(file);
      stream.pipe(parser);

      parser.on('data', function (data) {
        items++
        if(Math.random() < 0.01) console.log(items, '...')
      });

      parser.on('end', function () {
        t.equal(items, size)
      });

    };

    //////////////////////////////////////////////////////
    // main
    //////////////////////////////////////////////////////

    fs.stat(file, function (err, stat) {
      console.log(stat)
      if(err)
        generateTestData(testJSONStreamParse_causesOutOfMem);
      else
        testJSONStreamParse_causesOutOfMem()
    })

  })

// }
<|endoftext|>


<commit_before>/*
 * Copyright 2015-2016 OpenCB
 *
 * 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.
 */

import {LitElement, html} from "/web_modules/lit-element.js";
import {classMap} from "/web_modules/lit-html/directives/class-map.js";
import UtilsNew from "../../../utilsNew.js";
import "./variant-interpreter-browser-rd.js";
import "./variant-interpreter-browser-cancer.js";

class VariantInterpreterBrowser extends LitElement {

    constructor() {
        super();

        // Set status and init private properties
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            cellbaseClient: {
                type: Object
            },
            clinicalAnalysis: {
                type: Object
            },
            clinicalAnalysisId: {
                type: String
            },
            // query: {
            //     type: Object
            // },
            // config: {
            //     type: Object
            // }
        };
    }

    _init() {
        this._prefix = UtilsNew.randomString(8);
        this.activeTab = {"VariantBrowser": true}; //default active tab
    }

    updated(changedProperties) {
        if (changedProperties.has("clinicalAnalysis")) {
            this.clinicalAnalysisObserver();
        }
        if (changedProperties.has("clinicalAnalysisId")) {
            this.clinicalAnalysisIdObserver();
        }
    }

    clinicalAnalysisObserver() {
        if (this.clinicalAnalysis) {
            switch (this.clinicalAnalysis.type.toUpperCase()) {
                case "SINGLE":
                case "FAMILY":
                    this._sample = this.clinicalAnalysis.proband.samples[0];
                    this.activeTab = {"VariantBrowser": true};
                    break;
                case "CANCER":
                    this._somaticSample = this.clinicalAnalysis.proband.samples.find(s => s.somatic);
                    this._germlineSample = this.clinicalAnalysis.proband.samples.find(s => !s.somatic);
                    this.activeTab = {"CancerSomaticVariantBrowser": true};
                    break;
            }
        }
        this.requestUpdate();
    }

    clinicalAnalysisIdObserver() {
        if (this.opencgaSession && this.clinicalAnalysisId) {
            this.opencgaSession.opencgaClient.clinical().info(this.clinicalAnalysisId, {study: this.opencgaSession.study.fqn})
                .then(response => {
                    this.clinicalAnalysis = response.responses[0].results[0];
                    this.clinicalAnalysisObserver();
                })
                .catch(response => {
                    console.error("An error occurred fetching clinicalAnalysis: ", response);
                });
        }
    }

    _changeTab(e) {
        e.preventDefault();

        const tabId = e.currentTarget.dataset.id;
        const navTabs = $(`#${this._prefix}QcTabs > .nav-tabs > .content-pills`, this);
        const contentTabs = $(`#${this._prefix}QcTabs > .content-tab-wrapper > .tab-pane`, this);
        if (!e.currentTarget?.className?.split(" ")?.includes("disabled")) {
            navTabs.removeClass("active");
            contentTabs.removeClass("active");
            $("#" + this._prefix + tabId).addClass("active");
            for (const tab in this.activeTab) this.activeTab[tab] = false;
            this.activeTab[tabId] = true;
            this.requestUpdate();
        }
    }

    onClinicalAnalysisUpdate (e) {
        this.dispatchEvent(new CustomEvent("clinicalAnalysisUpdate", {
            detail: {
                clinicalAnalysis: e.detail.clinicalAnalysis
            },
            bubbles: true,
            composed: true
        }));
    }

    render() {
        // Check Project exists
        if (!this.opencgaSession.project) {
            return html`

No public projects available to browse. Please login to continue

            `;
        }

        if (!this.clinicalAnalysis) {
            return html`

No Case found

`;
        }

        return this.clinicalAnalysis ? html`

                        ${this.clinicalAnalysis.type.toUpperCase() === "SINGLE" || this.clinicalAnalysis.type.toUpperCase() === "FAMILY"
                            ? html`

                                    Variant Browser

`
                            : html`

                                    Somatic Variant Browser

                                    Germline Variant Browser

`
                        }

                    ${this.clinicalAnalysis.type.toUpperCase() === "SINGLE" || this.clinicalAnalysis.type.toUpperCase() === "FAMILY"
                        ? html`

                                <tool-header title="Variant Browser - ${this._sample?.id}" class="bg-white"></tool-header>
                                <variant-interpreter-browser-rd .opencgaSession="${this.opencgaSession}"
                                                                .clinicalAnalysis="${this.clinicalAnalysis}"
                                                                .query="${this.query}"
                                                                .cellbaseClient="${this.cellbaseClient}"
                                                                @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}"
                                                                @samplechange="${this.onSampleChange}">
                                </variant-interpreter-browser-rd>

`
                        : null
                    }
                    ${this.clinicalAnalysis.type.toUpperCase() === "CANCER"
                        ? html`

                                <tool-header title="Somatic Variant Browser - ${this._somaticSample?.id}" class="bg-white"></tool-header>
                                <variant-interpreter-browser-cancer .opencgaSession="${this.opencgaSession}"
                                                                    .clinicalAnalysis="${this.clinicalAnalysis}"
                                                                    .query="${this.query}"
                                                                    .cellbaseClient="${this.cellbaseClient}"
                                                                    @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}">
                                </variant-interpreter-browser-cancer>

                            ${this._germlineSample     // Check Germline sample exist
                                ? html`

                                        <tool-header title="Germline Variant Browser - ${this._germlineSample?.id}" class="bg-white"></tool-header>
                                        <variant-interpreter-browser-rd .opencgaSession="${this.opencgaSession}"
                                                                        .clinicalAnalysis="${this.clinicalAnalysis}"
                                                                        .query="${this.query}"
                                                                        .cellbaseClient="${this.cellbaseClient}"
                                                                        @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}"
                                                                        @samplechange="${this.onSampleChange}">
                                        </variant-interpreter-browser-rd>

`
                                : null
                            }
                            `
                        : null
                    }

        ` : null;
    }

}

customElements.define("variant-interpreter-browser", VariantInterpreterBrowser);
<commit_msg>wc: check germiline sample in cancer browser<commit_after>/*
 * Copyright 2015-2016 OpenCB
 *
 * 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.
 */

import {LitElement, html} from "/web_modules/lit-element.js";
import {classMap} from "/web_modules/lit-html/directives/class-map.js";
import UtilsNew from "../../../utilsNew.js";
import "./variant-interpreter-browser-rd.js";
import "./variant-interpreter-browser-cancer.js";

class VariantInterpreterBrowser extends LitElement {

    constructor() {
        super();

        // Set status and init private properties
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            opencgaSession: {
                type: Object
            },
            cellbaseClient: {
                type: Object
            },
            clinicalAnalysis: {
                type: Object
            },
            clinicalAnalysisId: {
                type: String
            },
            // query: {
            //     type: Object
            // },
            // config: {
            //     type: Object
            // }
        };
    }

    _init() {
        this._prefix = UtilsNew.randomString(8);
        this.activeTab = {"VariantBrowser": true}; //default active tab
    }

    updated(changedProperties) {
        if (changedProperties.has("clinicalAnalysis")) {
            this.clinicalAnalysisObserver();
        }
        if (changedProperties.has("clinicalAnalysisId")) {
            this.clinicalAnalysisIdObserver();
        }
    }

    clinicalAnalysisObserver() {
        if (this.clinicalAnalysis) {
            switch (this.clinicalAnalysis.type.toUpperCase()) {
                case "SINGLE":
                case "FAMILY":
                    this._sample = this.clinicalAnalysis.proband.samples[0];
                    this.activeTab = {"VariantBrowser": true};
                    break;
                case "CANCER":
                    this._somaticSample = this.clinicalAnalysis.proband.samples.find(s => s.somatic);
                    this._germlineSample = this.clinicalAnalysis.proband.samples.find(s => !s.somatic);
                    this.activeTab = {"CancerSomaticVariantBrowser": true};
                    break;
            }
        }
        this.requestUpdate();
    }

    clinicalAnalysisIdObserver() {
        if (this.opencgaSession && this.clinicalAnalysisId) {
            this.opencgaSession.opencgaClient.clinical().info(this.clinicalAnalysisId, {study: this.opencgaSession.study.fqn})
                .then(response => {
                    this.clinicalAnalysis = response.responses[0].results[0];
                    this.clinicalAnalysisObserver();
                })
                .catch(response => {
                    console.error("An error occurred fetching clinicalAnalysis: ", response);
                });
        }
    }

    _changeTab(e) {
        e.preventDefault();

        const tabId = e.currentTarget.dataset.id;
        const navTabs = $(`#${this._prefix}QcTabs > .nav-tabs > .content-pills`, this);
        const contentTabs = $(`#${this._prefix}QcTabs > .content-tab-wrapper > .tab-pane`, this);
        if (!e.currentTarget?.className?.split(" ")?.includes("disabled")) {
            navTabs.removeClass("active");
            contentTabs.removeClass("active");
            $("#" + this._prefix + tabId).addClass("active");
            for (const tab in this.activeTab) this.activeTab[tab] = false;
            this.activeTab[tabId] = true;
            this.requestUpdate();
        }
    }

    onClinicalAnalysisUpdate (e) {
        this.dispatchEvent(new CustomEvent("clinicalAnalysisUpdate", {
            detail: {
                clinicalAnalysis: e.detail.clinicalAnalysis
            },
            bubbles: true,
            composed: true
        }));
    }

    render() {
        // Check Project exists
        if (!this.opencgaSession.project) {
            return html`

No public projects available to browse. Please login to continue

            `;
        }

        if (!this.clinicalAnalysis) {
            return html`

No Case found

`;
        }

        return this.clinicalAnalysis ? html`

                        ${this.clinicalAnalysis.type.toUpperCase() === "SINGLE" || this.clinicalAnalysis.type.toUpperCase() === "FAMILY"
                            ? html`

                                    Variant Browser

`
                            : null
                        }

                        ${this.clinicalAnalysis.type.toUpperCase() === "CANCER"
                            ? html`

                                    Somatic Variant Browser

                                ${this._germlineSample
                                    ? html`

                                            Germline Variant Browser

`
                                    : null
                                }
                                `
                            : null
                        }

                    ${this.clinicalAnalysis.type.toUpperCase() === "SINGLE" || this.clinicalAnalysis.type.toUpperCase() === "FAMILY"
                        ? html`

                                <tool-header title="Variant Browser - ${this._sample?.id}" class="bg-white"></tool-header>
                                <variant-interpreter-browser-rd .opencgaSession="${this.opencgaSession}"
                                                                .clinicalAnalysis="${this.clinicalAnalysis}"
                                                                .query="${this.query}"
                                                                .cellbaseClient="${this.cellbaseClient}"
                                                                @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}"
                                                                @samplechange="${this.onSampleChange}">
                                </variant-interpreter-browser-rd>

`
                        : null
                    }
                    ${this.clinicalAnalysis.type.toUpperCase() === "CANCER"
                        ? html`

                                <tool-header title="Somatic Variant Browser - ${this._somaticSample?.id}" class="bg-white"></tool-header>
                                <variant-interpreter-browser-cancer .opencgaSession="${this.opencgaSession}"
                                                                    .clinicalAnalysis="${this.clinicalAnalysis}"
                                                                    .query="${this.query}"
                                                                    .cellbaseClient="${this.cellbaseClient}"
                                                                    @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}">
                                </variant-interpreter-browser-cancer>

                            ${this._germlineSample     // Check Germline sample exist
                                ? html`

                                        <tool-header title="Germline Variant Browser - ${this._germlineSample?.id}" class="bg-white"></tool-header>
                                        <variant-interpreter-browser-rd .opencgaSession="${this.opencgaSession}"
                                                                        .clinicalAnalysis="${this.clinicalAnalysis}"
                                                                        .query="${this.query}"
                                                                        .cellbaseClient="${this.cellbaseClient}"
                                                                        @clinicalAnalysisUpdate="${this.onClinicalAnalysisUpdate}"
                                                                        @samplechange="${this.onSampleChange}">
                                        </variant-interpreter-browser-rd>

`
                                : null
                            }
                            `
                        : null
                    }

        ` : null;
    }

}

customElements.define("variant-interpreter-browser", VariantInterpreterBrowser);
<|endoftext|>


<commit_before>require('traceur/bin/traceur-runtime.js');
require('longjohn');

var test = require('tape');
var joinPath = require('path').join;
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var PGN = require('../lib/pgn.js').PGN;
var ChessError = require('../lib/error.js').ChessError;

test('PGN parser', function (t) {
	getPGNs().
		tap(function (pgns) {
			t.plan(pgns.length);
		}).
		map(PGN.parse).
		then(function () {
			t.ok(true);
		}).
		catch(ChessError, function (err) {
			console.error("Chess error! ");
			console.error("Last position: " + err.lastPosition);
			console.error(err.message);
			t.ok(false);
		})
	;
});

function getPGNs() {
	return (
		fs.readdirAsync(joinPath(__dirname, 'data/pgn')).
		map(function (filename) {
			return fs.readFileAsync(joinPath(__dirname, 'data/pgn', filename))
		}).
		map(String)
	);
}
<commit_msg>test: proper count for pgn<commit_after>require('traceur/bin/traceur-runtime.js');
require('longjohn');

var test = require('tape');
var joinPath = require('path').join;
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var PGN = require('../lib/pgn.js').PGN;
var ChessError = require('../lib/error.js').ChessError;

test('PGN parser', function (t) {
	getPGNs().
		tap(function (pgns) {
			t.plan(pgns.length);
		}).
		map(PGN.parse).
		map(t.ok).
		catch(ChessError, function (err) {
			console.error("Chess error! ");
			console.error("Last position: " + err.lastPosition);
			console.error(err.message);
			t.ok(false);
		})
	;
});

function getPGNs() {
	return (
		fs.readdirAsync(joinPath(__dirname, 'data/pgn')).
		map(function (filename) {
			return fs.readFileAsync(joinPath(__dirname, 'data/pgn', filename))
		}).
		map(String)
	);
}
<|endoftext|>


<commit_before>//simple binary tree

var bst =  (function binarySearchTree(){

  //private variables
  var root = null;

  function Node(value, left, right){
    this.value = value;
    this.left = left;
    this.right = right;
  }

  function insert(data){
    if(!data) return;

    //create BSTNode with data
    var node = new Node(data, null, null);

    //call recursive Insert
    root = insertRecurse(node, root);
  }

  function insertRecurse(data, current){
    if(current === null){
      return data;
    }

    console.dir(root);
    console.dir(current);

    if(data.value < current.value){
      current.left = insertRecurse(data, current.left);
    } else{
      current.right = insertRecurse(data, current.right);
    }

    //returns self if no insert
    return current;
  }

  function search(value){

  }

  function inOrder(callback){
    inOrderRecurse(root, callback);
  }

  function inOrderRecurse(node, callback){
    if(!node) return;

    inOrderRecurse(node.left, callback);
    callback(node.value);
    inOrderRecurse(node.right, callback);

  }

  return {
    insert: insert,
    inOrder: inOrder,
    search: search
    };
}());

bst.insert(5);
bst.insert(5);
bst.insert(3);
bst.insert(4);
bst.insert(6);

bst.inOrder(function printVal(data){
  console.log(data);
});
<commit_msg>added BST refactored to Recursive insert<commit_after>//simple binary tree

var bst =  (function binarySearchTree(){

  //private variables
  var root = null;

  function Node(value, left, right){
    this.value = value;
    this.left = left;
    this.right = right;
  }

  function insert(data){
    if(!data) return;

    //create BSTNode with data
    var node = new Node(data, null, null);

    //call recursive Insert
    root = insertRecurse(node, root);
  }

  function insertRecurse(data, current){
    if(current === null){
      return data;
    }

    if(data.value < current.value){
      current.left = insertRecurse(data, current.left);
    } else{
      current.right = insertRecurse(data, current.right);
    }

    //returns self if no insert
    return current;
  }

  function search(value){

  }

  function inOrder(callback){
    inOrderRecurse(root, callback);
  }

  function inOrderRecurse(node, callback){
    if(!node) return;

    inOrderRecurse(node.left, callback);
    callback(node.value);
    inOrderRecurse(node.right, callback);

  }

  return {
    insert: insert,
    inOrder: inOrder,
    search: search
    };
}());

bst.insert(5);
bst.insert(5);
bst.insert(3);
bst.insert(4);
bst.insert(6);

bst.inOrder(function printVal(data){
  console.log(data);
});
<|endoftext|>


<commit_before>/* eslint-env node, shelljs */
require('shelljs/global')

const doctest = 'node ./cli.js'

const testfiles = ls(['src/*.elm', 'test/*.elm']).join(' ')
if (exec(`${doctest} -- ${testfiles}`).code !== 0) {
  echo('those tests must pass')
  exit(1)
}

if (exec(`${doctest} -- test/TestData/TestFail.elm`).code === 0) {
  echo('this doctest must fail')
  exit(1)
}

if (exec(`${doctest} -- test/TestData/TestFail2.elm`).code === 0) {
  echo('this doctest must fail')
  exit(1)
}

echo('all tests passed')
<commit_msg>Replaced test/run.js: elm-doctest bin path .<commit_after>/* eslint-env node, shelljs */
require('shelljs/global')

const doctest = 'node ./bin/cli.js'

const testfiles = ls(['src/*.elm', 'test/*.elm']).join(' ')
if (exec(`${doctest} -- ${testfiles}`).code !== 0) {
  echo('those tests must pass')
  exit(1)
}

if (exec(`${doctest} -- test/TestData/TestFail.elm`).code === 0) {
  echo('this doctest must fail')
  exit(1)
}

if (exec(`${doctest} -- test/TestData/TestFail2.elm`).code === 0) {
  echo('this doctest must fail')
  exit(1)
}

echo('all tests passed')
<|endoftext|>


<commit_before>#!/usr/bin/env node

var lint = require("./lint/lint");

lint.checkDir("mode");
lint.checkDir("lib");
lint.checkDir("addon");

var ok = lint.success();

var files = new (require('node-static').Server)('.');

var server = require('http').createServer(function (req, res) {
  req.addListener('end', function () {
    files.serve(req, res);
  });
}).addListener('error', function (err) {
  throw err;
}).listen(3000, function () {
  var child_process = require('child_process');
  child_process.exec("which phantomjs", function (err) {
    if (err) {
      console.error("PhantomJS is not installed. Download from http://phantomjs.org");
      process.exit(1);
    }
    var cmd = 'phantomjs test/phantom_driver.js';
    child_process.exec(cmd, function (err, stdout) {
      server.close();
      console.log(stdout);
      process.exit(err || !ok ? 1 : 0);
    });
  });
});
<commit_msg>lint keymap<commit_after>#!/usr/bin/env node

var lint = require("./lint/lint");

lint.checkDir("mode");
lint.checkDir("lib");
lint.checkDir("addon");
lint.checkDir("keymap");

var ok = lint.success();

var files = new (require('node-static').Server)('.');

var server = require('http').createServer(function (req, res) {
  req.addListener('end', function () {
    files.serve(req, res);
  });
}).addListener('error', function (err) {
  throw err;
}).listen(3000, function () {
  var child_process = require('child_process');
  child_process.exec("which phantomjs", function (err) {
    if (err) {
      console.error("PhantomJS is not installed. Download from http://phantomjs.org");
      process.exit(1);
    }
    var cmd = 'phantomjs test/phantom_driver.js';
    child_process.exec(cmd, function (err, stdout) {
      server.close();
      console.log(stdout);
      process.exit(err || !ok ? 1 : 0);
    });
  });
});
<|endoftext|>


<commit_before>$(document).ready(function(){
	enableExtension();
});
<commit_msg>Delete enable.js<commit_after><|endoftext|>