<commit_before>(function () {
    "use strict";

    var levelWidth = window.innerWidth;
    var levelHeight = window.innerHeight;

    // Setup pixi.
    var stage = new PIXI.Container();
    var renderer = PIXI.autoDetectRenderer(levelWidth, levelHeight);
    document.body.appendChild(renderer.view);

    // Setup world.
    var world = new hitagi.World();

    // Setup controls.
    var controls = new hitagi.Controls();
    controls.bind('m1', 'flap');

    // Register systems.
    var renderSystem = new hitagi.systems.PixiRenderSystem(stage);
    world.register(renderSystem);
    renderSystem.load(['flappybird.png', 'pipe.png', 'floor.png'], function () {

    var velocitySystem = new hitagi.systems.VelocitySystem();
    world.register(velocitySystem);

    var collisionSystem = new hitagi.systems.CollisionSystem();
    world.register(collisionSystem);

    var GravitySystem = function () {
        this.update = {
            gravity: function (entity, dt) {
                if (entity.c.velocity.yspeed < entity.c.gravity.terminal) {
                    entity.c.velocity.yspeed += hitagi.utils.delta(entity.c.gravity.magnitude, dt);
                }
            }
        };
    };
    world.register(new GravitySystem());

    var BirdSystem = function (world, controls, collisionSystem) {
        var that = this;
        var savedState;

        this.saveState = function () {
            savedState = world.save();
        };

        this.loadState = function () {
            world.clear();
            world.load(savedState);
        };

        var score = null;

        this.build = {
            score: function (entity) {
                score = entity;
            }
        };

        this.update = {
            bird: function (entity, dt) {
                if (controls.check('flap', true)) {
                    entity.c.velocity.yspeed = -entity.c.bird.flapSpeed;
                }

                var x = entity.c.position.x;
                var y = entity.c.position.y;
                var test;

                test = collisionSystem.collide(entity, 'kill', x, y);
                if (test.hit) {
                    that.loadState();
                    return;
                }

                if (score) {
                    test = collisionSystem.collide(entity, 'goal', x, y);
                    if (test.hit) {
                        if (!test.entity.c.goal.done) {
                            test.entity.c.goal.done = true;
                            console.log('goal ' + test.entity.c.goal.n + ' reached!');
                            score.c.cleared = test.entity.c.goal.n;
                            score.c.graphic.copy = test.entity.c.goal.n;
                        }
                    }
                }

                entity.c.graphic.rotation = entity.c.velocity.yspeed/15;

                if (entity.c.position.y < 0) {
                    entity.c.position.y = 0;
                    entity.c.velocity.yspeed = 0;
                }

                if (entity.c.position.y > levelHeight) {
                    that.loadState();
                }
            }
        };
    };
    var birdSystem = new BirdSystem(world, controls, collisionSystem);
    world.register(birdSystem);

    // Pipe stuff.
    var Pipe = function (params) {
        var pipe = new hitagi.Entity()
            .attach(new hitagi.components.Position({x: levelWidth + 200, y: params.y}))
            .attach(new hitagi.components.Velocity({xspeed: -5, yspeed: 0}))
            .attach(new hitagi.components.Graphic({
                type:'sprite',
                path: 'pipe.png',
                scale: {
                    x: 1,
                    y: params.yscale
                },
                z: 10
            }))
            .attach(new hitagi.components.Collision({
                height: 793,
                width: 138
            }))
            .attach({id: 'pipe'})
            .attach({id: 'kill'});

        return pipe;
    };

    var Goal = function (params) {
        return new hitagi.Entity()
            .attach(new hitagi.components.Position({
                x: levelWidth + 200,
                y: params.y
            }))
            .attach(new hitagi.components.Velocity({
                xspeed: -5,
                yspeed: 0
            }))
            .attach(new hitagi.components.Collision({
                width: params.width,
                height: params.height
            }))
            .attach({
                id: 'goal',
                n: params.n,
                done: false
            });
    };

    var PipeSystem = function (world) {
        this.update = {
            pipe: function (entity) {
                if (entity.c.position.x < -100) {
                    world.remove(entity);
                }
            },

            score: function (entity) {
                // Update timer.
                entity.c.score.pipeTimer--;

                // Update pipes made count.
                entity.c.score.pipesMade++;

                // Generate pipes if they're ready.
                if (entity.c.score.pipeTimer <= 0) {
                    entity.c.score.pipeTimer = entity.c.score.pipeTimerMax;

                    var pipeHeight = 793;
                    var pipeGap = 120;
                    var minimumTopDistance = 200;
                    var offset = Math.random() * (pipeHeight/2) - minimumTopDistance;

                    world.add(
                        new Pipe({
                            y: -offset,
                            yscale: -1
                        })
                    );
                    world.add(
                        new Pipe({
                            y: pipeHeight + pipeGap - offset,
                            yscale: 1
                        })
                    );
                    world.add(new Goal({
                        width: 60,
                        height: pipeGap,
                        y: pipeHeight/2 + pipeGap/2 - offset,
                        n: entity.c.score.pipesMade
                    }));
                }
            }
        };
    };
    world.register(new PipeSystem(world));

    var FloorSystem = function () {
        this.update = {
            floor: function (entity) {
                if (entity.c.position.x <= -154) {
                    entity.c.position.x = 308 * 11;
                }
            }
        };
    };
    world.register(new FloorSystem(world));

    // Add entities.
    var player = world.add(
        new hitagi.Entity()
            .attach(new hitagi.components.Position({x: 320, y: levelHeight/2}))
            .attach(new hitagi.components.Velocity({xspeed: 0, yspeed: 0}))
            .attach(new hitagi.components.Graphic({
                type: 'sprite',
                path: 'flappybird.png'
            }))
            .attach({
                id: 'gravity',
                magnitude: 0.6,
                terminal: 12
            })
            .attach({
                id: 'bird',
                flapSpeed: 10
            })
            .attach(new hitagi.components.Collision({
                height: 18,
                width: 32
            }))
    );

    var background = world.add(
        new hitagi.Entity()
            .attach(new hitagi.components.Position({x: levelWidth/2, y: levelHeight/2}))
            .attach(new hitagi.components.Graphic({
                type: 'rectangle',
                color: 0X139BC9,
                height: levelHeight,
                width: levelWidth,
                z: -100
            }))
    );

    var score = world.add(
        new hitagi.Entity()
            .attach(new hitagi.components.Position({x: 25, y: 10}))
            .attach(new hitagi.components.Graphic({
                type: 'text',
                copy: '0',
                options: {
                    font: '128px Arial',
                    fill: 'white'
                },
                z: Infinity
            }))
            .attach({
                id: 'score',
                pipeTimer: 0,
                pipeTimerMax: 85,
                pipesMade: 0,
                cleared: 0
            })
    );

    for (var i = 0; i < 12; i++) {
        world.add(
            new hitagi.Entity()
                .attach(new hitagi.components.Position({
                    x: 308 * i,
                    y: levelHeight - 108/2
                }))
                .attach(new hitagi.components.Velocity({
                    xspeed: -5,
                    yspeed: 0
                }))
                .attach(new hitagi.components.Graphic({
                    type: 'sprite',
                    path: 'floor.png',
                    z: 1000
                }))
                .attach(new hitagi.components.Collision({
                    height: 108,
                    width: 308
                }))
                .attach({id: 'floor'})
                .attach({id: 'kill'})
        );
    }
    // Save a clean state for reloading the game.
    birdSystem.saveState();

    // Setup game loop.
    requestAnimationFrame(animate);

    function animate() {
        // Update the world.
        world.tick(1000);

        // Render the world.
        renderer.render(stage);

        // Next frame.
        requestAnimationFrame(animate);
    }
});

} ());
<commit_msg>Fix Flappy Bird example timer glitch<commit_after>(function () {
    "use strict";

    var levelWidth = window.innerWidth;
    var levelHeight = window.innerHeight;

    // Setup pixi.
    var stage = new PIXI.Container();
    var renderer = PIXI.autoDetectRenderer(levelWidth, levelHeight);
    document.body.appendChild(renderer.view);

    // Setup world.
    var world = new hitagi.World();

    // Setup controls.
    var controls = new hitagi.Controls();
    controls.bind('m1', 'flap');

    // Register systems.
    var renderSystem = new hitagi.systems.PixiRenderSystem(stage);
    world.register(renderSystem);
    renderSystem.load(['flappybird.png', 'pipe.png', 'floor.png'], function () {

    var velocitySystem = new hitagi.systems.VelocitySystem();
    world.register(velocitySystem);

    var collisionSystem = new hitagi.systems.CollisionSystem();
    world.register(collisionSystem);

    var GravitySystem = function () {
        this.update = {
            gravity: function (entity, dt) {
                if (entity.c.velocity.yspeed < entity.c.gravity.terminal) {
                    entity.c.velocity.yspeed += hitagi.utils.delta(entity.c.gravity.magnitude, dt);
                }
            }
        };
    };
    world.register(new GravitySystem());

    var BirdSystem = function (world, controls, collisionSystem) {
        var that = this;
        var savedState;

        this.saveState = function () {
            savedState = world.save();
        };

        this.loadState = function () {
            world.clear();
            world.load(savedState);
        };

        var score = null;

        this.build = {
            score: function (entity) {
                score = entity;
            }
        };

        this.update = {
            bird: function (entity, dt) {
                if (controls.check('flap', true)) {
                    entity.c.velocity.yspeed = -entity.c.bird.flapSpeed;
                }

                var x = entity.c.position.x;
                var y = entity.c.position.y;
                var test;

                test = collisionSystem.collide(entity, 'kill', x, y);
                if (test.hit) {
                    that.loadState();
                    return;
                }

                if (score) {
                    test = collisionSystem.collide(entity, 'goal', x, y);
                    if (test.hit) {
                        if (!test.entity.c.goal.done) {
                            test.entity.c.goal.done = true;
                            console.log('goal ' + test.entity.c.goal.n + ' reached!');
                            score.c.cleared = test.entity.c.goal.n;
                            score.c.graphic.copy = test.entity.c.goal.n;
                        }
                    }
                }

                entity.c.graphic.rotation = entity.c.velocity.yspeed/15;

                if (entity.c.position.y < 0) {
                    entity.c.position.y = 0;
                    entity.c.velocity.yspeed = 0;
                }

                if (entity.c.position.y > levelHeight) {
                    that.loadState();
                }
            }
        };
    };
    var birdSystem = new BirdSystem(world, controls, collisionSystem);
    world.register(birdSystem);

    // Pipe stuff.
    var Pipe = function (params) {
        var pipe = new hitagi.Entity()
            .attach(new hitagi.components.Position({x: levelWidth + 200, y: params.y}))
            .attach(new hitagi.components.Velocity({xspeed: -5, yspeed: 0}))
            .attach(new hitagi.components.Graphic({
                type:'sprite',
                path: 'pipe.png',
                scale: {
                    x: 1,
                    y: params.yscale
                },
                z: 10
            }))
            .attach(new hitagi.components.Collision({
                height: 793,
                width: 138
            }))
            .attach({id: 'pipe'})
            .attach({id: 'kill'});

        return pipe;
    };

    var Goal = function (params) {
        return new hitagi.Entity()
            .attach(new hitagi.components.Position({
                x: levelWidth + 200,
                y: params.y
            }))
            .attach(new hitagi.components.Velocity({
                xspeed: -5,
                yspeed: 0
            }))
            .attach(new hitagi.components.Collision({
                width: params.width,
                height: params.height
            }))
            .attach({
                id: 'goal',
                n: params.n,
                done: false
            });
    };

    var PipeSystem = function (world) {
        this.update = {
            pipe: function (entity) {
                if (entity.c.position.x < -100) {
                    world.remove(entity);
                }
            },

            score: function (entity) {
                // Update timer.
                entity.c.score.pipeTimer--;

                // Generate pipes if they're ready.
                if (entity.c.score.pipeTimer <= 0) {
                    entity.c.score.pipeTimer = entity.c.score.pipeTimerMax;

                    var pipeHeight = 793;
                    var pipeGap = 120;
                    var minimumTopDistance = 200;
                    var offset = Math.random() * (pipeHeight/2) - minimumTopDistance;

                    // Update pipes made count.
                    entity.c.score.pipesMade++;

                    world.add(
                        new Pipe({
                            y: -offset,
                            yscale: -1
                        })
                    );
                    world.add(
                        new Pipe({
                            y: pipeHeight + pipeGap - offset,
                            yscale: 1
                        })
                    );
                    world.add(new Goal({
                        width: 60,
                        height: pipeGap,
                        y: pipeHeight/2 + pipeGap/2 - offset,
                        n: entity.c.score.pipesMade
                    }));
                }
            }
        };
    };
    world.register(new PipeSystem(world));

    var FloorSystem = function () {
        this.update = {
            floor: function (entity) {
                if (entity.c.position.x <= -154) {
                    entity.c.position.x = 308 * 11;
                }
            }
        };
    };
    world.register(new FloorSystem(world));

    // Add entities.
    var player = world.add(
        new hitagi.Entity()
            .attach(new hitagi.components.Position({x: 320, y: levelHeight/2}))
            .attach(new hitagi.components.Velocity({xspeed: 0, yspeed: 0}))
            .attach(new hitagi.components.Graphic({
                type: 'sprite',
                path: 'flappybird.png'
            }))
            .attach({
                id: 'gravity',
                magnitude: 0.6,
                terminal: 12
            })
            .attach({
                id: 'bird',
                flapSpeed: 10
            })
            .attach(new hitagi.components.Collision({
                height: 18,
                width: 32
            }))
    );

    var background = world.add(
        new hitagi.Entity()
            .attach(new hitagi.components.Position({x: levelWidth/2, y: levelHeight/2}))
            .attach(new hitagi.components.Graphic({
                type: 'rectangle',
                color: 0X139BC9,
                height: levelHeight,
                width: levelWidth,
                z: -100
            }))
    );

    var score = world.add(
        new hitagi.Entity()
            .attach(new hitagi.components.Position({x: 25, y: 10}))
            .attach(new hitagi.components.Graphic({
                type: 'text',
                copy: '0',
                options: {
                    font: '128px Arial',
                    fill: 'white'
                },
                z: Infinity
            }))
            .attach({
                id: 'score',
                pipeTimer: 0,
                pipeTimerMax: 85,
                pipesMade: 0,
                cleared: 0
            })
    );

    for (var i = 0; i < 12; i++) {
        world.add(
            new hitagi.Entity()
                .attach(new hitagi.components.Position({
                    x: 308 * i,
                    y: levelHeight - 108/2
                }))
                .attach(new hitagi.components.Velocity({
                    xspeed: -5,
                    yspeed: 0
                }))
                .attach(new hitagi.components.Graphic({
                    type: 'sprite',
                    path: 'floor.png',
                    z: 1000
                }))
                .attach(new hitagi.components.Collision({
                    height: 108,
                    width: 308
                }))
                .attach({id: 'floor'})
                .attach({id: 'kill'})
        );
    }
    // Save a clean state for reloading the game.
    birdSystem.saveState();

    // Setup game loop.
    requestAnimationFrame(animate);

    function animate() {
        // Update the world.
        world.tick(1000);

        // Render the world.
        renderer.render(stage);

        // Next frame.
        requestAnimationFrame(animate);
    }
});

} ());
<|endoftext|>


<commit_before>//Require JS for node
//otherwise just make sure that the browser version loads before this file.
if(typeof process !== "undefined"){
	var requirejs = require('requirejs');
	var define = requirejs.define;
	var _Noodles = require('./../lib');
}

define(function(require, exports, module){
//get Noodles, the blank concat is to preven requirejs from getting too smart on us.
var Noodles = typeof _Noodles === "undefined" ? require(''+'./../../lib/browser-index') : _Noodles;
/*--exports--
name:Plugin
description:Plugin Class implementation
@type{Noodles.Plugin}
*/
exports.Plugin = new Noodles.Plugin({
	/*--settag--
	name:willHandle
	description:array of tags that the coretags plugin will handle
	@param{Noodles.Template}
	@return {array}
	*/
	willHandle : function(Template){
		return [Template.language.tag('set'),Template.language.tag('setalist'),Template.language.tag('setahash')];
	},
	/*--settag--
	name:pluginName
	@type{string}
	*/
	pluginName : 'settag',
	/*--settag--
	name:browserFriendly
	description:is this plugin browser friendly?
	*/
	browserFriendly: true,
	/*--settag--
	name:onTemplateCreate
	description:executed on template creation
	@param{Noodles.Template}
	*/
	onTemplateCreate : function(Context,Template){},
	/*--settag--
	name:onTemplateExecute
	description:executed when template is run
	@param{Noodles.Context}
	@param{Noodles.Template}
	*/
	onTemplateExecute : function(Context, Template){},
	/*--settag--
	name:handleToken
	description:executed when any tag in "willHandle" is found
	@param{Noodles.Template}
	@param{string}
	@param{string}
	*/
	handleToken : function(Template, expression, tag){
		switch(tag){
			case Template.language.tag('set'):
				return new Set(Template,expression);
			case Template.language.tag('setalist'):
				console.log('case met!');
				return new SetList(Template,expression);
			case Template.language.tag('setahash'):
				return new SetHash(Template,expression);
			default:
				return {skip:true};
		}
	}
});
/*--module--
name: Set
description: Set execution
@param {Noodles.Template}
@param {expression}
*/
var Set = function(Template,expression){
	this.needs = {};
	expression = expression.split(' ');
	if(expression.length < 4){
		this.skip = true;
		Noodles.Utilities.warning(Template,'Set tag has bad syntax');
		return;
	}
	var temp = Noodles.Utilities.parseType(Template,expression[1]);
	if(temp.type !== "object"){
		this.skip = true;
		Noodles.Utilities.warning(Template,'Set tag has bad syntax');
		return;
	}
	this.key = temp;

	if(this.key.order.length > 1){
		this.needs = Noodles.Utilities.mergeObjectWith(this.needs,this.key.needs);
	}
	else{
		this.sets = {};
		this.sets[this.key.order[0]] = true;
	}
	this.modifies = {};
	this.modifies[this.key.order[0]] = true;

	this.value = Noodles.Utilities.parseType(Template,expression[3]);
	this.needs = Noodles.Utilities.mergeObjectWith(this.needs,this.value.needs);
};
/*--Set--
name: execute
description: Set execution
@param {Noodles.Template}
@param {Noodles.Context}
@param {function=}
*/
Set.prototype.execute = function(Template,Context){
	this.key.set(Template,Context,this.value);
	return '';
};
/*--module--
name: SetList
description: List object set method
@param {Noodles.Template}
@param {expression}
*/
var SetList = function(Template,expression){
	this.needs = {};
	var reListSplit = /^setalist\s+([^=]+)\s*=\s*(.+)/,
		obj,list,item;
	if(!reListSplit.test(expression)){
		this.skip = true;
		Noodles.Utilities.warning(Template,'Setalist tag has bad syntax');
		return;
	}
	expression = reListSplit.exec(expression)
	obj = Noodles.Utilities.parseType(Template,expression[1]);

	if(obj.type !== "object"){
		this.skip = true;
		Noodles.Utilities.warning(Template,'Setalist tag has bad syntax');
		return;
	}
	this.key = obj;

	if(this.key.order.length > 1){
		this.needs = Noodles.Utilities.mergeObjectWith(this.needs,this.key.needs);
	}
	else{
		this.sets = {};
		this.sets[this.key.order[0]] = true;
	}
	this.modifies = {};
	this.modifies[this.key.order[0]] = true;
	list = expression[2].split(',');
	for(var i = 0, l= list.length; i < l; i++){
		list[i] = Noodles.Utilities.parseType(Template,list[i].trim());
		this.needs = Noodles.Utilities.mergeObjectWith(this.needs,list[i].needs);
	}
	this.value = list;
};
/*--SetList--
name: execute
description: SetList execution
@param {Noodles.Template}
@param {Noodles.Context}
@param {function=}
*/
SetList.prototype.execute = function(Template,Context){
	this.key.set(Template,Context,this.value);
	return '';
};
});<commit_msg>added setahash tag functionality<commit_after>//Require JS for node
//otherwise just make sure that the browser version loads before this file.
if(typeof process !== "undefined"){
	var requirejs = require('requirejs');
	var define = requirejs.define;
	var _Noodles = require('./../lib');
}

define(function(require, exports, module){
//get Noodles, the blank concat is to preven requirejs from getting too smart on us.
var Noodles = typeof _Noodles === "undefined" ? require(''+'./../../lib/browser-index') : _Noodles;
/*--exports--
name:Plugin
description:Plugin Class implementation
@type{Noodles.Plugin}
*/
exports.Plugin = new Noodles.Plugin({
	/*--settag--
	name:willHandle
	description:array of tags that the coretags plugin will handle
	@param{Noodles.Template}
	@return {array}
	*/
	willHandle : function(Template){
		return [Template.language.tag('set'),Template.language.tag('setalist'),Template.language.tag('setahash')];
	},
	/*--settag--
	name:pluginName
	@type{string}
	*/
	pluginName : 'settag',
	/*--settag--
	name:browserFriendly
	description:is this plugin browser friendly?
	*/
	browserFriendly: true,
	/*--settag--
	name:onTemplateCreate
	description:executed on template creation
	@param{Noodles.Template}
	*/
	onTemplateCreate : function(Context,Template){},
	/*--settag--
	name:onTemplateExecute
	description:executed when template is run
	@param{Noodles.Context}
	@param{Noodles.Template}
	*/
	onTemplateExecute : function(Context, Template){},
	/*--settag--
	name:handleToken
	description:executed when any tag in "willHandle" is found
	@param{Noodles.Template}
	@param{string}
	@param{string}
	*/
	handleToken : function(Template, expression, tag){
		switch(tag){
			case Template.language.tag('set'):
				return new Set(Template,expression);
			case Template.language.tag('setalist'):
				console.log('case met!');
				return new SetList(Template,expression);
			case Template.language.tag('setahash'):
				return new SetHash(Template,expression);
			default:
				return {skip:true};
		}
	}
});
/*--module--
name: Set
description: Set execution
@param {Noodles.Template}
@param {expression}
*/
var Set = function(Template,expression){
	this.needs = {};
	expression = expression.split(' ');
	if(expression.length < 4){
		this.skip = true;
		Noodles.Utilities.warning(Template,'Set tag has bad syntax');
		return;
	}
	var temp = Noodles.Utilities.parseType(Template,expression[1]);
	if(temp.type !== "object"){
		this.skip = true;
		Noodles.Utilities.warning(Template,'Set tag has bad syntax, the variable must be an identifier or object');
		return;
	}
	this.key = temp;

	if(this.key.order.length > 1){
		this.needs = Noodles.Utilities.mergeObjectWith(this.needs,this.key.needs);
	}
	else{
		this.sets = {};
		this.sets[this.key.order[0]] = true;
	}
	this.modifies = {};
	this.modifies[this.key.order[0]] = true;

	this.value = Noodles.Utilities.parseType(Template,expression[3]);
	this.needs = Noodles.Utilities.mergeObjectWith(this.needs,this.value.needs);
};
/*--Set--
name: execute
description: Set execution
@param {Noodles.Template}
@param {Noodles.Context}
@param {function=}
*/
Set.prototype.execute = function(Template,Context){
	this.key.set(Template,Context,this.value);
	return '';
};
/*--module--
name: SetList
description: List object set method
@param {Noodles.Template}
@param {expression}
*/
var SetList = function(Template,expression){
	this.needs = {};
	var reListSplit = /^setalist\s+([^=]+)\s*=\s*(.+)/,
		obj,list,item;
	if(!reListSplit.test(expression)){
		this.skip = true;
		Noodles.Utilities.warning(Template,'Setalist tag has bad syntax');
		return;
	}
	expression = reListSplit.exec(expression)
	obj = Noodles.Utilities.parseType(Template,expression[1]);

	if(obj.type !== "object"){
		this.skip = true;
		Noodles.Utilities.warning(Template,'Setalist tag has bad syntax, the variable must be an identifier or object');
		return;
	}
	this.key = obj;

	if(this.key.order.length > 1){
		this.needs = Noodles.Utilities.mergeObjectWith(this.needs,this.key.needs);
	}
	else{
		this.sets = {};
		this.sets[this.key.order[0]] = true;
	}
	this.modifies = {};
	this.modifies[this.key.order[0]] = true;
	list = expression[2].split(',');
	for(var i = 0, l= list.length; i < l; i++){
		list[i] = Noodles.Utilities.parseType(Template,list[i].trim());
		this.needs = Noodles.Utilities.mergeObjectWith(this.needs,list[i].needs);
	}
	this.value = list;
};
/*--SetList--
name: execute
description: SetList execution
@param {Noodles.Template}
@param {Noodles.Context}
@param {function=}
*/
SetList.prototype.execute = function(Template,Context){
	this.key.set(Template,Context,this.value);
	return '';
};
/*--module--
name: SetHash
description: Hash object set method
@param {Noodles.Template}
@param {expression}
*/
var SetHash = function(Template,expression){
	this.needs = {};
	var reHashSplit = /^setahash\s+([^=]+)\s*=\s*(.+)/,
		hashObject =  {},
		obj,hash,value;
	if(!reHashSplit.test(expression)){
		this.skip = true;
		Noodles.Utilities.warning(Template,'Setahash tag has bad syntax');
		return;
	}
	expression = reHashSplit.exec(expression)
	obj = Noodles.Utilities.parseType(Template,expression[1]);

	if(obj.type !== "object"){
		this.skip = true;
		Noodles.Utilities.warning(Template,'Setahash tag has bad syntax, the variable must be an identifier or object');
		return;
	}
	this.key = obj;

	if(this.key.order.length > 1){
		this.needs = Noodles.Utilities.mergeObjectWith(this.needs,this.key.needs);
	}
	else{
		this.sets = {};
		this.sets[this.key.order[0]] = true;
	}
	this.modifies = {};
	this.modifies[this.key.order[0]] = true;

	hash = expression[2].split(',');
	for(var i = 0, l= hash.length; i < l; i++){
		hash[i] = hash[i].split(':');
		value = hash[i][0].trim().toLowerCase();
		hashObject[value] = Noodles.Utilities.parseType(Template,hash[i][1].trim())
		this.needs = Noodles.Utilities.mergeObjectWith(this.needs,hashObject[value].needs);
	}
	this.value = hashObject;
};
/*--SetHash--
name: execute
description: SetHash execution
@param {Noodles.Template}
@param {Noodles.Context}
@param {function=}
*/
SetHash.prototype.execute = function(Template,Context){
	this.key.set(Template,Context,this.value);
	return '';
};
});<|endoftext|>


<commit_before>/**
 *
 * Copyright 2016, Institute for Systems Biology
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

require.config({
    baseUrl: '/static/js/',
    paths: {
        jquery: 'libs/jquery-1.11.1.min',
        bootstrap: 'libs/bootstrap.min',
        jqueryui: 'libs/jquery-ui.min',
        session_security: 'session_security',
        underscore: 'libs/underscore-min',
        tokenfield: 'libs/bootstrap-tokenfield.min'
    },
    shim: {
        'bootstrap': ['jquery'],
        'jqueryui': ['jquery'],
        'session_security': ['jquery'],
        'tokenfield': ['jquery', 'jqueryui']
    }
});

require([
    'jquery',
    'jqueryui',
    'bootstrap',
    'session_security',
    'tokenfield'
], function ($) {

    var file_list_total = 0;

    // File selection storage object
    // The data-type/name input checkbox attritbutes in the form below must be reflected here in this map
    // to properly convey the checked list to IGV
    var selFiles = {
        gcs_bam: {},
        readgroupset_id: {},
        toTokens: function() {
            var tokens = [];
            for(var i in this.gcs_bam) {
                tokens.push({
                    label: this.gcs_bam[i],
                    value: i,
                    dataType: "gcs_bam"
                });
            }
            for(var i in this.readgroupset_id) {
                tokens.push({
                    value: i,
                    label: this.readgroupset_id[i],
                    dataType: "readgroupset_id"
                });
            }
            return tokens;
        },
        count: function() {
            return (Object.keys(this.gcs_bam).length
                + Object.keys(this.readgroupset_id).length);
        }
    };

    // Set of display controls to update when we check or uncheck
    var update_on_selex_change = function() {
        // Update the hidden form control
        $('#checked_list_input').attr('value',JSON.stringify(selFiles));

        // Update the submit button
        $('input[type="submit"]').prop('disabled', (selFiles.count() <= 0));

        // Update the display counter
        $('#selected-count').text(selFiles.count());

        // Update the limit display
        $('#selected-file-limit').css('color', (selFiles.count() < SEL_FILE_MAX ? "#000000" : "#BD12CC"));

        // If we've cleared out our tokenfield, re-display the placeholder
        selFiles.count() <= 0 && $('#selected-files-tokenfield').show();

        selFiles.count() >= 5 ? $('#file-max-alert').show() : $('#file-max-alert').hide();
    };

    var update_on_platform_filter_change = function(e) {

        var totalSel = 0;

        if($('input[name="platform-selected"]:checked').length <= 0) {
            $('input[name="platform-selected"]').each(function(i) {
               totalSel += parseInt($(this).attr('data-platform-count'));
            });
        } else {
            $('input[name="platform-selected"]:checked').each(function(i) {
               totalSel += parseInt($(this).attr('data-platform-count'));
            });
        }
        $('.file-list-limit').text(FILE_LIST_MAX);
        $('.file-list-total').text(totalSel);

        if(totalSel < FILE_LIST_MAX) {
            $('#file-list-warning').hide();
        }
    };

    $('.file-limit').text(SEL_FILE_MAX);

    // Our file list tokenizer
    var selFileField = $('#selected-files');

    // Build the file tokenizer
    // Bootstrap tokenfield requires 'value' as the datem attribute field
    selFileField.tokenfield({
        delimiter : " ",
        minLength: 2,
        limit: SEL_FILE_MAX,
        tokens: selFiles.toTokens()
    // No creating
    }).on('tokenfield:edittoken',function(e){
        e.preventDefault();
        return false;
    }).on('tokenfield:removedtoken',function(e){

        // Uncheck the input checkbox - note this will not fire the event, which
        // is bound to form click
        var thisCheck = $('.filelist-panel input[value="'+e.attrs.value+'"');
        thisCheck.prop('checked',false);

        delete selFiles[e.attrs.dataType][e.attrs.value];

        update_on_selex_change();

        if(selFiles.count() <= SEL_FILE_MAX) {
            $('.filelist-panel input[type="checkbox"]').attr('disabled',false);
        }
    });

    // Prevent direct user input on the tokenfield
    $('#selected-files-tokenfield').prop('disabled','disabled');

    var happy_name = function(input) {
        var dictionary = {
            'DNAseq_data': 'DNAseq',
            'Yes': 'GA',
            'No': 'N/A',
            'mirnPlatform': 'microRNA',
            'None': 'N/A',
            'IlluminaHiSeq_miRNASeq': 'HiSeq',
            'IlluminaGA_miRNASeq': 'GA',
            'cnvrPlatform': 'SNP/CN',
            'Genome_Wide_SNP_6': 'SNP6',
            'methPlatform': 'DNAmeth',
            'HumanMethylation27': '27k',
            'HumanMethylation450': '450k',
            'gexpPlatform': 'mRNA',
            'IlluminaHiSeq_RNASeq': 'HiSeq/BCGSC',
            'IlluminaHiSeq_RNASeqV2': 'HiSeq/UNC V2',
            'IlluminaGA_RNASeq': 'GA/BCGSC',
            'IlluminaGA_RNASeqV2': 'GA/UNC V2',
            'rppaPlatform': 'Protein',
            'MDA_RPPA_Core': 'RPPA'
        };
        if (input in dictionary) {
            return dictionary[input];
        } else {
            return input.replace(/_/g, ' ');
        }

    };

    var update_table = function () {
        var selector_list = [];
        $('#filter-panel input[type="checkbox"]:checked').each(function() {
            selector_list.push($(this).attr('id'));
        });
        var url = ajax_update_url + '?page=' + page;

        file_list_total = 0;

        if($('input[name="platform-selected"]:checked').length <= 0) {
             $('input[name="platform-selected"]').each(function(i) {
               file_list_total += parseInt($(this).attr('data-platform-count'));
            });
        } else {
            $('input[name="platform-selected"]:checked').each(function(i) {
               file_list_total += parseInt($(this).attr('data-platform-count'));
            });
        }

        if (selector_list.length) {
            for (var selector in selector_list) {
                url += '&' + selector_list[selector] + '=True';
            }

            $('#download-link').attr('href', download_url + '?params=' + selector_list.join(',') + '&total=' + file_list_total);
        } else {
            $('#download-link').attr('href', download_url + '?total=' + file_list_total)
        }

        $('#prev-page').addClass('disabled');
        $('#next-page').addClass('disabled');
        $('#content-panel .spinner i').removeClass('hidden');
        $.ajax({
            url: url,
            success: function (data) {
                data = JSON.parse(data);
                var total_files = data['total_file_count'];
                var total_pages = Math.ceil(total_files / 20);
                $('.filelist-panel .panel-body .file-count').html(total_pages);
                $('.filelist-panel .panel-body .page-num').html(page);
                var files = data['file_list'];
                $('.filelist-panel table tbody').empty();
                for (var i = 0; i < files.length; i++) {
                    if (!('datatype' in files[i])) {
                        files[i]['datatype'] = '';
                    }

                    var val = null;
                    var dataTypeName = '';
                    var label = '';
                    var tokenLabel = files[i]['sample']+", "+files[i]['pipeline']+", "+happy_name(files[i]['platform'])+", "+files[i]['datatype'];
                    var checkbox_inputs = '';
                    var disable = true;
                    if (files[i]['access'] != 'dbGap controlled-access' || has_access == 'True') {
                        disable = false;
                    }
                    if (files[i]['gg_readgroupset_id']) {
                        val = files[i]['gg_readgroupset_id'] + ',' + files[i]['sample'];
                        dataTypeName = "readgroupset_id";
                        label = "GA4GH";
                        checkbox_inputs += '<input type="checkbox" token-label="'+tokenLabel+'"name="'+dataTypeName+'" data-type="'+dataTypeName+'" value="'+val+'"';
                        if (disable) {
                            checkbox_inputs += ' disabled="disabled"';
                        }
                        checkbox_inputs += '> '+label+'';
                    }
                    if (files[i]['cloudstorage_location'] && files[i]['cloudstorage_location'].split('.').pop() == 'bam') {
                        val = files[i]['cloudstorage_location'] + ',' + files[i]['sample'];
                        dataTypeName = "gcs_bam";
                        label = "Cloud Storage";
                        checkbox_inputs += '<input type="checkbox" token-label="'+tokenLabel+'"name="'+dataTypeName+'" data-type="'+dataTypeName+'" value="'+val+'"';
                        if (disable) {
                            checkbox_inputs += ' disabled="disabled"';
                        }
                        checkbox_inputs += '> '+label+'';
                    }

                    files[i]['gg_readgroupset_id'] = checkbox_inputs;

                    $('.filelist-panel table tbody').append(
                        '
' +
                        '' + files[i]['sample'] + '	' +
                        '' + files[i]['pipeline'] + '	' +
                        '' + happy_name(files[i]['platform']) + '	' +
                        '' + files[i]['datalevel'] + '	' +
                        '' + files[i]['datatype'] + '	' +
                        '' + files[i]['gg_readgroupset_id'] + '	' +
                        '
'
                    )

                    // Remember any previous checks
                    var thisCheck = $('.filelist-panel input[value="'+val+'"');
                    selFiles[thisCheck.attr('data-type')] && selFiles[thisCheck.attr('data-type')][thisCheck.attr('value')] && thisCheck.attr('checked', true);
                }

                // If we're at the max, disable all checkboxes which are not currently checked
                selFiles.count() >= SEL_FILE_MAX && $('.filelist-panel input[type="checkbox"]:not(:checked)').attr('disabled',true);

                selFileField.tokenfield('setTokens',selFiles.toTokens());

                // If there are checkboxes for igv, show the "Launch IGV" button
                if (selFiles.count() > 0 || $('.filelist-panel input[type="checkbox"]').length > 0) {
                    $('input[type="submit"]').show();
                } else {
                    $('input[type="submit"]').hide();
                }

                // Bind event handler to checkboxes
                $('.filelist-panel input[type="checkbox"]').on('click', function() {

                    var self=$(this);

                    if(self.is(':checked')) {
                        selFiles[self.attr('data-type')][self.attr('value')] = self.attr('token-label');
                        $('#selected-files-tokenfield').hide();
                    } else {
                        delete selFiles[self.attr('data-type')][self.attr('value')];
                    }

                    selFileField.tokenfield('setTokens',selFiles.toTokens());

                    update_on_selex_change();

                    if (self.is(':checked') && selFiles.count() >= SEL_FILE_MAX) {
                        $('.filelist-panel input[type="checkbox"]:not(:checked)').attr('disabled',true);
                    } else {
                        $('.filelist-panel input[type="checkbox"]').attr('disabled',false);
                    }

                });

                $('#prev-page').removeClass('disabled');
                $('#next-page').removeClass('disabled');
                if (parseInt(page) == 1) {
                    $('#prev-page').addClass('disabled');
                }
                if (parseInt(page) * 20 > total_files) {
                    $('#next-page').addClass('disabled');
                }
                $('#content-panel .spinner i').addClass('hidden');
            },
            error: function(e) {
                console.log(e);
                $('#content-panel .spinner i').addClass('hidden');
            }
        })
    };

    // Next page button click
    $('#next-page').on('click', function () {
        page = page + 1;
        update_table();
    });

    // Previous page button click
    $('#prev-page').on('click', function () {
        page = page - 1;
        update_table();
    });

    $('#filter-panel input[type="checkbox"]').on('change', function() {
        page = 1;

        var totalSel = 0;

        if($('input[name="platform-selected"]:checked').length <= 0) {
            $('input[name="platform-selected"]').each(function(i) {
               totalSel += parseInt($(this).attr('data-platform-count'));
            });
        } else {
            $('input[name="platform-selected"]:checked').each(function(i) {
               totalSel += parseInt($(this).attr('data-platform-count'));
            });
        }

        $('.file-list-total').text(totalSel);

        if(totalSel < FILE_LIST_MAX) {
            $('#file-list-warning').hide();
        }

        update_table();
    });

    $('#download-link').on('click',function(e) {

        update_on_platform_filter_change();

        if(parseInt($('.file-list-total').text()) > FILE_LIST_MAX) {
            $('#file-list-warning').show();
            e.preventDefault();
            return false;
        } else {
            $('#file-list-warning').hide();
        }
    });

    $('input[type="submit"]').prop('disabled', true);
    $('input[type="submit"]').hide();
    update_table();
});
<commit_msg>#1739<commit_after>/**
 *
 * Copyright 2016, Institute for Systems Biology
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

require.config({
    baseUrl: '/static/js/',
    paths: {
        jquery: 'libs/jquery-1.11.1.min',
        bootstrap: 'libs/bootstrap.min',
        jqueryui: 'libs/jquery-ui.min',
        session_security: 'session_security',
        underscore: 'libs/underscore-min',
        tokenfield: 'libs/bootstrap-tokenfield.min'
    },
    shim: {
        'bootstrap': ['jquery'],
        'jqueryui': ['jquery'],
        'session_security': ['jquery'],
        'tokenfield': ['jquery', 'jqueryui']
    }
});

require([
    'jquery',
    'jqueryui',
    'bootstrap',
    'session_security',
    'tokenfield'
], function ($) {

    var file_list_total = 0;

    // File selection storage object
    // The data-type/name input checkbox attritbutes in the form below must be reflected here in this map
    // to properly convey the checked list to IGV
    var selFiles = {
        gcs_bam: {},
        toTokens: function() {
            var tokens = [];
            for(var i in this.gcs_bam) {
                tokens.push({
                    label: this.gcs_bam[i],
                    value: i,
                    dataType: "gcs_bam"
                });
            }
            return tokens;
        },
        count: function() {
            return (Object.keys(this.gcs_bam).length);
        }
    };

    // Set of display controls to update when we check or uncheck
    var update_on_selex_change = function() {
        // Update the hidden form control
        $('#checked_list_input').attr('value',JSON.stringify(selFiles));

        // Update the submit button
        $('input[type="submit"]').prop('disabled', (selFiles.count() <= 0));

        // Update the display counter
        $('#selected-count').text(selFiles.count());

        // Update the limit display
        $('#selected-file-limit').css('color', (selFiles.count() < SEL_FILE_MAX ? "#000000" : "#BD12CC"));

        // If we've cleared out our tokenfield, re-display the placeholder
        selFiles.count() <= 0 && $('#selected-files-tokenfield').show();

        selFiles.count() >= 5 ? $('#file-max-alert').show() : $('#file-max-alert').hide();
    };

    var update_on_platform_filter_change = function(e) {

        var totalSel = 0;

        if($('input[name="platform-selected"]:checked').length <= 0) {
            $('input[name="platform-selected"]').each(function(i) {
               totalSel += parseInt($(this).attr('data-platform-count'));
            });
        } else {
            $('input[name="platform-selected"]:checked').each(function(i) {
               totalSel += parseInt($(this).attr('data-platform-count'));
            });
        }
        $('.file-list-limit').text(FILE_LIST_MAX);
        $('.file-list-total').text(totalSel);

        if(totalSel < FILE_LIST_MAX) {
            $('#file-list-warning').hide();
        }
    };

    $('.file-limit').text(SEL_FILE_MAX);

    // Our file list tokenizer
    var selFileField = $('#selected-files');

    // Build the file tokenizer
    // Bootstrap tokenfield requires 'value' as the datem attribute field
    selFileField.tokenfield({
        delimiter : " ",
        minLength: 2,
        limit: SEL_FILE_MAX,
        tokens: selFiles.toTokens()
    // No creating
    }).on('tokenfield:edittoken',function(e){
        e.preventDefault();
        return false;
    }).on('tokenfield:removedtoken',function(e){

        // Uncheck the input checkbox - note this will not fire the event, which
        // is bound to form click
        var thisCheck = $('.filelist-panel input[value="'+e.attrs.value+'"');
        thisCheck.prop('checked',false);

        delete selFiles[e.attrs.dataType][e.attrs.value];

        update_on_selex_change();

        if(selFiles.count() <= SEL_FILE_MAX) {
            $('.filelist-panel input[type="checkbox"]').attr('disabled',false);
        }
    });

    // Prevent direct user input on the tokenfield
    $('#selected-files-tokenfield').prop('disabled','disabled');

    var happy_name = function(input) {
        var dictionary = {
            'DNAseq_data': 'DNAseq',
            'Yes': 'GA',
            'No': 'N/A',
            'mirnPlatform': 'microRNA',
            'None': 'N/A',
            'IlluminaHiSeq_miRNASeq': 'HiSeq',
            'IlluminaGA_miRNASeq': 'GA',
            'cnvrPlatform': 'SNP/CN',
            'Genome_Wide_SNP_6': 'SNP6',
            'methPlatform': 'DNAmeth',
            'HumanMethylation27': '27k',
            'HumanMethylation450': '450k',
            'gexpPlatform': 'mRNA',
            'IlluminaHiSeq_RNASeq': 'HiSeq/BCGSC',
            'IlluminaHiSeq_RNASeqV2': 'HiSeq/UNC V2',
            'IlluminaGA_RNASeq': 'GA/BCGSC',
            'IlluminaGA_RNASeqV2': 'GA/UNC V2',
            'rppaPlatform': 'Protein',
            'MDA_RPPA_Core': 'RPPA'
        };
        if (input in dictionary) {
            return dictionary[input];
        } else {
            return input.replace(/_/g, ' ');
        }

    };

    var update_table = function () {
        var selector_list = [];
        $('#filter-panel input[type="checkbox"]:checked').each(function() {
            selector_list.push($(this).attr('id'));
        });
        var url = ajax_update_url + '?page=' + page;

        file_list_total = 0;

        if($('input[name="platform-selected"]:checked').length <= 0) {
             $('input[name="platform-selected"]').each(function(i) {
               file_list_total += parseInt($(this).attr('data-platform-count'));
            });
        } else {
            $('input[name="platform-selected"]:checked').each(function(i) {
               file_list_total += parseInt($(this).attr('data-platform-count'));
            });
        }

        if (selector_list.length) {
            for (var selector in selector_list) {
                url += '&' + selector_list[selector] + '=True';
            }

            $('#download-link').attr('href', download_url + '?params=' + selector_list.join(',') + '&total=' + file_list_total);
        } else {
            $('#download-link').attr('href', download_url + '?total=' + file_list_total)
        }

        $('#prev-page').addClass('disabled');
        $('#next-page').addClass('disabled');
        $('#content-panel .spinner i').removeClass('hidden');
        $.ajax({
            url: url,
            success: function (data) {
                data = JSON.parse(data);
                var total_files = data['total_file_count'];
                var total_pages = Math.ceil(total_files / 20);
                $('.filelist-panel .panel-body .file-count').html(total_pages);
                $('.filelist-panel .panel-body .page-num').html(page);
                var files = data['file_list'];
                $('.filelist-panel table tbody').empty();
                for (var i = 0; i < files.length; i++) {
                    if (!('datatype' in files[i])) {
                        files[i]['datatype'] = '';
                    }

                    var val = null;
                    var dataTypeName = '';
                    var label = '';
                    var tokenLabel = files[i]['sample']+", "+files[i]['pipeline']+", "+happy_name(files[i]['platform'])+", "+files[i]['datatype'];
                    var checkbox_inputs = '';
                    var disable = true;
                    if (files[i]['access'] != 'dbGap controlled-access' || has_access == 'True') {
                        disable = false;
                    }

                    if (files[i]['cloudstorage_location'] && files[i]['cloudstorage_location'].split('.').pop() == 'bam') {
                        val = files[i]['cloudstorage_location'] + ',' + files[i]['sample'];
                        dataTypeName = "gcs_bam";
                        label = "Cloud Storage";
                        checkbox_inputs += '<input type="checkbox" token-label="'+tokenLabel+'"name="'+dataTypeName+'" data-type="'+dataTypeName+'" value="'+val+'"';
                        if (disable) {
                            checkbox_inputs += ' disabled="disabled"';
                        }
                        checkbox_inputs += '> '+label+'';
                    }

                    files[i]['igv_viewer'] = checkbox_inputs;

                    $('.filelist-panel table tbody').append(
                        '
' +
                        '' + files[i]['sample'] + '	' +
                        '' + files[i]['pipeline'] + '	' +
                        '' + happy_name(files[i]['platform']) + '	' +
                        '' + files[i]['datalevel'] + '	' +
                        '' + files[i]['datatype'] + '	' +
                        '' + files[i]['igv_viewer'] + '	' +
                        '
'
                    )

                    // Remember any previous checks
                    var thisCheck = $('.filelist-panel input[value="'+val+'"');
                    selFiles[thisCheck.attr('data-type')] && selFiles[thisCheck.attr('data-type')][thisCheck.attr('value')] && thisCheck.attr('checked', true);
                }

                // If we're at the max, disable all checkboxes which are not currently checked
                selFiles.count() >= SEL_FILE_MAX && $('.filelist-panel input[type="checkbox"]:not(:checked)').attr('disabled',true);

                selFileField.tokenfield('setTokens',selFiles.toTokens());

                // If there are checkboxes for igv, show the "Launch IGV" button
                if (selFiles.count() > 0 || $('.filelist-panel input[type="checkbox"]').length > 0) {
                    $('input[type="submit"]').show();
                } else {
                    $('input[type="submit"]').hide();
                }

                // Bind event handler to checkboxes
                $('.filelist-panel input[type="checkbox"]').on('click', function() {

                    var self=$(this);

                    if(self.is(':checked')) {
                        selFiles[self.attr('data-type')][self.attr('value')] = self.attr('token-label');
                        $('#selected-files-tokenfield').hide();
                    } else {
                        delete selFiles[self.attr('data-type')][self.attr('value')];
                    }

                    selFileField.tokenfield('setTokens',selFiles.toTokens());

                    update_on_selex_change();

                    if (self.is(':checked') && selFiles.count() >= SEL_FILE_MAX) {
                        $('.filelist-panel input[type="checkbox"]:not(:checked)').attr('disabled',true);
                    } else {
                        $('.filelist-panel input[type="checkbox"]').attr('disabled',false);
                    }

                });

                $('#prev-page').removeClass('disabled');
                $('#next-page').removeClass('disabled');
                if (parseInt(page) == 1) {
                    $('#prev-page').addClass('disabled');
                }
                if (parseInt(page) * 20 > total_files) {
                    $('#next-page').addClass('disabled');
                }
                $('#content-panel .spinner i').addClass('hidden');
            },
            error: function(e) {
                console.log(e);
                $('#content-panel .spinner i').addClass('hidden');
            }
        })
    };

    // Next page button click
    $('#next-page').on('click', function () {
        page = page + 1;
        update_table();
    });

    // Previous page button click
    $('#prev-page').on('click', function () {
        page = page - 1;
        update_table();
    });

    $('#filter-panel input[type="checkbox"]').on('change', function() {
        page = 1;

        var totalSel = 0;

        if($('input[name="platform-selected"]:checked').length <= 0) {
            $('input[name="platform-selected"]').each(function(i) {
               totalSel += parseInt($(this).attr('data-platform-count'));
            });
        } else {
            $('input[name="platform-selected"]:checked').each(function(i) {
               totalSel += parseInt($(this).attr('data-platform-count'));
            });
        }

        $('.file-list-total').text(totalSel);

        if(totalSel < FILE_LIST_MAX) {
            $('#file-list-warning').hide();
        }

        update_table();
    });

    $('#download-link').on('click',function(e) {

        update_on_platform_filter_change();

        if(parseInt($('.file-list-total').text()) > FILE_LIST_MAX) {
            $('#file-list-warning').show();
            e.preventDefault();
            return false;
        } else {
            $('#file-list-warning').hide();
        }
    });

    $('input[type="submit"]').prop('disabled', true);
    $('input[type="submit"]').hide();
    update_table();
});
<|endoftext|>


<commit_before>(function () {
  if (!window.GIDEO) {
    window.GIDEO = true;

    window.gideoRoot = window.gideoRoot || (
      document.location.protocol + "//dmfrancisco.github.io/gideo/"
    );

    videojs.options.flash.swf = window.gideoRoot + "video-js.swf";

    function isMobile() {
      return navigator.userAgent.match(/(Android|iPod|iPhone|iPad)/);
    }

    function listen(eventName, elem, func) {
      if (elem.addEventListener) {
        elem.addEventListener(eventName, func, false);
      }
      else if (elem.attachEvent) {
        elem.attachEvent("on" + eventName, func);
      }
    }

    function isVisible(elem) {
      var rect = elem.getBoundingClientRect();

      return (
        rect.top > -elem.offsetHeight &&
        rect.top < (window.innerHeight || document.documentElement.clientHeight)
      );
    }

    // Add new CSS rules (based on goo.gl/Ygvaqy)
    function injectStyles(rules) {
      var div = document.createElement('div');
      div.innerHTML = '<style>' + rules + '</style>';
      document.body.appendChild(div.childNodes[1]);
    }

    if (!isMobile()) {
      window.setInterval(function () {
        var embeds = document.querySelectorAll('.gideo');

        for (var i = 0; i < embeds.length; i++) {
          var gideo = embeds[i].player;

          if (!gideo) {
            continue;
          } else if (isVisible(embeds[i])) {
            if (gideo.paused()) {
              try { gideo.currentTime(0); }
              catch (e) { /* Random error with the flash fallback */ }
              gideo.play();
            }
          } else if (!gideo.paused()) {
            gideo.pause();
          }
        }
      }, 1000);

      listen("click", document.querySelector('body'), function (e) {
        var target = e.target ? e.target : e.srcElement;

        if (target.className === "gideo-mute") {
          var gideo = target.nextSibling.player;

          if (!gideo) {
            return;
          } else if (gideo.muted()) {
            gideo.currentTime(0);
            gideo.muted(false);
            target.style.backgroundPosition = "0 -36px";
          } else {
            gideo.muted(true);
            target.style.backgroundPosition = "0 0";
          }
        } else if (target.className === "gideo-replay") {
          var gideo = target.previousSibling.player;
          if (gideo) { gideo.currentTime(0); }
        }
      });

      // Inject styles for controls
      injectStyles(""
        + " .gideo-mute, .gideo-replay {"
          + " position: absolute; z-index: 2;"
          + " width: 44px; height: 36px; left: 20px;"
          + " background: url("+ window.gideoRoot +"sprites.png);"
          + " cursor: pointer }"
        + " .gideo-mute { top: 20px }"
        + " .gideo-replay { bottom: 20px; background-position: 0 -72px }");

    } else {
      // We don't autoplay (in mobile devices) but we still need to pause.
      // This is not necessary for iOS since videos open in a new window.
      window.setInterval(function () {
        var embeds = document.querySelectorAll('.gideo');

        for (var i = 0; i < embeds.length; i++) {
          var gideo = embeds[i].player;
          if (gideo && !isVisible(embeds[i])) { gideo.pause(); }
        }
      }, 1000);
    }

    // Inject styles for the play button (for devices without autoplay)
    injectStyles(""
      + " .gideo .vjs-big-play-button {"
        + " position: absolute; z-index: 2;"
        + " width: 68px; height: 68px;"
        + " top: 50%; left: 50%; margin: -34px auto auto -34px;"
        + " background: url("+ window.gideoRoot +"sprites.png) -44px 0 }"
      + " .gideo.vjs-playing .vjs-big-play-button {"
        + " display: none }");
  }

  var embeds = document.querySelectorAll('.gideo');

  // Force mute (this is not done using the `muted` attribute in
  // order to work in browsers that require the flash fallback)
  function mute() {
    this.muted(!isMobile());
  }

  // Initialize all videos
  for (var i = 0; i < embeds.length; i++) {
    if (!embeds[i].player) {
      videojs(embeds[i]).ready(mute);
    }
  }
})();
<commit_msg>Minor code improvements<commit_after>/*global videojs */
(function () {
  var isMobile = function () {
    return navigator.userAgent.match(/(Android|iPod|iPhone|iPad)/);
  };

  if (!window.GIDEO) {
    window.GIDEO = true;

    window.gideoRoot = window.gideoRoot || (
      document.location.protocol + "//dmfrancisco.github.io/gideo/"
    );

    videojs.options.flash.swf = window.gideoRoot + "video-js.swf";

    var listen = function (eventName, elem, func) {
      if (elem.addEventListener) {
        elem.addEventListener(eventName, func, false);
      } else if (elem.attachEvent) {
        elem.attachEvent("on" + eventName, func);
      }
    };

    var isVisible = function (elem) {
      var rect = elem.getBoundingClientRect();

      return (
        rect.top > -elem.offsetHeight &&
        rect.top < (window.innerHeight || document.documentElement.clientHeight)
      );
    };

    // Add new CSS rules (based on goo.gl/Ygvaqy)
    var injectStyles = function (rules) {
      var div = document.createElement('div');
      div.innerHTML = '<style>' + rules + '</style>';
      document.body.appendChild(div.childNodes[1]);
    };

    if (!isMobile()) {
      window.setInterval(function () {
        var gideo, embeds = document.querySelectorAll('.gideo');

        for (var i = 0; i < embeds.length; i++) {
          gideo = embeds[i].player;

          if (!gideo) {
            continue;
          } else if (isVisible(embeds[i])) {
            if (gideo.paused()) {
              try { gideo.currentTime(0); }
              catch (e) { /* Random error with the flash fallback */ }
              gideo.play();
            }
          } else if (!gideo.paused()) {
            gideo.pause();
          }
        }
      }, 1000);

      listen("click", document.querySelector('body'), function (e) {
        var gideo, target = e.target || e.srcElement;

        if (target.className === "gideo-mute") {
          gideo = target.nextSibling.player;

          if (!gideo) {
            return;
          } else if (gideo.muted()) {
            gideo.currentTime(0);
            gideo.muted(false);
            target.style.backgroundPosition = "0 -36px";
          } else {
            gideo.muted(true);
            target.style.backgroundPosition = "0 0";
          }
        } else if (target.className === "gideo-replay") {
          gideo = target.previousSibling.player;
          if (gideo) { gideo.currentTime(0); }
        }
      });

      // Inject styles for controls
      injectStyles(""
        + " .gideo-mute, .gideo-replay {"
          + " position: absolute; z-index: 2;"
          + " width: 44px; height: 36px; left: 20px;"
          + " background: url("+ window.gideoRoot +"sprites.png);"
          + " cursor: pointer }"
        + " .gideo-mute { top: 20px }"
        + " .gideo-replay { bottom: 20px; background-position: 0 -72px }");

    } else {
      // We don't autoplay (in mobile devices) but we still need to pause.
      // This is not necessary for iOS since videos open in a new window.
      window.setInterval(function () {
        var gideo, embeds = document.querySelectorAll('.gideo');

        for (var i = 0; i < embeds.length; i++) {
          gideo = embeds[i].player;
          if (gideo && !isVisible(embeds[i])) { gideo.pause(); }
        }
      }, 1000);
    }

    // Inject styles for the play button (for devices without autoplay)
    injectStyles(""
      + " .gideo .vjs-big-play-button {"
        + " position: absolute; z-index: 2;"
        + " width: 68px; height: 68px;"
        + " top: 50%; left: 50%; margin: -34px auto auto -34px;"
        + " background: url("+ window.gideoRoot +"sprites.png) -44px 0 }"
      + " .gideo.vjs-playing .vjs-big-play-button {"
        + " display: none }");
  }

  var embeds = document.querySelectorAll('.gideo');

  // Force mute (this is not done using the `muted` attribute in
  // order to work in browsers that require the flash fallback)
  var mute = function () {
    this.muted(!isMobile());
  };

  // Initialize all videos
  for (var i = 0; i < embeds.length; i++) {
    if (!embeds[i].player) {
      videojs(embeds[i]).ready(mute);
    }
  }
})();
<|endoftext|>


<commit_before>;(function($$){ 'use strict';

  // gets the rendered style for an element
  $$.styfn.getRenderedStyle = function( ele ){
    var ele = ele[0]; // insure it's an element

    if( ele ){
      var rstyle = {};
      var style = ele._private.style;
      var cy = this._private.cy;
      var zoom = cy.zoom();

      for( var i = 0; i < $$.style.properties.length; i++ ){
        var prop = $$.style.properties[i];
        var styleProp = style[ prop.name ];

        if( styleProp ){
          var val = styleProp.unitless ? styleProp.strValue : (styleProp.pxValue * zoom) + 'px';
          rstyle[ prop.name ] = val;
          rstyle[ $$.util.dash2camel(prop.name) ] = val;
        }
      }

      return rstyle;
    }
  };

  // gets the raw style for an element
  $$.styfn.getRawStyle = function( ele ){
    var ele = ele[0]; // insure it's an element

    if( ele ){
      var rstyle = {};
      var style = ele._private.style;

      for( var i = 0; i < $$.style.properties.length; i++ ){
        var prop = $$.style.properties[i];
        var styleProp = style[ prop.name ];

        if( styleProp ){
          rstyle[ prop.name ] = styleProp.strValue;
          rstyle[ $$.util.dash2camel(prop.name) ] = styleProp.strValue;
        }
      }

      return rstyle;
    }
  };

  // gets the value style for an element (useful for things like animations)
  $$.styfn.getValueStyle = function( ele ){
    var rstyle = {};
    var style;
    var isEle = $$.is.element(ele);

    if( isEle ){
      style = ele._private.style;
    } else {
      style = ele; // just passed the style itself
    }

    if( style ){
      for( var i = 0; i < $$.style.properties.length; i++ ){
        var prop = $$.style.properties[i];
        var styleProp = style[ prop.name ] || style[ $$.util.dash2camel(prop.name) ];

        if( styleProp !== undefined && !$$.is.plainObject( styleProp ) ){ // then make a prop of it
          styleProp = this.parse(prop.name, styleProp);
        }

        if( styleProp ){
          rstyle[ prop.name ] = styleProp;
          rstyle[ $$.util.dash2camel(prop.name) ] = styleProp;
        }
      }
    }

    return rstyle;
  };

  $$.styfn.getPropsList = function( propsObj ){
    var rstyle = [];
    var style = propsObj;
    var props = $$.style.properties;

    if( style ){
      for( var name in style ){
        var val = style[name];
        var prop = props[name] || props[ $$.util.camel2dash(name) ];
        var styleProp = this.parse( prop.name, val );

        rstyle.push( styleProp );
      }
    }

    return rstyle;
  };

})( cytoscape );
<commit_msg> Transitions can exponentially speed up with style property caching #1057<commit_after>;(function($$){ 'use strict';

  // gets the rendered style for an element
  $$.styfn.getRenderedStyle = function( ele ){
    var ele = ele[0]; // insure it's an element

    if( ele ){
      var rstyle = {};
      var style = ele._private.style;
      var cy = this._private.cy;
      var zoom = cy.zoom();

      for( var i = 0; i < $$.style.properties.length; i++ ){
        var prop = $$.style.properties[i];
        var styleProp = style[ prop.name ];

        if( styleProp ){
          var val = styleProp.unitless ? styleProp.strValue : (styleProp.pxValue * zoom) + 'px';
          rstyle[ prop.name ] = val;
          rstyle[ $$.util.dash2camel(prop.name) ] = val;
        }
      }

      return rstyle;
    }
  };

  // gets the raw style for an element
  $$.styfn.getRawStyle = function( ele ){
    var ele = ele[0]; // insure it's an element

    if( ele ){
      var rstyle = {};
      var style = ele._private.style;

      for( var i = 0; i < $$.style.properties.length; i++ ){
        var prop = $$.style.properties[i];
        var styleProp = style[ prop.name ];

        if( styleProp ){
          rstyle[ prop.name ] = styleProp.strValue;
          rstyle[ $$.util.dash2camel(prop.name) ] = styleProp.strValue;
        }
      }

      return rstyle;
    }
  };

  // gets the value style for an element (useful for things like animations)
  $$.styfn.getValueStyle = function( ele ){
    var rstyle = {};
    var style;
    var isEle = $$.is.element(ele);

    if( isEle ){
      style = ele._private.style;
    } else {
      style = ele; // just passed the style itself
    }

    if( style ){
      for( var i = 0; i < $$.style.properties.length; i++ ){
        var prop = $$.style.properties[i];
        var styleProp = style[ prop.name ] || style[ $$.util.dash2camel(prop.name) ];

        if( styleProp !== undefined ){ // then make a prop of it
          if( $$.is.plainObject( styleProp ) ){
            styleProp = this.parse( prop.name, styleProp.strValue );
          } else {
            styleProp = this.parse( prop.name, styleProp );
          }
        }

        if( styleProp ){
          rstyle[ prop.name ] = styleProp;
          rstyle[ $$.util.dash2camel(prop.name) ] = styleProp;
        }
      }
    }

    return rstyle;
  };

  $$.styfn.getPropsList = function( propsObj ){
    var rstyle = [];
    var style = propsObj;
    var props = $$.style.properties;

    if( style ){
      for( var name in style ){
        var val = style[name];
        var prop = props[name] || props[ $$.util.camel2dash(name) ];
        var styleProp = this.parse( prop.name, val );

        rstyle.push( styleProp );
      }
    }

    return rstyle;
  };

})( cytoscape );
<|endoftext|>


<commit_before>/*!
 *
 *   melonJS
 *   http://www.melonjs.org
 *
 *   Step by step game creation tutorial
 *
 **/

// game resources
var g_resources= [
                     // our level tileset
                     {name: "area01_level_tiles",  type:"image",	src: "data/area01_tileset/area01_level_tiles.png"},
                     // our levels
                     {name: "area01",              type: "tmx",	src: "data/area01.tmx"},
                     // the main player spritesheet
                     {name: "gripe_run_right",     type:"image",	src: "data/sprite/gripe_run_right.png"},
                     // the parallax background
                     {name: "area01_bkg0",         type:"image",	src: "data/area01_parallax/area01_bkg0.png"},
                     {name: "area01_bkg1",         type:"image",	src: "data/area01_parallax/area01_bkg1.png"},
                     // the spinning coin spritesheet
                     {name: "spinning_coin_gold",  type:"image",	src: "data/sprite/spinning_coin_gold.png"},
                     // our enemty entity
                     {name: "wheelie_right",       type:"image",	src: "data/sprite/wheelie_right.png"},
                     // game font
                     {name: "32x32_font",          type:"image",	src: "data/sprite/32x32_font.png"},
                      // title screen
                     {name: "title_screen",        type:"image",	src: "data/GUI/title_screen.png"},
                  ];

var jsApp	=
{
   /* ---

      Initialize the jsApp

      ---			*/
   onload: function()
   {

      // enable the dirtyRect feature
      me.sys.dirtyRegion = true;

      // some debug (draw the dirty area, if true)
      me.debug.renderDirty = false;

      // init the video
      if (!me.video.init('jsapp', 1024, 768))
      {
         alert("Sorry but your browser does not support html 5 canvas.");
         return;
      }

      // initialize the "audio"
      me.audio.init("mp3,ogg");

      // set all resources to be loaded
      me.loader.onload = this.loaded.bind(this);

      // set all resources to be loaded
      me.loader.preload(g_resources);

      // load everything & display a loading screen
      me.state.change(me.state.LOADING);
   },

   /* ---

		callback when everything is loaded
   ---										*/
   loaded: function ()
   {
      // set the "Play/Ingame" Screen Object
      me.state.set(me.state.MENU, new TitleScreen());

      // set the "Play/Ingame" Screen Object
      me.state.set(me.state.PLAY, new PlayScreen());

      // NOT WORKING WITH Dirty Rect..
      // Screen is not refresh when the fading is over
      // set a global fading transition for the screen
		//me.state.transition("fade", "#FFFFFF", 15);

      // add our Player entity & Coin in the entity pool
      me.entityPool.add("mainPlayer", PlayerEntity);
      me.entityPool.add("CoinEntity", CoinEntity);

      // enable the keyboard
      me.input.bindKey(me.input.KEY.LEFT,    "left");
      me.input.bindKey(me.input.KEY.RIGHT,   "right");
      me.input.bindKey(me.input.KEY.X,       "jump", true);

      // BUG WITH Dirty rec
      // Menu screen is broken when using dirty rect
      // SO start the game directly !
      me.state.change(me.state.PLAY);
	}

}; // jsApp

/* the in game stuff*/
var PlayScreen = me.ScreenObject.extend(
{

   onResetEvent: function()
   {
      // load a level
      me.levelDirector.loadLevel("area01");

      // add a default HUD to the game mngr
      me.game.addHUD(850,0,174,50);

      // add a new HUD item
      me.game.HUD.addItem("score", new ScoreObject(170,10));

      // make sure everyhting is in the right order
      me.game.sort();

   },

   /* ---

      action to perform when game is finished (state change)

   ---	*/
   onDestroyEvent: function()
   {
      // remove the HUD
      me.game.disableHUD();
   }

});

//bootstrap :)
window.onReady(function()
{
	jsApp.onload();
});
<commit_msg>Re-enabled fading transition effect and switch to menu, since they are both working now<commit_after>/*!
 *
 *   melonJS
 *   http://www.melonjs.org
 *
 *   Step by step game creation tutorial
 *
 **/

// game resources
var g_resources= [
                     // our level tileset
                     {name: "area01_level_tiles",  type:"image",	src: "data/area01_tileset/area01_level_tiles.png"},
                     // our levels
                     {name: "area01",              type: "tmx",	src: "data/area01.tmx"},
                     // the main player spritesheet
                     {name: "gripe_run_right",     type:"image",	src: "data/sprite/gripe_run_right.png"},
                     // the parallax background
                     {name: "area01_bkg0",         type:"image",	src: "data/area01_parallax/area01_bkg0.png"},
                     {name: "area01_bkg1",         type:"image",	src: "data/area01_parallax/area01_bkg1.png"},
                     // the spinning coin spritesheet
                     {name: "spinning_coin_gold",  type:"image",	src: "data/sprite/spinning_coin_gold.png"},
                     // our enemty entity
                     {name: "wheelie_right",       type:"image",	src: "data/sprite/wheelie_right.png"},
                     // game font
                     {name: "32x32_font",          type:"image",	src: "data/sprite/32x32_font.png"},
                      // title screen
                     {name: "title_screen",        type:"image",	src: "data/GUI/title_screen.png"},
                  ];

var jsApp	=
{
   /* ---

      Initialize the jsApp

      ---			*/
   onload: function()
   {

      // enable the dirtyRect feature
      me.sys.dirtyRegion = true;

      // some debug (draw the dirty area, if true)
      me.debug.renderDirty = false;

      // init the video
      if (!me.video.init('jsapp', 1024, 768))
      {
         alert("Sorry but your browser does not support html 5 canvas.");
         return;
      }

	   // initialize the "audio"
      me.audio.init("mp3,ogg");

      // set all resources to be loaded
      me.loader.onload = this.loaded.bind(this);

      // set all resources to be loaded
      me.loader.preload(g_resources);

      // load everything & display a loading screen
      me.state.change(me.state.LOADING);
   },

   /* ---

         callback when everything is loaded

      --- */
   loaded: function ()
   {
      // set the "Play/Ingame" Screen Object
      me.state.set(me.state.MENU, new TitleScreen());

      // set the "Play/Ingame" Screen Object
      me.state.set(me.state.PLAY, new PlayScreen());

      // set a global fading transition for the screen
		me.state.transition("fade", "#FFFFFF", 15);

      // add our Player entity & Coin in the entity pool
      me.entityPool.add("mainPlayer", PlayerEntity);
      me.entityPool.add("CoinEntity", CoinEntity);

      // enable the keyboard
      me.input.bindKey(me.input.KEY.LEFT,    "left");
      me.input.bindKey(me.input.KEY.RIGHT,   "right");
      me.input.bindKey(me.input.KEY.X,       "jump", true);

      // switch to our menu !
      me.state.change(me.state.MENU);
	}

}; // jsApp

/* the in game stuff*/
var PlayScreen = me.ScreenObject.extend(
{

   onResetEvent: function()
   {
      // load a level
      me.levelDirector.loadLevel("area01");

      // add a default HUD to the game mngr
      me.game.addHUD(850,0,174,50);

      // add a new HUD item
      me.game.HUD.addItem("score", new ScoreObject(170,10));
   },

   /* ---

      action to perform when game is finished (state change)

   ---	*/
   onDestroyEvent: function()
   {
      // remove the HUD
      me.game.disableHUD();
   }

});

//bootstrap :)
window.onReady(function()
{
	jsApp.onload();
});
<|endoftext|>


<commit_before>/*
 * 0xtrades.info
 * https://github.com/vsergeev/0xtrades.info
 *
 * Copyright (c) 2017 Ivan (Vanya) A. Sergeev
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/******************************************************************************/
/* Constants */
/******************************************************************************/

var ZEROEX_GENESIS_BLOCK = {
  1: 4145578,
  42: 4145578,
};

var ZEROEX_RELAY_ADDRESSES = {
  1: {
    "0xa258b39954cef5cb142fd567a46cddb31a670124": "Radar Relay",
    "0xeb71bad396acaa128aeadbc7dbd59ca32263de01": "Kin Alpha",
    "0xc22d5b2951db72b44cfb8089bb8cd374a3c354ea": "OpenRelay",
  },
  42: {},
};

/* Populated by model */
var ZEROEX_TOKEN_INFOS = {};

/* Populated by model */
var ZEROEX_EXCHANGE_ADDRESS = null;

/* Populated by model */
var ZEROEX_TOKEN_ADDRESS = null;

var NETWORK_NAME = {
  1: "Mainnet",
  3: "Ropsten",
  4: "Rinkeby",
  42: "Kovan",
};

var NETWORK_BLOCK_EXPLORER = {
  1: "https://etherscan.io",
  3: "https://ropsten.etherscan.io",
  4: "https://rinkeby.etherscan.io",
  42: "https://kovan.etherscan.io",
};

var PRICE_API_URL = function (symbols, base) {
  return "https://min-api.cryptocompare.com/data/pricemulti?fsyms=" + symbols.join(',') + "&tsyms=" + base;
};

var INFURA_API_URL = "https://mainnet.infura.io/rdkuEWbeKAjSR9jZ6P1h";

var STATISTICS_TIME_WINDOW = 86400; /* 24 hours */

var BLOCK_FETCH_COUNT = Math.ceil(STATISTICS_TIME_WINDOW/17);

var PRICE_UPDATE_TIMEOUT = 5*60*1000;

var PRICE_CHART_DEFAULT_PAIR = "ZRX:WETH";

var CHART_DEFAULT_COLORS = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a',
                            '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94',
                            '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d',
                            '#17becf', '#9edae5'];

var CHART_DEFAULT_TOOLTIP_CALLBACK = function (item, data) {
  var label = data.labels[item.index];
  var value = data.datasets[item.datasetIndex].tooltips[item.index] || data.datasets[item.datasetIndex].data[item.index];
  return label + ": " + value;
};

/* From http://www.localeplanet.com/api/auto/currencymap.json */
var FIAT_CURRENCY_MAP = {
  "USD": {
    "symbol": "$",
    "symbol_native": "$",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "USD"
  },
  "EUR": {
    "symbol": "€",
    "symbol_native": "€",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "EUR"
  },
  "GBP": {
    "symbol": "£",
    "symbol_native": "£",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "GBP"
  },
  "JPY": {
    "symbol": "¥",
    "symbol_native": "￥",
    "decimal_digits": 0,
    "rounding": 0,
    "code": "JPY"
  },
  "KRW": {
    "symbol": "₩",
    "symbol_native": "₩",
    "decimal_digits": 0,
    "rounding": 0,
    "code": "KRW"
  },
};

var FIAT_CURRENCY_DEFAULT = "USD";

/******************************************************************************/
/* Logger */
/******************************************************************************/

Logger = {
  enable: function () { Logger.log = Logger._log_console; },
  disable: function () { Logger.log = Logger._log_null; },

  _log_console: console.log.bind(window.console),
  _log_null: function (s) { },

  log: null,
  error: console.error.bind(window.console),
};
<commit_msg>constants: add REQ token to token infos<commit_after>/*
 * 0xtrades.info
 * https://github.com/vsergeev/0xtrades.info
 *
 * Copyright (c) 2017 Ivan (Vanya) A. Sergeev
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/******************************************************************************/
/* Constants */
/******************************************************************************/

var ZEROEX_GENESIS_BLOCK = {
  1: 4145578,
  42: 4145578,
};

var ZEROEX_RELAY_ADDRESSES = {
  1: {
    "0xa258b39954cef5cb142fd567a46cddb31a670124": "Radar Relay",
    "0xeb71bad396acaa128aeadbc7dbd59ca32263de01": "Kin Alpha",
    "0xc22d5b2951db72b44cfb8089bb8cd374a3c354ea": "OpenRelay",
  },
  42: {},
};

/* Populated by model */
var ZEROEX_TOKEN_INFOS = {
    /* Pre-load some newer token infos */
    "0x8f8221afbb33998d8584a2b05749ba73c37a938a": {
      name: "Request",
      symbol: "REQ",
      decimals: 18,
    },
};

/* Populated by model */
var ZEROEX_EXCHANGE_ADDRESS = null;

/* Populated by model */
var ZEROEX_TOKEN_ADDRESS = null;

var NETWORK_NAME = {
  1: "Mainnet",
  3: "Ropsten",
  4: "Rinkeby",
  42: "Kovan",
};

var NETWORK_BLOCK_EXPLORER = {
  1: "https://etherscan.io",
  3: "https://ropsten.etherscan.io",
  4: "https://rinkeby.etherscan.io",
  42: "https://kovan.etherscan.io",
};

var PRICE_API_URL = function (symbols, base) {
  return "https://min-api.cryptocompare.com/data/pricemulti?fsyms=" + symbols.join(',') + "&tsyms=" + base;
};

var INFURA_API_URL = "https://mainnet.infura.io/rdkuEWbeKAjSR9jZ6P1h";

var STATISTICS_TIME_WINDOW = 86400; /* 24 hours */

var BLOCK_FETCH_COUNT = Math.ceil(STATISTICS_TIME_WINDOW/17);

var PRICE_UPDATE_TIMEOUT = 5*60*1000;

var PRICE_CHART_DEFAULT_PAIR = "ZRX:WETH";

var CHART_DEFAULT_COLORS = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c', '#98df8a',
                            '#d62728', '#ff9896', '#9467bd', '#c5b0d5', '#8c564b', '#c49c94',
                            '#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7', '#bcbd22', '#dbdb8d',
                            '#17becf', '#9edae5'];

var CHART_DEFAULT_TOOLTIP_CALLBACK = function (item, data) {
  var label = data.labels[item.index];
  var value = data.datasets[item.datasetIndex].tooltips[item.index] || data.datasets[item.datasetIndex].data[item.index];
  return label + ": " + value;
};

/* From http://www.localeplanet.com/api/auto/currencymap.json */
var FIAT_CURRENCY_MAP = {
  "USD": {
    "symbol": "$",
    "symbol_native": "$",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "USD"
  },
  "EUR": {
    "symbol": "€",
    "symbol_native": "€",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "EUR"
  },
  "GBP": {
    "symbol": "£",
    "symbol_native": "£",
    "decimal_digits": 2,
    "rounding": 0,
    "code": "GBP"
  },
  "JPY": {
    "symbol": "¥",
    "symbol_native": "￥",
    "decimal_digits": 0,
    "rounding": 0,
    "code": "JPY"
  },
  "KRW": {
    "symbol": "₩",
    "symbol_native": "₩",
    "decimal_digits": 0,
    "rounding": 0,
    "code": "KRW"
  },
};

var FIAT_CURRENCY_DEFAULT = "USD";

/******************************************************************************/
/* Logger */
/******************************************************************************/

Logger = {
  enable: function () { Logger.log = Logger._log_console; },
  disable: function () { Logger.log = Logger._log_null; },

  _log_console: console.log.bind(window.console),
  _log_null: function (s) { },

  log: null,
  error: console.error.bind(window.console),
};
<|endoftext|>


<commit_before>/* eslint-disable mocha/no-top-level-hooks */

import { beforeEach, afterEach } from 'mocha';

import startApp from 'skylines/tests/helpers/start-app';
import destroyApp from 'skylines/tests/helpers/destroy-app';

export default function setupAcceptanceTest() {
  beforeEach(function() {
    this.application = startApp();
  });

  afterEach(function() {
    destroyApp(this.application);
  });
}
<commit_msg>tests: Start pretender automatically for all acceptance tests<commit_after>/* eslint-disable mocha/no-top-level-hooks */

import { beforeEach, afterEach } from 'mocha';
import Pretender from 'pretender';

import startApp from 'skylines/tests/helpers/start-app';
import destroyApp from 'skylines/tests/helpers/destroy-app';

export default function setupAcceptanceTest() {
  beforeEach(function() {
    this.server = new Pretender(function() {
      this.get('/translations/:locale.json', this.passthrough);
    });

    this.application = startApp();
  });

  afterEach(function() {
    destroyApp(this.application);

    this.server.shutdown();
  });
}
<|endoftext|>


<commit_before>var express = require('express');
var fs = require('fs');
var bp = require('body-parser');
var https = require('https');
var argv = require('yargs')
  .default('p', 8901)
  .number('p')
  .argv;

process.env.UV_THREADPOOL_SIZE = 42;

var frame = fs.readFileSync('./essence/frame3.pgrp');

var app = express();
app.use(bp.raw({ limit : 6000000 }));

app.get('/essence', function (req, res) {
  res.send(frame);
});

var pushCount = 0;
var startTime = process.hrtime();

app.post('/essence', function (req, res) {
  if (pushCount === 0) startTime = process.hrtime();
  console.log(pushCount++, process.hrtime(startTime), req.body.length);
  res.json({ wibble : 'wibble' });
});

var server = https.createServer({
  key : fs.readFileSync('./gonzales.pem'),
  cert : fs.readFileSync('./gonzales-cert.pem')
}, app).listen(argv.p);

server.on('listening', () => {
  console.log(`Gonzales HTTPS server listining on port ${argv.p}.`);
});

server.on('connection', (s) => {
  console.log(`Gonzales HTTPS server new connection ${s.address().address}.`);
  s.setNoDelay(true);
});
server.on('error', console.error);
<commit_msg>Adding date to logging.<commit_after>var express = require('express');
var fs = require('fs');
var bp = require('body-parser');
var https = require('https');
var argv = require('yargs')
  .default('p', 8901)
  .number('p')
  .argv;

process.env.UV_THREADPOOL_SIZE = 42;

var frame = fs.readFileSync('./essence/frame3.pgrp');

var app = express();
app.use(bp.raw({ limit : 6000000 }));

app.get('/essence', function (req, res) {
  res.send(frame);
});

var pushCount = 0;
var startTime = process.hrtime();

app.post('/essence', function (req, res) {
  if (pushCount === 0) startTime = process.hrtime();
  console.log(pushCount++, process.hrtime(startTime), req.body.length);
  res.json({ wibble : 'wibble' });
});

var server = https.createServer({
  key : fs.readFileSync('./gonzales.pem'),
  cert : fs.readFileSync('./gonzales-cert.pem')
}, app).listen(argv.p);

server.on('listening', () => {
  console.log(`Gonzales HTTPS server listining on port ${argv.p}.`);
});

var date = () => { return new Date().toISOString(); }
server.on('connection', (s) => {
  console.log(`${date}: Gonzales HTTPS server new connection ${s.address().address}.`);
  s.setNoDelay(true);
});
server.on('error', console.error);
<|endoftext|>