<commit_before>'use strict';

var should = require('should');
var helper = require("../helper");
var POGarmentAccessoriesManager = require("../../src/managers/po/po-garment-accessories-manager");
var instanceManager = null;

function getData() {
    var POGarmentAccessories = require('dl-models').po.POGarmentAccessories;
    var Supplier = require('dl-models').core.Supplier;
    var Buyer = require('dl-models').core.Buyer;
    var UoM_Template = require('dl-models').core.UoM_Template;
    var UoM = require('dl-models').core.UoM;
    var PurchaseOrderItem = require('dl-models').po.PurchaseOrderItem;
    var Product = require('dl-models').core.Product;

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

    var pOGarmentAccessories = new POGarmentAccessories();
    pOGarmentAccessories.RONo = '1' + code + stamp;
    pOGarmentAccessories.RefPONo = '2' + code + stamp;
    pOGarmentAccessories.PRNo = '3' + code + stamp;
    pOGarmentAccessories.PONo = '3' + code + stamp;
    pOGarmentAccessories.ppn = 10;
    pOGarmentAccessories.deliveryDate = new Date();
    pOGarmentAccessories.termOfPayment = 'Tempo 2 bulan';
    pOGarmentAccessories.deliveryFeeByBuyer = true;
    pOGarmentAccessories.PODLNo = '';
    pOGarmentAccessories.description = 'SP1';
    pOGarmentAccessories.supplierID = {};
    pOGarmentAccessories.buyerID = {};
    pOGarmentAccessories.article = "Test Article";

    var supplier = new Supplier({
        code: '123',
        name: 'hot',
        contact: '0812....',
        PIC:'Suppy',
        address: 'test',
        import: true
    });

    var buyer = new Buyer({
        code: '123',
        name: 'hot',
        contact: '0812....',
        address: 'test',
        tempo: 0
    });

    var template = new UoM_Template({
        mainUnit: 'M',
        mainValue: 1,
        convertedUnit: 'M',
        convertedValue: 1
    });

    var _units = [];
    _units.push(template);

    var _uom = new UoM({
        category: 'UoM-Unit-Test',
        default: template,
        units: _units
    });

    var product = new Product({
        code: '22',
        name: 'hotline',
        price: 0,
        description: 'hotline123',
        UoM: _uom,
        detail: {}
    });

    var productValue = new PurchaseOrderItem({
        qty: 0,
        price: 0,
        product: product
    });

    var _products = [];
    _products.push(productValue);

    pOGarmentAccessories.supplier = supplier;
    pOGarmentAccessories.items = _products;
    return pOGarmentAccessories;
}

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

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

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

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

var createdPODLId;
it('#04. should success when create podl data', function (done) {
    instanceManager.getSingleByQuery({ _id: createdId })
        .then(result => {
            var _poNumbers = []
            _poNumbers.push(result.PONo)
            instanceManager.createGroup(_poNumbers)
                .then(id => {
                    id.should.be.Object();
                    createdPODLId = id;
                    done();
                })
                .catch(e => {
                    done(e);
                })

        })
        .catch(e => {
            done(e);
        })
});

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

it(`#06. should success when update created data`, function (done) {
    createdData.RONo += '[updated]';
    createdData.PRNo += '[updated]';
    createdData.PONo += '[updated]';
    createdData.RefPONo += '[updated]';
    createdData.termOfPayment += '[updated]';
    createdData.PODLNo += '[updated]';
    createdData.description += '[updated]';

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

it(`#07. should success when get updated data with id`, function (done) {
    instanceManager.getSingleByQuery({ _id: createdId })
        .then(data => {
            data.RONo.should.equal(createdData.RONo);
            data.PRNo.should.equal(createdData.PRNo);
            data.PONo.should.equal(createdData.PONo);
            data.RefPONo.should.equal(createdData.RefPONo);
            data.termOfPayment.should.equal(createdData.termOfPayment);
            data.PODLNo.should.equal(createdData.PODLNo);
            data.description.should.equal(createdData.description);

            done();
        })
        .catch(e => {
            done(e);
        })
});

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

// it(`#09. should _deleted=true`, function (done) {
//     instanceManager.getSingleByQuery({ _id: createdId })
//         .then(data => {
//             // validate.product(data);
//             data._deleted.should.be.Boolean();
//             data._deleted.should.equal(true);
//             done();
//         })
//         .catch(e => {
//             done(e);
//         })
// });<commit_msg>updating po accessories<commit_after>'use strict';

var should = require('should');
var helper = require("../helper");
var POGarmentAccessoriesManager = require("../../src/managers/po/po-garment-accessories-manager");
var instanceManager = null;

function getData() {
    var POGarmentAccessories = require('dl-models').po.POGarmentAccessories;
    var Supplier = require('dl-models').core.Supplier;
    var Buyer = require('dl-models').core.Buyer;
    var UoM_Template = require('dl-models').core.UoM_Template;
    var UoM = require('dl-models').core.UoM;
    var PurchaseOrderItem = require('dl-models').po.PurchaseOrderItem;
    var Product = require('dl-models').core.Product;

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

    var pOGarmentAccessories = new POGarmentAccessories();
    pOGarmentAccessories.RONo = '1' + code + stamp;
    pOGarmentAccessories.RefPONo = '2' + code + stamp;
    pOGarmentAccessories.PRNo = '3' + code + stamp;
    pOGarmentAccessories.PONo = '3' + code + stamp;
    pOGarmentAccessories.ppn = 10;
    pOGarmentAccessories.deliveryDate = new Date();
    pOGarmentAccessories.termOfPayment = 'Tempo 2 bulan';
    pOGarmentAccessories.deliveryFeeByBuyer = true;
    pOGarmentAccessories.PODLNo = '';
    pOGarmentAccessories.description = 'SP1';
    pOGarmentAccessories.supplierID = {};
    pOGarmentAccessories.buyerID = {};
    pOGarmentAccessories.article = "Test Article";

    var supplier = new Supplier({
        code: '123',
        name: 'Supplier01',
        contact: '0812....',
        PIC:'Suppy',
        address: 'test',
        import: true
    });

    var buyer = new Buyer({
        code: '123',
        name: 'Buyer01',
        contact: '0812....',
        address: 'test',
        tempo: 0
    });

    var template = new UoM_Template({
        mainUnit: 'M',
        mainValue: 1,
        convertedUnit: 'M',
        convertedValue: 1
    });

    var _units = [];
    _units.push(template);

    var _uom = new UoM({
        category: 'UoM-Unit-Test',
        default: template,
        units: _units
    });

    var product = new Product({
        code: '22',
        name: 'hotline',
        price: 0,
        description: 'hotline123',
        UoM: _uom,
        detail: {}
    });

    var productValue = new PurchaseOrderItem({
        qty: 0,
        price: 0,
        product: product
    });

    var _products = [];
    _products.push(productValue);

    pOGarmentAccessories.supplier = supplier;
    pOGarmentAccessories.buyer = buyer;
    pOGarmentAccessories.items = _products;
    return pOGarmentAccessories;
}

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

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

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

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

var createdPODLId;
it('#04. should success when create podl data', function (done) {
    instanceManager.getSingleByQuery({ _id: createdId })
        .then(result => {
            var _poNumbers = []
            _poNumbers.push(result.PONo)
            instanceManager.createGroup(_poNumbers)
                .then(id => {
                    id.should.be.Object();
                    createdPODLId = id;
                    done();
                })
                .catch(e => {
                    done(e);
                })

        })
        .catch(e => {
            done(e);
        })
});

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

it(`#06. should success when update created data`, function (done) {
    createdData.RONo += '[updated]';
    createdData.PRNo += '[updated]';
    createdData.PONo += '[updated]';
    createdData.RefPONo += '[updated]';
    createdData.termOfPayment += '[updated]';
    createdData.PODLNo += '[updated]';
    createdData.description += '[updated]';

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

it(`#07. should success when get updated data with id`, function (done) {
    instanceManager.getSingleByQuery({ _id: createdId })
        .then(data => {
            data.RONo.should.equal(createdData.RONo);
            data.PRNo.should.equal(createdData.PRNo);
            data.PONo.should.equal(createdData.PONo);
            data.RefPONo.should.equal(createdData.RefPONo);
            data.termOfPayment.should.equal(createdData.termOfPayment);
            data.PODLNo.should.equal(createdData.PODLNo);
            data.description.should.equal(createdData.description);

            done();
        })
        .catch(e => {
            done(e);
        })
});

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

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


<commit_before>var expect = require('chai').expect
  , fs = require('fs')
  , path = require('path')
  , exec = require('child_process').exec
  , rimraf = require('rimraf')
  , mktmpdir = require('mktmpdir')
  , scripts = require('../');

describe('git-scripts', function() {
  beforeEach(function(done) {
    var self = this;
    mktmpdir(function(err, dir) {
      self.proj = scripts(dir);
      done(err);
    });
  });

  afterEach(function(done) {
    rimraf(this.proj.path, done);
  });

  describe('when the path is not a git repo', function() {
    describe('isGitRepo()', function() {
      it('should be false', function(done) {
        this.proj.isGitRepo(function(result) {
          expect(result).to.be.false;
          done();
        });
      });
    });

    describe('installed()', function() {
      it('should be false', function(done) {
        this.proj.installed(function(result) {
          expect(result).to.be.false;
          done();
        });
      });
    });

    describe('install()', function() {
      it('should be an error', function(done) {
        this.proj.install(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });

    describe('uninstall()', function() {
      it('should be an error', function(done) {
        this.proj.uninstall(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });
  });

  describe('when the path is a git repo', function() {
    beforeEach(function(done) {
      exec('git init', {cwd: this.proj.path}, done);
    });

    describe('isGitRepo()', function() {
      it('should be true', function(done) {
        this.proj.isGitRepo(function(result) {
          expect(result).to.be.true;
          done();
        });
      });
    });

    describe('installed()', function() {
      it('should be false', function(done) {
        this.proj.installed(function(result) {
          expect(result).to.be.false;
          done();
        });
      });
    });

    describe('install()', function() {
      it('should move the old hooks directory and create the new symlink', function(done) {
        var self = this;
        this.proj.install(function(err) {
          var gitPath = self.proj.path + '/.git'
            , binHooksPath = path.resolve(gitPath, fs.readlinkSync(gitPath + '/hooks'));

          expect(binHooksPath).to.equal(path.normalize(__dirname + '/../bin/hooks'));
          expect(fs.existsSync(self.proj.path + '/.git/hooks.old')).to.be.true;
          done(err);
        });
      });

      it('should work if no hooks directory exist', function(done) {
        var hooksPath = this.proj.path + '/.git/hooks';
        var self = this;

        rimraf(hooksPath, function(err) {
          if (err) throw err;
          self.proj.install(done);
        });
      });
    });

    describe('uninstall()', function() {
      it('should be an error', function(done) {
        this.proj.uninstall(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });
  });

  describe('when installed', function() {
    beforeEach(function(done) {
      var self = this;
      exec('git init', {cwd: this.proj.path}, function(err) {
        if (err) return done(err);
        self.proj.install(done);
      });
    });

    describe('installed()', function() {
      it('should be true', function(done) {
        this.proj.installed(function(result) {
          expect(result).to.be.true;
          done();
        });
      });
    });

    describe('install()', function() {
      it('should be an error', function(done) {
        this.proj.install(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });

    describe('uninstall()', function() {
      it('should delete the symlink and move old hooks directory', function(done) {
        var self = this;
        this.proj.uninstall(function(err) {
          expect(fs.existsSync(self.proj.path + '/.git/hooks')).to.be.true;
          expect(fs.existsSync(self.proj.path + '/.git/hooks.old')).to.be.false;
          done(err);
        });
      });
    });
  });

  describe('when the path has no package.json', function() {
    describe('readCommand()', function() {
      it('should be an error', function(done) {
        this.proj.readCommand('foo', function(err, cmd) {
          expect(err).to.be.an.instanceof(Error);
          expect(cmd).to.not.exist;
          done();
        });
      });
    });

    describe('run()', function() {
      it('should be an error', function(done) {
        this.proj.run('foo', function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });
  });

  describe('when the path has package.json', function() {
    beforeEach(function(done) {
      var pkg = {git: {scripts: {
        foo: 'echo "hello, $1"',
        bar: 'exit 1'
      }}};
      fs.writeFile(this.proj.path + '/package.json', JSON.stringify(pkg), done);
    });

    describe('readCommand()', function() {
      it('should parse command', function(done) {
        this.proj.readCommand('foo', function(err, cmd) {
          expect(err).to.not.exist;
          expect(cmd).to.equal('echo "hello, $1"');
          done();
        });
      });

      it('should not be error when the command does not exist', function(done) {
        this.proj.readCommand('any', function(err, cmd) {
          expect(err).to.not.exist;
          expect(cmd).to.not.exist;
          done();
        });
      });
    });

    describe('run()', function() {
      it('should be able to supply arguments', function(done) {
        this.proj.run('foo', ['world'], done);
      });

      it('should be an error when the command failed', function(done) {
        this.proj.run('bar', function(err) {
          expect(err).to.be.an.instanceof(Error);
          expect(err).to.have.property('code', 1);
          done();
        });
      });

      it('should not be an error when the command does not exist', function(done) {
        this.proj.run('any', function(err) {
          expect(err).to.not.exist;
          done();
        });
      });
    });
  });
});
<commit_msg>add test coverage for submodule/gitdir support<commit_after>var expect = require('chai').expect
  , fs = require('fs')
  , path = require('path')
  , exec = require('child_process').exec
  , rimraf = require('rimraf')
  , mktmpdir = require('mktmpdir')
  , scripts = require('../');

describe('git-scripts', function() {
  beforeEach(function(done) {
    var self = this;
    mktmpdir(function(err, dir) {
      self.proj = scripts(dir);
      done(err);
    });
  });

  afterEach(function(done) {
    rimraf(this.proj.path, done);
  });

  describe('when the path is not a git repo', function() {
    describe('isGitRepo()', function() {
      it('should be false', function(done) {
        this.proj.isGitRepo(function(result) {
          expect(result).to.be.false;
          done();
        });
      });
    });

    describe('installed()', function() {
      it('should be false', function(done) {
        this.proj.installed(function(result) {
          expect(result).to.be.false;
          done();
        });
      });
    });

    describe('install()', function() {
      it('should be an error', function(done) {
        this.proj.install(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });

    describe('uninstall()', function() {
      it('should be an error', function(done) {
        this.proj.uninstall(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });
  });

  describe('when the path is a git repo', function() {
    beforeEach(function(done) {
      exec('git init', {cwd: this.proj.path}, done);
    });

    describe('isGitRepo()', function() {
      it('should be true', function(done) {
        this.proj.isGitRepo(function(result) {
          expect(result).to.be.true;
          done();
        });
      });
    });

    describe('installed()', function() {
      it('should be false', function(done) {
        this.proj.installed(function(result) {
          expect(result).to.be.false;
          done();
        });
      });
    });

    describe('install()', function() {
      it('should move the old hooks directory and create the new symlink', function(done) {
        var self = this;
        this.proj.install(function(err) {
          var gitPath = self.proj.path + '/.git'
            , binHooksPath = path.resolve(gitPath, fs.readlinkSync(gitPath + '/hooks'));

          expect(binHooksPath).to.equal(path.normalize(__dirname + '/../bin/hooks'));
          expect(fs.existsSync(self.proj.path + '/.git/hooks.old')).to.be.true;
          done(err);
        });
      });

      it('should work if no hooks directory exist', function(done) {
        var hooksPath = this.proj.path + '/.git/hooks';
        var self = this;

        rimraf(hooksPath, function(err) {
          if (err) throw err;
          self.proj.install(done);
        });
      });
    });

    describe('uninstall()', function() {
      it('should be an error', function(done) {
        this.proj.uninstall(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });
  });

  describe('when the gitdir is specified in a text file', function() {
    beforeEach(function(done) {
      var self = this;
      mktmpdir(function(err, dir) {
        exec('git init', {cwd: dir});
        exec('mv .git .git2', {cwd: dir});
        exec('echo "gitdir: ./.git2" > .git', {cwd: dir}, function(){
          self.proj = scripts(dir);
          done(err);
        });
      });
    });

    describe('isGitRepo()', function() {
      it('should be true', function(done) {
        this.proj.isGitRepo(function(result) {
          expect(result).to.be.true;
          done();
        });
      });
    });

    describe('installed()', function() {
      it('should be false', function(done) {
        this.proj.installed(function(result) {
          expect(result).to.be.false;
          done();
        });
      });
    });

    describe('install()', function() {
      it('should move the old hooks directory and create the new symlink', function(done) {
        var self = this;
        this.proj.install(function(err) {
          var gitPath = self.proj.gitPath
            , binHooksPath = path.resolve(gitPath, fs.readlinkSync(gitPath + '/hooks'));

          expect(binHooksPath).to.equal(path.normalize(__dirname + '/../bin/hooks'));
          expect(fs.existsSync(gitPath + '/hooks.old')).to.be.true;
          done(err);
        });
      });

      it('should work if no hooks directory exist', function(done) {
        var hooksPath = this.proj.path + '/hooks';
        var self = this;

        rimraf(hooksPath, function(err) {
          if (err) throw err;
          self.proj.install(done);
        });
      });
    });

    describe('uninstall()', function() {
      it('should be an error', function(done) {
        this.proj.uninstall(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });
  });

  describe('when installed', function() {
    beforeEach(function(done) {
      var self = this;
      exec('git init', {cwd: this.proj.path}, function(err) {
        if (err) return done(err);
        self.proj.install(done);
      });
    });

    describe('installed()', function() {
      it('should be true', function(done) {
        this.proj.installed(function(result) {
          expect(result).to.be.true;
          done();
        });
      });
    });

    describe('install()', function() {
      it('should be an error', function(done) {
        this.proj.install(function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });

    describe('uninstall()', function() {
      it('should delete the symlink and move old hooks directory', function(done) {
        var self = this;
        this.proj.uninstall(function(err) {
          expect(fs.existsSync(self.proj.path + '/.git/hooks')).to.be.true;
          expect(fs.existsSync(self.proj.path + '/.git/hooks.old')).to.be.false;
          done(err);
        });
      });
    });
  });

  describe('when the path has no package.json', function() {
    describe('readCommand()', function() {
      it('should be an error', function(done) {
        this.proj.readCommand('foo', function(err, cmd) {
          expect(err).to.be.an.instanceof(Error);
          expect(cmd).to.not.exist;
          done();
        });
      });
    });

    describe('run()', function() {
      it('should be an error', function(done) {
        this.proj.run('foo', function(err) {
          expect(err).to.be.an.instanceof(Error);
          done();
        });
      });
    });
  });

  describe('when the path has package.json', function() {
    beforeEach(function(done) {
      var pkg = {git: {scripts: {
        foo: 'echo "hello, $1"',
        bar: 'exit 1'
      }}};
      fs.writeFile(this.proj.path + '/package.json', JSON.stringify(pkg), done);
    });

    describe('readCommand()', function() {
      it('should parse command', function(done) {
        this.proj.readCommand('foo', function(err, cmd) {
          expect(err).to.not.exist;
          expect(cmd).to.equal('echo "hello, $1"');
          done();
        });
      });

      it('should not be error when the command does not exist', function(done) {
        this.proj.readCommand('any', function(err, cmd) {
          expect(err).to.not.exist;
          expect(cmd).to.not.exist;
          done();
        });
      });
    });

    describe('run()', function() {
      it('should be able to supply arguments', function(done) {
        this.proj.run('foo', ['world'], done);
      });

      it('should be an error when the command failed', function(done) {
        this.proj.run('bar', function(err) {
          expect(err).to.be.an.instanceof(Error);
          expect(err).to.have.property('code', 1);
          done();
        });
      });

      it('should not be an error when the command does not exist', function(done) {
        this.proj.run('any', function(err) {
          expect(err).to.not.exist;
          done();
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict';
var ko = require('knockout');
var $ = require('jquery');
var $osf = require('js/osfHelpers');
var Raven = require('raven-js');
var Markdown = require('pagedown-ace-converter');
Markdown.getSanitizingConverter = require('pagedown-ace-sanitizer').getSanitizingConverter;
require('imports?Markdown=pagedown-ace-converter!pagedown-ace-editor');

/**
 * Binding handler that instantiates an ACE editor.
 * The value accessor must be a ko.observable.
 * Example:

 */
var editor;

ko.bindingHandlers.ace = {
    init: function (element, valueAccessor) {
        editor = ace.edit(element.id);  // jshint ignore: line
        editor.renderer.setShowGutter(true);
        editor.renderer.setOption('showLineNumbers', true);

        // Updates the view model based on changes to the editor
        editor.getSession().on('change', function () {
            valueAccessor()(editor.getValue());
        });
    },

    update: function (element, valueAccessor) {
        var content = editor.getValue();        // Content of ace editor
        var value = ko.unwrap(valueAccessor()); // Value from view model

        // Updates the editor based on changes to the view model
        if (value !== undefined && content !== value) {
            var cursorPosition = editor.getCursorPosition();
            editor.setValue(value);
            editor.gotoLine(cursorPosition.row + 1, cursorPosition.column);
        }
    }
};

function ViewModel(url, viewText) {
    var self = this;

    self.initText = ko.observable('');
    self.currentText = viewText; //from wikiPage's VM
    self.activeUsers = ko.observableArray([]);
    self.status = ko.observable('connecting');
    self.throttledStatus = ko.observable(self.status());
    self.autocom = ko.observable(false);

    self.displayCollaborators = ko.computed(function() {
       return (self.activeUsers().length > 1);
    });

    // Display the icons of up to the first 18 collaborators on a page
    self.showCollaborators = ko.pureComputed(function() {
        if (self.activeUsers().length > 18) {
            return self.activeUsers().slice(0,18);
        }
        return self.activeUsers();
    });

    // Show text that says "and # more" collaborators
    self.andOthersMessage = ko.computed(function() {
        if (self.activeUsers().length > 18) {
            var leftovers = self.activeUsers().length - 18;
            return '...and ' + leftovers + ' more';
        }
        return '';
    });

    // Throttle the display when updating status.
    self.updateStatus = function() {
        self.throttledStatus(self.status());
    };

    self.throttledUpdateStatus = $osf.throttle(self.updateStatus, 4000, {leading: false});

    self.status.subscribe(function (newValue) {
        if (newValue !== 'connecting') {
            self.updateStatus();
        }
        self.throttledUpdateStatus();
    });

    self.statusDisplay = ko.computed(function() {
        switch(self.throttledStatus()) {
            case 'connected':
                return 'Live editing mode';
            case 'connecting':
                return 'Attempting to connect';
            case 'unsupported':
                return 'Unsupported browser';
            default:
                return 'Unavailable: Live editing';
        }
    });

    self.progressBar = ko.computed(function() {
        switch(self.throttledStatus()) {
            case 'connected':
                return {
                    class: 'progress-bar progress-bar-success',
                    style: 'width: 100%'
                };
            case 'connecting':
                return {
                    class: 'progress-bar progress-bar-warning progress-bar-striped active',
                    style: 'width: 100%'
                };
            default:
                return {
                    class: 'progress-bar progress-bar-danger',
                    style: 'width: 100%'
                };
        }
    });

    self.modalTarget = ko.computed(function() {
        switch(self.throttledStatus()) {
            case 'connected':
                return '#connectedModal';
            case 'connecting':
                return '#connectingModal';
            case 'unsupported':
                return '#unsupportedModal';
            default:
                return '#disconnectedModal';
        }
    });

    self.wikisDiffer = function(wiki1, wiki2) {
        // Handle inconsistencies in newline notation
        var clean1 = typeof wiki1 === 'string' ?

            wiki1.replace(/(\r\n|\n|\r)/gm, '\n') : '';

var clean2 = typeof wiki2 === 'string' ?

            wiki2.replace(/(\r\n|\n|\r)/gm, '\n') : '';
        return clean1 !== clean2;
    };

    self.changed = function() {
        return self.wikisDiffer(self.initText(), self.currentText());
    };

    // Fetch initial wiki text
    self.fetchData = function() {
        var request = $.ajax({
            type: 'GET',
            url: url,
            dataType: 'json'
        });
        request.done(function (response) {
            // Most recent version, whether saved or in mongo
            self.initText(response.wiki_draft);
        });
        request.fail(function (xhr, textStatus, error) {
            $osf.growl('Error','The wiki content could not be loaded.');
            Raven.captureMessage('Could not GET wiki contents.', {
                url: url,
                textStatus: textStatus,
                error: error
            });
        });
        return request;
    };

    // Revert to last saved version, even if draft is more recent
    self.revertChanges = function() {
        return self.fetchData().then(function(response) {
            // Dirty check now covers last saved version
            self.initText(response.wiki_content);
            self.currentText(response.wiki_content);
        });
    };

    $(window).on('beforeunload', function() {
        if (self.changed() && self.status() !== 'connected') {
            return 'There are unsaved changes to your wiki. If you exit ' +
                'the page now, those changes may be lost.';
        }
    });

    $(document).ready(function() {
        $('#autocom').on('change', function() {
            self.autocom($(this).is(':checked'));
        });
    });

}

function WikiEditor(url, viewText, editor) {
    this.viewModel = new ViewModel(url, viewText);
    var mdConverter = Markdown.getSanitizingConverter();
    var mdEditor = new Markdown.Editor(mdConverter);
    mdEditor.run(editor);

}

module.exports = WikiEditor;
<commit_msg>More updates to PR 5301<commit_after>'use strict';
var ko = require('knockout');
var $ = require('jquery');
var $osf = require('js/osfHelpers');
var Raven = require('raven-js');
var Markdown = require('pagedown-ace-converter');
Markdown.getSanitizingConverter = require('pagedown-ace-sanitizer').getSanitizingConverter;
require('imports?Markdown=pagedown-ace-converter!pagedown-ace-editor');

/**
 * Binding handler that instantiates an ACE editor.
 * The value accessor must be a ko.observable.
 * Example:

 */
var editor;

ko.bindingHandlers.ace = {
    init: function (element, valueAccessor) {
        editor = ace.edit(element.id);  // jshint ignore: line
        editor.renderer.setShowGutter(true);
        editor.renderer.setOption('showLineNumbers', true);

        // Updates the view model based on changes to the editor
        editor.getSession().on('change', function () {
            valueAccessor()(editor.getValue());
        });
    },

    update: function (element, valueAccessor) {
        var content = editor.getValue();        // Content of ace editor
        var value = ko.unwrap(valueAccessor()); // Value from view model

        // Updates the editor based on changes to the view model
        if (value !== undefined && content !== value) {
            var cursorPosition = editor.getCursorPosition();
            editor.setValue(value);
            editor.gotoLine(cursorPosition.row + 1, cursorPosition.column);
        }
    }
};

function ViewModel(url, viewText) {
    var self = this;

    self.initText = ko.observable('');
    self.currentText = viewText; //from wikiPage's VM
    self.activeUsers = ko.observableArray([]);
    self.status = ko.observable('connecting');
    self.throttledStatus = ko.observable(self.status());
    self.autocom = ko.observable(false);

    self.displayCollaborators = ko.computed(function() {
       return (self.activeUsers().length > 1);
    });

    // Display the icons of up to the first 18 collaborators on a page
    self.showCollaborators = ko.computed(function() {
        if (self.activeUsers().length > 18) {
            return self.activeUsers().slice(0,18);
        }
        return self.activeUsers();
    });

    // Show text that says "and # more" collaborators
    self.andOthersMessage = ko.pureComputed(function() {
        if (self.activeUsers().length > 18) {
            var leftovers = self.activeUsers().length - 18;
            return '...and ' + leftovers + ' more';
        }
        return '';
    });

    // Throttle the display when updating status.
    self.updateStatus = function() {
        self.throttledStatus(self.status());
    };

    self.throttledUpdateStatus = $osf.throttle(self.updateStatus, 4000, {leading: false});

    self.status.subscribe(function (newValue) {
        if (newValue !== 'connecting') {
            self.updateStatus();
        }
        self.throttledUpdateStatus();
    });

    self.statusDisplay = ko.computed(function() {
        switch(self.throttledStatus()) {
            case 'connected':
                return 'Live editing mode';
            case 'connecting':
                return 'Attempting to connect';
            case 'unsupported':
                return 'Unsupported browser';
            default:
                return 'Unavailable: Live editing';
        }
    });

    self.progressBar = ko.computed(function() {
        switch(self.throttledStatus()) {
            case 'connected':
                return {
                    class: 'progress-bar progress-bar-success',
                    style: 'width: 100%'
                };
            case 'connecting':
                return {
                    class: 'progress-bar progress-bar-warning progress-bar-striped active',
                    style: 'width: 100%'
                };
            default:
                return {
                    class: 'progress-bar progress-bar-danger',
                    style: 'width: 100%'
                };
        }
    });

    self.modalTarget = ko.computed(function() {
        switch(self.throttledStatus()) {
            case 'connected':
                return '#connectedModal';
            case 'connecting':
                return '#connectingModal';
            case 'unsupported':
                return '#unsupportedModal';
            default:
                return '#disconnectedModal';
        }
    });

    self.wikisDiffer = function(wiki1, wiki2) {
        // Handle inconsistencies in newline notation
        var clean1 = typeof wiki1 === 'string' ?

            wiki1.replace(/(\r\n|\n|\r)/gm, '\n') : '';

var clean2 = typeof wiki2 === 'string' ?

            wiki2.replace(/(\r\n|\n|\r)/gm, '\n') : '';
        return clean1 !== clean2;
    };

    self.changed = function() {
        return self.wikisDiffer(self.initText(), self.currentText());
    };

    // Fetch initial wiki text
    self.fetchData = function() {
        var request = $.ajax({
            type: 'GET',
            url: url,
            dataType: 'json'
        });
        request.done(function (response) {
            // Most recent version, whether saved or in mongo
            self.initText(response.wiki_draft);
        });
        request.fail(function (xhr, textStatus, error) {
            $osf.growl('Error','The wiki content could not be loaded.');
            Raven.captureMessage('Could not GET wiki contents.', {
                url: url,
                textStatus: textStatus,
                error: error
            });
        });
        return request;
    };

    // Revert to last saved version, even if draft is more recent
    self.revertChanges = function() {
        return self.fetchData().then(function(response) {
            // Dirty check now covers last saved version
            self.initText(response.wiki_content);
            self.currentText(response.wiki_content);
        });
    };

    $(window).on('beforeunload', function() {
        if (self.changed() && self.status() !== 'connected') {
            return 'There are unsaved changes to your wiki. If you exit ' +
                'the page now, those changes may be lost.';
        }
    });

    $(document).ready(function() {
        $('#autocom').on('change', function() {
            self.autocom($(this).is(':checked'));
        });
    });

}

function WikiEditor(url, viewText, editor) {
    this.viewModel = new ViewModel(url, viewText);
    var mdConverter = Markdown.getSanitizingConverter();
    var mdEditor = new Markdown.Editor(mdConverter);
    mdEditor.run(editor);

}

module.exports = WikiEditor;
<|endoftext|>


<commit_before>'use strict';

var should = require('should');

var CluestrClient = require('../lib/cluestr.js/index.js');

var fakeCluestrId = 123;
var fakeCluestrSecret = 123;
var fakeCluestrToken = 123;

describe('CluestrClient', function() {
  process.env.CLUESTR_FRONT = 'http://localhost:1337';
  process.env.CLUESTR_SERVER = 'http://localhost:1338';
  CluestrClient.debug.createTestFrontServer().listen(1337);
  CluestrClient.debug.createTestApiServer().listen(1338);

  describe('getAccessToken()', function() {
    var cluestrClient = new CluestrClient(fakeCluestrId,fakeCluestrSecret);
    it('should return access token', function(done) {

      cluestrClient.getAccessToken("fake_code", "fake_uri",   function(err, token) {
        should.equal(err, null);
        token.should.equal('fake_access_token');

        done();
      });
    });
  });

  describe('sendDocument()', function() {
    var cluestrClient = new CluestrClient(fakeCluestrId,fakeCluestrSecret);
    cluestrClient.setAccessToken(fakeCluestrToken);

    it('should require an accessToken', function(done) {
      var rawCluestrClient = new CluestrClient(fakeCluestrId,fakeCluestrSecret);
      rawCluestrClient.sendDocument({}, function(err) {
        err.toString().should.include('accessToken');
        done();
      });
    });

    it('should require an identifier', function(done) {
      cluestrClient.sendDocument({}, function(err) {
        err.toString().should.include('identifier');
        done();
      });
    });

    it('should allow for noHydrate parameter', function(done) {
      cluestrClient.sendDocument({}, false, function(err) {
        err.toString().should.include('identifier');
        done();
      });
    });

    it('should send document', function(done) {
      var datas = {
        identifier: 'test-identifier',
        binary_document_type: 'file',
        metadatas: {
          'foo': 'bar'
        },
      };

      cluestrClient.sendDocument(datas, function(err, document) {
        if(err) {
          throw err;
        }

        document.should.eql(datas);

        done();
      });
    });
  });

  describe('deleteDocument()', function() {
    var cluestrClient = new CluestrClient(process.env.CLUESTR_ID, process.env.CLUESTR_SECRET);
    cluestrClient.setAccessToken(process.env.ACCESS_TOKEN);

    var datas = {
      identifier: 'test-identifier',
      binary_document_type: 'file',
      metadatas: {
        'foo': 'bar'
      },
    };

    var documentId = null;

    beforeEach(function(done) {
      cluestrClient.sendDocument(datas, function(err, document) {
        if(err) {
          throw err;
        }

        documentId = document.id;

        done();
      });
    });

    it('should delete document', function(done) {
      cluestrClient.deleteDocument(datas.identifier, function(err) {
        if(err) {
          throw err;
        }

        // Sending the same data again should now create a new document
        cluestrClient.sendDocument(datas, function(err, document) {
          if(err) {
            throw err;
          }

          document.id.should.not.equal(documentId);
          done();
        });

      });
    });

    it('should forward errors when deleting document', function(done) {
      var datas = {
        'identifier': 'nonexisting-document'
      };

      cluestrClient.deleteDocument(datas.identifier, function(err) {
        err.toString().should.include('404');
        done();
      });
    });
  });
});
<commit_msg>Correct all test for local<commit_after>'use strict';

var should = require('should');

var CluestrClient = require('../lib/cluestr.js/index.js');

var fakeCluestrId = 123;
var fakeCluestrSecret = 123;
var fakeCluestrToken = 123;

describe('CluestrClient', function() {
  process.env.CLUESTR_FRONT = 'http://localhost:1337';
  process.env.CLUESTR_SERVER = 'http://localhost:1338';
  CluestrClient.debug.createTestFrontServer().listen(1337);
  CluestrClient.debug.createTestApiServer().listen(1338);

  var cluestrClient = new CluestrClient(fakeCluestrId,fakeCluestrSecret);
  cluestrClient.setAccessToken(fakeCluestrToken);

  describe('getAccessToken()', function() {
    var rawCluestrClient = new CluestrClient(fakeCluestrId,fakeCluestrSecret);
    it('should return access token', function(done) {

      rawCluestrClient.getAccessToken("fake_code", "fake_uri",   function(err, token) {
        should.equal(err, null);
        token.should.equal('fake_access_token');

        done();
      });
    });
  });

  describe('sendDocument()', function() {
    it('should require an accessToken', function(done) {
      var rawCluestrClient = new CluestrClient(fakeCluestrId,fakeCluestrSecret);
      rawCluestrClient.sendDocument({}, function(err) {
        err.toString().should.include('accessToken');
        done();
      });
    });

    it('should require an identifier', function(done) {
      cluestrClient.sendDocument({}, function(err) {
        err.toString().should.include('identifier');
        done();
      });
    });

    it('should allow for noHydrate parameter', function(done) {
      cluestrClient.sendDocument({}, false, function(err) {
        err.toString().should.include('identifier');
        done();
      });
    });

    it('should send document', function(done) {
      var datas = {
        identifier: 'test-identifier',
        binary_document_type: 'file',
        metadatas: {
          'foo': 'bar'
        },
      };

      cluestrClient.sendDocument(datas, function(err, document) {
        if(err) {
          throw err;
        }

        document.should.eql(datas);

        done();
      });
    });
  });

  describe('deleteDocument()', function() {
    it('should require an accessToken', function(done) {
      var rawCluestrClient = new CluestrClient(fakeCluestrId,fakeCluestrSecret);
      rawCluestrClient.deleteDocument(123, function(err) {
        err.toString().should.include('accessToken');
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>(function(
	Base,
	Vector,
	Logo,
	Shapes,
	Grid,
	Chainable
){

var sqrt, pow, Engine;

if (!window.requestAnimationFrame) {
	window.requestAnimationFrame = (function(){
		return  window.requestAnimationFrame   ||
			window.webkitRequestAnimationFrame ||
			window.mozRequestAnimationFrame    ||
			function( callback ){
				window.setTimeout(callback, 1000 / 60);
			};
	})();
}

sqrt = Math.sqrt;
pow  = Math.pow;

Engine = Base.extend({

	scale: window.devicePixelRatio || 1,
	// scale:1,

	shapes     : [],
	particles  : [],
	particlesA : [],
	particlesB : [],

	_deferredParticles: [],

	ticks: [],

	starGeneratorRate: 600,

	mouse: {
		x: -9999,
		y: -9999
	},

	constructor: function(canvas, image){
		if (typeof canvas === 'string') {
			this.canvas = document.getElementById(canvas);
		} else {
			this.canvas = canvas;
		}

		if (!this.canvas.getContext) {
			return;
		}

		this.context = this.canvas.getContext('2d');

		this.resize = this.resize.bind(this);
		this.resize();
		window.addEventListener('resize', this.resize, false);

		this._handleScroll = this._handleScroll.bind(this);
		this._handleScroll();
		window.addEventListener('scroll', this._handleScroll, false);

		this.setupStarfield();
		this.setupTessellation();

		this.last = Date.now() / 1000;

		this.start = this.last;

		this._handleMouseCoords = this._handleMouseCoords.bind(this);
		window.addEventListener('mousemove', this._handleMouseCoords, false);

		this.render = this.render.bind(this);
		this.render();

		this.canvas.style.opacity = 1;

		this.cssAnimations(
			document.getElementById(image)
		);
	},

	cssAnimations: function(image){
		var parent = this.canvas.parentNode;

		image.style.webkitTransform = 'translate3d(0,0,0) scale(1)';
		image.style.opacity = 1;

		new Chainable()
			.wait(1000)
			.then(function(){
				this.starGeneratorRate = 200;
			}, this)
			.wait(1000)
			.then(function(){
				this.showGrid = true;
			}, this)
			.wait(2000)
			.then(function(){
				parent.className += ' state-one';
			})
			.wait(150)
			.then(function(){
				parent.className += ' state-two';
			})
			.wait(150)
			.then(function(){
				parent.className += ' state-three';
			})
			.wait(500)
			.then(function(){
				parent.className += ' state-four';
			})
			.wait(100)
			.then(function(){
				this.showShapes = true;
			}, this)
			.wait(1000)
			.then(function(){
			}, this);
	},

	setupStarfield: function(){
		this.particles = [];
		// this.generateParticles(50, true);
		this.generateParticles(400);
	},

	setupTessellation: function(canvas){
		this.shapes = [];
		this.logo = new Engine.Shape(
			-(180),
			-(180),
			360,
			360,
			Logo.Points,
			Logo.Polygons
		);

		this.grid = new Engine.Shape.Puller(this.width, this.height, Grid);
	},

	getAverageTickTime: function(){
		var sum = 0, s;

		for (s = 0; s < this.ticks.length; s++) {
			sum += this.ticks[s];
		}

		window.console.log('Average Tick Time:', sum / this.ticks.length);
	},

	getLongestTick: function(){
		var max = 0, index, s;

		for (s = 0; s < this.ticks.length; s++) {
			if (this.ticks[s] > max) {
				max = this.ticks[s];
				index = s;
			}
		}

		window.console.log('Max tick was:', max, 'at index:', index);
	},

	render: function(){
		var scale = this.scale;

		if (this.scrollY > 700) {
			window.requestAnimationFrame(this.render);
			return;
		}

		this.context.clearRect(
			-(this.width  / 2) * scale,
			-(this.height / 2) * scale,
			this.width  * scale,
			this.height * scale
		);

		this.now = Date.now() / 1000;

		this.tick = Math.min(this.now - this.last, 0.017);

		this.renderStarfield(this.now);

		if (this.showGrid) {
			this.grid
				.update(this)
				.draw(this.context, scale, this);
		}

		if (this.showShapes) {
			// this.renderTessellation(this.now);
			this.logo
				.update(this)
				.draw(this.context, scale, this);
		}

		this.last = this.now;

		window.requestAnimationFrame(this.render);
	},

	renderTessellation: function(){
		var scale = this.scale, p, index;

		for (p = 0; p < this.shapes.length; p++)  {
			this.shapes[p]
				.update(this)
				.draw(this.context, scale, this);
		}

		this.logo
			.update(this)
			.draw(this.context, scale, this);

		// Remove destroyed shapes
		for (p = 0; p < this._deferredShapes.length; p++) {
			index = this.shapes.indexOf(this._deferredShapes.pop());
			if (index >= 0) {
				this.shapes.splice(index, 1);
			}
		}

		// 1 Per second? Maybe?
		// if (Engine.getRandomFloat(0,100) < 1.6666) {
		//     this.generateRandomShape();
		// }
	},

	generateRandomShape: function(){
		var halfWidth, halfHeight, iter,
			shape, shapeTemplate, columns, rows, modWidth, row, column,
			xOffset, yOffset;

		iter = 140;

		rows = this.height / iter - 1;
		modWidth = this.width % iter;
		columns  = (this.width - modWidth) / iter - 1;

		row    = Engine.getRandomInt(0, rows);
		column = Engine.getRandomInt(0, columns);

		halfWidth  = this.width  / 2;
		halfHeight = this.height / 2;
		shapeTemplate = Shapes[Engine.getRandomInt(0, Shapes.length - 1)];

		xOffset = Engine.getRandomInt(-50, 50);
		yOffset = Engine.getRandomInt(-50, 50);

		shape = new Engine.Shape(
			(iter / 2) + (column * iter) - (modWidth / 2) - halfWidth + xOffset - 25,
			(iter / 2) + (row * iter) - halfHeight + yOffset - 25,
			50,
			50,
			shapeTemplate.points,
			shapeTemplate.polygons,
			true
		);
		shape.selfDestruct(10);
		this.shapes.push(shape);
	},

	generateParticles: function(num, fixed){
		var p;

		for (p = 0; p < num; p++) {
			if (fixed) {
				this.particles.push(new Engine.Particle.Fixed(this.width, this.height));
			} else {
				this.particles.push(new Engine.Particle(this.width, this.height));
			}
		}
	},

	resize: function(){
		var scale = this.scale;

		this.width  = window.innerWidth;
		this.height = 700;

		this.canvas.width  = this.width  * scale;
		this.canvas.height = this.height * scale;

		this.context.translate(
			this.width  / 2 * scale >> 0,
			this.height / 2 * scale >> 0
		);

		if (this.grid) {
			this.grid.resize(this.width, this.height);
		}
	},

	renderStarfield: function(){
		var scale = this.scale, p, index, particle;

		// Update all particles... may need to be optimized
		for (p = 0; p < this.particles.length; p++) {
			this.particles[p].update(this);
		}

		// Batch render particles based on color
		// to prevent unneeded context state change
		this.context.fillStyle = '#8750c2';
		for (p = 0; p < this.particlesA.length; p++) {
			particle = this.particlesA[p];

			if (particle.radius < 0.25) {
				continue;
			}
			this.context.fillRect(
				particle.pos.x * scale >> 0,
				particle.pos.y * scale >> 0,
				particle.radius * scale,
				particle.radius * scale
			);
		}

		this.context.fillStyle = '#b976ff';
		for (p = 0; p < this.particlesB.length; p++) {
			particle = this.particlesB[p];

			if (particle.radius < 0.25) {
				continue;
			}
			this.context.fillRect(
				particle.pos.x * scale >> 0,
				particle.pos.y * scale >> 0,
				particle.radius * scale,
				particle.radius * scale
			);
		}

		this.particlesA.length = 0;
		this.particlesB.length = 0;

		// Remove destroyed particles
		for (p = 0; p < this._deferredParticles.length; p++) {
			index = this.particles.indexOf(this._deferredParticles.pop());
			if (index >= 0) {
				this.particles.splice(index, 1);
			}
		}

		this.generateParticles(this.starGeneratorRate * this.tick >> 0);
	},

	_handleMouseCoords: function(event){
		this.mouse.x = event.pageX;
		this.mouse.y = event.pageY;
	},

	_handleScroll: function(){
		this.scrollY = window.scrollY;
	}

});

Engine.map = function(val, istart, istop, ostart, ostop) {
	return ostart + (ostop - ostart) * ((val - istart) / (istop - istart));
};

Engine.getRandomFloat = function(min, max) {
	return Math.random() * (max - min) + min;
};

Engine.getRandomInt = function(min, max) {
	return Math.floor(Math.random() * (max - min + 1) + min);
};

Engine.clone = function(ref) {
	var clone = {}, key;
	for (key in ref) {
		clone[key] = ref[key];
	}
	return clone;
};

window.Engine = Engine;

})(
	window.Base,
	window.Vector,
	window.Logo,
	window.Shapes,
	window.Grid,
	window.Chainable
);
<commit_msg>Removing more unneccesary function calls<commit_after>(function(
	Base,
	Vector,
	Logo,
	Shapes,
	Grid,
	Chainable
){

var sqrt, pow, Engine;

if (!window.requestAnimationFrame) {
	window.requestAnimationFrame = (function(){
		return  window.requestAnimationFrame   ||
			window.webkitRequestAnimationFrame ||
			window.mozRequestAnimationFrame    ||
			function( callback ){
				window.setTimeout(callback, 1000 / 60);
			};
	})();
}

sqrt = Math.sqrt;
pow  = Math.pow;

Engine = Base.extend({

	scale: window.devicePixelRatio || 1,
	// scale:1,

	shapes     : [],
	particles  : [],
	particlesA : [],
	particlesB : [],

	_deferredParticles: [],

	ticks: [],

	starGeneratorRate: 600,

	mouse: {
		x: -9999,
		y: -9999
	},

	constructor: function(canvas, image){
		if (typeof canvas === 'string') {
			this.canvas = document.getElementById(canvas);
		} else {
			this.canvas = canvas;
		}

		if (!this.canvas.getContext) {
			return;
		}

		this.context = this.canvas.getContext('2d');

		this.resize = this.resize.bind(this);
		this.resize();
		window.addEventListener('resize', this.resize, false);

		this._handleScroll = this._handleScroll.bind(this);
		this._handleScroll();
		window.addEventListener('scroll', this._handleScroll, false);

		this.setupStarfield();
		this.setupTessellation();

		this.last = Date.now() / 1000;

		this.start = this.last;

		this._handleMouseCoords = this._handleMouseCoords.bind(this);
		window.addEventListener('mousemove', this._handleMouseCoords, false);

		this.render = this.render.bind(this);
		this.render();

		this.canvas.style.opacity = 1;

		this.cssAnimations(
			document.getElementById(image)
		);
	},

	cssAnimations: function(image){
		var parent = this.canvas.parentNode;

		image.style.webkitTransform = 'translate3d(0,0,0) scale(1)';
		image.style.opacity = 1;

		new Chainable()
			.wait(1000)
			.then(function(){
				this.starGeneratorRate = 200;
			}, this)
			.wait(1000)
			.then(function(){
				this.showGrid = true;
			}, this)
			.wait(2000)
			.then(function(){
				parent.className += ' state-one';
			})
			.wait(150)
			.then(function(){
				parent.className += ' state-two';
			})
			.wait(150)
			.then(function(){
				parent.className += ' state-three';
			})
			.wait(500)
			.then(function(){
				parent.className += ' state-four';
			})
			.wait(100)
			.then(function(){
				this.showShapes = true;
			}, this)
			.wait(1000)
			.then(function(){
			}, this);
	},

	setupStarfield: function(){
		this.particles = [];
		// this.generateParticles(50, true);
		this.generateParticles(400);
	},

	setupTessellation: function(canvas){
		this.shapes = [];
		this.logo = new Engine.Shape(
			-(180),
			-(180),
			360,
			360,
			Logo.Points,
			Logo.Polygons
		);

		this.grid = new Engine.Shape.Puller(this.width, this.height, Grid);
	},

	getAverageTickTime: function(){
		var sum = 0, s;

		for (s = 0; s < this.ticks.length; s++) {
			sum += this.ticks[s];
		}

		window.console.log('Average Tick Time:', sum / this.ticks.length);
	},

	getLongestTick: function(){
		var max = 0, index, s;

		for (s = 0; s < this.ticks.length; s++) {
			if (this.ticks[s] > max) {
				max = this.ticks[s];
				index = s;
			}
		}

		window.console.log('Max tick was:', max, 'at index:', index);
	},

	render: function(){
		var scale = this.scale, p, particle, index;

		if (this.scrollY > 700) {
			window.requestAnimationFrame(this.render);
			return;
		}

		this.context.clearRect(
			-(this.width  / 2) * scale,
			-(this.height / 2) * scale,
			this.width  * scale,
			this.height * scale
		);

		this.now = Date.now() / 1000;

		this.tick = Math.min(this.now - this.last, 0.017);

		// Update all particles... may need to be optimized
		for (p = 0; p < this.particles.length; p++) {
			this.particles[p].update(this);
		}

		// Batch render particles based on color
		// to prevent unneeded context state change
		this.context.fillStyle = '#8750c2';
		for (p = 0; p < this.particlesA.length; p++) {
			particle = this.particlesA[p];

			if (particle.radius < 0.25) {
				continue;
			}
			this.context.fillRect(
				particle.pos.x * scale >> 0,
				particle.pos.y * scale >> 0,
				particle.radius * scale,
				particle.radius * scale
			);
		}

		this.context.fillStyle = '#b976ff';
		for (p = 0; p < this.particlesB.length; p++) {
			particle = this.particlesB[p];

			if (particle.radius < 0.25) {
				continue;
			}
			this.context.fillRect(
				particle.pos.x * scale >> 0,
				particle.pos.y * scale >> 0,
				particle.radius * scale,
				particle.radius * scale
			);
		}

		this.particlesA.length = 0;
		this.particlesB.length = 0;

		// Remove destroyed particles
		for (p = 0; p < this._deferredParticles.length; p++) {
			index = this.particles.indexOf(this._deferredParticles.pop());
			if (index >= 0) {
				this.particles.splice(index, 1);
			}
		}

		if (this.showGrid) {
			this.grid
				.update(this)
				.draw(this.context, scale, this);
		}

		if (this.showShapes) {
			this.logo
				.update(this)
				.draw(this.context, scale, this);
		}

		this.last = this.now;

		this.generateParticles(this.starGeneratorRate * this.tick >> 0);

		window.requestAnimationFrame(this.render);
	},

	generateParticles: function(num, fixed){
		var p;

		for (p = 0; p < num; p++) {
			if (fixed) {
				this.particles.push(new Engine.Particle.Fixed(this.width, this.height));
			} else {
				this.particles.push(new Engine.Particle(this.width, this.height));
			}
		}
	},

	generateRandomShape: function(){
		var halfWidth, halfHeight, iter,
			shape, shapeTemplate, columns, rows, modWidth, row, column,
			xOffset, yOffset;

		iter = 140;

		rows = this.height / iter - 1;
		modWidth = this.width % iter;
		columns  = (this.width - modWidth) / iter - 1;

		row    = Engine.getRandomInt(0, rows);
		column = Engine.getRandomInt(0, columns);

		halfWidth  = this.width  / 2;
		halfHeight = this.height / 2;
		shapeTemplate = Shapes[Engine.getRandomInt(0, Shapes.length - 1)];

		xOffset = Engine.getRandomInt(-50, 50);
		yOffset = Engine.getRandomInt(-50, 50);

		shape = new Engine.Shape(
			(iter / 2) + (column * iter) - (modWidth / 2) - halfWidth + xOffset - 25,
			(iter / 2) + (row * iter) - halfHeight + yOffset - 25,
			50,
			50,
			shapeTemplate.points,
			shapeTemplate.polygons,
			true
		);
		shape.selfDestruct(10);
		this.shapes.push(shape);
	},

	resize: function(){
		var scale = this.scale;

		this.width  = window.innerWidth;
		this.height = 700;

		this.canvas.width  = this.width  * scale;
		this.canvas.height = this.height * scale;

		this.context.translate(
			this.width  / 2 * scale >> 0,
			this.height / 2 * scale >> 0
		);

		if (this.grid) {
			this.grid.resize(this.width, this.height);
		}
	},

	_handleMouseCoords: function(event){
		this.mouse.x = event.pageX;
		this.mouse.y = event.pageY;
	},

	_handleScroll: function(){
		this.scrollY = window.scrollY;
	}

});

Engine.map = function(val, istart, istop, ostart, ostop) {
	return ostart + (ostop - ostart) * ((val - istart) / (istop - istart));
};

Engine.getRandomFloat = function(min, max) {
	return Math.random() * (max - min) + min;
};

Engine.getRandomInt = function(min, max) {
	return Math.floor(Math.random() * (max - min + 1) + min);
};

Engine.clone = function(ref) {
	var clone = {}, key;
	for (key in ref) {
		clone[key] = ref[key];
	}
	return clone;
};

window.Engine = Engine;

})(
	window.Base,
	window.Vector,
	window.Logo,
	window.Shapes,
	window.Grid,
	window.Chainable
);
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var mongoose = require('mongoose');
var mongooseInteger = require('../index');

module.exports = {

	afterEach: function(done) {
		for (var key in mongoose.connection.collections) {
			mongoose.connection.collections[key].remove();
		}

		mongoose.models = {};
		mongoose.modelSchemas = {};
		mongoose.connection.models = {};
		done();
	},

	createIntegerSchema: function() {
		return new mongoose.Schema({
			value: {
				type: Number,
				integer: true
			}
		});
	},

	createIntegerStringSchema: function() {
		return new mongoose.Schema({
			value: {
				type: String,
				integer: true
			}
		});
	},

	createIntegerNestedObjectSchema: function() {
		return new mongoose.Schema({
			nested: {
				value: {
					type: Number,
					integer: true
				}
			}
		});
	},

	createIntegerNestedObjectArraySchema: function() {
		return new mongoose.Schema({
			nested: [{
				value: {
					type: Number,
					integer: true
				}
			}]
		});
	},

	createIntegerNestedNestedObjectArraySchema: function() {
		return new mongoose.Schema({
			nested: [{
				nested: [{
					value: {
						type: Number,
						integer: true
					}
				}]
			}]
		});

	},

	createIntegerNestedSchema: function() {
		var nestedSchema = new mongoose.Schema({
			value: {
				type: Number,
				integer: true
			}
		});

		nestedSchema.plugin(mongooseInteger);

		return new mongoose.Schema({
			nested: nestedSchema
		});
	},

	createIntegerNestedSchemaArray: function() {
		var nestedSchema = new mongoose.Schema({
			value: {
				type: Number,
				integer: true
			}
		});

		nestedSchema.plugin(mongooseInteger);

		return new mongoose.Schema({
			nested: [nestedSchema]
		});
	},

	createIntegerValidationSchema: function() {
		var schema = new mongoose.Schema({
			value: {
				type: Number,
				integer: true,
				required: true,
				min: 1,
				max: 10
			}
		});

		schema.path('value').validate(function(value) {
			return value > 5;
		}, 'Value is not greater than 5.');

		return schema;
	},

	createCustomIntegerSchema: function() {
		return new mongoose.Schema({
			value: {
				type: Number,
				integer: 'Value is not an integer.'
			}
		});
	}
};
<commit_msg>removed blank line<commit_after>/* jshint node: true */
'use strict';

var mongoose = require('mongoose');
var mongooseInteger = require('../index');

module.exports = {

	afterEach: function(done) {
		for (var key in mongoose.connection.collections) {
			mongoose.connection.collections[key].remove();
		}

		mongoose.models = {};
		mongoose.modelSchemas = {};
		mongoose.connection.models = {};
		done();
	},

	createIntegerSchema: function() {
		return new mongoose.Schema({
			value: {
				type: Number,
				integer: true
			}
		});
	},

	createIntegerStringSchema: function() {
		return new mongoose.Schema({
			value: {
				type: String,
				integer: true
			}
		});
	},

	createIntegerNestedObjectSchema: function() {
		return new mongoose.Schema({
			nested: {
				value: {
					type: Number,
					integer: true
				}
			}
		});
	},

	createIntegerNestedObjectArraySchema: function() {
		return new mongoose.Schema({
			nested: [{
				value: {
					type: Number,
					integer: true
				}
			}]
		});
	},

	createIntegerNestedNestedObjectArraySchema: function() {
		return new mongoose.Schema({
			nested: [{
				nested: [{
					value: {
						type: Number,
						integer: true
					}
				}]
			}]
		});
	},

	createIntegerNestedSchema: function() {
		var nestedSchema = new mongoose.Schema({
			value: {
				type: Number,
				integer: true
			}
		});

		nestedSchema.plugin(mongooseInteger);

		return new mongoose.Schema({
			nested: nestedSchema
		});
	},

	createIntegerNestedSchemaArray: function() {
		var nestedSchema = new mongoose.Schema({
			value: {
				type: Number,
				integer: true
			}
		});

		nestedSchema.plugin(mongooseInteger);

		return new mongoose.Schema({
			nested: [nestedSchema]
		});
	},

	createIntegerValidationSchema: function() {
		var schema = new mongoose.Schema({
			value: {
				type: Number,
				integer: true,
				required: true,
				min: 1,
				max: 10
			}
		});

		schema.path('value').validate(function(value) {
			return value > 5;
		}, 'Value is not greater than 5.');

		return schema;
	},

	createCustomIntegerSchema: function() {
		return new mongoose.Schema({
			value: {
				type: Number,
				integer: 'Value is not an integer.'
			}
		});
	}
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';

var translateService = Ember.Object.create({
    translateKey( data ) {
        this.set( 'key', data.key );
        this.set( 'pluralKey', data.pluralKey );
        this.set( 'pluralCount', data.pluralCount );
        this.set( 'parameters', data.parameters );

        return 'TRANSLATE: ' + data.key;
    }
});

moduleForComponent( 'sl-translate', 'Unit - component:sl-translate' );

/**
 * Ensures that the template is wrapping the content in a span tag and not in
 * any block-level tags. While it appears that core Ember functionality is being
 * tested this test is ensuring that the implied contract about how this non-UI
 * component is rendered into the DOM is adhered to.
 */
test( 'Renders as a span tag with no classes', function( assert ) {
    var component = this.subject({ translateService });

    assert.equal( this.$().prop( 'tagName' ), 'SPAN' );
    assert.equal( this.$().prop( 'class' ), 'ember-view' );
});

/**
 * That it renders and functions as expected
 */
test( 'DOM and content of rendered translation', function( assert ) {
    var component = this.subject({ key: 'the_key', translateService });

    assert.equal( Ember.$.trim( this.$().text() ), 'TRANSLATE: the_key' );
});

/**
 * Ensure haven't broken any default behavior of Ember, since manipulate properties passed to the component
 * A side effect of this test is the appearance that core Ember functionality is being tested
 */
test( 'Can be used alongside other properties or attribute bindings', function( assert ) {
    var component  = this.subject({
        translateService,
        key        : 'key_alongside',
        tagName    : 'h1',
        classNames : [ 'testClass' ]
    });

    assert.equal( this.$().prop( 'tagName' ), 'H1' );
    assert.equal( Ember.$.trim( this.$().text() ), 'TRANSLATE: key_alongside' );
    assert.equal( this.$().prop( 'class'), ['ember-view testClass'] );
});

test( 'On initialization, extractParameterKeys() filters passed parameters', function( assert ) {
    var component = this.subject({
            key         : 'the_key',
            pluralKey   : 'plural_key',
            pluralCount : 'plural_count',
            $0          : 'a',
            $1Binding   : 'b',
            $2          : 'c'
        });

    assert.deepEqual( component.get( 'parameters' ).sort(), [ '$0', '$1', '$2' ] );
});

test( 'On initialization, extractParameterKeys() filters passed parameters to be bound', function( assert ) {
    var component = this.subject({
            key         : 'the_key',
            pluralKey   : 'plural_key',
            pluralCount : 'plural_count',
            $0          : 'a',
            $1Binding   : 'b',
            $2          : 'c'
        });

    assert.deepEqual( component.get( 'observedParameters' ), [ '$1' ] );
});

test( 'setTranslatedString() sets translatedString property with value from translateString()', function( assert ) {
    var component = this.subject();

    component.translateString = function() {
        return 'test value';
    };

    component.setTranslatedString();

    assert.equal( component.get( 'translatedString' ), 'test value' );
});

test( 'translateString() calls translateKey() on the translation service', function( assert ) {
    var component = this.subject({
        translateService,
        key         : 'the_key',
        pluralKey   : 'plural_key',
        pluralCount : 'plural_count',
        $0          : 'a',
        $1          : 'b'
    });

    this.render();

    assert.equal( translateService.get( 'key' ), 'the_key' );
    assert.equal( translateService.get( 'pluralKey' ), 'plural_key' );
    assert.equal( translateService.get( 'pluralCount' ), 'plural_count' );
    assert.deepEqual( translateService.get( 'parameters' ), { $0: 'a', $1: 'b' } );
});

test( 'willInsertElement event causes setTranslatedString() to be called', function( assert ) {
    var component                    = this.subject(),
        setTranslatedStringWasCalled = false;

    component.setTranslatedString = function() {
        setTranslatedStringWasCalled = true;
    };

    // Render in DOM to trigger willInsertElement event
    this.render();

    assert.equal( setTranslatedStringWasCalled, true );
});

test( 'willInsertElement event causes observers to be added to each entry in observedParameters property', function( assert ) {
    var component = this.subject({
            translateService,
            key       : 'the_key',
            $0Binding : 'a',
            $1        : 'b'
        }),
        setTranslatedStringWasCalled = false;

    component.setTranslatedString = function() {
        setTranslatedStringWasCalled = true;
    };

    // Render in DOM to trigger willInsertElement event
    this.render();

    // Change value so can monitor for change
    setTranslatedStringWasCalled = false;

    Ember.run( function(){
        component.set( '$0', 'c' );
    });

    assert.equal( setTranslatedStringWasCalled, true );
});

test( 'willClearRender event causes observers to be removed', function( assert ) {
    var component = this.subject({
            translateService,
            key       : 'the_key',
            $0Binding : 'a',
            $1        : 'b'
        }),
        setTranslatedStringWasCalled = false;

    component.setTranslatedString = () => {
        setTranslatedStringWasCalled = true;
    };

    // Render in DOM to trigger willInsertElement event
    this.render();

    // Change value so can monitor for change
    setTranslatedStringWasCalled = false;

    component.trigger( 'willClearRender' );

    Ember.run( () => {
        component.set( '$0', 'c' );
    });

    assert.equal( setTranslatedStringWasCalled, false );
});
<commit_msg>Remove unnecessary component var assignments<commit_after>import Ember from 'ember';
import { moduleForComponent, test } from 'ember-qunit';

var translateService = Ember.Object.create({
    translateKey( data ) {
        this.set( 'key', data.key );
        this.set( 'pluralKey', data.pluralKey );
        this.set( 'pluralCount', data.pluralCount );
        this.set( 'parameters', data.parameters );

        return 'TRANSLATE: ' + data.key;
    }
});

moduleForComponent( 'sl-translate', 'Unit - component:sl-translate' );

/**
 * Ensures that the template is wrapping the content in a span tag and not in
 * any block-level tags. While it appears that core Ember functionality is being
 * tested this test is ensuring that the implied contract about how this non-UI
 * component is rendered into the DOM is adhered to.
 */
test( 'Renders as a span tag with no classes', function( assert ) {
    this.subject({ translateService });

    assert.equal( this.$().prop( 'tagName' ), 'SPAN' );
    assert.equal( this.$().prop( 'class' ), 'ember-view' );
});

/**
 * That it renders and functions as expected
 */
test( 'DOM and content of rendered translation', function( assert ) {
    this.subject({ key: 'the_key', translateService });

    assert.equal( Ember.$.trim( this.$().text() ), 'TRANSLATE: the_key' );
});

/**
 * Ensure haven't broken any default behavior of Ember, since manipulate properties passed to the component
 * A side effect of this test is the appearance that core Ember functionality is being tested
 */
test( 'Can be used alongside other properties or attribute bindings', function( assert ) {
    this.subject({
        translateService,
        key        : 'key_alongside',
        tagName    : 'h1',
        classNames : [ 'testClass' ]
    });

    assert.equal( this.$().prop( 'tagName' ), 'H1' );
    assert.equal( Ember.$.trim( this.$().text() ), 'TRANSLATE: key_alongside' );
    assert.equal( this.$().prop( 'class'), ['ember-view testClass'] );
});

test( 'On initialization, extractParameterKeys() filters passed parameters', function( assert ) {
    var component = this.subject({
            key         : 'the_key',
            pluralKey   : 'plural_key',
            pluralCount : 'plural_count',
            $0          : 'a',
            $1Binding   : 'b',
            $2          : 'c'
        });

    assert.deepEqual( component.get( 'parameters' ).sort(), [ '$0', '$1', '$2' ] );
});

test( 'On initialization, extractParameterKeys() filters passed parameters to be bound', function( assert ) {
    var component = this.subject({
            key         : 'the_key',
            pluralKey   : 'plural_key',
            pluralCount : 'plural_count',
            $0          : 'a',
            $1Binding   : 'b',
            $2          : 'c'
        });

    assert.deepEqual( component.get( 'observedParameters' ), [ '$1' ] );
});

test( 'setTranslatedString() sets translatedString property with value from translateString()', function( assert ) {
    var component = this.subject();

    component.translateString = function() {
        return 'test value';
    };

    component.setTranslatedString();

    assert.equal( component.get( 'translatedString' ), 'test value' );
});

test( 'translateString() calls translateKey() on the translation service', function( assert ) {
    this.subject({
        translateService,
        key         : 'the_key',
        pluralKey   : 'plural_key',
        pluralCount : 'plural_count',
        $0          : 'a',
        $1          : 'b'
    });

    this.render();

    assert.equal( translateService.get( 'key' ), 'the_key' );
    assert.equal( translateService.get( 'pluralKey' ), 'plural_key' );
    assert.equal( translateService.get( 'pluralCount' ), 'plural_count' );
    assert.deepEqual( translateService.get( 'parameters' ), { $0: 'a', $1: 'b' } );
});

test( 'willInsertElement event causes setTranslatedString() to be called', function( assert ) {
    var component                    = this.subject(),
        setTranslatedStringWasCalled = false;

    component.setTranslatedString = function() {
        setTranslatedStringWasCalled = true;
    };

    // Render in DOM to trigger willInsertElement event
    this.render();

    assert.equal( setTranslatedStringWasCalled, true );
});

test( 'willInsertElement event causes observers to be added to each entry in observedParameters property', function( assert ) {
    var component = this.subject({
            translateService,
            key       : 'the_key',
            $0Binding : 'a',
            $1        : 'b'
        }),
        setTranslatedStringWasCalled = false;

    component.setTranslatedString = function() {
        setTranslatedStringWasCalled = true;
    };

    // Render in DOM to trigger willInsertElement event
    this.render();

    // Change value so can monitor for change
    setTranslatedStringWasCalled = false;

    Ember.run( function(){
        component.set( '$0', 'c' );
    });

    assert.equal( setTranslatedStringWasCalled, true );
});

test( 'willClearRender event causes observers to be removed', function( assert ) {
    var component = this.subject({
            translateService,
            key       : 'the_key',
            $0Binding : 'a',
            $1        : 'b'
        }),
        setTranslatedStringWasCalled = false;

    component.setTranslatedString = () => {
        setTranslatedStringWasCalled = true;
    };

    // Render in DOM to trigger willInsertElement event
    this.render();

    // Change value so can monitor for change
    setTranslatedStringWasCalled = false;

    component.trigger( 'willClearRender' );

    Ember.run( () => {
        component.set( '$0', 'c' );
    });

    assert.equal( setTranslatedStringWasCalled, false );
});
<|endoftext|>


<commit_before>import React from 'react';
import { css } from '@emotion/core';

import Page from './page';
import { mq } from '../utils';
import styled from '@emotion/styled';

const Children = styled.div`
  overflow: auto;
`;

const SidebarLayout = ({ sidebar, children }) => (
  <Page
    css={css`
      ${mq[1]} {
        display: grid;
        grid-template-columns: 300px 1fr;
        grid-gap: 2rem;
      }
    `}
  >

{sidebar}

    <Children>{children}</Children>
  </Page>
);

export default SidebarLayout;
<commit_msg>fix(website): missing headers anchors (#3218)<commit_after>import React from 'react';
import { css } from '@emotion/core';

import Page from './page';
import { mq } from '../utils';
import styled from '@emotion/styled';

const Children = styled.div`
  overflow: auto;
  padding-left: 2rem;
`;

const SidebarLayout = ({ sidebar, children }) => (
  <Page
    css={css`
      ${mq[1]} {
        display: grid;
        grid-template-columns: 300px 1fr;
        grid-gap: 2rem;
      }
    `}
  >

{sidebar}

    <Children>{children}</Children>
  </Page>
);

export default SidebarLayout;
<|endoftext|>


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

describe('inter', function () {
    var inter = require('../build/en_us');

    describe('#renderDate()', function () {
        var d = new Date(2013, 11, 6, 10, 54, 10);

        it('should format a date according to the mediumDateTime format', function () {
            expect(inter.renderDate(d, 'mediumDateTime'), 'to equal', 'Dec 6, 2013, 10:54:10 am');
        });

        it('should use the fullDateTime format if the formatId parameter is omitted', function () {
            var timeZoneOffsetStr = d.toTimeString().match(/GMT([-+]\d\d\d\d)/)[1].replace(/(\d\d)$/, ':$1');
            expect(inter.renderDate(d), 'to equal', 'Friday, December 6, 2013 at 10:54:10 am ' + timeZoneOffsetStr);
        });

        it('should accept a number (epoch milliseconds) instead of a Date instance', function () {
            expect(inter.renderDate(5000, 'shortDate'), 'to equal', '1/1/1970');
        });

        it('should accept a parsable date string instead of a Date instance', function () {
            expect(inter.renderDate('Nov 18 2014 18:00', 'shortDate'), 'to equal', '11/18/2014');
        });

        it('should use the regular month format when using the L format character', function () {
            expect(require('../build/fi').renderDateFormat(new Date('Nov 18 2014 18:00'), 'MMMM'), 'to equal', 'marraskuuta');
        });

        it('should use the standalone month format when using the L format character', function () {
            expect(require('../build/fi').renderDateFormat(new Date('Nov 18 2014 18:00'), 'LLLL'), 'to equal', 'marraskuu');
        });
    });

    describe('#renderList()', function () {
        it('should should render a list according to the unitNarrow pattern', function () {
            expect(inter.renderList(['foo', 'bar', 'quux'], 'unitNarrow'), 'to equal', 'foo bar quux');
        });

        it('should use the default format when the type parameter is omitted', function () {
            expect(inter.renderList(['foo', 'bar', 'quux']), 'to equal', 'foo, bar, and quux');
        });
    });

    describe('#renderNumber', function () {
        it('should render a number in the Indian English locale (#11)', function () {
            expect(require('../build/en_in').renderNumber(10000000.23), 'to equal', '10,000,000.23');
        });

        it('should render a number in the Danish locale (#11)', function () {
            expect(require('../build/da').renderNumber(10000000.23), 'to equal', '10.000.000,23');
        });
    });

    describe('#renderPercentage', function () {
        it('should accept the number of decimals as the second parameter', function () {
            expect(require('../build/da').renderPercentage(12.345678, 2), 'to equal', '1.234,57\xa0%');
        });

        it('should accept the number system as the third parameter', function () {
            expect(require('../build/da').renderPercentage(12.345678, 2, 'mlym'), 'to equal', '൧.൨൩൪,൫൭\xa0%');
        });
    });

    describe('#renderUnit', function () {
        it('should render a singular number of units', function () {
            expect(inter.renderUnit(1, 'durationWeek'), 'to equal', '1 week');
        });

        it('should render a plural number of units', function () {
            expect(inter.renderUnit(2, 'durationWeek'), 'to equal', '2 weeks');
        });

        it('should render in the narrow format', function () {
            expect(inter.renderUnit(1, 'durationWeek', 'narrow'), 'to equal', '1w');
        });
    });

    describe('#renderCurrencyShort', function () {
        it('should render a float with a currency', function () {
            expect(inter.renderCurrencyShort(134.40, 'USD'), 'to equal', '$134.40');
        });

        it('should render a float with a currency, with a different amount of decimals', function () {
            expect(inter.renderCurrencyShort(134.40, 'USD', 'latn', 1), 'to equal', '$134.4');
        });

        it('should render a number in the Dutch locale', function () {
            expect(require('../build/nl').renderCurrencyShort(134.40, 'EUR'), 'to equal', '€ 134,40');
        });
    });

    describe('#renderCurrencyLong', function () {
        it('should render a float with a currency', function () {
            expect(inter.renderCurrencyLong(134.40, 'USD'), 'to equal', 'USD\xa0134.40');
        });

        it('should render a float with a currency, with a different amount of decimals', function () {
            expect(inter.renderCurrencyLong(134.40, 'USD', 'latn', 1), 'to equal', 'USD\xa0134.4');
        });

        it('should render a number in the Dutch locale', function () {
            expect(require('../build/nl').renderCurrencyLong(134.40, 'EUR'), 'to equal', 'EUR\xa0134,40');
        });
    });

    describe('#makeUnitRenderer', function () {
        it('should render in the narrow format', function () {
            expect(inter.makeUnitRenderer('durationWeek', 'narrow')(1), 'to equal', '1w');
        });
    });

    describe('#adaptICUFormat', function () {
        it('should adapt a pattern that uses L correctly when the format id uses M', function () {
            expect(require('../build/fi').adaptICUFormat('LLL', 'MMMM'), 'to equal', 'LLLL');
        });
    });
});
<commit_msg>Test formatting negative GMT offsets.<commit_after>/*global describe, it, beforeEach, afterEach*/
var expect = require('unexpected');

describe('inter', function () {
    var inter = require('../build/en_us');

    describe('#renderDate()', function () {
        var d = new Date(2013, 11, 6, 10, 54, 10);

        it('should format a date according to the mediumDateTime format', function () {
            expect(inter.renderDate(d, 'mediumDateTime'), 'to equal', 'Dec 6, 2013, 10:54:10 am');
        });

        it('should use the fullDateTime format if the formatId parameter is omitted', function () {
            var timeZoneOffsetStr = d.toTimeString().match(/GMT([-+]\d\d\d\d)/)[1].replace(/(\d\d)$/, ':$1');
            expect(inter.renderDate(d), 'to equal', 'Friday, December 6, 2013 at 10:54:10 am ' + timeZoneOffsetStr);
        });

        describe('with a negative time zone offset (GMT-02:00)', function () {
            var originalGetTimezoneOffset = Date.prototype.getTimezoneOffset;
            beforeEach(function () {
                Date.prototype.getTimezoneOffset = function () {
                    return 120; // This is a bit of a wtf, I would expect it to return -120, but it doesn't
                };
            });
            afterEach(function () {
                Date.prototype.getTimezoneOffset = originalGetTimezoneOffset;
            });

            it('should render the time zone offset correctly', function () {
                expect(inter.renderDate(new Date(2016, 0, 15, 11, 30), 'fullDateTime'), 'to equal', 'Friday, January 15, 2016 at 11:30:00 am -02:00');
            });
        });

        describe('with a positive time zone offset (GMT+02:00)', function () {
            var originalGetTimezoneOffset = Date.prototype.getTimezoneOffset;
            beforeEach(function () {
                Date.prototype.getTimezoneOffset = function () {
                    return -120; // This is a bit of a wtf, I would expect it to return 120, but it doesn't
                };
            });
            afterEach(function () {
                Date.prototype.getTimezoneOffset = originalGetTimezoneOffset;
            });

            it('should render the time zone offset correctly', function () {
                expect(inter.renderDate(new Date(2016, 0, 15, 11, 30), 'fullDateTime'), 'to equal', 'Friday, January 15, 2016 at 11:30:00 am +02:00');
            });
        });

        it('should accept a number (epoch milliseconds) instead of a Date instance', function () {
            expect(inter.renderDate(5000, 'shortDate'), 'to equal', '1/1/1970');
        });

        it('should accept a parsable date string instead of a Date instance', function () {
            expect(inter.renderDate('Nov 18 2014 18:00', 'shortDate'), 'to equal', '11/18/2014');
        });

        it('should use the regular month format when using the L format character', function () {
            expect(require('../build/fi').renderDateFormat(new Date('Nov 18 2014 18:00'), 'MMMM'), 'to equal', 'marraskuuta');
        });

        it('should use the standalone month format when using the L format character', function () {
            expect(require('../build/fi').renderDateFormat(new Date('Nov 18 2014 18:00'), 'LLLL'), 'to equal', 'marraskuu');
        });
    });

    describe('#renderList()', function () {
        it('should should render a list according to the unitNarrow pattern', function () {
            expect(inter.renderList(['foo', 'bar', 'quux'], 'unitNarrow'), 'to equal', 'foo bar quux');
        });

        it('should use the default format when the type parameter is omitted', function () {
            expect(inter.renderList(['foo', 'bar', 'quux']), 'to equal', 'foo, bar, and quux');
        });
    });

    describe('#renderNumber', function () {
        it('should render a number in the Indian English locale (#11)', function () {
            expect(require('../build/en_in').renderNumber(10000000.23), 'to equal', '10,000,000.23');
        });

        it('should render a number in the Danish locale (#11)', function () {
            expect(require('../build/da').renderNumber(10000000.23), 'to equal', '10.000.000,23');
        });
    });

    describe('#renderPercentage', function () {
        it('should accept the number of decimals as the second parameter', function () {
            expect(require('../build/da').renderPercentage(12.345678, 2), 'to equal', '1.234,57\xa0%');
        });

        it('should accept the number system as the third parameter', function () {
            expect(require('../build/da').renderPercentage(12.345678, 2, 'mlym'), 'to equal', '൧.൨൩൪,൫൭\xa0%');
        });
    });

    describe('#renderUnit', function () {
        it('should render a singular number of units', function () {
            expect(inter.renderUnit(1, 'durationWeek'), 'to equal', '1 week');
        });

        it('should render a plural number of units', function () {
            expect(inter.renderUnit(2, 'durationWeek'), 'to equal', '2 weeks');
        });

        it('should render in the narrow format', function () {
            expect(inter.renderUnit(1, 'durationWeek', 'narrow'), 'to equal', '1w');
        });
    });

    describe('#renderCurrencyShort', function () {
        it('should render a float with a currency', function () {
            expect(inter.renderCurrencyShort(134.40, 'USD'), 'to equal', '$134.40');
        });

        it('should render a float with a currency, with a different amount of decimals', function () {
            expect(inter.renderCurrencyShort(134.40, 'USD', 'latn', 1), 'to equal', '$134.4');
        });

        it('should render a number in the Dutch locale', function () {
            expect(require('../build/nl').renderCurrencyShort(134.40, 'EUR'), 'to equal', '€ 134,40');
        });
    });

    describe('#renderCurrencyLong', function () {
        it('should render a float with a currency', function () {
            expect(inter.renderCurrencyLong(134.40, 'USD'), 'to equal', 'USD\xa0134.40');
        });

        it('should render a float with a currency, with a different amount of decimals', function () {
            expect(inter.renderCurrencyLong(134.40, 'USD', 'latn', 1), 'to equal', 'USD\xa0134.4');
        });

        it('should render a number in the Dutch locale', function () {
            expect(require('../build/nl').renderCurrencyLong(134.40, 'EUR'), 'to equal', 'EUR\xa0134,40');
        });
    });

    describe('#makeUnitRenderer', function () {
        it('should render in the narrow format', function () {
            expect(inter.makeUnitRenderer('durationWeek', 'narrow')(1), 'to equal', '1w');
        });
    });

    describe('#adaptICUFormat', function () {
        it('should adapt a pattern that uses L correctly when the format id uses M', function () {
            expect(require('../build/fi').adaptICUFormat('LLL', 'MMMM'), 'to equal', 'LLLL');
        });
    });
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import CloudinaryImageMixin from 'ember-cli-cloudinary-images/mixins/cloudinary-image';
import { module, test } from 'qunit';

module('mixin:cloudinary-image');

test('it works', function(assert) {
  var CloudinaryImageObject = Ember.Object.extend(CloudinaryImageMixin);
  var subject = CloudinaryImageObject.create();
  assert.ok(subject);
});

test('allFilters identical to filters', function(assert) {
  assert.expect(1);

  var subject = Ember.Object.extend(CloudinaryImageMixin).create();

  subject.set('filters', 'fl_progressive,c_fill');

  Ember.run(function() {
    console.log(subject.get('allFilters'));
    assert.equal(subject.get('allFilters'), 'fl_progressive,c_fill');
  });
});

test('allFilters can handle array filters', function(assert) {
  assert.expect(1);

  var subject = Ember.Object.extend(CloudinaryImageMixin).create();
  subject.set('filters', ['c_fill' , 'fl_progressive']);

  assert.equal(subject.get('allFilters'), 'c_fill,fl_progressive');
});

test('allFilters includes w and h', function(assert) {
  assert.expect(1);

  var subject = Ember.Object.extend(CloudinaryImageMixin).create();
  subject.setProperties({
    filters: 'fl_progressive',
    w: 100,
    h: 50
  });

  assert.equal(subject.get('allFilters'), 'fl_progressive,w_100,h_50');
});
<commit_msg>removed unneeded code<commit_after>import Ember from 'ember';
import CloudinaryImageMixin from 'ember-cli-cloudinary-images/mixins/cloudinary-image';
import { module, test } from 'qunit';

module('mixin:cloudinary-image');

test('it works', function(assert) {
  var CloudinaryImageObject = Ember.Object.extend(CloudinaryImageMixin);
  var subject = CloudinaryImageObject.create();
  assert.ok(subject);
});

test('allFilters identical to filters', function(assert) {
  assert.expect(1);

  var subject = Ember.Object.extend(CloudinaryImageMixin).create();

  subject.set('filters', 'fl_progressive,c_fill');

  assert.equal(subject.get('allFilters'), 'fl_progressive,c_fill');
});

test('allFilters can handle array filters', function(assert) {
  assert.expect(1);

  var subject = Ember.Object.extend(CloudinaryImageMixin).create();
  subject.set('filters', ['c_fill' , 'fl_progressive']);

  assert.equal(subject.get('allFilters'), 'c_fill,fl_progressive');
});

test('allFilters includes w and h', function(assert) {
  assert.expect(1);

  var subject = Ember.Object.extend(CloudinaryImageMixin).create();
  subject.setProperties({
    filters: 'fl_progressive',
    w: 100,
    h: 50
  });

  assert.equal(subject.get('allFilters'), 'fl_progressive,w_100,h_50');
});
<|endoftext|>