<commit_before>var WIDTH = window.innerWidth,HEIGHT = window.innerHeight, delta;
var lastFrame,delta,time,fps = 0,tempfps,lastFPS = getTime();
var btnPressSnd = new Audio("http://ragulbalaji.github.io/curl/audio/BtnPress.mp3");
var ballHitWallSnd = new Audio("http://ragulbalaji.github.io/curl/audio/BallHitWall.mp3");
var ballHitBatSnd = new Audio("http://ragulbalaji.github.io/curl/audio/BallHitBat.mp3");
var PointScoredSnd = new Audio("http://ragulbalaji.github.io/curl/audio/PointScored.mp3");
var leftBatElement = document.getElementById("leftBat"),rightBatElement = document.getElementById("rightBat"),BallElement = document.getElementById("Ball");
var mainMenu = document.getElementById("mainMenu"), gameState = document.getElementById("gameState");
var leftScoreEle = document.getElementById("leftScore"), rightScoreEle = document.getElementById("rightScore");
var gameLoopVar, gameRunning;
var Ball , leftBat, rightBat;
var leftScore, rightScore;
var ballBounceEfficiency = 0.999, batMoveVelocity = 0.4, batBallFrictionCoeff = 0.5;
var CurrentState = 0, State = {MainMenu:1, Game:2};
var XMin = 0, XMax = WIDTH, YMin = 0.17*HEIGHT, YMax = 0.95*HEIGHT;
var keys = new Array(255),oldKeys = new Array(255);

function gotoState(id){
   if(id == State.MainMenu){
      mainMenu.style.display="block";
      gameState.style.display="none";
   }else if(id == State.Game){
      mainMenu.style.display="none";
      gameState.style.display="block";
   }
}

function setObjToEle(obj, ele){
   ele.style.left = obj.x;
   ele.style.top = obj.y;
}

function startGame(){
   gotoState(State.Game);
   WIDTH = window.innerWidth;
   HEIGHT = window.innerHeight;
   gameRunning = true;
   leftScore = 0;
   rightScore = 0;
   getDelta();
   Ball = new gameObj(WIDTH/2-HEIGHT/100,11*HEIGHT/20,0,0);
   leftBat = new gameObj((HEIGHT*5)/100,HEIGHT*23/50,0,0);
   rightBat = new gameObj(WIDTH - 2*((HEIGHT*5)/100),HEIGHT*23/50,0,0);
   //init
   if(randInt(1,2)==1){
      resetBall(1);
   }else{
      resetBall(-1);
   }
   setObjToEle(Ball, BallElement);
   setObjToEle(leftBat, leftBatElement);
   setObjToEle(rightBat, rightBatElement);
   //
   gameLoopVar = setInterval(gameLoop,0);
}
function input(){
   leftBat.vy = 0;
   if(keys[87] || keys[38]){
      leftBat.vy = -batMoveVelocity;
   }else if(keys[83] || keys[40]){
      leftBat.vy = batMoveVelocity;
   }else if(keys[27]){ //Esc
      gameLoopVar = clearInterval(gameLoopVar);
   }else if(keys[80] && !oldKeys[80]){ //Pause-P
      if(gameRunning){
         gameRunning = false;
         gameLoopVar = clearInterval(gameLoopVar);
      }else{
         gameRunning = true;
         getDelta();
         gameLoopVar = setInterval(gameLoop,0);
      }
   }
}
function touch(x, y, action) {
   leftBat.vy = 0;
   if(x <= WIDTH/2 && action){
      if(y < leftBat.y+(HEIGHT*9/100)){
         leftBat.vy = -batMoveVelocity;
      }else if(y > leftBat.y+(HEIGHT*9/100)){
         leftBat.vy = batMoveVelocity;
      }
   }
}
function gameLoop(){
   getDelta();
   //updates
   if(Ball.x <= XMin){ // LEFTHIT
      PointScoredSnd.play();
      resetBall(1);
      rightScore++;
   }else if(Ball.x >= XMax){ //RIGHTHIT
      PointScoredSnd.play();
      resetBall(-1);
      leftScore++;
   }
   if(Ball.y >= YMax ||  Ball.y <= YMin){
      ballHitWallSnd.play();
      Ball.vy = -ballBounceEfficiency *Ball.vy;
      if(Ball.y >= YMax){
         Ball.y = YMax;
      }else{
         Ball.y = YMin;
      }
   }
   if(Ball.y > rightBat.y+(HEIGHT*9/100)){
      rightBat.vy = batMoveVelocity;
   }else if(Ball.y < rightBat.y+(HEIGHT*9/100)){
      rightBat.vy = -batMoveVelocity;
   }else{
      rightBat.vy = 0;
   }
   if(Ball.x+(HEIGHT*2/100) >= rightBat.x && Ball.x+(HEIGHT*2/100) <= rightBat.x+(HEIGHT*5/100) && Ball.y+(HEIGHT*1/100) >= rightBat.y && Ball.y+(HEIGHT*1/100) <= rightBat.y+(HEIGHT*20/100)){
      ballHitBatSnd.play();
      Ball.x=rightBat.x-2*HEIGHT/100;
      Ball.vx=-ballBounceEfficiency *Ball.vx;
      Ball.vx += batBallFrictionCoeff*0.1*rightBat.vy;
      Ball.vy += batBallFrictionCoeff*rightBat.vy;
   }else if(Ball.x <= leftBat.x+(HEIGHT*5/100) && Ball.x >= leftBat.x && Ball.y+(HEIGHT*1/100) >= leftBat.y && Ball.y+(HEIGHT*1/100) <= leftBat.y+(HEIGHT*20/100)){
      ballHitBatSnd.play();
      Ball.x=leftBat.x+7*HEIGHT/100;
      Ball.vx=-ballBounceEfficiency *Ball.vx;
      Ball.vx += batBallFrictionCoeff*0.1*leftBat.vy;
      Ball.vy += batBallFrictionCoeff*leftBat.vy;
   }
   if(rightBat.y >= YMax-(HEIGHT*19/100)){
      rightBat.y = YMax-(HEIGHT*19/100);
   }else if(rightBat.y <= YMin+(HEIGHT/100)){
      rightBat.y = YMin+(HEIGHT/100);
   }
   if(leftBat.y >= YMax-(HEIGHT*19/100)){
      leftBat.y = YMax-(HEIGHT*19/100);
   }else if(leftBat.y <= YMin+(HEIGHT/100)){
      leftBat.y = YMin+(HEIGHT/100);
   }
   leftBat.x += leftBat.vx*delta;
   leftBat.y += leftBat.vy*delta;
   rightBat.x += rightBat.vx*delta;
   rightBat.y += rightBat.vy*delta;
   Ball.x += Ball.vx*delta;
   Ball.y += Ball.vy*delta;
   //
   gameRender();
   updateFPS();
}
function gameRender(){
   setObjToEle(Ball, BallElement);
   setObjToEle(leftBat, leftBatElement);
   setObjToEle(rightBat, rightBatElement);
   leftScoreEle.innerHTML = leftScore;
   rightScoreEle.innerHTML = rightScore;
}
function gameObj(px,py, pvx, pvy){
   this.x = px;
   this.y = py;
   this.vx = pvx;
   this.vy = pvy;
}
function resetBall(direction){
   Ball.x = WIDTH/2-HEIGHT/100;
   Ball.y = 11*HEIGHT/20;
   Ball.vx = (randInt(3,8)/(10*direction));
   Ball.vy = Math.random()-0.5;
}
function getTime() {return Date.now();}
function updateFPS() {
   if (getTime() - lastFPS > 1000) {
      console.log(fps);// FPS OUTPUT
      fps = tempfps;
      tempfps = 0;
      lastFPS += 1000;
   }
   tempfps++;
}
function getDelta() {
   time = getTime();
   delta = (time - lastFrame);
   lastFrame = time;
}
function randInt(min, max) {
   return Math.floor(Math.random() * (max - min + 1)) + min;
}

window.onkeydown = function (e) {
   keys[e.keyCode] = true;
   oldKeys[e.keyCode] = false;
   input();
};
window.onkeyup = function (e) {
   keys[e.keyCode] = false;
   oldKeys[e.keyCode] = true;
   input();
};
window.addEventListener('touchstart', function(e) {
 touch(e.changedTouches[0].pageX, e.changedTouches[0].pageY, true);
}, false);
window.addEventListener('touchmove', function(e) {
   e.preventDefault();
   touch(e.targetTouches[0].pageX, e.targetTouches[0].pageY, true);
}, false);
//Math.seedrandom(2000);
gotoState(State.MainMenu);
//startGame();
<commit_msg>+       Ball.vx = -ballBounceEfficiency *Ball.vx;<commit_after>var WIDTH = window.innerWidth,HEIGHT = window.innerHeight, delta;
var lastFrame,delta,time,fps = 0,tempfps,lastFPS = getTime();
var btnPressSnd = new Audio("http://ragulbalaji.github.io/curl/audio/BtnPress.mp3");
var ballHitWallSnd = new Audio("http://ragulbalaji.github.io/curl/audio/BallHitWall.mp3");
var ballHitBatSnd = new Audio("http://ragulbalaji.github.io/curl/audio/BallHitBat.mp3");
var PointScoredSnd = new Audio("http://ragulbalaji.github.io/curl/audio/PointScored.mp3");
var leftBatElement = document.getElementById("leftBat"),rightBatElement = document.getElementById("rightBat"),BallElement = document.getElementById("Ball");
var mainMenu = document.getElementById("mainMenu"), gameState = document.getElementById("gameState");
var leftScoreEle = document.getElementById("leftScore"), rightScoreEle = document.getElementById("rightScore");
var gameLoopVar, gameRunning;
var Ball , leftBat, rightBat;
var leftScore, rightScore;
var ballBounceEfficiency = 0.999, batMoveVelocity = 0.4, batBallFrictionCoeff = 0.5;
var CurrentState = 0, State = {MainMenu:1, Game:2};
var XMin = 0, XMax = WIDTH, YMin = 0.17*HEIGHT, YMax = 0.95*HEIGHT;
var keys = new Array(255),oldKeys = new Array(255);

function gotoState(id){
   if(id == State.MainMenu){
      mainMenu.style.display="block";
      gameState.style.display="none";
   }else if(id == State.Game){
      mainMenu.style.display="none";
      gameState.style.display="block";
   }
}

function setObjToEle(obj, ele){
   ele.style.left = obj.x;
   ele.style.top = obj.y;
}

function startGame(){
   gotoState(State.Game);
   WIDTH = window.innerWidth;
   HEIGHT = window.innerHeight;
   gameRunning = true;
   leftScore = 0;
   rightScore = 0;
   getDelta();
   Ball = new gameObj(WIDTH/2-HEIGHT/100,11*HEIGHT/20,0,0);
   leftBat = new gameObj((HEIGHT*5)/100,HEIGHT*23/50,0,0);
   rightBat = new gameObj(WIDTH - 2*((HEIGHT*5)/100),HEIGHT*23/50,0,0);
   //init
   if(randInt(1,2)==1){
      resetBall(1);
   }else{
      resetBall(-1);
   }
   setObjToEle(Ball, BallElement);
   setObjToEle(leftBat, leftBatElement);
   setObjToEle(rightBat, rightBatElement);
   //
   gameLoopVar = setInterval(gameLoop,0);
}
function input(){
   leftBat.vy = 0;
   if(keys[87] || keys[38]){
      leftBat.vy = -batMoveVelocity;
   }else if(keys[83] || keys[40]){
      leftBat.vy = batMoveVelocity;
   }else if(keys[27]){ //Esc
      gameLoopVar = clearInterval(gameLoopVar);
   }else if(keys[80] && !oldKeys[80]){ //Pause-P
      if(gameRunning){
         gameRunning = false;
         gameLoopVar = clearInterval(gameLoopVar);
      }else{
         gameRunning = true;
         getDelta();
         gameLoopVar = setInterval(gameLoop,0);
      }
   }
}
function touch(x, y, action) {
   leftBat.vy = 0;
   if(x <= WIDTH/2 && action){
      if(y < leftBat.y+(HEIGHT*9/100)){
         leftBat.vy = -batMoveVelocity;
      }else if(y > leftBat.y+(HEIGHT*9/100)){
         leftBat.vy = batMoveVelocity;
      }
   }
}
function gameLoop(){
   getDelta();
   //updates
   if(Ball.x <= XMin){ // LEFTHIT
      PointScoredSnd.play();
      resetBall(1);
      rightScore++;
   }else if(Ball.x >= XMax){ //RIGHTHIT
      PointScoredSnd.play();
      resetBall(-1);
      leftScore++;
   }
   if(Ball.y >= YMax ||  Ball.y <= YMin){
      ballHitWallSnd.play();
      Ball.vy = -ballBounceEfficiency *Ball.vy;
      Ball.vx = -ballBounceEfficiency *Ball.vx;
      if(Ball.y >= YMax){
         Ball.y = YMax;
      }else{
         Ball.y = YMin;
      }
   }
   if(Ball.y > rightBat.y+(HEIGHT*9/100)){
      rightBat.vy = batMoveVelocity;
   }else if(Ball.y < rightBat.y+(HEIGHT*9/100)){
      rightBat.vy = -batMoveVelocity;
   }else{
      rightBat.vy = 0;
   }
   if(Ball.x+(HEIGHT*2/100) >= rightBat.x && Ball.x+(HEIGHT*2/100) <= rightBat.x+(HEIGHT*5/100) && Ball.y+(HEIGHT*1/100) >= rightBat.y && Ball.y+(HEIGHT*1/100) <= rightBat.y+(HEIGHT*20/100)){
      ballHitBatSnd.play();
      Ball.x=rightBat.x-2*HEIGHT/100;
      Ball.vx=-ballBounceEfficiency *Ball.vx;
      Ball.vx += batBallFrictionCoeff*0.1*rightBat.vy;
      Ball.vy += batBallFrictionCoeff*rightBat.vy;
   }else if(Ball.x <= leftBat.x+(HEIGHT*5/100) && Ball.x >= leftBat.x && Ball.y+(HEIGHT*1/100) >= leftBat.y && Ball.y+(HEIGHT*1/100) <= leftBat.y+(HEIGHT*20/100)){
      ballHitBatSnd.play();
      Ball.x=leftBat.x+7*HEIGHT/100;
      Ball.vx=-ballBounceEfficiency *Ball.vx;
      Ball.vx += batBallFrictionCoeff*0.1*leftBat.vy;
      Ball.vy += batBallFrictionCoeff*leftBat.vy;
   }
   if(rightBat.y >= YMax-(HEIGHT*19/100)){
      rightBat.y = YMax-(HEIGHT*19/100);
   }else if(rightBat.y <= YMin+(HEIGHT/100)){
      rightBat.y = YMin+(HEIGHT/100);
   }
   if(leftBat.y >= YMax-(HEIGHT*19/100)){
      leftBat.y = YMax-(HEIGHT*19/100);
   }else if(leftBat.y <= YMin+(HEIGHT/100)){
      leftBat.y = YMin+(HEIGHT/100);
   }
   leftBat.x += leftBat.vx*delta;
   leftBat.y += leftBat.vy*delta;
   rightBat.x += rightBat.vx*delta;
   rightBat.y += rightBat.vy*delta;
   Ball.x += Ball.vx*delta;
   Ball.y += Ball.vy*delta;
   //
   gameRender();
   updateFPS();
}
function gameRender(){
   setObjToEle(Ball, BallElement);
   setObjToEle(leftBat, leftBatElement);
   setObjToEle(rightBat, rightBatElement);
   leftScoreEle.innerHTML = leftScore;
   rightScoreEle.innerHTML = rightScore;
}
function gameObj(px,py, pvx, pvy){
   this.x = px;
   this.y = py;
   this.vx = pvx;
   this.vy = pvy;
}
function resetBall(direction){
   Ball.x = WIDTH/2-HEIGHT/100;
   Ball.y = 11*HEIGHT/20;
   Ball.vx = (randInt(3,8)/(10*direction));
   Ball.vy = Math.random()-0.5;
}
function getTime() {return Date.now();}
function updateFPS() {
   if (getTime() - lastFPS > 1000) {
      console.log(fps);// FPS OUTPUT
      fps = tempfps;
      tempfps = 0;
      lastFPS += 1000;
   }
   tempfps++;
}
function getDelta() {
   time = getTime();
   delta = (time - lastFrame);
   lastFrame = time;
}
function randInt(min, max) {
   return Math.floor(Math.random() * (max - min + 1)) + min;
}

window.onkeydown = function (e) {
   keys[e.keyCode] = true;
   oldKeys[e.keyCode] = false;
   input();
};
window.onkeyup = function (e) {
   keys[e.keyCode] = false;
   oldKeys[e.keyCode] = true;
   input();
};
window.addEventListener('touchstart', function(e) {
 touch(e.changedTouches[0].pageX, e.changedTouches[0].pageY, true);
}, false);
window.addEventListener('touchmove', function(e) {
   e.preventDefault();
   touch(e.targetTouches[0].pageX, e.targetTouches[0].pageY, true);
}, false);
//Math.seedrandom(2000);
gotoState(State.MainMenu);
//startGame();
<|endoftext|>


<commit_before>/*
	This pageview module will be responsible for
	showing Live Match data.

	Process method will find the corresponding group
	data and fetch from it.
*/
module.exports = {
	type: 'pageview',

	initialize: function(sails){

	},

	process: function (match, next) {
		return next(null, match);

		// Match data inside match key, can be either:
		if(_.isObject(match.options.match)){
			// OBJECT: We are dealing with a custom Game.
			match.data = match.options.match;
			next(null, match);
		}else{
			// INT/STRING: We are dealing with a match on the database
			sails.controllers.match._findAssociated(match.options.match || null, afterAssociate);
			// console.log('&&', match);
			// sails.controllers.match._findAssociated(20, afterAssociate);

			function afterAssociate(err, data){
				match.data = data;
				next(null, match);
			}
		}

	},

	beforeValidation: function(page){
		_.defaults(page.options, {
			match: null,
		});

		return page;
	}
}<commit_msg>REALLY hot fix.<commit_after>/*
	This pageview module will be responsible for
	showing Live Match data.

	Process method will find the corresponding group
	data and fetch from it.
*/
module.exports = {
	type: 'pageview',

	initialize: function(sails){

	},

	process: function (match, next) {

		// Match data inside match key, can be either:
		if(_.isObject(match.options.match)){
			// OBJECT: We are dealing with a custom Game.
			match.data = match.options.match;
			next(null, match);
		}else{
			// INT/STRING: We are dealing with a match on the database
			sails.controllers.match._findAssociated(match.options.match || null, afterAssociate);
			// console.log('&&', match);
			// sails.controllers.match._findAssociated(20, afterAssociate);

			function afterAssociate(err, data){
				match.data = data;
				next(null, match);
			}
		}

	},

	beforeValidation: function(page){
		_.defaults(page.options, {
			match: null,
		});

		return page;
	}
}<|endoftext|>


<commit_before>class Board {
    constructor(width, height, gameWidth, gameHeight, inputs, outputs, pieces){
        this.layout = new Array(gameWidth);
        for(var i = 0; i < gameWidth; i++){
            this.layout[i] = new Array(gameHeight);
        }
        this.width = width;
        this.height = height;
        this.inputs = inputs;
        this.outputs = outputs;
        this.pieces = pieces;
    }

    set width(width){
        this._width = width;
        this.updateBoardDim();
    }

    get width(){
        return this._width;
    }

    set height(height){
        this._height = height;
        this.updateBoardDim();
    }

    get height(){
        return this._height;
    }

    updateBoardDim(){
        // Find a scale unit on the board
        // This is the number of pixels a square takes up
        var unitWidth = (this.width - 20) / this.gameWidth;
        var unitHeight = (this.height - 30) / (this.gameHeight + 1);
        if (unitWidth < unitHeight) {
            this._unit = unitWidth;
        } else {
            this._unit = unitHeight;
        }
    }

    get unit(){
        return this._unit;
    }

    get boardWidth(){
        return this.unit * this.gameWidth;
    }

    get boardHeight(){
        return this.unit * this.gameHeight;
    }

    get boardX(){
        return (this.width - this.boardWidth) / 2;
    }

    get boardY(){
        return ((this.height - this.boardHeight - this.unit) / 2) - 5;
    }

    get gameWidth(){
        return this.layout.length;
    }

    get gameHeight(){
        return this.layout[0].length;
    }

    draw(canvas){
        canvas.fillStyle = "#000000";
        canvas.fillRect(this.boardX ,this.boardY, this.boardWidth, this.boardHeight);
        var color = false;
        for(var x = 0; x < this.gameWidth; x++){
            if (this.gameWidth % 2 != 0) color = !color;
            for(var y = 0; y < this.gameHeight; y++){
                color = !color;
                canvas.fillStyle = color ? "#555555" : "#333333";
                canvas.fillRect(this.unit * x + this.boardX, this.unit * y + this.boardY, this.unit, this.unit);
                var piece = pieceAsset(this.layout[x][y], false);
                if (piece != null) {
                    canvas.drawImage(piece, this.unit * x + this.boardX, this.unit * y + this.boardY, this.unit, this.unit);
                }
            }
        }
        for(var x = 0; x < this.gameWidth; x++){
            color = !color;
            canvas.fillStyle = color ? "#555555" : "#333333";
            canvas.fillRect(this.unit * x + this.boardX, this.boardHeight + this.boardY + 10, this.unit, this.unit);
            if(x < this.pieces.length){
                canvas.drawImage(pieceAsset(this.pieces[x], false), this.unit * x + this.boardX, this.boardHeight + this.boardY + 10, this.unit, this.unit);
            }
        }
    }

    getPiece(x, y) {
        var tmp = (y - this.boardY - this.boardHeight - 10);
        if (tmp > 0 && tmp < this.unit) {
            tmp = Math.trunc((x - this.boardX) / this.unit);
            if (0 <= tmp && tmp < this.pieces.length){
                return this.pieces.splice(tmp, 1);
            }
        } else {
            var cx = Math.trunc((x - this.boardX) / this.unit);
            var cy = Math.trunc((y - this.boardY) / this.unit);
            if (0 <= cy && 0 <= cx && cy < this.gameHeight && cx < this.gameWidth && this.layout[cx][cy] != 0) {
                tmp = this.layout[cx][cy];
                this.layout[cx][cy] = null;
                return tmp;
            }
        }
        return null;
    }

    setPiece(x, y, p) {
        if (p != null) {
            var cx = Math.trunc((x - this.boardX) / this.unit);
            var cy = Math.trunc((y - this.boardY) / this.unit);
            if (0 <= cy && 0 <= cx && cy < this.gameHeight && cx < this.gameWidth && this.layout[cx][cy] == null) {
                this.layout[cx][cy] = p;
            } else {
                this.pieces.push(p);
            }
        }
    }
}

var board;
var canvas;
var mouseDown;
var mouseX, mouseY;
var pieceAssets;
var wireAssets;
var currentPiece;

// This will return the image that is associated with a piece number then the given state if on or off
function pieceAsset(num, bool) { return pieceAssets[(2 * num) - (bool ? 2 : 1)]; }

document.addEventListener("DOMContentLoaded", function(event){
    canvas = document.getElementsByTagName("canvas")[0].getContext("2d");
    isMouseDown = false;
    var gameBoard = document.getElementById("game_board");
    var inputs = toLogicArray(gameBoard, "input");
    var outputs = toLogicArray(gameBoard, "output");
    var piecesHTML = Array.from(gameBoard.getElementsByClassName("pieces")[0].getElementsByTagName("div"));
    var pieces = new Array(piecesHTML.length);
    piecesHTML.forEach(
        function(element, index){
            pieces[index] = parseInt(element.innerHTML);
        }
    );

    board = new Board(
        window.innerWidth,
        window.innerHeight,
        parseInt(gameBoard.getElementsByClassName("width")[0].innerHTML),
        parseInt(gameBoard.getElementsByClassName("height")[0].innerHTML),
        inputs,
        outputs,
        pieces
    );
    console.log(board);

    // Read in all the images
    var images = [
        "/images/and-on.svg",
        "/images/and-off.svg",
        "/images/or-on.svg",
        "/images/or-off.svg",
        "/images/not-on.svg",
        "/images/not-off.svg"
    ];
    pieceAssets = new Array(images.length);
    images.forEach(
        function(element, index){
            pieceAssets[index] = new Image();
            pieceAssets[index].src = element;
        }
    );

    // Read in all the images
    images = [
        "/images/0-on.svg",
        "/images/0-off.svg",
        "/images/1-on.svg",
        "/images/1-off.svg",
        "/images/2c-on.svg",
        "/images/2c-off.svg",
        "/images/2s-on.svg",
        "/images/2s-off.svg",
        "/images/3-on.svg",
        "/images/3-off.svg",
        "/images/4-on.svg",
        "/images/4-off.svg"
    ];
    wireAssets = new Array(images.length);
    images.forEach(
        function(element, index){
            wireAssets[index] = new Image();
            wireAssets[index].src = element;
        }
    );

    repaint();
    // This gives it 100ms to actualy load the assets
    setInterval(repaint, 100);
});

function toLogicArray(element, className){
    var inputsHTML = Array.from(element.getElementsByClassName(className));
    var inputs = new Array(inputsHTML.lenght);
    inputsHTML.forEach(
        function(input, inputIndex){
            var elementsHTML = Array.from(input.getElementsByTagName("div"));
            inputs[inputIndex] = new Array(elementsHTML.lenght);
            elementsHTML.forEach(
                function(element, elementIndex){
                    inputs[inputIndex][elementIndex] = parseInt(element.innerHTML);
                }
            );
        }
    );
    return inputs;
}

window.addEventListener("resize", function(event){
    board.width = window.innerWidth;
    board.height = window.innerHeight;
    repaint();
});

document.addEventListener("mousedown", function(event){
    mouseX = event.clientX;
    mouseY = event.clientY;
    mouseDown = true;
    currentPiece = board.getPiece(event.clientX, event.clientY);
    repaint();
});

document.addEventListener("mouseup", function(event){
    mouseDown = false;
    board.setPiece(event.clientX, event.clientY, currentPiece);
    repaint();
});

document.addEventListener("mousemove", function(event){
    if(mouseDown){
        mouseX = event.clientX;
        mouseY = event.clientY;
        repaint();
    }
});

function repaint(){
    clear(canvas);
    board.draw(canvas);
    if (mouseDown && currentPiece != null) {
        canvas.fillStyle = "#ffffff";
        canvas.drawImage(pieceAsset(currentPiece, false), mouseX - (board.unit * 0.6), mouseY - (board.unit * 0.6), board.unit * 1.2, board.unit * 1.2);
    }
}

function clear(canvas){
    if (canvas != null){
        canvas.clearRect(0, 0, window.innerWidth, window.innerHeight);
    }
}
<commit_msg>Getting ready for wire drawing<commit_after>class Board {
    constructor(width, height, gameWidth, gameHeight, inputs, outputs, pieces){
        this.layout = new Array(gameWidth);
        for(var i = 0; i < gameWidth; i++){
            this.layout[i] = new Array(gameHeight);
        }
        this.width = width;
        this.height = height;
        this.inputs = inputs;
        this.outputs = outputs;
        this.pieces = pieces;
    }

    set width(width){
        this._width = width;
        this.updateBoardDim();
    }

    get width(){
        return this._width;
    }

    set height(height){
        this._height = height;
        this.updateBoardDim();
    }

    get height(){
        return this._height;
    }

    updateBoardDim(){
        // Find a scale unit on the board
        // This is the number of pixels a square takes up
        var unitWidth = (this.width - 20) / this.gameWidth;
        var unitHeight = (this.height - 30) / (this.gameHeight + 1);
        if (unitWidth < unitHeight) {
            this._unit = unitWidth;
        } else {
            this._unit = unitHeight;
        }
    }

    get unit(){
        return this._unit;
    }

    get boardWidth(){
        return this.unit * this.gameWidth;
    }

    get boardHeight(){
        return this.unit * this.gameHeight;
    }

    get boardX(){
        return (this.width - this.boardWidth) / 2;
    }

    get boardY(){
        return ((this.height - this.boardHeight - this.unit) / 2) - 5;
    }

    get gameWidth(){
        return this.layout.length;
    }

    get gameHeight(){
        return this.layout[0].length;
    }

    draw(canvas){
        canvas.fillStyle = "#000000";
        canvas.fillRect(this.boardX ,this.boardY, this.boardWidth, this.boardHeight);
        var color = false;
        for(var x = 0; x < this.gameWidth; x++){
            if (this.gameWidth % 2 != 0) color = !color;
            for(var y = 0; y < this.gameHeight; y++){
                color = !color;
                canvas.fillStyle = color ? "#555555" : "#333333";
                canvas.fillRect(this.unit * x + this.boardX, this.unit * y + this.boardY, this.unit, this.unit);
                var piece = pieceAsset(this.layout[x][y], false);
                if (piece != null) {
                    canvas.drawImage(piece, this.unit * x + this.boardX, this.unit * y + this.boardY, this.unit, this.unit);
                }
            }
        }
        for(var x = 0; x < this.gameWidth; x++){
            color = !color;
            canvas.fillStyle = color ? "#555555" : "#333333";
            canvas.fillRect(this.unit * x + this.boardX, this.boardHeight + this.boardY + 10, this.unit, this.unit);
            if(x < this.pieces.length){
                canvas.drawImage(pieceAsset(this.pieces[x], false), this.unit * x + this.boardX, this.boardHeight + this.boardY + 10, this.unit, this.unit);
            }
        }
    }

    getPiece(x, y) {
        var tmp = (y - this.boardY - this.boardHeight - 10);
        if (tmp > 0 && tmp < this.unit) {
            tmp = Math.trunc((x - this.boardX) / this.unit);
            if (0 <= tmp && tmp < this.pieces.length){
                return this.pieces.splice(tmp, 1);
            }
        } else {
            var cx = Math.trunc((x - this.boardX) / this.unit);
            var cy = Math.trunc((y - this.boardY) / this.unit);
            if (0 <= cy && 0 <= cx && cy < this.gameHeight && cx < this.gameWidth && this.layout[cx][cy] != 0) {
                tmp = this.layout[cx][cy];
                this.layout[cx][cy] = undefined;
                return tmp;
            }
        }
        return null;
    }

    setPiece(x, y, p) {
        if (p != null) {
            var cx = Math.trunc((x - this.boardX) / this.unit);
            var cy = Math.trunc((y - this.boardY) / this.unit);
            if (0 <= cy && 0 <= cx && cy < this.gameHeight && cx < this.gameWidth && [0, null, undefined].includes(this.layout[cx][cy])) {
                this.layout[cx][cy] = p;
            } else {
                this.pieces.push(p);
            }
        }
    }
}

var board;
var canvas;
var mouseDown;
var mouseX, mouseY;
var pieceAssets;
var wireAssets;
var currentPiece;

// This will return the image that is associated with a piece number then the given state if on or off
function pieceAsset(num, bool) {
    if (num > 0) {
        return pieceAssets[(2 * num) - (bool ? 2 : 1)];
    } else if (num == 0) {
        return wireAssets[1];
    }
}

document.addEventListener("DOMContentLoaded", function(event){
    canvas = document.getElementsByTagName("canvas")[0].getContext("2d");
    isMouseDown = false;
    var gameBoard = document.getElementById("game_board");
    var inputs = toLogicArray(gameBoard, "input");
    var outputs = toLogicArray(gameBoard, "output");
    var piecesHTML = Array.from(gameBoard.getElementsByClassName("pieces")[0].getElementsByTagName("div"));
    var pieces = new Array(piecesHTML.length);
    piecesHTML.forEach(
        function(element, index){
            pieces[index] = parseInt(element.innerHTML);
        }
    );

    board = new Board(
        window.innerWidth,
        window.innerHeight,
        parseInt(gameBoard.getElementsByClassName("width")[0].innerHTML),
        parseInt(gameBoard.getElementsByClassName("height")[0].innerHTML),
        inputs,
        outputs,
        pieces
    );
    console.log(board);

    // Read in all the images
    var images = [
        "/images/and-on.svg",
        "/images/and-off.svg",
        "/images/or-on.svg",
        "/images/or-off.svg",
        "/images/not-on.svg",
        "/images/not-off.svg"
    ];
    pieceAssets = new Array(images.length);
    images.forEach(
        function(element, index){
            pieceAssets[index] = new Image();
            pieceAssets[index].src = element;
        }
    );

    // Read in all the images
    images = [
        "/images/0-on.svg",
        "/images/0-off.svg",
        "/images/1-on.svg",
        "/images/1-off.svg",
        "/images/2c-on.svg",
        "/images/2c-off.svg",
        "/images/2s-on.svg",
        "/images/2s-off.svg",
        "/images/3-on.svg",
        "/images/3-off.svg",
        "/images/4-on.svg",
        "/images/4-off.svg"
    ];
    wireAssets = new Array(images.length);
    images.forEach(
        function(element, index){
            wireAssets[index] = new Image();
            wireAssets[index].src = element;
        }
    );

    repaint();
    // This gives it 100ms to actualy load the assets
    setInterval(repaint, 100);
});

function toLogicArray(element, className){
    var inputsHTML = Array.from(element.getElementsByClassName(className));
    var inputs = new Array(inputsHTML.lenght);
    inputsHTML.forEach(
        function(input, inputIndex){
            var elementsHTML = Array.from(input.getElementsByTagName("div"));
            inputs[inputIndex] = new Array(elementsHTML.lenght);
            elementsHTML.forEach(
                function(element, elementIndex){
                    inputs[inputIndex][elementIndex] = parseInt(element.innerHTML);
                }
            );
        }
    );
    return inputs;
}

window.addEventListener("resize", function(event){
    board.width = window.innerWidth;
    board.height = window.innerHeight;
    repaint();
});

document.addEventListener("mousedown", function(event){
    mouseX = event.clientX;
    mouseY = event.clientY;
    mouseDown = true;
    currentPiece = board.getPiece(event.clientX, event.clientY);
    repaint();
});

document.addEventListener("mouseup", function(event){
    mouseDown = false;
    board.setPiece(event.clientX, event.clientY, currentPiece);
    repaint();
});

document.addEventListener("mousemove", function(event){
    if(mouseDown){
        mouseX = event.clientX;
        mouseY = event.clientY;
        repaint();
    }
});

function repaint(){
    clear(canvas);
    board.draw(canvas);
    if (mouseDown && currentPiece != null) {
        canvas.fillStyle = "#ffffff";
        canvas.drawImage(pieceAsset(currentPiece, false), mouseX - (board.unit * 0.6), mouseY - (board.unit * 0.6), board.unit * 1.2, board.unit * 1.2);
    }
}

function clear(canvas){
    if (canvas != null){
        canvas.clearRect(0, 0, window.innerWidth, window.innerHeight);
    }
}
<|endoftext|>


<commit_before>// Create an image element
var canvas = document.getElementById('c');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var ctx    = canvas.getContext('2d');
var img    = document.createElement('IMG');
var width  = canvas.width;
var height = canvas.height;
var radius = 10;
var playerX;
var playerY;
var playerDirection = (90*Math.PI)/180;
playerX = width/2-radius;
playerY = height/2-radius;

function drawPlayer(ctx,x,y,direction){
  ctx.beginPath();
  ctx.fillStyle = "#ffffff";
  ctx.arc(x,y, radius+2, 0, Math.PI*2, false);
  ctx.fill();
  ctx.closePath();

  ctx.beginPath();
  ctx.fillStyle = "#5e9fd2";
  ctx.arc(x,y, radius, 0, Math.PI*2, false);
  ctx.fill();
  ctx.closePath();

  drawPeripheryVision(ctx,x,y,direction);
  drawCentralVision(ctx,x,y,direction);
}

function solveASA(angle1,side,angle2){
  // Solve the triangle to get S
  var a,b,c; // sides
  var A,B,C; // angles
  c = side;
  A = angle1 * Math.PI / 180;// half of the visual field
  B = angle2 * Math.PI / 180;
  C = (180-(angle1+angle2)) * Math.PI / 180;

  // law of sines => a/sin(A) = b/sin(B) = c/sin(C)
  // c/sin(C) = y/sin(60) = 300/sin(60) = 150*sqrt(3)
  // 150*sqrt(3) = a/sin(A)
  // 150*sqrt(3) = a/sin(30)
  // 150*sqrt(3) * sin(30) = a
  // 150*sqrt(3) * sin(30) = 129.904
  a = (c/Math.sin(C)) * Math.sin(A);
  b = Math.sin(B) * (a/Math.sin(A));
  return {
    A:A,
    B:B,
    C:C,
    a:a,
    b:b,
    c:c
  };
}
function drawPeripheryVision(ctx,x,y,direction){
  var triangle = solveASA(50,y,90);
  var linearVisionLength = triangle.a;
  var distanceToFarWall  = ctx.canvas.width - x*Math.cos(direction); // D
  ctx.beginPath();

  ctx.strokeStyle = "#dddddd";
  ctx.fillStyle = "#dddddd";
  ctx.moveTo(x,y);
  // need to create a triangle, using the angle to determine
  // how far to move the x from playerX to the left, and right
  ctx.lineTo(x-linearVisionLength/2,10);
  ctx.lineTo(x+linearVisionLength/2,10);
  ctx.lineTo(x,y);

  ctx.closePath();
  ctx.fill();
}
function drawCentralVision(ctx,x,y,direction) {
  // V = 2arctan(S/2D)
  // V = 2 * (cos(S/2D)/sin(S/2D))
  // V/2 = cos(S/2D)/sin(S/2D)
  // V = visual angle
  // S = frontal extent linear distance (what?)
  // D = Distance from observer to the viewing object

  var triangle = solveASA(30,y,90);

  var linearVisionLength = triangle.a;
  var distanceToFarWall  = ctx.canvas.width - Math.cos(direction)*x; // D
  ctx.beginPath();

  ctx.strokeStyle = "#ffffff";
  ctx.fillStyle = "#ffffff";
  ctx.moveTo(x,y);
  // need to create a triangle, using the angle to determine
  // how far to move the x from playerX to the left, and right
  ctx.lineTo(Math.cos(direction)*(x-linearVisionLength/2),Math.sin(direction)*10);
  ctx.lineTo(Math.cos(direction)*(x+linearVisionLength/2),Math.sin(direction)*10);
  ctx.lineTo(x,y);

  ctx.closePath();
  ctx.fill();
}

document.onkeydown = function(e){
  if(e.which == 38){
    //up
    playerY -=5;
    return false;
  }
  else if(e.which == 40){
    //down
    playerY +=5;
    return false;
  }
  else if(e.which == 37 ){
    //left
    //playerX -=5;
    playerDirection += (5*Math.PI/180);
    return false;
  }
  else if(e.which == 39 ){
    //right
    playerDirection -= (5*Math.PI/180);
    return false;
  }
}

function main(){
  ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
  drawPlayer(ctx,playerX,playerY,playerDirection);
}

setInterval(main,100);

// When the image is loaded, draw it
// Pulled from: http://blog.teamtreehouse.com/create-vector-masks-using-the-html5-canvas
img.onload = function () {
  // Save the state, so we can undo the clipping
  ctx.save();
  // Create a shape, of some sort
  ctx.beginPath();
  ctx.moveTo(10, 10);
  ctx.lineTo(100, 30);
  ctx.lineTo(180, 10);
  ctx.lineTo(200, 60);
  ctx.arcTo(180, 70, 120, 0, 10);
  ctx.lineTo(200, 180);
  ctx.lineTo(100, 150);
  ctx.lineTo(70, 180);
  ctx.lineTo(20, 130);
  ctx.lineTo(50, 70);
  ctx.closePath();
  // Clip to the current path
  ctx.clip();
  ctx.drawImage(img, 0, 0);
  // Undo the clipping
  ctx.restore();
  //drawPlayer(ctx,playerX,playerY);
}

// Specify the src to load the image
//img.src = "http://i.imgur.com/gwlPu.jpg";
<commit_msg>Removing weird math<commit_after>// Create an image element
var canvas = document.getElementById('c');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

var ctx    = canvas.getContext('2d');
var img    = document.createElement('IMG');
var width  = canvas.width;
var height = canvas.height;
var radius = 10;
var playerX;
var playerY;
var playerDirection = (90*Math.PI)/180;
playerX = width/2-radius;
playerY = height/2-radius;

function drawPlayer(ctx,x,y,direction){
  ctx.beginPath();
  ctx.fillStyle = "#ffffff";
  ctx.arc(x,y, radius+2, 0, Math.PI*2, false);
  ctx.fill();
  ctx.closePath();

  ctx.beginPath();
  ctx.fillStyle = "#5e9fd2";
  ctx.arc(x,y, radius, 0, Math.PI*2, false);
  ctx.fill();
  ctx.closePath();

  drawPeripheryVision(ctx,x,y,direction);
  drawCentralVision(ctx,x,y,direction);
}

function solveASA(angle1,side,angle2){
  // Solve the triangle to get S
  var a,b,c; // sides
  var A,B,C; // angles
  c = side;
  A = angle1 * Math.PI / 180;// half of the visual field
  B = angle2 * Math.PI / 180;
  C = (180-(angle1+angle2)) * Math.PI / 180;

  // law of sines => a/sin(A) = b/sin(B) = c/sin(C)
  // c/sin(C) = y/sin(60) = 300/sin(60) = 150*sqrt(3)
  // 150*sqrt(3) = a/sin(A)
  // 150*sqrt(3) = a/sin(30)
  // 150*sqrt(3) * sin(30) = a
  // 150*sqrt(3) * sin(30) = 129.904
  a = (c/Math.sin(C)) * Math.sin(A);
  b = Math.sin(B) * (a/Math.sin(A));
  return {
    A:A,
    B:B,
    C:C,
    a:a,
    b:b,
    c:c
  };
}
function drawPeripheryVision(ctx,x,y,direction){
  var triangle = solveASA(50,y,90);
  var linearVisionLength = triangle.a;
  var distanceToFarWall  = ctx.canvas.width - x*Math.cos(direction); // D
  ctx.beginPath();

  ctx.strokeStyle = "#dddddd";
  ctx.fillStyle = "#dddddd";
  ctx.moveTo(x,y);
  // need to create a triangle, using the angle to determine
  // how far to move the x from playerX to the left, and right
  ctx.lineTo(x-linearVisionLength/2,10);
  ctx.lineTo(x+linearVisionLength/2,10);
  ctx.lineTo(x,y);

  ctx.closePath();
  ctx.fill();
}
function drawCentralVision(ctx,x,y,direction) {
  // V = 2arctan(S/2D)
  // V = 2 * (cos(S/2D)/sin(S/2D))
  // V/2 = cos(S/2D)/sin(S/2D)
  // V = visual angle
  // S = frontal extent linear distance (what?)
  // D = Distance from observer to the viewing object

  var triangle = solveASA(30,y,90);

  var linearVisionLength = triangle.a;
  var distanceToFarWall  = ctx.canvas.width - x; // D
  ctx.beginPath();

  ctx.strokeStyle = "#ffffff";
  ctx.fillStyle = "#ffffff";
  ctx.moveTo(x,y);
  // need to create a triangle, using the angle to determine
  // how far to move the x from playerX to the left, and right
  ctx.lineTo((x-linearVisionLength/2),10);
  ctx.lineTo((x+linearVisionLength/2),10);
  ctx.lineTo(x,y);

  ctx.closePath();
  ctx.fill();
}

document.onkeydown = function(e){
  if(e.which == 38){
    //up
    playerY -=5;
    return false;
  }
  else if(e.which == 40){
    //down
    playerY +=5;
    return false;
  }
  else if(e.which == 37 ){
    //left
    //playerX -=5;
    playerDirection += (5*Math.PI/180);
    return false;
  }
  else if(e.which == 39 ){
    //right
    playerDirection -= (5*Math.PI/180);
    return false;
  }
}

function main(){
  ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
  drawPlayer(ctx,playerX,playerY,playerDirection);
}

setInterval(main,100);

// When the image is loaded, draw it
// Pulled from: http://blog.teamtreehouse.com/create-vector-masks-using-the-html5-canvas
img.onload = function () {
  // Save the state, so we can undo the clipping
  ctx.save();
  // Create a shape, of some sort
  ctx.beginPath();
  ctx.moveTo(10, 10);
  ctx.lineTo(100, 30);
  ctx.lineTo(180, 10);
  ctx.lineTo(200, 60);
  ctx.arcTo(180, 70, 120, 0, 10);
  ctx.lineTo(200, 180);
  ctx.lineTo(100, 150);
  ctx.lineTo(70, 180);
  ctx.lineTo(20, 130);
  ctx.lineTo(50, 70);
  ctx.closePath();
  // Clip to the current path
  ctx.clip();
  ctx.drawImage(img, 0, 0);
  // Undo the clipping
  ctx.restore();
  //drawPlayer(ctx,playerX,playerY);
}

// Specify the src to load the image
//img.src = "http://i.imgur.com/gwlPu.jpg";
<|endoftext|>


<commit_before>var pg = require('pg');
/*
* Query wrapper that connects to the database and accepts a queryObj
* @param queryObj - A JSON structure that consists of a query String
*                   and an array of values be to escaped.
*
*                   var queryObj = {
*                       query: String,
*                       arg: Array of escaped variables (optional)
*                   }
*
*/

var DELIMITER = ' ';

var query = function(queryObj, callback) {
    pg.connect(process.env.DATABASE_URL, function(err, client, done) {
        if (err) {
            console.error('error fetching client from pool', err);
            return callback(err, null);
        }
        var args = queryObj.arg || [];
        client.query(queryObj.query, args, function(err, result) {
            // client back to the pool
            done();
            if (err) {
                console.error('error running query', err);
                return callback(err, null);
            }
            console.log(result);
            return callback(null, result);
        });
    });
};

var pgInsertRow = function(params, callback) {

    var sQuery =
        'INSERT INTO $1 ($2) VALUES ($3)';

    var queryObj = {
        query: sQuery,
        arg: [params.table, params.attr, params.values]
    };

    query(sQuery, function(err, result) {
        callback(err, result);
    });
};

var open = function(params, callback) {
    var sQuery =
        'SELECT channel_id FROM poll WHERE team_id = $1';

    var queryObj = {
        query: sQuery,
        arg: [params.team_id]
    };

    query.(queryObj, function(err, result) {
        if (err) {
            return callback(false);
        }

        var row = {
            table: 'poll',
            attr: 'team_id, channel_id, title',
            values: params.team_id + ', ' + params.channel_id + ', ' + params.title
        }

        if (result.rowCount > 0) {
            return close(function() {
                pgInsertRow(row, function(err, result) {
                    if (err) {
                        return callback(false);
                    }
                    return callback(result)
                });
            });
        }

        return pgInsertRow(row, function(err, result) {
            if (err) {
                return callback(false);
            }
            return callback(result)
        });
    });
};

var close = function(params, callback) {
    // tear down DB row
    var oQuery = {
        query : 'DELETE FROM poll WHERE team_id = $1 AND channel_id = $2',
        arg: [params.team_id, params.channel_id]
    };

    query(oQuery, function() {
        oQuery.query = 'DELETE FROM options WHERE team_id = $1 AND channel_id = $2';
        query(oQuery, function() {
            oQuery.query = 'DELETE FROM votes WHERE team_id = $1 AND channel_id = $2';
            query(oQuery, callback);
        });
    });
};

var vote = function(params) {
    //

};

var results = function(params, callback) {
    var sQuery =
        'SELECT title FROM poll WHERE team_id = $1 AND channel_id = $2';

    var queryObj = {
        query: sQuery,
        arg: [params.team_id, params.channel_id]
    };

    query(queryObj, function(err, pollInfo) {
        if (err || pollInfo.rowCount === 0) {
            return callback(err, null);
        }

        queryObj.query = 'SELECT option, votes FROM options WHERE team_id = $1 AND channel_id = $2';

        query(queryObj, function(err, optionsInfo) {
            if (err) {
                return callback(err, null);
            }

            var message = {
                "response_type": "in_channel",
                "text": pollInfo.rows[0].title,
                "attachments": []
            };

            optionsInfo.rows.forEach(function(item) {
                message.attachments.push({"text" : item.option + ", Votes: " + item.votes});
            });

            callback(message);
        });
    });
};

var doPost = function(req, res) {
    var fields = req.body.text.split(DELIMITER);
    var command = fields[0].toLowerCase();
    var params = {
        "title" : title,
        "team_id" : req.body.team_id,
        "team_domain" : req.body.team_domain,
        "channel_id" : req.body.channel_id,
        "channel_name" : req.body.channel_name,
        "user_id" : req.body.user_id,
        "user_name" : req.body.user_name,
        "command" : req.body.command,
        "text" : req.body.text,
        "response_url" : req.body.response_url
    };
    var callback = function (err, result) {
        if (err)
            return;
        res.json(result);
    };

    switch (command) {
        case "open":
            var title = fields[1];
            var opts = fields.splice(2, fields.length - 1);
            params.opts = opts;
            open(params, callback);
            break;
        case "close":
            close(params, function() {}); //Don't care about return value
            results(params, callback);
            break;
        case "vote":
            vote(params, callback);
            break;
        default:
            var result = {
                "text": "No command " + command + "found"
            };
            res.json(result);
            break;
    }
};

module.exports = {
    open: open,
    close: close,
    vote: vote,
    results: results,
    doPost : doPost
};
<commit_msg>Fix title not in the params<commit_after>var pg = require('pg');
/*
* Query wrapper that connects to the database and accepts a queryObj
* @param queryObj - A JSON structure that consists of a query String
*                   and an array of values be to escaped.
*
*                   var queryObj = {
*                       query: String,
*                       arg: Array of escaped variables (optional)
*                   }
*
*/

var DELIMITER = ' ';

var query = function(queryObj, callback) {
    pg.connect(process.env.DATABASE_URL, function(err, client, done) {
        if (err) {
            console.error('error fetching client from pool', err);
            return callback(err, null);
        }
        var args = queryObj.arg || [];
        client.query(queryObj.query, args, function(err, result) {
            // client back to the pool
            done();
            if (err) {
                console.error('error running query', err);
                return callback(err, null);
            }
            console.log(result);
            return callback(null, result);
        });
    });
};

var pgInsertRow = function(params, callback) {

    var sQuery =
        'INSERT INTO $1 ($2) VALUES ($3)';

    var queryObj = {
        query: sQuery,
        arg: [params.table, params.attr, params.values]
    };

    query(sQuery, function(err, result) {
        callback(err, result);
    });
};

var open = function(params, callback) {
    var sQuery =
        'SELECT channel_id FROM poll WHERE team_id = $1';

    var queryObj = {
        query: sQuery,
        arg: [params.team_id]
    };

    query.(queryObj, function(err, result) {
        if (err) {
            return callback(false);
        }

        var row = {
            table: 'poll',
            attr: 'team_id, channel_id, title',
            values: params.team_id + ', ' + params.channel_id + ', ' + params.title
        }

        if (result.rowCount > 0) {
            return close(function() {
                pgInsertRow(row, function(err, result) {
                    if (err) {
                        return callback(false);
                    }
                    return callback(result)
                });
            });
        }

        return pgInsertRow(row, function(err, result) {
            if (err) {
                return callback(false);
            }
            return callback(result)
        });
    });
};

var close = function(params, callback) {
    // tear down DB row
    var oQuery = {
        query : 'DELETE FROM poll WHERE team_id = $1 AND channel_id = $2',
        arg: [params.team_id, params.channel_id]
    };

    query(oQuery, function() {
        oQuery.query = 'DELETE FROM options WHERE team_id = $1 AND channel_id = $2';
        query(oQuery, function() {
            oQuery.query = 'DELETE FROM votes WHERE team_id = $1 AND channel_id = $2';
            query(oQuery, callback);
        });
    });
};

var vote = function(params) {
    //

};

var results = function(params, callback) {
    var sQuery =
        'SELECT title FROM poll WHERE team_id = $1 AND channel_id = $2';

    var queryObj = {
        query: sQuery,
        arg: [params.team_id, params.channel_id]
    };

    query(queryObj, function(err, pollInfo) {
        if (err || pollInfo.rowCount === 0) {
            return callback(err, null);
        }

        queryObj.query = 'SELECT option, votes FROM options WHERE team_id = $1 AND channel_id = $2';

        query(queryObj, function(err, optionsInfo) {
            if (err) {
                return callback(err, null);
            }

            var message = {
                "response_type": "in_channel",
                "text": pollInfo.rows[0].title,
                "attachments": []
            };

            optionsInfo.rows.forEach(function(item) {
                message.attachments.push({"text" : item.option + ", Votes: " + item.votes});
            });

            callback(message);
        });
    });
};

var doPost = function(req, res) {
    var fields = req.body.text.split(DELIMITER);
    var command = fields[0].toLowerCase();
    var params = {
        "team_id" : req.body.team_id,
        "team_domain" : req.body.team_domain,
        "channel_id" : req.body.channel_id,
        "channel_name" : req.body.channel_name,
        "user_id" : req.body.user_id,
        "user_name" : req.body.user_name,
        "command" : req.body.command,
        "text" : req.body.text,
        "response_url" : req.body.response_url
    };
    var callback = function (err, result) {
        if (err)
            return;
        res.json(result);
    };

    switch (command) {
        case "open":
            var title = fields[1];
            var opts = fields.splice(2, fields.length - 1);
            params.title = title;
            params.opts = opts;
            open(params, callback);
            break;
        case "close":
            close(params, function() {}); //Don't care about return value
            results(params, callback);
            break;
        case "vote":
            vote(params, callback);
            break;
        default:
            var result = {
                "text": "No command " + command + "found"
            };
            res.json(result);
            break;
    }
};

module.exports = {
    open: open,
    close: close,
    vote: vote,
    results: results,
    doPost : doPost
};
<|endoftext|>


<commit_before>(function(babel, $, _, ace, window) {

  /* Throw meaningful errors for getters of commonjs. */
  ["module", "exports", "require"].forEach(function(commonVar){
    Object.defineProperty(window, commonVar, {
      configurable: true,
      get: function () {
        throw new Error(commonVar + " is not supported in the browser, you need a commonjs environment such as node.js/io.js, browserify/webpack etc");
      }
    });
  });

  /*
   * Utils for working with the browser's URI (e.g. the query params)
   */
  function UriUtils () {}

  UriUtils.encode = function (value) {
    return window.encodeURIComponent(value);
  };

  UriUtils.decode = function (value) {
    try {
      return window.decodeURIComponent('' + value);
    } catch (err) {
      return value;
    }
  };

  UriUtils.parseQuery = function () {
    var query = window.location.hash.replace(/^\#\?/, '');

    if (!query) {
      return null;
    }

    return query.split('&').map(function(param) {
      var splitPoint = param.indexOf('=');

      return {
        key : param.substring(0, splitPoint),
        value : param.substring(splitPoint + 1)
      };
    }).reduce(function(params, param){
      if (param.key && param.value) {
        params[param.key] = UriUtils.decode(param.value);
      }
      return params;
    }, {});
  };

  UriUtils.updateQuery = function (object) {
    var query = Object.keys(object).map(function(key){
      return key + '=' + UriUtils.encode(object[key]);
    }).join('&');

    window.location.hash = '?' + query;
  };

  /*
   * Long term storage for persistence of state/etc
   */
  function StorageService () {
    this.store = window.localStorage;
  }

  StorageService.prototype.get = function (key) {
    try {
      return JSON.parse(this.store.getItem(key));
    } catch(e) {}
  };

  StorageService.prototype.set = function (key, value) {
    try {
      this.store.setItem(key, JSON.stringify(value));
    } catch(e) {}
  };

  /*
   * Decorating the ACE editor
   */
  function Editor(selector) {
    this.$el = $(selector);
    this.editor = ace.edit(this.$el[0]);
    this.session = this.editor.getSession();
    this.document = this.session.getDocument();

    this.editor.setTheme('ace/theme/tomorrow');
    this.editor.setShowPrintMargin(false);
    this.$el.css({
      fontFamily: 'Menlo, Monaco, Consolas, "Courier New", monospace',
      lineHeight: 'inherit'
    });

    this.session.setMode('ace/mode/javascript');
    this.session.setUseSoftTabs(true);
    this.session.setTabSize(2);
    this.session.setUseWorker(false);

    this.editor.setOption('scrollPastEnd', 0.33);
  }

  /*
   * Options exposed for the REPL that will influence Babel's transpiling
   */
  function $checkbox($element){
    return {
      get: function () {
        return $element.is(":checked");
      } ,
      set: function (value) {
        var setting = value !== 'false' && value !== false;
        $element.prop('checked', setting);
      },
      enumerable: true,
      configurable: false
    };
  }

  /*
   * Babel options for transpilation as used by the REPL
   */
  function Options () {
    var $experimental = $('#option-experimental');
    var $evaluate = $('#option-evaluate');
    var $loose = $('#option-loose-mode');
    var $spec = $('#option-spec');

    var options = {};
    Object.defineProperties(options, {
      'experimental': $checkbox($experimental),
      'evaluate': $checkbox($evaluate),
      'loose': $checkbox($loose),
      'spec': $checkbox($spec)
    });

    // Merge in defaults
    var defaults = {
      experimental : false,
      loose : false,
      spec : false,
      evaluate : true
    };

    _.assign(options, defaults);

    return options;
  }

  /*
   * Babel Web REPL
   */
  function REPL () {
    this.storage = new StorageService();
    var state = this.storage.get('replState') || {};
    _.assign(state, UriUtils.parseQuery());

    this.options = _.assign(new Options(), state);

    this.input = new Editor('.babel-repl-input .ace_editor').editor;
    this.input.setValue(UriUtils.decode(state.code || ''));

    this.output = new Editor('.babel-repl-output .ace_editor').editor;
    this.output.setReadOnly(true);
    this.output.setHighlightActiveLine(false);
    this.output.setHighlightGutterLine(false);

    this.$errorReporter = $('.babel-repl-errors');
    this.$consoleReporter = $('.babel-repl-console');
    this.$toolBar = $('.babel-repl-toolbar');
  }

  REPL.prototype.clearOutput = function () {
    this.$errorReporter.text('');
    this.$consoleReporter.text('');
  };

  REPL.prototype.setOutput = function (output) {
    this.output.setValue(output, -1);
  };

  REPL.prototype.printError = function (message) {
    this.$errorReporter.text(message);
  };

  REPL.prototype.getSource = function () {
    return this.input.getValue();
  };

  REPL.prototype.compile = function () {

    var transformed;
    var code = this.getSource();
    this.clearOutput();

    try {
      transformed = babel.transform(code, {
        stage: this.options.experimental ? 0 : 2,
        loose: this.options.loose && "all",
        optional: this.options.spec && ["es6.spec.templateLiterals", "es6.spec.blockScoping", "es6.spec.symbols"],
        filename: 'repl'
      });
    } catch (err) {
      this.printError(err.message);
      throw err;
    }

    this.setOutput(transformed.code);

    if (this.options.evaluate) {
      this.evaluate(transformed.code);
    }
  };

  var capturingConsole;
  REPL.prototype.evaluate = function(code) {
    capturingConsole = Object.create(console);
    var $consoleReporter = this.$consoleReporter;
    var buffer = [];
    var error;
    var done = false;

    function flush() {
      $consoleReporter.text(buffer.join('\n'));
    }

    function write(data) {
      buffer.push(data);
      if (done) flush();
    }

    capturingConsole.clear = function() {
      buffer = [];
      flush();
    };

    capturingConsole.error = function () {
      error = true;
      capturingConsole.log.apply(capturingConsole, arguments);
    };

    capturingConsole.log =
    capturingConsole.info =
    capturingConsole.debug = function() {
      if (this !== capturingConsole) { return; }

      var args = Array.prototype.slice.call(arguments);
      Function.prototype.apply.call(console.log, console, args);

      var logs = args.reduce(function (logs, log) {
        if (typeof log === 'string') {
          logs.push(log);
        } else if (log instanceof Function) {
          logs.push(log.toString());
        } else {
          logs.push(JSON.stringify(log));
        }
        return logs;
      }, []);

      write(logs.join(' '));
    };

    try {
      new Function('console', code)(capturingConsole);
    } catch (err) {
      error = err;
      buffer.push(err.message);
    }

    done = true;
    flush();

    if (error) throw error;
  };

  REPL.prototype.persistState = function (state) {
    UriUtils.updateQuery(state);
    this.storage.set('replState', state);
  };

  /*
   * Initialize the REPL
   */
  var repl = new REPL();

  function onSourceChange () {
    var error;
    try {
      repl.compile();
    } catch(err) {
      error = err;
    }
    var code = repl.getSource();
    var state = _.assign(repl.options, {
      code: code
    });
    repl.persistState(state);
    if (error) throw error;
  }

  repl.input.on('change', _.debounce(onSourceChange, 500));
  repl.$toolBar.on('change', onSourceChange);

  repl.compile();

}(babel, $, _, ace, window));
<commit_msg>Get rid of keyboard hijacking annoyances.<commit_after>(function(babel, $, _, ace, window) {

  /* Throw meaningful errors for getters of commonjs. */
  ["module", "exports", "require"].forEach(function(commonVar){
    Object.defineProperty(window, commonVar, {
      configurable: true,
      get: function () {
        throw new Error(commonVar + " is not supported in the browser, you need a commonjs environment such as node.js/io.js, browserify/webpack etc");
      }
    });
  });

  /*
   * Utils for working with the browser's URI (e.g. the query params)
   */
  function UriUtils () {}

  UriUtils.encode = function (value) {
    return window.encodeURIComponent(value);
  };

  UriUtils.decode = function (value) {
    try {
      return window.decodeURIComponent('' + value);
    } catch (err) {
      return value;
    }
  };

  UriUtils.parseQuery = function () {
    var query = window.location.hash.replace(/^\#\?/, '');

    if (!query) {
      return null;
    }

    return query.split('&').map(function(param) {
      var splitPoint = param.indexOf('=');

      return {
        key : param.substring(0, splitPoint),
        value : param.substring(splitPoint + 1)
      };
    }).reduce(function(params, param){
      if (param.key && param.value) {
        params[param.key] = UriUtils.decode(param.value);
      }
      return params;
    }, {});
  };

  UriUtils.updateQuery = function (object) {
    var query = Object.keys(object).map(function(key){
      return key + '=' + UriUtils.encode(object[key]);
    }).join('&');

    window.location.hash = '?' + query;
  };

  /*
   * Long term storage for persistence of state/etc
   */
  function StorageService () {
    this.store = window.localStorage;
  }

  StorageService.prototype.get = function (key) {
    try {
      return JSON.parse(this.store.getItem(key));
    } catch(e) {}
  };

  StorageService.prototype.set = function (key, value) {
    try {
      this.store.setItem(key, JSON.stringify(value));
    } catch(e) {}
  };

  /*
   * Decorating the ACE editor
   */
  function Editor(selector) {
    this.$el = $(selector);
    this.editor = ace.edit(this.$el[0]);
    this.session = this.editor.getSession();
    this.document = this.session.getDocument();

    this.editor.setTheme('ace/theme/tomorrow');
    this.editor.setShowPrintMargin(false);
    this.editor.commands.removeCommands(['gotoline', 'find']);
    this.$el.css({
      fontFamily: 'Menlo, Monaco, Consolas, "Courier New", monospace',
      lineHeight: 'inherit'
    });

    this.session.setMode('ace/mode/javascript');
    this.session.setUseSoftTabs(true);
    this.session.setTabSize(2);
    this.session.setUseWorker(false);

    this.editor.setOption('scrollPastEnd', 0.33);
  }

  /*
   * Options exposed for the REPL that will influence Babel's transpiling
   */
  function $checkbox($element){
    return {
      get: function () {
        return $element.is(":checked");
      } ,
      set: function (value) {
        var setting = value !== 'false' && value !== false;
        $element.prop('checked', setting);
      },
      enumerable: true,
      configurable: false
    };
  }

  /*
   * Babel options for transpilation as used by the REPL
   */
  function Options () {
    var $experimental = $('#option-experimental');
    var $evaluate = $('#option-evaluate');
    var $loose = $('#option-loose-mode');
    var $spec = $('#option-spec');

    var options = {};
    Object.defineProperties(options, {
      'experimental': $checkbox($experimental),
      'evaluate': $checkbox($evaluate),
      'loose': $checkbox($loose),
      'spec': $checkbox($spec)
    });

    // Merge in defaults
    var defaults = {
      experimental : false,
      loose : false,
      spec : false,
      evaluate : true
    };

    _.assign(options, defaults);

    return options;
  }

  /*
   * Babel Web REPL
   */
  function REPL () {
    this.storage = new StorageService();
    var state = this.storage.get('replState') || {};
    _.assign(state, UriUtils.parseQuery());

    this.options = _.assign(new Options(), state);

    this.input = new Editor('.babel-repl-input .ace_editor').editor;
    this.input.setValue(UriUtils.decode(state.code || ''));

    this.output = new Editor('.babel-repl-output .ace_editor').editor;
    this.output.setReadOnly(true);
    this.output.setHighlightActiveLine(false);
    this.output.setHighlightGutterLine(false);

    this.$errorReporter = $('.babel-repl-errors');
    this.$consoleReporter = $('.babel-repl-console');
    this.$toolBar = $('.babel-repl-toolbar');
  }

  REPL.prototype.clearOutput = function () {
    this.$errorReporter.text('');
    this.$consoleReporter.text('');
  };

  REPL.prototype.setOutput = function (output) {
    this.output.setValue(output, -1);
  };

  REPL.prototype.printError = function (message) {
    this.$errorReporter.text(message);
  };

  REPL.prototype.getSource = function () {
    return this.input.getValue();
  };

  REPL.prototype.compile = function () {

    var transformed;
    var code = this.getSource();
    this.clearOutput();

    try {
      transformed = babel.transform(code, {
        stage: this.options.experimental ? 0 : 2,
        loose: this.options.loose && "all",
        optional: this.options.spec && ["es6.spec.templateLiterals", "es6.spec.blockScoping", "es6.spec.symbols"],
        filename: 'repl'
      });
    } catch (err) {
      this.printError(err.message);
      throw err;
    }

    this.setOutput(transformed.code);

    if (this.options.evaluate) {
      this.evaluate(transformed.code);
    }
  };

  var capturingConsole;
  REPL.prototype.evaluate = function(code) {
    capturingConsole = Object.create(console);
    var $consoleReporter = this.$consoleReporter;
    var buffer = [];
    var error;
    var done = false;

    function flush() {
      $consoleReporter.text(buffer.join('\n'));
    }

    function write(data) {
      buffer.push(data);
      if (done) flush();
    }

    capturingConsole.clear = function() {
      buffer = [];
      flush();
    };

    capturingConsole.error = function () {
      error = true;
      capturingConsole.log.apply(capturingConsole, arguments);
    };

    capturingConsole.log =
    capturingConsole.info =
    capturingConsole.debug = function() {
      if (this !== capturingConsole) { return; }

      var args = Array.prototype.slice.call(arguments);
      Function.prototype.apply.call(console.log, console, args);

      var logs = args.reduce(function (logs, log) {
        if (typeof log === 'string') {
          logs.push(log);
        } else if (log instanceof Function) {
          logs.push(log.toString());
        } else {
          logs.push(JSON.stringify(log));
        }
        return logs;
      }, []);

      write(logs.join(' '));
    };

    try {
      new Function('console', code)(capturingConsole);
    } catch (err) {
      error = err;
      buffer.push(err.message);
    }

    done = true;
    flush();

    if (error) throw error;
  };

  REPL.prototype.persistState = function (state) {
    UriUtils.updateQuery(state);
    this.storage.set('replState', state);
  };

  /*
   * Initialize the REPL
   */
  var repl = new REPL();

  function onSourceChange () {
    var error;
    try {
      repl.compile();
    } catch(err) {
      error = err;
    }
    var code = repl.getSource();
    var state = _.assign(repl.options, {
      code: code
    });
    repl.persistState(state);
    if (error) throw error;
  }

  repl.input.on('change', _.debounce(onSourceChange, 500));
  repl.$toolBar.on('change', onSourceChange);

  repl.compile();

}(babel, $, _, ace, window));
<|endoftext|>


<commit_before>define(['Ti/_/lang', 'Tizen/_/Package/PackageInformation', 'Ti/_/Evented'], function(lang, PackageInformation, Evented) {

	function onError (e, callback) {
		callback({
			code: e.code,
			success: false,
			error: e.type + ': ' + e.message
		});
	}

	var listening;

	return lang.mixProps(require.mix({}, Evented), {

		install: function(path /*DOMString*/, callback /*PackageProgressCallback*/) {
			return tizen.package.install(path, {
				onprogress: callback && function(id, progress) {
					callback({
						code: 0,
						success: true,
						id: id,
						progress: progress,
						onprogress: true,
						oncomplette: false
					});
				},
				oncomplette: callback && function(id) {
					callback({
						code: 0,
						success: true,
						id: id,
						onprogress: false,
						oncomplette: true
					});
				}

			}, callback && function(e) {
				onError(e, callback);
			});
		},

		uninstall: function(id /*PackageId*/, progressCallback /*PackageProgressCallback*/) {
			return tizen.package.uninstall(id, {
				onprogress: callback && function(id, progress) {
					callback({
						code: 0,
						success: true,
						id: id,
						progress: progress,
						onprogress: true,
						oncomplette: false
					});
				},
				oncomplette: callback && function(id) {
					callback({
						code: 0,
						success: true,
						id: id,
						onprogress: false,
						oncomplette: true
					});
				}

			}, callback && function(e) {
				onError(e, callback);
			});
		},

		getPackagesInfo: function(callback /*PackageInformationArraySuccessCallback*/) {
			return tizen.package.getPackagesInfo(callback && function(informationArray) {
				var result = [],
					i = 0,
					length = informationArray.length;
				for (; i < length; i++) {
					result.push(new PackageInformation(void 0, informationArray[i]));
				}

				callback({
					code: 0,
					success: true,
					informationArray: result
				});

			}, callback && function(e) {
				onError(e, callback);
			});
		},

		getPackageInfo: function(id /*PackageId*/) {
			var packageInfo = izen.package.getPackageInfo(id);
			return new PackageInformation(void 0, packageInfo);
		},

		addEventListener: function() {
			var self = this;
			Evented.addEventListener.apply(this, arguments);
			if (! listening) {
				tizen.package.setPackageInfoEventListener({
					oninstalled: function(info) {
						self.fireEvent('packageinstalled', {
							info: new PackageInformation(void 0, info)
						});
					},
					onupdated: function(info) {
						self.fireEvent('packageupdated', {
							info: new PackageInformation(void 0, info)
						});
					},
					onuninstalled: function(id) {
						self.fireEvent('packageuninstalled', {
							id: id
						});
					}
				});
			}
		}

	}, true);
});<commit_msg>Package progress callback changed<commit_after>define(['Ti/_/lang', 'Tizen/_/Package/PackageInformation', 'Ti/_/Evented'], function(lang, PackageInformation, Evented) {

	function onError (e, callback) {
		callback({
			code: e.code,
			success: false,
			error: e.type + ': ' + e.message
		});
	}

	var listening;

	return lang.mixProps(require.mix({}, Evented), {

		install: function(path /*DOMString*/, callback /*PackageProgressCallback*/) {
			return tizen.package.install(path, {
				onprogress: callback && function(id, progress) {
					callback({
						code: 0,
						success: true,
						id: id,
						progress: progress,
						onprogress: true,
						oncomplette: false
					});
				},
				oncomplette: callback && function(id) {
					callback({
						code: 0,
						success: true,
						id: id,
						progress: 100,
						onprogress: false,
						oncomplette: true
					});
				}

			}, callback && function(e) {
				onError(e, callback);
			});
		},

		uninstall: function(id /*PackageId*/, progressCallback /*PackageProgressCallback*/) {
			return tizen.package.uninstall(id, {
				onprogress: callback && function(id, progress) {
					callback({
						code: 0,
						success: true,
						id: id,
						progress: progress,
						onprogress: true,
						oncomplette: false
					});
				},
				oncomplette: callback && function(id) {
					callback({
						code: 0,
						success: true,
						id: id,
						onprogress: false,
						oncomplette: true
					});
				}

			}, callback && function(e) {
				onError(e, callback);
			});
		},

		getPackagesInfo: function(callback /*PackageInformationArraySuccessCallback*/) {
			return tizen.package.getPackagesInfo(callback && function(informationArray) {
				var result = [],
					i = 0,
					length = informationArray.length;
				for (; i < length; i++) {
					result.push(new PackageInformation(void 0, informationArray[i]));
				}

				callback({
					code: 0,
					success: true,
					informationArray: result
				});

			}, callback && function(e) {
				onError(e, callback);
			});
		},

		getPackageInfo: function(id /*PackageId*/) {
			var packageInfo = izen.package.getPackageInfo(id);
			return new PackageInformation(void 0, packageInfo);
		},

		addEventListener: function() {
			var self = this;
			Evented.addEventListener.apply(this, arguments);
			if (! listening) {
				tizen.package.setPackageInfoEventListener({
					oninstalled: function(info) {
						self.fireEvent('packageinstalled', {
							info: new PackageInformation(void 0, info)
						});
					},
					onupdated: function(info) {
						self.fireEvent('packageupdated', {
							info: new PackageInformation(void 0, info)
						});
					},
					onuninstalled: function(id) {
						self.fireEvent('packageuninstalled', {
							id: id
						});
					}
				});
			}
		}

	}, true);
});<|endoftext|>