<commit_before>require([], function() {

  describe('toHaveLength', function() {

    describe('matches', function() {
      it('should work for `{length:null}`', function() {
        expect({length: null}).toHaveLength(null);
      });
    });

  });

  describe('toHaveProperties', function() {

    describe('matches', function() {
      it('should work with one property', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveProperties('x');
      });
      it('should work with one property as array', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveProperties(['x']);
      });
      it('should work for `{x:0, y:undefined}`', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveProperties('x', 'y');
      });
      it('should work with an array too', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveProperties(['x', 'y']);
      });
    });
  });

  describe('toHavePropertiesWithValues', function() {

    describe('matches', function() {
      it('should work with a reference object', function() {
        function C() { this.x = 0; }

        C.prototype.y = 'arbitrary';

        expect(new C).toHavePropertiesWithValues({
          x: 0,
          y: 'arbitrary',
          constructor: C
        });
      });
      it('should work with nested objects', function() {
        expect({obj: {x: 1, y: 2}})
          .toHavePropertiesWithValues({obj: {x: 1, y: 2}});
      });
      it('should work with nested objects, also when the keys are not in the same order', function() {
        expect({obj: {x: 1, y: 2}})
          .toHavePropertiesWithValues({obj: {y: 2, x: 1}});
      });
      it('should work with nested objects of depth>2, and different key order', function() {
        expect({obj: {x: 1, y: 2, subObj: {subsub: {a: 9, b: 10}}}})
          .toHavePropertiesWithValues({obj: {x: 1, subObj: {subsub: {b: 10, a: 9}}, y: 2}});
      });
    });

    describe('non-matches', function() {
      it('should not fail with undefined', function() {
        expect(undefined)
          .not.toHavePropertiesWithValues({obj: {x: 1, y: 2}});
      });
      it('should work in nested objects', function() {
        expect({tagCount: {DefineButton: 2}})
          .not.toHavePropertiesWithValues({tagCount: {DefineButton: 1}});
      });
      it('should work when all actual values` values are 0', function() {
        expect({audio: 0, video: 0, image: 0, font: 0})
          .not.toHavePropertiesWithValues({audio: 1, video: 0, image: 3, font: 1});
      });
    });

  });

  describe('toHaveOwnProperties', function() {

    describe('matches', function() {
      it('should work with one property', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveOwnProperties('x');
      });
      it('should work with one property as array', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveOwnProperties(['x']);
      });
      it('should work for `{x:0, y:undefined}`', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveOwnProperties('x', 'y');
      });
      it('should work with an array', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveOwnProperties(['x', 'y']);
      });
    });
  });

  describe('toHaveOwnPropertiesWithValues', function() {

    describe('matches', function() {
      it('should work with a reference object', function() {
        expect({
          x: 0,
          y: 'arbitrary'
        }).toHaveOwnPropertiesWithValues({
            x: 0,
            y: 'arbitrary'
          });
      });
    });

  });

  describe('toHaveBeenCalledXTimes', function() {

    describe('matches', function() {
      it('should work for 1', function() {
        var func = jasmine.createSpy('func');
        func();
        expect(func).toHaveBeenCalledXTimes(1);
      });

      it('should work for 2', function() {
        var func = jasmine.createSpy('func');
        func();
        func();
        expect(func).not.toHaveBeenCalledXTimes(1);
      });
    });

  });

  describe('toExactlyHaveProperties', function() {

    describe('matches', function() {
      it('should work for `{x:0, y:undefined}`', function() {
        var obj = {x: 0, y: undefined};
        expect(obj)
          .toExactlyHaveProperties('x', 'y');
      });
      it('should work in any order', function() {
        var obj = {x: 0, y: undefined};
        expect(obj)
          .toExactlyHaveProperties('y', 'x');
      });
    });

    describe('non-matches', function() {
      it('should work for too many properties', function() {
        var obj = {x: 0, y: undefined};
        expect(obj)
          .not.toExactlyHaveProperties('x');
      });
      it('should work for missing properties', function() {
        var obj = {x: 0, y: undefined};
        expect(obj)
          .not.toExactlyHaveProperties('x', 'y', 'z');
      });
    });

  });

  describe('toHaveEnumerableProperties', function() {
    describe('matches', function() {

      it('should find `x` on obj', function() {
        var obj = {x: 1};
        expect(obj)
          .toHaveEnumerableProperties(['x']);
      });

      it('should find `x` and `y` on obj', function() {
        var obj = {x: 1, y: 2};
        expect(obj)
          .toHaveEnumerableProperties(['x', 'y']);
      });

      it('should find one but not the other', function() {
        var obj = {z: 2};
        expect(obj)
          .toHaveEnumerableProperties(['x', 'z']);
      });

    });

    describe('non-matches', function() {

      it('should NOT find `y` on obj', function() {
        var obj = {x: 1};
        expect(obj)
          .not.toHaveEnumerableProperties(['y']);
      });

      it('should NOT find `x` and `y` on obj', function() {
        var obj = {z: 2};
        expect(obj)
          .not.toHaveEnumerableProperties(['x', 'y']);
      });

      it('should NOT find one but the other', function() {
        var obj = {z: 2};
        expect(obj)
          .not.toHaveEnumerableProperties(['x', 'z']);
      });

    });
  });

});
<commit_msg>Fixed test, that didnt pass.<commit_after>require([], function() {

  describe('toHaveLength', function() {

    describe('matches', function() {
      it('should work for `{length:null}`', function() {
        expect({length: null}).toHaveLength(null);
      });
    });

  });

  describe('toHaveProperties', function() {

    describe('matches', function() {
      it('should work with one property', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveProperties('x');
      });
      it('should work with one property as array', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveProperties(['x']);
      });
      it('should work for `{x:0, y:undefined}`', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveProperties('x', 'y');
      });
      it('should work with an array too', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveProperties(['x', 'y']);
      });
    });
  });

  describe('toHavePropertiesWithValues', function() {

    describe('matches', function() {
      it('should work with a reference object', function() {
        function C() { this.x = 0; }

        C.prototype.y = 'arbitrary';

        expect(new C).toHavePropertiesWithValues({
          x: 0,
          y: 'arbitrary',
          constructor: C
        });
      });
      it('should work with nested objects', function() {
        expect({obj: {x: 1, y: 2}})
          .toHavePropertiesWithValues({obj: {x: 1, y: 2}});
      });
      it('should work with nested objects, also when the keys are not in the same order', function() {
        expect({obj: {x: 1, y: 2}})
          .toHavePropertiesWithValues({obj: {y: 2, x: 1}});
      });
      it('should work with nested objects of depth>2, and different key order', function() {
        expect({obj: {x: 1, y: 2, subObj: {subsub: {a: 9, b: 10}}}})
          .toHavePropertiesWithValues({obj: {x: 1, subObj: {subsub: {b: 10, a: 9}}, y: 2}});
      });
    });

    describe('non-matches', function() {
      it('should not fail with undefined', function() {
        expect(undefined)
          .not.toHavePropertiesWithValues({obj: {x: 1, y: 2}});
      });
      it('should work in nested objects', function() {
        expect({tagCount: {DefineButton: 2}})
          .not.toHavePropertiesWithValues({tagCount: {DefineButton: 1}});
      });
      it('should work when all actual values` values are 0', function() {
        expect({audio: 0, video: 0, image: 0, font: 0})
          .not.toHavePropertiesWithValues({audio: 1, video: 0, image: 3, font: 1});
      });
    });

  });

  describe('toHaveOwnProperties', function() {

    describe('matches', function() {
      it('should work with one property', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveOwnProperties('x');
      });
      it('should work with one property as array', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveOwnProperties(['x']);
      });
      it('should work for `{x:0, y:undefined}`', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveOwnProperties('x', 'y');
      });
      it('should work with an array', function() {
        var obj = {x: 0, y: undefined};
        expect(obj).toHaveOwnProperties(['x', 'y']);
      });
    });
  });

  describe('toHaveOwnPropertiesWithValues', function() {

    describe('matches', function() {
      it('should work with a reference object', function() {
        expect({
          x: 0,
          y: 'arbitrary'
        }).toHaveOwnPropertiesWithValues({
            x: 0,
            y: 'arbitrary'
          });
      });
    });

  });

  describe('toHaveBeenCalledXTimes', function() {

    describe('matches', function() {
      it('should work for 1', function() {
        var func = jasmine.createSpy('func');
        func();
        expect(func).toHaveBeenCalledXTimes(1);
      });

      it('should work for 2', function() {
        var func = jasmine.createSpy('func');
        func();
        func();
        expect(func).not.toHaveBeenCalledXTimes(1);
      });
    });

  });

  describe('toExactlyHaveProperties', function() {

    describe('matches', function() {
      it('should work for `{x:0, y:undefined}`', function() {
        var obj = {x: 0, y: undefined};
        expect(obj)
          .toExactlyHaveProperties('x', 'y');
      });
      it('should work in any order', function() {
        var obj = {x: 0, y: undefined};
        expect(obj)
          .toExactlyHaveProperties('y', 'x');
      });
    });

    describe('non-matches', function() {
      it('should work for too many properties', function() {
        var obj = {x: 0, y: undefined};
        expect(obj)
          .not.toExactlyHaveProperties('x');
      });
      it('should work for missing properties', function() {
        var obj = {x: 0, y: undefined};
        expect(obj)
          .not.toExactlyHaveProperties('x', 'y', 'z');
      });
    });

  });

  describe('toHaveEnumerableProperties', function() {
    describe('matches', function() {

      it('should find `x` on obj', function() {
        var obj = {x: 1};
        expect(obj)
          .toHaveEnumerableProperties(['x']);
      });

      it('should find `x` and `y` on obj', function() {
        var obj = {x: 1, y: 2};
        expect(obj)
          .toHaveEnumerableProperties(['x', 'y']);
      });

    });

    describe('non-matches', function() {

      it('should NOT find `y` on obj', function() {
        var obj = {x: 1};
        expect(obj)
          .not.toHaveEnumerableProperties(['y']);
      });

      it('should NOT find `x` and `y` on obj', function() {
        var obj = {z: 2};
        expect(obj)
          .not.toHaveEnumerableProperties(['x', 'y']);
      });

      it('should find one but NOT the other', function() {
        var obj = {z: 2};
        expect(obj)
          .not.toHaveEnumerableProperties(['x', 'z']);
      });

    });
  });

});
<|endoftext|>


<commit_before>/*globals rabbitmq_test_bindings: false,
          rabbitmq_bindings_to_remove: false */
/*jslint mocha: true */
"use strict";

var expect = require('chai').expect,
    util = require('util'),
    Qlobber = require('..').Qlobber;

function QlobberTopicCount (options)
{
    Qlobber.call(this, options);
    this.topic_count = 0;
}

util.inherits(QlobberTopicCount, Qlobber);

QlobberTopicCount.prototype._initial_value = function (val)
{
    this.topic_count += 1;
    return Qlobber.prototype._initial_value(val);
};

QlobberTopicCount.prototype._remove_value = function (vals, val)
{
    var removed = Qlobber.prototype._remove_value(vals, val);
    if (removed)
    {
        this.topic_count -= 1;
    }
    return removed;
};

QlobberTopicCount.prototype.clear = function ()
{
    this.topic_count = 0;
    return Qlobber.prototype.clear.call(this);
};

describe('qlobber-topic-count', function ()
{
    it('should be able to count topics added', function ()
    {
        var matcher = new QlobberTopicCount();

        rabbitmq_test_bindings.forEach(function (topic_val)
        {
            matcher.add(topic_val[0], topic_val[1]);
        });
        expect(matcher.topic_count).to.equal(25);

        rabbitmq_bindings_to_remove.forEach(function (i)
        {
            matcher.remove(rabbitmq_test_bindings[i-1][0],
                           rabbitmq_test_bindings[i-1][1]);
        });
        expect(matcher.topic_count).to.equal(21);

		matcher.clear();
		expect(matcher.topic_count).to.equal(0);
        expect(matcher.match('a.b.c').length).to.equal(0);
    });
});
<commit_msg>Add extra tests for topic count example<commit_after>/*globals rabbitmq_test_bindings: false,
          rabbitmq_bindings_to_remove: false */
/*jslint mocha: true */
"use strict";

var expect = require('chai').expect,
    util = require('util'),
    Qlobber = require('..').Qlobber;

function QlobberTopicCount (options)
{
    Qlobber.call(this, options);
    this.topic_count = 0;
}

util.inherits(QlobberTopicCount, Qlobber);

QlobberTopicCount.prototype._initial_value = function (val)
{
    this.topic_count += 1;
    return Qlobber.prototype._initial_value(val);
};

QlobberTopicCount.prototype._remove_value = function (vals, val)
{
    var removed = Qlobber.prototype._remove_value(vals, val);
    if (removed)
    {
        this.topic_count -= 1;
    }
    return removed;
};

QlobberTopicCount.prototype.clear = function ()
{
    this.topic_count = 0;
    return Qlobber.prototype.clear.call(this);
};

describe('qlobber-topic-count', function ()
{
    it('should be able to count topics added', function ()
    {
        var matcher = new QlobberTopicCount();

        rabbitmq_test_bindings.forEach(function (topic_val)
        {
            matcher.add(topic_val[0], topic_val[1]);
        });
        expect(matcher.topic_count).to.equal(25);

        rabbitmq_bindings_to_remove.forEach(function (i)
        {
            matcher.remove(rabbitmq_test_bindings[i-1][0],
                           rabbitmq_test_bindings[i-1][1]);
        });
        expect(matcher.topic_count).to.equal(21);

		matcher.clear();
		expect(matcher.topic_count).to.equal(0);
        expect(matcher.match('a.b.c').length).to.equal(0);
    });

    it('should not decrement count if entry does not exist', function ()
    {
        var matcher = new QlobberTopicCount();
        expect(matcher.topic_count).to.equal(0);

        matcher.add('foo.bar', 23);
        expect(matcher.topic_count).to.equal(1);

        matcher.remove('foo.bar', 24);
        expect(matcher.topic_count).to.equal(1);

        matcher.remove('foo.bar2', 23);
        expect(matcher.topic_count).to.equal(1);

        matcher.remove('foo.bar', 23);
        expect(matcher.topic_count).to.equal(0);

        matcher.remove('foo.bar', 24);
        expect(matcher.topic_count).to.equal(0);

        matcher.remove('foo.bar2', 23);
        expect(matcher.topic_count).to.equal(0);
    });
});
<|endoftext|>


<commit_before>define("ace/theme/bxl",["require","exports","module","ace/lib/dom"],function(e,t,n){t.cssClass="ace-bxl",t.cssText=".ace-bxl .ace_gutter {background: #f0f0f0;border-right: 1px solid #eee;color: #8F908A;}.ace-bxl.ace_editor{border: 1px solid lightgray;border-radius: 4px;background-color: white;margin-bottom: 1em;}.ace-bxl .ace_cursor {color: #666666;}.ace-bxl .ace_marker-layer .ace_selected-word {border: 1px solid #666666;border-radius: 1px;}.ace-bxl .ace_marker-layer .ace_active-line,.ace-bxl .ace_gutter-active-line {background: rgba(34, 170, 255, 0.10);}.ace-bxl .ace_marker-layer .ace_selection {background: rgba(0, 120, 205, 0.15);}.ace-bxl .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid #666666;border-radius: 1px;}.ace-bxl .ace_invalid {color: #F8F8F0;background-color: #F92626;padding-left: 0.1em;padding-right: 0.1em;}.ace-bxl .ace_support.ace_function {color: #DD00DD;}.ace-bxl .ace_fold {background-color: #A6E22E;border-color: #F8F8F2}.ace-bxl .ace_variable {color: #879EFA;font-weight: bold;}.ace-bxl .ace_keyword,.ace-bxl .ace_keyword.ace_control,.ace-bxl .ace_constant.ace_language {color: #7F0055;font-weight: bold;}.ace_keyword.ace_operator {color: black;font-weight: normal;}.ace-bxl .ace_identifier.ace_tree{color: #FF7F00;}.ace-bxl .ace_variable.ace_parameter {font-style: italic;color: #009DFF;}.ace-bxl .ace_constant.ace_numeric,.ace-bxl .ace_constant.ace_character,.ace-bxl .ace_string,.ace-bxl .ace_constant.ace_other {color: blue;}.ace-bxl .ace_comment {color: #007F00;}.ace-bxl .ace_indent-guide {border-right: 1px solid lightgray;margin-right: -1px; }.ace_variable .ace_language .ace_invalid .ace_illegal {text-decoration: line-through;color: red;background-color: inherit;}";var r=e("../lib/dom");r.importCssString(t.cssText,t.cssClass)})<commit_msg>Brum.<commit_after>define("ace/theme/bxl",["require","exports","module","ace/lib/dom"],function(e,t,n){t.cssClass="ace-bxl",t.cssText=".ace-bxl .ace_gutter {background: #f0f0f0;border-right: 1px solid #eee;color: #8F908A;}.ace-bxl.ace_editor{border: 1px solid lightgray;border-radius: 4px;background-color: white;margin-bottom: 1em;}.ace-bxl .ace_cursor {color: #666666;}.ace-bxl .ace_marker-layer .ace_selected-word {border: 1px solid #666666;border-radius: 1px;}.ace-bxl .ace_marker-layer .ace_active-line,.ace-bxl .ace_gutter-active-line {background: rgba(34, 170, 255, 0.10);}.ace-bxl .ace_marker-layer .ace_selection {background: rgba(0, 120, 205, 0.15);}.ace-bxl .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid #666666;border-radius: 1px;}.ace-bxl .ace_invalid {color: #F8F8F0;background-color: #F92626;padding-left: 0.1em;padding-right: 0.1em;}.ace-bxl .ace_support.ace_function {color: #DD00DD;}.ace-bxl .ace_fold {background-color: #A6E22E;border-color: #F8F8F2}.ace-bxl .ace_variable {color: #879EFA;font-weight: bold;}.ace-bxl .ace_keyword,.ace-bxl .ace_keyword.ace_control,.ace-bxl .ace_constant.ace_language {color: #7F0055;font-weight: bold;}.ace_keyword.ace_operator {color: black;font-weight: normal;}.ace-bxl .ace_identifier.ace_tree{color: #FF7F00;}.ace-bxl .ace_variable.ace_parameter {font-style: italic;color: #009DFF;}.ace-bxl .ace_constant.ace_numeric,.ace-bxl .ace_constant.ace_character,.ace-bxl .ace_string,.ace-bxl .ace_constant.ace_other {color: blue;}.ace-bxl .ace_comment {color: #007F00;}.ace-bxl .ace_indent-guide {border-right: 1px solid lightgray;margin-right: -1px; }.ace_variable.ace_language.ace_invalid.ace_illegal {text-decoration: line-through;color: red;background-color: inherit;}";var r=e("../lib/dom");r.importCssString(t.cssText,t.cssClass)})<|endoftext|>


<commit_before>/* global describe, it, beforeEach */

var assert = require('assert')
var bscript = require('../src/script')
var fixtures = require('./fixtures/transaction')
var Transaction = require('../src/transaction')

describe('Transaction', function () {
  function fromRaw (raw, noWitness) {
    var tx = new Transaction()
    tx.version = raw.version
    tx.locktime = raw.locktime

    raw.ins.forEach(function (txIn, i) {
      var txHash = new Buffer(txIn.hash, 'hex')
      var scriptSig

      if (txIn.data) {
        scriptSig = new Buffer(txIn.data, 'hex')
      } else if (txIn.script) {
        scriptSig = bscript.fromASM(txIn.script)
      }

      tx.addInput(txHash, txIn.index, txIn.sequence, scriptSig)

      if (!noWitness && txIn.witness) {
        var witness = txIn.witness.map(function (x) {
          return new Buffer(x, 'hex')
        })

        tx.setWitness(i, witness)
      }
    })

    raw.outs.forEach(function (txOut) {
      var script

      if (txOut.data) {
        script = new Buffer(txOut.data, 'hex')
      } else if (txOut.script) {
        script = bscript.fromASM(txOut.script)
      }

      tx.addOutput(script, txOut.value)
    })

    return tx
  }

  describe('fromBuffer/fromHex', function () {
    function importExport (f) {
      var id = f.id || f.hash
      var txHex = f.hex || f.txHex

      it('imports ' + f.description + ' (' + id + ')', function () {
        var actual = Transaction.fromHex(txHex)

        assert.strictEqual(actual.toHex(), txHex)
      })

      if (f.whex) {
        it('imports ' + f.description + ' (' + id + ') as witness', function () {
          var actual = Transaction.fromHex(f.whex)

          assert.strictEqual(actual.toHex(), f.whex)
        })
      }
    }

    fixtures.valid.forEach(importExport)
    fixtures.hashForSignature.forEach(importExport)
    fixtures.hashForWitnessV0.forEach(importExport)

    fixtures.invalid.fromBuffer.forEach(function (f) {
      it('throws on ' + f.exception, function () {
        assert.throws(function () {
          Transaction.fromHex(f.hex)
        }, new RegExp(f.exception))
      })
    })

    it('.version should be interpreted as an int32le', function () {
      var txHex = 'ffffffff0000ffffffff'
      var tx = Transaction.fromHex(txHex)
      assert.equal(-1, tx.version)
      assert.equal(0xffffffff, tx.locktime)
    })
  })

  describe('toBuffer/toHex', function () {
    fixtures.valid.forEach(function (f) {
      it('exports ' + f.description + ' (' + f.id + ')', function () {
        if (f.whex) {
          var wactual = fromRaw(f.raw)
          assert.strictEqual(wactual.toHex(), f.whex)
        }

        var actual = fromRaw(f.raw, true)
        assert.strictEqual(actual.toHex(), f.hex)
      })
    })

    it('accepts target Buffer and offset parameters', function () {
      var f = fixtures.valid[0]
      var actual = fromRaw(f.raw)
      var byteLength = actual.byteLength()

      var target = new Buffer(byteLength * 2)
      var a = actual.toBuffer(target, 0)
      var b = actual.toBuffer(target, byteLength)

      assert.strictEqual(a.length, byteLength)
      assert.strictEqual(b.length, byteLength)
      assert.strictEqual(a.toString('hex'), f.hex)
      assert.strictEqual(b.toString('hex'), f.hex)
      assert.deepEqual(a, b)
      assert.deepEqual(a, target.slice(0, byteLength))
      assert.deepEqual(b, target.slice(byteLength))
    })
  })

  describe('hasWitnesses', function () {
    fixtures.valid.forEach(function (f) {
      it('detects if the transaction has witnesses: ' + (f.whex ? 'true' : 'false'), function () {
        assert.strictEqual(Transaction.fromHex(f.whex ? f.whex : f.hex).hasWitnesses(), !!f.whex)
      })
    })
  })

  describe('addInput', function () {
    var prevTxHash
    beforeEach(function () {
      prevTxHash = new Buffer('ffffffff00ffff000000000000000000000000000000000000000000101010ff', 'hex')
    })

    it('returns an index', function () {
      var tx = new Transaction()
      assert.strictEqual(tx.addInput(prevTxHash, 0), 0)
      assert.strictEqual(tx.addInput(prevTxHash, 0), 1)
    })

    it('defaults to empty script, witness and 0xffffffff SEQUENCE number', function () {
      var tx = new Transaction()
      tx.addInput(prevTxHash, 0)

      assert.strictEqual(tx.ins[0].script.length, 0)
      assert.strictEqual(tx.ins[0].witness.length, 0)
      assert.strictEqual(tx.ins[0].sequence, 0xffffffff)
    })

    fixtures.invalid.addInput.forEach(function (f) {
      it('throws on ' + f.exception, function () {
        var tx = new Transaction()
        var hash = new Buffer(f.hash, 'hex')

        assert.throws(function () {
          tx.addInput(hash, f.index)
        }, new RegExp(f.exception))
      })
    })
  })

  describe('addOutput', function () {
    it('returns an index', function () {
      var tx = new Transaction()
      assert.strictEqual(tx.addOutput(new Buffer(0), 0), 0)
      assert.strictEqual(tx.addOutput(new Buffer(0), 0), 1)
    })
  })

  describe('clone', function () {
    fixtures.valid.forEach(function (f) {
      var actual, expected

      beforeEach(function () {
        expected = Transaction.fromHex(f.hex)
        actual = expected.clone()
      })

      it('should have value equality', function () {
        assert.deepEqual(actual, expected)
      })

      it('should not have reference equality', function () {
        assert.notEqual(actual, expected)
      })
    })
  })

  describe('getHash/getId', function () {
    function verify (f) {
      it('should return the id for ' + f.id, function () {
        var tx = Transaction.fromHex(f.whex || f.hex)

        assert.strictEqual(tx.getHash().toString('hex'), f.hash)
        assert.strictEqual(tx.getId(), f.id)
      })
    }

    fixtures.valid.forEach(verify)
  })

  describe('isCoinbase', function () {
    function verify (f) {
      it('should return ' + f.coinbase + ' for ' + f.id, function () {
        var tx = Transaction.fromHex(f.hex)

        assert.strictEqual(tx.isCoinbase(), f.coinbase)
      })
    }

    fixtures.valid.forEach(verify)
  })

  describe('hashForSignature', function () {
    it('only uses legacy serialization', function () {
      var randScript = new Buffer('6a', 'hex')

      var tx = new Transaction()
      tx.addInput(new Buffer('0000000000000000000000000000000000000000000000000000000000000000', 'hex'), 0)
      tx.addOutput(randScript, 5000000000)

      var original = tx.__toBuffer
      tx.__toBuffer = function (a, b, c) {
        if (c !== false) throw new Error('hashForSignature MUST pass false')

        return original.call(this, a, b, c)
      }

      assert.throws(function () {
        tx.__toBuffer(undefined, undefined, true)
      }, /hashForSignature MUST pass false/)

      // assert hashForSignature does not pass false
      assert.doesNotThrow(function () {
        tx.hashForSignature(0, randScript, 1)
      })
    })

    fixtures.hashForSignature.forEach(function (f) {
      it('should return ' + f.hash + ' for ' + (f.description ? ('case "' + f.description + '"') : f.script), function () {
        var tx = Transaction.fromHex(f.txHex)
        var script = bscript.fromASM(f.script)

        assert.strictEqual(tx.hashForSignature(f.inIndex, script, f.type).toString('hex'), f.hash)
      })
    })
  })

  describe('hashForWitnessV0', function () {
    fixtures.hashForWitnessV0.forEach(function (f) {
      it('should return ' + f.hash + ' for ' + (f.description ? ('case "' + f.description + '"') : ''), function () {
        var tx = Transaction.fromHex(f.txHex)
        var script = bscript.fromASM(f.script)

        assert.strictEqual(tx.hashForWitnessV0(f.inIndex, script, f.value, f.type).toString('hex'), f.hash)
      })
    })
  })

  describe('setWitness', function () {
    it('only accepts a a witness stack (Array of Buffers)', function () {
      assert.throws(function () {
        (new Transaction()).setWitness(0, 'foobar')
      }, /Expected property "1" of type \[Buffer], got String "foobar"/)
    })
  })
})
<commit_msg>tests: reword, more explicit<commit_after>/* global describe, it, beforeEach */

var assert = require('assert')
var bscript = require('../src/script')
var fixtures = require('./fixtures/transaction')
var Transaction = require('../src/transaction')

describe('Transaction', function () {
  function fromRaw (raw, noWitness) {
    var tx = new Transaction()
    tx.version = raw.version
    tx.locktime = raw.locktime

    raw.ins.forEach(function (txIn, i) {
      var txHash = new Buffer(txIn.hash, 'hex')
      var scriptSig

      if (txIn.data) {
        scriptSig = new Buffer(txIn.data, 'hex')
      } else if (txIn.script) {
        scriptSig = bscript.fromASM(txIn.script)
      }

      tx.addInput(txHash, txIn.index, txIn.sequence, scriptSig)

      if (!noWitness && txIn.witness) {
        var witness = txIn.witness.map(function (x) {
          return new Buffer(x, 'hex')
        })

        tx.setWitness(i, witness)
      }
    })

    raw.outs.forEach(function (txOut) {
      var script

      if (txOut.data) {
        script = new Buffer(txOut.data, 'hex')
      } else if (txOut.script) {
        script = bscript.fromASM(txOut.script)
      }

      tx.addOutput(script, txOut.value)
    })

    return tx
  }

  describe('fromBuffer/fromHex', function () {
    function importExport (f) {
      var id = f.id || f.hash
      var txHex = f.hex || f.txHex

      it('imports ' + f.description + ' (' + id + ')', function () {
        var actual = Transaction.fromHex(txHex)

        assert.strictEqual(actual.toHex(), txHex)
      })

      if (f.whex) {
        it('imports ' + f.description + ' (' + id + ') as witness', function () {
          var actual = Transaction.fromHex(f.whex)

          assert.strictEqual(actual.toHex(), f.whex)
        })
      }
    }

    fixtures.valid.forEach(importExport)
    fixtures.hashForSignature.forEach(importExport)
    fixtures.hashForWitnessV0.forEach(importExport)

    fixtures.invalid.fromBuffer.forEach(function (f) {
      it('throws on ' + f.exception, function () {
        assert.throws(function () {
          Transaction.fromHex(f.hex)
        }, new RegExp(f.exception))
      })
    })

    it('.version should be interpreted as an int32le', function () {
      var txHex = 'ffffffff0000ffffffff'
      var tx = Transaction.fromHex(txHex)
      assert.equal(-1, tx.version)
      assert.equal(0xffffffff, tx.locktime)
    })
  })

  describe('toBuffer/toHex', function () {
    fixtures.valid.forEach(function (f) {
      it('exports ' + f.description + ' (' + f.id + ')', function () {
        if (f.whex) {
          var wactual = fromRaw(f.raw)
          assert.strictEqual(wactual.toHex(), f.whex)
        }

        var actual = fromRaw(f.raw, true)
        assert.strictEqual(actual.toHex(), f.hex)
      })
    })

    it('accepts target Buffer and offset parameters', function () {
      var f = fixtures.valid[0]
      var actual = fromRaw(f.raw)
      var byteLength = actual.byteLength()

      var target = new Buffer(byteLength * 2)
      var a = actual.toBuffer(target, 0)
      var b = actual.toBuffer(target, byteLength)

      assert.strictEqual(a.length, byteLength)
      assert.strictEqual(b.length, byteLength)
      assert.strictEqual(a.toString('hex'), f.hex)
      assert.strictEqual(b.toString('hex'), f.hex)
      assert.deepEqual(a, b)
      assert.deepEqual(a, target.slice(0, byteLength))
      assert.deepEqual(b, target.slice(byteLength))
    })
  })

  describe('hasWitnesses', function () {
    fixtures.valid.forEach(function (f) {
      it('detects if the transaction has witnesses: ' + (f.whex ? 'true' : 'false'), function () {
        assert.strictEqual(Transaction.fromHex(f.whex ? f.whex : f.hex).hasWitnesses(), !!f.whex)
      })
    })
  })

  describe('addInput', function () {
    var prevTxHash
    beforeEach(function () {
      prevTxHash = new Buffer('ffffffff00ffff000000000000000000000000000000000000000000101010ff', 'hex')
    })

    it('returns an index', function () {
      var tx = new Transaction()
      assert.strictEqual(tx.addInput(prevTxHash, 0), 0)
      assert.strictEqual(tx.addInput(prevTxHash, 0), 1)
    })

    it('defaults to empty script, witness and 0xffffffff SEQUENCE number', function () {
      var tx = new Transaction()
      tx.addInput(prevTxHash, 0)

      assert.strictEqual(tx.ins[0].script.length, 0)
      assert.strictEqual(tx.ins[0].witness.length, 0)
      assert.strictEqual(tx.ins[0].sequence, 0xffffffff)
    })

    fixtures.invalid.addInput.forEach(function (f) {
      it('throws on ' + f.exception, function () {
        var tx = new Transaction()
        var hash = new Buffer(f.hash, 'hex')

        assert.throws(function () {
          tx.addInput(hash, f.index)
        }, new RegExp(f.exception))
      })
    })
  })

  describe('addOutput', function () {
    it('returns an index', function () {
      var tx = new Transaction()
      assert.strictEqual(tx.addOutput(new Buffer(0), 0), 0)
      assert.strictEqual(tx.addOutput(new Buffer(0), 0), 1)
    })
  })

  describe('clone', function () {
    fixtures.valid.forEach(function (f) {
      var actual, expected

      beforeEach(function () {
        expected = Transaction.fromHex(f.hex)
        actual = expected.clone()
      })

      it('should have value equality', function () {
        assert.deepEqual(actual, expected)
      })

      it('should not have reference equality', function () {
        assert.notEqual(actual, expected)
      })
    })
  })

  describe('getHash/getId', function () {
    function verify (f) {
      it('should return the id for ' + f.id, function () {
        var tx = Transaction.fromHex(f.whex || f.hex)

        assert.strictEqual(tx.getHash().toString('hex'), f.hash)
        assert.strictEqual(tx.getId(), f.id)
      })
    }

    fixtures.valid.forEach(verify)
  })

  describe('isCoinbase', function () {
    function verify (f) {
      it('should return ' + f.coinbase + ' for ' + f.id, function () {
        var tx = Transaction.fromHex(f.hex)

        assert.strictEqual(tx.isCoinbase(), f.coinbase)
      })
    }

    fixtures.valid.forEach(verify)
  })

  describe('hashForSignature', function () {
    it('does not use Witness serialization', function () {
      var randScript = new Buffer('6a', 'hex')

      var tx = new Transaction()
      tx.addInput(new Buffer('0000000000000000000000000000000000000000000000000000000000000000', 'hex'), 0)
      tx.addOutput(randScript, 5000000000)

      var original = tx.__toBuffer
      tx.__toBuffer = function (a, b, c) {
        if (c !== false) throw new Error('hashForSignature MUST pass false')

        return original.call(this, a, b, c)
      }

      assert.throws(function () {
        tx.__toBuffer(undefined, undefined, true)
      }, /hashForSignature MUST pass false/)

      // assert hashForSignature does not pass false
      assert.doesNotThrow(function () {
        tx.hashForSignature(0, randScript, 1)
      })
    })

    fixtures.hashForSignature.forEach(function (f) {
      it('should return ' + f.hash + ' for ' + (f.description ? ('case "' + f.description + '"') : f.script), function () {
        var tx = Transaction.fromHex(f.txHex)
        var script = bscript.fromASM(f.script)

        assert.strictEqual(tx.hashForSignature(f.inIndex, script, f.type).toString('hex'), f.hash)
      })
    })
  })

  describe('hashForWitnessV0', function () {
    fixtures.hashForWitnessV0.forEach(function (f) {
      it('should return ' + f.hash + ' for ' + (f.description ? ('case "' + f.description + '"') : ''), function () {
        var tx = Transaction.fromHex(f.txHex)
        var script = bscript.fromASM(f.script)

        assert.strictEqual(tx.hashForWitnessV0(f.inIndex, script, f.value, f.type).toString('hex'), f.hash)
      })
    })
  })

  describe('setWitness', function () {
    it('only accepts a a witness stack (Array of Buffers)', function () {
      assert.throws(function () {
        (new Transaction()).setWitness(0, 'foobar')
      }, /Expected property "1" of type \[Buffer], got String "foobar"/)
    })
  })
})
<|endoftext|>


<commit_before>import User from 'flarum/models/User';
import username from 'flarum/helpers/username';
import extractText from 'flarum/utils/extractText';
import extract from 'flarum/utils/extract';

/**
 * Translator with the same API as Symfony's.
 *
 * Derived from https://github.com/willdurand/BazingaJsTranslationBundle
 * which is available under the MIT License.
 * Copyright (c) William Durand <william.durand1@gmail.com>
 */
export default class Translator {
  constructor() {
    /**
     * A map of translation keys to their translated values.
     *
     * @type {Object}
     * @public
     */
    this.translations = {};

    this.locale = null;
  }

  trans(id, parameters) {
    const translation = this.translations[id];

    if (translation) {
      return this.apply(translation, parameters || {});
    }

    return id;
  }

  transChoice(id, number, parameters) {
    let translation = this.translations[id];

    if (translation) {
      number = parseInt(number, 10);

      translation = this.pluralize(translation, number);

      return this.apply(translation, parameters || {});
    }

    return id;
  }

  apply(translation, input) {
    // If we've been given a user model as one of the input parameters, then
    // we'll extract the username and use that for the translation. In the
    // future there should be a hook here to inspect the user and change the
    // translation key. This will allow a gender property to determine which
    // translation key is used.
    if ('user' in input) {
      const user = extract(input, 'user');

      if (!input.username) input.username = username(user);
    }

    translation = translation.split(new RegExp('({[a-z0-9_]+}|</?[a-z0-9_]+>)', 'gi'));

    const hydrated = [];
    const open = [hydrated];

    translation.forEach(part => {
      const match = part.match(new RegExp('{([a-z0-9_]+)}|<(/?)([a-z0-9_]+)>', 'i'));

      if (match) {
        if (match[1]) {
          open[0].push(input[match[1]]);
        } else if (match[3]) {
          if (match[2]) {
            open.shift();
          } else {
            let tag = input[match[3]] || {tag: match[3], children: []};
            open[0].push(tag);
            open.unshift(tag.children || tag);
          }
        }
      } else {
        open[0].push(part);
      }
    });

    return hydrated.filter(part => part);
  }

  pluralize(translation, number) {
    const sPluralRegex = new RegExp(/^\w+\: +(.+)$/),
      cPluralRegex = new RegExp(/^\s*((\{\s*(\-?\d+[\s*,\s*\-?\d+]*)\s*\})|([\[\]])\s*(-Inf|\-?\d+)\s*,\s*(\+?Inf|\-?\d+)\s*([\[\]]))\s?(.+?)$/),
      iPluralRegex = new RegExp(/^\s*(\{\s*(\-?\d+[\s*,\s*\-?\d+]*)\s*\})|([\[\]])\s*(-Inf|\-?\d+)\s*,\s*(\+?Inf|\-?\d+)\s*([\[\]])/),
      standardRules = [],
      explicitRules = [];

    translation.split('|').forEach(part => {
      if (cPluralRegex.test(part)) {
        const matches = part.match(cPluralRegex);
        explicitRules[matches[0]] = matches[matches.length - 1];
      } else if (sPluralRegex.test(part)) {
        const matches = part.match(sPluralRegex);
        standardRules.push(matches[1]);
      } else {
        standardRules.push(part);
      }
    });

    explicitRules.forEach((rule, e) => {
      if (iPluralRegex.test(e)) {
        const matches = e.match(iPluralRegex);

        if (matches[1]) {
          const ns = matches[2].split(',');

          for (let n in ns) {
            if (number == ns[n]) {
              return explicitRules[e];
            }
          }
        } else {
          var leftNumber  = this.convertNumber(matches[4]);
          var rightNumber = this.convertNumber(matches[5]);

          if (('[' === matches[3] ? number >= leftNumber : number > leftNumber) &&
            (']' === matches[6] ? number <= rightNumber : number < rightNumber)) {
            return explicitRules[e];
          }
        }
      }
    });

    return standardRules[this.pluralPosition(number, this.locale)] || standardRules[0] || undefined;
  }

  convertNumber(number) {
    if ('-Inf' === number) {
      return Number.NEGATIVE_INFINITY;
    } else if ('+Inf' === number || 'Inf' === number) {
      return Number.POSITIVE_INFINITY;
    }

    return parseInt(number, 10);
  }

  pluralPosition(number, locale) {
    if ('pt_BR' === locale) {
      locale = 'xbr';
    }

    if (locale.length > 3) {
      locale = locale.split('_')[0];
    }

    switch (locale) {
      case 'bo':
      case 'dz':
      case 'id':
      case 'ja':
      case 'jv':
      case 'ka':
      case 'km':
      case 'kn':
      case 'ko':
      case 'ms':
      case 'th':
      case 'vi':
      case 'zh':
        return 0;
      case 'af':
      case 'az':
      case 'bn':
      case 'bg':
      case 'ca':
      case 'da':
      case 'de':
      case 'el':
      case 'en':
      case 'eo':
      case 'es':
      case 'et':
      case 'eu':
      case 'fa':
      case 'fi':
      case 'fo':
      case 'fur':
      case 'fy':
      case 'gl':
      case 'gu':
      case 'ha':
      case 'he':
      case 'hu':
      case 'is':
      case 'it':
      case 'ku':
      case 'lb':
      case 'ml':
      case 'mn':
      case 'mr':
      case 'nah':
      case 'nb':
      case 'ne':
      case 'nl':
      case 'nn':
      case 'no':
      case 'om':
      case 'or':
      case 'pa':
      case 'pap':
      case 'ps':
      case 'pt':
      case 'so':
      case 'sq':
      case 'sv':
      case 'sw':
      case 'ta':
      case 'te':
      case 'tk':
      case 'tr':
      case 'ur':
      case 'zu':
        return (number == 1) ? 0 : 1;

      case 'am':
      case 'bh':
      case 'fil':
      case 'fr':
      case 'gun':
      case 'hi':
      case 'ln':
      case 'mg':
      case 'nso':
      case 'xbr':
      case 'ti':
      case 'wa':
        return ((number === 0) || (number == 1)) ? 0 : 1;

      case 'be':
      case 'bs':
      case 'hr':
      case 'ru':
      case 'sr':
      case 'uk':
        return ((number % 10 == 1) && (number % 100 != 11)) ? 0 : (((number % 10 >= 2) && (number % 10 <= 4) && ((number % 100 < 10) || (number % 100 >= 20))) ? 1 : 2);

      case 'cs':
      case 'sk':
        return (number == 1) ? 0 : (((number >= 2) && (number <= 4)) ? 1 : 2);

      case 'ga':
        return (number == 1) ? 0 : ((number == 2) ? 1 : 2);

      case 'lt':
        return ((number % 10 == 1) && (number % 100 != 11)) ? 0 : (((number % 10 >= 2) && ((number % 100 < 10) || (number % 100 >= 20))) ? 1 : 2);

      case 'sl':
        return (number % 100 == 1) ? 0 : ((number % 100 == 2) ? 1 : (((number % 100 == 3) || (number % 100 == 4)) ? 2 : 3));

      case 'mk':
        return (number % 10 == 1) ? 0 : 1;

      case 'mt':
        return (number == 1) ? 0 : (((number === 0) || ((number % 100 > 1) && (number % 100 < 11))) ? 1 : (((number % 100 > 10) && (number % 100 < 20)) ? 2 : 3));

      case 'lv':
        return (number === 0) ? 0 : (((number % 10 == 1) && (number % 100 != 11)) ? 1 : 2);

      case 'pl':
        return (number == 1) ? 0 : (((number % 10 >= 2) && (number % 10 <= 4) && ((number % 100 < 12) || (number % 100 > 14))) ? 1 : 2);

      case 'cy':
        return (number == 1) ? 0 : ((number == 2) ? 1 : (((number == 8) || (number == 11)) ? 2 : 3));

      case 'ro':
        return (number == 1) ? 0 : (((number === 0) || ((number % 100 > 0) && (number % 100 < 20))) ? 1 : 2);

      case 'ar':
        return (number === 0) ? 0 : ((number == 1) ? 1 : ((number == 2) ? 2 : (((number >= 3) && (number <= 10)) ? 3 : (((number >= 11) && (number <= 99)) ? 4 : 5))));

      default:
        return 0;
    }
  }
}
<commit_msg>Add newline to locale switch (#974)<commit_after>import User from 'flarum/models/User';
import username from 'flarum/helpers/username';
import extractText from 'flarum/utils/extractText';
import extract from 'flarum/utils/extract';

/**
 * Translator with the same API as Symfony's.
 *
 * Derived from https://github.com/willdurand/BazingaJsTranslationBundle
 * which is available under the MIT License.
 * Copyright (c) William Durand <william.durand1@gmail.com>
 */
export default class Translator {
  constructor() {
    /**
     * A map of translation keys to their translated values.
     *
     * @type {Object}
     * @public
     */
    this.translations = {};

    this.locale = null;
  }

  trans(id, parameters) {
    const translation = this.translations[id];

    if (translation) {
      return this.apply(translation, parameters || {});
    }

    return id;
  }

  transChoice(id, number, parameters) {
    let translation = this.translations[id];

    if (translation) {
      number = parseInt(number, 10);

      translation = this.pluralize(translation, number);

      return this.apply(translation, parameters || {});
    }

    return id;
  }

  apply(translation, input) {
    // If we've been given a user model as one of the input parameters, then
    // we'll extract the username and use that for the translation. In the
    // future there should be a hook here to inspect the user and change the
    // translation key. This will allow a gender property to determine which
    // translation key is used.
    if ('user' in input) {
      const user = extract(input, 'user');

      if (!input.username) input.username = username(user);
    }

    translation = translation.split(new RegExp('({[a-z0-9_]+}|</?[a-z0-9_]+>)', 'gi'));

    const hydrated = [];
    const open = [hydrated];

    translation.forEach(part => {
      const match = part.match(new RegExp('{([a-z0-9_]+)}|<(/?)([a-z0-9_]+)>', 'i'));

      if (match) {
        if (match[1]) {
          open[0].push(input[match[1]]);
        } else if (match[3]) {
          if (match[2]) {
            open.shift();
          } else {
            let tag = input[match[3]] || {tag: match[3], children: []};
            open[0].push(tag);
            open.unshift(tag.children || tag);
          }
        }
      } else {
        open[0].push(part);
      }
    });

    return hydrated.filter(part => part);
  }

  pluralize(translation, number) {
    const sPluralRegex = new RegExp(/^\w+\: +(.+)$/),
      cPluralRegex = new RegExp(/^\s*((\{\s*(\-?\d+[\s*,\s*\-?\d+]*)\s*\})|([\[\]])\s*(-Inf|\-?\d+)\s*,\s*(\+?Inf|\-?\d+)\s*([\[\]]))\s?(.+?)$/),
      iPluralRegex = new RegExp(/^\s*(\{\s*(\-?\d+[\s*,\s*\-?\d+]*)\s*\})|([\[\]])\s*(-Inf|\-?\d+)\s*,\s*(\+?Inf|\-?\d+)\s*([\[\]])/),
      standardRules = [],
      explicitRules = [];

    translation.split('|').forEach(part => {
      if (cPluralRegex.test(part)) {
        const matches = part.match(cPluralRegex);
        explicitRules[matches[0]] = matches[matches.length - 1];
      } else if (sPluralRegex.test(part)) {
        const matches = part.match(sPluralRegex);
        standardRules.push(matches[1]);
      } else {
        standardRules.push(part);
      }
    });

    explicitRules.forEach((rule, e) => {
      if (iPluralRegex.test(e)) {
        const matches = e.match(iPluralRegex);

        if (matches[1]) {
          const ns = matches[2].split(',');

          for (let n in ns) {
            if (number == ns[n]) {
              return explicitRules[e];
            }
          }
        } else {
          var leftNumber  = this.convertNumber(matches[4]);
          var rightNumber = this.convertNumber(matches[5]);

          if (('[' === matches[3] ? number >= leftNumber : number > leftNumber) &&
            (']' === matches[6] ? number <= rightNumber : number < rightNumber)) {
            return explicitRules[e];
          }
        }
      }
    });

    return standardRules[this.pluralPosition(number, this.locale)] || standardRules[0] || undefined;
  }

  convertNumber(number) {
    if ('-Inf' === number) {
      return Number.NEGATIVE_INFINITY;
    } else if ('+Inf' === number || 'Inf' === number) {
      return Number.POSITIVE_INFINITY;
    }

    return parseInt(number, 10);
  }

  pluralPosition(number, locale) {
    if ('pt_BR' === locale) {
      locale = 'xbr';
    }

    if (locale.length > 3) {
      locale = locale.split('_')[0];
    }

    switch (locale) {
      case 'bo':
      case 'dz':
      case 'id':
      case 'ja':
      case 'jv':
      case 'ka':
      case 'km':
      case 'kn':
      case 'ko':
      case 'ms':
      case 'th':
      case 'vi':
      case 'zh':
        return 0;

      case 'af':
      case 'az':
      case 'bn':
      case 'bg':
      case 'ca':
      case 'da':
      case 'de':
      case 'el':
      case 'en':
      case 'eo':
      case 'es':
      case 'et':
      case 'eu':
      case 'fa':
      case 'fi':
      case 'fo':
      case 'fur':
      case 'fy':
      case 'gl':
      case 'gu':
      case 'ha':
      case 'he':
      case 'hu':
      case 'is':
      case 'it':
      case 'ku':
      case 'lb':
      case 'ml':
      case 'mn':
      case 'mr':
      case 'nah':
      case 'nb':
      case 'ne':
      case 'nl':
      case 'nn':
      case 'no':
      case 'om':
      case 'or':
      case 'pa':
      case 'pap':
      case 'ps':
      case 'pt':
      case 'so':
      case 'sq':
      case 'sv':
      case 'sw':
      case 'ta':
      case 'te':
      case 'tk':
      case 'tr':
      case 'ur':
      case 'zu':
        return (number == 1) ? 0 : 1;

      case 'am':
      case 'bh':
      case 'fil':
      case 'fr':
      case 'gun':
      case 'hi':
      case 'ln':
      case 'mg':
      case 'nso':
      case 'xbr':
      case 'ti':
      case 'wa':
        return ((number === 0) || (number == 1)) ? 0 : 1;

      case 'be':
      case 'bs':
      case 'hr':
      case 'ru':
      case 'sr':
      case 'uk':
        return ((number % 10 == 1) && (number % 100 != 11)) ? 0 : (((number % 10 >= 2) && (number % 10 <= 4) && ((number % 100 < 10) || (number % 100 >= 20))) ? 1 : 2);

      case 'cs':
      case 'sk':
        return (number == 1) ? 0 : (((number >= 2) && (number <= 4)) ? 1 : 2);

      case 'ga':
        return (number == 1) ? 0 : ((number == 2) ? 1 : 2);

      case 'lt':
        return ((number % 10 == 1) && (number % 100 != 11)) ? 0 : (((number % 10 >= 2) && ((number % 100 < 10) || (number % 100 >= 20))) ? 1 : 2);

      case 'sl':
        return (number % 100 == 1) ? 0 : ((number % 100 == 2) ? 1 : (((number % 100 == 3) || (number % 100 == 4)) ? 2 : 3));

      case 'mk':
        return (number % 10 == 1) ? 0 : 1;

      case 'mt':
        return (number == 1) ? 0 : (((number === 0) || ((number % 100 > 1) && (number % 100 < 11))) ? 1 : (((number % 100 > 10) && (number % 100 < 20)) ? 2 : 3));

      case 'lv':
        return (number === 0) ? 0 : (((number % 10 == 1) && (number % 100 != 11)) ? 1 : 2);

      case 'pl':
        return (number == 1) ? 0 : (((number % 10 >= 2) && (number % 10 <= 4) && ((number % 100 < 12) || (number % 100 > 14))) ? 1 : 2);

      case 'cy':
        return (number == 1) ? 0 : ((number == 2) ? 1 : (((number == 8) || (number == 11)) ? 2 : 3));

      case 'ro':
        return (number == 1) ? 0 : (((number === 0) || ((number % 100 > 0) && (number % 100 < 20))) ? 1 : 2);

      case 'ar':
        return (number === 0) ? 0 : ((number == 1) ? 1 : ((number == 2) ? 2 : (((number >= 3) && (number <= 10)) ? 3 : (((number >= 11) && (number <= 99)) ? 4 : 5))));

      default:
        return 0;
    }
  }
}
<|endoftext|>


<commit_before>// Load modules

var Lab = require('lab');
var Joi = require('../../lib');
var Support = require('../support/meta');

// Declare internals

var internals = {};

// Test shortcuts

var expect = Lab.expect;
var before = Lab.before;
var after = Lab.after;
var describe = Lab.experiment;
var it = Lab.test;
var verifyBehavior = Support.verifyValidatorBehavior;

describe('Types', function () {

    describe('Array', function () {

        var A = Joi.types.Array,
            N = Joi.types.Number,
            S = Joi.types.String
            O = Joi.types.Object;

        it('should have mixins', function (done) {

            var result = A();
            expect(result.validate).to.exist;
            done();
        });

        describe('#convert', function () {

            it('should convert a string to an array', function (done) {

                var result = A().convert('[1,2,3]');
                expect(result.length).to.equal(3);
                done();
            });

            it('should convert a non-array string to an array', function (done) {

                var result = A().convert('{ "something": false }');
                expect(result.length).to.equal(1);
                done();
            });

            it('should return a non array', function (done) {

                var result = A().convert(3);
                expect(result).to.equal(3);
                done();
            });

            it('should convert a non-array string with number type', function (done) {

                var result = A().convert('3');
                expect(result.length).to.equal(1);
                expect(result[0]).to.equal('3');
                done();
            });

            it('should convert a non-array string', function(done) {

                var result = A().convert('asdf');
                expect(result).to.equal('asdf');
                done();
            });
        });

        describe('#validate', function () {

            it('should work', function (done) {

                expect(function () {

                    var arr = A();
                    var result = arr.validate([1]);
                }).to.not.throw();
                done();
            });

            it('should, by default, allow undefined, allow empty array', function (done) {

                verifyBehavior(A(), [
                    [undefined, true],
                    [
                        [],
                        true
                    ]
                ], done);
            });

            it('should, when .required(), deny undefined', function (done) {

                verifyBehavior(A().required(), [
                    [undefined, false]
                ], done);
            });

            it('should allow empty arrays with emptyOk', function (done) {

                verifyBehavior(A().emptyOk(), [
                    [undefined, true],
                    [[], true]
                ], done);
            });

            it('should exclude values when excludes is called', function (done) {

                verifyBehavior(A().excludes(S()), [
                    [['2', '1'], false],
                    [['1'], false],
                    [[2], true]
                ], done);
            });

            it('should allow types to be excluded', function (done) {

                var validator = A().excludes(N());

                var n = [1, 2, 'hippo'];
                var result = validator.validate(n);

                expect(result).to.equal(false);

                var m = ['x', 'y', 'z'];
                var result2 = validator.validate(m);

                expect(result2).to.equal(true);
                done();
            });

            it('should validate array of Numbers', function (done) {

                verifyBehavior(A().includes(N()), [
                    [
                        [1, 2, 3],
                        true
                    ],
                    [
                        [50, 100, 1000],
                        true
                    ],
                    [
                        ['a', 1, 2],
                        false
                    ]
                ], done);
            });

            it('should validate array of mixed Numbers & Strings', function (done) {

                verifyBehavior(A().includes(N(), S()), [
                    [
                        [1, 2, 3],
                        true
                    ],
                    [
                        [50, 100, 1000],
                        true
                    ],
                    [
                        [1, 'a', 5, 10],
                        true
                    ],
                    [
                        ['walmart', 'everydaylowprices', 5000],
                        true
                    ]
                ], done);
            });

            it('should validate array of objects with schema', function (done) {

                verifyBehavior(A().includes(O({ h1: N().required()})), [
                    [
                        [{ h1: 1 }, { h1: 2 }, { h1: 3 }],
                        true
                    ],
                    [
                        [{ h2: 1, h3: 'somestring' }, { h1: 2 }, { h1: 3 }],
                        false
                    ],
                    [
                        [1, 2, [1]],
                        false
                    ]
                ], done);
            });

            it('should not validate array of unallowed mixed types (Array)', function (done) {

                verifyBehavior(A().includes(N()), [
                    [
                        [1, 2, 3],
                        true
                    ],
                    [
                        [1, 2, [1]],
                        false
                    ]
                ], done);
            });

            it('should not throw when using includes', function (done) {

                var schema = {
                    arr: Joi.types.Array().includes(Joi.types.Number().integer())
                };

                var input = { arr: [1, 2, 2.1] };
                var err = Joi.validate(input, schema);

                expect(err).to.exist;
                done();
            });
        });
    });
});
<commit_msg>Fixing global variable leak in test<commit_after>// Load modules

var Lab = require('lab');
var Joi = require('../../lib');
var Support = require('../support/meta');

// Declare internals

var internals = {};

// Test shortcuts

var expect = Lab.expect;
var before = Lab.before;
var after = Lab.after;
var describe = Lab.experiment;
var it = Lab.test;
var verifyBehavior = Support.verifyValidatorBehavior;

describe('Types', function () {

    describe('Array', function () {

        var A = Joi.types.Array,
            N = Joi.types.Number,
            S = Joi.types.String,
            O = Joi.types.Object;

        it('should have mixins', function (done) {

            var result = A();
            expect(result.validate).to.exist;
            done();
        });

        describe('#convert', function () {

            it('should convert a string to an array', function (done) {

                var result = A().convert('[1,2,3]');
                expect(result.length).to.equal(3);
                done();
            });

            it('should convert a non-array string to an array', function (done) {

                var result = A().convert('{ "something": false }');
                expect(result.length).to.equal(1);
                done();
            });

            it('should return a non array', function (done) {

                var result = A().convert(3);
                expect(result).to.equal(3);
                done();
            });

            it('should convert a non-array string with number type', function (done) {

                var result = A().convert('3');
                expect(result.length).to.equal(1);
                expect(result[0]).to.equal('3');
                done();
            });

            it('should convert a non-array string', function(done) {

                var result = A().convert('asdf');
                expect(result).to.equal('asdf');
                done();
            });
        });

        describe('#validate', function () {

            it('should work', function (done) {

                expect(function () {

                    var arr = A();
                    var result = arr.validate([1]);
                }).to.not.throw();
                done();
            });

            it('should, by default, allow undefined, allow empty array', function (done) {

                verifyBehavior(A(), [
                    [undefined, true],
                    [
                        [],
                        true
                    ]
                ], done);
            });

            it('should, when .required(), deny undefined', function (done) {

                verifyBehavior(A().required(), [
                    [undefined, false]
                ], done);
            });

            it('should allow empty arrays with emptyOk', function (done) {

                verifyBehavior(A().emptyOk(), [
                    [undefined, true],
                    [[], true]
                ], done);
            });

            it('should exclude values when excludes is called', function (done) {

                verifyBehavior(A().excludes(S()), [
                    [['2', '1'], false],
                    [['1'], false],
                    [[2], true]
                ], done);
            });

            it('should allow types to be excluded', function (done) {

                var validator = A().excludes(N());

                var n = [1, 2, 'hippo'];
                var result = validator.validate(n);

                expect(result).to.equal(false);

                var m = ['x', 'y', 'z'];
                var result2 = validator.validate(m);

                expect(result2).to.equal(true);
                done();
            });

            it('should validate array of Numbers', function (done) {

                verifyBehavior(A().includes(N()), [
                    [
                        [1, 2, 3],
                        true
                    ],
                    [
                        [50, 100, 1000],
                        true
                    ],
                    [
                        ['a', 1, 2],
                        false
                    ]
                ], done);
            });

            it('should validate array of mixed Numbers & Strings', function (done) {

                verifyBehavior(A().includes(N(), S()), [
                    [
                        [1, 2, 3],
                        true
                    ],
                    [
                        [50, 100, 1000],
                        true
                    ],
                    [
                        [1, 'a', 5, 10],
                        true
                    ],
                    [
                        ['walmart', 'everydaylowprices', 5000],
                        true
                    ]
                ], done);
            });

            it('should validate array of objects with schema', function (done) {

                verifyBehavior(A().includes(O({ h1: N().required()})), [
                    [
                        [{ h1: 1 }, { h1: 2 }, { h1: 3 }],
                        true
                    ],
                    [
                        [{ h2: 1, h3: 'somestring' }, { h1: 2 }, { h1: 3 }],
                        false
                    ],
                    [
                        [1, 2, [1]],
                        false
                    ]
                ], done);
            });

            it('should not validate array of unallowed mixed types (Array)', function (done) {

                verifyBehavior(A().includes(N()), [
                    [
                        [1, 2, 3],
                        true
                    ],
                    [
                        [1, 2, [1]],
                        false
                    ]
                ], done);
            });

            it('should not throw when using includes', function (done) {

                var schema = {
                    arr: Joi.types.Array().includes(Joi.types.Number().integer())
                };

                var input = { arr: [1, 2, 2.1] };
                var err = Joi.validate(input, schema);

                expect(err).to.exist;
                done();
            });
        });
    });
});
<|endoftext|>


<commit_before>/** @license
 *
 * Mindspace: WebGL Content Management System (CMS)
 * ----------------------------------------------
 * https://github.com/drahmel/mindspace
 *
 * Copyright (c) 2013, Dan Rahmel. All rights reserved.
 * Code provided under the MIT License:
 * https://github.com/drahmel/mindspace/blob/master/LICENSE-MIT
 *
 */

var objDom = {};
var collisionObjects = [];
var canvas;
var engine;
var scene;
var camera;
var version = 0.1;

function init(canvasId) {
	canvas = document.getElementById(canvasId);

	// Load BABYLON 3D engine and set the root directory
	engine = new BABYLON.Engine(canvas, true);

	// Create a new scene with a camera (mandatory), a light (better) and a sphere (to see the origin)
	scene = new BABYLON.Scene(engine);

	// Creating a camera looking to the zero point (0,0,0)
	if(false) {
		camera = new BABYLON.ArcRotateCamera("Camera", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene);
		camera.setPosition(new BABYLON.Vector3(-40, 40, 0));
	} else {
		camera = new BABYLON.FreeCamera("Camera", new BABYLON.Vector3(-20, 0, -60), scene);
	}
	// Creating a omnidirectional light
	//var light0 = new BABYLON.PointLight("Omni", new BABYLON.Vector3(0, 0, 10), scene);
	var sun = new BABYLON.PointLight("Omni0", new BABYLON.Vector3(60, 100, 10), scene);

	window.addEventListener("resize", function () {
		engine.resize();
	});

}

function addParams(obj, params) {
	if(params['xyz']!=undefined) {
		obj.position = new BABYLON.Vector3(params['xyz'][0], params['xyz'][1], params['xyz'][2]);
	}
	if(params['color']!=undefined) {
		var matName = params['name']+"_mat";
		var matObj = new BABYLON.StandardMaterial(matName, scene);
		matObj.diffuseColor = new BABYLON.Color3(params['color'][0], params['color'][1], params['color'][2]);
		if(params['alpha']!=undefined) {
			matObj.alpha = params['alpha'];
		}
		if(params['texture'] != undefined) {
			matObj.diffuseTexture = new BABYLON.Texture(params['texture'], scene);
			matObj.emissiveTexture = new BABYLON.Texture(params['texture'], scene);
			// new BABYLON.Texture(params['texture'], scene);
			if(params['texture_alpha'] != undefined) {
				matObj.diffuseTexture.hasAlpha = true;
			}
		}

		obj.material = matObj;
		objDom[matName] = matObj;
	}
	if(params['rotate']!=undefined) {
		obj.rotation.x = Math.PI/4;
	}
	if(params['lightcolor']!=undefined) {
		obj.diffuse = new BABYLON.Color3(1, 0, 0);
		obj.specular = new BABYLON.Color3(1, 0, 0);
	}
	if(params['scalex'] != undefined) {
		obj.scaling.x = params['scalex'];
	}
	if(params['scaley'] != undefined) {
		obj.scaling.y = params['scaley'];
	}
	if(params['scalez'] != undefined) {
		obj.scaling.z = params['scalez'];
	}
	if(params['collision'] != undefined) {
		obj.checkCollisions = true;
		collisionObjects.push(obj);
	}

}

function addSphere(params) {
	var segments = (params['segments'] != undefined) ? params['segments'] : 10;
	var width = (params['width'] != undefined) ? params['width'] : 1;
	var obj = BABYLON.Mesh.CreateSphere(params['name'], segments, width, scene);
	var materialSphere2 = new BABYLON.StandardMaterial("texture1", scene);
	addParams(obj, params);
	objDom[name] = obj;
	return obj;
}

function addBox(params) {
	var width = (params['width'] != undefined) ? params['width'] : 1;
	var obj = BABYLON.Mesh.CreateBox(params['name'], width, scene);
	addParams(obj, params);
	objDom[name] = obj;
	return obj;
}
function addPicture(params) {
	var width = (params['width'] != undefined) ? params['width'] : 1;
	params['scalez'] = .01;
	//params['scalez'] = .1;

	var obj = BABYLON.Mesh.CreateBox(params['name'], width, scene);
	addParams(obj, params);
	objDom[name] = obj;
	return obj;
}

function addCylinder(params) {
	var segments = (params['segments'] != undefined) ? params['segments'] : 20;
	var width = (params['width'] != undefined) ? params['width'] : 1;
	var widthTop = (params['widthtop'] != undefined) ? params['widthtop'] : 0;
	var widthBottom = (params['widthbottom'] != undefined) ? params['widthbottom'] : 0;
	if(widthTop == 0 && widthBottom == 0) {
		widthTop = width;
		widthBottom = width;
	}
	var obj = BABYLON.Mesh.CreateCylinder(params['name'], widthTop, widthBottom, segments, scene, false);
	addParams(obj, params);
	objDom[name] = obj;
	return obj;
}
function addDonut(params) {
	var segments = (params['segments'] != undefined) ? params['segments'] : 20;
	var width = (params['width'] != undefined) ? params['width'] : 5;
	var thickness = (params['thickness'] != undefined) ? params['thickness'] : 1;
	var obj = BABYLON.Mesh.CreateTorus(params['name'], width, thickness, segments, scene, false);
	addParams(obj, params);
	objDom[name] = obj;
	return obj;
}
function addPointLight(params) {
	var lightx = 1;
	var lighty = 5;
	var lightz = 1;
	if(params['lightxyz']!=undefined) {
		lightx = params['lightxyz'][0];
		lighty = params['lightxyz'][1];
		lightz = params['lightxyz'][2];
	}
	var obj = new BABYLON.PointLight(name, new BABYLON.Vector3(lightx, lighty, lightz), scene);
	addParams(obj, params);
	objDom[name] = obj;
	return obj;
}

function addFog() {
	scene.fogMode = BABYLON.Scene.FOGMODE_EXP;
	//BABYLON.Scene.FOGMODE_NONE;
	//BABYLON.Scene.FOGMODE_EXP;
	//BABYLON.Scene.FOGMODE_EXP2;
	//BABYLON.Scene.FOGMODE_LINEAR;

	scene.fogColor = new BABYLON.Color3(0.9, 0.9, 0.85);
	scene.fogDensity = 0.01;

	//Only if LINEAR
	//scene.fogStart = 20.0;
	//scene.fogEnd = 60.0;
	var alpha = 0;
	if(false) {
		scene.registerBeforeRender(function () {
			scene.fogDensity = Math.cos(alpha)/10;
			alpha+=0.02;
		});
	}
}

function addSkybox() {
	// Skybox
	var skybox = BABYLON.Mesh.CreateBox("skyBox", 1000.0, scene);
	var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", scene);
	skyboxMaterial.backFaceCulling = false;
	skyboxMaterial.reflectionTexture = new BABYLON.CubeTexture("/images/mindspace/skybox/skybox", scene);
	skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
	skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
	skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
	skybox.material = skyboxMaterial;
	if(false) {
		var skybox = BABYLON.Mesh.CreateBox("skyBox", 100.0, scene);
		var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", scene);
		skyboxMaterial.backFaceCulling = false;
		skybox.material = skyboxMaterial;
		skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
		skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
		skyboxMaterial.reflectionTexture = new BABYLON.CubeTexture("/images/mindspace/skybox/skybox", scene);
		skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
	}
}

function addCameraRestriction() {
	var beforeRenderFunction = function () {
		// Camera
		if (camera.beta < 0.1)
			camera.beta = 0.1;
		else if (camera.beta > (Math.PI / 2) * 0.9)
			camera.beta = (Math.PI / 2) * 0.9;

		if (camera.radius > 50) {
			camera.radius = 50;
		}

		if (camera.radius < 5) {
			camera.radius = 5;
		}
	};
	scene.registerBeforeRender(beforeRenderFunction);
}
function addGravity() {
    var ground = BABYLON.Mesh.CreatePlane("ground", 20.0, scene);
    ground.material = new BABYLON.StandardMaterial("groundMat", scene);
    ground.material.diffuseColor = new BABYLON.Color3(1,1,1);
    ground.material.backFaceCulling = false;
    ground.position = new BABYLON.Vector3(5, -10, -15);
    ground.rotation = new BABYLON.Vector3(Math.PI / 2, 0, 0);

    	console.log("Adding gravity");
    	scene.gravity = new BABYLON.Vector3(0, -0.1, 0);
	scene.collisionsEnabled = true;
	camera.checkCollisions = true;
	//scene.gravity = new BABYLON.Vector3(0, -9.81, 0);
	//camera.applyGravity = true;
	camera.ellipsoid = new BABYLON.Vector3(1, 1, 1);
}
function addCollision() {
    scene.registerBeforeRender(function () {

    		   /*
        //Baloon 1 collision -- Precise = false
        if (balloon1.intersectsMesh(plan1, false)) {
            balloon1.material.emissiveColor = new BABYLON.Color4(1, 0, 0, 1);
        } else {
            balloon1.material.emissiveColor = new BABYLON.Color4(1, 1, 1, 1);
        }

        //Baloon 2 collision -- Precise = true
        if (balloon2.intersectsMesh(plan2, true)) {
            balloon2.material.emissiveColor = new BABYLON.Color4(1, 0, 0, 1);
        } else {
            balloon2.material.emissiveColor = new BABYLON.Color4(1, 1, 1, 1);
        }
*/
        //baloon 3 collision on single point
        var num = collisionObjects.length;
        for(var i=0;i<num;i++) {
		if (collisionObjects[i].intersectsPoint(camera.position)) {
		    collisionObjects[i].material.emissiveColor = new BABYLON.Color4(1, 0, 0, 1);
		    window.location = "/mindspace";
		}
	}
/*
        alpha += 0.01;
        balloon1.position.y += Math.cos(alpha) / 10;
        balloon2.position.y += Math.cos(alpha) / 10;
        balloon3.position.y += Math.cos(alpha) / 10;
        */
    });

}
function addPlane(name) {
	var plane = BABYLON.Mesh.CreatePlane(name, 50.0, scene);
	plane.position = new BABYLON.Vector3(0, 50, 0);
}
<commit_msg>DJR:Portal is working<commit_after>/** @license
 *
 * Mindspace: WebGL Content Management System (CMS)
 * ----------------------------------------------
 * https://github.com/drahmel/mindspace
 *
 * Copyright (c) 2013, Dan Rahmel. All rights reserved.
 * Code provided under the MIT License:
 * https://github.com/drahmel/mindspace/blob/master/LICENSE-MIT
 *
 */

var objDom = {};
var collisionObjects = [];
var canvas;
var engine;
var scene;
var camera;
var version = 0.1;

function init(canvasId) {
	canvas = document.getElementById(canvasId);

	// Load BABYLON 3D engine and set the root directory
	engine = new BABYLON.Engine(canvas, true);

	// Create a new scene with a camera (mandatory), a light (better) and a sphere (to see the origin)
	scene = new BABYLON.Scene(engine);

	// Creating a camera looking to the zero point (0,0,0)
	if(false) {
		camera = new BABYLON.ArcRotateCamera("Camera", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene);
		camera.setPosition(new BABYLON.Vector3(-40, 40, 0));
	} else {
		camera = new BABYLON.FreeCamera("Camera", new BABYLON.Vector3(-20, 0, -60), scene);
	}
	// Creating a omnidirectional light
	//var light0 = new BABYLON.PointLight("Omni", new BABYLON.Vector3(0, 0, 10), scene);
	var sun = new BABYLON.PointLight("Omni0", new BABYLON.Vector3(60, 100, 10), scene);

	window.addEventListener("resize", function () {
		engine.resize();
	});

}

function addParams(obj, params) {
	if(params['xyz']!=undefined) {
		obj.position = new BABYLON.Vector3(params['xyz'][0], params['xyz'][1], params['xyz'][2]);
	}
	if(params['color']!=undefined) {
		var matName = params['name']+"_mat";
		var matObj = new BABYLON.StandardMaterial(matName, scene);
		matObj.diffuseColor = new BABYLON.Color3(params['color'][0], params['color'][1], params['color'][2]);
		if(params['alpha']!=undefined) {
			matObj.alpha = params['alpha'];
		}
		if(params['texture'] != undefined) {
			matObj.diffuseTexture = new BABYLON.Texture(params['texture'], scene);
			matObj.emissiveTexture = new BABYLON.Texture(params['texture'], scene);
			// new BABYLON.Texture(params['texture'], scene);
			if(params['texture_alpha'] != undefined) {
				matObj.diffuseTexture.hasAlpha = true;
			}
		}

		obj.material = matObj;
		objDom[matName] = matObj;
	}
	if(params['rotate']!=undefined) {
		obj.rotation.x = Math.PI/4;
	}
	if(params['lightcolor']!=undefined) {
		obj.diffuse = new BABYLON.Color3(1, 0, 0);
		obj.specular = new BABYLON.Color3(1, 0, 0);
	}
	if(params['scalex'] != undefined) {
		obj.scaling.x = params['scalex'];
	}
	if(params['scaley'] != undefined) {
		obj.scaling.y = params['scaley'];
	}
	if(params['scalez'] != undefined) {
		obj.scaling.z = params['scalez'];
	}
	if(params['collision'] != undefined) {
		obj.checkCollisions = true;
		collisionObjects.push(obj);
	}

}

function addSphere(params) {
	var segments = (params['segments'] != undefined) ? params['segments'] : 10;
	var width = (params['width'] != undefined) ? params['width'] : 1;
	var obj = BABYLON.Mesh.CreateSphere(params['name'], segments, width, scene);
	var materialSphere2 = new BABYLON.StandardMaterial("texture1", scene);
	addParams(obj, params);
	objDom[name] = obj;
	return obj;
}

function addBox(params) {
	var width = (params['width'] != undefined) ? params['width'] : 1;
	var obj = BABYLON.Mesh.CreateBox(params['name'], width, scene);
	addParams(obj, params);
	objDom[name] = obj;
	return obj;
}
function addPicture(params) {
	var width = (params['width'] != undefined) ? params['width'] : 1;
	params['scalez'] = .05;
	//params['scalez'] = .1;

	var obj = BABYLON.Mesh.CreateBox(params['name'], width, scene);
	addParams(obj, params);
	objDom[name] = obj;
	return obj;
}

function addCylinder(params) {
	var segments = (params['segments'] != undefined) ? params['segments'] : 20;
	var width = (params['width'] != undefined) ? params['width'] : 1;
	var widthTop = (params['widthtop'] != undefined) ? params['widthtop'] : 0;
	var widthBottom = (params['widthbottom'] != undefined) ? params['widthbottom'] : 0;
	if(widthTop == 0 && widthBottom == 0) {
		widthTop = width;
		widthBottom = width;
	}
	var obj = BABYLON.Mesh.CreateCylinder(params['name'], widthTop, widthBottom, segments, scene, false);
	addParams(obj, params);
	objDom[name] = obj;
	return obj;
}
function addDonut(params) {
	var segments = (params['segments'] != undefined) ? params['segments'] : 20;
	var width = (params['width'] != undefined) ? params['width'] : 5;
	var thickness = (params['thickness'] != undefined) ? params['thickness'] : 1;
	var obj = BABYLON.Mesh.CreateTorus(params['name'], width, thickness, segments, scene, false);
	addParams(obj, params);
	objDom[name] = obj;
	return obj;
}
function addPointLight(params) {
	var lightx = 1;
	var lighty = 5;
	var lightz = 1;
	if(params['lightxyz']!=undefined) {
		lightx = params['lightxyz'][0];
		lighty = params['lightxyz'][1];
		lightz = params['lightxyz'][2];
	}
	var obj = new BABYLON.PointLight(name, new BABYLON.Vector3(lightx, lighty, lightz), scene);
	addParams(obj, params);
	objDom[name] = obj;
	return obj;
}

function addFog() {
	scene.fogMode = BABYLON.Scene.FOGMODE_EXP;
	//BABYLON.Scene.FOGMODE_NONE;
	//BABYLON.Scene.FOGMODE_EXP;
	//BABYLON.Scene.FOGMODE_EXP2;
	//BABYLON.Scene.FOGMODE_LINEAR;

	scene.fogColor = new BABYLON.Color3(0.9, 0.9, 0.85);
	scene.fogDensity = 0.01;

	//Only if LINEAR
	//scene.fogStart = 20.0;
	//scene.fogEnd = 60.0;
	var alpha = 0;
	if(false) {
		scene.registerBeforeRender(function () {
			scene.fogDensity = Math.cos(alpha)/10;
			alpha+=0.02;
		});
	}
}

function addSkybox() {
	// Skybox
	var skybox = BABYLON.Mesh.CreateBox("skyBox", 1000.0, scene);
	var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", scene);
	skyboxMaterial.backFaceCulling = false;
	skyboxMaterial.reflectionTexture = new BABYLON.CubeTexture("/images/mindspace/skybox/skybox", scene);
	skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
	skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
	skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
	skybox.material = skyboxMaterial;
	if(false) {
		var skybox = BABYLON.Mesh.CreateBox("skyBox", 100.0, scene);
		var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", scene);
		skyboxMaterial.backFaceCulling = false;
		skybox.material = skyboxMaterial;
		skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
		skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
		skyboxMaterial.reflectionTexture = new BABYLON.CubeTexture("/images/mindspace/skybox/skybox", scene);
		skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
	}
}

function addCameraRestriction() {
	var beforeRenderFunction = function () {
		// Camera
		if (camera.beta < 0.1)
			camera.beta = 0.1;
		else if (camera.beta > (Math.PI / 2) * 0.9)
			camera.beta = (Math.PI / 2) * 0.9;

		if (camera.radius > 50) {
			camera.radius = 50;
		}

		if (camera.radius < 5) {
			camera.radius = 5;
		}
	};
	scene.registerBeforeRender(beforeRenderFunction);
}
function addGravity() {
	var ground = BABYLON.Mesh.CreatePlane("ground", 20.0, scene);
	ground.material = new BABYLON.StandardMaterial("groundMat", scene);
	ground.material.diffuseColor = new BABYLON.Color3(1,1,1);
	ground.material.backFaceCulling = false;
	ground.position = new BABYLON.Vector3(5, -10, -15);
	ground.rotation = new BABYLON.Vector3(Math.PI / 2, 0, 0);

    	console.log("Adding gravity");
    	scene.gravity = new BABYLON.Vector3(0, -0.1, 0);
	scene.collisionsEnabled = true;
	//camera.checkCollisions = true;
	//scene.gravity = new BABYLON.Vector3(0, -9.81, 0);
	//camera.applyGravity = true;
	camera.ellipsoid = new BABYLON.Vector3(1, 1, 1);
}
function addCollision() {
    scene.registerBeforeRender(function () {

    		   /*
        //Baloon 1 collision -- Precise = false
        if (balloon1.intersectsMesh(plan1, false)) {
            balloon1.material.emissiveColor = new BABYLON.Color4(1, 0, 0, 1);
        } else {
            balloon1.material.emissiveColor = new BABYLON.Color4(1, 1, 1, 1);
        }

        //Baloon 2 collision -- Precise = true
        if (balloon2.intersectsMesh(plan2, true)) {
            balloon2.material.emissiveColor = new BABYLON.Color4(1, 0, 0, 1);
        } else {
            balloon2.material.emissiveColor = new BABYLON.Color4(1, 1, 1, 1);
        }
*/
        //baloon 3 collision on single point
        var num = collisionObjects.length;
        for(var i=0;i<num;i++) {
		if (collisionObjects[i].intersectsPoint(camera.position)) {
		    collisionObjects[i].material.emissiveColor = new BABYLON.Color4(1, 0, 0, 1);
		    window.location = "/mindspace";
		}
	}
/*
        alpha += 0.01;
        balloon1.position.y += Math.cos(alpha) / 10;
        balloon2.position.y += Math.cos(alpha) / 10;
        balloon3.position.y += Math.cos(alpha) / 10;
        */
    });

}
function addPlane(name) {
	var plane = BABYLON.Mesh.CreatePlane(name, 50.0, scene);
	plane.position = new BABYLON.Vector3(0, 50, 0);
}
<|endoftext|>


<commit_before>import m from 'mithril';
import AppComponent from '../../app/scripts/components/app.js';
import { qs } from './utils.js';

// Minimize the transition duration to speed up tests (interestingly, a
// duration of 0ms will prevent transitionEnd from firing)
export function _before() {
  const style = document.createElement('style');
  style.innerHTML = '* {transition-duration: 200ms !important;}';
  document.head.appendChild(style);
}

export function _beforeEach() {
  document.body.appendChild(document.createElement('main'));
  m.mount(qs('main'), AppComponent);
}

export function _afterEach() {
  m.mount(qs('main'), null);
}
<commit_msg>Zero out AI Player's waitDelay to fix broken test<commit_after>import m from 'mithril';
import AppComponent from '../../app/scripts/components/app.js';
import AIPlayer from '../../app/scripts/models/ai-player.js';
import { qs } from './utils.js';

export function _before() {
  // Minimize the transition duration to speed up tests (interestingly, a
  // duration of 0ms will prevent transitionEnd from firing)
  const style = document.createElement('style');
  style.innerHTML = '* {transition-duration: 200ms !important;}';
  document.head.appendChild(style);
  // Also zero out the AI Player's delay between each swift movement
  AIPlayer.waitDelay = 0;
}

export function _beforeEach() {
  document.body.appendChild(document.createElement('main'));
  m.mount(qs('main'), AppComponent);
}

export function _afterEach() {
  m.mount(qs('main'), null);
}
<|endoftext|>


<commit_before>define(function (require, exports, module) {
    "use strict";
    var invariant = require("modules/invariant");
    var extend = require("extend");
    var eventEmitter = require("modules/events/eventEmitter");
    var serializable = require("modules/serialization/serializable");
    var model = require("mixins/model");
    var urandom = require("modules/urandom/urandom");

    function Profile(factory, app) {
        invariant(factory, "Can be constructed only with factory");
        invariant(app, "Can i haz app?");
        this.factory = factory;
        this._defineEvent("changed");

        this.app = app;
        this.bg = null;
        this.documents = [];
        this.contacts = [];
        this.dialogs = [];
    }

    extend(Profile.prototype, eventEmitter, serializable, model, {
        serialize: function (packet, context) {
            //console.log("serializing Profile");
            packet.setData({
                name: this.name,
                bg: this.bg
            });
            packet.setLink("documents", context.getPacket(this.documents));
            packet.setLink("contacts", context.getPacket(this.contacts));
        },
        deserialize: function (packet, context) {
            //console.log("deserializing Profile");
            var factory = this.factory;
            var data = packet.getData();
            this.name = data.name;
            this.bg = data.bg;
            this.documents = context.deserialize(packet.getLink("documents"), factory.createDocument.bind(factory, this));
            this.contacts = context.deserialize(packet.getLink("contacts"), factory.createContact.bind(factory, this));

        },
        createDocument: function () {
            var document = this.factory.createDocument(this);
            document.set("name", urandom.animal());
            this.documents.push(document);
            this.onChanged();
            return document;
        },
        createContact: function () {
            var contact = this.factory.createContact(this);
            contact.set("name", urandom.name());
            this.contacts.push(contact);
            this.onChanged();
            return contact;
        },

        _findDirectDialog: function (contact) {
            var i;
            for (i = 0; i < this.dialogs.length; i += 1) {
                if (this.dialogs[i].contacts.length === 1 &&  this.dialogs[i].contacts[0] === contact) {
                    return this.dialogs[i];
                }
            }
            return null;
        },

        startDirectDialog: function (contact) {
            var dialog = this._findDirectDialog(contact);
            if (!dialog) {
                dialog = this.factory.createDialog(this);
                dialog.set("name", contact.name);
                dialog.addContact(contact);
                this.dialogs.push(dialog);
                this.onChanged();
            }
            return dialog;
        }
    });

    module.exports = Profile;
});<commit_msg>dialogs serialization<commit_after>define(function (require, exports, module) {
    "use strict";
    var invariant = require("modules/invariant");
    var extend = require("extend");
    var eventEmitter = require("modules/events/eventEmitter");
    var serializable = require("modules/serialization/serializable");
    var model = require("mixins/model");
    var urandom = require("modules/urandom/urandom");

    function Profile(factory, app) {
        invariant(factory, "Can be constructed only with factory");
        invariant(app, "Can i haz app?");
        this.factory = factory;
        this._defineEvent("changed");

        this.app = app;
        this.bg = null;
        this.documents = [];
        this.contacts = [];
        this.dialogs = [];
    }

    extend(Profile.prototype, eventEmitter, serializable, model, {
        serialize: function (packet, context) {
            //console.log("serializing Profile");
            packet.setData({
                name: this.name,
                bg: this.bg
            });
            packet.setLink("documents", context.getPacket(this.documents));
            packet.setLink("contacts", context.getPacket(this.contacts));
            packet.setLink("dialogs", context.getPacket(this.dialogs));
        },
        deserialize: function (packet, context) {
            //console.log("deserializing Profile");
            var factory = this.factory;
            var data = packet.getData();
            this.name = data.name;
            this.bg = data.bg;
            this.documents = context.deserialize(packet.getLink("documents"), factory.createDocument.bind(factory, this));
            this.contacts = context.deserialize(packet.getLink("contacts"), factory.createContact.bind(factory, this));
            this.dialogs = context.deserialize(packet.getLink("dialogs"), factory.createDialog.bind(factory, this));

        },
        createDocument: function () {
            var document = this.factory.createDocument(this);
            document.set("name", urandom.animal());
            this.documents.push(document);
            this.onChanged();
            return document;
        },
        createContact: function () {
            var contact = this.factory.createContact(this);
            contact.set("name", urandom.name());
            this.contacts.push(contact);
            this.onChanged();
            return contact;
        },

        _findDirectDialog: function (contact) {
            var i;
            for (i = 0; i < this.dialogs.length; i += 1) {
                if (this.dialogs[i].contacts.length === 1 &&  this.dialogs[i].contacts[0] === contact) {
                    return this.dialogs[i];
                }
            }
            return null;
        },

        startDirectDialog: function (contact) {
            var dialog = this._findDirectDialog(contact);
            if (!dialog) {
                dialog = this.factory.createDialog(this);
                dialog.set("name", contact.name);
                dialog.addContact(contact);
                this.dialogs.push(dialog);
                this.onChanged();
            }
            return dialog;
        }
    });

    module.exports = Profile;
});<|endoftext|>


<commit_before>
/* medea - an Open Source, WebGL-based 3d engine for next-generation browser games.
 * (or alternatively, for clumsy and mostly useless tech demos written solely for fun)
 *
 * medea is (c) 2011, Alexander C. Gessler
 * licensed under the terms and conditions of a 3 clause BSD license.
 */

medea._addMod('simpleanim',['entity'],function(undefined) {
	"use strict";
	var medea = this;

	var FromToAnimator = medea.Entity.extend(
	{
		init : function(from, to, duration, auto_unadd) {
			this.from = from;
			this.to = to;
			this.duration = duration;
			this.auto_unadd = auto_unadd;
		},

		Render : function(viewport,entity,node,rqmanager) {
			// nothing to be done
		},

		Update : function(dtime,node) {
			if (this.finished) {
				if(this.auto_unadd) {
					node.RemoveEntity(this);
					return medea.ENTITY_UPDATE_WAS_REMOVED;
				}
				return;
			}

			if(this.time === undefined) {
				this.time = 0.0;
			}
			else if(this.time > this.duration) {
				this.finished = true;
				return;
			}

			this.time += dtime;

			var fraction = this.time / this.duration;
			var position = [this.from[0],this.from[1],this.from[2]];

			position[0] += (this.to[0] - this.from[0]) * fraction;
			position[1] += (this.to[1] - this.from[1]) * fraction;
			position[2] += (this.to[2] - this.from[2]) * fraction;

			node.LocalPos(position);
		},

		Finished : function(h) {
			if (h === undefined) {
				return this.finished;
			}
			this.finished = h;
		}
	});

	medea.CreateFromToAnimator = function(from, to, duration, auto_unadd) {
		return new FromToAnimator (from, to, duration, auto_unadd);
	};
});<commit_msg>simpleanim: make sure end position is reached.<commit_after>
/* medea - an Open Source, WebGL-based 3d engine for next-generation browser games.
 * (or alternatively, for clumsy and mostly useless tech demos written solely for fun)
 *
 * medea is (c) 2011, Alexander C. Gessler
 * licensed under the terms and conditions of a 3 clause BSD license.
 */

medea._addMod('simpleanim',['entity'],function(undefined) {
	"use strict";
	var medea = this;

	var FromToAnimator = medea.Entity.extend(
	{
		init : function(from, to, duration, auto_unadd) {
			this.from = from;
			this.to = to;
			this.duration = duration;
			this.auto_unadd = auto_unadd;
		},

		Render : function(viewport,entity,node,rqmanager) {
			// nothing to be done
		},

		Update : function(dtime,node) {
			if (this.finished) {
				if(this.auto_unadd) {
					node.RemoveEntity(this);
					return medea.ENTITY_UPDATE_WAS_REMOVED;
				}
				return;
			}

			if(this.time === undefined) {
				this.time = 0.0;
			}

			this.time += dtime;
			if(this.time > this.duration) {
				// ensure proper end position
				node.LocalPos(this.to);
				this.finished = true;
				return;
			}

			var fraction = this.time / this.duration;
			var position = [this.from[0],this.from[1],this.from[2]];

			position[0] += (this.to[0] - this.from[0]) * fraction;
			position[1] += (this.to[1] - this.from[1]) * fraction;
			position[2] += (this.to[2] - this.from[2]) * fraction;

			node.LocalPos(position);
		},

		Finished : function(h) {
			if (h === undefined) {
				return this.finished;
			}
			this.finished = h;
		}
	});

	medea.CreateFromToAnimator = function(from, to, duration, auto_unadd) {
		return new FromToAnimator (from, to, duration, auto_unadd);
	};
});<|endoftext|>