<commit_before>import 'jsdom-global/register'
import elrUI from 'elr-ui'
import elrAccordion from '../src/main.js'
import $ from 'jquery'

const ui = elrUI()
const accordion = elrAccordion()
const expect = require('chai').expect
const chai = require('chai')
const jsdom = require('mocha-jsdom')

describe('elrAccordion', function() {
    beforeEach(function () {
        document.body.innerHTML = `

First Section

Some Content

Second Section

Some Content

`
    });

    it('should create a button', function() {
        const $container = $('.elr-accordion')
        const $button = accordion.createButton('showButton', 'Show All', 'elr-show-all elr-button elr-button-primary', $container)

        expect($button.hasClass('elr-show-all')).to.be.true
        expect($button.text()).to.equal('Show All')
    });

    it('should add buttons', function() {
        const $container = $('.elr-accordion')

        accordion.addButtons($container)

        expect($('.elr-button').length).to.equal(2)
    });

    it('should show all content', function() {
        const $container = $('.elr-accordion')
        accordion.showAll($('.elr-accordion-label'), $('.elr-accordion-content'))

        expect($('.elr-accordion-content.active').length).to.equal(2)
        expect($('.elr-accordion-label.active').length).to.equal(2)
    })

    it('should hide all content', function() {
        const $container = $('.elr-accordion')
        accordion.hideAll($('.elr-accordion-label'), $('.elr-accordion-content'))

        expect($('.elr-accordion-content.active').length).to.equal(0)
        expect($('.elr-accordion-label.active').length).to.equal(0)
    })

    it('should toggle content', function() {
        const $container = $('.elr-accordion')

        accordion.toggle.call($('.elr-accordion-label').eq(1), $('.elr-accordion-label'), $('.elr-accordion-content'))

        expect($('.elr-accordion-content').first().hasClass('active')).to.be.false
        expect($('.elr-accordion-label').first().hasClass('active')).to.be.false
        expect($('.elr-accordion-content').eq(1).hasClass('active')).to.be.true
        expect($('.elr-accordion-label').eq(1).hasClass('active')).to.be.true

        accordion.toggle.call($('.elr-accordion-label').first(), $('.elr-accordion-content'), $('.elr-accordion-label'))

        expect($('.elr-accordion-content').first().hasClass('active')).to.be.true
        expect($('.elr-accordion-label').first().hasClass('active')).to.be.true
        expect($('.elr-accordion-content').eq(1).hasClass('active')).to.be.false
        expect($('.elr-accordion-label').eq(1).hasClass('active')).to.be.false
    })

    it('should add buttons', function() {
        const accordion = elrAccordion()

        expect($('.elr-show-all').length).to.equal(1)
        expect($('.elr-hide-all').length).to.equal(1)
    })

    it('should not add buttons if showButtons is false', function() {
        const accordion = elrAccordion({showButtons: false})

        expect($('.elr-show-all').length).to.equal(0)
        expect($('.elr-hide-all').length).to.equal(0)
    })

    it('should show all content when show all button is clicked', function() {
        const accordion = elrAccordion()

        $('button.elr-show-all').trigger('click')

        expect($('.elr-accordion-label.active').length).to.equal(2)
        expect($('.elr-accordion-content.active').length).to.equal(2)
    })

    it('should toggle active class when label is clicked', function() {
        const accordion = elrAccordion()

        $('.elr-accordion-label').eq(1).trigger('click')

        expect($('.elr-accordion-label').eq(1).hasClass('active')).to.be.true
        expect($('.elr-accordion-content').eq(1).hasClass('active')).to.be.true

        $('.elr-accordion-label').eq(1).trigger('click')

        expect($('.elr-accordion-label').eq(1).hasClass('active')).to.be.false
        expect($('.elr-accordion-content').eq(1).hasClass('active')).to.be.false
    })

    it('should remove active class from active content if another label is clicked', function() {
        const accordion = elrAccordion()

        expect($('.elr-accordion-label').first().hasClass('active')).to.be.true
        expect($('.elr-accordion-content').first().hasClass('active')).to.be.true

        $('.elr-accordion-label').eq(1).trigger('click')

        expect($('.elr-accordion-label').first().hasClass('active')).to.be.false
        expect($('.elr-accordion-content').first().hasClass('active')).to.be.false
    })
});<commit_msg>add space before function args<commit_after>import 'jsdom-global/register'
import elrUI from 'elr-ui'
import elrAccordion from '../src/main.js'
import $ from 'jquery'

const ui = elrUI()
const accordion = elrAccordion()
const expect = require('chai').expect
const chai = require('chai')
const jsdom = require('mocha-jsdom')

describe('elrAccordion', function () {
    beforeEach(function () {
        document.body.innerHTML = `

First Section

Some Content

Second Section

Some Content

`
    });

    it('should create a button', function () {
        const $container = $('.elr-accordion')
        const $button = accordion.createButton('showButton', 'Show All', 'elr-show-all elr-button elr-button-primary', $container)

        expect($button.hasClass('elr-show-all')).to.be.true
        expect($button.text()).to.equal('Show All')
    });

    it('should add buttons', function () {
        const $container = $('.elr-accordion')

        accordion.addButtons($container)

        expect($('.elr-button').length).to.equal(2)
    });

    it('should show all content', function () {
        const $container = $('.elr-accordion')
        accordion.showAll($('.elr-accordion-label'), $('.elr-accordion-content'))

        expect($('.elr-accordion-content.active').length).to.equal(2)
        expect($('.elr-accordion-label.active').length).to.equal(2)
    })

    it('should hide all content', function () {
        const $container = $('.elr-accordion')
        accordion.hideAll($('.elr-accordion-label'), $('.elr-accordion-content'))

        expect($('.elr-accordion-content.active').length).to.equal(0)
        expect($('.elr-accordion-label.active').length).to.equal(0)
    })

    it('should toggle content', function () {
        const $container = $('.elr-accordion')

        accordion.toggle.call($('.elr-accordion-label').eq(1), $('.elr-accordion-label'), $('.elr-accordion-content'))

        expect($('.elr-accordion-content').first().hasClass('active')).to.be.false
        expect($('.elr-accordion-label').first().hasClass('active')).to.be.false
        expect($('.elr-accordion-content').eq(1).hasClass('active')).to.be.true
        expect($('.elr-accordion-label').eq(1).hasClass('active')).to.be.true

        accordion.toggle.call($('.elr-accordion-label').first(), $('.elr-accordion-content'), $('.elr-accordion-label'))

        expect($('.elr-accordion-content').first().hasClass('active')).to.be.true
        expect($('.elr-accordion-label').first().hasClass('active')).to.be.true
        expect($('.elr-accordion-content').eq(1).hasClass('active')).to.be.false
        expect($('.elr-accordion-label').eq(1).hasClass('active')).to.be.false
    })

    it('should add buttons', function () {
        const accordion = elrAccordion()

        expect($('.elr-show-all').length).to.equal(1)
        expect($('.elr-hide-all').length).to.equal(1)
    })

    it('should not add buttons if showButtons is false', function () {
        const accordion = elrAccordion({showButtons: false})

        expect($('.elr-show-all').length).to.equal(0)
        expect($('.elr-hide-all').length).to.equal(0)
    })

    it('should show all content when show all button is clicked', function () {
        const accordion = elrAccordion()

        $('button.elr-show-all').trigger('click')

        expect($('.elr-accordion-label.active').length).to.equal(2)
        expect($('.elr-accordion-content.active').length).to.equal(2)
    })

    it('should toggle active class when label is clicked', function () {
        const accordion = elrAccordion()

        $('.elr-accordion-label').eq(1).trigger('click')

        expect($('.elr-accordion-label').eq(1).hasClass('active')).to.be.true
        expect($('.elr-accordion-content').eq(1).hasClass('active')).to.be.true

        $('.elr-accordion-label').eq(1).trigger('click')

        expect($('.elr-accordion-label').eq(1).hasClass('active')).to.be.false
        expect($('.elr-accordion-content').eq(1).hasClass('active')).to.be.false
    })

    it('should remove active class from active content if another label is clicked', function () {
        const accordion = elrAccordion()

        expect($('.elr-accordion-label').first().hasClass('active')).to.be.true
        expect($('.elr-accordion-content').first().hasClass('active')).to.be.true

        $('.elr-accordion-label').eq(1).trigger('click')

        expect($('.elr-accordion-label').first().hasClass('active')).to.be.false
        expect($('.elr-accordion-content').first().hasClass('active')).to.be.false
    })
});<|endoftext|>


<commit_before>/* global describe, it, require */
'use strict';

// MODULES //

var matrix = require( 'dstructs-matrix' );

var // Expectation library:
	chai = require( 'chai' ),

	// Module to be tested:
	variance = require( './../lib' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'compute-variance', function tests() {

	it( 'should export a function', function test() {
		expect( variance ).to.be.a( 'function' );
	});

	it( 'should throw an error if the first argument is neither array-like or matrix-like', function test() {
		var values = [
		//	'5', // valid as is array-like (length)
			5,
			true,
			undefined,
			null,
			NaN,
			function(){},
			{}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				variance( value );
			};
		}
	});

	it( 'should throw an error if provided an unrecognized/unsupported data type option', function test() {
		var values = [
			'beep',
			'boop'
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( Error );
		}
		function badValue( value ) {
			return function() {
				variance( matrix( [2,2] ), {
					'dtype': value
				});
			};
		}
	});

	it( 'should throw an error if provided a dim option which is not a positive integer', function test() {
		var data = matrix( new Int32Array([1,2,3,4]), [2,2] );
		var values = [
			'5',
			-5,
			2.2,
			true,
			undefined,
			null,
			NaN,
			[],
			{}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[ i ] ) ).to.throw( Error );
		}

		function badValue( value ) {
			return function() {
				variance( data, {'dim': value} );
			};
		}
	});

	it( 'should throw an error if provided a dim option which exceeds matrix dimensions ( = 2 )', function test() {
		var data = matrix( new Int32Array([1,2,3,4]), [2,2] );
		var values = [
			3,
			4,
			5
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[ i ] ) ).to.throw( RangeError );
		}

		function badValue( value ) {
			return function() {
				variance( data, {'dim': value} );
			};
		}
	});

	it( 'should compute the sample variance', function test() {
		var data, expected;

		data = [ 2, 4, 5, 3, 8, 2 ];
		expected = 5.2;

		assert.strictEqual( variance( data ), expected );
	});

	it( 'should compute the sample variance of a typed array', function test() {
		var data, expected;

		data = new Int8Array( [ 2, 4, 5, 3, 8, 2 ] );
		expected = 5.2;

		assert.strictEqual( variance( data ), expected );
	});

	it( 'should compute the (biased) sample variance', function test() {
		var data, expected, actual;

		data = [ 2, 4, 5, 3, 8, 2 ];
		expected = 5.2 * (data.length-1) / data.length;

		actual =  variance( data, {
			'bias': true
		});

		assert.strictEqual( actual, expected );
	});

	it( 'should compute the sample variance using an accessor function', function test() {
		var data, expected, actual;

		data = [
			{'x':2},
			{'x':4},
			{'x':5},
			{'x':3},
			{'x':8},
			{'x':2}
		];
		expected = 5.2;
		actual = variance( data, {
			'accessor': getValue
		});

		function getValue( d ) {
			return d.x;
		}

		assert.strictEqual( actual, expected );
	});

	it( 'should return `null` when provided an empty array', function test() {
		var data, expected;

		data = [];
		expected = null;

		assert.strictEqual( variance( data ), expected );
	});

	it( 'should calculate the column products of a matrix', function test() {
		var data, expected, results;

		data = matrix( new Int32Array( [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] ), [3,3] );
		expected = matrix( new Float32Array( [ 1, 1, 1 ] ), [3,1] );

		results = variance( data, {'dtype': 'float32'} );

		assert.strictEqual( results.data.length, expected.data.length );
		assert.deepEqual( results.data, expected.data );
	});

	it( 'should calculate the row products of a matrix', function test() {
		var data, expected, results;

		data = matrix( new Int32Array( [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] ), [3,3] );
		expected = matrix( new Float32Array( [ 9, 9, 9 ] ), [1, 3] );

		results = variance( data, {'dim': 1, 'dtype': 'float32'} );

		assert.strictEqual( results.data.length, expected.data.length );
		assert.deepEqual( results.data, expected.data );
	});

	it( 'should compute the product for a vector (matrix with one column or row)', function test() {
		var data, expected;

		expected = 5.2;
		data = matrix( new Int32Array( [ 2, 4, 5, 3, 8, 2 ] ), [6,1] );

		assert.strictEqual( variance( data ), expected );
	});

});
<commit_msg>[FIX] copy-paste err: prod -> variance<commit_after>/* global describe, it, require */
'use strict';

// MODULES //

var matrix = require( 'dstructs-matrix' );

var // Expectation library:
	chai = require( 'chai' ),

	// Module to be tested:
	variance = require( './../lib' );

// VARIABLES //

var expect = chai.expect,
	assert = chai.assert;

// TESTS //

describe( 'compute-variance', function tests() {

	it( 'should export a function', function test() {
		expect( variance ).to.be.a( 'function' );
	});

	it( 'should throw an error if the first argument is neither array-like or matrix-like', function test() {
		var values = [
		//	'5', // valid as is array-like (length)
			5,
			true,
			undefined,
			null,
			NaN,
			function(){},
			{}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( TypeError );
		}
		function badValue( value ) {
			return function() {
				variance( value );
			};
		}
	});

	it( 'should throw an error if provided an unrecognized/unsupported data type option', function test() {
		var values = [
			'beep',
			'boop'
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[i] ) ).to.throw( Error );
		}
		function badValue( value ) {
			return function() {
				variance( matrix( [2,2] ), {
					'dtype': value
				});
			};
		}
	});

	it( 'should throw an error if provided a dim option which is not a positive integer', function test() {
		var data = matrix( new Int32Array([1,2,3,4]), [2,2] );
		var values = [
			'5',
			-5,
			2.2,
			true,
			undefined,
			null,
			NaN,
			[],
			{}
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[ i ] ) ).to.throw( Error );
		}

		function badValue( value ) {
			return function() {
				variance( data, {'dim': value} );
			};
		}
	});

	it( 'should throw an error if provided a dim option which exceeds matrix dimensions ( = 2 )', function test() {
		var data = matrix( new Int32Array([1,2,3,4]), [2,2] );
		var values = [
			3,
			4,
			5
		];

		for ( var i = 0; i < values.length; i++ ) {
			expect( badValue( values[ i ] ) ).to.throw( RangeError );
		}

		function badValue( value ) {
			return function() {
				variance( data, {'dim': value} );
			};
		}
	});

	it( 'should compute the sample variance', function test() {
		var data, expected;

		data = [ 2, 4, 5, 3, 8, 2 ];
		expected = 5.2;

		assert.strictEqual( variance( data ), expected );
	});

	it( 'should compute the sample variance of a typed array', function test() {
		var data, expected;

		data = new Int8Array( [ 2, 4, 5, 3, 8, 2 ] );
		expected = 5.2;

		assert.strictEqual( variance( data ), expected );
	});

	it( 'should compute the (biased) sample variance', function test() {
		var data, expected, actual;

		data = [ 2, 4, 5, 3, 8, 2 ];
		expected = 5.2 * (data.length-1) / data.length;

		actual =  variance( data, {
			'bias': true
		});

		assert.strictEqual( actual, expected );
	});

	it( 'should compute the sample variance using an accessor function', function test() {
		var data, expected, actual;

		data = [
			{'x':2},
			{'x':4},
			{'x':5},
			{'x':3},
			{'x':8},
			{'x':2}
		];
		expected = 5.2;
		actual = variance( data, {
			'accessor': getValue
		});

		function getValue( d ) {
			return d.x;
		}

		assert.strictEqual( actual, expected );
	});

	it( 'should return `null` when provided an empty array', function test() {
		var data, expected;

		data = [];
		expected = null;

		assert.strictEqual( variance( data ), expected );
	});

	it( 'should calculate the column variances of a matrix', function test() {
		var data, expected, results;

		data = matrix( new Int32Array( [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] ), [3,3] );
		expected = matrix( new Float32Array( [ 1, 1, 1 ] ), [3,1] );

		results = variance( data, {'dtype': 'float32'} );

		assert.strictEqual( results.data.length, expected.data.length );
		assert.deepEqual( results.data, expected.data );
	});

	it( 'should calculate the row variances of a matrix', function test() {
		var data, expected, results;

		data = matrix( new Int32Array( [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] ), [3,3] );
		expected = matrix( new Float32Array( [ 9, 9, 9 ] ), [1, 3] );

		results = variance( data, {'dim': 1, 'dtype': 'float32'} );

		assert.strictEqual( results.data.length, expected.data.length );
		assert.deepEqual( results.data, expected.data );
	});

	it( 'should compute the variance for a vector (matrix with one column or row)', function test() {
		var data, expected;

		expected = 5.2;
		data = matrix( new Int32Array( [ 2, 4, 5, 3, 8, 2 ] ), [6,1] );

		assert.strictEqual( variance( data ), expected );
	});

});
<|endoftext|>


<commit_before>var game;

var assets = {
    battleLost: jasmine.createSpyObj("asset", ["play"]),
    battleWon: jasmine.createSpyObj("asset", ["play"])
};
var chromeUI = jasmine.createSpyObj("chromeUI", ["eventLog", "onUnitActivated", "showModal"]);
var mapUI = jasmine.createSpyObj("mapUI", ["render"]);

function createBattle(params) {
    var u1, u2;

    // New game each time
    game = new Game(1, 1, 2);

    // Same tiles every time
    game.map.tiles[0][0].terrain = params.tileTerrain;
    game.map.tiles[0][0].features = params.tileFeatures;
    game.map.tiles[0][1].terrain = params.tileTerrain;
    game.map.tiles[0][1].features = params.tileFeatures;

    // Same units every time
    u1 = new Units[params.u1Type](config.PLAYER_ID, [0, 0]);
    u2 = new Units[params.u2Type](config.BARB_ID, [0, 1]);
    params.u1Promotions.forEach(function (promotion) {
        u1.promote(promotion, true);
    });
    params.u2Promotions.forEach(function (promotion) {
        u2.promote(promotion, true);
    });
    u1.currentStrength *= params.u1HP / 100;
    u2.currentStrength *= params.u2HP / 100;

    return new Combat.Battle(u1, u2);
}

// Last two params are optional. If provided, compare Battle.odds against civ4 odds. Otherwise, only compare Battle.odds and Battle.fight.
function testBattleOdds(params, civ4OddsAttackerWins, civ4OddsAttackerRetreats) {
    var afterFightsComplete, attackerRetreats, attackerWins, b, expectedAttackerRetreats, expectedAttackerWins, expectedOddsAttackerRetreats, expectedOddsAttackerWins, i, numFights, numFightsComplete, odds;

    numFights = 20000;

    attackerWins = 0;
    attackerRetreats = 0;
    numFightsComplete = 0;

    for (i = 0; i < numFights; i++) {
        (function (i) {
            b = createBattle(params);

            if (i === 0) {
                // Calculate odds for battle
                odds = b.odds();
/*console.log([b.A, b.D]);
console.log(b.appliedBonuses);
console.log(b.firstStrikes);
console.log(odds);*/
                expectedOddsAttackerWins = odds.attackerWinsFight;
                expectedOddsAttackerRetreats = odds.hasOwnProperty("attackerRetreats") ? odds.attackerRetreats : 0;
            }

            b.fight(function () {
                if (b.winner === "attacker") {
                    attackerWins += 1;
                } else if (!b.winner) {
                    attackerRetreats += 1;
                }

                numFightsComplete += 1;
console.log(numFightsComplete);
                if (numFightsComplete === numFights) {
                    afterFightsComplete();
                }
            }, false);
        }(i));
    }

    afterFightsComplete = function () {
        expectedAttackerWins = expectedOddsAttackerWins * numFights;
        expectedAttackerRetreats = expectedOddsAttackerRetreats * numFights;

console.log(params);
if (civ4OddsAttackerWins !== null) { console.log("civ4 Wins: " + civ4OddsAttackerWins); }
console.log("Expected Wins: " + expectedAttackerWins / numFights);
console.log("Observed Wins: " + attackerWins / numFights);
if (civ4OddsAttackerRetreats !== null) { console.log("civ4 Retreats: " + civ4OddsAttackerRetreats); }
console.log("Expected Retreats: " + expectedAttackerRetreats / numFights);
console.log("Observed Retreats: " + attackerRetreats / numFights);

        expect(Math.abs((attackerWins - expectedAttackerWins) / numFights)).toBeLessThan(0.01);
        expect(Math.abs((attackerRetreats - expectedAttackerRetreats) / numFights)).toBeLessThan(0.01);
        if (civ4OddsAttackerWins !== null) { expect(Math.abs(civ4OddsAttackerWins - expectedAttackerWins / numFights)).toBeLessThan(0.01); }
        if (civ4OddsAttackerRetreats !== null) { expect(Math.abs(civ4OddsAttackerRetreats - expectedAttackerRetreats / numFights)).toBeLessThan(0.01); }
    };
}

describe("Combat.Battle.odds()", function() {
    var async;

    async = new AsyncSpec(this);

    async.it("should accurately predict outcome for random battle", function(done) {
        var i, params, rand;

        for (i = 0; i < 1; i++) {
            params = {};

            // Randomize tile
            params.tileTerrain = "grassland";
            rand = Math.random();
            if (rand < 0.25) {
                params.tileFeatures = [];
            } else if (rand < 0.5) {
                params.tileFeatures = ["forest"];
            } else if (rand < 0.75) {
                params.tileFeatures = ["hills"];
            } else {
                params.tileFeatures = ["forest", "hills"];
            }

            // Randomize Units
            params.u1Type = Random.choice(["Warrior", "Archer", "Chariot", "Spearman", "Axeman"]);
            params.u2Type = Random.choice(["Scout", "Warrior", "Archer", "Chariot", "Spearman", "Axeman"]);

            // Randomize promotions
            params.u1Promotions = [Random.choice(Object.keys(Units.promotions)), Random.choice(Object.keys(Units.promotions)), Random.choice(Object.keys(Units.promotions)), Random.choice(Object.keys(Units.promotions))];
            params.u2Promotions = [Random.choice(Object.keys(Units.promotions)), Random.choice(Object.keys(Units.promotions)), Random.choice(Object.keys(Units.promotions)), Random.choice(Object.keys(Units.promotions))];

            // Randomize health
            params.u1HP = 1 + Math.round(Math.random() * 99);
            params.u2HP = 1 + Math.round(Math.random() * 99);
//params = {tileTerrain: 'grassland', tileFeatures: ['hills'], u1Type: 'Warrior', u2Type: 'Chariot', u1Promotions: ['drill2', 'combat1', 'combat2', 'cityRaider2'], u2Promotions: ['cityGarrison3', 'drill4', 'cityGarrison3', 'cityRaider3'], u1HP: 77, u2HP: 37};

            testBattleOdds(params, null, null, done);
        }
    });
/*    it("should match results from civ4", function() {
        var params;

        params = {tileTerrain: 'grassland', tileFeatures: [], u1Type: 'Axeman', u2Type: 'Axeman', u1Promotions: ['drill1', 'drill2', 'drill3', 'drill4'], u2Promotions: [], u1HP: 100, u2HP: 100};
        testBattleOdds(params, 0.787, 0);

        params = {tileTerrain: 'grassland', tileFeatures: [], u1Type: 'Axeman', u2Type: 'Axeman', u1Promotions: ['drill1', 'drill2', 'drill3'], u2Promotions: [], u1HP: 100, u2HP: 100};
        testBattleOdds(params, 0.667, 0);

        params = {tileTerrain: 'grassland', tileFeatures: [], u1Type: 'Archer', u2Type: 'Chariot', u1Promotions: [], u2Promotions: ['drill2', 'drill3', 'drill4'], u1HP: 100, u2HP: 100};
        testBattleOdds(params, 0.096, 0);

        params = {tileTerrain: 'grassland', tileFeatures: [], u1Type: 'Chariot', u2Type: 'Chariot', u1Promotions: ['drill4'], u2Promotions: ['drill2', 'drill3', 'drill4'], u1HP: 100, u2HP: 100};
        testBattleOdds(params, 0.364, 0.064);

        params = {tileTerrain: 'grassland', tileFeatures: ["forest", "hills"], u1Type: 'Spearman', u2Type: 'Archer', u1Promotions: ['cover'], u2Promotions: ['combat1'], u1HP: 100, u2HP: 100};
        testBattleOdds(params, 0.093, 0);

        params = {tileTerrain: 'grassland', tileFeatures: ["forest", "hills"], u1Type: 'Spearman', u2Type: 'Archer', u1Promotions: ['cover'], u2Promotions: ['combat1'], u1HP: 100, u2HP: 2.5/3 * 100};
        testBattleOdds(params, 0.341, 0);
    });*/
});<commit_msg>Fix variable scope<commit_after>var game;

var assets = {
    battleLost: jasmine.createSpyObj("asset", ["play"]),
    battleWon: jasmine.createSpyObj("asset", ["play"])
};
var chromeUI = jasmine.createSpyObj("chromeUI", ["eventLog", "onUnitActivated", "showModal"]);
var mapUI = jasmine.createSpyObj("mapUI", ["render"]);

function createBattle(params) {
    var u1, u2;

    // New game each time
    game = new Game(1, 1, 2);

    // Same tiles every time
    game.map.tiles[0][0].terrain = params.tileTerrain;
    game.map.tiles[0][0].features = params.tileFeatures;
    game.map.tiles[0][1].terrain = params.tileTerrain;
    game.map.tiles[0][1].features = params.tileFeatures;

    // Same units every time
    u1 = new Units[params.u1Type](config.PLAYER_ID, [0, 0]);
    u2 = new Units[params.u2Type](config.BARB_ID, [0, 1]);
    params.u1Promotions.forEach(function (promotion) {
        u1.promote(promotion, true);
    });
    params.u2Promotions.forEach(function (promotion) {
        u2.promote(promotion, true);
    });
    u1.currentStrength *= params.u1HP / 100;
    u2.currentStrength *= params.u2HP / 100;

    return new Combat.Battle(u1, u2);
}

// Last two params are optional. If provided, compare Battle.odds against civ4 odds. Otherwise, only compare Battle.odds and Battle.fight.
function testBattleOdds(params, civ4OddsAttackerWins, civ4OddsAttackerRetreats) {
    var afterFightsComplete, attackerRetreats, attackerWins, expectedAttackerRetreats, expectedAttackerWins, expectedOddsAttackerRetreats, expectedOddsAttackerWins, i, numFights, numFightsComplete;

    numFights = 20000;

    attackerWins = 0;
    attackerRetreats = 0;
    numFightsComplete = 0;

    for (i = 0; i < numFights; i++) {
        (function (i) {
            var b, odds;

            b = createBattle(params);

            if (i === 0) {
                // Calculate odds for battle
                odds = b.odds();
/*console.log([b.A, b.D]);
console.log(b.appliedBonuses);
console.log(b.firstStrikes);
console.log(odds);*/
                expectedOddsAttackerWins = odds.attackerWinsFight;
                expectedOddsAttackerRetreats = odds.hasOwnProperty("attackerRetreats") ? odds.attackerRetreats : 0;
            }

            b.fight(function () {
                if (b.winner === "attacker") {
                    attackerWins += 1;
                } else if (!b.winner) {
                    attackerRetreats += 1;
                }

                numFightsComplete += 1;
console.log(numFightsComplete);
                if (numFightsComplete === numFights) {
                    afterFightsComplete();
                }
            }, false);
        }(i));
    }

    afterFightsComplete = function () {
        expectedAttackerWins = expectedOddsAttackerWins * numFights;
        expectedAttackerRetreats = expectedOddsAttackerRetreats * numFights;

console.log(params);
if (civ4OddsAttackerWins !== null) { console.log("civ4 Wins: " + civ4OddsAttackerWins); }
console.log("Expected Wins: " + expectedAttackerWins / numFights);
console.log("Observed Wins: " + attackerWins / numFights);
if (civ4OddsAttackerRetreats !== null) { console.log("civ4 Retreats: " + civ4OddsAttackerRetreats); }
console.log("Expected Retreats: " + expectedAttackerRetreats / numFights);
console.log("Observed Retreats: " + attackerRetreats / numFights);

        expect(Math.abs((attackerWins - expectedAttackerWins) / numFights)).toBeLessThan(0.01);
        expect(Math.abs((attackerRetreats - expectedAttackerRetreats) / numFights)).toBeLessThan(0.01);
        if (civ4OddsAttackerWins !== null) { expect(Math.abs(civ4OddsAttackerWins - expectedAttackerWins / numFights)).toBeLessThan(0.01); }
        if (civ4OddsAttackerRetreats !== null) { expect(Math.abs(civ4OddsAttackerRetreats - expectedAttackerRetreats / numFights)).toBeLessThan(0.01); }
    };
}

describe("Combat.Battle.odds()", function() {
    var async;

    async = new AsyncSpec(this);

    async.it("should accurately predict outcome for random battle", function(done) {
        var i, params, rand;

        for (i = 0; i < 1; i++) {
            params = {};

            // Randomize tile
            params.tileTerrain = "grassland";
            rand = Math.random();
            if (rand < 0.25) {
                params.tileFeatures = [];
            } else if (rand < 0.5) {
                params.tileFeatures = ["forest"];
            } else if (rand < 0.75) {
                params.tileFeatures = ["hills"];
            } else {
                params.tileFeatures = ["forest", "hills"];
            }

            // Randomize Units
            params.u1Type = Random.choice(["Warrior", "Archer", "Chariot", "Spearman", "Axeman"]);
            params.u2Type = Random.choice(["Scout", "Warrior", "Archer", "Chariot", "Spearman", "Axeman"]);

            // Randomize promotions
            params.u1Promotions = [Random.choice(Object.keys(Units.promotions)), Random.choice(Object.keys(Units.promotions)), Random.choice(Object.keys(Units.promotions)), Random.choice(Object.keys(Units.promotions))];
            params.u2Promotions = [Random.choice(Object.keys(Units.promotions)), Random.choice(Object.keys(Units.promotions)), Random.choice(Object.keys(Units.promotions)), Random.choice(Object.keys(Units.promotions))];

            // Randomize health
            params.u1HP = 1 + Math.round(Math.random() * 99);
            params.u2HP = 1 + Math.round(Math.random() * 99);
//params = {tileTerrain: 'grassland', tileFeatures: ['hills'], u1Type: 'Warrior', u2Type: 'Chariot', u1Promotions: ['drill2', 'combat1', 'combat2', 'cityRaider2'], u2Promotions: ['cityGarrison3', 'drill4', 'cityGarrison3', 'cityRaider3'], u1HP: 77, u2HP: 37};

            testBattleOdds(params, null, null, done);
        }
    });
/*    it("should match results from civ4", function() {
        var params;

        params = {tileTerrain: 'grassland', tileFeatures: [], u1Type: 'Axeman', u2Type: 'Axeman', u1Promotions: ['drill1', 'drill2', 'drill3', 'drill4'], u2Promotions: [], u1HP: 100, u2HP: 100};
        testBattleOdds(params, 0.787, 0);

        params = {tileTerrain: 'grassland', tileFeatures: [], u1Type: 'Axeman', u2Type: 'Axeman', u1Promotions: ['drill1', 'drill2', 'drill3'], u2Promotions: [], u1HP: 100, u2HP: 100};
        testBattleOdds(params, 0.667, 0);

        params = {tileTerrain: 'grassland', tileFeatures: [], u1Type: 'Archer', u2Type: 'Chariot', u1Promotions: [], u2Promotions: ['drill2', 'drill3', 'drill4'], u1HP: 100, u2HP: 100};
        testBattleOdds(params, 0.096, 0);

        params = {tileTerrain: 'grassland', tileFeatures: [], u1Type: 'Chariot', u2Type: 'Chariot', u1Promotions: ['drill4'], u2Promotions: ['drill2', 'drill3', 'drill4'], u1HP: 100, u2HP: 100};
        testBattleOdds(params, 0.364, 0.064);

        params = {tileTerrain: 'grassland', tileFeatures: ["forest", "hills"], u1Type: 'Spearman', u2Type: 'Archer', u1Promotions: ['cover'], u2Promotions: ['combat1'], u1HP: 100, u2HP: 100};
        testBattleOdds(params, 0.093, 0);

        params = {tileTerrain: 'grassland', tileFeatures: ["forest", "hills"], u1Type: 'Spearman', u2Type: 'Archer', u1Promotions: ['cover'], u2Promotions: ['combat1'], u1HP: 100, u2HP: 2.5/3 * 100};
        testBattleOdds(params, 0.341, 0);
    });*/
});<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var nock = require('nock');
var rimraf = require('rimraf');
var test = require('ava');
var Download = require('../');
var fixture = path.join.bind(path, __dirname, 'fixtures');

test('expose a constructor', function (t) {
	t.plan(1);
	t.assert(typeof Download === 'function');
});

test('return an instance if it called without `new`', function (t) {
	t.plan(1);
	t.assert(Download() instanceof Download);
});

test('set a file to get', function (t) {
	t.plan(1);

	var download = new Download()
		.get('http://example.com/test.jpg');

	t.assert(download._get[0].url === 'http://example.com/test.jpg');
});

test('download a file', function (t) {
	t.plan(4);

	var scope = nock('http://foo.com')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'));

	new Download()
		.get('http://foo.com/test-file.zip')
		.run(function (err, files) {
			t.assert(!err, err);
			t.assert(scope.isDone());
			t.assert(files[0].path === 'test-file.zip');
			t.assert(files[0].url === 'http://foo.com/test-file.zip');
		});
});

test('download multiple files', function (t) {
	t.plan(7);

	var scope = nock('http://foo.com')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'))
		.get('/nested/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'));

	new Download()
		.get('http://foo.com/test-file.zip')
		.get('http://foo.com/nested/test-file.zip')
		.run(function (err, files) {
			t.assert(!err, err);
			t.assert(scope.isDone());
			t.assert(files.length === 2);
			t.assert(files[0].path === 'test-file.zip');
			t.assert(files[0].url === 'http://foo.com/test-file.zip');
			t.assert(files[1].path === 'test-file.zip');
			t.assert(files[1].url === 'http://foo.com/nested/test-file.zip');
		});
});

test('download a file and rename it', function (t) {
	t.plan(4);

	var scope = nock('http://foo.com')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'));

	new Download()
		.get('http://foo.com/test-file.zip')
		.rename('foobar.zip')
		.run(function (err, files) {
			t.assert(!err, err);
			t.assert(scope.isDone());
			t.assert(path.basename(files[0].path) === 'foobar.zip');
			t.assert(files[0].url === 'http://foo.com/test-file.zip');
		});
});

test('download and extract a file', function (t) {
	t.plan(3);

	var scope = nock('http://foo.com')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'));

	new Download({extract: true})
		.get('http://foo.com/test-file.zip')
		.run(function (err, files) {
			t.assert(!err, err);
			t.assert(scope.isDone());
			t.assert(files[0].path === 'file.txt');
		});
});

test('specify destination folder', function (t) {
	t.plan(4);

	var d0 = path.join(__dirname, 'tmp');
	var scope = nock('http://foo.com')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'))
		.get('/test.js')
		.replyWithFile(200, __filename);

	new Download({extract: true})
		.get('http://foo.com/test-file.zip')
		.get('http://foo.com/test.js')
		.dest(d0)
		.run(function (err, files) {
			var r0 = fs.readdirSync(d0);
			t.assert(!err, err);
			t.assert(scope.isDone());
			rimraf.sync(d0);
			t.assert(r0[0] === 'file.txt');
			t.assert(r0[1] === 'test.js');
		});
});

test('specify multiple destination folders', function (t) {
	t.plan(4);

	var d1 = path.join(__dirname, 't1');
	var d2 = path.join(__dirname, 't2');
	var scope = nock('http://foo.com')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'))
		.get('/test.js')
		.replyWithFile(200, __filename);

	new Download({extract: true})
		.get('http://foo.com/test-file.zip', d1)
		.get('http://foo.com/test.js')
		.dest(d2)
		.run(function (err, files) {
			var r1 = fs.readdirSync(d1);
			var r2 = fs.readdirSync(d2);
			t.assert(!err, err);
			t.assert(scope.isDone());
			rimraf.sync(d1);
			rimraf.sync(d2);
			t.assert(r1[0] === 'file.txt');
			t.assert(r2[0] === 'test.js');
		});
});

test('rename file to a valid filename', function (t) {
	t.plan(4);

	var scope = nock('http://foo.com')
		.get('/test?file.zip')
		.replyWithFile(200, fixture('test-file.zip'));

	new Download()
		.get('http://foo.com/test?file.zip')
		.run(function (err, files) {
			t.assert(!err, err);
			t.assert(scope.isDone());
			t.assert(files[0].path === 'test!file.zip');
			t.assert(files[0].url === 'http://foo.com/test?file.zip');
		});
});

test('error on invalid URL', function (t) {
	t.plan(1);

	new Download()
		.get('foobar')
		.run(function (err) {
			t.assert(err.message === 'Specify a valid URL');
		});
});

test('error on 404', function (t) {
	t.plan(3);

	var scope = nock('http://foo.com')
		.get('/')
		.reply(404);

	new Download()
		.get('http://foo.com')
		.run(function (err) {
			t.assert(scope.isDone());
			t.assert(err.code === 404);
			t.assert(err.message === 'http://foo.com response code is 404 (Not Found)');
		});
});

test('request options', function (t) {
	t.plan(4);

	var scope = nock('http://foo.com')
		.matchHeader('authorization', 'Basic dXNlcjpwYXNzd29yZA==')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'));

	new Download({auth: 'user:password'})
		.get('http://foo.com/test-file.zip')
		.run(function (err, files) {
			t.assert(!err, err);
			t.assert(scope.isDone());
			t.assert(files[0].path === 'test-file.zip');
			t.assert(files[0].url === 'http://foo.com/test-file.zip');
		});
});

test('expose the response object', function (t) {
	t.plan(7);

	var scope = nock('http://foo.com')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'));

	new Download()
		.get('http://foo.com/test-file.zip')
		.use(function (res, url) {
			t.assert(res);
			t.assert(res.statusCode === 200);
			t.assert(url === 'http://foo.com/test-file.zip');
		})
		.run(function (err, files) {
			t.assert(!err, err);
			t.assert(scope.isDone());
			t.assert(files[0].path === 'test-file.zip');
			t.assert(files[0].url === 'http://foo.com/test-file.zip');
		});
});
<commit_msg>Show values of failing tests<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var nock = require('nock');
var rimraf = require('rimraf');
var test = require('ava');
var Download = require('../');
var fixture = path.join.bind(path, __dirname, 'fixtures');

test('expose a constructor', function (t) {
	t.plan(1);
	t.assert(typeof Download === 'function', typeof Download);
});

test('return an instance if it called without `new`', function (t) {
	t.plan(1);
	t.assert(Download() instanceof Download);
});

test('set a file to get', function (t) {
	t.plan(1);

	var download = new Download()
		.get('http://example.com/test.jpg');

	t.assert(download._get[0].url === 'http://example.com/test.jpg', download._get[0].url);
});

test('download a file', function (t) {
	t.plan(4);

	var scope = nock('http://foo.com')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'));

	new Download()
		.get('http://foo.com/test-file.zip')
		.run(function (err, files) {
			t.assert(!err, err);
			t.assert(scope.isDone(), scope.isDone());
			t.assert(files[0].path === 'test-file.zip', files[0].path);
			t.assert(files[0].url === 'http://foo.com/test-file.zip', files[0].url);
		});
});

test('download multiple files', function (t) {
	t.plan(7);

	var scope = nock('http://foo.com')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'))
		.get('/nested/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'));

	new Download()
		.get('http://foo.com/test-file.zip')
		.get('http://foo.com/nested/test-file.zip')
		.run(function (err, files) {
			t.assert(!err, err);
			t.assert(scope.isDone(), scope.isDone());
			t.assert(files.length === 2, files.length);
			t.assert(files[0].path === 'test-file.zip', files[0].path);
			t.assert(files[0].url === 'http://foo.com/test-file.zip', files[0].url);
			t.assert(files[1].path === 'test-file.zip', files[1].path);
			t.assert(files[1].url === 'http://foo.com/nested/test-file.zip', files[1].url);
		});
});

test('download a file and rename it', function (t) {
	t.plan(4);

	var scope = nock('http://foo.com')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'));

	new Download()
		.get('http://foo.com/test-file.zip')
		.rename('foobar.zip')
		.run(function (err, files) {
			t.assert(!err, err);
			t.assert(scope.isDone(), scope.isDone());
			t.assert(path.basename(files[0].path) === 'foobar.zip', path.basename(files[0].path));
			t.assert(files[0].url === 'http://foo.com/test-file.zip', files[0].url);
		});
});

test('download and extract a file', function (t) {
	t.plan(3);

	var scope = nock('http://foo.com')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'));

	new Download({extract: true})
		.get('http://foo.com/test-file.zip')
		.run(function (err, files) {
			t.assert(!err, err);
			t.assert(scope.isDone(), scope.isDone());
			t.assert(files[0].path === 'file.txt', files[0].path);
		});
});

test('specify destination folder', function (t) {
	t.plan(4);

	var d0 = path.join(__dirname, 'tmp');
	var scope = nock('http://foo.com')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'))
		.get('/test.js')
		.replyWithFile(200, __filename);

	new Download({extract: true})
		.get('http://foo.com/test-file.zip')
		.get('http://foo.com/test.js')
		.dest(d0)
		.run(function (err, files) {
			var r0 = fs.readdirSync(d0);
			t.assert(!err, err);
			t.assert(scope.isDone(), scope.isDone());
			rimraf.sync(d0);
			t.assert(r0[0] === 'file.txt', r0[0]);
			t.assert(r0[1] === 'test.js', r0[1]);
		});
});

test('specify multiple destination folders', function (t) {
	t.plan(4);

	var d1 = path.join(__dirname, 't1');
	var d2 = path.join(__dirname, 't2');
	var scope = nock('http://foo.com')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'))
		.get('/test.js')
		.replyWithFile(200, __filename);

	new Download({extract: true})
		.get('http://foo.com/test-file.zip', d1)
		.get('http://foo.com/test.js')
		.dest(d2)
		.run(function (err, files) {
			var r1 = fs.readdirSync(d1);
			var r2 = fs.readdirSync(d2);
			t.assert(!err, err);
			t.assert(scope.isDone(), scope.isDone());
			rimraf.sync(d1);
			rimraf.sync(d2);
			t.assert(r1[0] === 'file.txt', r1[0]);
			t.assert(r2[0] === 'test.js', r2[0]);
		});
});

test('rename file to a valid filename', function (t) {
	t.plan(4);

	var scope = nock('http://foo.com')
		.get('/test?file.zip')
		.replyWithFile(200, fixture('test-file.zip'));

	new Download()
		.get('http://foo.com/test?file.zip')
		.run(function (err, files) {
			t.assert(!err, err);
			t.assert(scope.isDone(), scope.isDone());
			t.assert(files[0].path === 'test!file.zip', files[0].path);
			t.assert(files[0].url === 'http://foo.com/test?file.zip', files[0].url);
		});
});

test('error on invalid URL', function (t) {
	t.plan(1);

	new Download()
		.get('foobar')
		.run(function (err) {
			t.assert(err.message === 'Specify a valid URL', err.message);
		});
});

test('error on 404', function (t) {
	t.plan(3);

	var scope = nock('http://foo.com')
		.get('/')
		.reply(404);

	new Download()
		.get('http://foo.com')
		.run(function (err) {
			t.assert(scope.isDone(), scope.isDone());
			t.assert(err.code === 404, err.code);
			t.assert(err.message === 'http://foo.com response code is 404 (Not Found)', err.message);
		});
});

test('request options', function (t) {
	t.plan(4);

	var scope = nock('http://foo.com')
		.matchHeader('authorization', 'Basic dXNlcjpwYXNzd29yZA==')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'));

	new Download({auth: 'user:password'})
		.get('http://foo.com/test-file.zip')
		.run(function (err, files) {
			t.assert(!err, err);
			t.assert(scope.isDone(), scope.isDone());
			t.assert(files[0].path === 'test-file.zip', files[0].path);
			t.assert(files[0].url === 'http://foo.com/test-file.zip', files[0].url);
		});
});

test('expose the response object', function (t) {
	t.plan(7);

	var scope = nock('http://foo.com')
		.get('/test-file.zip')
		.replyWithFile(200, fixture('test-file.zip'));

	new Download()
		.get('http://foo.com/test-file.zip')
		.use(function (res, url) {
			t.assert(res, res);
			t.assert(res.statusCode === 200, res.statusCode);
			t.assert(url === 'http://foo.com/test-file.zip', url);
		})
		.run(function (err, files) {
			t.assert(!err, err);
			t.assert(scope.isDone(), scope.isDone());
			t.assert(files[0].path === 'test-file.zip', files[0].path);
			t.assert(files[0].url === 'http://foo.com/test-file.zip', files[0].url);
		});
});
<|endoftext|>


<commit_before>var stream = require("stream");
var router = require("../");

router.setMap({
    "/my/**/*":"func:testFun",

    "index":"index.html",

    "test?v=*":"my*.html",

    "nihao/**/ho*eo":"**/*.html",

    "/public/bi*/**/*":"public/**/*"
});

router.on("notmatch" , function(){
    console.log('not match');
});

router.on("path" , function(path , requestpath){
    console.log("请求路径："+requestpath);
    console.log("路由转换： "+path);
});

router.on("error" , function(err){
    console.log(err);
});

router.set("testFun" , function(req , res , requestpath){
    console.log("请求路径：" + requestpath);
    console.log("执行方法：testFun");
});

describe("check" , function(){
    it("test1" , function(done){
        test("/public/biz009/stylesheets/css/man.css");
        done();
    });

    it("test2" , function(done){
        test("/my/1/2/3/4/abs.html?v=22");
        done();
    });

    it("test3" , function(done){
        test("/index");
        done();
    });

    it("test4" , function(done){
        test("/test?v=index");
        done();
    });

    it("test5" , function(done){
        test("/nihao/asd/asd/asd/homemeeo");
        done();
    });
});

function test(url){
    var res = new stream.Writable();
    res.writeHead = function(){};
    res._write = function(chunk , enc , done){
        done();
    };

    var req = {
        url:url,
        headers:{
            'accept-encoding':''
        }
    };

    router.route(req , res);
}<commit_msg>update<commit_after>var stream = require("stream");
var router = require("../");

router.setMap({
    "/my/**/*":"func:testFun",

    "index":"index.html",

    "test?v=*":"my*.html",

    "nihao/**/ho*eo":"**/*.html",

    "/public/bi*/**/*":"public/**/*"
});

router.on("notmatch" , function(){
    console.log('not match\n');
});

router.on("path" , function(path , requestpath){
    console.log("请求路径："+requestpath);
    console.log("路由转换： "+path+"\n");
});

router.on("error" , function(err){
    console.log(err);
});

router.set("testFun" , function(req , res , requestpath){
    console.log("请求路径：" + requestpath);
    console.log("执行方法：testFun\n");
});

test("/public/biz009/stylesheets/css/man.css");
test("/my/1/2/3/4/abs.html?v=22");
test("/index");
test("/test?v=index");
test("/nihao/asd/asd/asd/homemeeo");

function test(url){
    var res = new stream.Writable();
    res.writeHead = function(){};
    res._write = function(chunk , enc , done){
        done();
    };

    var req = {
        url:url,
        headers:{
            'accept-encoding':''
        }
    };

    router.route(req , res);
}<|endoftext|>


<commit_before>(function ($) {
  $.fn.enable = function () {
    return this.removeAttr('disabled');
  };
  $.fn.disable = function () {
    return this.attr('disabled', 'disabled');
  };
})(jQuery);

$(document).ready(function () {
  var popoverNormalOptions = [
    'animate',
    'delayIn',
    'delayOut',
    'fallback',
    'html',
    'live',
    'offset',
    'placement',
    'trigger'
  ];
  $('[data-popover]').each(function () {
    var $this = $(this);
    var options = {
      content: 'data-content',
      title: 'data-title'
    };
    $.each(popoverNormalOptions, function (_, v) {
      options[v] = $this.attr('data-' + v);
    });
    $this.popover(options);
  });
});

$(document).ready(function () {
  var twipsyNormalOptions = [
    'animate',
    'delayIn',
    'delayOut',
    'fallback',
    'html',
    'live',
    'offset',
    'placement',
    'trigger'
  ];
  $('[data-twipsy]').each(function () {
    var $this = $(this);
    var options = {
      title: 'data-title'
    };
    $.each(twipsyNormalOptions, function (_, v) {
      options[v] = $this.attr('data-' + v);
    });
    $this.twipsy(options);
  });
});

$(document).ready(function () {
  $('#columns .tweets').empty();  // Remove dummy content.

  $('.not-signed-in #the-sign-in-menu').popover('show');

  var updateCharacterCount = function () {
    $('#character-count').text(140 - $(this).val().length);  // FIXME
  };
  $('#status')
    .keydown(updateCharacterCount)
    .keyup(updateCharacterCount);

  $('.not-signed-in #tweet-form :input').disable();
  $('#tweet-form').submit(function () {
    var indicateRequestingStatus = function () {
      $('#tweet-form :input').disable();
      $('#tweet-form #status').twipsy('show');
    };
    var restoreRequestingStatus = function () {
      $('#tweet-form :input').enable();
      $('#tweet-form #status').twipsy('hide');
    };
    indicateRequestingStatus();
    $.post(
      '/api/1/statuses/update.json',
      {
        status: $('#status').val()
      },
      'json'
    )
    .done(function (data) {
      if (data.error == null) {
        alert(data);  // FIXME: Update view.
        $('#status').val('');
      } else {
        // FIXME: Alert gracefully.
        alert('Failed to tweet: ' + data.error);
      }
    })
    .fail(function (_jqXHR, textStatus, errorThrown) {
      // FIXME: Alert gracefully.
      alert('Failed to tweet: ' + textStatus + ' / ' + errorThrown);
    })
    .always(function (_jqXHR, _textStatus) {
      restoreRequestingStatus();
    });

    return false;
  });
});

// __END__  {{{1
// vim: expandtab shiftwidth=2 softtabstop=2
// vim: foldmethod=marker
<commit_msg>Handle statuses/update response correctly<commit_after>(function ($) {
  $.fn.enable = function () {
    return this.removeAttr('disabled');
  };
  $.fn.disable = function () {
    return this.attr('disabled', 'disabled');
  };
})(jQuery);

$(document).ready(function () {
  var popoverNormalOptions = [
    'animate',
    'delayIn',
    'delayOut',
    'fallback',
    'html',
    'live',
    'offset',
    'placement',
    'trigger'
  ];
  $('[data-popover]').each(function () {
    var $this = $(this);
    var options = {
      content: 'data-content',
      title: 'data-title'
    };
    $.each(popoverNormalOptions, function (_, v) {
      options[v] = $this.attr('data-' + v);
    });
    $this.popover(options);
  });
});

$(document).ready(function () {
  var twipsyNormalOptions = [
    'animate',
    'delayIn',
    'delayOut',
    'fallback',
    'html',
    'live',
    'offset',
    'placement',
    'trigger'
  ];
  $('[data-twipsy]').each(function () {
    var $this = $(this);
    var options = {
      title: 'data-title'
    };
    $.each(twipsyNormalOptions, function (_, v) {
      options[v] = $this.attr('data-' + v);
    });
    $this.twipsy(options);
  });
});

$(document).ready(function () {
  $('#columns .tweets').empty();  // Remove dummy content.

  $('.not-signed-in #the-sign-in-menu').popover('show');

  var updateCharacterCount = function () {
    $('#character-count').text(140 - $(this).val().length);  // FIXME
  };
  $('#status')
    .keydown(updateCharacterCount)
    .keyup(updateCharacterCount);

  $('.not-signed-in #tweet-form :input').disable();
  $('#tweet-form').submit(function () {
    var indicateRequestingStatus = function () {
      $('#tweet-form :input').disable();
      $('#tweet-form #status').twipsy('show');
    };
    var restoreRequestingStatus = function () {
      $('#tweet-form :input').enable();
      $('#tweet-form #status').twipsy('hide');
    };
    indicateRequestingStatus();
    $.ajax({
      url: '/api/1/statuses/update.json',
      type: 'POST',
      dataType: 'json',
      data: {
        status: $('#status').val()
      }
    })
    .done(function (data) {
      if (data.error == null) {
        alert(data);  // FIXME: Update view.
        $('#status').val('');
      } else {
        // FIXME: Alert gracefully.
        alert('Failed to tweet: ' + data.error);
      }
    })
    .fail(function (_jqXHR, textStatus, errorThrown) {
      // FIXME: Alert gracefully.
      alert('Failed to tweet: ' + textStatus + ' / ' + errorThrown);
    })
    .always(function (_jqXHR, _textStatus) {
      restoreRequestingStatus();
    });

    return false;
  });
});

// __END__  {{{1
// vim: expandtab shiftwidth=2 softtabstop=2
// vim: foldmethod=marker
<|endoftext|>


<commit_before>"use strict";
let _ = require('lodash');
var assert = require('assert');
var tlsAsana = require('../index.js');
var tlsConsts = require('../tlsConstants.js');

let client = undefined;
let tlsTasks;

/**
 * Test cache so that we can make sure a refresh function is being called
 * for our caches without having to alter their production refresh times
 */
let testCache = {
    name: 'testCache',
    lastUpdated: Date.now(),
    refreshTime: 1000,
    testRefresh: function(){
        return true;
    }
};

describe('Connecting to Asana', function(){

   it('Should setup the connection', function(){
        this.timeout(8000);
        return tlsAsana.connect('166216691534199').then(function(response){
            client = response;
            assert(response,'Connection failed');
        });
   });

});

describe('Making sure the available users update', function(){
    it('Should update the workspace users', function(){
        this.timeout(8000);
        return tlsAsana.updateUsers().then( response => {
            assert(response.data[0].name, "Chris Hodge", 'Failed to update the available users');
        });
    });
})

describe('Making sure caches update', function(){

    it('Should update the tag cache', function(){
        this.timeout(8000);
        return tlsAsana.updateTagNames(10).then(function(response){
            assert.equal(response.Accepted,167304830178303,'Failed to update the tag cache');
        })
    });

    it('Should update the task cache', function(){
        this.timeout(8000);
        return tlsAsana.updateTasks().then(function(response){
            tlsTasks = response;
            assert.equal(response.data[0].id, 180230098413779, 'Failed to update task cache');
        })
    });

    it('Should get the tags associated with a task when the tasks are cached', function(){
        if(!tlsTasks){
            throw "Error, cannot check the tags associated with a task if the task cache did not update";
        }
        assert.equal(tlsTasks.data[4].tags[0].name,"New Request",'Failed to get tags associated with tasks');
    });

    it('Should update a local cache if it is older than its set refresh time', function(){
        this.timeout(8000);

        assert(tlsAsana.checkLastCacheUpdate(testCache, testCache.testRefresh), 'Failed to update local cache');
    });

});

describe('Querying our local caches', function(){

    it('Should get information about a specific task from the local tag cache', function(){
        return tlsAsana.getTaskInfoByID(169176168459508).then(taskInfo => {
            assert.equal(taskInfo.created_at, '2016-08-17T21:06:24.132Z', 'getting specific task info failed');
        })
    });

    it('Should get a cached tag id from the local tag cache', function(){
        return tlsAsana.getTagIDByName('captioning_unassigned').then(tagID => {
            assert.equal(tagID, 167304830178312, 'Failed to get cached tag id');
        });
    });

    it('Should get all of the local tasks that have a certain tag', function(){
        let tagID = 167304830178312;

        return tlsAsana.getTasksByTag(tagID).then(taskArray => {
            assert.notDeepEqual(_.filter(taskArray[0].tags, x => {
                return x.id === tagID;
            }), [], 'Failed to return a task with the correct tag');
        })
    });

    it('Should get all of the local tasks that have an unassigned tag', function(){
        let unassignedTagID = 167304830178312;

        return tlsAsana.getUnassignedTasks().then(taskArray => {
            assert.notDeepEqual(_.filter(taskArray[0].tags, x => {
                return x.id === unassignedTagID;
            }), [], 'Failed to return a task with an unassigned tag');
        });
    });

    it('Should get all of the local tasks that have a new task tag', function(){
        let newTagID = 44184307053951;

        return tlsAsana.getNewTasks().then(taskArray => {
            assert.notDeepEqual(_.filter(taskArray[0].tags, x => {
                return x.id === newTagID;
            }), [], 'Failed to return a task with a new task tag');
        });
    });

});

describe('Querying Asana', function(){

    it('Should get all of the projects from Asana', function(){
        this.timeout(8000);

        return tlsAsana.getAllProjects().then(projects => {
            assert.ok( projects.length > 0 );
        });
    });

});

describe('Working with tags in Asana', function(){

    it("Should change a task's tag from captioning_unassigned to captioning_accepted", function(){
        this.timeout(8000);

        return tlsAsana.switchTag('166304358745259', 'captioning_unassigned', 'captioning_accepted').then(tag => {
                return client.tasks.findById('166304358745259').then(taskInfo => {
                    //Test looks at the tag in the first position of the tag array for this
                    //task,so the test may be broken if other tags are added to this task

                    // console.log('Task tag switched to:');
                    // console.log(taskInfo.tags[0]);
                    assert.strictEqual(taskInfo.tags[0].name, 'captioning_accepted', 'tag change failed');
                });
        });
    });

    it("Should change a task's tag from captioning_accepted to captioning_unassigned", function(){
        this.timeout(8000);

        return tlsAsana.switchTag('166304358745259', 'captioning_accepted', 'captioning_unassigned').then(tag => {
                return client.tasks.findById('166304358745259').then(taskInfo => {
                    //Test looks at the tag in the first position of the tag array for this
                    //task,so the test may be broken if other tags are added to this task

                    // console.log('Task tag switched to:');
                    // console.log(taskInfo.tags[0]);
                    assert.strictEqual(taskInfo.tags[0].name, 'captioning_unassigned', 'tag change failed');
                });
        });
    });

    //Test is ugly, but I was having trouble using the 'assert.throws' method with our promise structure.
    //This works as a thorough test even though it is messy
    it('Should look up an undefined tag and receive a tag error', function(){
        this.timeout(8000);

        return tlsAsana.getTagIDByName('blahblahblah').then( response => {
            assert.ok(false, 'Undefined tag did not throw an error');
        }).catch(err => {
            if ( (err instanceof Error) && /Error, no tag exists in the cache with that name/.test(err) ) {
                assert.ok(true);
            }
            else {
                assert.ok(false, 'Undefined tag did not throw an error');
            }
        });
    });

});

// describe('Creating tasks in Asana', function(){
//     it('should create a new task', function(){
//         this.timeout(8000);
//         return tlsAsana.createTask(166216691534199, 'TestTask', "Test description here', '2/2/2016', {Teacher: 'Mr. Davis',Course: 'MAAT799'}).then( response => {
//             console.log(response);
//         });
//     });
// });
<commit_msg>Improves accuracy of task unit test, and improves consistency of arrow function format<commit_after>"use strict";
let _ = require('lodash');
var assert = require('assert');
var tlsAsana = require('../index.js');
var tlsConsts = require('../tlsConstants.js');

let client = undefined;
let tlsTasks;

/**
 * Test cache so that we can make sure a refresh function is being called
 * for our caches without having to alter their production refresh times
 */
let testCache = {
    name: 'testCache',
    lastUpdated: Date.now(),
    refreshTime: 1000,
    testRefresh: function(){
        return true;
    }
};

describe('Connecting to Asana', function(){

   it('Should setup the connection', function(){
        this.timeout(8000);
        return tlsAsana.connect('166216691534199').then(function(response){
            client = response;
            assert(response,'Connection failed');
        });
   });

});

describe('Making sure the available users update', function(){
    it('Should update the workspace users', function(){
        this.timeout(8000);
        return tlsAsana.updateUsers().then( response => {
            assert(response.data[0].name, "Chris Hodge", 'Failed to update the available users');
        });
    });
})

describe('Making sure caches update', function(){

    it('Should update the tag cache', function(){
        this.timeout(8000);
        return tlsAsana.updateTagNames(10).then( response => assert.equal(response.Accepted,167304830178303,'Failed to update the tag cache') );
    });

    it('Should update the task cache', function(){
        this.timeout(8000);
        return tlsAsana.updateTasks().then(response => {
            tlsTasks = response;
            var testTask = _.filter(tlsTasks.data, ['created_at', "2016-08-26T20:13:13.727Z"]);
            assert.equal(testTask[0].id, 172981416524848, 'Failed to update task cache');
        });
    });

    it('Should get the tags associated with a task when the tasks are cached', function(){
        if(!tlsTasks){
            throw "Error, cannot check the tags associated with a task if the task cache did not update";
        }
        var testTask = _.filter(tlsTasks.data, ['created_at', "2016-08-26T20:13:13.727Z"]);
        assert.equal(testTask[0].tags[1].name,"testing",'Failed to get tags associated with tasks');
    });

    it('Should update a local cache if it is older than its set refresh time', function(){
        this.timeout(8000);
        assert(tlsAsana.checkLastCacheUpdate(testCache, testCache.testRefresh), 'Failed to update local cache');
    });

});

describe('Querying our local caches', function(){

    it('Should get information about a specific task from the local tag cache', function(){
        return tlsAsana.getTaskInfoByID(169176168459508).then( taskInfo => assert.equal(taskInfo.created_at, '2016-08-17T21:06:24.132Z', 'getting specific task info failed') );
    });

    it('Should get a cached tag id from the local tag cache', function(){
        return tlsAsana.getTagIDByName('captioning_unassigned').then( tagID => assert.equal(tagID, 167304830178312, 'Failed to get cached tag id') );
    });

    it('Should get all of the local tasks that have a certain tag', function(){
        let tagID = 167304830178312;

        return tlsAsana.getTasksByTag(tagID).then(taskArray => {
            assert.notDeepEqual(_.filter(taskArray[0].tags, x => {
                return x.id === tagID;
            }), [], 'Failed to return a task with the correct tag');
        });
    });

    it('Should get all of the local tasks that have an unassigned tag', function(){
        let unassignedTagID = 167304830178312;

        return tlsAsana.getUnassignedTasks().then(taskArray => {
            assert.notDeepEqual(_.filter(taskArray[0].tags, x => {
                return x.id === unassignedTagID;
            }), [], 'Failed to return a task with an unassigned tag');
        });
    });

    it('Should get all of the local tasks that have a new task tag', function(){
        let newTagID = 44184307053951;

        return tlsAsana.getNewTasks().then(taskArray => {
            assert.notDeepEqual(_.filter(taskArray[0].tags, x => {
                return x.id === newTagID;
            }), [], 'Failed to return a task with a new task tag');
        });
    });

});

describe('Querying Asana', function(){

    it('Should get all of the projects from Asana', function(){
        this.timeout(8000);

        return tlsAsana.getAllProjects().then( projects => assert.ok( projects.length > 0 ) );
    });

});

describe('Working with tags in Asana', function(){

    it("Should change a task's tag from captioning_unassigned to captioning_accepted", function(){
        this.timeout(8000);

        //Test looks at the tag in the first position of the tag array for this
        //task,so the test may be broken if other tags are added to this task
        return tlsAsana.switchTag('166304358745259', 'captioning_unassigned', 'captioning_accepted').then(tag => {
            return client.tasks.findById('166304358745259').then( taskInfo => assert.strictEqual(taskInfo.tags[0].name, 'captioning_accepted', 'tag change failed') );
        });
    });

    it("Should change a task's tag from captioning_accepted to captioning_unassigned", function(){
        this.timeout(8000);

        //Test looks at the tag in the first position of the tag array for this
        //task,so the test may be broken if other tags are added to this task
        return tlsAsana.switchTag('166304358745259', 'captioning_accepted', 'captioning_unassigned').then(tag => {
            return client.tasks.findById('166304358745259').then( taskInfo => assert.strictEqual(taskInfo.tags[0].name, 'captioning_unassigned', 'tag change failed') );
        });
    });

    //Test is ugly, but I was having trouble using the 'assert.throws' method with our promise structure.
    //This works as a thorough test even though it is messy
    it('Should look up an undefined tag and receive a tag error', function(){
        this.timeout(8000);

        return tlsAsana.getTagIDByName('blahblahblah').then( response => assert.ok(false, 'Undefined tag did not throw an error') )
        .catch(err => {
            if ( (err instanceof Error) && /Error, no tag exists in the cache with that name/.test(err) ) {
                assert.ok(true);
            }
            else {
                assert.ok(false, 'Undefined tag did not throw an error');
            }
        });
    });

});

// describe('Creating tasks in Asana', function(){
//     it('should create a new task', function(){
//         this.timeout(8000);
//         return tlsAsana.createTask(166216691534199, 'TestTask', "Test description here', '2/2/2016', {Teacher: 'Mr. Davis',Course: 'MAAT799'}).then( response => {
//             console.log(response);
//         });
//     });
// });
<|endoftext|>


<commit_before>import Ember from 'ember';
import { getInternalModel } from '../internal-model';
import CollectionLoader from './collection-loader';
import QueryFindMixin from '../util/query-find-mixin';
import CollectionQueryMixin from './collection-query';

const {
  A
} = Ember;

export default class InternalCollection {

  constructor(database, collectionClass, opts) {
    this.database = database;
    this.collectionClass = collectionClass;
    this.opts = opts;
    this.collectionModel = null;
    this.content = A();
    this.internalModels = database._modelIdentity.all;
    this.loader = new CollectionLoader(this);
  }

  modelClassForName(modelName) {
    if(!modelName) {
      return;
    }
    return this.database.modelClassForName(modelName, 'collection');
  }

  createCollectionModel() {
    return this.database._createCollectionForInternalCollection(this);
  }

  getCollectionModel() {
    let model = this.collectionModel;
    if(!model) {
      model = this.createCollectionModel();
      this.collectionModel = model;
    }
    return model;
  }

  //

  createQuery() {
    let collection = this.getCollectionModel();
    let queryModelName = collection.get('queryName');
    if(!queryModelName) {
      return;
    }
    let Query = this.database.get('store')._queryClassForName(queryModelName, 'collection-find', Query => {
      return Query.extend(QueryFindMixin, CollectionQueryMixin);
    });
    return Query._create({ _internalCollection: this });
  }

  getQuery() {
    let query = this.query;
    if(!query) {
      query = this.createQuery();
      this.query = query;
    }
    return query;
  }

  collectionLoaderDidLoad() {
  }

  //

  internalModelFromModel(model) {
    if(!model) {
      return null;
    }
    return getInternalModel(model);
  }

  modelFromInternalModel(internal) {
    if(!internal) {
      return null;
    }
    return internal.getModel();
  }

  //

  serialize(type) {
    if(!this.collectionModel) {
      return;
    }
    return {
      isLoaded: this.loader.state.isLoaded
    };
  }

  collectionWillDestroy() {
    this.database._onInternalCollectionDestroyed(this);
  }

}
<commit_msg>jshint<commit_after>import Ember from 'ember';
import { getInternalModel } from '../internal-model';
import CollectionLoader from './collection-loader';
import QueryFindMixin from '../util/query-find-mixin';
import CollectionQueryMixin from './collection-query';

const {
  A
} = Ember;

export default class InternalCollection {

  constructor(database, collectionClass, opts) {
    this.database = database;
    this.collectionClass = collectionClass;
    this.opts = opts;
    this.collectionModel = null;
    this.content = A();
    this.internalModels = database._modelIdentity.all;
    this.loader = new CollectionLoader(this);
  }

  modelClassForName(modelName) {
    if(!modelName) {
      return;
    }
    return this.database.modelClassForName(modelName, 'collection');
  }

  createCollectionModel() {
    return this.database._createCollectionForInternalCollection(this);
  }

  getCollectionModel() {
    let model = this.collectionModel;
    if(!model) {
      model = this.createCollectionModel();
      this.collectionModel = model;
    }
    return model;
  }

  //

  createQuery() {
    let collection = this.getCollectionModel();
    let queryModelName = collection.get('queryName');
    if(!queryModelName) {
      return;
    }
    let Query = this.database.get('store')._queryClassForName(queryModelName, 'collection-find', Query => {
      return Query.extend(QueryFindMixin, CollectionQueryMixin);
    });
    return Query._create({ _internalCollection: this });
  }

  getQuery() {
    let query = this.query;
    if(!query) {
      query = this.createQuery();
      this.query = query;
    }
    return query;
  }

  collectionLoaderDidLoad() {
  }

  //

  internalModelFromModel(model) {
    if(!model) {
      return null;
    }
    return getInternalModel(model);
  }

  modelFromInternalModel(internal) {
    if(!internal) {
      return null;
    }
    return internal.getModel();
  }

  //

  serialize() {
    if(!this.collectionModel) {
      return;
    }
    return {
      isLoaded: this.loader.state.isLoaded
    };
  }

  collectionWillDestroy() {
    this.database._onInternalCollectionDestroyed(this);
  }

}
<|endoftext|>


<commit_before>//     http://www.bizrez.com
//     (c) 2004-2014 David Mallon
//     Freely distributed under the MIT license.

/*global describe: false, it: false, require: false, console: false, before: false, after: false*/

var config = require('../config.json');
var connect = require('../db/connect');
var mongoose = require('../db/action');
var assert = require("assert");
var http = require('http');
var request = require('request');
var validate = require('validator');
var Log = require('log');
var log = new Log(config.logLevel);
log.info('test.js - Logger Set');

(function () {

    "use strict";

    var url = "http://localhost:" + config.nodePort;

    function Options() {

        return {
            url: "setURLHere",
            method: "setMethodHere",
            headers: {
                'Content-Type': 'application/json'
            },
            body: "setBodyHere"
        };
    }

    var token = null;

    // Dummy Data
    var createMock = {

        org: 'test_org',
        div: 'test_div',
        unit: 'test_unit',
        user: 'mary_test_mocha',
        isPerson: true,
        assignmentType: 'Test Assignment Type',
        status: 'Test Status',
        statusInfo: 'Test Status Info ',
        priority: 10,   // 0 - 100
        createDate: Date.now(),
        completionDate: Date.now(),
        goalDate: Date.now(),
        deadlineDate: Date.now(),
        header: 'Test Header',
        detail: 'Test Detail',
        deeplink: 'http://www.bizrez.com'

    };

    // Get token once - use on all subsequent calls
    function getToken(done) {

        var options = new Options();
        options.url = url + "/authenticate";
        options.method = "POST";
        options.body = JSON.stringify({"ownerId": "mary"});

        request(options, function (error, response, body) {
            if (!error && response.statusCode === 200) {
                var result = JSON.parse(body);
                assert.strictEqual((result.token !== ""), true);
                token = result;
                done();
            } else {
                assert.strictEqual(true, false);
                done();
            }
        });
    }

    // Begin Test Suite
    describe('Asynchronous Test Suite Biz-Status ', function () {

        // Set up the Token
        before(function (done) {
            getToken(done);
            log.debug('Token:' + token);
        });

        // Clean up
        after(function (done) {
            console.log('hack to get log.info written to buffer');
            log.debug('after - cleaning up');
            mongoose.purge({ownerId: 'mary_test_mocha'});
            done();
        });

        describe('Token Test', function (done) {

        //curl -H "Content-Type: application/json" -X POST -d '{"ownerId":"mary"}' http://localhost:3000/authenticate

            it('should return token', function (done) {
                console.dir(token);
                log.debug('token test:' + token.token);
                assert.strictEqual((token !== null), true);
                done();
            });
        });

        describe('Create Test with Token', function (done) {

        //curl -H "Content-Type: application/json" -X POST -d '{add token and data}' http://localhost:3000/status/create

            it('should return mongo id', function (done) {

                var options = new Options();
                options.url = url + "/status/create";
                options.method = "POST";

                createMock.token = token.token;
                options.body = JSON.stringify(createMock);

                request(options, function (error, response, body) {

                    if (!error && response.statusCode === 200) {
                        var result = JSON.parse(body);
                        assert.strictEqual((result.ok === 1), true);
                        //token = result;
                        done();
                    } else {
                        assert.strictEqual(true, false);
                        done();
                    }
                });

            });
        });

        describe('Read Test with Token', function (done) {

        //curl -H "Content-Type: application/json" -X POST -d '{add token and data}' http://localhost:3000/status/read

            it('should return {ok:1, json_result}', function (done) {

                var options = new Options();
                var body = {ownerId: "mary_test_mocha"};
                body.token = token.token;

                options.url = url + "/status/read";
                options.method = "POST";
                options.body = JSON.stringify(body);

                request(options, function (error, response, body) {

                    if (!error && response.statusCode === 200) {
                        var result = JSON.parse(body);
                        log.debug(body);
                        assert.strictEqual((result.ok === 1), true);
                        done();
                    } else {
                        log.debug(error);
                        assert.strictEqual(true, false);
                        done();
                    }
                });

            });
        });

        describe('Update Test with Token', function (done) {

        //curl -H "Content-Type: application/json" -X POST -d '{add token and data}' http://localhost:3000/status/update

            it('should return {ok:1}', function (done) {

                var options = new Options();
                var body = {ownerId: "mary_test_mocha"};
                body.token = token.token;
                body.query = {ownerId: "mary_test_mocha"};
                body.update = {'$set':{status:'Closed-Yahoo'}};

                options.url = url + "/status/update";
                options.method = "POST";
                options.body = JSON.stringify(body);

                request(options, function (error, response, body) {

                    if (!error && response.statusCode === 200) {
                        var result = JSON.parse(body);
                        log.debug(body);
                        assert.strictEqual((result.ok === 1), true);
                        done();
                    } else {
                        log.debug(error);
                        assert.strictEqual(true, false);
                        done();
                    }
                });

            });
        });

        describe('Paginate Test with Token', function (done) {

            it('should return {ok:1, JsonList}', function (done) {

                var options = new Options();
                var body = {};
                body.token = token.token;
                body.pageNumber = 1;

                options.url = url + "/status/paginate";
                options.method = "POST";
                options.body = JSON.stringify(body);

                request(options, function (error, response, body) {

                    log.debug("paginated");

                    if (!error && response.statusCode === 200) {
                        var result = JSON.parse(body);
                        console.log('');
                        log.debug("paginate result: " + body);
                        assert.strictEqual((result.ok === 1), true);
                        done();
                    } else {
                        log.debug(error);
                        assert.strictEqual(true, false);
                        done();
                    }

                });

            });
        });
    });

})();<commit_msg>added debug log<commit_after>//     http://www.bizrez.com
//     (c) 2004-2014 David Mallon
//     Freely distributed under the MIT license.

/*global describe: false, it: false, require: false, console: false, before: false, after: false*/

var config = require('../config.json');
var connect = require('../db/connect');
var mongoose = require('../db/action');
var assert = require("assert");
var http = require('http');
var request = require('request');
var validate = require('validator');
var Log = require('log');
var log = new Log(config.logLevel);
log.info('test.js - Logger Set');

(function () {

    "use strict";

    var url = "http://localhost:" + config.nodePort;

    function Options() {

        return {
            url: "setURLHere",
            method: "setMethodHere",
            headers: {
                'Content-Type': 'application/json'
            },
            body: "setBodyHere"
        };
    }

    var token = null;

    // Dummy Data
    var createMock = {

        org: 'test_org',
        div: 'test_div',
        unit: 'test_unit',
        user: 'mary_test_mocha',
        isPerson: true,
        assignmentType: 'Test Assignment Type',
        status: 'Test Status',
        statusInfo: 'Test Status Info ',
        priority: 10,   // 0 - 100
        createDate: Date.now(),
        completionDate: Date.now(),
        goalDate: Date.now(),
        deadlineDate: Date.now(),
        header: 'Test Header',
        detail: 'Test Detail',
        deeplink: 'http://www.bizrez.com'

    };

    // Get token once - use on all subsequent calls
    function getToken(done) {

        var options = new Options();
        options.url = url + "/authenticate";
        options.method = "POST";
        options.body = JSON.stringify({"ownerId": "mary"});

        request(options, function (error, response, body) {
            if (!error && response.statusCode === 200) {
                var result = JSON.parse(body);
                assert.strictEqual((result.token !== ""), true);
                token = result;
                done();
            } else {
                assert.strictEqual(true, false);
                done();
            }
        });
    }

    // Begin Test Suite
    describe('Asynchronous Test Suite Biz-Status ', function () {

        // Set up the Token
        before(function (done) {
            log.debug("Testing REST services using HTTP Calls");
            getToken(done);
            log.debug('Token:' + token);
        });

        // Clean up
        after(function (done) {
            console.log('hack to get log.info written to buffer');
            log.debug('after - cleaning up');
            mongoose.purge({ownerId: 'mary_test_mocha'});
            done();
        });

        describe('Token Test', function (done) {

        //curl -H "Content-Type: application/json" -X POST -d '{"ownerId":"mary"}' http://localhost:3000/authenticate

            it('should return token', function (done) {
                console.dir(token);
                log.debug('token test:' + token.token);
                assert.strictEqual((token !== null), true);
                done();
            });
        });

        describe('Create Test with Token', function (done) {

        //curl -H "Content-Type: application/json" -X POST -d '{add token and data}' http://localhost:3000/status/create

            it('should return mongo id', function (done) {

                var options = new Options();
                options.url = url + "/status/create";
                options.method = "POST";

                createMock.token = token.token;
                options.body = JSON.stringify(createMock);

                request(options, function (error, response, body) {

                    if (!error && response.statusCode === 200) {
                        var result = JSON.parse(body);
                        assert.strictEqual((result.ok === 1), true);
                        //token = result;
                        done();
                    } else {
                        assert.strictEqual(true, false);
                        done();
                    }
                });

            });
        });

        describe('Read Test with Token', function (done) {

        //curl -H "Content-Type: application/json" -X POST -d '{add token and data}' http://localhost:3000/status/read

            it('should return {ok:1, json_result}', function (done) {

                var options = new Options();
                var body = {ownerId: "mary_test_mocha"};
                body.token = token.token;

                options.url = url + "/status/read";
                options.method = "POST";
                options.body = JSON.stringify(body);

                request(options, function (error, response, body) {

                    if (!error && response.statusCode === 200) {
                        var result = JSON.parse(body);
                        log.debug(body);
                        assert.strictEqual((result.ok === 1), true);
                        done();
                    } else {
                        log.debug(error);
                        assert.strictEqual(true, false);
                        done();
                    }
                });

            });
        });

        describe('Update Test with Token', function (done) {

        //curl -H "Content-Type: application/json" -X POST -d '{add token and data}' http://localhost:3000/status/update

            it('should return {ok:1}', function (done) {

                var options = new Options();
                var body = {ownerId: "mary_test_mocha"};
                body.token = token.token;
                body.query = {ownerId: "mary_test_mocha"};
                body.update = {'$set':{status:'Closed-Yahoo'}};

                options.url = url + "/status/update";
                options.method = "POST";
                options.body = JSON.stringify(body);

                request(options, function (error, response, body) {

                    if (!error && response.statusCode === 200) {
                        var result = JSON.parse(body);
                        log.debug(body);
                        assert.strictEqual((result.ok === 1), true);
                        done();
                    } else {
                        log.debug(error);
                        assert.strictEqual(true, false);
                        done();
                    }
                });

            });
        });

        describe('Paginate Test with Token', function (done) {

            it('should return {ok:1, JsonList}', function (done) {

                var options = new Options();
                var body = {};
                body.token = token.token;
                body.pageNumber = 1;

                options.url = url + "/status/paginate";
                options.method = "POST";
                options.body = JSON.stringify(body);

                request(options, function (error, response, body) {

                    log.debug("paginated");

                    if (!error && response.statusCode === 200) {
                        var result = JSON.parse(body);
                        console.log('');
                        log.debug("paginate result: " + body);
                        assert.strictEqual((result.ok === 1), true);
                        done();
                    } else {
                        log.debug(error);
                        assert.strictEqual(true, false);
                        done();
                    }

                });

            });
        });
    });

})();<|endoftext|>


<commit_before>var dpm = require('../index')
  , util = require('../util')
  , assert = require('assert')
  ;

describe('basics', function(){
  it('findDataFiles CSV OK', function() {
    var out = dpm.findDataFiles('test/data/dp1');
    assert.deepEqual(['data.csv'], out);
  });
  it('findDataFiles GeoJSON OK', function() {
    var out = dpm.findDataFiles('test/data/dp2');
    assert.deepEqual(['data.geojson'], out);
  });
  it('createResourceEntry OK', function(done) {
    var fp = 'test/data/dp1/data.csv';
    dpm.createResourceEntry(fp, function(err, out) {
      var exp = {
        name: 'data',
        path: fp,
        format: 'csv',
        mediatype: 'text/csv',
        bytes: 48,
        schema: {
          fields: [
            {
              name: 'date',
              type: 'date',
              description: ''
            },
            {
              name: 'value',
              type: 'number',
              description: ''
            }
          ]
        }
      }
      assert.deepEqual(JSON.stringify(out, null, 2), JSON.stringify(exp, null, 2));
      done();
    });
  });
  it('createResourceEntry GeoJSON OK', function(done) {
    var fp = 'test/data/dp2/data.geojson';
    dpm.createResourceEntry(fp, function(err, out) {
      var exp = {
        name: 'data',
        path: fp,
        format: 'geojson',
        mediatype: 'application/json',
        bytes: 4
      }
      assert.deepEqual(JSON.stringify(out, null, 2), JSON.stringify(exp, null, 2));
      done();
    });
  });
  it('createResourceEntries OK', function(done) {
    dpm.createResourceEntries('test/data/dp1', function(err, out) {
      assert.equal(out.length, 1);
      assert.equal(out[0].name, 'data');
      done();
    });
  });
});

<commit_msg>[test][xs]: remove left in require for util.js (which had been removed).<commit_after>var dpm = require('../index')
  , assert = require('assert')
  ;

describe('basics', function(){
  it('findDataFiles CSV OK', function() {
    var out = dpm.findDataFiles('test/data/dp1');
    assert.deepEqual(['data.csv'], out);
  });
  it('findDataFiles GeoJSON OK', function() {
    var out = dpm.findDataFiles('test/data/dp2');
    assert.deepEqual(['data.geojson'], out);
  });
  it('createResourceEntry OK', function(done) {
    var fp = 'test/data/dp1/data.csv';
    dpm.createResourceEntry(fp, function(err, out) {
      var exp = {
        name: 'data',
        path: fp,
        format: 'csv',
        mediatype: 'text/csv',
        bytes: 48,
        schema: {
          fields: [
            {
              name: 'date',
              type: 'date',
              description: ''
            },
            {
              name: 'value',
              type: 'number',
              description: ''
            }
          ]
        }
      }
      assert.deepEqual(JSON.stringify(out, null, 2), JSON.stringify(exp, null, 2));
      done();
    });
  });
  it('createResourceEntry GeoJSON OK', function(done) {
    var fp = 'test/data/dp2/data.geojson';
    dpm.createResourceEntry(fp, function(err, out) {
      var exp = {
        name: 'data',
        path: fp,
        format: 'geojson',
        mediatype: 'application/json',
        bytes: 4
      }
      assert.deepEqual(JSON.stringify(out, null, 2), JSON.stringify(exp, null, 2));
      done();
    });
  });
  it('createResourceEntries OK', function(done) {
    dpm.createResourceEntries('test/data/dp1', function(err, out) {
      assert.equal(out.length, 1);
      assert.equal(out[0].name, 'data');
      done();
    });
  });
});

<|endoftext|>


<commit_before>var map;
var markers;
var popup;

OpenLayers._getScriptLocation = function () {
   return "/openlayers/";
}

function createMap(divName) {
   map = new OpenLayers.Map(divName, {
      controls: [
         new OpenLayers.Control.ArgParser(),
         new OpenLayers.Control.Attribution(),
         new OpenLayers.Control.LayerSwitcher(),
         new OpenLayers.Control.Navigation(),
         new OpenLayers.Control.PanZoomBar()
      ]
   });

   var mapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik", { displayOutsideMaxExtent: true });
   map.addLayer(mapnik);

   var osmarender = new OpenLayers.Layer.OSM.Osmarender("Osmarender", { displayOutsideMaxExtent: true });
   map.addLayer(osmarender);

   var maplint = new OpenLayers.Layer.OSM.Maplint("Maplint", { displayOutsideMaxExtent: true });
   map.addLayer(maplint);

   var numZoomLevels = Math.max(mapnik.numZoomLevels, osmarender.numZoomLevels);
   markers = new OpenLayers.Layer.Markers("Markers", {
      displayInLayerSwitcher: false, numZoomLevels: numZoomLevels,
      maxExtent: new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508),
      maxResolution: 156543,
      units: "m",
      projection: "EPSG:41001"
   });
   map.addLayer(markers);

   return map;
}

function getArrowIcon() {
   var size = new OpenLayers.Size(25, 22);
   var offset = new OpenLayers.Pixel(-30, -27);
   var icon = new OpenLayers.Icon("/images/arrow.png", size, offset);

   return icon;
}

function addMarkerToMap(position, icon, description) {
   var marker = new OpenLayers.Marker(position, icon);

   markers.addMarker(marker);

   if (description) {
      marker.events.register("click", marker, function() { openMapPopup(marker, description) });
   }

   return marker;
}

function openMapPopup(marker, description) {
   closeMapPopup();

   popup = new OpenLayers.Popup.AnchoredBubble("popup", marker.lonlat,
                                               sizeMapPopup(description),
                                               "
" + description + "
",
                                               marker.icon, true);
   popup.setBackgroundColor("#E3FFC5");
   map.addPopup(popup);

   return popup;
}

function closeMapPopup() {
   if (popup) {
      map.removePopup(popup);
      delete popup;
   }
}

function sizeMapPopup(text) {
   var box = document.createElement("div");

   box.innerHTML = text;
   box.style.visibility = "hidden";
   box.style.position = "absolute";
   box.style.top = "0px";
   box.style.left = "0px";
   box.style.width = "200px";
   box.style.height = "auto";

   document.body.appendChild(box);

   var width = box.offsetWidth;
   var height = box.offsetHeight;

   document.body.removeChild(box);

   return new OpenLayers.Size(width + 30, height + 24);
}

function removeMarkerFromMap(marker){
   markers.removeMarker(marker);
}

function getMapLayers() {
   var layers = "";

   for (var i=0; i< this.map.layers.length; i++) {
      var layer = this.map.layers[i];

      if (layer.isBaseLayer) {
         layers += (layer == this.map.baseLayer) ? "B" : "0";
      } else {
         layers += (layer.getVisibility()) ? "T" : "F";
      }
   }

   return layers;
}

function setMapLayers(layers) {
   for (var i=0; i < layers.length; i++) {
      var layer = map.layers[i];
      var c = layers.charAt(i);

      if (c == "B") {
         map.setBaseLayer(layer);
      } else if ( (c == "T") || (c == "F") ) {
         layer.setVisibility(c == "T");
      }
   }
}

function mercatorToLonLat(merc) {
   var lon = (merc.lon / 20037508.34) * 180;
   var lat = (merc.lat / 20037508.34) * 180;

   lat = 180/Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2);

   return new OpenLayers.LonLat(lon, lat);
}

function lonLatToMercator(ll) {
   var lon = ll.lon * 20037508.34 / 180;
   var lat = Math.log(Math.tan((90 + ll.lat) * Math.PI / 360)) / (Math.PI / 180);

   lat = lat * 20037508.34 / 180;

   return new OpenLayers.LonLat(lon, lat);
}

function scaleToZoom(scale) {
   return Math.log(360.0/(scale * 512.0)) / Math.log(2.0);
}
<commit_msg>Turn on wrapDateLine for all layers. Also correct the declared projection for the markers layer.<commit_after>var map;
var markers;
var popup;

OpenLayers._getScriptLocation = function () {
   return "/openlayers/";
}

function createMap(divName) {
   map = new OpenLayers.Map(divName, {
      controls: [
         new OpenLayers.Control.ArgParser(),
         new OpenLayers.Control.Attribution(),
         new OpenLayers.Control.LayerSwitcher(),
         new OpenLayers.Control.Navigation(),
         new OpenLayers.Control.PanZoomBar()
      ]
   });

   var mapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik", {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(mapnik);

   var osmarender = new OpenLayers.Layer.OSM.Osmarender("Osmarender", {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(osmarender);

   var maplint = new OpenLayers.Layer.OSM.Maplint("Maplint", {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(maplint);

   var numZoomLevels = Math.max(mapnik.numZoomLevels, osmarender.numZoomLevels);
   markers = new OpenLayers.Layer.Markers("Markers", {
      displayInLayerSwitcher: false,
      numZoomLevels: numZoomLevels,
      maxExtent: new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508),
      maxResolution: 156543,
      units: "m",
      projection: "EPSG:900913",
   });
   map.addLayer(markers);

   return map;
}

function getArrowIcon() {
   var size = new OpenLayers.Size(25, 22);
   var offset = new OpenLayers.Pixel(-30, -27);
   var icon = new OpenLayers.Icon("/images/arrow.png", size, offset);

   return icon;
}

function addMarkerToMap(position, icon, description) {
   var marker = new OpenLayers.Marker(position, icon);

   markers.addMarker(marker);

   if (description) {
      marker.events.register("click", marker, function() { openMapPopup(marker, description) });
   }

   return marker;
}

function openMapPopup(marker, description) {
   closeMapPopup();

   popup = new OpenLayers.Popup.AnchoredBubble("popup", marker.lonlat,
                                               sizeMapPopup(description),
                                               "
" + description + "
",
                                               marker.icon, true);
   popup.setBackgroundColor("#E3FFC5");
   map.addPopup(popup);

   return popup;
}

function closeMapPopup() {
   if (popup) {
      map.removePopup(popup);
      delete popup;
   }
}

function sizeMapPopup(text) {
   var box = document.createElement("div");

   box.innerHTML = text;
   box.style.visibility = "hidden";
   box.style.position = "absolute";
   box.style.top = "0px";
   box.style.left = "0px";
   box.style.width = "200px";
   box.style.height = "auto";

   document.body.appendChild(box);

   var width = box.offsetWidth;
   var height = box.offsetHeight;

   document.body.removeChild(box);

   return new OpenLayers.Size(width + 30, height + 24);
}

function removeMarkerFromMap(marker){
   markers.removeMarker(marker);
}

function getMapLayers() {
   var layers = "";

   for (var i=0; i< this.map.layers.length; i++) {
      var layer = this.map.layers[i];

      if (layer.isBaseLayer) {
         layers += (layer == this.map.baseLayer) ? "B" : "0";
      } else {
         layers += (layer.getVisibility()) ? "T" : "F";
      }
   }

   return layers;
}

function setMapLayers(layers) {
   for (var i=0; i < layers.length; i++) {
      var layer = map.layers[i];
      var c = layers.charAt(i);

      if (c == "B") {
         map.setBaseLayer(layer);
      } else if ( (c == "T") || (c == "F") ) {
         layer.setVisibility(c == "T");
      }
   }
}

function mercatorToLonLat(merc) {
   var lon = (merc.lon / 20037508.34) * 180;
   var lat = (merc.lat / 20037508.34) * 180;

   lat = 180/Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2);

   return new OpenLayers.LonLat(lon, lat);
}

function lonLatToMercator(ll) {
   var lon = ll.lon * 20037508.34 / 180;
   var lat = Math.log(Math.tan((90 + ll.lat) * Math.PI / 360)) / (Math.PI / 180);

   lat = lat * 20037508.34 / 180;

   return new OpenLayers.LonLat(lon, lat);
}

function scaleToZoom(scale) {
   return Math.log(360.0/(scale * 512.0)) / Math.log(2.0);
}
<|endoftext|>