<commit_before>/*
* @license Proprietary
* @copyright Copyright (c) 2014 borkedLabs - All Rights Reserved
*/

siggy2.Activity = siggy2.Activity || {};

siggy2.Activity.Thera = function(core)
{
	this.key = 'thera';
	this._updateTimeout = null;
	this.core = core;
	this.sigClocks = {};
	this.eolClocks = {};

	this.templateRow = Handlebars.compile( $("#template-thera-table-row").html() );

	this.table = $('#thera-exits-table tbody');

	var tableSorterHeaders = {
		0: {
			sortInitialOrder: 'asc'
		},
	};

	$('#thera-exits-table').tablesorter(
	{
		headers: tableSorterHeaders
	});

	$('#thera-exits-table').trigger("sorton", [ [[0,0]] ]);
}

siggy2.Activity.Thera.prototype.start = function()
{
	$('#activity-' + this.key).show();
	this.update();
}

siggy2.Activity.Thera.prototype.stop = function()
{
	clearTimeout(this._updateTimeout);
	$('#activity-' + this.key).hide();
}

siggy2.Activity.Thera.prototype.update = function()
{
	var $this = this;
	$.ajax({
				url: this.core.settings.baseUrl + 'thera/latest_exits',
				dataType: 'json',
				cache: false,
				async: true,
				method: 'get',
				success: function (data)
				{
					$this.updateTable(data);

					$this._updateTimeout = setTimeout(function(thisObj)
					{
						thisObj.update()
					}, 10000, $this);
				}
		});
}

siggy2.Activity.Thera.prototype.updateTable = function( exits )
{
	var $this = this;

	$('#thera-exits-table tbody tr').each(function()
	{
		var id = $(this).data('id');

		if( typeof exits[id] == 'undefined' )
		{
			$(this).children('td.wormhole-type').qtip('destroy');

			if( typeof $this.sigClocks[id] != 'undefined' )
			{
				$this.sigClocks[i].destroy();
				delete $this.sigClocks[i];
			}

			if( typeof $this.eolClocks[id] != 'undefined' )
			{
				$this.eolClocks[i].destroy();
				delete $this.eolClocks[i];
			}

			$(this).remove();
		}
		else
		{
			exits[id].row_already_exists = true;
		}
	});

	for( var i in exits )
	{
		var exit = exits[i];
		if( exit.row_already_exists )
			continue;

		var wh = siggy2.StaticData.getWormholeByID(exit.wormhole_type);

		if( wh != null )
		{
			desc_tooltip = siggy2.StaticData.templateWormholeInfoTooltip(wh);
			exit.wormhole_name = wh.name;
		}

		var row = this.templateRow( exit );

		this.table.append(row);

		this.sigClocks[exit.id] = new siggy2.Timer(exit.created_at * 1000, null, '#thera-sig-' + exit.id + ' td.age span.age-clock', "test");

		if( wh != null )
		{
			var endDate = parseInt(exit.created_at)+(3600*wh.lifetime);
			this.eolClocks[exit.id] = new siggy2.Timer(exit.created_at * 1000, endDate* 1000, '#thera-sig-' + exit.id + ' td.age p.eol-clock', "test");
		}

		$('#thera-sig-' + exit.id + ' td.wormhole-type').qtip({
			content: {
				text: desc_tooltip
			},
			position: {
				target: 'mouse',
				adjust: { x: 5, y: 5 },
				viewport: $(window)
			}
		});
	}

	$('#thera-exits-table').trigger('update');
}
<commit_msg>Poll thera exits every 60 seconds only.<commit_after>/*
* @license Proprietary
* @copyright Copyright (c) 2014 borkedLabs - All Rights Reserved
*/

siggy2.Activity = siggy2.Activity || {};

siggy2.Activity.Thera = function(core)
{
	this.key = 'thera';
	this._updateTimeout = null;
	this.core = core;
	this.sigClocks = {};
	this.eolClocks = {};

	this.templateRow = Handlebars.compile( $("#template-thera-table-row").html() );

	this.table = $('#thera-exits-table tbody');

	var tableSorterHeaders = {
		0: {
			sortInitialOrder: 'asc'
		},
	};

	$('#thera-exits-table').tablesorter(
	{
		headers: tableSorterHeaders
	});

	$('#thera-exits-table').trigger("sorton", [ [[0,0]] ]);
}

siggy2.Activity.Thera.prototype.start = function()
{
	$('#activity-' + this.key).show();
	this.update();
}

siggy2.Activity.Thera.prototype.stop = function()
{
	clearTimeout(this._updateTimeout);
	$('#activity-' + this.key).hide();
}

siggy2.Activity.Thera.prototype.update = function()
{
	var $this = this;
	$.ajax({
				url: this.core.settings.baseUrl + 'thera/latest_exits',
				dataType: 'json',
				cache: false,
				async: true,
				method: 'get',
				success: function (data)
				{
					$this.updateTable(data);

					$this._updateTimeout = setTimeout(function(thisObj)
					{
						thisObj.update()
					}, 60000, $this);
				}
		});
}

siggy2.Activity.Thera.prototype.updateTable = function( exits )
{
	var $this = this;

	$('#thera-exits-table tbody tr').each(function()
	{
		var id = $(this).data('id');

		if( typeof exits[id] == 'undefined' )
		{
			$(this).children('td.wormhole-type').qtip('destroy');

			if( typeof $this.sigClocks[id] != 'undefined' )
			{
				$this.sigClocks[i].destroy();
				delete $this.sigClocks[i];
			}

			if( typeof $this.eolClocks[id] != 'undefined' )
			{
				$this.eolClocks[i].destroy();
				delete $this.eolClocks[i];
			}

			$(this).remove();
		}
		else
		{
			exits[id].row_already_exists = true;
		}
	});

	for( var i in exits )
	{
		var exit = exits[i];
		if( exit.row_already_exists )
			continue;

		var wh = siggy2.StaticData.getWormholeByID(exit.wormhole_type);

		if( wh != null )
		{
			desc_tooltip = siggy2.StaticData.templateWormholeInfoTooltip(wh);
			exit.wormhole_name = wh.name;
		}

		var row = this.templateRow( exit );

		this.table.append(row);

		this.sigClocks[exit.id] = new siggy2.Timer(exit.created_at * 1000, null, '#thera-sig-' + exit.id + ' td.age span.age-clock', "test");

		if( wh != null )
		{
			var endDate = parseInt(exit.created_at)+(3600*wh.lifetime);
			this.eolClocks[exit.id] = new siggy2.Timer(exit.created_at * 1000, endDate* 1000, '#thera-sig-' + exit.id + ' td.age p.eol-clock', "test");
		}

		$('#thera-sig-' + exit.id + ' td.wormhole-type').qtip({
			content: {
				text: desc_tooltip
			},
			position: {
				target: 'mouse',
				adjust: { x: 5, y: 5 },
				viewport: $(window)
			}
		});
	}

	$('#thera-exits-table').trigger('update');
}
<|endoftext|>


<commit_before>if (typeof _ === "undefined") {
    var _ = require("./underscore");
}
var world = function () {
    var gridH = 25;
	var gridW = 25;
    var grid = [];
    var players =  [];
    var minPlayersToStart = 1;
    var maxPlayers = 4;

    var howManyPlayers = function() {return players.length;};
    var timerId = 0;
    var io = null;
    // last tick value
    var lastTick;
    // the update interval in ms
    var cycleSpeedMs = 1000;
    // the players speed in units per second
    var playerSpeed = 1;
    // the players move at units (direction) per second (rate).
    var playerRate = 1000;
    // the current tick spinner (a 1 second tick spinner) - used to figure out when a second is up
    var tickSpinner = 0;
    var chatLog = [];

    var playerDiedCallback = function() {
        console.log("Player died");

    };

    var resetGameCallback = function() {};

    function getPlayerIndexById(id) {
        for (var i = 0, l = players.length; i < l; i++) {
            if(players[i].id == id)
                return i;
        }

        return -1;
    }

    function getPlayerById(id) {
        return players[getPlayerIndexById(id)];
    }

    function roundedPos(pos) {
        return {x: Math.round(pos.x), y: Math.round(pos.y)};
    }

    // TODO: Stop this from really dark colors
    function getRandomColor() {
        var letters = '0123456789ABCDEF'.split('');
        var color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.round(Math.random() * 15)];
        }
        return color;
    }

    function getPlayerData() {
        var playas = [];
        for (var i = 0, p; p = players[i++];) {
                var playaObj = {};
                _.extend(playaObj, p, {pos:roundedPos(p.pos)});
                playas.push(playaObj);
        }
        return playas;
    }

    // add a player to the world
    var addPlayer = function(player) {
    	console.log("add player: " + JSON.stringify(player));
        player.color = getRandomColor();
        player.status = "playing";
        if (getPlayerIndexById(player.id)===-1 && players.length < maxPlayers){
    	    players.push(player);
            setInitPosition(getPlayerIndexById(player.id));
            console.log(players);
        }
    };

    function setInitPosition(i) {
        _.extend(players[i], getInitCoordsAndDir(i));
    }

    var removePlayerById = function(id) {
        var pIndex = getPlayerIndexById(id);
        if (pIndex >=0)
            players.remove(pIndex);
    }

    function getDirObj(d){
        var dir;
        switch (d) {
              case 'w': dir = {x:-playerSpeed, y:0}; break;
	          case 'n': dir = {x:0, y:-playerSpeed}; break;
	          case 'e': dir = {x:playerSpeed, y:0}; break;
	          case 's': dir = {x:0, y:playerSpeed}; break;
	          default: return;
	        }
        return dir;
    }

    var updatePlayerDirById = function(id, dirStr) {
        var pIndex = getPlayerIndexById(id);
        var dir;
        if (pIndex >=0) {
        	dir = getDirObj(dirStr);
	        //console.log(dir);

            _.extend(players[pIndex], {newDir:dir});
            console.log("update player: " + JSON.stringify(players[pIndex]));
        }
    }

    var getPlayerNameById = function(id) {
        return players[getPlayerIndexById(id)].name;
    }

    var getPlayerColorById = function(id) {
        return players[getPlayerIndexById(id)].color;
    }

    function getInitCoordsAndDir(i){
        var x,y,dir,retObj;
        switch (i) {
            case 0:
                x = 0;
                y = 0;
                dir = "e";
                break;
            case 1:
                x = gridW - 1;
                y = 0;
                dir = "s";
                break;
            case 2:
                x=gridW - 1;
                y=gridH - 1;
                dir="w"
                break;
            case 3:
                x=0;
                y=gridH - 1;
                dir="n";
            default:
                break;
        }
        retObj =  {pos:{x:x,y:y},newDir:getDirObj(dir)};
        return retObj;
    }

    // initialize the world model for a new game.
    var initWorld = function() {
    	grid = new Array(gridW)

		  for (var i = 0; i < gridW; i++) {
			  grid[i]=new Array(gridH);
		  }

		// start players off in a direction when game starts
		//for (var i = 0; i < players.length; i++) {
		//	players[i].dir.x = playerSpeed;
		//}
    }
    function playerHitBorder(player) {
        return (player.pos.x < 0 || player.pos.x >= gridW ||
                player.pos.y < 0 || player.pos.y >= gridH);
    }

    // determines if player can move in the desired new direction
    function updatePlayerDirection(player) {
    	var deltaX = player.dir.x + player.newDir.x;
    	var deltaY = player.dir.y + player.newDir.y;

    	// double back - invalid
    	if (deltaX == 0 && deltaY == 0) {
    		player.newDir = player.dir;
    	} else {
    		player.dir = player.newDir;
    	}
    }

    // update the world state
    var crank = function(tick) {
		// elapsed ticks
		var dt = tick - lastTick;
		tickSpinner += dt;

		// elapsed per second clock rate (how much time in seconds has elapsed since last cycle)
		//var dRate = (dt / playerRate);

		// update player positions if a second has elapsed
		if (tickSpinner > 1000) {
			//console.log("crank - delta: " + dt + " tick: " + tick);
			// update player positions
			for (var i = 0; i < players.length; i++) {

				if (!players[i] || !players[i].pos || !players[i].dir)
				    continue;

                if (players[i].status != "playing")
                    continue;

				// applies desired direction change if valid
				updatePlayerDirection(players[i]);

				// spatial float position updates (overkill currently)
				//players[i].pos.x += players[i].dir.x * dRate;
				//players[i].pos.y += players[i].dir.y * dRate;
				players[i].pos.x += players[i].dir.x;
				players[i].pos.y += players[i].dir.y;

				//console.log("* " + players[i].pos.x + " - " + players[i].pos.y + " - " + grid[players[i].pos.x, players[i].pos.y]);
				// collision
				//console.log(grid[players[i].pos.x][players[i].pos.y]);
				if (playerHitBorder(players[i]) || grid[players[i].pos.x][players[i].pos.y]) {
				    console.log("player " + players[i].id +
					  " collision at (" + players[i].pos.x + "," + players[i].pos.y + ")");
				    playerDiedCallback(players[i]);
                    players[i].status = "dead";

				} else {
    				grid[players[i].pos.x][players[i].pos.y] = players[i].id;
				}

				//console.log("player " + players[i].id + " - (" + players[i].pos.x + "," + players[i].pos.y + ")");
			}

			tickSpinner %= 1000; // spin around
		}
    };

    function addDummyPlayers(){
    	addPlayer({id:"leo", pos:{x:10, py:10}, dir:{x:10, y:2}});
		addPlayer({id:"mike", pos:{x:10, py:10}, dir:{x:10, y:2}});
		addPlayer({id:"ralph", pos:{x:10, py:10}, dir:{x:10, y:2}});
		addPlayer({id:"don", pos:{x:10, py:10}, dir:{x:10, y:2}});
    }

    // debug
    var godSays = function(data) {
    	if (data.message == "startCycle") {
    		console.log("force cycle start");
    		initWorld();
    		startCycle();
    	}
    	else if (data.message == "setCycle") {
    		console.log("set cycle speed");
    		setCycleSpeed(data.arg1);
    	}
    	else if (data.message == "dummyPlayers") {
    		addDummyPlayers();
    	}
    };

    // synchronous cycle update
    var update = function() {
        // tick tock
        var tick = (new Date()).getTime();

        crank(tick);

        // broadcast world state
        if (io) {
            io.sockets.volatile.emit('update', {"tick": tick, "playaData":getPlayerData()});
        }

        lastTick = tick;
    };

    // start the game
    var init = function() {
        if (timerId || howManyPlayers() < minPlayersToStart)
            return;

        initWorld();
        startCycle();
    };

    var resetGame =  function() {
        clearTimeout(timerId);
        timerId = 0;
        for (var i = 0; i<players.length; i++) {
          _.extend(players[i], getInitCoordsAndDir(i));
          resetGameCallback(players[i]);
        }
        initWorld();
        startCycle();

    };
    var startCycle = function() {
    	lastTick = (new Date()).getTime();
    	timerId = setInterval(world.update, cycleSpeedMs);
    };
    var setIo = function(pIo) {
        io = pIo;
    };
    var setCycleSpeed = function(ms) {
    	clearInterval(timerId);
    	cycleSpeedMs = ms;
    	startCycle();
    }
    var addChatMessage = function(msgText, playerId) {
        var player = getPlayerById(playerId),
            message = {msg: msgText, name: player.name || "Anon", color: player.color};

        console.log(player);
        chatLog.push(message);

        return message;
    };

    var getChatLog = function() {
        return _.clone(chatLog);
    };

    var updatePlayerById = function(id, obj) {
        var pIndex = getPlayerIndexById(id);
            _.extend(players[pIndex], obj);
            console.log("update player: " + JSON.stringify(players[pIndex]));
    };

    var setPlayerDiedCallback = function (callback) {
        playerDiedCallback = callback;
    };

    var setResetGameCallback = function (callback) {
        resetGameCallback = callback;
    };

    return {
        addPlayer:addPlayer ,
        howManyPlayers:howManyPlayers,
        update:update,
        init:init,
        setIo: setIo,
        godSays: godSays,
        removePlayerById: removePlayerById,
        getChatLog: getChatLog,
        addChatMessage: addChatMessage,
        updatePlayerDirById: updatePlayerDirById,
        updatePlayerById: updatePlayerById,
        setPlayerDiedCallback: setPlayerDiedCallback,
        getPlayerNameById: getPlayerNameById,
        getPlayerColorById: getPlayerColorById,
        resetGame: resetGame,
        setResetGameCallback: setResetGameCallback
    };
}();

if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = world;
    }
    exports.testingObj = world;
}<commit_msg>Reset the player status when you reset the game<commit_after>if (typeof _ === "undefined") {
    var _ = require("./underscore");
}
var world = function () {
    var gridH = 25;
	var gridW = 25;
    var grid = [];
    var players =  [];
    var minPlayersToStart = 1;
    var maxPlayers = 4;

    var howManyPlayers = function() {return players.length;};
    var timerId = 0;
    var io = null;
    // last tick value
    var lastTick;
    // the update interval in ms
    var cycleSpeedMs = 1000;
    // the players speed in units per second
    var playerSpeed = 1;
    // the players move at units (direction) per second (rate).
    var playerRate = 1000;
    // the current tick spinner (a 1 second tick spinner) - used to figure out when a second is up
    var tickSpinner = 0;
    var chatLog = [];

    var playerDiedCallback = function() {
        console.log("Player died");

    };

    var resetGameCallback = function() {};

    function getPlayerIndexById(id) {
        for (var i = 0, l = players.length; i < l; i++) {
            if(players[i].id == id)
                return i;
        }

        return -1;
    }

    function getPlayerById(id) {
        return players[getPlayerIndexById(id)];
    }

    function roundedPos(pos) {
        return {x: Math.round(pos.x), y: Math.round(pos.y)};
    }

    // TODO: Stop this from really dark colors
    function getRandomColor() {
        var letters = '0123456789ABCDEF'.split('');
        var color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.round(Math.random() * 15)];
        }
        return color;
    }

    function getPlayerData() {
        var playas = [];
        for (var i = 0, p; p = players[i++];) {
                var playaObj = {};
                _.extend(playaObj, p, {pos:roundedPos(p.pos)});
                playas.push(playaObj);
        }
        return playas;
    }

    // add a player to the world
    var addPlayer = function(player) {
    	console.log("add player: " + JSON.stringify(player));
        player.color = getRandomColor();
        player.status = "playing";
        if (getPlayerIndexById(player.id)===-1 && players.length < maxPlayers){
    	    players.push(player);
            setInitPosition(getPlayerIndexById(player.id));
            console.log(players);
        }
    };

    function setInitPosition(i) {
        _.extend(players[i], getInitCoordsAndDir(i));
    }

    var removePlayerById = function(id) {
        var pIndex = getPlayerIndexById(id);
        if (pIndex >=0)
            players.remove(pIndex);
    }

    function getDirObj(d){
        var dir;
        switch (d) {
              case 'w': dir = {x:-playerSpeed, y:0}; break;
	          case 'n': dir = {x:0, y:-playerSpeed}; break;
	          case 'e': dir = {x:playerSpeed, y:0}; break;
	          case 's': dir = {x:0, y:playerSpeed}; break;
	          default: return;
	        }
        return dir;
    }

    var updatePlayerDirById = function(id, dirStr) {
        var pIndex = getPlayerIndexById(id);
        var dir;
        if (pIndex >=0) {
        	dir = getDirObj(dirStr);
	        //console.log(dir);

            _.extend(players[pIndex], {newDir:dir});
            console.log("update player: " + JSON.stringify(players[pIndex]));
        }
    }

    var getPlayerNameById = function(id) {
        return players[getPlayerIndexById(id)].name;
    }

    var getPlayerColorById = function(id) {
        return players[getPlayerIndexById(id)].color;
    }

    function getInitCoordsAndDir(i){
        var x,y,dir,retObj;
        switch (i) {
            case 0:
                x = 0;
                y = 0;
                dir = "e";
                break;
            case 1:
                x = gridW - 1;
                y = 0;
                dir = "s";
                break;
            case 2:
                x=gridW - 1;
                y=gridH - 1;
                dir="w"
                break;
            case 3:
                x=0;
                y=gridH - 1;
                dir="n";
            default:
                break;
        }
        retObj =  {pos:{x:x,y:y},newDir:getDirObj(dir)};
        return retObj;
    }

    // initialize the world model for a new game.
    var initWorld = function() {
    	grid = new Array(gridW)

		  for (var i = 0; i < gridW; i++) {
			  grid[i]=new Array(gridH);
		  }

		// start players off in a direction when game starts
		//for (var i = 0; i < players.length; i++) {
		//	players[i].dir.x = playerSpeed;
		//}
    }
    function playerHitBorder(player) {
        return (player.pos.x < 0 || player.pos.x >= gridW ||
                player.pos.y < 0 || player.pos.y >= gridH);
    }

    // determines if player can move in the desired new direction
    function updatePlayerDirection(player) {
    	var deltaX = player.dir.x + player.newDir.x;
    	var deltaY = player.dir.y + player.newDir.y;

    	// double back - invalid
    	if (deltaX == 0 && deltaY == 0) {
    		player.newDir = player.dir;
    	} else {
    		player.dir = player.newDir;
    	}
    }

    // update the world state
    var crank = function(tick) {
		// elapsed ticks
		var dt = tick - lastTick;
		tickSpinner += dt;

		// elapsed per second clock rate (how much time in seconds has elapsed since last cycle)
		//var dRate = (dt / playerRate);

		// update player positions if a second has elapsed
		if (tickSpinner > 1000) {
			//console.log("crank - delta: " + dt + " tick: " + tick);
			// update player positions
			for (var i = 0; i < players.length; i++) {

				if (!players[i] || !players[i].pos || !players[i].dir)
				    continue;

                if (players[i].status != "playing")
                    continue;

				// applies desired direction change if valid
				updatePlayerDirection(players[i]);

				// spatial float position updates (overkill currently)
				//players[i].pos.x += players[i].dir.x * dRate;
				//players[i].pos.y += players[i].dir.y * dRate;
				players[i].pos.x += players[i].dir.x;
				players[i].pos.y += players[i].dir.y;

				//console.log("* " + players[i].pos.x + " - " + players[i].pos.y + " - " + grid[players[i].pos.x, players[i].pos.y]);
				// collision
				//console.log(grid[players[i].pos.x][players[i].pos.y]);
				if (playerHitBorder(players[i]) || grid[players[i].pos.x][players[i].pos.y]) {
				    console.log("player " + players[i].id +
					  " collision at (" + players[i].pos.x + "," + players[i].pos.y + ")");
				    playerDiedCallback(players[i]);
                    players[i].status = "dead";

				} else {
    				grid[players[i].pos.x][players[i].pos.y] = players[i].id;
				}

				//console.log("player " + players[i].id + " - (" + players[i].pos.x + "," + players[i].pos.y + ")");
			}

			tickSpinner %= 1000; // spin around
		}
    };

    function addDummyPlayers(){
    	addPlayer({id:"leo", pos:{x:10, py:10}, dir:{x:10, y:2}});
		addPlayer({id:"mike", pos:{x:10, py:10}, dir:{x:10, y:2}});
		addPlayer({id:"ralph", pos:{x:10, py:10}, dir:{x:10, y:2}});
		addPlayer({id:"don", pos:{x:10, py:10}, dir:{x:10, y:2}});
    }

    // debug
    var godSays = function(data) {
    	if (data.message == "startCycle") {
    		console.log("force cycle start");
    		initWorld();
    		startCycle();
    	}
    	else if (data.message == "setCycle") {
    		console.log("set cycle speed");
    		setCycleSpeed(data.arg1);
    	}
    	else if (data.message == "dummyPlayers") {
    		addDummyPlayers();
    	}
    };

    // synchronous cycle update
    var update = function() {
        // tick tock
        var tick = (new Date()).getTime();

        crank(tick);

        // broadcast world state
        if (io) {
            io.sockets.volatile.emit('update', {"tick": tick, "playaData":getPlayerData()});
        }

        lastTick = tick;
    };

    // start the game
    var init = function() {
        if (timerId || howManyPlayers() < minPlayersToStart)
            return;

        initWorld();
        startCycle();
    };

    var resetGame =  function() {
        clearTimeout(timerId);
        timerId = 0;
        for (var i = 0; i<players.length; i++) {
          _.extend(players[i], getInitCoordsAndDir(i), {"status": "playing"});
          resetGameCallback(players[i]);
        }
        initWorld();
        startCycle();

    };
    var startCycle = function() {
    	lastTick = (new Date()).getTime();
    	timerId = setInterval(world.update, cycleSpeedMs);
    };
    var setIo = function(pIo) {
        io = pIo;
    };
    var setCycleSpeed = function(ms) {
    	clearInterval(timerId);
    	cycleSpeedMs = ms;
    	startCycle();
    }
    var addChatMessage = function(msgText, playerId) {
        var player = getPlayerById(playerId),
            message = {msg: msgText, name: player.name || "Anon", color: player.color};

        console.log(player);
        chatLog.push(message);

        return message;
    };

    var getChatLog = function() {
        return _.clone(chatLog);
    };

    var updatePlayerById = function(id, obj) {
        var pIndex = getPlayerIndexById(id);
            _.extend(players[pIndex], obj);
            console.log("update player: " + JSON.stringify(players[pIndex]));
    };

    var setPlayerDiedCallback = function (callback) {
        playerDiedCallback = callback;
    };

    var setResetGameCallback = function (callback) {
        resetGameCallback = callback;
    };

    return {
        addPlayer:addPlayer ,
        howManyPlayers:howManyPlayers,
        update:update,
        init:init,
        setIo: setIo,
        godSays: godSays,
        removePlayerById: removePlayerById,
        getChatLog: getChatLog,
        addChatMessage: addChatMessage,
        updatePlayerDirById: updatePlayerDirById,
        updatePlayerById: updatePlayerById,
        setPlayerDiedCallback: setPlayerDiedCallback,
        getPlayerNameById: getPlayerNameById,
        getPlayerColorById: getPlayerColorById,
        resetGame: resetGame,
        setResetGameCallback: setResetGameCallback
    };
}();

if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = world;
    }
    exports.testingObj = world;
}<|endoftext|>


<commit_before>'use strict';
/*global utils, app*/

$(window).on('action:composer.submit', function(ev, data) {
    // data.composerEl is the dom element for the composer
    // data.action can be `topics.post`, `posts.reply` or `posts.edit`
    // data.composerData is the object that will be submitted to the server.

    // lets add our new field into the data to be submitted for new topics
    if (data.action === 'topics.post') {

    	var cid = data.composerData.cid;

    	if (cid >= 19 && cid <= 30) {
			var age = data.composerEl.find('#age').val() || "None";
			var sex = data.composerEl.find('#sex').val() || "None";
			var ecog = data.composerEl.find('#ecog-ps').val() || "None";
			var abnormalFunc = data.composerEl.find('#abnormal-function').val() || "None";
			var abnormalLab = data.composerEl.find('#abnormal-labs').val() || "None";
			var mutation = data.composerEl.find('#mutation-status').val() || "None";

			var priorLines, linesArray = $('input[type=checkbox]:checked').map(function(){
	      		return $(this).val();
	    	}).get();

	    	if (linesArray.length == 0) {
			    priorLines = "None";
			}
			else {
			    priorLines = linesArray.join(', ');
			}

			var priorInterv = data.composerEl.find('#prior-intervention').val() || "None";
			var progression = data.composerEl.find('#progression-history').val() || "None";
			var questions = data.composerEl.find('#questions').val() || "None";

			data.composerData.formData = {
				age: age,
				sex: sex,
				ecog: ecog,
				abnormalFunc: abnormalFunc,
				abnormalLab: abnormalLab,
				mutation: mutation,
				priorLines: priorLines,
				priorInterv: priorInterv,
				progression: progression,
				questions: questions
			};

			data.composerData.message = `## **Question/Inquiry**
---
${questions}
## **Case Information**
---
**Age:** ${age}
**Sex:** ${sex}
**ECOG PS:** ${ecog}
**Abnormal Organ Function:** ${abnormalFunc}
**Abnormal Labs:** ${abnormalLab}
**Mutation Status:** ${mutation}
**Prior Lines of Therapy:** ${priorLines}
**Prior Intervention(s):** ${priorInterv}
**Progression History:** ${progression}
**Additional Information:** `;

		}

		else if (cid == 37) {
			var oncologyField = data.composerEl.find('#oncology-field').val() || "None";
			var studyType = data.composerEl.find('#study-type').val() || "None";
			var location = data.composerEl.find('#location').val() || "None";
			var sponsor = data.composerEl.find('#sponsor').val() || "None";

			var inclusionCriteria, inclusionArray = data.composerEl.find('#inclusion-criteria').val().split(',');
			var exclusionCriteria, exclusionArray = data.composerEl.find('#exclusion-criteria').val().split(',');

			if (inclusionArray.length == 0) {
			    inclusionCriteria = "None";
			}

			else {
			    for (criteria in inclusionArray) {
			    	inclusionCriteria += "*" + criteria + "  ";
			    }
			}

			if (exclusionArray.length == 0) {
			    exclusionCriteria = "None";
			}

			else {
			    for (criteria in exclusionArray) {
			    	exclusionCriteria += "*" + criteria + "  ";
			    }
			}

			var phase = data.composerEl.find('#phase').val() || "None";
			var contactInfo = data.composerEl.find('#contact-info').val() || "None";

			data.composerData.formData = {
				oncologyField: oncologyField,
				studyType: studyType,
				location: location,
				sponsor: sponsor,
				inclusionCriteria: inclusionCriteria,
				exclusionCriteria: exclusionCriteria,
				phase: phase,
				contactInfo: contactInfo
			};

			data.composerData.message = `## **New Clinical Trial**
---
**Tumor Type:** ${oncologyField}
**Study Type:** ${studyType}
**Location(s):** ${location}
**Sponsor:** ${sponsor}
**Inclusion Criteria:** ${inclusionCriteria}
**Exclusion Criteria:** ${exclusionCriteria}
**Phase:** ${phase}
**Contact Information:** ${contactInfo}
**Additional Information:** `;
		}

		else if ((cid >= 33 && cid <= 36) || cid == 31) {
			var oncologyField = data.composerEl.find('#oncology-field').val() || "None";

			data.composerData.formData = {
				oncologyField: oncologyField
			};

			data.composerData.message = `## **New Treatment Modality**
---
**Tumor Type:** ${oncologyField}
**Modality Information:** `;
		}
	}
});<commit_msg>Fix For loop and new line on criteria<commit_after>'use strict';
/*global utils, app*/

$(window).on('action:composer.submit', function(ev, data) {
    // data.composerEl is the dom element for the composer
    // data.action can be `topics.post`, `posts.reply` or `posts.edit`
    // data.composerData is the object that will be submitted to the server.

    // lets add our new field into the data to be submitted for new topics
    if (data.action === 'topics.post') {

    	var cid = data.composerData.cid;

    	if (cid >= 19 && cid <= 30) {
			var age = data.composerEl.find('#age').val() || "None";
			var sex = data.composerEl.find('#sex').val() || "None";
			var ecog = data.composerEl.find('#ecog-ps').val() || "None";
			var abnormalFunc = data.composerEl.find('#abnormal-function').val() || "None";
			var abnormalLab = data.composerEl.find('#abnormal-labs').val() || "None";
			var mutation = data.composerEl.find('#mutation-status').val() || "None";

			var priorLines, linesArray = $('input[type=checkbox]:checked').map(function(){
	      		return $(this).val();
	    	}).get();

	    	if (linesArray.length == 0) {
			    priorLines = "None";
			}
			else {
			    priorLines = linesArray.join(', ');
			}

			var priorInterv = data.composerEl.find('#prior-intervention').val() || "None";
			var progression = data.composerEl.find('#progression-history').val() || "None";
			var questions = data.composerEl.find('#questions').val() || "None";

			data.composerData.formData = {
				age: age,
				sex: sex,
				ecog: ecog,
				abnormalFunc: abnormalFunc,
				abnormalLab: abnormalLab,
				mutation: mutation,
				priorLines: priorLines,
				priorInterv: priorInterv,
				progression: progression,
				questions: questions
			};

			data.composerData.message = `## **Question/Inquiry**
---
${questions}
## **Case Information**
---
**Age:** ${age}
**Sex:** ${sex}
**ECOG PS:** ${ecog}
**Abnormal Organ Function:** ${abnormalFunc}
**Abnormal Labs:** ${abnormalLab}
**Mutation Status:** ${mutation}
**Prior Lines of Therapy:** ${priorLines}
**Prior Intervention(s):** ${priorInterv}
**Progression History:** ${progression}
**Additional Information:** `;

		}

		else if (cid == 37) {
			var oncologyField = data.composerEl.find('#oncology-field').val() || "None";
			var studyType = data.composerEl.find('#study-type').val() || "None";
			var location = data.composerEl.find('#location').val() || "None";
			var sponsor = data.composerEl.find('#sponsor').val() || "None";

			var inclusionCriteria, inclusionArray = data.composerEl.find('#inclusion-criteria').val().split(',');
			var exclusionCriteria, exclusionArray = data.composerEl.find('#exclusion-criteria').val().split(',');

			if (inclusionArray.length == 0) {
			    inclusionCriteria = "None";
			}

			else {
			    for (criteria in inclusionArray) {
			    	inclusionCriteria += "*" + inclusionArray[criteria] + `<br />`;
			    }
			}

			if (exclusionArray.length == 0) {
			    exclusionCriteria = "None";
			}

			else {
			    for (criteria in exclusionArray) {
			    	exclusionCriteria += "*" + exclusionArray[criteria] + `<br />`;
			    }
			}

			var phase = data.composerEl.find('#phase').val() || "None";
			var contactInfo = data.composerEl.find('#contact-info').val() || "None";

			data.composerData.formData = {
				oncologyField: oncologyField,
				studyType: studyType,
				location: location,
				sponsor: sponsor,
				inclusionCriteria: inclusionCriteria,
				exclusionCriteria: exclusionCriteria,
				phase: phase,
				contactInfo: contactInfo
			};

			data.composerData.message = `## **New Clinical Trial**
---
**Tumor Type:** ${oncologyField}
**Study Type:** ${studyType}
**Location(s):** ${location}
**Sponsor:** ${sponsor}
**Inclusion Criteria:** ${inclusionCriteria}
**Exclusion Criteria:** ${exclusionCriteria}
**Phase:** ${phase}
**Contact Information:** ${contactInfo}
**Additional Information:** `;
		}

		else if ((cid >= 33 && cid <= 36) || cid == 31) {
			var oncologyField = data.composerEl.find('#oncology-field').val() || "None";

			data.composerData.formData = {
				oncologyField: oncologyField
			};

			data.composerData.message = `## **New Treatment Modality**
---
**Tumor Type:** ${oncologyField}
**Modality Information:** `;
		}
	}
});<|endoftext|>


<commit_before>$(document).ready(function() {

  function updateProgressBar(pct) {
      $('#current-progress').animate({width: pct+'%'}, 400);
  }

  function updateUI() {
      $.get("/status/"+window.installID, function(resp) {
          console.log(resp);
          if (resp.status == 'waiting for ssh') {
              $('#status-line').text('Waiting for SSH…');
              updateProgressBar(15);
          } else if (resp.status == 'waiting for http') {
              $('#status-line').text('Waiting for HTTP…');
              updateProgressBar(35);
          } else if (resp.status == 'creating client token') {
              $('#status-line').text('Creating client token…');
              updateProgressBar(95);
          } else if (resp.status == 'done') {
              $('#status-line').text('Install complete');
              updateProgressBar(100);
              $('#open-dashboard').attr('href', 'http://' + resp.client_token + '@' + resp.ip_address + '/dashboard');
              $('#core-info').css('display', 'block');
          } else if (resp.status == 'failed') {
              $('status-line').text('Install failed');
              updateProgressBar(0);
          }

          if (resp.status != 'done' && resp.status != 'failed') {
              setTimeout(updateUI, 1000);
          }
      });
  }

  updateUI();
});
<commit_msg>port 1999<commit_after>$(document).ready(function() {

  function updateProgressBar(pct) {
      $('#current-progress').animate({width: pct+'%'}, 400);
  }

  function updateUI() {
      $.get("/status/"+window.installID, function(resp) {
          console.log(resp);
          if (resp.status == 'waiting for ssh') {
              $('#status-line').text('Waiting for SSH…');
              updateProgressBar(15);
          } else if (resp.status == 'waiting for http') {
              $('#status-line').text('Waiting for HTTP…');
              updateProgressBar(35);
          } else if (resp.status == 'creating client token') {
              $('#status-line').text('Creating client token…');
              updateProgressBar(95);
          } else if (resp.status == 'done') {
              $('#status-line').text('Install complete');
              updateProgressBar(100);
              $('#open-dashboard').attr('href', 'http://' + resp.client_token + '@' + resp.ip_address + ':1999/dashboard');
              $('#core-info').css('display', 'block');
          } else if (resp.status == 'failed') {
              $('status-line').text('Install failed');
              updateProgressBar(0);
          }

          if (resp.status != 'done' && resp.status != 'failed') {
              setTimeout(updateUI, 1000);
          }
      });
  }

  updateUI();
});
<|endoftext|>


<commit_before>/*
 * Copyright 2009 Google Inc.
 *
 * 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.
 */

/**
 * @param dateObj
 * @param clearBody
 * @param opt_runTestLoop
 * @constructor
 */
jstestdriver.plugins.TestRunnerPlugin = function(dateObj, clearBody, opt_runTestLoop) {
  this.dateObj_ = dateObj;
  this.clearBody_ = clearBody;
  this.boundRunTest_ = jstestdriver.bind(this, this.runTest);
  this.runTestLoop_ = opt_runTestLoop || jstestdriver.plugins.defaultRunTestLoop;
};

jstestdriver.plugins.createPausingRunTestLoop =
    function (interval, now, setTimeout) {
  var lastPause;
  function pausingRunTestLoop(testCaseName,
                              template,
                              tests,
                              runTest,
                              onTest,
                              onComplete) {
    var i = 0;
    lastPause = now();
    function nextTest() {
      if (tests[i]) {
        var test = tests[i++];
        jstestdriver.log("running " + testCaseName + '.' + test);
        onTest(runTest(testCaseName, template, test));
        if (i > 20 || (now() - lastPause) >= interval) {
          jstestdriver.log("pausing after " + testCaseName + '.' + test);
          lastPause = now();
          setTimeout(nextTest, 1);
        } else {
          nextTest();
        }
      } else {
        onComplete();
      }
    }
    nextTest();
  }
  return pausingRunTestLoop;
};

jstestdriver.plugins.pausingRunTestLoop =
    jstestdriver.plugins.createPausingRunTestLoop(
        0,
        jstestdriver.now,
        jstestdriver.setTimeout);

jstestdriver.plugins.defaultRunTestLoop =
    function(testCaseName, template, tests, runTest, onTest, onComplete) {
  for (var i = 0; tests[i]; i++) {
    onTest(runTest(testCaseName, template, tests[i]));
  }
  onComplete();
};

jstestdriver.plugins.TestRunnerPlugin.prototype.runTestConfiguration =
    function(testRunConfiguration, onTestDone, onTestRunConfigurationComplete) {
  var testCaseInfo = testRunConfiguration.getTestCaseInfo();
  var tests = testRunConfiguration.getTests();
  var size = tests.length;

  if (testCaseInfo.getType() != jstestdriver.TestCaseInfo.DEFAULT_TYPE) {
    for (var i = 0; tests[i]; i++) {
      onTestDone(new jstestdriver.TestResult(
          testCaseInfo.getTestCaseName(),
          tests[i],
          'error',
          testCaseInfo.getTestCaseName() +
            ' is an unhandled test case: ' +
            testCaseInfo.getType(),
          '',
          0));
    }
    onTestRunConfigurationComplete();
    return;
  }

  this.runTestLoop_(testCaseInfo.getTestCaseName(),
                    testCaseInfo.getTemplate(),
                    tests,
                    this.boundRunTest_,
                    onTestDone,
                    onTestRunConfigurationComplete)
};

jstestdriver.plugins.TestRunnerPlugin.prototype.runTest =
    function(testCaseName, testCase, testName) {
  var testCaseInstance;
  var errors = [];
  try {
    try {
      testCaseInstance = new testCase();
    } catch (e) {
      return new jstestdriver.TestResult(
          testCaseName,
          testName,
          jstestdriver.TestResult.RESULT.ERROR,
          testCaseName + ' is not a test case',
          '',
          0);
    }
    var start = new this.dateObj_().getTime();

    jstestdriver.expectedAssertCount = -1;
    jstestdriver.assertCount = 0;
    var res = jstestdriver.TestResult.RESULT.PASSED;
    try {
      // Adding calls to clear down our application's static state
		if(typeof(br) != "undefined")
		{
			if(br.AliasRegistry && br.AliasRegistry.clear) {
				br.AliasRegistry.clear();
			}
			if(br.ServiceRegistry && br.ServiceRegistry.clear) {
				br.ServiceRegistry.clear();
			}
		}

      if (testCaseInstance.setUp) {
        testCaseInstance.setUp();
      }
      if (!(testName in testCaseInstance)) {
        var err = new Error(testName + ' not found in ' + testCaseName);
        err.name = 'AssertError';
        throw err;
      }
      testCaseInstance[testName]();
      if (jstestdriver.expectedAssertCount != -1 &&
          jstestdriver.expectedAssertCount != jstestdriver.assertCount) {
        var err = new Error("Expected '" +
            jstestdriver.expectedAssertCount +
            "' asserts but '" +
            jstestdriver.assertCount +
            "' encountered.");

        err.name = 'AssertError';
        throw err;
      }
    } catch (e) {
      // We use the global here because of a circular dependency. The isFailure plugin should be
      // refactored.
      res = jstestdriver.pluginRegistrar.isFailure(e) ?
          jstestdriver.TestResult.RESULT.FAILED :
            jstestdriver.TestResult.RESULT.ERROR;
      errors.push(e);
    }
    try {
      if (testCaseInstance.tearDown) {
        testCaseInstance.tearDown();
      }
      this.clearBody_();
    } catch (e) {
      if (res == jstestdriver.TestResult.RESULT.PASSED) {
        res = jstestdriver.TestResult.RESULT.ERROR;
      }
      errors.push(e);
    }
    var end = new this.dateObj_().getTime();
    var msg = this.serializeError(errors);
    return new jstestdriver.TestResult(testCaseName, testName, res, msg,
            jstestdriver.console.getAndResetLog(), end - start);
  } catch (e) {
    errors.push(e);
    return new jstestdriver.TestResult(testCaseName, testName,
            'error', 'Unexpected runner error: ' + this.serializeError(errors),
            jstestdriver.console.getAndResetLog(), 0);
  }
};

/**
 *@param {Error} e
 */
jstestdriver.plugins.TestRunnerPlugin.prototype.serializeError = function(e) {
  return jstestdriver.utils.serializeObject(e);
};
<commit_msg>Add require so commonjs can also call clear methods for alias and service registry<commit_after>/*
 * Copyright 2009 Google Inc.
 *
 * 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.
 */

/**
 * @param dateObj
 * @param clearBody
 * @param opt_runTestLoop
 * @constructor
 */
jstestdriver.plugins.TestRunnerPlugin = function(dateObj, clearBody, opt_runTestLoop) {
  this.dateObj_ = dateObj;
  this.clearBody_ = clearBody;
  this.boundRunTest_ = jstestdriver.bind(this, this.runTest);
  this.runTestLoop_ = opt_runTestLoop || jstestdriver.plugins.defaultRunTestLoop;
};

jstestdriver.plugins.createPausingRunTestLoop =
    function (interval, now, setTimeout) {
  var lastPause;
  function pausingRunTestLoop(testCaseName,
                              template,
                              tests,
                              runTest,
                              onTest,
                              onComplete) {
    var i = 0;
    lastPause = now();
    function nextTest() {
      if (tests[i]) {
        var test = tests[i++];
        jstestdriver.log("running " + testCaseName + '.' + test);
        onTest(runTest(testCaseName, template, test));
        if (i > 20 || (now() - lastPause) >= interval) {
          jstestdriver.log("pausing after " + testCaseName + '.' + test);
          lastPause = now();
          setTimeout(nextTest, 1);
        } else {
          nextTest();
        }
      } else {
        onComplete();
      }
    }
    nextTest();
  }
  return pausingRunTestLoop;
};

jstestdriver.plugins.pausingRunTestLoop =
    jstestdriver.plugins.createPausingRunTestLoop(
        0,
        jstestdriver.now,
        jstestdriver.setTimeout);

jstestdriver.plugins.defaultRunTestLoop =
    function(testCaseName, template, tests, runTest, onTest, onComplete) {
  for (var i = 0; tests[i]; i++) {
    onTest(runTest(testCaseName, template, tests[i]));
  }
  onComplete();
};

jstestdriver.plugins.TestRunnerPlugin.prototype.runTestConfiguration =
    function(testRunConfiguration, onTestDone, onTestRunConfigurationComplete) {
  var testCaseInfo = testRunConfiguration.getTestCaseInfo();
  var tests = testRunConfiguration.getTests();
  var size = tests.length;

  if (testCaseInfo.getType() != jstestdriver.TestCaseInfo.DEFAULT_TYPE) {
    for (var i = 0; tests[i]; i++) {
      onTestDone(new jstestdriver.TestResult(
          testCaseInfo.getTestCaseName(),
          tests[i],
          'error',
          testCaseInfo.getTestCaseName() +
            ' is an unhandled test case: ' +
            testCaseInfo.getType(),
          '',
          0));
    }
    onTestRunConfigurationComplete();
    return;
  }

  this.runTestLoop_(testCaseInfo.getTestCaseName(),
                    testCaseInfo.getTemplate(),
                    tests,
                    this.boundRunTest_,
                    onTestDone,
                    onTestRunConfigurationComplete)
};

jstestdriver.plugins.TestRunnerPlugin.prototype._invokeRegistryClearFunctions = function() {
  // Adding calls to clear down our application's static state
  var registries = [];
  if (typeof(br) !== "undefined") {
    registries.push(br.AliasRegistry);
    registries.push(br.ServiceRegistry);
  }
  else {
    try {
      registries.push(require('br/AliasRegistry'));
      registries.push(require('br/ServiceRegistry'));
    } catch (e) {
      // This exception is probably caused because the project
      // doesn't require the alias or service registry, so brjs
      // didn't bundle it.
    }
  }

  registries.forEach(
    function(registry) {
      if (registry && typeof registry.clear === 'function') {
        registry.clear();
      }
    }
  );
};

jstestdriver.plugins.TestRunnerPlugin.prototype.runTest = function(testCaseName, testCase, testName) {
  var testCaseInstance;
  var errors = [];
  try {
    try {
      testCaseInstance = new testCase();
    } catch (e) {
      return new jstestdriver.TestResult(
          testCaseName,
          testName,
          jstestdriver.TestResult.RESULT.ERROR,
          testCaseName + ' is not a test case',
          '',
          0);
    }
    var start = new this.dateObj_().getTime();

    jstestdriver.expectedAssertCount = -1;
    jstestdriver.assertCount = 0;
    var res = jstestdriver.TestResult.RESULT.PASSED;

    try {
      this._invokeRegistryClearFunctions();
      if (testCaseInstance.setUp) {
        testCaseInstance.setUp();
      }
      if (!(testName in testCaseInstance)) {
        var err = new Error(testName + ' not found in ' + testCaseName);
        err.name = 'AssertError';
        throw err;
      }
      testCaseInstance[testName]();
      if (jstestdriver.expectedAssertCount != -1 &&
          jstestdriver.expectedAssertCount != jstestdriver.assertCount) {
        var err = new Error("Expected '" +
            jstestdriver.expectedAssertCount +
            "' asserts but '" +
            jstestdriver.assertCount +
            "' encountered.");

        err.name = 'AssertError';
        throw err;
      }
    } catch (e) {
      // We use the global here because of a circular dependency. The isFailure plugin should be
      // refactored.
      res = jstestdriver.pluginRegistrar.isFailure(e) ?
          jstestdriver.TestResult.RESULT.FAILED :
            jstestdriver.TestResult.RESULT.ERROR;
      errors.push(e);
    }
    try {
      if (testCaseInstance.tearDown) {
        testCaseInstance.tearDown();
      }
      this.clearBody_();
    } catch (e) {
      if (res == jstestdriver.TestResult.RESULT.PASSED) {
        res = jstestdriver.TestResult.RESULT.ERROR;
      }
      errors.push(e);
    }
    var end = new this.dateObj_().getTime();
    var msg = this.serializeError(errors);
    return new jstestdriver.TestResult(testCaseName, testName, res, msg,
            jstestdriver.console.getAndResetLog(), end - start);
  } catch (e) {
    errors.push(e);
    return new jstestdriver.TestResult(testCaseName, testName,
            'error', 'Unexpected runner error: ' + this.serializeError(errors),
            jstestdriver.console.getAndResetLog(), 0);
  }
};

/**
 *@param {Error} e
 */
jstestdriver.plugins.TestRunnerPlugin.prototype.serializeError = function(e) {
  return jstestdriver.utils.serializeObject(e);
};
<|endoftext|>


<commit_before>import React from "react";

import {ButtonToolbar,Button, Col, ControlLabel, Form, FormControl, Panel} from "react-bootstrap";

import ExportModal from "./ExportModal";

class ClipsButtonBar extends React.Component{
    static propTypes = {
        sortChangeHandler:React.PropTypes.func,
        clips:React.PropTypes.object
    };

    constructor(props){
        super(props);

        this.state = {
            modalIsActive:false
        };
    }

    /**
     * Show the modal window by changing the
     * state.
     */
    openModal(){
        this.setState({
            modalIsActive:true
        });
    }

    /**
     * Close the modal window by changing the
     * state.
     */
    closeModal(){
        this.setState({
            modalIsActive:false
        });
    }

    render(){
        const {sortChangeHandler, clips} = this.props;
        return(

                <ExportModal closeModalHandler={this.closeModal.bind(this)}
                                  modalIsActive={this.state.modalIsActive}
                                  clips={clips}/>
                <Panel>
                    <Col sm={6}>
                        <Button onClick={this.openModal.bind(this)}>Save or Copy Clips</Button>
                    </Col>
                    <Form horizontal>
                    <Col componentClass={ControlLabel} sm={2}>
                        Sort By:
                    </Col>
                    <Col sm={4}>
                        <FormControl componentClass="select"
                            onChange={sortChangeHandler}>
                            <option value="location_start|asc">Location</option>
                            <option value="unix_timestamp|asc">Date - Oldest First</option>
                            <option value="unix_timestamp|desc">Date - Newest First</option>
                        </FormControl>
                    </Col>
                    </Form>
                </Panel>

        );
    }
}

export default ClipsButtonBar;<commit_msg>Removed whitespace.<commit_after>import React from "react";

import {ButtonToolbar,Button, Col, ControlLabel, Form, FormControl, Panel} from "react-bootstrap";

import ExportModal from "./ExportModal";

class ClipsButtonBar extends React.Component{
    static propTypes = {
        sortChangeHandler:React.PropTypes.func,
        clips:React.PropTypes.object
    };

    constructor(props){
        super(props);

        this.state = {
            modalIsActive:false
        };
    }

    /**
     * Show the modal window by changing the
     * state.
     */
    openModal(){
        this.setState({
            modalIsActive:true
        });
    }

    /**
     * Close the modal window by changing the
     * state.
     */
    closeModal(){
        this.setState({
            modalIsActive:false
        });
    }

    render(){
        const {sortChangeHandler, clips} = this.props;
        return(

                <ExportModal closeModalHandler={this.closeModal.bind(this)}
                                  modalIsActive={this.state.modalIsActive}
                                  clips={clips}/>
                <Panel>
                    <Col sm={6}>
                        <Button onClick={this.openModal.bind(this)}>Save or Copy Clips</Button>
                    </Col>
                    <Form horizontal>
                    <Col componentClass={ControlLabel} sm={2}>
                        Sort By:
                    </Col>
                    <Col sm={4}>
                        <FormControl componentClass="select"
                            onChange={sortChangeHandler}>
                            <option value="location_start|asc">Location</option>
                            <option value="unix_timestamp|asc">Date - Oldest First</option>
                            <option value="unix_timestamp|desc">Date - Newest First</option>
                        </FormControl>
                    </Col>
                    </Form>
                </Panel>

        );
    }
}

export default ClipsButtonBar;<|endoftext|>


<commit_before>const dbUser = require('../db/connectors/user');
const jwt = require('jsonwebtoken');
const errorCreator = require('../error/errorCreator');
const { appConfig, dbConfig } = require('../config/defaults/config');

/**
 * Create json web token. The user can be found by either the username or userId.
 * @param {Object} params - Parameters.
 * @param {string} params.password - Password of user to auth.
 * @param {Function} params.callback - Callback.
 * @param {string} [params.userId] - Id of user to auth.
 * @param {string} [params.username] - Name of user to auth.
 */
function createToken({
  username,
  userId,
  password,
  callback,
}) {
  if (!appConfig.jsonKey) {
    callback({ error: new errorCreator.Internal({ name: 'json key not set' }) });

    return;
  }

  dbUser.authUser({
    userId,
    username,
    password,
    callback: ({ error, data }) => {
      if (error) {
        callback({ error });

        return;
      } else if (data.user.isBanned) {
        callback({ error: new errorCreator.Banned({ name: `user ${data.user.username}` }) });

        return;
      } else if (!data.user.isVerified) {
        callback({ error: new errorCreator.NotAllowed({ name: `user ${data.user.username} not verified` }) });

        return;
      }

      const { user } = data;

      const jwtUser = { userId: user.objectId };

      jwt.sign({ data: jwtUser }, appConfig.jsonKey, (err, token) => {
        if (err) {
          callback({ error: new errorCreator.Internal({ name: 'jwt', errorObject: err }) });

          return;
        }

        callback({ data: { token, user } });
      });
    },
  });
}

/**
 * Checks if the user is allowed to use the command.
 * @param {Object} params - Parameters.
 * @param {string} params.token - Json web token.
 * @param {string} params.commandName - Name of the command.
 * @param {Object} [params.internalCallUser] - User set in an internal system call.
 * @param {Function} params.callback - callback.
 */
function isUserAllowed({
  commandName,
  token,
  internalCallUser,
  callback,
}) {
  const commandUsed = dbConfig.apiCommands[commandName];
  const anonUser = dbConfig.anonymousUser;

  if (internalCallUser) {
    callback({ data: { user: internalCallUser } });

    return;
  }

  if (!commandUsed) {
    callback({ error: new errorCreator.DoesNotExist({ name: commandName }) });

    return;
  } else if (!token) {
    if (commandUsed.accessLevel > anonUser.accessLevel) {
      callback({ error: new errorCreator.NotAllowed({ name: commandName, verbose: false }) });

      return;
    }

    callback({ data: { user: anonUser } });

    return;
  }

  jwt.verify(token, appConfig.jsonKey, (err, decoded) => {
    if (err || !decoded) {
      callback({ error: new errorCreator.NotAllowed({ name: commandName }) });

      return;
    }

    const { userId } = decoded.data;

    dbUser.getUserById({
      userId,
      callback: ({ error, data }) => {
        if (error) {
          callback({ error });

          return;
        }

        const { user } = data;
        const { accessLevel } = commandUsed;

        if (accessLevel > user.accessLevel) {
          callback({ error: new errorCreator.NotAllowed({ name: commandName }) });

          return;
        }

        callback({ data: { user } });
      },
    });
  });
}

/**
 * Does the user have equal or higher access level to the set visibility/access level in the object that will be created?
 * @param {Object} params - Parameters.
 * @param {Object} params.objectToCreate - Object that is going to be created.
 * @param {Object} params.toAuth - User trying to create an object.
 * @return {boolean} - Does the user have a high enough access level?
 */
function isAllowedAccessLevel({ objectToCreate, toAuth }) {
  return (!objectToCreate.accessLevel || toAuth.accessLevel >= objectToCreate.accessLevel) || (!objectToCreate.visibility || toAuth.accessLevel >= objectToCreate.visibility);
}

/**
 * Checks if user has access, is admin or can see the object.
 * @param {Object} params - Parameter.
 * @param {Object} params.objectToAccess - Object to access.
 * @param {Object} params.toAuth - Object to auth.
 * @returns {boolean} - Does the user have access to the object?
 */
function hasAccessTo({
  objectToAccess,
  toAuth,
}) {
  const {
    teamIds = [],
    userIds = [],
    userAdminIds = [],
    teamAdminIds = [],
    ownerId,
    isPublic,
    visibility,
  } = objectToAccess;
  const {
    hasFullAccess,
    accessLevel,
    teamIds: authTeamIds = [],
    objectId: authUserId = [],
    aliases = [],
  } = toAuth;
  const userHasAccess = userIds.concat([ownerId]).includes(authUserId);
  const teamHasAccess = teamIds.find(teamId => authTeamIds.includes(teamId));
  const aliasHasAccess = aliases.find(aliasId => userIds.includes(aliasId));
  const userHasAdminAccess = userAdminIds.includes(authUserId);
  const aliasHasAdminAccess = aliases.find(aliasId => userAdminIds.includes(aliasId));
  const teamHasAdminAccess = teamAdminIds.find(adminId => authTeamIds.includes(adminId));
  const isAdmin = ownerId === authUserId || hasFullAccess || accessLevel >= dbConfig.AccessLevels.ADMIN;

  return {
    canSee: isAdmin || isPublic || accessLevel >= visibility,
    hasAccess: isAdmin || isPublic || userHasAccess || teamHasAccess || aliasHasAccess,
    hasFullAccess: isAdmin || userHasAdminAccess || teamHasAdminAccess || aliasHasAdminAccess,
  };
}

exports.isUserAllowed = isUserAllowed;
exports.createToken = createToken;
exports.hasAccessTo = hasAccessTo;
exports.isAllowedAccessLevel = isAllowedAccessLevel;
<commit_msg>eslint fix<commit_after>const dbUser = require('../db/connectors/user');
const jwt = require('jsonwebtoken');
const errorCreator = require('../error/errorCreator');
const { appConfig, dbConfig } = require('../config/defaults/config');

/**
 * Create json web token. The user can be found by either the username or userId.
 * @param {Object} params - Parameters.
 * @param {string} params.password - Password of user to auth.
 * @param {Function} params.callback - Callback.
 * @param {string} [params.userId] - Id of user to auth.
 * @param {string} [params.username] - Name of user to auth.
 */
function createToken({
  username,
  userId,
  password,
  callback,
}) {
  if (!appConfig.jsonKey) {
    callback({ error: new errorCreator.Internal({ name: 'json key not set' }) });

    return;
  }

  dbUser.authUser({
    userId,
    username,
    password,
    callback: ({ error, data }) => {
      if (error) {
        callback({ error });

        return;
      } else if (data.user.isBanned) {
        callback({ error: new errorCreator.Banned({ name: `user ${data.user.username}` }) });

        return;
      } else if (!data.user.isVerified) {
        callback({ error: new errorCreator.NotAllowed({ name: `user ${data.user.username} not verified` }) });

        return;
      }

      const { user } = data;

      const jwtUser = { userId: user.objectId };

      jwt.sign({ data: jwtUser }, appConfig.jsonKey, (err, token) => {
        if (err) {
          callback({ error: new errorCreator.Internal({ name: 'jwt', errorObject: err }) });

          return;
        }

        callback({ data: { token, user } });
      });
    },
  });
}

/**
 * Checks if the user is allowed to use the command.
 * @param {Object} params - Parameters.
 * @param {string} params.token - Json web token.
 * @param {string} params.commandName - Name of the command.
 * @param {Object} [params.internalCallUser] - User set in an internal system call.
 * @param {Function} params.callback - callback.
 */
function isUserAllowed({
  commandName,
  token,
  internalCallUser,
  callback,
}) {
  const commandUsed = dbConfig.apiCommands[commandName];
  const anonUser = dbConfig.anonymousUser;

  if (internalCallUser) {
    callback({ data: { user: internalCallUser } });

    return;
  }

  if (!commandUsed) {
    callback({ error: new errorCreator.DoesNotExist({ name: commandName }) });

    return;
  } else if (!token) {
    if (commandUsed.accessLevel > anonUser.accessLevel) {
      callback({ error: new errorCreator.NotAllowed({ name: commandName, verbose: false }) });

      return;
    }

    callback({ data: { user: anonUser } });

    return;
  }

  jwt.verify(token, appConfig.jsonKey, (err, decoded) => {
    if (err || !decoded) {
      callback({ error: new errorCreator.NotAllowed({ name: commandName }) });

      return;
    }

    const { userId } = decoded.data;

    dbUser.getUserById({
      userId,
      callback: ({ error, data }) => {
        if (error) {
          callback({ error });

          return;
        }

        const { user } = data;
        const { accessLevel } = commandUsed;

        if (accessLevel > user.accessLevel) {
          callback({ error: new errorCreator.NotAllowed({ name: commandName }) });

          return;
        }

        callback({ data: { user } });
      },
    });
  });
}

/**
 * Does the user have equal or higher access level to the set visibility/access level in the object that will be created?
 * @param {Object} params - Parameters.
 * @param {Object} params.objectToCreate - Object that is going to be created.
 * @param {Object} params.toAuth - User trying to create an object.
 * @return {boolean} - Does the user have a high enough access level?
 */
function isAllowedAccessLevel({ objectToCreate, toAuth }) {
  return (!objectToCreate.accessLevel || toAuth.accessLevel >= objectToCreate.accessLevel) || (!objectToCreate.visibility || toAuth.accessLevel >= objectToCreate.visibility);
}

/**
 * Checks if user has access, is admin or can see the object.
 * @param {Object} params - Parameter.
 * @param {Object} params.objectToAccess - Object to access.
 * @param {Object} params.toAuth - Object to auth.
 * @returns {boolean} - Does the user have access to the object?
 */
function hasAccessTo({
  objectToAccess,
  toAuth,
}) {
  const {
    teamIds = [],
    userIds = [],
    userAdminIds = [],
    teamAdminIds = [],
    ownerId,
    isPublic,
    visibility,
  } = objectToAccess;
  const {
    hasFullAccess,
    accessLevel,
    teamIds: authTeamIds = [],
    objectId: authUserId = [],
    aliases = [],
  } = toAuth;

  const userHasAccess = userIds.concat([ownerId]).includes(authUserId);
  const teamHasAccess = teamIds.find(teamId => authTeamIds.includes(teamId));
  const aliasHasAccess = aliases.find(aliasId => userIds.includes(aliasId));
  const userHasAdminAccess = userAdminIds.includes(authUserId);
  const aliasHasAdminAccess = aliases.find(aliasId => userAdminIds.includes(aliasId));
  const teamHasAdminAccess = teamAdminIds.find(adminId => authTeamIds.includes(adminId));
  const isAdmin = ownerId === authUserId || hasFullAccess || accessLevel >= dbConfig.AccessLevels.ADMIN;

  return {
    canSee: isAdmin || isPublic || accessLevel >= visibility,
    hasAccess: isAdmin || isPublic || userHasAccess || teamHasAccess || aliasHasAccess,
    hasFullAccess: isAdmin || userHasAdminAccess || teamHasAdminAccess || aliasHasAdminAccess,
  };
}

exports.isUserAllowed = isUserAllowed;
exports.createToken = createToken;
exports.hasAccessTo = hasAccessTo;
exports.isAllowedAccessLevel = isAllowedAccessLevel;
<|endoftext|>


<commit_before>/*global self, caches, fetch*/

var urlsToCache = [
	// '/index.html',
	'/offline.html',
	'/style.css',
	'/fonts/FiraSans-Regular.woff',
	'/fonts/FiraSans-Regular.woff2',
	'/images/CoffeeCup.svg',
	'/js/stampit.min.js',
	'/js/Util.js',
	'/js/Events.js',
	'/js/View.js',
	'/js/Controller.js',
	'/js/Model.js',
	'/js/app/CardsModel.js',
	'/js/app/ToolbarView.js',
	'/js/app/cardHelper.js',
	'/js/app/CardsView.js',
	'/js/app/BigCardView.js',
	'/js/app/BigCardController.js',
	'/js/app/ToolbarController.js',
	'/js/app/CardsController.js',
	'/js/app/app.js'
];

var cacheName = 'scrumpoker-v1.0.2';

self.addEventListener('activate', function (event) {
	'use strict';
	var cacheWhitelist = [cacheName];

	event.waitUntil(
		caches.keys().then(function(cacheNames) {
			return Promise.all(
				cacheNames.map(function(cacheName) {
					if (cacheWhitelist.indexOf(cacheName) === -1) {
						return caches.delete(cacheName);
					}
				})
			);
		}).then(self.clients.claim())
	);
});
self.addEventListener('install', function (e) {
	'use strict';
	e.waitUntil(caches.open(cacheName).then(function (cache) {
		return cache.addAll(urlsToCache);
	}));
}, false);

function serveRightFromCache(event) {
	'use strict';
	return caches.open(cacheName).then(function (cache) {
		return cache.match(event.request);
	}).catch(function () {
		return fetch(event.request);
	});
}

function serveOnline(event, alias) {
	'use strict';

	return fetch(event.request, {cache: 'no-cache'}).catch(function() {
		return caches.open(cacheName).then(function (cache) {
			return cache.match(alias || event.request);
		});
	});
}

self.addEventListener('fetch', function (event) {
	'use strict';

	if (new URL(event.request.url).pathname === '/') {
		event.respondWith(serveOnline(event, '/offline.html'));
	} else {
		event.respondWith(serveRightFromCache(event));
	}
}, false);
<commit_msg>Fix cache response?<commit_after>/*global self, caches, fetch*/

var urlsToCache = [
	// '/index.html',
	'/offline.html',
	'/style.css',
	'/fonts/FiraSans-Regular.woff',
	'/fonts/FiraSans-Regular.woff2',
	'/images/CoffeeCup.svg',
	'/js/stampit.min.js',
	'/js/Util.js',
	'/js/Events.js',
	'/js/View.js',
	'/js/Controller.js',
	'/js/Model.js',
	'/js/app/CardsModel.js',
	'/js/app/ToolbarView.js',
	'/js/app/cardHelper.js',
	'/js/app/CardsView.js',
	'/js/app/BigCardView.js',
	'/js/app/BigCardController.js',
	'/js/app/ToolbarController.js',
	'/js/app/CardsController.js',
	'/js/app/app.js'
];

var cacheName = 'scrumpoker-v1.0.2';

self.addEventListener('activate', function (event) {
	'use strict';
	var cacheWhitelist = [cacheName];

	event.waitUntil(
		caches.keys().then(function(cacheNames) {
			return Promise.all(
				cacheNames.map(function(cacheName) {
					if (cacheWhitelist.indexOf(cacheName) === -1) {
						return caches.delete(cacheName);
					}
				})
			);
		}).then(self.clients.claim())
	);
});
self.addEventListener('install', function (e) {
	'use strict';
	e.waitUntil(caches.open(cacheName).then(function (cache) {
		return cache.addAll(urlsToCache);
	}));
}, false);

function serveRightFromCache(event) {
	'use strict';

	return caches.open(cacheName).then(function (cache) {
		return cache.match(event.request);
	}).then(function (response) {
		if (typeof response === 'undefined') {
			return fetch(event.request);
		}

		return Promise.resolve(response);
	});
}

function serveOnline(event, alias) {
	'use strict';

	return fetch(event.request, {cache: 'no-cache'}).catch(function() {
		return caches.open(cacheName).then(function (cache) {
			return cache.match(alias || event.request);
		});
	});
}

self.addEventListener('fetch', function (event) {
	'use strict';

	if (new URL(event.request.url).pathname === '/') {
		event.respondWith(serveOnline(event, '/offline.html'));
	} else {
		event.respondWith(serveRightFromCache(event));
	}
}, false);
<|endoftext|>


<commit_before>'use strict'
var Web3 = require('web3')
var EventManager = require('../eventManager')
var EthJSVM = require('ethereumjs-vm')
var ethUtil = require('ethereumjs-util')
var StateManager = require('ethereumjs-vm/dist/stateManager')
var Web3VMProvider = require('../web3Provider/web3VmProvider')

var rlp = ethUtil.rlp

var injectedProvider

var web3
if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') {
  injectedProvider = window.web3.currentProvider
  web3 = new Web3(injectedProvider)
} else {
  web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))
}

var blankWeb3 = new Web3()

/*
  extend vm state manager and instanciate VM
*/

class StateManagerCommonStorageDump extends StateManager {
  constructor (arg) {
    super(arg)
    this.keyHashes = {}
  }

  putContractStorage (address, key, value, cb) {
    this.keyHashes[ethUtil.sha3(key).toString('hex')] = ethUtil.bufferToHex(key)
    super.putContractStorage(address, key, value, cb)
  }

  dumpStorage (address, cb) {
    var self = this
    this._getStorageTrie(address, function (err, trie) {
      if (err) {
        return cb(err)
      }
      var storage = {}
      var stream = trie.createReadStream()
      stream.on('data', function (val) {
        var value = rlp.decode(val.value)
        storage['0x' + val.key.toString('hex')] = {
          key: self.keyHashes[val.key.toString('hex')],
          value: '0x' + value.toString('hex')
        }
      })
      stream.on('end', function () {
        cb(storage)
      })
    })
  }
}

function createVm (hardfork) {
  var stateManager = new StateManagerCommonStorageDump({})
  stateManager.checkpoint(() => {})
  var vm = new EthJSVM({
    activatePrecompiles: true,
    blockchain: stateManager.blockchain,
    stateManager: stateManager,
    hardfork: hardfork
  })
  var web3vm = new Web3VMProvider()
  web3vm.setVM(vm)
  return { vm, web3vm, stateManager }
}

var vms = {
  byzantium: createVm('byzantium'),
  constantinople: createVm('constantinople')
}

var mainNetGenesisHash = '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3'

/*
  trigger contextChanged, web3EndpointChanged
*/
function ExecutionContext () {
  var self = this
  this.event = new EventManager()

  var executionContext = null

  this.blockGasLimitDefault = 4300000
  this.blockGasLimit = this.blockGasLimitDefault
  this.customNetWorks = {}

  this.init = function (config) {
    if (config.get('settings/always-use-vm')) {
      executionContext = 'vm'
    } else {
      executionContext = injectedProvider ? 'injected' : 'vm'
    }
  }

  this.getProvider = function () {
    return executionContext
  }

  this.isVM = function () {
    return executionContext === 'vm'
  }

  this.web3 = function () {
    return this.isVM() ? vms.constantinople.web3vm : web3
  }

  this.detectNetwork = function (callback) {
    if (this.isVM()) {
      callback(null, { id: '-', name: 'VM' })
    } else {
      this.web3().version.getNetwork((err, id) => {
        var name = null
        if (err) name = 'Unknown'
        // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
        else if (id === '1') name = 'Main'
        else if (id === '2') name = 'Morden (deprecated)'
        else if (id === '3') name = 'Ropsten'
        else if (id === '4') name = 'Rinkeby'
        else if (id === '42') name = 'Kovan'
        else name = 'Custom'

        if (id === '1') {
          this.web3().eth.getBlock(0, (error, block) => {
            if (error) console.log('cant query first block')
            if (block && block.hash !== mainNetGenesisHash) name = 'Custom'
            callback(err, { id, name })
          })
        } else {
          callback(err, { id, name })
        }
      })
    }
  }

  this.removeProvider = function (name) {
    if (name && this.customNetWorks[name]) {
      delete this.customNetWorks[name]
      self.event.trigger('removeProvider', [name])
    }
  }

  this.addProvider = function (network) {
    if (network && network.name && network.url) {
      this.customNetWorks[network.name] = network
      self.event.trigger('addProvider', [network])
    }
  }

  this.internalWeb3 = function () {
    return web3
  }

  this.blankWeb3 = function () {
    return blankWeb3
  }

  this.vm = function () {
    return vms.constantinople.vm
  }

  this.setContext = function (context, endPointUrl, confirmCb, infoCb) {
    executionContext = context
    this.executionContextChange(context, endPointUrl, confirmCb, infoCb)
  }

  this.executionContextChange = function (context, endPointUrl, confirmCb, infoCb, cb) {
    if (!cb) cb = () => {}

    if (context === 'vm') {
      executionContext = context
      vms.constantinople.stateManager.revert(() => {
        vms.constantinople.stateManager.checkpoint(() => {})
      })
      self.event.trigger('contextChanged', ['vm'])
      return cb()
    }

    if (context === 'injected') {
      if (injectedProvider === undefined) {
        var alertMsg = 'No injected Web3 provider found. '
        alertMsg += 'Make sure your provider (e.g. MetaMask) is active and running '
        alertMsg += '(when recently activated you may have to reload the page).'
        infoCb(alertMsg)
        return cb()
      } else {
        executionContext = context
        web3.setProvider(injectedProvider)
        self._updateBlockGasLimit()
        self.event.trigger('contextChanged', ['injected'])
        return cb()
      }
    }

    if (context === 'web3') {
      confirmCb(cb)
    }

    if (this.customNetWorks[context]) {
      var provider = this.customNetWorks[context]
      setProviderFromEndpoint(provider.url, provider.name, () => { cb() })
    }
  }

  this.currentblockGasLimit = function () {
    return this.blockGasLimit
  }

  this.stopListenOnLastBlock = function () {
    if (this.listenOnLastBlockId) clearInterval(this.listenOnLastBlockId)
    this.listenOnLastBlockId = null
  }

  this._updateBlockGasLimit = function () {
    if (this.getProvider() !== 'vm') {
      web3.eth.getBlock('latest', (err, block) => {
        if (!err) {
          // we can't use the blockGasLimit cause the next blocks could have a lower limit : https://github.com/ethereum/remix/issues/506
          this.blockGasLimit = (block && block.gasLimit) ? Math.floor(block.gasLimit - (5 * block.gasLimit) / 1024) : this.blockGasLimitDefault
        } else {
          this.blockGasLimit = this.blockGasLimitDefault
        }
      })
    }
  }

  this.listenOnLastBlock = function () {
    this.listenOnLastBlockId = setInterval(() => {
      this._updateBlockGasLimit()
    }, 15000)
  }

  // TODO: not used here anymore and needs to be moved
  function setProviderFromEndpoint (endpoint, context, cb) {
    var oldProvider = web3.currentProvider

    if (endpoint === 'ipc') {
      web3.setProvider(new web3.providers.IpcProvider())
    } else {
      web3.setProvider(new web3.providers.HttpProvider(endpoint))
    }
    if (web3.isConnected()) {
      executionContext = context
      self._updateBlockGasLimit()
      self.event.trigger('contextChanged', ['web3'])
      self.event.trigger('web3EndpointChanged')
      cb()
    } else {
      web3.setProvider(oldProvider)
      var alertMsg = 'Not possible to connect to the Web3 provider. '
      alertMsg += 'Make sure the provider is running and a connection is open (via IPC or RPC).'
      cb(alertMsg)
    }
  }
  this.setProviderFromEndpoint = setProviderFromEndpoint

  this.txDetailsLink = function (network, hash) {
    if (transactionDetailsLinks[network]) {
      return transactionDetailsLinks[network] + hash
    }
  }
}

var transactionDetailsLinks = {
  'Main': 'https://www.etherscan.io/tx/',
  'Rinkeby': 'https://rinkeby.etherscan.io/tx/',
  'Ropsten': 'https://ropsten.etherscan.io/tx/',
  'Kovan': 'https://kovan.etherscan.io/tx/'
}

module.exports = new ExecutionContext()
<commit_msg>Update execution-context.js<commit_after>/* global ethereum */
'use strict'
var Web3 = require('web3')
var EventManager = require('../eventManager')
var EthJSVM = require('ethereumjs-vm')
var ethUtil = require('ethereumjs-util')
var StateManager = require('ethereumjs-vm/dist/stateManager')
var Web3VMProvider = require('../web3Provider/web3VmProvider')

var rlp = ethUtil.rlp

var injectedProvider

var web3
if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') {
  injectedProvider = window.web3.currentProvider
  web3 = new Web3(injectedProvider)
} else {
  web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))
}

var blankWeb3 = new Web3()

/*
  extend vm state manager and instanciate VM
*/

class StateManagerCommonStorageDump extends StateManager {
  constructor (arg) {
    super(arg)
    this.keyHashes = {}
  }

  putContractStorage (address, key, value, cb) {
    this.keyHashes[ethUtil.sha3(key).toString('hex')] = ethUtil.bufferToHex(key)
    super.putContractStorage(address, key, value, cb)
  }

  dumpStorage (address, cb) {
    var self = this
    this._getStorageTrie(address, function (err, trie) {
      if (err) {
        return cb(err)
      }
      var storage = {}
      var stream = trie.createReadStream()
      stream.on('data', function (val) {
        var value = rlp.decode(val.value)
        storage['0x' + val.key.toString('hex')] = {
          key: self.keyHashes[val.key.toString('hex')],
          value: '0x' + value.toString('hex')
        }
      })
      stream.on('end', function () {
        cb(storage)
      })
    })
  }
}

function createVm (hardfork) {
  var stateManager = new StateManagerCommonStorageDump({})
  stateManager.checkpoint(() => {})
  var vm = new EthJSVM({
    activatePrecompiles: true,
    blockchain: stateManager.blockchain,
    stateManager: stateManager,
    hardfork: hardfork
  })
  var web3vm = new Web3VMProvider()
  web3vm.setVM(vm)
  return { vm, web3vm, stateManager }
}

var vms = {
  byzantium: createVm('byzantium'),
  constantinople: createVm('constantinople')
}

var mainNetGenesisHash = '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3'

/*
  trigger contextChanged, web3EndpointChanged
*/
function ExecutionContext () {
  var self = this
  this.event = new EventManager()

  var executionContext = null

  this.blockGasLimitDefault = 4300000
  this.blockGasLimit = this.blockGasLimitDefault
  this.customNetWorks = {}

  this.init = function (config) {
    if (config.get('settings/always-use-vm')) {
      executionContext = 'vm'
    } else {
      executionContext = injectedProvider ? 'injected' : 'vm'
      if (executionContext === 'injected') this.askPermission()
    }
  }

  this.askPermission = function () {
    // metamask
    if (ethereum && typeof ethereum.enable === 'function') ethereum.enable()
  }

  this.getProvider = function () {
    return executionContext
  }

  this.isVM = function () {
    return executionContext === 'vm'
  }

  this.web3 = function () {
    return this.isVM() ? vms.constantinople.web3vm : web3
  }

  this.detectNetwork = function (callback) {
    if (this.isVM()) {
      callback(null, { id: '-', name: 'VM' })
    } else {
      this.web3().version.getNetwork((err, id) => {
        var name = null
        if (err) name = 'Unknown'
        // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
        else if (id === '1') name = 'Main'
        else if (id === '2') name = 'Morden (deprecated)'
        else if (id === '3') name = 'Ropsten'
        else if (id === '4') name = 'Rinkeby'
        else if (id === '42') name = 'Kovan'
        else name = 'Custom'

        if (id === '1') {
          this.web3().eth.getBlock(0, (error, block) => {
            if (error) console.log('cant query first block')
            if (block && block.hash !== mainNetGenesisHash) name = 'Custom'
            callback(err, { id, name })
          })
        } else {
          callback(err, { id, name })
        }
      })
    }
  }

  this.removeProvider = function (name) {
    if (name && this.customNetWorks[name]) {
      delete this.customNetWorks[name]
      self.event.trigger('removeProvider', [name])
    }
  }

  this.addProvider = function (network) {
    if (network && network.name && network.url) {
      this.customNetWorks[network.name] = network
      self.event.trigger('addProvider', [network])
    }
  }

  this.internalWeb3 = function () {
    return web3
  }

  this.blankWeb3 = function () {
    return blankWeb3
  }

  this.vm = function () {
    return vms.constantinople.vm
  }

  this.setContext = function (context, endPointUrl, confirmCb, infoCb) {
    executionContext = context
    this.executionContextChange(context, endPointUrl, confirmCb, infoCb)
  }

  this.executionContextChange = function (context, endPointUrl, confirmCb, infoCb, cb) {
    if (!cb) cb = () => {}

    if (context === 'vm') {
      executionContext = context
      vms.constantinople.stateManager.revert(() => {
        vms.constantinople.stateManager.checkpoint(() => {})
      })
      self.event.trigger('contextChanged', ['vm'])
      return cb()
    }

    if (context === 'injected') {
      if (injectedProvider === undefined) {
        var alertMsg = 'No injected Web3 provider found. '
        alertMsg += 'Make sure your provider (e.g. MetaMask) is active and running '
        alertMsg += '(when recently activated you may have to reload the page).'
        infoCb(alertMsg)
        return cb()
      } else {
        self.askPermission()
        executionContext = context
        web3.setProvider(injectedProvider)
        self._updateBlockGasLimit()
        self.event.trigger('contextChanged', ['injected'])
        return cb()
      }
    }

    if (context === 'web3') {
      confirmCb(cb)
    }

    if (this.customNetWorks[context]) {
      var provider = this.customNetWorks[context]
      setProviderFromEndpoint(provider.url, provider.name, () => { cb() })
    }
  }

  this.currentblockGasLimit = function () {
    return this.blockGasLimit
  }

  this.stopListenOnLastBlock = function () {
    if (this.listenOnLastBlockId) clearInterval(this.listenOnLastBlockId)
    this.listenOnLastBlockId = null
  }

  this._updateBlockGasLimit = function () {
    if (this.getProvider() !== 'vm') {
      web3.eth.getBlock('latest', (err, block) => {
        if (!err) {
          // we can't use the blockGasLimit cause the next blocks could have a lower limit : https://github.com/ethereum/remix/issues/506
          this.blockGasLimit = (block && block.gasLimit) ? Math.floor(block.gasLimit - (5 * block.gasLimit) / 1024) : this.blockGasLimitDefault
        } else {
          this.blockGasLimit = this.blockGasLimitDefault
        }
      })
    }
  }

  this.listenOnLastBlock = function () {
    this.listenOnLastBlockId = setInterval(() => {
      this._updateBlockGasLimit()
    }, 15000)
  }

  // TODO: not used here anymore and needs to be moved
  function setProviderFromEndpoint (endpoint, context, cb) {
    var oldProvider = web3.currentProvider

    if (endpoint === 'ipc') {
      web3.setProvider(new web3.providers.IpcProvider())
    } else {
      web3.setProvider(new web3.providers.HttpProvider(endpoint))
    }
    if (web3.isConnected()) {
      executionContext = context
      self._updateBlockGasLimit()
      self.event.trigger('contextChanged', ['web3'])
      self.event.trigger('web3EndpointChanged')
      cb()
    } else {
      web3.setProvider(oldProvider)
      var alertMsg = 'Not possible to connect to the Web3 provider. '
      alertMsg += 'Make sure the provider is running and a connection is open (via IPC or RPC).'
      cb(alertMsg)
    }
  }
  this.setProviderFromEndpoint = setProviderFromEndpoint

  this.txDetailsLink = function (network, hash) {
    if (transactionDetailsLinks[network]) {
      return transactionDetailsLinks[network] + hash
    }
  }
}

var transactionDetailsLinks = {
  'Main': 'https://www.etherscan.io/tx/',
  'Rinkeby': 'https://rinkeby.etherscan.io/tx/',
  'Ropsten': 'https://ropsten.etherscan.io/tx/',
  'Kovan': 'https://kovan.etherscan.io/tx/'
}

module.exports = new ExecutionContext()
<|endoftext|>