<commit_before>var global_min = 0;
var global_max = 0;
var chr_lengths = new Array();
var total_len = 0;
function manhattan_plot(canvasid,study) {
	// fetch the list of chromosomes and their lengths
	$.getJSON("/chromosomes/at",
		function(json1) {
			for(var i=0;i<json1.length;i++) {
				chr_lengths[i] = json1[i][1];
				total_len += json1[i][1];
			}
			// fetch the max score for this study
			$.getJSON("/maxscore/GWAS/"+study,
			function(json2) {
				global_max = Math.ceil(json2[0][0]);
				draw_manhattan(canvasid,study);
			}
		);
	});
}

function draw_manhattan(canvasid,study) {
  // get the canvas
	var canvas = document.getElementById(canvasid);
	var ctx = canvas.getContext('2d');
	ctx.canvas.width = window.innerWidth-20;
	ctx.canvas.height = window.innerHeight - 20;
	ctx.strokeStyle="black";
	ctx.strokeRect(0,0,ctx.canvas.width,ctx.canvas.height);
	var offset=0;
	var ysize = ctx.canvas.height;
	for(var i=0;i<chr_lengths.length;i++) {
		var xsize = ctx.canvas.width*(chr_lengths[i]/total_len);
		do_scatter(ctx,study,i+1,offset,xsize,ysize,chr_lengths[i]);
		offset += xsize;
	}
}

function do_scatter(ctx,study,chr,offset,xsize,ysize,chr_length) {
	$.getJSON("/scatter/GWAS/"+study+"/"+chr+"/"+Math.floor(xsize)+"/"+Math.floor(ysize)+"/"+1.2+"/"+0+"/"+chr_length+"/"+0+"/"+global_max+"/100",
		function(json) {
			var xrange = chr_length;
			var yrange = global_max;
			var xfactor = xsize/xrange;
			var yfactor = ysize/yrange;
			if (chr % 2 === 0) {
				ctx.fillStyle="darkorange";
			} else {
				ctx.fillStyle="black";
			}
			for(var i=0; i<json.data.length; i++) {
				var rect = json.data[i];
				var width = xfactor*(rect[1]-rect[0]);
				var height = yfactor*(rect[3]-rect[2]);
				var x = xfactor*rect[0] + offset;
				var y = ysize - height - yfactor*rect[2];
				if (height < 1) {height=1;}
				if (width < 1) {width = 1;}
				if (height * width < 4) {
					ctx.fillRect(Math.floor(x),Math.floor(y),2,2);
				} else {
					ctx.fillRect(Math.floor(x),Math.floor(y),Math.ceil(width),Math.ceil(height));
				}
			}
		});
}

function manhattan_plot_dots(canvasid,study) {
	// fetch the list of chromosomes and their lengths
	$.getJSON("/chromosomes/at",
		function(json1) {
			for(var i=0;i<json1.length;i++) {
				chr_lengths[i] = json1[i][1];
				total_len += json1[i][1];
			}
			// fetch the max score for this study
			$.getJSON("/maxscore/GWAS/"+study,
			function(json2) {
				global_max = Math.ceil(json2[0][0]);
				draw_manhattan_dots(canvasid,study);
			}
		);
	});
}
var ctxi;
function draw_manhattan_dots(canvasid,study) {
  // get the canvas
	var canvas = document.getElementById(canvasid);
	var ctx = canvas.getContext('2d');
	ctx.canvas.width = window.innerWidth-20;
	ctx.canvas.height = window.innerHeight - 20;
	ctx.strokeStyle="black";
	ctx.strokeRect(0,0,ctx.canvas.width,ctx.canvas.height);

	// resize the interactive layer
	var canvasi = document.getElementById(canvasid+'i');
	ctxi = canvasi.getContext('2d');
	ctxi.canvas.width = ctx.canvas.width;
	ctxi.canvas.height = ctx.canvas.height;

	// add event listeners
	canvasi.addEventListener('mousedown', ev_canvas, false);
	canvasi.addEventListener('mousemove', ev_canvas, false);
	canvasi.addEventListener('mouseup',   ev_canvas, false);

	var offset=0;
	var ysize = ctx.canvas.height;
	for(var i=0;i<chr_lengths.length;i++) {
		var xsize = ctx.canvas.width*(chr_lengths[i]/total_len);
		do_scatter_dots(ctx,study,i+1,offset,xsize,ysize,chr_lengths[i]);
		offset += xsize;
	}
}

function do_scatter_dots(ctx,study,chr,offset,xsize,ysize,chr_length) {
	$.getJSON("/scatter/GWAS/nobinning/"+study+"/"+chr,
		function(json) {
			var xrange = chr_length;
			var yrange = global_max;
			var xfactor = xsize/xrange;
			var yfactor = ysize/yrange;
			if (chr % 2 === 0) {
				ctx.fillStyle="darkorange";
			} else {
				ctx.fillStyle="black";
			}
			for(var i=0; i<json.length; i++) {
				var x = xfactor*json[i][0] + offset;
				var y = ysize - 2 - yfactor*json[i][1];
				ctx.fillRect(Math.floor(x),Math.floor(y),2,2);
			}
		});
}
function drag_select () {
	var tool = this;
	this.started = false;

	this.mousedown = function (ev) {
		tool.started = true;
		tool.x = ev._x;
		tool.y = ev._y;
		ctxi.clearRect(0,0,ctxi.canvas.width,ctxi.canvas.height);
		ctxi.strokeRect(tool.x,tool.y,1,1);
	};

	this.mousemove = function (ev) {
		if (tool.started) {
			var x1 = tool.x;
			var y1 = tool.y;
			var x2 = ev._x;
			var y2 = ev._y;
			if (x2 - x1 > 1) {
				x1++;
				x2--;
				if (y2 - y1 > 1) {
					y1++;
					y2--;
					ctxi.clearRect(x1,y1,x2,y2);
				} else if (y1 - y2 > 1) {
					y1--;
					y2++;
					ctxi.clearRect(x1,y1,x2,y2);
				}
			} else if (x1 - x2 > 1) {
				x1--;
				x2++;
				if (y2 - y1 > 1) {
					y1++;
					y2--;
					ctxi.clearRect(x1,y1,x2,y2);
				} else if (y1 - y2 > 1) {
					y1--;
					y2++;
					ctxi.clearRect(x1,y1,x2,y2);
				}
			}
			ctxi.strokeRect(tool.x, tool.y, ev._x - tool.x + 1, ev._y - tool.y + 1);
		}
	};

	this.mouseup = function(ev) {
		if (tool.started) {
			alert("selected rectangle (" + tool.x + "," + tool.y + "," + ev._x + "," + ev._y + ")");
			tool.started = false;
		}
	};
}

function ev_canvas (ev) {
	if (ev.layerX || ev.layerX == 0) {
		ev._x = ev.layerX;
		ev._y = ev.layerY;
	} else if (ev.offsetX || ev.offsetX == 0) {
		ev._x = ev.offsetX;
		ev._y = ev.offsetY;
	}
	var func = drag_select[ev.type];
	if (func) {
		func(ev)
	}
}<commit_msg>automatically set minbins<commit_after>var global_min = 0;
var global_max = 0;
var chr_lengths = new Array();
var total_len = 0;
function manhattan_plot(canvasid,study) {
	// fetch the list of chromosomes and their lengths
	$.getJSON("/chromosomes/at",
		function(json1) {
			for(var i=0;i<json1.length;i++) {
				chr_lengths[i] = json1[i][1];
				total_len += json1[i][1];
			}
			// fetch the max score for this study
			$.getJSON("/maxscore/GWAS/"+study,
			function(json2) {
				global_max = Math.ceil(json2[0][0]);
				draw_manhattan(canvasid,study);
			}
		);
	});
}

function draw_manhattan(canvasid,study) {
  // get the canvas
	var canvas = document.getElementById(canvasid);
	var ctx = canvas.getContext('2d');
	ctx.canvas.width = window.innerWidth-20;
	ctx.canvas.height = window.innerHeight - 20;
	ctx.strokeStyle="black";
	ctx.strokeRect(0,0,ctx.canvas.width,ctx.canvas.height);
	var offset=0;
	var ysize = ctx.canvas.height;
	for(var i=0;i<chr_lengths.length;i++) {
		var xsize = ctx.canvas.width*(chr_lengths[i]/total_len);
		do_scatter(ctx,study,i+1,offset,xsize,ysize,chr_lengths[i]);
		offset += xsize;
	}
}

function do_scatter(ctx,study,chr,offset,xsize,ysize,chr_length) {
	var minbins = Math.floor(Math.max([xsize,ysize])/2);
	$.getJSON("/scatter/GWAS/"+study+"/"+chr+"/"+Math.floor(xsize)+"/"+Math.floor(ysize)+"/"+1.2+"/"+0+"/"+chr_length+"/"+0+"/"+global_max+"/"+minbins,
		function(json) {
			var xrange = chr_length;
			var yrange = global_max;
			var xfactor = xsize/xrange;
			var yfactor = ysize/yrange;
			if (chr % 2 === 0) {
				ctx.fillStyle="darkorange";
			} else {
				ctx.fillStyle="black";
			}
			for(var i=0; i<json.data.length; i++) {
				var rect = json.data[i];
				var width = xfactor*(rect[1]-rect[0]);
				var height = yfactor*(rect[3]-rect[2]);
				var x = xfactor*rect[0] + offset;
				var y = ysize - height - yfactor*rect[2];
				if (height < 1) {height=1;}
				if (width < 1) {width = 1;}
				if (height * width < 4) {
					ctx.fillRect(Math.floor(x),Math.floor(y),2,2);
				} else {
					ctx.fillRect(Math.floor(x),Math.floor(y),Math.ceil(width),Math.ceil(height));
				}
			}
		});
}

function manhattan_plot_dots(canvasid,study) {
	// fetch the list of chromosomes and their lengths
	$.getJSON("/chromosomes/at",
		function(json1) {
			for(var i=0;i<json1.length;i++) {
				chr_lengths[i] = json1[i][1];
				total_len += json1[i][1];
			}
			// fetch the max score for this study
			$.getJSON("/maxscore/GWAS/"+study,
			function(json2) {
				global_max = Math.ceil(json2[0][0]);
				draw_manhattan_dots(canvasid,study);
			}
		);
	});
}
var ctxi;
function draw_manhattan_dots(canvasid,study) {
  // get the canvas
	var canvas = document.getElementById(canvasid);
	var ctx = canvas.getContext('2d');
	ctx.canvas.width = window.innerWidth-20;
	ctx.canvas.height = window.innerHeight - 20;
	ctx.strokeStyle="black";
	ctx.strokeRect(0,0,ctx.canvas.width,ctx.canvas.height);

	// resize the interactive layer
	var canvasi = document.getElementById(canvasid+'i');
	ctxi = canvasi.getContext('2d');
	ctxi.canvas.width = ctx.canvas.width;
	ctxi.canvas.height = ctx.canvas.height;

	// add event listeners
	canvasi.addEventListener('mousedown', ev_canvas, false);
	canvasi.addEventListener('mousemove', ev_canvas, false);
	canvasi.addEventListener('mouseup',   ev_canvas, false);

	var offset=0;
	var ysize = ctx.canvas.height;
	for(var i=0;i<chr_lengths.length;i++) {
		var xsize = ctx.canvas.width*(chr_lengths[i]/total_len);
		do_scatter_dots(ctx,study,i+1,offset,xsize,ysize,chr_lengths[i]);
		offset += xsize;
	}
}

function do_scatter_dots(ctx,study,chr,offset,xsize,ysize,chr_length) {
	$.getJSON("/scatter/GWAS/nobinning/"+study+"/"+chr,
		function(json) {
			var xrange = chr_length;
			var yrange = global_max;
			var xfactor = xsize/xrange;
			var yfactor = ysize/yrange;
			if (chr % 2 === 0) {
				ctx.fillStyle="darkorange";
			} else {
				ctx.fillStyle="black";
			}
			for(var i=0; i<json.length; i++) {
				var x = xfactor*json[i][0] + offset;
				var y = ysize - 2 - yfactor*json[i][1];
				ctx.fillRect(Math.floor(x),Math.floor(y),2,2);
			}
		});
}
function drag_select () {
	var tool = this;
	this.started = false;

	this.mousedown = function (ev) {
		tool.started = true;
		tool.x = ev._x;
		tool.y = ev._y;
		ctxi.clearRect(0,0,ctxi.canvas.width,ctxi.canvas.height);
		ctxi.strokeRect(tool.x,tool.y,1,1);
	};

	this.mousemove = function (ev) {
		if (tool.started) {
			var x1 = tool.x;
			var y1 = tool.y;
			var x2 = ev._x;
			var y2 = ev._y;
			if (x2 - x1 > 1) {
				x1++;
				x2--;
				if (y2 - y1 > 1) {
					y1++;
					y2--;
					ctxi.clearRect(x1,y1,x2,y2);
				} else if (y1 - y2 > 1) {
					y1--;
					y2++;
					ctxi.clearRect(x1,y1,x2,y2);
				}
			} else if (x1 - x2 > 1) {
				x1--;
				x2++;
				if (y2 - y1 > 1) {
					y1++;
					y2--;
					ctxi.clearRect(x1,y1,x2,y2);
				} else if (y1 - y2 > 1) {
					y1--;
					y2++;
					ctxi.clearRect(x1,y1,x2,y2);
				}
			}
			ctxi.strokeRect(tool.x, tool.y, ev._x - tool.x + 1, ev._y - tool.y + 1);
		}
	};

	this.mouseup = function(ev) {
		if (tool.started) {
			alert("selected rectangle (" + tool.x + "," + tool.y + "," + ev._x + "," + ev._y + ")");
			tool.started = false;
		}
	};
}

function ev_canvas (ev) {
	if (ev.layerX || ev.layerX == 0) {
		ev._x = ev.layerX;
		ev._y = ev.layerY;
	} else if (ev.offsetX || ev.offsetX == 0) {
		ev._x = ev.offsetX;
		ev._y = ev.offsetY;
	}
	var func = drag_select[ev.type];
	if (func) {
		func(ev)
	}
}<|endoftext|>


<commit_before>
window.onload = load;

var worldW = 17,
    worldH = 21,

    spacing = 3, // pixels
    blockSize = 20, // pixels

    canvas,
    context;

var world,
    level = 0,
    ySpeed = 1,
    baseSpeed = 30;

var sampleBlocks = [
    new Tetro("t", {x: 4, y: 4}),
    new Tetro("j", {x: 4, y: 10}),
    new Tetro("l", {x: 4, y: 15}),
    new Tetro("i", {x: 9, y: 3}),
    new Tetro("z", {x: 9, y: 9}),
    new Tetro("s", {x: 9, y: 14}),
];

var activePiece = null,
    rotatePiece = false,
    xMovement = 0,
    yMovement = -1;

function load() {
    initCanvas();
    initWorld();
    handleKeyboard();

    start();
}

function initCanvas() {
    canvas = document.getElementsByTagName("canvas")[0];
    context = canvas.getContext("2d");

    canvas.width = worldW * (blockSize + spacing) + spacing;
    canvas.height = worldH * (blockSize + spacing) + spacing;
}

function initWorld() {
    world = [];

    for (var y = 0; y < worldH; y++) {
        world[y] = new Array(worldW);
    }

    addToWorld(new Tetro("i", {x: 1, y: 0}));
    addToWorld(new Tetro("i", {x: 5, y: 0}));
    addToWorld(new Tetro("t", {x: 1, y: 1})
            .rotate()
            .rotate());
}

function drawWorld() {
    for (var y = 0; y < worldH; y++) {
        for (var x = 0; x < worldW; x++) {
            var color = world[y][x];
            if (color) {
                drawBlock(context, {x: x, y: y}, color);
            }
        }
    }
}

function start() {
    newActivePiece();
    activePiece.color = "white";

    mozRequestAnimationFrame(gameLoop);
}

function newActivePiece() {
    activePiece = tetroGenerator(
            {x: Number.toInteger(worldW / 2),
                y: worldH - 3});
}

var frame = 0;
function gameLoop(t) {
    update(frame);
    draw();

    frame++;
    mozRequestAnimationFrame(gameLoop);
}

function update(frame) {
    // rotate sample blocks

    if (frame % 10 == 0) {
        sampleBlocks = sampleBlocks.map(function(block) {
            return block.rotate();
        });
    }

    if (frame % 5 == 0) {
        if (rotatePiece) {
            var rotatedPiece = activePiece.rotate();
            if ( ! inCollision(rotatedPiece)) {
                activePiece = rotatedPiece;
            }
        }

        if (xMovement != 0) {
            var movedPiece = activePiece.move(xMovement, 0);
            if ( ! inCollision(movedPiece)) {
                activePiece = movedPiece;
            }
        }
    }

    ascend(activePiece);
}

function ascend() {
    if ((frame % (baseSpeed - ySpeed)) == 0) {
        var movedPiece = activePiece.move(0, yMovement);
        if ( ! inCollision(movedPiece)) {
            activePiece = movedPiece;
        } else {
            addToWorld(activePiece);
            newActivePiece();
        }
    }
}

function draw() {
    clearScreen();
    drawWorld();
    //renderSampleBlocks();

    if (activePiece) {
        activePiece.draw(context, drawBlock);
    }
}

function renderSampleBlocks() {
    sampleBlocks.forEach(function(block) {
        block.draw(context, drawBlock);
    });
}

function huh() {
    for (var x = 0; x < 1000; x++) {
        for (var y = 0; y < 1000; y++) {
            if ((x ^ y) % 3 == 0) {
                drawBlock(context, {x: x, y: y} , "white");
            }
            if ((x ^ y) % 5 == 0) {
                drawBlock(context, {x: x, y: y} , "blue");
            }
            if ((x ^ y) % 7 == 0) {
                drawBlock(context, {x: x, y: y} , "orange");
            }
            if ((x ^ y) % 9 == 0) {
                drawBlock(context, {x: x, y: y} , "red");
            }
        }
    }
}

function clearScreen() {
    context.clearRect(0, 0, canvas.width, canvas.height);
}

function drawBlock(ctx, pos, style) {
    pos = toPixelPos(pos);
    if (style) {
        ctx.fillStyle = style;
    }
    ctx.fillRect(pos.x, pos.y, blockSize, blockSize);
}

function toPixelPos(pos) {
    return {
        x: spacing + (spacing + blockSize) * pos.x,
        y: spacing + (spacing + blockSize) * pos.y,
    }
}

function addToWorld(piece) {
    piece.getBlocks().forEach(function(block) {
        world[block.y][block.x] = piece.color;
    });
}

function tetroGenerator(pos) {
    var index = Number.toInteger(Math.random() * typeNames.length),
        type = typeNames[index];

    return new Tetro(type, pos);
}

function handleKeyboard() {
    window.onkeydown = function(e) {
        console.log("keycode -> " + e.keyCode);
        if (e.keyCode == 72) {
            xMovement = -1;
        } else if (e.keyCode == 76) {
            xMovement =  1;
        }

        if (e.keyCode == 74) {
            yMovement = -1;
        }

        if (e.keyCode == 75) {
            rotatePiece = true;
        }
    }
    window.onkeyup = function(e) {
        //console.log("keycode -> " + e.keyCode);
        if (e.keyCode == 72 || e.keyCode == 76) {
            xMovement = 0;
        } else if (e.keyCode == 75) {
            rotatePiece = false;
        } else if (e.keyCode == 74) {
            //yMovement =  0;
        }
    }
}

function inCollision(piece) {
    return piece.getBlocks()
        .some(function(block) {
            return outOfBounds(block) ||
                !!world[block.y][block.x];
        });
}

function outOfBounds(pos) {
    return pos.x < 0 ||
        pos.x >= worldW ||
        pos.y < 0 ||
        pos.y >= worldH;
}

<commit_msg>Restart when stacked blocks reached spawn point<commit_after>
window.onload = load;

var worldW = 17,
    worldH = 21,

    spacing = 3, // pixels
    blockSize = 20, // pixels

    canvas,
    context;

var world,
    level = 0,
    ySpeed = 1,
    baseSpeed = 20;

var sampleBlocks = [
    new Tetro("t", {x: 4, y: 4}),
    new Tetro("j", {x: 4, y: 10}),
    new Tetro("l", {x: 4, y: 15}),
    new Tetro("i", {x: 9, y: 3}),
    new Tetro("z", {x: 9, y: 9}),
    new Tetro("s", {x: 9, y: 14}),
];

var activePiece = null,
    rotatePiece = false,
    xMovement = 0,
    yMovement = -1;

function load() {
    initCanvas();
    initWorld();
    handleKeyboard();

    start();
}

function initCanvas() {
    canvas = document.getElementsByTagName("canvas")[0];
    context = canvas.getContext("2d");

    canvas.width = worldW * (blockSize + spacing) + spacing;
    canvas.height = worldH * (blockSize + spacing) + spacing;
}

function initWorld() {
    world = [];

    for (var y = 0; y < worldH; y++) {
        world[y] = new Array(worldW);
    }

    addToWorld(new Tetro("i", {x: 1, y: 0}));
    addToWorld(new Tetro("i", {x: 5, y: 0}));
    addToWorld(new Tetro("t", {x: 1, y: 1})
            .rotate()
            .rotate());
}

function drawWorld() {
    for (var y = 0; y < worldH; y++) {
        for (var x = 0; x < worldW; x++) {
            var color = world[y][x];
            if (color) {
                drawBlock(context, {x: x, y: y}, color);
            }
        }
    }
}

function start() {
    newActivePiece();
    activePiece.color = "white";

    mozRequestAnimationFrame(gameLoop);
}

function newActivePiece() {
    activePiece = tetroGenerator(
            {x: Number.toInteger(worldW / 2),
                y: worldH - 3});
}

var frame = 0;
function gameLoop(t) {
    update(frame);
    draw();

    frame++;
    mozRequestAnimationFrame(gameLoop);
}

function update(frame) {
    // rotate sample blocks

    if (frame % 10 == 0) {
        sampleBlocks = sampleBlocks.map(function(block) {
            return block.rotate();
        });
    }

    if (frame % 5 == 0) {
        if (rotatePiece) {
            var rotatedPiece = activePiece.rotate();
            if ( ! inCollision(rotatedPiece)) {
                activePiece = rotatedPiece;
            }
        }

        if (xMovement != 0) {
            var movedPiece = activePiece.move(xMovement, 0);
            if ( ! inCollision(movedPiece)) {
                activePiece = movedPiece;
            }
        }
    }

    ascend(activePiece);
}

function ascend() {
    if ((frame % (baseSpeed - ySpeed)) == 0) {
        var movedPiece = activePiece.move(0, yMovement);
        if ( ! inCollision(movedPiece)) {
            activePiece = movedPiece;
        } else {
            addToWorld(activePiece);
            newActivePiece();

            if (inCollision(activePiece)) {
                endGame();
            }
        }
    }
}

function endGame() {
    initWorld();
}

function draw() {
    clearScreen();
    drawWorld();
    //renderSampleBlocks();

    if (activePiece) {
        activePiece.draw(context, drawBlock);
    }
}

function renderSampleBlocks() {
    sampleBlocks.forEach(function(block) {
        block.draw(context, drawBlock);
    });
}

function huh() {
    for (var x = 0; x < 1000; x++) {
        for (var y = 0; y < 1000; y++) {
            if ((x ^ y) % 3 == 0) {
                drawBlock(context, {x: x, y: y} , "white");
            }
            if ((x ^ y) % 5 == 0) {
                drawBlock(context, {x: x, y: y} , "blue");
            }
            if ((x ^ y) % 7 == 0) {
                drawBlock(context, {x: x, y: y} , "orange");
            }
            if ((x ^ y) % 9 == 0) {
                drawBlock(context, {x: x, y: y} , "red");
            }
        }
    }
}

function clearScreen() {
    context.clearRect(0, 0, canvas.width, canvas.height);
}

function drawBlock(ctx, pos, style) {
    pos = toPixelPos(pos);
    if (style) {
        ctx.fillStyle = style;
    }
    ctx.fillRect(pos.x, pos.y, blockSize, blockSize);
}

function toPixelPos(pos) {
    return {
        x: spacing + (spacing + blockSize) * pos.x,
        y: spacing + (spacing + blockSize) * pos.y,
    }
}

function addToWorld(piece) {
    piece.getBlocks().forEach(function(block) {
        world[block.y][block.x] = piece.color;
    });
}

function tetroGenerator(pos) {
    var index = Number.toInteger(Math.random() * typeNames.length),
        type = typeNames[index];

    return new Tetro(type, pos);
}

function handleKeyboard() {
    window.onkeydown = function(e) {
        console.log("keycode -> " + e.keyCode);
        if (e.keyCode == 72) {
            xMovement = -1;
        } else if (e.keyCode == 76) {
            xMovement =  1;
        }

        if (e.keyCode == 74) {
            yMovement = -1;
        }

        if (e.keyCode == 75) {
            rotatePiece = true;
        }
    }
    window.onkeyup = function(e) {
        //console.log("keycode -> " + e.keyCode);
        if (e.keyCode == 72 || e.keyCode == 76) {
            xMovement = 0;
        } else if (e.keyCode == 75) {
            rotatePiece = false;
        } else if (e.keyCode == 74) {
            //yMovement =  0;
        }
    }
}

function inCollision(piece) {
    return piece.getBlocks()
        .some(function(block) {
            return outOfBounds(block) ||
                !!world[block.y][block.x];
        });
}

function outOfBounds(pos) {
    return pos.x < 0 ||
        pos.x >= worldW ||
        pos.y < 0 ||
        pos.y >= worldH;
}

<|endoftext|>


<commit_before>var app = require('express')();
var http = require('http').Server(app);
var morality = require('verbal-morality');

app.get('/level', (req, res) => {
  let score = morality(req.query.term);
  let message = ' is completely moral';
  switch(score) {
    case 1:
      message = ' is slightly immoral. Be careful, this is a pee see work environment';
      break;
    case 2:
      message = ' is immoral. You are running the risk of being fined';
      break;
    case 3:
    case 4:
    case 5:
      message = ' is significantly immmoral. A fine has been issued.';
      break;
  }
  res.send(req.query.term + message);
});

app.get('/', (req, res) => res.sendFile(__dirname + "/index.html"));

http.listen(3030, () => console.log('listening on *:3030'));
<commit_msg>saved file<commit_after>var app = require('express')();
var http = require('http').Server(app);
var morality = require('verbal-morality');

app.get('/level', (req, res) => {
  let score = morality(req.query.term);
  let message = '';
  switch(score) {
    case 1:
      message = ' is slightly immoral. Be careful, this is a pee see work environment';
      break;
    case 2:
      message = ' is immoral. You are running the risk of being fined';
      break;
    case 3:
    case 4:
    case 5:
      message = ' is significantly immmoral. A fine has been issued.';
      break;
  }
  res.send(req.query.term + message);
});

app.get('/', (req, res) => res.sendFile(__dirname + "/index.html"));

http.listen(3030, () => console.log('listening on *:3030'));
<|endoftext|>


<commit_before>/*!
 * Thrust 2010 Copyright (C) 2010 by Sven Helmberger.
 *
 * This software is licensed under the AGPL license.
 * project root for LICENSE AND README.
 *
 */
var paper, world, player;
(function($,window,undefined)
{

var FRAMES_PER_SECOND = 24;
var STEPS_PER_SECOND = 24;

var STEP_TIME = 1000 / STEPS_PER_SECOND;
var FRAME_TIME = 1000 / STEPS_PER_SECOND;

function points()
{
    var l = [];
    for (var i=0, len = arguments.length; i < len; i+=2 )
    {
        l.push( new Vector2D( arguments[i], arguments[i+1]));
    }
    return l;
}

var mouseDown;

var world;

function getParameter(name)
{
    var m = new RegExp("(?:&|\\?)" + name + "=([^&]+)(?:&|$)").exec(location.search);
    if (m)
    {
        return m[1];
    }
    else
    {
        return false;
    }
}

function convert(s)
{
    var m = /^(\d+)\:(-?\d+)$/.exec(s);
    if (m)
    {
        var level = +m[1];
        var chk = +m[2];
        if (chk != chksum(Thrust.levels[level]))
        {
            return 0;
        }

        return level;
    }

}

var $canvas, canvasOffset, animationTime = null;

window.Thrust = {
init:
    function()
    {
        if (!window.console)
        {
            window.console = {};
            var dummy = function() {};
            var names = "log debug error warn trace".split(" ");
            for ( var i = 0, len = names.length; i < len; i++)
            {
                window.console[names[i]] = dummy;
            }
        }

        var levelParam = getParameter("level");
        var level = +( convert(levelParam) || 0);

        world = new World("teh_canvas");
        world.level = level;
        world.overview = !!(getParameter("overview") || false);

        window.world = world;

        if (levelParam)
        {
            var data = JSON.parse($.cookies.get("thrust2010_data") || "{\"score\":0,\"lives\":5}");
            world.score = data.score;
            world.lives = data.lives;
        }

        var delayed = [];

        $.ajax({
            url: Thrust.levels[level],
            dataType: "xml",
            success:function(data)
            {
                var playerX = 0, playerY = 0;

                //console.debug(data);

                var svgFactories = SvgFactory.prototype.getRegistered();

                //console.debug("svgFactories = %o", svgFactories);

                $("path,rect", data.documentElement).each(function(){

                    var $elem = $(this);

                    //console.debug($elem);

                    var name = $elem.attr("inkscape:label");
                    var created = false;
                    if (name)
                    {
                        for ( var i = 0, len = svgFactories.length; i < len; i++)
                        {
                            var factory = svgFactories[i];
                            if (result = factory.create(world, $elem, name))
                            {
                                if (typeof result == "function")
                                {
                                    delayed.push(result);
                                }

                                created = true;
                                break;
                            }
                        }
                    }
                    if (!created)
                    {
                        console.info("no object created for SVG elem: %o, name=%s", $elem, name);
                    }
                });

                for ( var i = 0, len = delayed.length; i < len; i++)
                {
                    delayed[i].call(this);
                }

                var pt = world.base.pos;

                var playerX = pt.x + 25;
                var playerY = pt.y - 25 ;
                //console.debug("World box: %s", world.box);

                player = new Ship(world, playerX, playerY);
                world.player = player;

                $canvas = $("#teh_canvas");
                var off = $canvas.offset();
                canvasOffset = new Vector2D(off.left, off.top);

                //console.debug("canvasOffset = %o", canvasOffset);

                // register additional lines for level bounds
                var topLft = new Vector2D(world.box.x, world.box.y);
                var w = world.box.w;
                var h = world.box.h;
                var botRgt = new Vector2D(world.box.x + w, world.box.y + h);

                world.insertLineBox(topLft,topLft.add(w,0));
                world.insertLineBox(topLft,topLft.add(0,h));
                world.insertLineBox(botRgt,botRgt.substract(w,0));
                world.insertLineBox(botRgt,botRgt.substract(0,h));

                for ( var i = 0, len = world.objects.length; i < len; i++)
                {
                    var obj = world.objects[i];
                    obj.message("prepare");
                }

                animationTime = (new Date()).getTime();
                var lastFrame = animationTime;
                (function mainLoop()
                {
                    var time = (new Date()).getTime();

                    while (animationTime < time)
                    {
                        world.step();
                        animationTime += STEP_TIME;
                    }
                    world.step();
                    world.draw();

                    var wait = (lastFrame + FRAME_TIME) - (new Date()).getTime();
                    if (wait < 1)
                    {
                        wait = 1;
                    }
                    window.setTimeout(mainLoop, wait);
                    lastFrame = time;
                })();
            }
        });

        function thrust(ev)
        {
            var point = new Vector2D( ev.pageX , ev.pageY).substract(canvasOffset);
            player.thrust( point, mouseDown);

        }

        window.oncontextmenu = function () {
            return false;
         }

        var $doc = $(document).mousedown(function(ev)
        {
            if (ev.button == 2 || ev.ctrlKey)
            {
                var point = world.fromScreen(new Vector2D(ev.pageX,ev.pageY).substract(canvasOffset));
                player.shoot(point);
                return false;
            }
            else
            {
                mouseDown = true;
                thrust(ev);
            }
        }).mouseup(function(ev)
        {
            player.thrust(ev);
            mouseDown = false;
        }).mousemove(function(ev)
        {
            thrust(ev);
        }).keydown(function(ev)
        {
            switch(ev.keyCode)
            {
                case 84:    // T
                    var player = world.player;
                    var r = player.tractorMax;
                    var playerPos = player.pos;
                    var box = playerPos.substract(r,r);
                    box.w = box.h = r + r;
                    var objects = world.rtree.search(box);

                    for ( var i = 0, len = objects.length; i < len; i++)
                    {
                        var obj = objects[i];
                        if (obj.type === "cargo")
                        {
                            var dist = playerPos.substract(obj.pos).length();
                            if (obj.connected)
                            {
                                obj.connected = false;
                                player.connected = null;
                            }
                            else if (dist < r)
                            {
                                obj.connected = true;
                                obj.resting = false;
                                player.connected = obj;
                            }
                        }
                    }
                    break;
                default:
                    //console.debug("key = %d", ev.keyCode);
                    break;
            }
        });

        var opts = ["<option value=\"\">Choose Level</option>"];
        for ( var i = 0, len = Thrust.levels.length; i < len; i++)
        {
            var level = Thrust.levels[i];
            opts.push("<option value=\"", i , ":" , chksum(level), "\">", level, "</option>" );
        }

        $("#levelSelector").change(function(ev){
            document.location.href = "index.html?level=" + this.value;
        }).append($(opts.join("")));
    }
};

$(Thrust.init);

})(jQuery,window);
<commit_msg>try one-button interface<commit_after>/*!
 * Thrust 2010 Copyright (C) 2010 by Sven Helmberger.
 *
 * This software is licensed under the AGPL license.
 * project root for LICENSE AND README.
 *
 */
var paper, world, player;
(function($,window,undefined)
{

var FRAMES_PER_SECOND = 24;
var STEPS_PER_SECOND = 24;

var STEP_TIME = 1000 / STEPS_PER_SECOND;
var FRAME_TIME = 1000 / STEPS_PER_SECOND;

function points()
{
    var l = [];
    for (var i=0, len = arguments.length; i < len; i+=2 )
    {
        l.push( new Vector2D( arguments[i], arguments[i+1]));
    }
    return l;
}

var mouseDown;

var world;

function getParameter(name)
{
    var m = new RegExp("(?:&|\\?)" + name + "=([^&]+)(?:&|$)").exec(location.search);
    if (m)
    {
        return m[1];
    }
    else
    {
        return false;
    }
}

function convert(s)
{
    var m = /^(\d+)\:(-?\d+)$/.exec(s);
    if (m)
    {
        var level = +m[1];
        var chk = +m[2];
        if (chk != chksum(Thrust.levels[level]))
        {
            return 0;
        }

        return level;
    }

}

var $canvas, canvasOffset, animationTime = null, mouseTimer, mousePoint;

function tractOrNot(player, obj, r)
{
    var dist = player.pos.substract(obj.pos).length();
    if (obj.connected)
    {
        obj.connected = false;
        player.connected = null;
    }
    else if (dist < r)
    {
        obj.connected = true;
        obj.resting = false;
        player.connected = obj;
    }
}

window.Thrust = {
init:
    function()
    {
        if (!window.console)
        {
            window.console = {};
            var dummy = function() {};
            var names = "log debug error warn trace".split(" ");
            for ( var i = 0, len = names.length; i < len; i++)
            {
                window.console[names[i]] = dummy;
            }
        }

        var levelParam = getParameter("level");
        var level = +( convert(levelParam) || 0);

        world = new World("teh_canvas");
        world.level = level;
        world.overview = !!(getParameter("overview") || false);

        window.world = world;

        if (levelParam)
        {
            var data = JSON.parse($.cookies.get("thrust2010_data") || "{\"score\":0,\"lives\":5}");
            world.score = data.score;
            world.lives = data.lives;
        }

        var delayed = [];

        $.ajax({
            url: Thrust.levels[level],
            dataType: "xml",
            success:function(data)
            {
                var playerX = 0, playerY = 0;

                //console.debug(data);

                var svgFactories = SvgFactory.prototype.getRegistered();

                //console.debug("svgFactories = %o", svgFactories);

                $("path,rect", data.documentElement).each(function(){

                    var $elem = $(this);

                    //console.debug($elem);

                    var name = $elem.attr("inkscape:label");
                    var created = false;
                    if (name)
                    {
                        for ( var i = 0, len = svgFactories.length; i < len; i++)
                        {
                            var factory = svgFactories[i];
                            if (result = factory.create(world, $elem, name))
                            {
                                if (typeof result == "function")
                                {
                                    delayed.push(result);
                                }

                                created = true;
                                break;
                            }
                        }
                    }
                    if (!created)
                    {
                        console.info("no object created for SVG elem: %o, name=%s", $elem, name);
                    }
                });

                for ( var i = 0, len = delayed.length; i < len; i++)
                {
                    delayed[i].call(this);
                }

                var pt = world.base.pos;

                var playerX = pt.x + 25;
                var playerY = pt.y - 25 ;
                //console.debug("World box: %s", world.box);

                player = new Ship(world, playerX, playerY);
                world.player = player;

                $canvas = $("#teh_canvas");
                var off = $canvas.offset();
                canvasOffset = new Vector2D(off.left, off.top);

                //console.debug("canvasOffset = %o", canvasOffset);

                // register additional lines for level bounds
                var topLft = new Vector2D(world.box.x, world.box.y);
                var w = world.box.w;
                var h = world.box.h;
                var botRgt = new Vector2D(world.box.x + w, world.box.y + h);

                world.insertLineBox(topLft,topLft.add(w,0));
                world.insertLineBox(topLft,topLft.add(0,h));
                world.insertLineBox(botRgt,botRgt.substract(w,0));
                world.insertLineBox(botRgt,botRgt.substract(0,h));

                for ( var i = 0, len = world.objects.length; i < len; i++)
                {
                    var obj = world.objects[i];
                    obj.message("prepare");
                }

                animationTime = (new Date()).getTime();
                var lastFrame = animationTime;
                (function mainLoop()
                {
                    var time = (new Date()).getTime();

                    while (animationTime < time)
                    {
                        world.step();
                        animationTime += STEP_TIME;
                    }
                    world.step();
                    world.draw();

                    var wait = (lastFrame + FRAME_TIME) - (new Date()).getTime();
                    if (wait < 1)
                    {
                        wait = 1;
                    }
                    window.setTimeout(mainLoop, wait);
                    lastFrame = time;
                })();
            }
        });

        function thrust(ev)
        {
            var point = new Vector2D( ev.pageX , ev.pageY).substract(canvasOffset);
            player.thrust( point, mouseDown);

        }

        window.oncontextmenu = function () {
            return false;
         }

        var $doc = $(document).mousedown(function(ev)
        {
            mousePoint = world.fromScreen(new Vector2D(ev.pageX,ev.pageY).substract(canvasOffset));
            mouseTimer = setTimeout(function()
            {
                mouseTimer = null;
                mouseDown = true;
                thrust(ev);
            }, 150);
        }).mouseup(function(ev)
        {
            if (mouseTimer)
            {
                clearTimeout(mouseTimer);
                if (mousePoint)
                {
                    var r = world.player.tractorMax * .66;
                    var d = r+r;
                    var candidates = world.rtree.search({x: world.player.pos.x - r, y: world.player.pos.y - r, w: d, h: d });

                    for ( var i = 0, len = candidates.length; i < len; i++)
                    {
                        var obj = candidates[i];
                        if (obj.type === "cargo")
                        {
                            tractOrNot(world.player, obj, r);
                            return;
                        }
                    }

                    player.shoot(mousePoint);
                    mousePoint = null;
                }
            }

            player.thrust(ev);
            mouseDown = false;
        }).mousemove(function(ev)
        {
            thrust(ev);
        }).keydown(function(ev)
        {
            switch(ev.keyCode)
            {
                case 84:    // T
                    var player = world.player;
                    var r = player.tractorMax;
                    var playerPos = player.pos;
                    var box = playerPos.substract(r,r);
                    box.w = box.h = r + r;
                    var objects = world.rtree.search(box);

                    for ( var i = 0, len = objects.length; i < len; i++)
                    {
                        var obj = objects[i];
                        if (obj.type === "cargo")
                        {
                            tractOrNot(world.player, obj, r);
                        }
                    }
                    break;
                default:
                    //console.debug("key = %d", ev.keyCode);
                    break;
            }
        });

        var opts = ["<option value=\"\">Choose Level</option>"];
        for ( var i = 0, len = Thrust.levels.length; i < len; i++)
        {
            var level = Thrust.levels[i];
            opts.push("<option value=\"", i , ":" , chksum(level), "\">", level, "</option>" );
        }

        $("#levelSelector").change(function(ev){
            document.location.href = "index.html?level=" + this.value;
        }).append($(opts.join("")));
    }
};

$(Thrust.init);

})(jQuery,window);
<|endoftext|>


<commit_before>'use strict';

const uuid = require('uuid');
const uuidv1 = require('uuid/v1');
const uuidv4 = require('uuid/v4');
const uuidv5 = require('uuid/v5');
const baseX = require('base-x');
const base62 = baseX('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
const OUTPUT_LENGTH = 22;
const UUID_LENGTH = 32;

if (typeof Buffer === 'undefined') {
	// import buffer module for use in browser - browserify and perhaps webpack
	// should do this automatically, but otherwise we'll pull it in here
	Buffer = require('buffer').Buffer;
}

class UUID62 {
	constructor() {
		this.base = base62;
		// expose underlying methods for convenience (matches uuid-base62)
		this.uuid = uuid;
		this.baseX = baseX;
		// pre-defined v5/v3 namespaces
		this.URL = '3h8Pgc0Wb7WH6HsyG77m40';
		this.DNS = '3h8PgalTIPNcNhUD4ZbIKY';
	}

	get customBase() {
		return this.base;
	}

	set customBase(base) {
		this.base = base;
	}

	get length() {
		return OUTPUT_LENGTH;
	}

	get uuidLength() {
		return UUID_LENGTH;
	}

	v4() {
		const args = Array.prototype.slice.call(arguments);
		if (!args[1]) {
			// make sure we use a buffer to avoid getting a uuid with dashes
			args[1] = new Buffer(16);
		}
		const id = uuidv4.apply(this, args);
		return this.encode(id);
	}

	v5() {
		const args = Array.prototype.slice.call(arguments);
		if (typeof args[1] === 'string' && /^[0-9A-Za-z]{22}$/.test(args[1])) {
			args[1] = this.decode(args[1]);
		}
		const id = uuidv5.apply(this, args);
		return this.encode(id);
	}

	v1() {
		const args = Array.prototype.slice.call(arguments);
		if (!args[1]) {
			// make sure we use a buffer to avoid getting a uuid with dashes
			args[1] = new Buffer(16);
		}
		const id = uuidv1.apply(this, args);
		return this.encode(id);
	}

	encode(input, encoding) {
		encoding = encoding || 'hex';
		if (typeof input === 'string') {
			// remove the dashes to save some space
			input = new Buffer(input.replace(/-/g, ''), encoding);
		}
		return ensureLength(this.base.encode(input), OUTPUT_LENGTH);
	}

	decode(input, encoding) {
		encoding = encoding || 'hex';
		const res = ensureLength(
			new Buffer(this.base.decode(input)).toString(encoding),
			UUID_LENGTH
		);
		// insert dashes on return
		return `${res.slice(0, 8)}-${res.slice(8, 12)}-${res.slice(12, 16)}-${res.slice(16, 20)}-${res.slice(20)}`;
	}
}

function ensureLength(input, targetLength) {
	input = input.toString();
	return `${'0'.repeat(32)}${input}`.slice(-targetLength);
}

module.exports = new UUID62();
<commit_msg>declare Buffer in module scope<commit_after>'use strict';

const uuid = require('uuid');
const uuidv1 = require('uuid/v1');
const uuidv4 = require('uuid/v4');
const uuidv5 = require('uuid/v5');
const baseX = require('base-x');
const base62 = baseX('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
const OUTPUT_LENGTH = 22;
const UUID_LENGTH = 32;
let Buffer = (global) ? global.Buffer : undefined;

if (typeof Buffer === 'undefined') {
	// import buffer module for use in browser - browserify and perhaps webpack
	// should do this automatically, but otherwise we'll pull it in here
	Buffer = require('buffer').Buffer;
}

class UUID62 {
	constructor() {
		this.base = base62;
		// expose underlying methods for convenience (matches uuid-base62)
		this.uuid = uuid;
		this.baseX = baseX;
		// pre-defined v5/v3 namespaces
		this.URL = '3h8Pgc0Wb7WH6HsyG77m40';
		this.DNS = '3h8PgalTIPNcNhUD4ZbIKY';
	}

	get customBase() {
		return this.base;
	}

	set customBase(base) {
		this.base = base;
	}

	get length() {
		return OUTPUT_LENGTH;
	}

	get uuidLength() {
		return UUID_LENGTH;
	}

	v4() {
		const args = Array.prototype.slice.call(arguments);
		if (!args[1]) {
			// make sure we use a buffer to avoid getting a uuid with dashes
			args[1] = new Buffer(16);
		}
		const id = uuidv4.apply(this, args);
		return this.encode(id);
	}

	v5() {
		const args = Array.prototype.slice.call(arguments);
		if (typeof args[1] === 'string' && /^[0-9A-Za-z]{22}$/.test(args[1])) {
			args[1] = this.decode(args[1]);
		}
		const id = uuidv5.apply(this, args);
		return this.encode(id);
	}

	v1() {
		const args = Array.prototype.slice.call(arguments);
		if (!args[1]) {
			// make sure we use a buffer to avoid getting a uuid with dashes
			args[1] = new Buffer(16);
		}
		const id = uuidv1.apply(this, args);
		return this.encode(id);
	}

	encode(input, encoding) {
		encoding = encoding || 'hex';
		if (typeof input === 'string') {
			// remove the dashes to save some space
			input = new Buffer(input.replace(/-/g, ''), encoding);
		}
		return ensureLength(this.base.encode(input), OUTPUT_LENGTH);
	}

	decode(input, encoding) {
		encoding = encoding || 'hex';
		const res = ensureLength(
			new Buffer(this.base.decode(input)).toString(encoding),
			UUID_LENGTH
		);
		// insert dashes on return
		return `${res.slice(0, 8)}-${res.slice(8, 12)}-${res.slice(12, 16)}-${res.slice(16, 20)}-${res.slice(20)}`;
	}
}

function ensureLength(input, targetLength) {
	input = input.toString();
	return `${'0'.repeat(32)}${input}`.slice(-targetLength);
}

module.exports = new UUID62();
<|endoftext|>


<commit_before>const express = require('express');
const expressLogging = require('express-logging');
const logger = require('logops');
const bodyParser = require('body-parser');
logger.setLevel('DEBUG');
const fs = require('fs');
const redis = require('redis');
const Promise = require('bluebird');
const REDIS_PORT = process.env.REDIS_PORT || 6379;

Promise.promisifyAll(redis.RedisClient.prototype);

const app = express();
const redisClient = redis.createClient(REDIS_PORT);

redisClient.on("error", function (err) {
    console.log("Redis error " + err);
});

app.use(expressLogging(logger));
app.use(express.static('public'));
app.use(bodyParser.json());

function saveData(type, req, res) {
    var timestamp = 'Timestamp' in req.body ? parseInt(req.body.Timestamp) : Date.now();
    redisClient.zadd(type, timestamp, JSON.stringify(req.body), function(err, reply) {
        if (err) {
            logger.error(err);
            res.status(500).send(err);
        } else {
            res.sendStatus(200);
        }
    });
}

function sendLatestData(type, req, res) {
    if (req.query.since) {
        redisClient.zrangebyscore(type, req.query.since, '+inf', 'WITHSCORES', function(err, reply) {
            if (err) {
                logger.error(err);
                res.status(500).send(err);
            } else {
                var items = [];
                for (var i = 0; i < reply.length/2; i++) {
                    var data = JSON.parse(reply[i*2]);
                    data.Timestamp = parseInt(reply[i*2+1]);
                    items.push(data)
                }
                res.status(200).send(items);
            }
        });
    } else {
        redisClient.zrevrange(type, 0, 1, 'WITHSCORES', function(err, reply) {
            if (err) {
                logger.error(err);
                res.status(500).send(err);
            } else {
                var data = JSON.parse(reply[0]);
                data.Timestamp = parseInt(reply[1]);
                res.status(200).send(data);
            }
        });
    }
}

function dewpoint(humidity, temperature) {
    var a, b;
    if (temperature >= 0) {
        a = 7.5;
        b = 237.3;
    } else {
        a = 7.6;
        b = 240.7;
    }

    var sdd = 6.1078 * Math.pow(10, (a * temperature) / (b + temperature));
    var dd = sdd * (humidity / 100);
    v = Math.log(dd / 6.1078) / Math.log(10);
    return (b * v) / (a - v);
}

app.post('/api', function(req, res) {
    if (req.body.Type == 'PTU') {
        saveData('ptu', req, res);
    } else if (req.body.Type == 'Wind') {
        saveData('wind', req, res);
    } else if (req.body.Type == 'Rain') {
        saveData('rain', req, res);
    } else if (req.body.Type == 'RainTrigger') {
        saveData('raintrigger', req, res);
    } else if (req.body.Type == 'Status') {
        saveData('status', req, res);
    } else if (req.body.Type == 'Radar') {
        saveData('radar', req, res);
    } else {
        res.sendStatus(400);
        return;
    }
});

app.get('/api/ptu', function(req, res) {
    sendLatestData('ptu', req, res);
});

app.get('/api/wind', function(req, res) {
    sendLatestData('wind', req, res);
});

app.get('/api/rain', function(req, res) {
    sendLatestData('rain', req, res);
});

app.get('/api/raintrigger', function(req, res) {
    sendLatestData('raintrigger', req, res);
});

app.get('/api/status', function(req, res) {
    sendLatestData('status', req, res);
});

app.get('/api/radar', function(req, res) {
    sendLatestData('radar', req, res);
});

app.get('/api/weather', function(req, res) {
    var a = redisClient.zrevrangeAsync('ptu', 0, 0);
    var b = redisClient.zrevrangeAsync('wind', 0, 0);
    var c = redisClient.zrevrangeAsync('rain', 0, 0);

    Promise.join(a, b, c, function(ptureply, windreply, rainreply) {
        if (ptureply.length == 0 || windreply.length == 0 || rainreply.length == 0) {
            logger.error('Reading Redis failed');
            res.status(500).send('{"error":"Reading redis failed"}');
            return;
        }
        var ptu = JSON.parse(ptureply[0]);
        var wind = JSON.parse(windreply[0]);
        var rain = JSON.parse(rainreply[0]);

        var data = {
            temperature: ptu.Data.Temperature.Ambient[0],
            humidity: ptu.Data.Humidity[0],
            dewpoint: parseInt(dewpoint(ptu.Data.Humidity[0], ptu.Data.Temperature.Ambient[0])*100)/100,
            pressure: ptu.Data.Pressure[0],
            windspeed: wind.Data.Speed.average[0],
            windgust: wind.Data.Speed.limits[1][0],
            winddir: wind.Data.Direction.average[0],
            rainrate: rain.Data.Rain.Intensity[0],
            cloudcover: 0,
            skytemperature: 0,
            skyquality: 0
        };
        res.json(data);
    }).catch(function(err) {
        logger.error('Reading Redis failed', err);
        res.status(500).send('{"error":"Reading redis failed: ' + err+  '"}');
    });
});

var server = app.listen(9001, function() {
    var host = server.address().address;
    var port = server.address().port;

    logger.info('koma-weather-server listening at http://%s:%s', host, port);
}).on('error', function(err) {
    logger.error(err);
});
<commit_msg>Add endpoint for cloud data<commit_after>const express = require('express');
const expressLogging = require('express-logging');
const logger = require('logops');
const bodyParser = require('body-parser');
logger.setLevel('DEBUG');
const fs = require('fs');
const redis = require('redis');
const Promise = require('bluebird');
const REDIS_PORT = process.env.REDIS_PORT || 6379;

Promise.promisifyAll(redis.RedisClient.prototype);

const app = express();
const redisClient = redis.createClient(REDIS_PORT);

redisClient.on("error", function (err) {
    console.log("Redis error " + err);
});

app.use(expressLogging(logger));
app.use(express.static('public'));
app.use(bodyParser.json());

function saveData(type, req, res) {
    var timestamp = 'Timestamp' in req.body ? parseInt(req.body.Timestamp) : Date.now();
    redisClient.zadd(type, timestamp, JSON.stringify(req.body), function(err, reply) {
        if (err) {
            logger.error(err);
            res.status(500).send(err);
        } else {
            res.sendStatus(200);
        }
    });
}

function sendLatestData(type, req, res) {
    if (req.query.since) {
        redisClient.zrangebyscore(type, req.query.since, '+inf', 'WITHSCORES', function(err, reply) {
            if (err) {
                logger.error(err);
                res.status(500).send(err);
            } else {
                var items = [];
                for (var i = 0; i < reply.length/2; i++) {
                    var data = JSON.parse(reply[i*2]);
                    data.Timestamp = parseInt(reply[i*2+1]);
                    items.push(data)
                }
                res.status(200).send(items);
            }
        });
    } else {
        redisClient.zrevrange(type, 0, 1, 'WITHSCORES', function(err, reply) {
            if (err) {
                logger.error(err);
                res.status(500).send(err);
            } else {
                var data = JSON.parse(reply[0]);
                data.Timestamp = parseInt(reply[1]);
                res.status(200).send(data);
            }
        });
    }
}

function dewpoint(humidity, temperature) {
    var a, b;
    if (temperature >= 0) {
        a = 7.5;
        b = 237.3;
    } else {
        a = 7.6;
        b = 240.7;
    }

    var sdd = 6.1078 * Math.pow(10, (a * temperature) / (b + temperature));
    var dd = sdd * (humidity / 100);
    v = Math.log(dd / 6.1078) / Math.log(10);
    return (b * v) / (a - v);
}

app.post('/api', function(req, res) {
    if (req.body.Type == 'PTU') {
        saveData('ptu', req, res);
    } else if (req.body.Type == 'Wind') {
        saveData('wind', req, res);
    } else if (req.body.Type == 'Rain') {
        saveData('rain', req, res);
    } else if (req.body.Type == 'RainTrigger') {
        saveData('raintrigger', req, res);
    } else if (req.body.Type == 'Status') {
        saveData('status', req, res);
    } else if (req.body.Type == 'Radar') {
        saveData('radar', req, res);
    } else if (req.body.Type == 'Cloud') {
        saveData('cloud', req, res);
    } else {
        res.sendStatus(400);
        return;
    }
});

app.get('/api/ptu', function(req, res) {
    sendLatestData('ptu', req, res);
});

app.get('/api/wind', function(req, res) {
    sendLatestData('wind', req, res);
});

app.get('/api/rain', function(req, res) {
    sendLatestData('rain', req, res);
});

app.get('/api/raintrigger', function(req, res) {
    sendLatestData('raintrigger', req, res);
});

app.get('/api/status', function(req, res) {
    sendLatestData('status', req, res);
});

app.get('/api/radar', function(req, res) {
    sendLatestData('radar', req, res);
});

app.get('/api/cloud', function(req, res) {
    sendLatestData('cloud', req, res);
});

app.get('/api/weather', function(req, res) {
    var a = redisClient.zrevrangeAsync('ptu', 0, 0);
    var b = redisClient.zrevrangeAsync('wind', 0, 0);
    var c = redisClient.zrevrangeAsync('rain', 0, 0);

    Promise.join(a, b, c, function(ptureply, windreply, rainreply) {
        if (ptureply.length == 0 || windreply.length == 0 || rainreply.length == 0) {
            logger.error('Reading Redis failed');
            res.status(500).send('{"error":"Reading redis failed"}');
            return;
        }
        var ptu = JSON.parse(ptureply[0]);
        var wind = JSON.parse(windreply[0]);
        var rain = JSON.parse(rainreply[0]);

        var data = {
            temperature: ptu.Data.Temperature.Ambient[0],
            humidity: ptu.Data.Humidity[0],
            dewpoint: parseInt(dewpoint(ptu.Data.Humidity[0], ptu.Data.Temperature.Ambient[0])*100)/100,
            pressure: ptu.Data.Pressure[0],
            windspeed: wind.Data.Speed.average[0],
            windgust: wind.Data.Speed.limits[1][0],
            winddir: wind.Data.Direction.average[0],
            rainrate: rain.Data.Rain.Intensity[0],
            cloudcover: 0,
            skytemperature: 0,
            skyquality: 0
        };
        res.json(data);
    }).catch(function(err) {
        logger.error('Reading Redis failed', err);
        res.status(500).send('{"error":"Reading redis failed: ' + err+  '"}');
    });
});

var server = app.listen(9001, function() {
    var host = server.address().address;
    var port = server.address().port;

    logger.info('koma-weather-server listening at http://%s:%s', host, port);
}).on('error', function(err) {
    logger.error(err);
});
<|endoftext|>


<commit_before>var state = require('./state');
var utils = require("@/utils");

var default_element_name = 'element';
var template_escape = {"\\": "\\\\", "\n": "\\n", "\r": "\\r", "'": "\\'"};
var render_escape = {'&': '&', '"': '"', '<': '<', '>': '>'};

exports.state = state.state;

/**
 * Initialize the View module instance.
 *
 * @public
*/
exports.init = function () {
    var self = this;

    self._config = self._config || {};

    this.templates = {};

    // create and render the template
    if (self._config.templates) {

        var tmpl;
        self._config.defaultTemplate = self._config.defaultTemplate || Object.keys(self._config.templates)[0];

        for (var tmplKey in self._config.templates) {
            tmpl = self._config.templates[tmplKey];

            self.templates[tmplKey] = {
                'to': tmpl.to,
                'e': tmpl.dontEscape,
                'k': tmpl.leaveKeys,
                'f': default_escape_fn,
                '_elmName': tmpl.element || default_element_name,
                'element': '[data-' + (tmpl.element || default_element_name) + ']',
                'elements': {}
            };

            // add page selector to template
            if (tmpl.pages) {
                self.templates[tmplKey].pages.page = '_page_' + self._name;
            }

            // create template function
            if (!engine.markup[tmpl.html]) {
                return self.log('E', 'Template markup "' + tmpl.html + '" not found.');
            }
            self.templates[tmplKey].render = createTemplate(engine.markup[tmpl.html]);

            // auto render template
            if (tmpl.render) {
                draw.call(self, null, { template: tmplKey, data: {} });
            }
        }
    }

    // setup states
    if (self._config.states) {

        // create states cache
        self.states = {};

        // sage state in cache
        for (var stateName in self._config.states) {
            self.states[stateName] = self._config.states[stateName];
        }
    }
};

function draw (renderObj) {

    var self = this;
    // set document title
    if (self._config.title) {
        document.title = self._config.title;
    }
    renderObj = renderObj || {};

    // the template must exist
    var template = self.templates[renderObj.template || self._config.defaultTemplate];
    if (!template) {
        return;
    }

    var dontEscape = !!renderObj.dontEscape;
    var leaveKeys = !!renderObj.leaveKeys;
    var clearList = renderObj.clear === false ? false : true;
    var insertPosition = renderObj.position || template.position || 'beforeend';

    // prepare render data
    template.data = renderObj.data;

    // render page class name
    if (template.page) {
        template.data.page = template.page;
    }

    // create html
    template.html = template.render(renderObj.data, dontEscape, leaveKeys);

    // get dom parent
    if (typeof template.to === 'string') {
        template._to = template.to;
    }
    if (typeof template._to === 'string') {
        template.to = document.querySelector(template._to);
    }

    // render html
    if (template.to) {
        if (clearList) {
            template.to.innerHTML = '';
        }

        // append dom events
        if (!self._config.domEvents) {
            template.to.insertAdjacentHTML(insertPosition, template.html);
        } else {
            var tmpDiv = document.createElement('div');
            tmpDiv.innerHTML = template.html;

            setupDomEventFlow.call(self, tmpDiv, renderObj.data);

            var children = tmpDiv.children;
            for (var i = 0, l = children.length; i < l; ++i) {
                template.to.appendChild(document.adoptNode(children[0]));
            }
        }
    }

    // write to render done stream
    setTimeout(function() {
        self.flow("renderedDOM").write(null, renderObj);

    if (self._name === "app_builder_layout") {
        console.log(">");
        console.log(E.instances.app_builder);
    }
    }, 1000);
    //(function () {
    //});
}

/**
 * Render data to the HTML template.
 *
 * @public
 * @param {object} The event object.
 * @param {object} The data object.
*/
exports.render = function (stream) {
    stream.data([this, draw]);
    stream.error(function (error) {
        return;
    });
};

/**
 * Escape html chars.
 *
 * @private
 * @param {object} The template object.
 * @param {object} The data object.
 * @param {string} The data key.
*/
function default_escape_fn (data, key, dont_escape_html, leaveKeys) {

    // get options
    dont_escape_html = dont_escape_html || this.e;
    leaveKeys = leaveKeys || this.k;

    // get the string value
    str = key.indexOf('.') > 0 ? utils.path(key, data) : (data[key] || null);

    // if str is null or undefined
    str = str === null ? (leaveKeys ? '{' + key + '}' : '') : str;

    // render a nested view
    if (typeof str === 'object' && this.nested && this._.view[this.nested[key]]) {
        var tmpl = this.tmpls[this.nested[key]];

        // render nested view and don't append to the dom
        tmpl.render && tmpl.render(str, dont_escape_html, leaveKeys, true);

        // get html of rendered view
        str = tmpl.html || '';

        // don't escape html chars
        dont_escape_html = true;

    // make sure str is a string
    } else {
        str += '';
    }

    // escape html chars
    if (!dont_escape_html) {
        return str.replace(/[&\"<>]/g, function(_char) {
            return render_escape[_char];
        });
    }

    return str;
}

/**
 * Create a template function.
 * Heavily inspired by the https://github.com/muut/riotjs render method.
 *
 * @private
 * @param {string} The HTML string.
*/
function createTemplate (tmpl) {
    return new Function("_", "e", "k", "_=_||{};return '" +
        (tmpl || '').replace(/[\\\n\r']/g, function(_char) {
            return template_escape[_char];
        }).replace(/{\s*([\w\.]+)\s*}/g, "' + this.f(_,'$1',e,k) + '") + "'"
    );
}

/**
 * Setup the user (DOM) event flow.
 *
 * @private
 * @param {object} The moule instnace.
*/
function setupDomEventFlow (scope, data) {

    var self = this;

    if (!self._config || !self._config.domEvents) {
        return;
    }

    var events = self._config.domEvents;

    for (var i = 0, l = events.length, event, stream; i < l; ++i) {
        event = events[i];

        // handle element config
        if (event.element) {
            event.selector = "[data-element='" + event.element + "']";
            delete event.element;
        }

        var elms = scope.querySelectorAll(event.selector);
        if (elms) {
            // create event stream
            stream = self.flow(event.flow);
            stream.context = {
                renderData: data,
                dontPrevent: event.dontPrevent
            };

            for (var e = 0; e < elms.length; ++e) {
                elms[e].addEventListener(event.on, domEventListenerClosure(stream, elms, elms[e], data));
            }
        }
    }
}

function domEventListenerClosure (stream, elms, currentElement, data) {
    return function (event) {
        // dont prevent default browser actions
        if (!stream.context.dontPrevent) {
            event.preventDefault();
        }

        stream.write(null, {
            event: event,
            elms: elms,
            target: currentElement,
            item: data
        });
    };
}
<commit_msg>Send data in an array when calling utils.path<commit_after>var state = require('./state');
var utils = require("@/utils");

var default_element_name = 'element';
var template_escape = {"\\": "\\\\", "\n": "\\n", "\r": "\\r", "'": "\\'"};
var render_escape = {'&': '&', '"': '"', '<': '<', '>': '>'};

exports.state = state.state;

/**
 * Initialize the View module instance.
 *
 * @public
*/
exports.init = function () {
    var self = this;

    self._config = self._config || {};

    this.templates = {};

    // create and render the template
    if (self._config.templates) {

        var tmpl;
        self._config.defaultTemplate = self._config.defaultTemplate || Object.keys(self._config.templates)[0];

        for (var tmplKey in self._config.templates) {
            tmpl = self._config.templates[tmplKey];

            self.templates[tmplKey] = {
                'to': tmpl.to,
                'e': tmpl.dontEscape,
                'k': tmpl.leaveKeys,
                'f': default_escape_fn,
                '_elmName': tmpl.element || default_element_name,
                'element': '[data-' + (tmpl.element || default_element_name) + ']',
                'elements': {}
            };

            // add page selector to template
            if (tmpl.pages) {
                self.templates[tmplKey].pages.page = '_page_' + self._name;
            }

            // create template function
            if (!engine.markup[tmpl.html]) {
                return self.log('E', 'Template markup "' + tmpl.html + '" not found.');
            }
            self.templates[tmplKey].render = createTemplate(engine.markup[tmpl.html]);

            // auto render template
            if (tmpl.render) {
                draw.call(self, null, { template: tmplKey, data: {} });
            }
        }
    }

    // setup states
    if (self._config.states) {

        // create states cache
        self.states = {};

        // sage state in cache
        for (var stateName in self._config.states) {
            self.states[stateName] = self._config.states[stateName];
        }
    }
};

function draw (renderObj) {

    var self = this;
    // set document title
    if (self._config.title) {
        document.title = self._config.title;
    }
    renderObj = renderObj || {};

    // the template must exist
    var template = self.templates[renderObj.template || self._config.defaultTemplate];
    if (!template) {
        return;
    }

    var dontEscape = !!renderObj.dontEscape;
    var leaveKeys = !!renderObj.leaveKeys;
    var clearList = renderObj.clear === false ? false : true;
    var insertPosition = renderObj.position || template.position || 'beforeend';

    // prepare render data
    template.data = renderObj.data;

    // render page class name
    if (template.page) {
        template.data.page = template.page;
    }

    // create html
    template.html = template.render(renderObj.data, dontEscape, leaveKeys);

    // get dom parent
    if (typeof template.to === 'string') {
        template._to = template.to;
    }
    if (typeof template._to === 'string') {
        template.to = document.querySelector(template._to);
    }

    // render html
    if (template.to) {
        if (clearList) {
            template.to.innerHTML = '';
        }

        // append dom events
        if (!self._config.domEvents) {
            template.to.insertAdjacentHTML(insertPosition, template.html);
        } else {
            var tmpDiv = document.createElement('div');
            tmpDiv.innerHTML = template.html;

            setupDomEventFlow.call(self, tmpDiv, renderObj.data);

            var children = tmpDiv.children;
            for (var i = 0, l = children.length; i < l; ++i) {
                template.to.appendChild(document.adoptNode(children[0]));
            }
        }
    }

    // write to render done stream
    setTimeout(function() {
        self.flow("renderedDOM").write(null, renderObj);

    if (self._name === "app_builder_layout") {
        console.log(">");
        console.log(E.instances.app_builder);
    }
    }, 1000);
    //(function () {
    //});
}

/**
 * Render data to the HTML template.
 *
 * @public
 * @param {object} The event object.
 * @param {object} The data object.
*/
exports.render = function (stream) {
    stream.data([this, draw]);
    stream.error(function (error) {
        return;
    });
};

/**
 * Escape html chars.
 *
 * @private
 * @param {object} The template object.
 * @param {object} The data object.
 * @param {string} The data key.
*/
function default_escape_fn (data, key, dont_escape_html, leaveKeys) {

    // get options
    dont_escape_html = dont_escape_html || this.e;
    leaveKeys = leaveKeys || this.k;

    // get the string value
    str = key.indexOf('.') > 0 ? utils.path(key, [data]) : (data[key] || null);

    // if str is null or undefined
    str = str === null ? (leaveKeys ? '{' + key + '}' : '') : str;

    // render a nested view
    if (typeof str === 'object' && this.nested && this._.view[this.nested[key]]) {
        var tmpl = this.tmpls[this.nested[key]];

        // render nested view and don't append to the dom
        tmpl.render && tmpl.render(str, dont_escape_html, leaveKeys, true);

        // get html of rendered view
        str = tmpl.html || '';

        // don't escape html chars
        dont_escape_html = true;

    // make sure str is a string
    } else {
        str += '';
    }

    // escape html chars
    if (!dont_escape_html) {
        return str.replace(/[&\"<>]/g, function(_char) {
            return render_escape[_char];
        });
    }

    return str;
}

/**
 * Create a template function.
 * Heavily inspired by the https://github.com/muut/riotjs render method.
 *
 * @private
 * @param {string} The HTML string.
*/
function createTemplate (tmpl) {
    return new Function("_", "e", "k", "_=_||{};return '" +
        (tmpl || '').replace(/[\\\n\r']/g, function(_char) {
            return template_escape[_char];
        }).replace(/{\s*([\w\.]+)\s*}/g, "' + this.f(_,'$1',e,k) + '") + "'"
    );
}

/**
 * Setup the user (DOM) event flow.
 *
 * @private
 * @param {object} The moule instnace.
*/
function setupDomEventFlow (scope, data) {

    var self = this;

    if (!self._config || !self._config.domEvents) {
        return;
    }

    var events = self._config.domEvents;

    for (var i = 0, l = events.length, event, stream; i < l; ++i) {
        event = events[i];

        // handle element config
        if (event.element) {
            event.selector = "[data-element='" + event.element + "']";
            delete event.element;
        }

        var elms = scope.querySelectorAll(event.selector);
        if (elms) {
            // create event stream
            stream = self.flow(event.flow);
            stream.context = {
                renderData: data,
                dontPrevent: event.dontPrevent
            };

            for (var e = 0; e < elms.length; ++e) {
                elms[e].addEventListener(event.on, domEventListenerClosure(stream, elms, elms[e], data));
            }
        }
    }
}

function domEventListenerClosure (stream, elms, currentElement, data) {
    return function (event) {
        // dont prevent default browser actions
        if (!stream.context.dontPrevent) {
            event.preventDefault();
        }

        stream.write(null, {
            event: event,
            elms: elms,
            target: currentElement,
            item: data
        });
    };
}
<|endoftext|>


<commit_before>var KrempelAirApp = angular.module('KrempelAirApp', ['ngRoute']);
var uri = "/api"

KrempelAirApp.config(['$locationProvider', function($locationProvider) {
  $locationProvider.hashPrefix('');
}]);

KrempelAirApp.config(function ($routeProvider) {
  $routeProvider
      .when('/', {
        templateUrl: '../views/air.html',
        controller: 'AirFlowController'
      })
      .when('/login', {
        templateUrl: '../views/login.html',
        controller: 'LoginCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
})

KrempelAirApp.directive('selectOnClick', ['$window', function ($window) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('click', function () {
                if (!$window.getSelection().toString()) {
                    // Required for mobile Safari
                    this.setSelectionRange(0, this.value.length)
                }
            });
        }
    };
}]);

KrempelAirApp.factory('Auth', function ($rootScope, $window, $http) {
  return {
    login: function (user, successHandler, errorHandler) {
      if (user.username == 'test' && user.password == 'test') {
        this.setLoggedInUser(user);
        successHandler(user);
      } else {
        alert("please use username/password as test/test to login");
        errorHandler(user);
      }

      // call the server side login restful api
//      $http.post('api/login', user).success(function(user) {
//        this.setLoggedInUser(user);
//        successHandler(user);
//      }).error(errorHandler);
    },
    getLoggedInUser: function () {
      if ($rootScope.user === undefined || $rootScope.user == null) {
        var userStr = $window.sessionStorage.getItem('user');
        if (userStr) {
          $rootScope.user = angular.fromJson(userStr);
        }
      }
      return $rootScope.user;
    },
    isLoggedIn: function () {
      return this.getLoggedInUser() != null;
    },
    setLoggedInUser: function (user) {
      $rootScope.user = user;
      if (user == null) {
        $window.sessionStorage.removeItem('user');
      } else {
        $window.sessionStorage.setItem('user', angular.toJson($rootScope.user));
      }
    }
  };
})

KrempelAirApp.run(['$window', '$rootScope', '$location', 'Auth', function ($window, $rootScope, $location, Auth) {

    $rootScope.$on("$routeChangeStart", function (event) {
      if (!Auth.isLoggedIn() &&
          $location.path() !== '/login') {
        $location.path('/login');
      }
    });
}]);

KrempelAirApp.controller('LoginCtrl', function ($scope, Auth, $location, $http) {
  $scope.user = {};

  $scope.login = function () {
    Auth.login($scope.user, function () {
      $location.path('/');
    }, function (e) {
      // do some error handling.
    });
  };
})

KrempelAirApp.controller('MainCtrl', function ($scope, Auth, $location) {

  $scope.logout = function () {
    Auth.setLoggedInUser(null);
    $location.path('/somewhere');
  };
})

KrempelAirApp.controller('AirFlowController', function AirFlowController($scope, $http, $timeout) {

    $scope.Refresh = function(){
        $http.get(uri+"/").then(function (response) {
            $scope.status = response.data;
        });
        $http.get(uri+"/stoerung").then(function (response) {
            $scope.stoerung = response.data;
        });
        $http.get(uri+"/lueftung/temperatur").then(function (response) {
            $scope.temperatur = response.data;

            // sollTemp
            if(!$scope.sollTemp){
              $scope.sollTemp = response.data["TempSoll"];
            }

            // sollTempNAK
            if(!$scope.sollTempNAK){
               $scope.sollTempNAK = response.data["TempSollNAK"];
            }
        });

        $timeout(function(){
         $scope.Refresh();
        },800);
    }
    $scope.Klick = function(Klick){
        $http.get(uri+"/lueftung/stufe/"+Klick);
        $scope.Refresh();
    }

    $scope.SolltempClick = function(){
      $http.get(uri+"/lueftung/temperatur/sollTemp/"+parseFloat($scope.sollTemp));
      alert("Gespeichert")
    }

    $scope.NAKClick = function(){
      $http.get(uri+"/lueftung/temperatur/sollTempNAK/"+parseFloat($scope.sollTempNAK));
      alert("Gespeichert")
    }

    $scope.updateNAK = function(){
      if($scope.NAK){
        $http.get(uri+"/lueftung/NAK/1");
      }else{
        $http.get(uri+"/lueftung/NAK/0");
      }
    }

    $scope.Refresh();
});
<commit_msg>Update main.js<commit_after>var KrempelAirApp = angular.module('KrempelAirApp', ['ngRoute']);
var uri = "/api"

// Highcharts

Highcharts.chart('container', {

    title: {
        text: 'Solar Employment Growth by Sector, 2010-2016'
    },

    subtitle: {
        text: 'Source: thesolarfoundation.com'
    },

    yAxis: {
        title: {
            text: 'Number of Employees'
        }
    },
    legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'middle'
    },

    plotOptions: {
        series: {
            label: {
                connectorAllowed: false
            },
            pointStart: 2010
        }
    },

    series: [{
        name: 'Installation',
        data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
    }, {
        name: 'Manufacturing',
        data: [24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434]
    }, {
        name: 'Sales & Distribution',
        data: [11744, 17722, 16005, 19771, 20185, 24377, 32147, 39387]
    }, {
        name: 'Project Development',
        data: [null, null, 7988, 12169, 15112, 22452, 34400, 34227]
    }, {
        name: 'Other',
        data: [12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111]
    }],

    responsive: {
        rules: [{
            condition: {
                maxWidth: 500
            },
            chartOptions: {
                legend: {
                    layout: 'horizontal',
                    align: 'center',
                    verticalAlign: 'bottom'
                }
            }
        }]
    }

});
// Highcharts

KrempelAirApp.config(['$locationProvider', function($locationProvider) {
  $locationProvider.hashPrefix('');
}]);

KrempelAirApp.config(function ($routeProvider) {
  $routeProvider
      .when('/', {
        templateUrl: '../views/air.html',
        controller: 'AirFlowController'
      })
      .when('/login', {
        templateUrl: '../views/login.html',
        controller: 'LoginCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
})

KrempelAirApp.directive('selectOnClick', ['$window', function ($window) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.on('click', function () {
                if (!$window.getSelection().toString()) {
                    // Required for mobile Safari
                    this.setSelectionRange(0, this.value.length)
                }
            });
        }
    };
}]);

KrempelAirApp.factory('Auth', function ($rootScope, $window, $http) {
  return {
    login: function (user, successHandler, errorHandler) {
      if (user.username == 'test' && user.password == 'test') {
        this.setLoggedInUser(user);
        successHandler(user);
      } else {
        alert("please use username/password as test/test to login");
        errorHandler(user);
      }

      // call the server side login restful api
//      $http.post('api/login', user).success(function(user) {
//        this.setLoggedInUser(user);
//        successHandler(user);
//      }).error(errorHandler);
    },
    getLoggedInUser: function () {
      if ($rootScope.user === undefined || $rootScope.user == null) {
        var userStr = $window.sessionStorage.getItem('user');
        if (userStr) {
          $rootScope.user = angular.fromJson(userStr);
        }
      }
      return $rootScope.user;
    },
    isLoggedIn: function () {
      return this.getLoggedInUser() != null;
    },
    setLoggedInUser: function (user) {
      $rootScope.user = user;
      if (user == null) {
        $window.sessionStorage.removeItem('user');
      } else {
        $window.sessionStorage.setItem('user', angular.toJson($rootScope.user));
      }
    }
  };
})

KrempelAirApp.run(['$window', '$rootScope', '$location', 'Auth', function ($window, $rootScope, $location, Auth) {

    $rootScope.$on("$routeChangeStart", function (event) {
      if (!Auth.isLoggedIn() &&
          $location.path() !== '/login') {
        $location.path('/login');
      }
    });
}]);

KrempelAirApp.controller('LoginCtrl', function ($scope, Auth, $location, $http) {
  $scope.user = {};

  $scope.login = function () {
    Auth.login($scope.user, function () {
      $location.path('/');
    }, function (e) {
      // do some error handling.
    });
  };
})

KrempelAirApp.controller('MainCtrl', function ($scope, Auth, $location) {

  $scope.logout = function () {
    Auth.setLoggedInUser(null);
    $location.path('/somewhere');
  };
})

KrempelAirApp.controller('AirFlowController', function AirFlowController($scope, $http, $timeout) {

    $scope.Refresh = function(){
        $http.get(uri+"/").then(function (response) {
            $scope.status = response.data;
        });
        $http.get(uri+"/stoerung").then(function (response) {
            $scope.stoerung = response.data;
        });
        $http.get(uri+"/lueftung/temperatur").then(function (response) {
            $scope.temperatur = response.data;

            // sollTemp
            if(!$scope.sollTemp){
              $scope.sollTemp = response.data["TempSoll"];
            }

            // sollTempNAK
            if(!$scope.sollTempNAK){
               $scope.sollTempNAK = response.data["TempSollNAK"];
            }
        });

        $timeout(function(){
         $scope.Refresh();
        },800);
    }
    $scope.Klick = function(Klick){
        $http.get(uri+"/lueftung/stufe/"+Klick);
        $scope.Refresh();
    }

    $scope.SolltempClick = function(){
      $http.get(uri+"/lueftung/temperatur/sollTemp/"+parseFloat($scope.sollTemp));
      alert("Gespeichert")
    }

    $scope.NAKClick = function(){
      $http.get(uri+"/lueftung/temperatur/sollTempNAK/"+parseFloat($scope.sollTempNAK));
      alert("Gespeichert")
    }

    $scope.updateNAK = function(){
      if($scope.NAK){
        $http.get(uri+"/lueftung/NAK/1");
      }else{
        $http.get(uri+"/lueftung/NAK/0");
      }
    }

    $scope.Refresh();
});
<|endoftext|>


<commit_before>function degToRad(a) { return a*pi/180 }
var pi = Math.PI
var cos = function(a) { return Math.cos(degToRad(a)) }
var sin = function(a) { return Math.sin(degToRad(a)) }

var side = 100
var svg = d3.select("svg").node()

SVGMatrix.prototype.m = function() { return [this.a,this.b,this.c,this.d,this.e,this.f] }
I = svg.createSVGMatrix()

var drawnObj = function() {
    this.matrix = svg.createSVGMatrix()
}
drawnObj.prototype = {
    bbox : function () {
        obj = this.node
        bbox = $(obj)[0].getBBox()
        return bbox
    },
    draw : function() { this.update() },
    update : function() { // won't call this directly, but once draw() does its thing, it'll map here
        bbox = this.bbox()
        center = [ bbox.x + bbox.width/2, bbox.y + bbox.height/2 ]
        ang = this.rotation
        this.matrix = I
            .translate(this.x,this.y)
            .rotate(this.rotation)
        d3.select(this.node.parentNode).attr("transform",
                "matrix("+ this.matrix.m().join(' ') +")"
                )
    },
    show: function() {
        $(this.node).show()
    },
    hide: function() {
        $(this.node).hide()
    },
    translate: function(x,y) {
        this.x += x
        this.y += y
        this.draw()
    },
    setPosition: function(x,y) {
        this.x = x
        this.y = y
        this.draw()
    },
    setRotation: function(ang) {
        this.rotation = ang
        this.draw()
    },
    rotate : function(ang) {
        this.rotation += ang
        this.draw()
    },
    x: 0,
    y: 0,
    rotation: 0
}

var drawGroup = function() {
    drawnObj.apply(this)
    this.node = document.createElementNS("http://www.w3.org/2000/svg","g")
    svg.appendChild( this.node )
}
drawGroup.prototype = $.extend({},drawnObj.prototype,{
    appendChild: function(n) {
        this.node.appendChild(n)
    },
    removeChild: function(n) {
        this.node.removeChild(n)
    }
})

var poly = function() {
    drawnObj.apply(this)
}
poly.prototype = $.extend({},drawnObj.prototype,{
    points : function() { return [] },
    color : "#00FF00",
    draw : function() {
        pointsStr = ""
        for(var i=0; i<this.points.length; i++){
            pointsStr += this.points[i].toString() + " "
        }
        canvas = d3.select("svg")
        this.drawable = canvas.append("g").append("polygon")
            .attr("points", pointsStr)
            .attr({ fill: this.color })
        this.node = this.drawable.node()
        this.update() // we wanna be in the right place/orientation
        this.draw = this.update // done with first-time creation, drawing means updating, now
        return this.drawable
    }
})

function drawTriSides(tr) {
    sides = [
    {pt1: tr.points[0], pt2: tr.points[1], color:"FF0000"},
    {pt1: tr.points[1], pt2: tr.points[2], color:"00FF00"},
    {pt1: tr.points[2], pt2: tr.points[0], color:"0000FF"},
    ]
    console.log(sides)
    for(s in sides) {
        s=sides[s]
        d3.select(tr.node.parentNode).append("line").attr({x1: s.pt1[0], y1: s.pt1[1]}).attr({x2: s.pt2[0], y2: s.pt2[1]}).style({"stroke":s.color, "stroke-width":"5px"}).attr("transform", d3.select(tr.node).attr("transform"))
    }
}
// classes to contain the isosceles tris described in "Updown generation of Penrose patterns"
// http://www.sciencedirect.com/science/article/pii/0019357790900058
tri = function() {
    poly.apply(this)
    this.points = [
        [0,side*cos(this.beta)],
        [side * sin(this.beta),0],
        [0,-side * cos(this.beta)]
    ]
}
tri.prototype = $.extend({},poly.prototype, {
    alpha : 45, // the angle NOT on the cut
    beta : 45, // the two angles on the cut (bisected from the rhomb)
    color: "#000000"
})

// 'primed' triangle
trip = function() {
    tri.apply(this)
    // primed tris are mirror copies of unprimed tris
    this.points[1][0] *= -1
}
$.extend(trip.prototype,tri.prototype)

triA = function() {
    tri.apply(this)
    this.sides = {
        one: {pt1: this.points[0], pt2: this.points[1]},
        two: {pt1: this.points[2], pt2: this.points[1]},
        three: {pt1: this.points[2], pt2: this.points[0]},
        four: null
    }
}
triA.prototype = $.extend({},tri.prototype,{
    alpha : 36,
    beta : 144/2,
    color: "#FF0000",
})

triAp = function() {
    trip.apply(this)
    this.sides = {
        one: {pt1: this.points[0], pt2: this.points[1]},
        two: {pt1: this.points[2], pt2: this.points[1]},
        three: {pt1: this.points[2], pt2: this.points[0]},
        four: null
    }
}
triAp.prototype = $.extend({},trip.prototype,{
    alpha : 36,
    beta : 144/2,
    color: "#FF00FF"
})

triB = function() { tri.apply(this) }
triB.prototype = $.extend({},tri.prototype,{
    alpha : 108,
    beta : 72/2,
    color: "#0000FF"
})

triBp = function() { trip.apply(this) }
triBp.prototype = $.extend({},trip.prototype,{
    alpha : 108,
    beta : 72/2,
    color: "#00FFFF"
})

// universal prototype for rhombs
var rhomb = function() {
    this.points = this.points()
}
rhomb.prototype = $.extend({},poly.prototype,{
    points : function() {
        return [
            [0,0],
            [ side*cos(this.theta/2), side*sin(this.theta/2) ],
            [ 2*side*cos(this.theta/2), 0],
            [ side*cos(this.theta/2), -side*sin(this.theta/2) ]
        ]
    }
})

var thickrhomb = function() {
    rhomb.apply(this)
}
thickrhomb.prototype = $.extend({},rhomb.prototype,{
    theta : 72,
    alpha : 108,
    position : [0,50],

    color : "#FF0000"
})

var thinrhomb = function() {
    rhomb.apply(this)
}
thinrhomb.prototype = $.extend({},rhomb.prototype,{
    theta : 36,
    alpha : 144,
    position : [0,50],

    color : "#0000FF"
})

//thin = new thinrhomb()
//thin.rotate(90)
//thin.draw()
//
//thick = new thickrhomb()
//thick.draw()
//thick.setRotation(thin.theta*3/2)
//thick.setPosition([-40,120])

mytri = new triA();
mytri.draw()
mytri.setRotation(0)
mytri.setPosition(200,300)
drawTriSides(mytri)

mytri2 = new triAp();
mytri2.draw()
mytri2.setPosition(200,300)
drawTriSides(mytri2)

mytri3 = new triB();
mytri3.draw()
mytri3.setRotation(90)
mytri3.setPosition(200,400)
drawTriSides(mytri3)

mytri4 = new triBp();
mytri4.draw()
mytri4.setRotation(90)
mytri4.setPosition(200,400)
drawTriSides(mytri4)

//rhombB = new drawGroup();
//rhombB.appendChild(mytri3.drawable.node())
//rhombB.appendChild(mytri4.drawable.node())

d3.selectAll("polygon").attr("fill","black")
<commit_msg>transformations all matrix-based now, removed drawnObj.rotation; added drawnObj.rotateAroundPoint() and rotateAroundLocalPoint()<commit_after>function degToRad(a) { return a*pi/180 }
var pi = Math.PI
var cos = function(a) { return Math.cos(degToRad(a)) }
var sin = function(a) { return Math.sin(degToRad(a)) }

var side = 100
var svg = d3.select("svg").node()

SVGMatrix.prototype.m = function() { return [this.a,this.b,this.c,this.d,this.e,this.f] }
I = svg.createSVGMatrix()

var drawnObj = function() {
    this.matrix = svg.createSVGMatrix()
}
drawnObj.prototype = {
    bbox : function () {
        obj = this.node
        bbox = $(obj)[0].getBBox()
        return bbox
    },
    draw : function() { this.update() },
    update : function() { // won't call this directly, but once draw() does its thing, it'll map here
        d3.select(this.node.parentNode).attr("transform",
                "matrix("+ this.matrix.m().join(' ') +")"
                )
    },
    show: function() {
        for ( var i=0, len=sibs.length; i < len; i++ ) {
            $(sibs[i]).show()
        }
    },
    hide: function() {
        sibs = this.node.parentNode.children
        for ( var i=0, len=sibs.length; i < len; i++ ) {
            $(sibs[i]).hide()
        }
    },
    translate: function(x,y) {
        this.x += x
        this.y += y
        this.matrix = this.matrix.translate( x, y )
        this.draw()
    },
    setPosition: function(x,y) {
        this.matrix = this.matrix.translate( -this.x, -this.y )
        this.x = x
        this.y = y
        this.matrix = this.matrix.translate( this.x, this.y )
        this.draw()
    },
    setRotation: function(ang) {
        this.matrix = I.translate(this.x,this.y).rotate(ang)
        this.draw()
    },
    rotate : function(ang) {
        this.matrix = this.matrix.rotate(ang)
        this.draw()
    },
    rotateAroundPoint(pt,ang) {
        shift = [ pt[0] - this.x, pt[1] - this.y ]
        // shift, rotate, shift back; pretty sure this is correct
        this.matrix = this.matrix.translate( shift[0], shift[1] )
            .rotate(ang)
            .translate( -shift[0], -shift[1] )
        this.draw()
    },
    rotateAroundLocalPoint(pt,ang) {
        this.rotateAroundPoint( [ this.x + pt[0], this.y + pt[1] ], ang )
    },
    x: 0,
    y: 0,
}

var drawGroup = function() {
    drawnObj.apply(this)
    this.node = document.createElementNS("http://www.w3.org/2000/svg","g")
    svg.appendChild( this.node )
}
drawGroup.prototype = $.extend({},drawnObj.prototype,{
    appendChild: function(n) {
        this.node.appendChild(n)
    },
    removeChild: function(n) {
        this.node.removeChild(n)
    }
})

var poly = function() {
    drawnObj.apply(this)
}
poly.prototype = $.extend({},drawnObj.prototype,{
    points : function() { return [] },
    color : "#00FF00",
    draw : function() {
        pointsStr = ""
        for(var i=0; i<this.points.length; i++){
            pointsStr += this.points[i].toString() + " "
        }
        canvas = d3.select("svg")
        this.drawable = canvas.append("g").append("polygon")
            .attr("points", pointsStr)
            .attr({ fill: this.color })
        this.node = this.drawable.node()
        this.update() // we wanna be in the right place/orientation
        this.draw = this.update // done with first-time creation, drawing means updating, now
        return this.drawable
    }
})

function drawTriSides(tr) {
    sides = [
    {pt1: tr.points[0], pt2: tr.points[1], color:"FF0000"},
    {pt1: tr.points[1], pt2: tr.points[2], color:"00FF00"},
    {pt1: tr.points[2], pt2: tr.points[0], color:"0000FF"},
    ]
    console.log(sides)
    for(s in sides) {
        s=sides[s]
        d3.select(tr.node.parentNode).append("line").attr({x1: s.pt1[0], y1: s.pt1[1]}).attr({x2: s.pt2[0], y2: s.pt2[1]}).style({"stroke":s.color, "stroke-width":"5px"}).attr("transform", d3.select(tr.node).attr("transform"))
    }
}
// classes to contain the isosceles tris described in "Updown generation of Penrose patterns"
// http://www.sciencedirect.com/science/article/pii/0019357790900058
//
// local origin is the center of the defining cut
tri = function() {
    poly.apply(this)
    this.points = [
        [0,side*cos(this.beta)],
        [side * sin(this.beta),0],
        [0,-side * cos(this.beta)]
    ]
}
tri.prototype = $.extend({},poly.prototype, {
    alpha : 45, // the angle NOT on the cut
    beta : 45, // the two angles on the cut (bisected from the rhomb)
    color: "#000000"
})

// 'primed' triangle
trip = function() {
    tri.apply(this)
    // primed tris are mirror copies of unprimed tris
    this.points[1][0] *= -1
}
$.extend(trip.prototype,tri.prototype)

triA = function() {
    tri.apply(this)
    this.sides = {
        one: {pt1: this.points[0], pt2: this.points[1]},
        two: {pt1: this.points[2], pt2: this.points[1]},
        three: {pt1: this.points[2], pt2: this.points[0]},
        four: null
    }
}
triA.prototype = $.extend({},tri.prototype,{
    alpha : 36,
    beta : 144/2,
    color: "#FF0000",
})

triAp = function() {
    trip.apply(this)
    this.sides = {
        one: {pt1: this.points[0], pt2: this.points[1]},
        two: {pt1: this.points[2], pt2: this.points[1]},
        three: {pt1: this.points[2], pt2: this.points[0]},
        four: null
    }
}
triAp.prototype = $.extend({},trip.prototype,{
    alpha : 36,
    beta : 144/2,
    color: "#FF00FF"
})

triB = function() { tri.apply(this) }
triB.prototype = $.extend({},tri.prototype,{
    alpha : 108,
    beta : 72/2,
    color: "#0000FF"
})

triBp = function() { trip.apply(this) }
triBp.prototype = $.extend({},trip.prototype,{
    alpha : 108,
    beta : 72/2,
    color: "#00FFFF"
})

// universal prototype for rhombs
var rhomb = function() {
    this.points = this.points()
}
rhomb.prototype = $.extend({},poly.prototype,{
    points : function() {
        return [
            [0,0],
            [ side*cos(this.theta/2), side*sin(this.theta/2) ],
            [ 2*side*cos(this.theta/2), 0],
            [ side*cos(this.theta/2), -side*sin(this.theta/2) ]
        ]
    }
})

var thickrhomb = function() {
    rhomb.apply(this)
}
thickrhomb.prototype = $.extend({},rhomb.prototype,{
    theta : 72,
    alpha : 108,
    position : [0,50],

    color : "#FF0000"
})

var thinrhomb = function() {
    rhomb.apply(this)
}
thinrhomb.prototype = $.extend({},rhomb.prototype,{
    theta : 36,
    alpha : 144,
    position : [0,50],

    color : "#0000FF"
})

//thin = new thinrhomb()
//thin.rotate(90)
//thin.draw()
//
//thick = new thickrhomb()
//thick.draw()
//thick.setRotation(thin.theta*3/2)
//thick.setPosition([-40,120])

mytri = new triA();
mytri.draw()
mytri.setRotation(0)
mytri.setPosition(100,100)
drawTriSides(mytri)

mytri2 = new triAp();
mytri2.draw()
mytri2.setPosition(100,100)
drawTriSides(mytri2)

d3.selectAll("polygon").attr("fill","black")
<|endoftext|>


<commit_before>var http = require('http'),
	url = require("url");

function startServer (host, port, route, handle, mongodb) {

	http.createServer(function (request, response) {

		var pathname = url.parse(request.url).pathname;
		if ( request.method.toLowerCase() === 'get' ) {
			processGetRequest(pathname, url, route, handle, request, response, mongodb);
		}
		else if ( request.method.toLowerCase() === 'post' ) {
			processPostRequest(pathname, route, handle, request, response, mongodb);
		}

	}).listen(port, host);
}

function processGetRequest (pathname, url, route, handle, request, response, mongodb) {
	var url_parts = url.parse(request.url, true),
		query = url_parts.query;

	route(handle, pathname, query, response, mongodb);
}

function processPostRequest (pathname, route, handle, response, mongodb) {
	var postData = '';
	request.addListener("data", function(postDataChunk) {
      postData += postDataChunk;
    });

    request.addListener("end", function() {
      route(handle, pathname, JSON.parse(postData), request, response, mongodb);
    });
}

exports.startServer = startServer;<commit_msg>fast fix<commit_after>var http = require('http'),
	url = require("url");

function startServer (host, port, route, handle, mongodb) {

	http.createServer(function (request, response) {

		var pathname = url.parse(request.url).pathname;
		if ( request.method.toLowerCase() === 'get' ) {
			processGetRequest(pathname, url, route, handle, request, response, mongodb);
		}
		else if ( request.method.toLowerCase() === 'post' ) {
			processPostRequest(pathname, route, handle, request, response, mongodb);
		}

	}).listen(port, host);
}

function processGetRequest (pathname, url, route, handle, request, response, mongodb) {
	var url_parts = url.parse(request.url, true),
		query = url_parts.query;

	route(handle, pathname, query, response, mongodb);
}

function processPostRequest (pathname, route, handle, request, response, mongodb) {
	var postData = '';
	request.addListener("data", function(postDataChunk) {
      postData += postDataChunk;
    });

    request.addListener("end", function() {
      route(handle, pathname, JSON.parse(postData), request, response, mongodb);
    });
}

exports.startServer = startServer;<|endoftext|>