<commit_before>/*
Copyright (c) 2012 Ashwinee Dash

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.

*/
(function(context){

//create the empty object if already not available
var Dabba = {} || window.Dabba;

// overwriting any other Dabba object with this object
window.Dabba = Dabba;

var wls = window.localStorage;
//TODO
Dabba.adapter = {

	storage: 'dom';//
}

 //
var cache = {}; // useful for caching objects

//TODO
//check if localStorage is available
var isLocalStorage = function(){
	//function supports_html5_storage() {
	// taken from modernizer https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage-localstorage.js
  try {
      localStorage.setItem('mod', 'mod');
      localStorage.removeItem('mod');
      return true;
  } catch(e) {
      return false;
  }
}

// creates the new corner using the create method
var init = function(name, keys) {
		// check if localstorage is available
		if(!isLocalStorage()) {

			console.log("local storage is not available.")
			return; // object cannot be created hence no need to go further
		}

		// check if a key with same name exists
		if(localStorage.getItem(name) != undefined) {

			var sd = new ls(name);
			return sd;// since same key exists , there is no need to go further
		}

		var sd = new ls(name),
		tv1 = name + ".totalrecords"/* this will keep a tab on how many rows of data is set*/
		,tv2 = name + ".keys"
		,tv3 = name + ".ids";
		localStorage.setItem(tv1, '0');
		localStorage.setItem(tv3, '0');
		keys.id = "number";
		keys.create_date = "datetime";
		keys.update_date = "datetime";
		wls.setItem(tv2, JSON.stringify(keys));
		return sd;
	};

var ls = function (name/*string*/) {
		var name = name;
		if(wls.getItem(name) == undefined) {

			wls.setItem(name,getUID());
			//
		}

		this.uid = wls.getItem(name);
		this.name = name;
}

ls.prototype.add = function(data) {
	var i = parseInt(wls.getItem(this.name + ".ids"),10);
	//data.id = ++i;
	var trs = parseInt(wls.getItem(this.name + ".totalrecords"));
	wls.setItem(this.name + ".totalrecords", ++trs);
	var keys = JSON.parse(wls.getItem(this.name+'.keys'));
	var items = {};

	for (var key in keys) {
			items[key] = data[key] || ''; //looping through object
	}
	items.id = ++i;
	items.create_date = new Date();// should be javascript date so that later on it can be compared
	items.update_date = items.create_date;
	localStorage.setItem(this.name+"."+i, JSON.stringify(items));
	localStorage.setItem(this.name + ".ids", i);
};

//TODO
ls.prototype.edit = function(id/* number*/, data/*key: value, key:value*/) {
	var idn = this.name +'.'+ id;
	var item = this.find(id);//this{};
	if(item != null) {

		//item = //JSON.parse(localStorage.getItem(id));//parseInt(localStorage.getItem(this.name + ".totalrecords"),10);
		for (var key in data) {
			item[key] = data[key]; //looping through object
		}
		item.update_date = new Date();
		localStorage.setItem(idn, JSON.stringify(item));
	}
};

ls.prototype.find = function(id/* number*/) {
	// body...
	var id = this.name +"."+ parseInt(id, 10);

	if(itemExists(id)) {
		var item = localStorage.getItem(id); // if the item is deleted or not added it might retrun undefined
		item = JSON.parse(item);//parseInt(localStorage.getItem(this.name + ".totalrecords"),10);
		return item;
	}
	return null;
};

ls.prototype.findAll = function(from/*number optional*/, to/* number optional*/) {
	// body...
	var records = [];
	var length = parseInt(localStorage.getItem(this.name+ ".ids"));
	var i = 1;
	if(arguments.length == 0) {
		//
		fetch.apply(this);
	} else if (arguments.length == 1 && arguments[0] < 1) {
		i = parseInt(to, 10);
		fetch.apply(this);
	} else if (arguments.length == 2 && arguments[0] > 0 && arguments[1] > 1) {
		i = parseInt(to, 10);
		length = parseInt(from, 10);
		fetch.apply(this);
	} else {
		console.log('parameters for this method : from/*number optional*/, to/* number optional*/');
		return;
	};

	function fetch (){
		var j = 0;
		for ( i; i <= length; i++) { // TODO
			//var id = this.name + "."+i;

			var item = this.find(i);
			// adding to the list if object exists for this id
			if(item != null) {
				records[j] = item;
				j++;
			}

		};
	}

	return records;
};

ls.prototype.remove = function(id /* number*/) {
	var id = this.name +"."+ parseInt(id, 10);
	if(itemExists(id)) {
		localStorage.removeItem(id);
		var trs = parseInt(localStorage.getItem(this.name + ".totalrecords"),10);
		localStorage.setItem(this.name + ".totalrecords", --trs);
		return true;
	}
	return false;
};

ls.prototype.firstPage = function(number/*size of the records to be returned*/) {
	if(number > 0 && number !== NaN) {
	this.recordsPerPage = number;
	this.page = 1;
	this.findAll(1, this.recordsPerPage);
	}

	//return this.recordsPerPage;
};

ls.prototype.nextPage = function() {
	// body...
	if(!this.page) {
		console.log('firstPage method must be called first');
		return;
	}
	var from = (this.recordsPerPage * this.page) + 1;
	var to = this.recordsPerPage * (this.page+1)
	this.findAll(from, to);
	this.page++;
};

ls.prototype.prevPage = function() {
	// body...
	if(!this.page) {
		console.log('firstPage method must be called first and nextPage ');

		return;
	}

	if(this.page > 1) {
		console.log('looks like you are on first page itself');
		return;
	}

	this.page--;

	if(this.page == 1) {
		this.findAll(1, this.recordsPerPage);
	} else {
		var to = (this.recordsPerPage * this.page ) + 1;
		var from = this.recordsPerPage * (this.page+1);
		this.findAll(from, to);
	}

};

// utils

// get the uid
// returns a unique identifier (by way of Backbone.localStorage.js)
// TODO investigate smaller UUIDs to cut on storage cost
function getUID () {
        var S4 = function () {
            return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
        }
        return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
	//return "xxx-000-xxxx-00-xxxxx";
}

function itemExists(itemName) {
	if(localStorage.getItem(itemName) != undefined) {
		return true;
	} else {
		return false;
	}
}

//public API
Dabba.help = (function(){

	return {

	version: "0.1.1a"
	//public API
	,create: init//function(name, keys){ init(name, keys); }
	,modify: ''// add or remove key and corresponding values
	,destroy: ''
	,has: itemExists
	,toJSON: ''
	,replicate: ''

};

}())

}(window));

//
<commit_msg>refactoring<commit_after>/*
Copyright (c) 2012 Ashwinee Dash

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.

*/
(function (context) {

//create the empty object if already not available
var Dabba = {} || window.Dabba;

// overwriting any other Dabba object with this object
window.Dabba = Dabba;

var _wls = window.localStorage;
//TODO
Dabba.adapter = {

    storage: 'dom'//
};

 //
var cache = {}, // useful for caching objects

//TODO
//check if localStorage is available
 isLocalStorage = function () {
	//function supports_html5_storage() {
	// taken from modernizer https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage-localstorage.js
  try {
      localStorage.setItem('mod', 'mod');
      localStorage.removeItem('mod');
      return true;
  } catch (e) {
      return false;
  }
}

// creates the new corner using the create method
var _init = function(name/*name of the corner*/, keys/* name of the columns*/) {
		// check if localstorage is available
		if(!isLocalStorage()) {
			// TO DO
			console.log("local storage is not available.") // need to check if console is available
			return; // object cannot be created hence no need to go further
		}

		// check if a key with same name exists
		/*if(!(_wls.getItem(name))) {

			var sd = new ls(name);
			return sd;// since same key exists , there is no need to go further
		}*/

		// if some other script creates any item with provided key
		if (!(_wls.getItem(name))) {// if the key is not found
			_create(name, keys);
		} else {
			//raise exception;
		};

	};

var _create = function (name/*name of the corner*/, keys/* name of the columns*/) {

	var sd = new ls(name)
		,tmpVal1 = sd.name + ".totalrecords"/* this will keep a tab on how many rows of data is set*/
		,tmpVal2 = sd.name + ".keys"
		,tmpVal3 = sd.name + ".ids";
		localStorage.setItem(tmpVal1, '0');
		localStorage.setItem(tmpVal3, '0');
		keys.id = "number";
		keys.create_date = "datetime";
		keys.update_date = "datetime";
		wls.setItem(tmpVal2, JSON.stringify(keys));
		return sd;
}
var _ls = function (name/*string*/) {
		var _name = name;
		//if(_wls.getItem(_name) !== undefined) {
			//this.uid = wls.getItem(_name);
			this.name = _name;
			//
		//} else {
			// raise exception
		//}
		_wls.setItem(_name,getUID());

}

_ls.prototype.add = function(data) {
	var i = parseInt(wls.getItem(this.name + ".ids"),10);
	//data.id = ++i;
	var trs = parseInt(wls.getItem(this.name + ".totalrecords"));
	wls.setItem(this.name + ".totalrecords", ++trs);
	var keys = JSON.parse(wls.getItem(this.name+'.keys'));
	var items = {};

	for (var key in keys) {
			items[key] = data[key] || ''; //looping through object
	}
	items.id = ++i;
	items.create_date = new Date();// should be javascript date so that later on it can be compared
	items.update_date = items.create_date;
	localStorage.setItem(this.name+"."+i, JSON.stringify(items));
	localStorage.setItem(this.name + ".ids", i);
};

//TODO
_ls.prototype.edit = function(id/* number*/, data/*{key: value, key:value}*/) {
	var idn = this.name +'.'+ id;
	var item = this.find(id);//this{};
	if(item != null) {

		//item = //JSON.parse(localStorage.getItem(id));//parseInt(localStorage.getItem(this.name + ".totalrecords"),10);
		for (var key in data) {
			item[key] = data[key]; //looping through object
		}
		item.update_date = new Date();
		localStorage.setItem(idn, JSON.stringify(item));
	}
};

_ls.prototype.find = function(id/* number*/) {
	// body...
	var id = this.name +"."+ parseInt(id, 10);

	if(itemExists(id)) {
		var item = localStorage.getItem(id); // if the item is deleted or not added it might retrun undefined
		item = JSON.parse(item);//parseInt(localStorage.getItem(this.name + ".totalrecords"),10);
		return item;
	}
	return null;
};

_ls.prototype.findAll = function(from/*number optional*/, to/* number optional*/) {
	// body...
	var records = [];
	var length = parseInt(localStorage.getItem(this.name+ ".ids"));
	var i = 1;
	if(arguments.length == 0) {
		//
		fetch.apply(this);
	} else if (arguments.length == 1 && arguments[0] < 1) {
		i = parseInt(to, 10);
		fetch.apply(this);
	} else if (arguments.length == 2 && arguments[0] > 0 && arguments[1] > 1) {
		i = parseInt(to, 10);
		length = parseInt(from, 10);
		fetch.apply(this);
	} else {
		console.log('parameters for this method : from/*number optional*/, to/* number optional*/');
		return;
	};

	function fetch (){
		var j = 0;
		for ( i; i <= length; i++) { // TODO
			//var id = this.name + "."+i;

			var item = this.find(i);
			// adding to the list if object exists for this id
			if(item != null) {
				records[j] = item;
				j++;
			}

		};
	}

	return records;
};

_ls.prototype.remove = function(id /* number*/) {
	var id = this.name +"."+ parseInt(id, 10);
	if(itemExists(id)) {
		localStorage.removeItem(id);
		var trs = parseInt(localStorage.getItem(this.name + ".totalrecords"),10);
		localStorage.setItem(this.name + ".totalrecords", --trs);
		return true;
	}
	return false;
};

_ls.prototype.firstPage = function(number/*size of the records to be returned*/) {
	if(number > 0 && number !== NaN) {
	this.recordsPerPage = number;
	this.page = 1;
	this.findAll(1, this.recordsPerPage);
	}

	//return this.recordsPerPage;
};

_ls.prototype.nextPage = function() {
	// body...
	if(!this.page) {
		console.log('firstPage method must be called first');
		return;
	}
	var from = (this.recordsPerPage * this.page) + 1;
	var to = this.recordsPerPage * (this.page+1)
	this.findAll(from, to);
	this.page++;
};

_ls.prototype.prevPage = function() {
	// body...
	if(!this.page) {
		console.log('firstPage method must be called first and nextPage ');

		return;
	}

	if(this.page > 1) {
		console.log('looks like you are on first page itself');
		return;
	}

	this.page--;

	if(this.page == 1) {
		this.findAll(1, this.recordsPerPage);
	} else {
		var to = (this.recordsPerPage * this.page ) + 1;
		var from = this.recordsPerPage * (this.page+1);
		this.findAll(from, to);
	}

};

// utils

// get the uid
// returns a unique identifier (by way of Backbone.localStorage.js)
// TODO investigate smaller UUIDs to cut on storage cost
// why this is required ??
function getUID () {
        var S4 = function () {
            return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
        }
        return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
	//return "xxx-000-xxxx-00-xxxxx";
}

function itemExists(itemName) {
	if(localStorage.getItem(itemName) !== undefined) {
		return true;
	} else {
		return false;
	}
}

//public API
Dabba.help = (function(){

	return {

	version: "0.1.1a.2"
	//public API
	,create: _create//function(name, keys){ init(name, keys); }
	,modify: ''// add or remove key and corresponding values
	,destroy: ''
	,reset: ''
	,has: itemExists
	,toJSON: ''
	,replicate: ''

};

}())

}(window));

//
<|endoftext|>


<commit_before>angular.module("gameApp")
    .factory("gameService", ["graphicsEngineService", "gameBoardService", "globalSettings", "utilsService", "gameStateService", "boardLocation", "characterState", "characterDirection", "sprite", "scoreMarkerService", "spiderService", "fleaService", "snailService", "centipedeService", "bulletService", "playerService", "gameState", "keyPressHandlerService",
        function(graphicsEngineService, gameBoardService, globalSettings, utilsService, gameStateService, boardLocation, characterState, characterDirection, sprite, scoreMarkerService, spiderService, fleaService, snailService, centipedeService, bulletService, playerService, gameState, keyPressHandlerService) {
        "use strict";

            function resetBoard() {
                snailService.destroy();
                fleaService.destroy();
                spiderService.destroy();
                centipedeService.destroy();
                gameBoardService.initialise();
            }

            function initialiseLevel() {
                centipedeService.create(
                    Math.floor(globalSettings.gameBoardWidth / 2),
                    0,
                    globalSettings.centipedeMinimumLength + gameStateService.currentLevel(),
                    globalSettings.centipedeFramesPerMoveNormalSpeed,
                    characterDirection.down,
                    characterDirection.right,
                    false);

                for (var i = 1; i < gameStateService.currentLevel() && i < globalSettings.maxCentipedes; i++)
                {
                    centipedeService.create(
                        (i * 2) - 1,
                        1,
                        0,
                        gameStateService.isCurrentLevelHighSpeed() ? globalSettings.centipedeFramesPerMoveHighSpeed: globalSettings.centipedeFramesPerMoveNormalSpeed,
                        characterDirection.down,
                        characterDirection.right,
                        false);
                }
            }

            function movePlayer(animation) {
                playerService.update(animation);

                if (animation % 2 === 0 && playerService.isAlive() && playerService.isFiring()) {
                    var playerPosition = playerService.getPreviousPosition();
                    bulletService.createNewBullet(playerPosition.x, playerPosition.y - 1);
                }
            }

            function checkGenerateNewCentipede() {
                if (centipedeService.isFirstCentipedeAtEndOfScreen() && !centipedeService.isCentipedeAtPlayerTopBoundary()) {
                    centipedeService.create(
                        -1, // start just off the screen as we will immediately move forward.
                        (globalSettings.gameBoardHeight - globalSettings.playerAreaHeight) + 1,
                        0,
                        globalSettings.centipedeFramesPerMoveHighSpeed,
                        characterDirection.down,
                        characterDirection.right,
                        false);
                }
            }

            function moveCharacters(animation) {
                bulletService.update(animation);
                fleaService.update(animation);
                spiderService.update(animation);
                snailService.update(animation);
                centipedeService.update(animation);
                movePlayer(animation);
                scoreMarkerService.update(animation);

                if (animation == 0) {
                    fleaService.checkCreateFlea();
                    spiderService.checkCreateSpider();
                    snailService.checkCreateSnail();
                    checkGenerateNewCentipede();
                }

                checkPlayerCollision();
            }

            function checkPlayerCollision() {
                if (!playerService.isAlive()) {
                    return;
                }

                var playerPosition = playerService.getPosition();

                 if (spiderService.checkCollision(playerPosition.x, playerPosition.y) ||
                    fleaService.checkCollision(playerPosition.x, playerPosition.y) ||
                    centipedeService.checkCollision(playerPosition.x, playerPosition.y, false)) {

                    playerService.die();
                    gameStateService.die();
                 }
            }

            function resetAfterPlayerRegeneration() {
                if (gameStateService.isGameOver()) {
                    gameStateService.reset();
                }
                resetBoard();
                playerService.regenerate(true);
                gameStateService.playerRegenerate();
                initialiseLevel();
            }

            function levelTransitionUpdate() {
                if (gameStateService.hasLevelTransitionResetAllLines()) {
                    initialiseLevel();
                    gameStateService.completeLevelTransition();
                }
            }

            function activeGameUpdate(animation) {
                if (!centipedeService.anyAlive()) {
                    gameStateService.startLevelTransition();
                    playerService.regenerate(false);
                    bulletService.destroy();
                    spiderService.destroy();
                    fleaService.destroy();
                    snailService.destroy();
                } else {
                    moveCharacters(animation);
                }
            }

            function playerDeathTransitionUpdate(animation) {
                var keyPress = keyPressHandlerService.getNextMovement();
              //  if (gameStateService.hasPlayerDeathTransitionComplete() && keyPress.isFiring) {
              if (gameStateService.hasPlayerDeathTransitionComplete()) {
                    wait();
                    resetAfterPlayerRegeneration();
                } else {
                    moveCharacters(animation);
                }
            }

            function wait() {
              var start = new Date().getTime();
              var end = start;
              while (end < start + 5000000000000) {
                end = new Date().getTime();
              }
            }

            function gameOverTransitionUpdate(animation) {
                var keyPress = keyPressHandlerService.getNextMovement();
                if (gameStateService.hasGameOverTransitionComplete() && keyPress.isFiring) {
                    resetAfterPlayerRegeneration();
                } else {
                    moveCharacters(animation);
                }
            }

            return {
                initialise: function() {
                    resetBoard();
                    playerService.createPlayer();
                    initialiseLevel();
                },

                update: function(animation) {
                    switch (gameStateService.gameState) {
                        case gameState.gameActive:
                            activeGameUpdate(animation);
                            break;

                        case gameState.playerDeathTransition:
                            playerDeathTransitionUpdate(animation);
                            break;

                        case gameState.levelTransition:
                            levelTransitionUpdate();
                            break;

                        case gameState.gameOver:
                            gameOverTransitionUpdate(animation);
                            break;
                    }
                }
            }
        }]);
<commit_msg>trim down years waiting after death<commit_after>angular.module("gameApp")
    .factory("gameService", ["graphicsEngineService", "gameBoardService", "globalSettings", "utilsService", "gameStateService", "boardLocation", "characterState", "characterDirection", "sprite", "scoreMarkerService", "spiderService", "fleaService", "snailService", "centipedeService", "bulletService", "playerService", "gameState", "keyPressHandlerService",
        function(graphicsEngineService, gameBoardService, globalSettings, utilsService, gameStateService, boardLocation, characterState, characterDirection, sprite, scoreMarkerService, spiderService, fleaService, snailService, centipedeService, bulletService, playerService, gameState, keyPressHandlerService) {
        "use strict";

            function resetBoard() {
                snailService.destroy();
                fleaService.destroy();
                spiderService.destroy();
                centipedeService.destroy();
                gameBoardService.initialise();
            }

            function initialiseLevel() {
                centipedeService.create(
                    Math.floor(globalSettings.gameBoardWidth / 2),
                    0,
                    globalSettings.centipedeMinimumLength + gameStateService.currentLevel(),
                    globalSettings.centipedeFramesPerMoveNormalSpeed,
                    characterDirection.down,
                    characterDirection.right,
                    false);

                for (var i = 1; i < gameStateService.currentLevel() && i < globalSettings.maxCentipedes; i++)
                {
                    centipedeService.create(
                        (i * 2) - 1,
                        1,
                        0,
                        gameStateService.isCurrentLevelHighSpeed() ? globalSettings.centipedeFramesPerMoveHighSpeed: globalSettings.centipedeFramesPerMoveNormalSpeed,
                        characterDirection.down,
                        characterDirection.right,
                        false);
                }
            }

            function movePlayer(animation) {
                playerService.update(animation);

                if (animation % 2 === 0 && playerService.isAlive() && playerService.isFiring()) {
                    var playerPosition = playerService.getPreviousPosition();
                    bulletService.createNewBullet(playerPosition.x, playerPosition.y - 1);
                }
            }

            function checkGenerateNewCentipede() {
                if (centipedeService.isFirstCentipedeAtEndOfScreen() && !centipedeService.isCentipedeAtPlayerTopBoundary()) {
                    centipedeService.create(
                        -1, // start just off the screen as we will immediately move forward.
                        (globalSettings.gameBoardHeight - globalSettings.playerAreaHeight) + 1,
                        0,
                        globalSettings.centipedeFramesPerMoveHighSpeed,
                        characterDirection.down,
                        characterDirection.right,
                        false);
                }
            }

            function moveCharacters(animation) {
                bulletService.update(animation);
                fleaService.update(animation);
                spiderService.update(animation);
                snailService.update(animation);
                centipedeService.update(animation);
                movePlayer(animation);
                scoreMarkerService.update(animation);

                if (animation == 0) {
                    fleaService.checkCreateFlea();
                    spiderService.checkCreateSpider();
                    snailService.checkCreateSnail();
                    checkGenerateNewCentipede();
                }

                checkPlayerCollision();
            }

            function checkPlayerCollision() {
                if (!playerService.isAlive()) {
                    return;
                }

                var playerPosition = playerService.getPosition();

                 if (spiderService.checkCollision(playerPosition.x, playerPosition.y) ||
                    fleaService.checkCollision(playerPosition.x, playerPosition.y) ||
                    centipedeService.checkCollision(playerPosition.x, playerPosition.y, false)) {

                    playerService.die();
                    gameStateService.die();
                 }
            }

            function resetAfterPlayerRegeneration() {
                if (gameStateService.isGameOver()) {
                    gameStateService.reset();
                }
                resetBoard();
                playerService.regenerate(true);
                gameStateService.playerRegenerate();
                initialiseLevel();
            }

            function levelTransitionUpdate() {
                if (gameStateService.hasLevelTransitionResetAllLines()) {
                    initialiseLevel();
                    gameStateService.completeLevelTransition();
                }
            }

            function activeGameUpdate(animation) {
                if (!centipedeService.anyAlive()) {
                    gameStateService.startLevelTransition();
                    playerService.regenerate(false);
                    bulletService.destroy();
                    spiderService.destroy();
                    fleaService.destroy();
                    snailService.destroy();
                } else {
                    moveCharacters(animation);
                }
            }

            function playerDeathTransitionUpdate(animation) {
                var keyPress = keyPressHandlerService.getNextMovement();
              //  if (gameStateService.hasPlayerDeathTransitionComplete() && keyPress.isFiring) {
              if (gameStateService.hasPlayerDeathTransitionComplete()) {
                    wait();
                    resetAfterPlayerRegeneration();
                } else {
                    moveCharacters(animation);
                }
            }

            function wait() {
              var start = new Date().getTime();
              var end = start;
              while (end < start + 50000) {
                end = new Date().getTime();
              }
            }

            function gameOverTransitionUpdate(animation) {
                var keyPress = keyPressHandlerService.getNextMovement();
                if (gameStateService.hasGameOverTransitionComplete() && keyPress.isFiring) {
                    resetAfterPlayerRegeneration();
                } else {
                    moveCharacters(animation);
                }
            }

            return {
                initialise: function() {
                    resetBoard();
                    playerService.createPlayer();
                    initialiseLevel();
                },

                update: function(animation) {
                    switch (gameStateService.gameState) {
                        case gameState.gameActive:
                            activeGameUpdate(animation);
                            break;

                        case gameState.playerDeathTransition:
                            playerDeathTransitionUpdate(animation);
                            break;

                        case gameState.levelTransition:
                            levelTransitionUpdate();
                            break;

                        case gameState.gameOver:
                            gameOverTransitionUpdate(animation);
                            break;
                    }
                }
            }
        }]);
<|endoftext|>


<commit_before>/*$AMPERSAND_VERSION*/
var assign = require('lodash.assign');

module.exports ={
  limit: 10,
  skip: 0,
  fetchPage: function(options){
    options || (options = {remove: false, merge: false, add: true});
    options.data = options.data || {};
    if(options.reset){
        options = {};
        this.skip = 0;
    }
    assign(this, options.data);
    this.fetch(options);
    this.skip += this.limit;
  }
};<commit_msg>solving some issues with the API<commit_after>/*$AMPERSAND_VERSION*/
var assign = require('lodash.assign');

module.exports ={
  fetchPage: function(options){
    options || (options = {remove: false, merge: false, add: true});
    options.data = options.data || {};
    var data = this.data;
    if(options.reset){
      options = {};
      data.skip = 0;
    }
    assign(data, options.data);
    data.skip = data.skip ? data.skip : 0;
    data.limit = data.limit ? data.limit : 10;
    this.fetch(data);
    data.skip += data.limit;
    this.data = data;
  }
};<|endoftext|>


<commit_before>// Populating div with only meaningful words
const populateStopwordsRemoved = function(result) {
  console.log('Boom')
  console.log(result)
  const node = document.createElement('span')
  node.innerHTML = result
  emptyElement('stopwordsRemoved')
  document.getElementById('stopwordsRemoved').appendChild(node)
}

// Listen to key up and initiate a stopword removal
document.getElementById("text").onkeyup = function() {
  const oldString = document.getElementById("text").value.split(' ')
  const newString = sw.removeStopwords(oldString)
  console.log('oldString: ' + oldString)
  console.log('newString: ' + newString)
  populateStopwordsRemoved(newString.join(' '))
}

// Empty HTML element
const emptyElement = function (element) {
    document.getElementById(element).innerHTML = ''
}<commit_msg>feat: populate language select and react to its changes<commit_after>const languageSelect = document.getElementById('languages')
const sentenceInput = document.getElementById('text')
const resultText = document.getElementById('stopwordsRemoved')

function updateSentence() {
  const language = languageSelect.value
  const oldString = sentenceInput.value.split(' ')
  const newString = sw.removeStopwords(oldString, sw[language]).join(' ')
  console.group('Stopwords applied')
  console.log('oldString:', oldString.join(' '))
  console.log('newString:', newString)
  console.groupEnd()

  // Populate with only meaningful words
  resultText.textContent = newString
}

// Listen to events and initiate a stopword removal
sentenceInput.addEventListener('keyup', updateSentence)

// Configure the language select
const allLanguages = Object.entries(sw)
  .filter(([key, val]) => Array.isArray(val))
  .map((val) => val[0])

languageSelect.addEventListener('change', function (event) {
  languageSelect.value = event.target.value
  sentenceInput.focus()
  updateSentence()
})

languageSelect.innerHTML = allLanguages
  .map((lang) => `<option value=${lang}>${lang.toUpperCase()}</option>`)
  .join('')

languageSelect.value = 'en'
<|endoftext|>


<commit_before>require("./style/testsheet.scss")
document.write("testsdjabsjdabs");
//var pug = require('jstransformer')(require('jstransformer-pug'))
/*
// Compile the source code
const compiledFunction = pug.compileFile('test.pug');

// Render a set of data
console.log(compiledFunction({
  name: 'Timothy'
}));
*/
// "
Timothy's Pug source code!
"
<commit_msg>Delete entry.js<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2012 The Closure Compiler Authors.
 *
 * 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.
 */

/**
 * @fileoverview Definitions for Express.js.
 * @see http://expressjs.com/api.html
 * @externs
 * @author Daniel Wirtz <dcode@dcode.io>
 */

/**
 * @type {function(new:Application, ...)}
 */
function express() {}

/**
 * @type {@function(new:Application, ...}}
 */
express.application = function() {};

/**
 * @type {@function(new:ExpressRequest, ...)}
 */
express.request = function() {};

/**
 * @type {@function(new:ExpressResponse, ...)}
 */
express.response = function() {};

/**
 * @type {@function(new:ExpressRoute, ...})
 */
express.Route = function() {};

/**
 * @type {@function(new:ExpressRouter, ...})
 */
express.Router = function() {};

/**
 * @type {@function(...)}
 */
express.errorHandler = function() {};

/**
 * @type {function}
 * @return {*}
 */
express["static"] = function() {};

/**
 * @type {string}
 */
express.errorHandler.title;

/**
 * @typedef {function(new:Application, ...)}
 */
var Application;

/**
 * @param {string} name
 * @param {*} value
 */
Application.prototype.set = function(name, value) {};

/**
 * @param {string} name
 */
Application.prototype.get = function(name) {};

/**
 * @param {string} name
 */
Application.prototype.enable = function(name) {};

/**
 * @param {string} name
 */
Application.prototype.disable = function(name) {};

/**
 * @param {string} name
 * @return {boolean}
 */
Application.prototype.enabled = function(name) {};

/**
 * @param {string} name
 * @return {boolean}
 */
Application.prototype.disabled = function(name) {};

/**
 * @param {string|Function} env
 * @param {Function=} callback
 */
Application.prototype.configure = function(env, callback) {};

/**
 * @param {string|Function} path
 * @param {Function=} func
 */
Application.prototype.use = function(path, func) {};

// TODO: Finish...
<commit_msg>Express<commit_after><|endoftext|>


<commit_before>// ==UserScript==
// @id             iitc-plugin-show-portal-weakness@vita10gy
// @name           iitc: show portal weakness
// @version        0.3
// @namespace      https://github.com/breunigs/ingress-intel-total-conversion
// @updateURL      https://raw.github.com/breunigs/ingress-intel-total-conversion/gh-pages/plugins/show-portal-weakness.user.js
// @downloadURL    https://raw.github.com/breunigs/ingress-intel-total-conversion/gh-pages/plugins/show-portal-weakness.user.js
// @description    Uses the fill color of the portals to denote if the portal is weak (Needs recharging, missing a resonator, needs shields)  Red, needs energy and shields. Orange, only needs energy (either recharge or resonators). Yellow, only needs shields.
// @include        http://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// ==/UserScript==

function wrapper() {
// ensure plugin framework is there, even if iitc is not yet loaded
if(typeof window.plugin !== 'function') window.plugin = function() {};

// PLUGIN START ////////////////////////////////////////////////////////

// use own namespace for plugin
window.plugin.portalWeakness = function() {};

window.plugin.portalWeakness.portalAdded = function(data) {

  var d = data.portal.options.details;
  var portal_weakness = 0;
  if(getTeam(d) !== 0) {
    var only_shields = true;
 	  var missing_shields = 0;
    if(window.getTotalPortalEnergy(d) > 0 && window.getCurrentPortalEnergy(d) < window.getTotalPortalEnergy(d)) {
      portal_weakness = 1 - (window.getCurrentPortalEnergy(d)/window.getTotalPortalEnergy(d));
      only_shields = false;
    }
    //Ding the portal for every missing sheild.
    $.each(d.portalV2.linkedModArray, function(ind, mod) {
      if(mod === null) {
        missing_shields++;
        portal_weakness += .08;
      }
    });
    //Ding the portal for every missing resonator.
    var resCount = 0;
    $.each(d.resonatorArray.resonators, function(ind, reso) {
      if(reso === null) {
        portal_weakness += .125;
        only_shields = false;
      } else {
        resCount++;
      }
    });
    if(portal_weakness < 0) {
      portal_weakness = 0;
    }
    if(portal_weakness > 1)
    {
      portal_weakness = 1;
    }

    if(portal_weakness > 0) {
      var fill_opacity = portal_weakness*.7 + .3;
      var color = 'orange';
      if(only_shields) {
        color = 'yellow';
        //If only shields are missing, make portal yellow, but fill more than usual since pale yellow is basically invisible
        fill_opacity = missing_shields*.15 + .1;
      } else if(missing_shields > 0) {
        color = 'red';
      }
      fill_opacity = Math.round(fill_opacity*100)/100;
      var params = {fillColor: color, fillOpacity: fill_opacity};
      if(resCount < 8)
      {
        // Hole per missing resonator
        var dash = new Array(8-resCount + 1).join("1,4,") + "100,0"
        params["dashArray"] = dash;
      }
      data.portal.setStyle(params);
    }
  }
}

var setup =  function() {
  window.addHook('portalAdded', window.plugin.portalWeakness.portalAdded);
  window.COLOR_SELECTED_PORTAL = '#f0f';
}

// PLUGIN END //////////////////////////////////////////////////////////

if(window.iitcLoaded && typeof setup === 'function') {
  setup();
} else {
  if(window.bootPlugins)
    window.bootPlugins.push(setup);
  else
    window.bootPlugins = [setup];
}
} // wrapper end
// inject code into site context
var script = document.createElement('script');
script.appendChild(document.createTextNode('('+ wrapper +')();'));
(document.body || document.head || document.documentElement).appendChild(script);
<commit_msg>More Nits<commit_after>// ==UserScript==
// @id             iitc-plugin-show-portal-weakness@vita10gy
// @name           iitc: show portal weakness
// @version        0.3
// @namespace      https://github.com/breunigs/ingress-intel-total-conversion
// @updateURL      https://raw.github.com/breunigs/ingress-intel-total-conversion/gh-pages/plugins/show-portal-weakness.user.js
// @downloadURL    https://raw.github.com/breunigs/ingress-intel-total-conversion/gh-pages/plugins/show-portal-weakness.user.js
// @description    Uses the fill color of the portals to denote if the portal is weak (Needs recharging, missing a resonator, needs shields)  Red, needs energy and shields. Orange, only needs energy (either recharge or resonators). Yellow, only needs shields.
// @include        http://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// ==/UserScript==

function wrapper() {
// ensure plugin framework is there, even if iitc is not yet loaded
if(typeof window.plugin !== 'function') window.plugin = function() {};

// PLUGIN START ////////////////////////////////////////////////////////

// use own namespace for plugin
window.plugin.portalWeakness = function() {};

window.plugin.portalWeakness.portalAdded = function(data) {

  var d = data.portal.options.details;
  var portal_weakness = 0;
  if(getTeam(d) !== 0) {
    var only_shields = true;
    var missing_shields = 0;
    if(window.getTotalPortalEnergy(d) > 0 && window.getCurrentPortalEnergy(d) < window.getTotalPortalEnergy(d)) {
      portal_weakness = 1 - (window.getCurrentPortalEnergy(d)/window.getTotalPortalEnergy(d));
      only_shields = false;
    }
    //Ding the portal for every missing sheild.
    $.each(d.portalV2.linkedModArray, function(ind, mod) {
      if(mod === null) {
        missing_shields++;
        portal_weakness += .08;
      }
    });
    //Ding the portal for every missing resonator.
    var resCount = 0;
    $.each(d.resonatorArray.resonators, function(ind, reso) {
      if(reso === null) {
        portal_weakness += .125;
        only_shields = false;
      } else {
        resCount++;
      }
    });
    if(portal_weakness < 0) {
      portal_weakness = 0;
    }
    if(portal_weakness > 1)
    {
      portal_weakness = 1;
    }

    if(portal_weakness > 0) {
      var fill_opacity = portal_weakness*.7 + .3;
      var color = 'orange';
      if(only_shields) {
        color = 'yellow';
        //If only shields are missing, make portal yellow
        //but fill more than usual since pale yellow is basically invisible
        fill_opacity = missing_shields*.15 + .1;
      } else if(missing_shields > 0) {
        color = 'red';
      }
      fill_opacity = Math.round(fill_opacity*100)/100;
      var params = {fillColor: color, fillOpacity: fill_opacity};
      if(resCount < 8)
      {
        // Hole per missing resonator
        var dash = new Array(8-resCount + 1).join("1,4,") + "100,0"
        params["dashArray"] = dash;
      }
      data.portal.setStyle(params);
    }
  }
}

var setup =  function() {
  window.addHook('portalAdded', window.plugin.portalWeakness.portalAdded);
  window.COLOR_SELECTED_PORTAL = '#f0f';
}

// PLUGIN END //////////////////////////////////////////////////////////

if(window.iitcLoaded && typeof setup === 'function') {
  setup();
} else {
  if(window.bootPlugins)
    window.bootPlugins.push(setup);
  else
    window.bootPlugins = [setup];
}
} // wrapper end
// inject code into site context
var script = document.createElement('script');
script.appendChild(document.createTextNode('('+ wrapper +')();'));
(document.body || document.head || document.documentElement).appendChild(script);
<|endoftext|>


<commit_before>var async = require('async');

var db = require('../data/db');

var express = require('express');
var router = express.Router();

router.get('/create', function(req, res) {
    res.render('questions/create', {
        title: 'Create New Question'
    });
});

router.post('/create', isAuthenticated, function(req, res) {
    var database = req.app.get('db');

    req.assert('question', 'Question field is empty.').notEmpty();
    req.assert('details', 'Details field is empty.').notEmpty();

    var errors = req.validationErrors();

    if (errors) {
        req.flash('errors', errors);
        return res.redirect('create');
    } else {
        database.createQuestion(req.body.question, req.body.details,
                                req.user.username, success);

        function success(question) {
            req.flash('success', {msg: 'New question created.'});
            res.redirect('view?q=' + question.id);
        }
    }
});

router.get('/find', function(req, res) {
    var database = req.app.get('db');

    var page;
    if (req.query.page) {
        page = req.query.page - 1;
    } else {
        page = 0;
    }

    database.getNewQuestions(undefined, undefined, page * 10, function(questions) {
        getQuestionVoteScores(req, questions, database, function() {
            res.render('questions/find', {
                title: 'All Questions',
                questions: questions,
                currPage: page + 1,
                hasNextPage: questions.length == 10
            });
        });
    });
});

router.post('/search', function(req, res) {

    var filter = req.body.search;

    if (filter.length == 0){
        res.redirect('find');
    }
    else {
        res.render('questions/find', {
            title: 'Results for "'+filter+'"',
            filter: filter,
            questions: '',
            currPage: 1,
            hasNextPage: false
        });
    }
});

router.post('/pa', function(req, res) {
    if (req.user === undefined) {
        req.flash('errors', { msg: 'Please login before posting new argument.' });
        return res.redirect('/users/login');

    }else {
        if (req.body.argument == "") {
            req.flash('errors', { msg: 'Argument is empty.' });
            return res.redirect(req.get('referer'));

        }else {
            var argType = (req.body.post_arg === 'pro');

            req.app.get('db').createArgument(req.query.q, argType, req.body.argument, req.user.username, function (argument) {
                argType ? req.flash('success', {msg: 'New agree argument posted!'}) : req.flash('success', {msg: 'New disagree argument posted!'});
                res.redirect(req.get('referer'));

            });
        }
    }
});

router.get('/view', function(req, res) {
    function error() {
        req.flash('errors', {
            msg: 'Failed to load question. Please try again.'
        });
        res.redirect('/questions/find');
    }

    var dbInst = req.app.get('db');

    var page;
    if (req.query.page) {
        page = req.query.page - 1;
    } else {
        page = 0;
    }

    try {
        dbInst.getQuestion(req.query.q, function(question) {
            if (!question) {
                error();
                return;
            }

            dbInst.getQuestionVoteScore(question.id, function(questionVoteScore) {
                question.voteScore = questionVoteScore;

                dbInst.getNewArguments(question.id, undefined, undefined, undefined, page * 10, function(args) {
                    // Sort arguments into separate arrays for "for" and "against"
                    var argsFor = [];
                    var argsAgainst = [];
                    for (var i = 0; i < args.length; i++) {
                        if (args[i].type === db.ArgumentType.PRO) {
                            argsFor.push(args[i]);
                        } else {
                            argsAgainst.push(args[i]);
                        }
                    }

                    async.each(args, function(argument, callback) {
                        dbInst.getArgumentVoteScore(question.id, argument.id, function(argumentVoteScore) {
                            argument.voteScore = argumentVoteScore;
                            callback();
                        });
                    }, function() {
                        if (req.user) {
                            dbInst.getQuestionVote(question.id, req.user.username, function(questionVote) {
                                question.upVoted = questionVote === db.VoteType.UP;
                                question.downVoted = questionVote === db.VoteType.DOWN;

                                async.each(args, function(argument, callback) {
                                    dbInst.getArgumentVote(question.id, argument.id, req.user.username, function(argumentVote) {
                                        argument.upVoted = argumentVote === db.VoteType.UP;
                                        argument.downVoted = argumentVote === db.VoteType.DOWN;
                                        callback();
                                    });
                                }, function() {
                                    render();
                                });
                            });
                        } else {
                            question.upVoted = false;
                            question.downVoted = false;

                            for (var i = 0; i < args.length; i++) {
                                args[i].upVoted = false;
                                args[i].downVoted = false;
                            }

                            render();
                        }
                    });

                    function render() {
                        res.render('questions/view', {
                            title: "Question: " + question.title,
                            question: question,
                            argsFor: argsFor,
                            argsAgainst: argsAgainst,
                            currArgs: page + 1,
                            hasNextArgs: argsFor.length == 10 || argsAgainst.length == 10
                        });
                    }
                });
            });
        });
    } catch (err) {
        error();
    }
});

router.post('/vote', function(req, res) {
    if (!req.query.q) {
        req.flash('errors', {
            msg: 'No question ID specified. Please try voting again.'
        });
        res.redirect(req.get('referer'));
        return;
    } else if (!req.user) {
        req.flash('errors', {
            msg: 'Please login before voting on a question or argument.'
        });
        res.redirect('/users/login');
        return;
    } else if (req.body.vote !== "up" && req.body.vote !== "down" && req.body.vote !== "none") {
        req.flash('errors', {
            msg: 'No vote specified. Please try voting again.'
        });
        res.redirect(req.get('referer'));
        return;
    }

    var dbInst = req.app.get('db');
    try {
        function upVote() {
            req.flash('success', {
                msg: 'Upvote recorded!'
            });
            res.redirect(req.get('referer'));
        }

        function downVote() {
            req.flash('success', {
                msg: 'Downvote recorded!'
            });
            res.redirect(req.get('referer'));
        }

        function noVote() {
            req.flash('success', {
                msg: 'Vote removal recorded!'
            });
            res.redirect(req.get('referer'));
        }

        if (req.query.a) {
            if (req.body.vote === "up") {
                dbInst.setArgumentVote(req.query.q, req.query.a,
                                       req.user.username, db.VoteType.UP,
                                       upVote);
            } else if (req.body.vote === "down") {
                dbInst.setArgumentVote(req.query.q, req.query.a,
                                       req.user.username, db.VoteType.DOWN,
                                       downVote);
            } else {
                dbInst.setArgumentVote(req.query.q, req.query.a,
                                       req.user.username, db.VoteType.NONE,
                                       noVote);
            }
        } else {
            if (req.body.vote === "up") {
                dbInst.setQuestionVote(req.query.q, req.user.username,
                                       db.VoteType.UP, upVote);
            } else if (req.body.vote === "down") {
                dbInst.setQuestionVote(req.query.q, req.user.username,
                                       db.VoteType.DOWN, downVote);
            } else {
                dbInst.setQuestionVote(req.query.q, req.user.username,
                                       db.VoteType.NONE, noVote);
            }
        }
    } catch (err) {
        req.flash('errors', {
            msg: 'Error recording vote. Please try voting again.'
        });
        res.redirect(req.get('referer'));
    }
});

function isAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    req.flash('errors', {msg: 'Please login before performing that action.'});
    res.redirect('/users/login');
}

function getQuestionVoteScores(req, questions, database, callback) {
    async.each(questions, function(question, callback) {
        database.getQuestionVoteScore(question.id, function(questionVoteScore) {
            question.voteScore = questionVoteScore;
            if (req.isAuthenticated()) {
                database.getQuestionVote(question.id, req.user.username, function(questionVote) {
                    question.upVoted = questionVote === db.VoteType.UP;
                    question.downVoted = questionVote === db.VoteType.DOWN;

                    callback();
                });
            } else {
                question.upVoted = false;
                question.downVoted = false;

                callback();
            }
        });
    }, callback);
}

module.exports = router;
<commit_msg>Cleanup backend search<commit_after>var async = require('async');

var db = require('../data/db');

var express = require('express');
var router = express.Router();

router.get('/create', function(req, res) {
    res.render('questions/create', {
        title: 'Create New Question'
    });
});

router.post('/create', isAuthenticated, function(req, res) {
    var database = req.app.get('db');

    req.assert('question', 'Question field is empty.').notEmpty();
    req.assert('details', 'Details field is empty.').notEmpty();

    var errors = req.validationErrors();

    if (errors) {
        req.flash('errors', errors);
        return res.redirect('create');
    } else {
        database.createQuestion(req.body.question, req.body.details,
                                req.user.username, success);

        function success(question) {
            req.flash('success', {msg: 'New question created.'});
            res.redirect('view?q=' + question.id);
        }
    }
});

router.get('/find', function(req, res) {
    var database = req.app.get('db');

    var page;
    if (req.query.page) {
        page = req.query.page - 1;
    } else {
        page = 0;
    }

    database.getNewQuestions(undefined, undefined, page * 10, function(questions) {
        getQuestionVoteScores(req, questions, database, function() {
            res.render('questions/find', {
                title: 'All Questions',
                questions: questions,
                currPage: page + 1,
                hasNextPage: questions.length == 10
            });
        });
    });
});

router.post('/search', function(req, res) {
    var filter = req.body.search;

    // TODO: Implement database access for search
    if (filter.length === 0) {
        res.redirect('find');
    } else {
        res.render('questions/find', {
            title: 'Results for "' + filter + '"',
            filter: filter,
            questions: '',
            currPage: 1,
            hasNextPage: false
        });
    }
});

router.post('/pa', function(req, res) {
    if (req.user === undefined) {
        req.flash('errors', { msg: 'Please login before posting new argument.' });
        return res.redirect('/users/login');

    }else {
        if (req.body.argument == "") {
            req.flash('errors', { msg: 'Argument is empty.' });
            return res.redirect(req.get('referer'));

        }else {
            var argType = (req.body.post_arg === 'pro');

            req.app.get('db').createArgument(req.query.q, argType, req.body.argument, req.user.username, function (argument) {
                argType ? req.flash('success', {msg: 'New agree argument posted!'}) : req.flash('success', {msg: 'New disagree argument posted!'});
                res.redirect(req.get('referer'));

            });
        }
    }
});

router.get('/view', function(req, res) {
    function error() {
        req.flash('errors', {
            msg: 'Failed to load question. Please try again.'
        });
        res.redirect('/questions/find');
    }

    var dbInst = req.app.get('db');

    var page;
    if (req.query.page) {
        page = req.query.page - 1;
    } else {
        page = 0;
    }

    try {
        dbInst.getQuestion(req.query.q, function(question) {
            if (!question) {
                error();
                return;
            }

            dbInst.getQuestionVoteScore(question.id, function(questionVoteScore) {
                question.voteScore = questionVoteScore;

                dbInst.getNewArguments(question.id, undefined, undefined, undefined, page * 10, function(args) {
                    // Sort arguments into separate arrays for "for" and "against"
                    var argsFor = [];
                    var argsAgainst = [];
                    for (var i = 0; i < args.length; i++) {
                        if (args[i].type === db.ArgumentType.PRO) {
                            argsFor.push(args[i]);
                        } else {
                            argsAgainst.push(args[i]);
                        }
                    }

                    async.each(args, function(argument, callback) {
                        dbInst.getArgumentVoteScore(question.id, argument.id, function(argumentVoteScore) {
                            argument.voteScore = argumentVoteScore;
                            callback();
                        });
                    }, function() {
                        if (req.user) {
                            dbInst.getQuestionVote(question.id, req.user.username, function(questionVote) {
                                question.upVoted = questionVote === db.VoteType.UP;
                                question.downVoted = questionVote === db.VoteType.DOWN;

                                async.each(args, function(argument, callback) {
                                    dbInst.getArgumentVote(question.id, argument.id, req.user.username, function(argumentVote) {
                                        argument.upVoted = argumentVote === db.VoteType.UP;
                                        argument.downVoted = argumentVote === db.VoteType.DOWN;
                                        callback();
                                    });
                                }, function() {
                                    render();
                                });
                            });
                        } else {
                            question.upVoted = false;
                            question.downVoted = false;

                            for (var i = 0; i < args.length; i++) {
                                args[i].upVoted = false;
                                args[i].downVoted = false;
                            }

                            render();
                        }
                    });

                    function render() {
                        res.render('questions/view', {
                            title: "Question: " + question.title,
                            question: question,
                            argsFor: argsFor,
                            argsAgainst: argsAgainst,
                            currArgs: page + 1,
                            hasNextArgs: argsFor.length == 10 || argsAgainst.length == 10
                        });
                    }
                });
            });
        });
    } catch (err) {
        error();
    }
});

router.post('/vote', function(req, res) {
    if (!req.query.q) {
        req.flash('errors', {
            msg: 'No question ID specified. Please try voting again.'
        });
        res.redirect(req.get('referer'));
        return;
    } else if (!req.user) {
        req.flash('errors', {
            msg: 'Please login before voting on a question or argument.'
        });
        res.redirect('/users/login');
        return;
    } else if (req.body.vote !== "up" && req.body.vote !== "down" && req.body.vote !== "none") {
        req.flash('errors', {
            msg: 'No vote specified. Please try voting again.'
        });
        res.redirect(req.get('referer'));
        return;
    }

    var dbInst = req.app.get('db');
    try {
        function upVote() {
            req.flash('success', {
                msg: 'Upvote recorded!'
            });
            res.redirect(req.get('referer'));
        }

        function downVote() {
            req.flash('success', {
                msg: 'Downvote recorded!'
            });
            res.redirect(req.get('referer'));
        }

        function noVote() {
            req.flash('success', {
                msg: 'Vote removal recorded!'
            });
            res.redirect(req.get('referer'));
        }

        if (req.query.a) {
            if (req.body.vote === "up") {
                dbInst.setArgumentVote(req.query.q, req.query.a,
                                       req.user.username, db.VoteType.UP,
                                       upVote);
            } else if (req.body.vote === "down") {
                dbInst.setArgumentVote(req.query.q, req.query.a,
                                       req.user.username, db.VoteType.DOWN,
                                       downVote);
            } else {
                dbInst.setArgumentVote(req.query.q, req.query.a,
                                       req.user.username, db.VoteType.NONE,
                                       noVote);
            }
        } else {
            if (req.body.vote === "up") {
                dbInst.setQuestionVote(req.query.q, req.user.username,
                                       db.VoteType.UP, upVote);
            } else if (req.body.vote === "down") {
                dbInst.setQuestionVote(req.query.q, req.user.username,
                                       db.VoteType.DOWN, downVote);
            } else {
                dbInst.setQuestionVote(req.query.q, req.user.username,
                                       db.VoteType.NONE, noVote);
            }
        }
    } catch (err) {
        req.flash('errors', {
            msg: 'Error recording vote. Please try voting again.'
        });
        res.redirect(req.get('referer'));
    }
});

function isAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    req.flash('errors', {msg: 'Please login before performing that action.'});
    res.redirect('/users/login');
}

function getQuestionVoteScores(req, questions, database, callback) {
    async.each(questions, function(question, callback) {
        database.getQuestionVoteScore(question.id, function(questionVoteScore) {
            question.voteScore = questionVoteScore;
            if (req.isAuthenticated()) {
                database.getQuestionVote(question.id, req.user.username, function(questionVote) {
                    question.upVoted = questionVote === db.VoteType.UP;
                    question.downVoted = questionVote === db.VoteType.DOWN;

                    callback();
                });
            } else {
                question.upVoted = false;
                question.downVoted = false;

                callback();
            }
        });
    }, callback);
}

module.exports = router;
<|endoftext|>


<commit_before>"use strict";

const http = require('http');
const express = require('express');
const StandardError = require('standard-error');
const emptylogger = require('bunyan-blackhole');
const expressBunyanLogger = require("express-bunyan-logger");
const routes = require('./routes');
const bodyParser = require('body-parser');
const cors = require('cors');
const UrlAssembler = require('url-assembler');
const Redis = require('ioredis');
const js2xmlparser = require("js2xmlparser");
const formatFromUrl = require('./lib/middlewares/formatFromUrl')
const getApiKeyFromQueryParam = require('./lib/middlewares/getApiKeyFromQueryParam')
const identifyUser = require('./lib/middlewares/identifyUser')
const loggerProperties = require('./lib/middlewares/logger')
const formatError = require('./lib/middlewares/formatError')
const isAuthorized = require('./lib/middlewares/isAuthorized')
const UsersService = require('./lib/services/users');

var extend = require('extend');

module.exports = Server;

function Server (options) {
  var self = this;
  options = options || {};
  options.port = options.port || 0;
  var logger = options.logger || emptylogger();
  var app = express();
  app.set('port', options.port);
  app.set('json spaces', 2);
  app.set('logger', logger);
  app.set('cafHost',  options.cafHost);
  app.set('cafSslCertificate',  options.cafSslCertificate);
  app.set('cafSslKey',  options.cafSslKey);
  app.set('tokensPrefix',  options.redis.tokensPrefix);
  app.set('banBaseUrl', options.ban.baseUrl)
  app.disable('x-powered-by');
  app.use(express.static('public'));
  var usersService = new UsersService(options);
  app.set('usersService', usersService)

  app.use(bodyParser.json());
  var corsOptions = {
    exposedHeaders: ['Range', 'Content-Range', 'X-Content-Range'],
    credentials: true,
    origin: function (origin, callback) {
      logger.info('using cors origin', origin);
      callback(null, true);
    }
  };
  app.use(cors(corsOptions));

  app.use(expressBunyanLogger({
    name: "requests",
    logger: logger,
    excludes: loggerProperties.excludes,
    includesFn: loggerProperties.includesFn
  }));

  app.use((req, res, next) => {
    req.logger = logger;
    next();
  })

  app.use(getApiKeyFromQueryParam)
  app.use(identifyUser)

  app.use(formatFromUrl)

  app.use(isAuthorized(usersService))

  routes.configure(app, options);

  if (options.staticPath) app.use(express.static(options.staticPath));

  app.use(function notFound(req, res, next) {
    next(new StandardError('no route for URL ' + req.url, {code: 404}));
  });

  app.use(formatError);

  this.getPort = function() {
    return this.port;
  };

  var server = http.createServer(app);
  this.start = function (onStarted) {
    server.listen(app.get('port'), function (error) {
      if (error) {
        logger.error({error: error}, 'Got error while starting server');
        return onStarted(error);
      }
      self.port = server.address().port;
      app.set('port', self.port);
      logger.info({
        event: 'server_started',
        port: self.port
      }, 'Server listening on port', self.port);
      onStarted();
    });
  };

  this.stop = function (onStopped) {
    logger.info({
      event: 'server_stopping'
    }, 'Stopping server');
    server.close(function (error) {
      if (error) {
        logger.error({error: error}, 'Got error while stopping server');
        return onStopped(error);
      }
      logger.info({
        event: 'server_stopped'
      }, 'server stopped');
      onStopped();
    });
  }
}
<commit_msg>remove url from logging message<commit_after>"use strict";

const http = require('http');
const express = require('express');
const StandardError = require('standard-error');
const emptylogger = require('bunyan-blackhole');
const expressBunyanLogger = require("express-bunyan-logger");
const routes = require('./routes');
const bodyParser = require('body-parser');
const cors = require('cors');
const UrlAssembler = require('url-assembler');
const Redis = require('ioredis');
const js2xmlparser = require("js2xmlparser");
const formatFromUrl = require('./lib/middlewares/formatFromUrl')
const getApiKeyFromQueryParam = require('./lib/middlewares/getApiKeyFromQueryParam')
const identifyUser = require('./lib/middlewares/identifyUser')
const loggerProperties = require('./lib/middlewares/logger')
const formatError = require('./lib/middlewares/formatError')
const isAuthorized = require('./lib/middlewares/isAuthorized')
const UsersService = require('./lib/services/users');

var extend = require('extend');

module.exports = Server;

function Server (options) {
  var self = this;
  options = options || {};
  options.port = options.port || 0;
  var logger = options.logger || emptylogger();
  var app = express();
  app.set('port', options.port);
  app.set('json spaces', 2);
  app.set('logger', logger);
  app.set('cafHost',  options.cafHost);
  app.set('cafSslCertificate',  options.cafSslCertificate);
  app.set('cafSslKey',  options.cafSslKey);
  app.set('tokensPrefix',  options.redis.tokensPrefix);
  app.set('banBaseUrl', options.ban.baseUrl)
  app.disable('x-powered-by');
  app.use(express.static('public'));
  var usersService = new UsersService(options);
  app.set('usersService', usersService)

  app.use(bodyParser.json());
  var corsOptions = {
    exposedHeaders: ['Range', 'Content-Range', 'X-Content-Range'],
    credentials: true,
    origin: function (origin, callback) {
      logger.info('using cors origin', origin);
      callback(null, true);
    }
  };
  app.use(cors(corsOptions));

  app.use(expressBunyanLogger({
    name: "requests",
    logger: logger,
    excludes: loggerProperties.excludes,
    includesFn: loggerProperties.includesFn,
    format: '":remote-address :incoming :method HTTP/:http-version :status-code :res-headers[content-length] :referer :user-agent[family] :user-agent[major].:user-agent[minor] :user-agent[os] :response-time ms";'
  }));

  app.use((req, res, next) => {
    req.logger = logger;
    next();
  })

  app.use(getApiKeyFromQueryParam)
  app.use(identifyUser)

  app.use(formatFromUrl)

  app.use(isAuthorized(usersService))

  routes.configure(app, options);

  if (options.staticPath) app.use(express.static(options.staticPath));

  app.use(function notFound(req, res, next) {
    next(new StandardError('no route for URL ' + req.url, {code: 404}));
  });

  app.use(formatError);

  this.getPort = function() {
    return this.port;
  };

  var server = http.createServer(app);
  this.start = function (onStarted) {
    server.listen(app.get('port'), function (error) {
      if (error) {
        logger.error({error: error}, 'Got error while starting server');
        return onStarted(error);
      }
      self.port = server.address().port;
      app.set('port', self.port);
      logger.info({
        event: 'server_started',
        port: self.port
      }, 'Server listening on port', self.port);
      onStarted();
    });
  };

  this.stop = function (onStopped) {
    logger.info({
      event: 'server_stopping'
    }, 'Stopping server');
    server.close(function (error) {
      if (error) {
        logger.error({error: error}, 'Got error while stopping server');
        return onStopped(error);
      }
      logger.info({
        event: 'server_stopped'
      }, 'server stopped');
      onStopped();
    });
  }
}
<|endoftext|>


<commit_before><commit_msg>Optimization for array params<commit_after><|endoftext|>


<commit_before>/**
 * @fileoverview Enum을 구현한 모듈이 정의 되어있다.
 * @author 김성호 sungho-kim@nhnent.com
 * @dependency type, collection.js
 */

(function(ne) {

'use strict';

/* istanbul ignore if */
if (!ne) {
    ne = window.ne = {};
}
if (!ne.util) {
    ne.util = window.ne.util = {};
}

/**
 * definedProperty지원 여부 체크
 * @returns {boolean}
 */
var isModernBrowser = (function () {
    try {
        Object.defineProperty({}, 'x', {});
        return true;
    } catch (e) {
        return false;
    }
}());

/**
 * 상수에 들어갈 임의의 값
 * @type {number}
 */
var enumValue = 0;

/**
 * Enums
 * 임의의 값이지만 중복되지 않는 값을 갖는 상수의 목록을 만든다
 * IE8이하를 제외한 모던브라우저에서는
 * 한번 결정된값은 추후 변경될수 없다(바꾸려고 시도해도 원래 값을 유지한다)
 *
 * @param {...string} itemList 상수목록, 스트링 배열 가능
 * @exports Enums
 * @constructor
 * @class
 *
 * @examples
 *
 * //생성
 * var MYENUM = new Enums('TYPE1', 'TYPE2');
 * var MYENUM2 = new Enums(['TYPE1', 'TYPE2']);
 *
 * //사용
 * if (value === MYENUM.TYPE1) {
 *      ....
 * }
 *
 * //추가하기(이미 정해진 상수명을 입력하는경우 무시된다)
 * MYENUM.set('TYPE3', 'TYPE4');
 *
 * //값을 이용해 상수명을 얻어오는 방법
 * MYENUM.getName(MYENUM.TYPE1); // 'TYPE1'이 리턴된다.
 *
 * //IE9이상의 브라우저와 기타 모던브라우저에서는 값이 변경되지 않는다.
 * var originalValue = MYENUM.TYPE1;
 * MYENUM.TYPE1 = 1234; // maybe TypeError
 * MYENUM.TYPE1 === originalValue; // true
 *
 **/
function Enums(itemList) {
    if (itemList) {
        this.set.apply(this, arguments);
    }
}

/**
 * set
 * 상수를 정의한다.
 * @param {...string| string[]} itemList 상수목록, 스트링 배열도
 */
Enums.prototype.set = function(itemList) {
    var self = this;

    if (!ne.util.isArray(itemList)) {
        itemList = ne.util.toArray(arguments);
    }

    ne.util.forEach(itemList, function itemListIteratee(item) {
        self._addItem(item);
    });
};

/**
 * getName
 * 값을 넘기면 해당하는 상수의 키값을 리턴해준다.
 * @param {number} value 비교할 값
 * @returns {string} 상수의 키값
 */
Enums.prototype.getName = function(value) {
    var foundedKey,
        self = this;

    ne.util.forEach(this, function(itemValue, key) {
        if (self._isEnumItem(key) && value === itemValue) {
            foundedKey = key;
            return false;
        }
    });

    return foundedKey;
};

/**
 * _addItem
 * 상수를 생성한다
 * @private
 * @param {string} name 상수명
 */
Enums.prototype._addItem = function(name) {
    var value;

    if (!this.hasOwnProperty(name)) {
        value = this._makeEnumValue();

        if (isModernBrowser) {
            Object.defineProperty(this, name, {
                enumerable: true,
                configurable: false,
                writable: false,
                value: value
            });
        } else {
            this[name] = value;
        }
    }
};

/**
 * _makeEnumValue
 * id와 valueCount를 이용해 상수에 대입할 값을 구한다
 * 항상 string이다.
 * @private
 * @returns {number} 상수에 대입될 값
 */
Enums.prototype._makeEnumValue = function() {
    var value;

    value = enumValue;
    enumValue += 1;

    return value;
};

/**
 * _isEnumItem
 * 키의 이름을 입력받아 이 키에 해당하는 내용이 상수인지 아닌지를 판별한다
 * @param {string} key 프로퍼티 키값
 * @returns {boolean} 결과
 * @private
 */
Enums.prototype._isEnumItem = function(key) {
    return typeof this[key] === 'number';
};

ne.util.Enums = Enums;

})(window.ne);
<commit_msg>jsdoc수정<commit_after>/**
 * @fileoverview Enum을 구현한 모듈이 정의 되어있다.
 * @author 김성호 sungho-kim@nhnent.com
 * @dependency type, collection.js
 */

(function(ne) {

'use strict';

/* istanbul ignore if */
if (!ne) {
    ne = window.ne = {};
}
if (!ne.util) {
    ne.util = window.ne.util = {};
}

/**
 * definedProperty지원 여부 체크
 * @returns {boolean}
 */
var isModernBrowser = (function () {
    try {
        Object.defineProperty({}, 'x', {});
        return true;
    } catch (e) {
        return false;
    }
}());

/**
 * 상수에 들어갈 임의의 값
 * @type {number}
 */
var enumValue = 0;

/**
 * Enums
 * 임의의 값이지만 중복되지 않는 값을 갖는 상수의 목록을 만든다
 * IE8이하를 제외한 모던브라우저에서는
 * 한번 결정된값은 추후 변경될수 없다(바꾸려고 시도해도 원래 값을 유지한다)
 *
 * @param {...string | string[]} itemList 상수목록, 스트링 배열 가능
 * @exports Enums
 * @constructor
 * @class
 *
 * @examples
 *
 * //생성
 * var MYENUM = new Enums('TYPE1', 'TYPE2');
 * var MYENUM2 = new Enums(['TYPE1', 'TYPE2']);
 *
 * //사용
 * if (value === MYENUM.TYPE1) {
 *      ....
 * }
 *
 * //추가하기(이미 정해진 상수명을 입력하는경우 무시된다)
 * MYENUM.set('TYPE3', 'TYPE4');
 *
 * //값을 이용해 상수명을 얻어오는 방법
 * MYENUM.getName(MYENUM.TYPE1); // 'TYPE1'이 리턴된다.
 *
 * //IE9이상의 브라우저와 기타 모던브라우저에서는 값이 변경되지 않는다.
 * var originalValue = MYENUM.TYPE1;
 * MYENUM.TYPE1 = 1234; // maybe TypeError
 * MYENUM.TYPE1 === originalValue; // true
 *
 **/
function Enums(itemList) {
    if (itemList) {
        this.set.apply(this, arguments);
    }
}

/**
 * set
 * 상수를 정의한다.
 * @param {...string| string[]} itemList 상수목록, 스트링 배열도
 */
Enums.prototype.set = function(itemList) {
    var self = this;

    if (!ne.util.isArray(itemList)) {
        itemList = ne.util.toArray(arguments);
    }

    ne.util.forEach(itemList, function itemListIteratee(item) {
        self._addItem(item);
    });
};

/**
 * getName
 * 값을 넘기면 해당하는 상수의 키값을 리턴해준다.
 * @param {number} value 비교할 값
 * @returns {string} 상수의 키값
 */
Enums.prototype.getName = function(value) {
    var foundedKey,
        self = this;

    ne.util.forEach(this, function(itemValue, key) {
        if (self._isEnumItem(key) && value === itemValue) {
            foundedKey = key;
            return false;
        }
    });

    return foundedKey;
};

/**
 * _addItem
 * 상수를 생성한다
 * @private
 * @param {string} name 상수명
 */
Enums.prototype._addItem = function(name) {
    var value;

    if (!this.hasOwnProperty(name)) {
        value = this._makeEnumValue();

        if (isModernBrowser) {
            Object.defineProperty(this, name, {
                enumerable: true,
                configurable: false,
                writable: false,
                value: value
            });
        } else {
            this[name] = value;
        }
    }
};

/**
 * _makeEnumValue
 * id와 valueCount를 이용해 상수에 대입할 값을 구한다
 * 항상 string이다.
 * @private
 * @returns {number} 상수에 대입될 값
 */
Enums.prototype._makeEnumValue = function() {
    var value;

    value = enumValue;
    enumValue += 1;

    return value;
};

/**
 * _isEnumItem
 * 키의 이름을 입력받아 이 키에 해당하는 내용이 상수인지 아닌지를 판별한다
 * @param {string} key 프로퍼티 키값
 * @returns {boolean} 결과
 * @private
 */
Enums.prototype._isEnumItem = function(key) {
    return typeof this[key] === 'number';
};

ne.util.Enums = Enums;

})(window.ne);
<|endoftext|>


<commit_before>OO.ui.Demo.static.pages.icons = function ( demo ) {
	var i, len, iconSet, iconsFieldset, iconWidget, selector,
		icons = {
			core: [
				'add',
				'advanced',
				'alert',
				'cancel',
				'check',
				'circle',
				'close',
				'collapse',
				'comment',
				'ellipsis',
				'expand',
				'help',
				'history',
				'info',
				'menu',
				'next',
				'notice',
				'previous',
				'search',
				'settings',
				'tag',
				'window'
			],
			movement: [
				'arrowLast',
				'arrowNext',
				'downTriangle',
				'upTriangle',
				'caretLast',
				'caretNext',
				'caretDown',
				'caretUp',
				'move'
			],
			content: [
				'article',
				'articles',
				'articleCheck',
				'articleSearch',
				'articleRedirect',
				'citeArticle',
				'book',
				'journal',
				'newspaper',
				'folderPlaceholder',
				'die',
				'download',
				'upload'
			],
			alerts: [
				'bell',
				'bellOn',
				'eye',
				'eyeClosed',
				'message',
				'signature',
				'speechBubble',
				'speechBubbleAdd',
				'speechBubbles',
				'tray'
			],
			interactions: [
				'bookmark',
				'browser',
				'clear',
				'clock',
				'funnel',
				'heart',
				'key',
				'keyboard',
				'logOut',
				'newWindow',
				'printer',
				'sun',
				'watchlist'
			],
			moderation: [
				'block',
				'unBlock',
				'flag',
				'unFlag',
				'lock',
				'unLock',
				'star',
				'unStar',
				'trash',
				'unTrash',
				'ongoingConversation'
			],
			'editing-core': [
				'edit',
				'editLock',
				'editUndo',
				'link',
				'linkExternal',
				'linkSecure',
				'redo',
				'undo'
			],
			'editing-styling': [
				'bigger',
				'smaller',
				'subscript',
				'superscript',
				'bold',
				'italic',
				'strikethrough',
				'underline',
				'textDirLTR',
				'textDirRTL',
				'textStyle'
			],
			'editing-list': [
				'indent',
				'listBullet',
				'listNumbered',
				'outdent'
			],
			'editing-advanced': [
				'alignCentre',
				'alignLeft',
				'alignRight',
				'attachment',
				'calendar',
				'code',
				'find',
				'language',
				'layout',
				'markup',
				'newline',
				'noWikiText',
				'outline',
				'puzzle',
				'quotes',
				'quotesAdd',
				'searchCaseSensitive',
				'searchRegularExpression',
				'specialCharacter',
				'table',
				'tableAddColumnAfter',
				'tableAddColumnBefore',
				'tableAddRowAfter',
				'tableAddRowBefore',
				'tableCaption',
				'tableMergeCells',
				'templateAdd',
				'wikiText'
			],
			media: [
				'fullScreen',
				'image',
				'imageAdd',
				'imageLock',
				'imageGallery',
				'play',
				'stop'
			],
			location: [
				'map',
				'mapPin',
				'mapPinAdd',
				'wikitrail'
			],
			user: [
				'userActive',
				'userAvatar',
				'userInactive',
				'userTalk'
			],
			layout: [
				'stripeFlow',
				'stripeSideMenu',
				'stripeSummary',
				'stripeToC',
				'viewCompact',
				'viewDetails'
			],
			accessibility: [
				'bright',
				'halfBright',
				'notBright',
				'moon',
				'largerText',
				'smallerText',
				'visionSimulator'
			],
			wikimedia: [
				'logoCC',
				'logoWikimediaCommons',
				'logoWikimediaDiscovery',
				'logoWikipedia'
			]
		},
		indicators = [
			'alert',
			'clear',
			'down',
			'next',
			'previous',
			'required',
			'search',
			'up'
		],
		iconsFieldsets = [],
		iconsWidgets = [],
		indicatorsFieldset = new OO.ui.FieldsetLayout( { label: 'Indicators' } );

	for ( i = 0, len = indicators.length; i < len; i++ ) {
		indicatorsFieldset.addItems( [
			new OO.ui.FieldLayout(
				new OO.ui.IndicatorWidget( {
					indicator: indicators[ i ],
					title: indicators[ i ]
				} ),
				{
					align: 'inline',
					label: indicators[ i ]
				}
			)
		] );
	}
	for ( iconSet in icons ) {
		iconsFieldset = new OO.ui.FieldsetLayout( { label: 'Icons – ' + iconSet } );
		iconsFieldsets.push( iconsFieldset );

		for ( i = 0, len = icons[ iconSet ].length; i < len; i++ ) {
			iconWidget = new OO.ui.IconWidget( {
				icon: icons[ iconSet ][ i ],
				title: icons[ iconSet ][ i ]
			} );
			iconsWidgets.push( iconWidget );
			iconsFieldset.addItems( [
				new OO.ui.FieldLayout( iconWidget, {
					label: icons[ iconSet ][ i ],
					align: 'inline'
				} )
			] );
		}
	}

	selector = new OO.ui.ButtonSelectWidget( {
		items: [
			new OO.ui.ButtonOptionWidget( {
				label: 'None',
				flags: [],
				data: {
					progressive: false,
					constructive: false,
					destructive: false
				}
			} ),
			new OO.ui.ButtonOptionWidget( {
				label: 'Progressive',
				flags: [ 'progressive' ],
				data: {
					progressive: true,
					constructive: false,
					destructive: false
				}
			} ),
			new OO.ui.ButtonOptionWidget( {
				label: 'Constructive',
				flags: [ 'constructive' ],
				data: {
					progressive: false,
					constructive: true,
					destructive: false
				}
			} ),
			new OO.ui.ButtonOptionWidget( {
				label: 'Destructive',
				flags: [ 'destructive' ],
				data: {
					progressive: false,
					constructive: false,
					destructive: true
				}
			} )
		]
	} );

	selector
		.on( 'select', function ( selected ) {
			iconsWidgets.forEach( function ( iconWidget ) {
				iconWidget.setFlags( selected.getData() );
			} );
		} )
		.selectItemByData( {
			progressive: false,
			constructive: false,
			destructive: false
		} );

	demo.$element.append(
		new OO.ui.PanelLayout( {
			expanded: false,
			framed: true
		} ).$element
			.addClass( 'oo-ui-demo-container oo-ui-demo-icons' )
			.append(
				selector.$element,
				indicatorsFieldset.$element,
				iconsFieldsets.map( function ( item ) { return item.$element[ 0 ]; } )
			)
	);
};
<commit_msg>demo: Remove 'Constructive' button from the icons page<commit_after>OO.ui.Demo.static.pages.icons = function ( demo ) {
	var i, len, iconSet, iconsFieldset, iconWidget, selector,
		icons = {
			core: [
				'add',
				'advanced',
				'alert',
				'cancel',
				'check',
				'circle',
				'close',
				'collapse',
				'comment',
				'ellipsis',
				'expand',
				'help',
				'history',
				'info',
				'menu',
				'next',
				'notice',
				'previous',
				'search',
				'settings',
				'tag',
				'window'
			],
			movement: [
				'arrowLast',
				'arrowNext',
				'downTriangle',
				'upTriangle',
				'caretLast',
				'caretNext',
				'caretDown',
				'caretUp',
				'move'
			],
			content: [
				'article',
				'articles',
				'articleCheck',
				'articleSearch',
				'articleRedirect',
				'citeArticle',
				'book',
				'journal',
				'newspaper',
				'folderPlaceholder',
				'die',
				'download',
				'upload'
			],
			alerts: [
				'bell',
				'bellOn',
				'eye',
				'eyeClosed',
				'message',
				'signature',
				'speechBubble',
				'speechBubbleAdd',
				'speechBubbles',
				'tray'
			],
			interactions: [
				'bookmark',
				'browser',
				'clear',
				'clock',
				'funnel',
				'heart',
				'key',
				'keyboard',
				'logOut',
				'newWindow',
				'printer',
				'sun',
				'watchlist'
			],
			moderation: [
				'block',
				'unBlock',
				'flag',
				'unFlag',
				'lock',
				'unLock',
				'star',
				'unStar',
				'trash',
				'unTrash',
				'ongoingConversation'
			],
			'editing-core': [
				'edit',
				'editLock',
				'editUndo',
				'link',
				'linkExternal',
				'linkSecure',
				'redo',
				'undo'
			],
			'editing-styling': [
				'bigger',
				'smaller',
				'subscript',
				'superscript',
				'bold',
				'italic',
				'strikethrough',
				'underline',
				'textDirLTR',
				'textDirRTL',
				'textStyle'
			],
			'editing-list': [
				'indent',
				'listBullet',
				'listNumbered',
				'outdent'
			],
			'editing-advanced': [
				'alignCentre',
				'alignLeft',
				'alignRight',
				'attachment',
				'calendar',
				'code',
				'find',
				'language',
				'layout',
				'markup',
				'newline',
				'noWikiText',
				'outline',
				'puzzle',
				'quotes',
				'quotesAdd',
				'searchCaseSensitive',
				'searchRegularExpression',
				'specialCharacter',
				'table',
				'tableAddColumnAfter',
				'tableAddColumnBefore',
				'tableAddRowAfter',
				'tableAddRowBefore',
				'tableCaption',
				'tableMergeCells',
				'templateAdd',
				'wikiText'
			],
			media: [
				'fullScreen',
				'image',
				'imageAdd',
				'imageLock',
				'imageGallery',
				'play',
				'stop'
			],
			location: [
				'map',
				'mapPin',
				'mapPinAdd',
				'wikitrail'
			],
			user: [
				'userActive',
				'userAvatar',
				'userInactive',
				'userTalk'
			],
			layout: [
				'stripeFlow',
				'stripeSideMenu',
				'stripeSummary',
				'stripeToC',
				'viewCompact',
				'viewDetails'
			],
			accessibility: [
				'bright',
				'halfBright',
				'notBright',
				'moon',
				'largerText',
				'smallerText',
				'visionSimulator'
			],
			wikimedia: [
				'logoCC',
				'logoWikimediaCommons',
				'logoWikimediaDiscovery',
				'logoWikipedia'
			]
		},
		indicators = [
			'alert',
			'clear',
			'down',
			'next',
			'previous',
			'required',
			'search',
			'up'
		],
		iconsFieldsets = [],
		iconsWidgets = [],
		indicatorsFieldset = new OO.ui.FieldsetLayout( { label: 'Indicators' } );

	for ( i = 0, len = indicators.length; i < len; i++ ) {
		indicatorsFieldset.addItems( [
			new OO.ui.FieldLayout(
				new OO.ui.IndicatorWidget( {
					indicator: indicators[ i ],
					title: indicators[ i ]
				} ),
				{
					align: 'inline',
					label: indicators[ i ]
				}
			)
		] );
	}
	for ( iconSet in icons ) {
		iconsFieldset = new OO.ui.FieldsetLayout( { label: 'Icons – ' + iconSet } );
		iconsFieldsets.push( iconsFieldset );

		for ( i = 0, len = icons[ iconSet ].length; i < len; i++ ) {
			iconWidget = new OO.ui.IconWidget( {
				icon: icons[ iconSet ][ i ],
				title: icons[ iconSet ][ i ]
			} );
			iconsWidgets.push( iconWidget );
			iconsFieldset.addItems( [
				new OO.ui.FieldLayout( iconWidget, {
					label: icons[ iconSet ][ i ],
					align: 'inline'
				} )
			] );
		}
	}

	selector = new OO.ui.ButtonSelectWidget( {
		items: [
			new OO.ui.ButtonOptionWidget( {
				label: 'None',
				flags: [],
				data: {
					progressive: false,
					constructive: false,
					destructive: false
				}
			} ),
			new OO.ui.ButtonOptionWidget( {
				label: 'Progressive',
				flags: [ 'progressive' ],
				data: {
					progressive: true,
					constructive: false,
					destructive: false
				}
			} ),
			new OO.ui.ButtonOptionWidget( {
				label: 'Destructive',
				flags: [ 'destructive' ],
				data: {
					progressive: false,
					constructive: false,
					destructive: true
				}
			} )
		]
	} );

	selector
		.on( 'select', function ( selected ) {
			iconsWidgets.forEach( function ( iconWidget ) {
				iconWidget.setFlags( selected.getData() );
			} );
		} )
		.selectItemByData( {
			progressive: false,
			constructive: false,
			destructive: false
		} );

	demo.$element.append(
		new OO.ui.PanelLayout( {
			expanded: false,
			framed: true
		} ).$element
			.addClass( 'oo-ui-demo-container oo-ui-demo-icons' )
			.append(
				selector.$element,
				indicatorsFieldset.$element,
				iconsFieldsets.map( function ( item ) { return item.$element[ 0 ]; } )
			)
	);
};
<|endoftext|>


<commit_before>

var ymdFormat = d3.time.format('%Y-%m-%d'),
    timeFormat = d3.time.format('%H:%M'),
    monthFormat = d3.time.format('%B'),
    dayNumFormat = d3.time.format('%e'),
    dayNameFormat = d3.time.format('%A'),
    yearFormat = d3.time.format('%Y');

var today = ymdFormat.parse('2015-01-09');

var chart = new d3Kit.Skeleton('#month-view', {
    margin: {top: 0, right: 0, bottom: 0, left: 0}
  })
  .autoResize('both')
  .autoResizeToAspectRatio(1);

var redraw = function(date) {

  if (Object.prototype.toString.call( date ) !== '[object Date]') {
    // not a date - chart size (from resize)
    return;
  }

  if (!chart.hasData()) {
    return;
  }

  var x = chart.getInnerWidth()/7;
  var y = chart.getInnerHeight()/7;
  var r = x/2;

  var g = chart.getRootG().selectAll('g')
    .data(function() {
      var start = d3.time.sunday.floor(date);

      while (date.getMonth() == start.getMonth() &&
             start.getDate() != 0) {
        start = d3.time.sunday.floor(new Date(start.getTime() - (24*60*60*1000)));
      }

      var end = d3.time.sunday.ceil(new Date(date.getFullYear(), date.getMonth()+1, 0));

      var days = d3.time.days(start, end);

      while (days.length < 42) {
        end = d3.time.sunday.ceil(new Date(end.getTime() + (24*60*60*1000)));
        days = d3.time.days(start, end);
      }

      return [days.slice(0, 7),
          days.slice(7, 14),
          days.slice(14, 21),
          days.slice(21, 28),
          days.slice(28, 35),
          days.slice(35, 42)];
    });

  g.exit().remove();

  g.enter()
    .append('g');

  g.attr('transform', function(d,i) {
    return 'translate('+r+', ' + i*y + ')';
  });

  var c = g.selectAll('circle.cal')
    .data(function(d) { return d; });

  c.exit().remove();

  c.enter()
      .append('circle')
      .classed('cal', true);

  c.classed('current', function(d) {
    if (ymdFormat(date) == ymdFormat(d)) {
      return true;
    }
    return false;
  })
  .classed('in-month', function(d) {
    if (monthFormat(date) == monthFormat(d)) {
      return true;
    }
    return false;
  })
  .attr('cx', function(d,i) { return i*x; })
  .attr('cy', r)
  .attr('r', r)
  .on('mouseover', function(d) {
    console.log(d);
    d3.select('#circle-data').text(JSON.stringify(d));
  });

  var txt = g.selectAll('text.cal').data(function(d) { return d; });

  txt.exit().remove();

  txt.enter()
    .append('text')
    .classed('cal', true);

  txt.classed('current', function(d) {
    if (ymdFormat(date) == ymdFormat(d)) {
      return true;
    }
    return false;
  })
  .classed('in-month', function(d) {
    if (monthFormat(date) == monthFormat(d)) {
      return true;
    }
    return false;
  })
  .attr('x', function(d,i) { return i*x; })
  .attr('y', r+(r/4))
  .attr('font-size', r)
  .attr('text-anchor', 'middle')
  .text(function(d) {
    return dayNumFormat(d);
  });
}

chart
  .on('resize', redraw)
  .on('data', redraw);

var count = 1;
setInterval(function() {

  var date = new Date(today.getTime()+((count+=50)*6*60*1000));

  d3.select('#date').text(dayNumFormat(date) +' ' +monthFormat(date))
  d3.select('#year').text(yearFormat(date))
  d3.select('#day').text(dayNameFormat(date));
  d3.select('#time').text(timeFormat(date));

  chart.data(date);

  d3.select('#footer').html(' Last refreshed at ' + d3.time.format.iso(new Date()));

}, 100);

<commit_msg>resize to width of container<commit_after>

var ymdFormat = d3.time.format('%Y-%m-%d'),
    timeFormat = d3.time.format('%H:%M'),
    monthFormat = d3.time.format('%B'),
    dayNumFormat = d3.time.format('%e'),
    dayNameFormat = d3.time.format('%A'),
    yearFormat = d3.time.format('%Y');

var today = ymdFormat.parse('2015-01-09');

var chart = new d3Kit.Skeleton('#month-view', {
    margin: {top: 0, right: 0, bottom: 0, left: 0}
  })
  .autoResize('width')
  .autoResizeToAspectRatio(1);

var redraw = function(date) {

  if (Object.prototype.toString.call( date ) !== '[object Date]') {
    // not a date - chart size (from resize)
    return;
  }

  if (!chart.hasData()) {
    return;
  }

  var x = chart.getInnerWidth()/7;
  var y = chart.getInnerHeight()/7;
  var r = x/2;

  var g = chart.getRootG().selectAll('g')
    .data(function() {
      var start = d3.time.sunday.floor(date);

      while (date.getMonth() == start.getMonth() &&
             start.getDate() != 0) {
        start = d3.time.sunday.floor(new Date(start.getTime() - (24*60*60*1000)));
      }

      var end = d3.time.sunday.ceil(new Date(date.getFullYear(), date.getMonth()+1, 0));

      var days = d3.time.days(start, end);

      while (days.length < 42) {
        end = d3.time.sunday.ceil(new Date(end.getTime() + (24*60*60*1000)));
        days = d3.time.days(start, end);
      }

      return [days.slice(0, 7),
          days.slice(7, 14),
          days.slice(14, 21),
          days.slice(21, 28),
          days.slice(28, 35),
          days.slice(35, 42)];
    });

  g.exit().remove();

  g.enter()
    .append('g');

  g.attr('transform', function(d,i) {
    return 'translate('+r+', ' + i*y + ')';
  });

  var c = g.selectAll('circle.cal')
    .data(function(d) { return d; });

  c.exit().remove();

  c.enter()
      .append('circle')
      .classed('cal', true);

  c.classed('current', function(d) {
    if (ymdFormat(date) == ymdFormat(d)) {
      return true;
    }
    return false;
  })
  .classed('in-month', function(d) {
    if (monthFormat(date) == monthFormat(d)) {
      return true;
    }
    return false;
  })
  .attr('cx', function(d,i) { return i*x; })
  .attr('cy', r)
  .attr('r', r)
  .on('mouseover', function(d) {
    console.log(d);
    d3.select('#circle-data').text(JSON.stringify(d));
  });

  var txt = g.selectAll('text.cal').data(function(d) { return d; });

  txt.exit().remove();

  txt.enter()
    .append('text')
    .classed('cal', true);

  txt.classed('current', function(d) {
    if (ymdFormat(date) == ymdFormat(d)) {
      return true;
    }
    return false;
  })
  .classed('in-month', function(d) {
    if (monthFormat(date) == monthFormat(d)) {
      return true;
    }
    return false;
  })
  .attr('x', function(d,i) { return i*x; })
  .attr('y', r+(r/4))
  .attr('font-size', r)
  .attr('text-anchor', 'middle')
  .text(function(d) {
    return dayNumFormat(d);
  });
}

chart
  .on('resize', redraw)
  .on('data', redraw);

var count = 1;
setInterval(function() {

  var date = new Date(today.getTime()+((count+=50)*6*60*1000));

  d3.select('#date').text(dayNumFormat(date) +' ' +monthFormat(date))
  d3.select('#year').text(yearFormat(date))
  d3.select('#day').text(dayNameFormat(date));
  d3.select('#time').text(timeFormat(date));

  chart.data(date);

  d3.select('#footer').html(' Last refreshed at ' + d3.time.format.iso(new Date()));

}, 100);

<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var config_reader = require('yaml-config');
// Read in the configuration files that we have
//var config_db = config_reader.readConfig('../config/database.yml');

// Set the globals that are required
mongoose = require('mongoose');
var resourceSchema = mongoose.Schema({name: String, counter: Number});
var resourceModel = mongoose.model('resource', resourceSchema);

// Connect Mongoose to the db already
mongoose.connect(process.env.MONGOLAB_URI);

function getResourceList(req, res) {
	resourceModel.find().lean().exec(function (err, resourcelist) {
		//console.log(JSON.stringify(resourcelist));
		res.render('resources', {title: 'Resources', resources: JSON.parse(JSON.stringify(resourcelist))});
	});
}

/* GET resources listing. */
router.get('/', function(req, res, next) {
	//db.once('open', function (callback) {
		getResourceList(req, res)
	//});
});

router.get('/new', function(req, res, next) {
  res.render('newresource', {title: 'New Resource'})
});

router.post('/', function(req,res){
	//db.once('open', function (callback) {
		var newresource = new resourceModel({ name: req.body.name, counter: req.body.counter });
		newresource.save(function (err) {
			if (err) {
		  		res.writeHead(500, {'content-type': 'text/plain'});
		    	res.end('An error occurred');
			};
		});
		getResourceList(req, res)
	//});
});

module.exports = router;
<commit_msg>put render of resources after commit in callback of save<commit_after>var express = require('express');
var router = express.Router();
var config_reader = require('yaml-config');
// Read in the configuration files that we have
//var config_db = config_reader.readConfig('../config/database.yml');

// Set the globals that are required
mongoose = require('mongoose');
var resourceSchema = mongoose.Schema({name: String, counter: Number});
var resourceModel = mongoose.model('resource', resourceSchema);

// Connect Mongoose to the db already
mongoose.connect(process.env.MONGOLAB_URI);

function getResourceList(req, res) {
	resourceModel.find().lean().exec(function (err, resourcelist) {
		//console.log(JSON.stringify(resourcelist));
		res.render('resources', {title: 'Resources', resources: JSON.parse(JSON.stringify(resourcelist))});
	});
}

/* GET resources listing. */
router.get('/', function(req, res, next) {
	//db.once('open', function (callback) {
		getResourceList(req, res)
	//});
});

router.get('/new', function(req, res, next) {
  res.render('newresource', {title: 'New Resource'})
});

router.post('/', function(req,res){
	//db.once('open', function (callback) {
		var newresource = new resourceModel({ name: req.body.name, counter: req.body.counter });
		newresource.save(function (err) {
			if (err) {
		  		res.writeHead(500, {'content-type': 'text/plain'});
		    	res.end('An error occurred');
			};
			getResourceList(req, res)
		});

	//});
});

module.exports = router;
<|endoftext|>