<commit_before>var socket;
var g;

var LIONID = 0;
var ANTILOPEID = 1;

var canvas;
var canvasContext;
var canvasStage;

//Images
var lionSpriteSheetImage;
var antilopeSpriteSheetImage;
var objectsSpriteSheetImage;
var grassImage;
var logoImage;
var pressanyImage;
var treeImage;

var numberOfImages = 0;
var loaded = 0;

var lionSpriteSheet;
var antilopeSpriteSheet;
var objectsSpriteSheet;

var playerSprite;

var bmpLionAnimation;
var bmpAntilopeAnimation;

//SpriteSheet controlls.
var imageSize = 128;
var scale = 0.5;

//Game variables.
var animalID;
var x = 0;
var y = 0;
var ID;
var vx;
var vy;

var players = {};
var objects = [];

//Rendering
var backgroundContainer;
var playerContainer;
var objectContainer;
var guiContainer;

var ingame = false;
var timeloaded;

//Control
var mouseIsDown = false;

var map;
$.getJSON( "map.json", function( json ) {
	console.log('json done');
   	map = json;
   	loadMap();
});

$(document).ready(function(){

	canvas = document.getElementById('gamescreen');
	canvasContext = canvas.getContext("2d");
	canvasStage = new createjs.Stage(document.getElementById("gamescreen"));

	setup();

	$(document).bind('keyup',function(e){
        //console.log('Time ' + timeloaded + "/" + (new Date().getTime()) + " = " + ());
        if(!ingame && (new Date().getTime() - timeloaded) > 1000){
        	console.log('sending spawn message');
        	ingame = true;
        	showLogo(false);
        	sendDataToServer('spawn', '');
        }
    })

});

function connect(){
	var connectTo = 'http://'+location.host.substring(0,location.host.indexOf(':'));
	console.log('Connecting to ' + connectTo);

	socket = io.connect(connectTo);

	socket.on("setup", function(data) {
	  	console.log(data);
		animalID = data.aid;
		ID = data.id;
		x = data.x;
		y = data.y;
		vx = data.vx;
		vy = data.vy;
	}.bind(this));

	socket.on("die", function(data) {
	  	console.log('Data: ' + data);
		die(data);
	}.bind(this));

	socket.on("u", function(data) {
		update(data);
	}.bind(this));
}

function sendDataToServer(trigger, data){
	socket.emit(trigger, data);
}

function setup(){
	g = new createjs.Graphics();

	backgroundContainer = new createjs.Container();
	canvasStage.addChild(backgroundContainer);
	playerContainer = new createjs.Container();
	canvasStage.addChild(playerContainer);
	objectContainer = new createjs.Container();
	canvasStage.addChild(objectContainer);
 	guiContainer = new createjs.Container();
 	canvasStage.addChild(guiContainer);

	loadImages();

	$(document).bind('mousedown', function mouseDown(evt){
		mouseIsDown = true;
		console.log("Mouse down " + evt);
	}, false);

	$(document).bind('mouseup', function mouseUp(evt){
		mouseIsDown = false;
		console.log("Mouse up " + evt);
	}, false);

	$(document).bind('mousemove', function(evt) {
        var mousePos = getMousePos(canvas, evt);
        if(mouseIsDown) {
			var deltaX = mousePos.x - canvas.width/2;
			var deltaY = mousePos.y - canvas.height/2;

			var len = Math.sqrt(deltaX*deltaX + deltaY*deltaY);

			deltaX = deltaX/len;
			deltaY = deltaY/len;

			var speedVect = {};

			speedVect.vx = -deltaX;
			speedVect.vy = -deltaY;

			sendDataToServer("v", speedVect);
		}
    }, false);

	//createPlayer();
}

function getMousePos(canvas, evt) {
	var rect = canvas.getBoundingClientRect();
	return {
	  x: evt.clientX - rect.left,
	  y: evt.clientY - rect.top
	};
}

function mouseButtonToggle(){
}

function setupAnimations(){

	createjs.Ticker.addListener(window);
	createjs.Ticker.useRAF = true;
	// Best Framerate targeted (60 FPS)
	createjs.Ticker.setFPS(30);
}

function tick() {
	//render();
	//renderPlayer();
	updateLocal();
    // update the stage:
    canvasStage.update();
}

function loadImages(){
	lionSpriteSheetImage = new Image();
	lionSpriteSheetImage.src = 'lion.png';
	numberOfImages++;
	lionSpriteSheetImage.onload = function() {
    	preloadStatus();
  	};

  	antilopeSpriteSheetImage = new Image();
	antilopeSpriteSheetImage.src = 'antilope.png';
	numberOfImages++;
	antilopeSpriteSheetImage.onload = function() {
    	preloadStatus();
  	};

  	objectsSpriteSheetImage = new Image();
	objectsSpriteSheetImage.src = 'objects.png';
	numberOfImages++;
	objectsSpriteSheetImage.onload = function() {
    	preloadStatus();
  	};

  	logoImage = new Image();
	logoImage.src = 'logo.png';
	numberOfImages++;
	logoImage.onload = function() {
    	preloadStatus();
  	};

  	pressanyImage = new Image();
	pressanyImage.src = 'pressanykey.png';
	numberOfImages++;
	pressanyImage.onload = function() {
    	preloadStatus();
  	};
}

function preloadStatus(){
	loaded++;
	console.log('done loading image ' + loaded + '/' + numberOfImages);
	if(loaded == numberOfImages){
		console.log('Done loading!');
		createSpriteSheets();
		createBackground();
		createLogo();

		setupAnimations();
		timeloaded = new Date().getTime();
		connect();
	}
}

function createSpriteSheets(){
	createLionSpriteSheet();
	createAntilopeSpriteSheet();
	createObjectsSpriteSheet();
}

function createLionSpriteSheet(){
	//example code:
	lionSpriteSheet = new createjs.SpriteSheet({
      // image to use
      images: [lionSpriteSheetImage],
      // width, height & registration point of each sprite
      frames: {width: 128, height: 128, regX: 64, regY: 64},
      animations: {
          left: [0, 3, "left", 3],
          right: [4, 7, "right", 3],
          up: [8, 11, "up", 3],
          down: [12, 15, "down", 3]
          //water: [32, 33, "water", 30]
      }
  });
  //lionSpriteSheet.img.gotoAndPlay("attack");

}

function createAntilopeSpriteSheet(){
	//example code:
	antilopeSpriteSheet = new createjs.SpriteSheet({
      // image to use
      images: [antilopeSpriteSheetImage],
      // width, height & registration point of each sprite
      frames: {width: 128, height: 128, regX: 64, regY: 64},
      animations: {
          run: [0, 0, "run", 10]
          //attack: [8, 15, "attack", 5],
          //idle: [16, 17, "idle", 50],
          //die: [24, 31, "die", 10],
          //water: [32, 33, "water", 30]
      }
  });
  //antilopeSpriteSheet.img.gotoAndPlay("attack");
}

function createObjectsSpriteSheet(){
	objectsSpriteSheet = new createjs.SpriteSheet({
      images: [objectsSpriteSheetImage],
      frames: [
      	[0,0,256,256, 0,128,128]
      ],
      animations: {
      	tree: [0, 0, "tree", 30]
      }
  });
}

function createSprite(spriteSheet){

  return new createjs.BitmapAnimation(spriteSheet);

}

function createBackground(){
	//g.beginFill(createjs.Graphics.getRGB(224,195,29));

	var shape = new createjs.Shape();
	shape.graphics.beginFill("#E0C31D").drawRect(0, 0, canvas.width, canvas.height);

	//background = new createjs.Rectangle(0, 0, canvas.width, canvas.height);
	backgroundContainer.addChild(shape);
}

function loadMap(){
	for(var i = 0; i < map.length; i++){
		var def = map[i];
		if(def){
			var tree = new createjs.BitmapAnimation(objectsSpriteSheet);
			tree.gotoAndPlay(def.type);
			tree.x = def.x;
			tree.y = def.y;
			objectContainer.addChild(tree);
			objects.push(tree);
		}
	}
}

function createLogo(){
	var bitmap = new createjs.Bitmap(logoImage);
	bitmap.x = 400 - 512/2;
	bitmap.y = 240 - 512/2 - 30;
	guiContainer.addChild(bitmap);

	var imgaa = new Image(objectsSpriteSheet.getFrame(0).img);
	var pressany = new createjs.Bitmap(imgaa);
	pressany.x = 400 - 256/2;
	pressany.y = 240 - 256/2 + 175;
	pressany.alpha = 0;
	guiContainer.addChild(pressany);

	setTimeout(function() {
    	fade(pressany, 0, true, true);
	}, 25);
}

function showLogo(show){
	guiContainer.visible = show;
}

function fade(image, value, fadeIn, loop){
	image.alpha = value;
	var done = false;
	if(fadeIn){
		value += 1/30;
		if(value >= 1){
			fadeIn = false;
			done = true;
		}
	}else{
		value -= 1/30;
		if(value <= 0){
			fadeIn = true;
			done = true;
		}
	}
	if(!done || loop){
		setTimeout(function() {
	    	fade(image, value, fadeIn, loop);
		}, 25);
	}
}

function createPlayer(player){
	//var x = canvas.width/2;
	//var y = canvas.height/2;

	var sprite;

	if (player.animal == LIONID) {
		sprite = createSprite(lionSpriteSheet);
	}else{
		sprite = createSprite(antilopeSpriteSheet);
	}

	if (player.id == ID) {

		var x = canvas.width/2;
		var y = canvas.height/2;

		sprite.x = x;
		sprite.y = y;

		playerSprite = sprite;
	}
	else{
		sprite.x = player.x;
		sprite.y = player.y;
	}
	sprite.scaleX = scale;
	sprite.scaleY = scale;

	sprite.gotoAndPlay("run")

	player.sprite = sprite;

	playerContainer.addChild(sprite);
}

function die(data){
	var player = players[data.id];
	if(player){
		player.vx = 0;
		player.vy = 0;

		if(data.id == ID){
			console.log('We died :(');
			ingame = false;
			showLogo(true);
		}
	}
}

function updatePlayer(data){
	var id = data.id;

	if (!players[id]){

		var player = {
			id:data.id,
			animal:data.animal,
			x:relativeX(data.x),
			y:relativeY(data.y)
		}
		players[player.id] = player;
		createPlayer(player);
	}

	players[id].sprite.x = relativeX(data.x);
	players[id].sprite.y = relativeY(data.y);
	players[id].vx = data.vx;
	players[id].vy = data.vy;

	if(id == ID){
		x = data.x;
		y = data.y;
		players[id].sprite.x = 400;//canvas.width/2;
		players[id].sprite.y = 240;//canvas.heigth/2;
	}

}

function update(data){
	for(var i = 0; i < data.length;i++){
		var player = data[i];
		if (player) {
			updatePlayer(player);
		}
	}
}

function animate(player){
	var vx = player.vx;
	var vy = player.vy;
	if(Math.abs(vx) > Math.abs(vy)){
			if(vx > 0){
				if(player.sprite.currentAnimation !== 'left'){
					player.sprite.gotoAndPlay('left');
				}
			}else{
				if(player.sprite.currentAnimation !== 'right'){
					player.sprite.gotoAndPlay('right');
				}
			}
		}else{
			if(vy > 0){
				if(player.sprite.currentAnimation !== 'up'){
					player.sprite.gotoAndPlay('up');
				}

			}else{
				if(player.sprite.currentAnimation !== 'down'){
					player.sprite.gotoAndPlay('down');
				}

			}
		}
}

function updateLocal(){
	var myplayer = players[ID];
	if (myplayer) {
		var vx = myplayer.vx;
		var vy = myplayer.vy;
		animate(myplayer);
		//x = x + myplayer.vx*10;
		//y = y + myplayer.vy*10;

		//myplayer.sprite.x = 400;//canvas.width/2;
		//myplayer.sprite.y = 240;//canvas.heigth/2;
	}else{
		return;
	}
	//console.log('player speed ' + myplayer.vx + ' ' + myplayer.vy);
	for(var key in players){
		var player = players[key];
		if (player) {
			if(player.id != ID){
				/*
				var absoluteX = (x + player.sprite.x) + player.vx*10;
				var absoluteY = (y + player.sprite.y) + player.vy*10;
				player.sprite.x = relativeX(absoluteX);
				player.sprite.y = relativeY(absoluteY);
				*/
				player.sprite.x += myplayer.vx*10;
				player.sprite.y += myplayer.vy*10;
				animate(player);
			}
		}
	}
	for(var i = 0; i < objects.length; i++){
		var object = objects[i];
		if(object){
			object.x += myplayer.vx*10;
			object.y += myplayer.vy*10;
		}
	}
}

function relativeX(otherX){
	return canvas.width/2 + (x - otherX);
}

function relativeY(otherY){
	return canvas.height/2 + (y - otherY);
}<commit_msg>changed background color<commit_after>var socket;
var g;

var LIONID = 0;
var ANTILOPEID = 1;

var canvas;
var canvasContext;
var canvasStage;

//Images
var lionSpriteSheetImage;
var antilopeSpriteSheetImage;
var objectsSpriteSheetImage;
var grassImage;
var logoImage;
var pressanyImage;
var treeImage;

var numberOfImages = 0;
var loaded = 0;

var lionSpriteSheet;
var antilopeSpriteSheet;
var objectsSpriteSheet;

var playerSprite;

var bmpLionAnimation;
var bmpAntilopeAnimation;

//SpriteSheet controlls.
var imageSize = 128;
var scale = 0.5;

//Game variables.
var animalID;
var x = 0;
var y = 0;
var ID;
var vx;
var vy;

var players = {};
var objects = [];

//Rendering
var backgroundContainer;
var playerContainer;
var objectContainer;
var guiContainer;

var ingame = false;
var timeloaded;

//Control
var mouseIsDown = false;

var map;
$.getJSON( "map.json", function( json ) {
	console.log('json done');
   	map = json;
   	loadMap();
});

$(document).ready(function(){

	canvas = document.getElementById('gamescreen');
	canvasContext = canvas.getContext("2d");
	canvasStage = new createjs.Stage(document.getElementById("gamescreen"));

	setup();

	$(document).bind('keyup',function(e){
        //console.log('Time ' + timeloaded + "/" + (new Date().getTime()) + " = " + ());
        if(!ingame && (new Date().getTime() - timeloaded) > 1000){
        	console.log('sending spawn message');
        	ingame = true;
        	showLogo(false);
        	sendDataToServer('spawn', '');
        }
    })

});

function connect(){
	var connectTo = 'http://'+location.host.substring(0,location.host.indexOf(':'));
	console.log('Connecting to ' + connectTo);

	socket = io.connect(connectTo);

	socket.on("setup", function(data) {
	  	console.log(data);
		animalID = data.aid;
		ID = data.id;
		x = data.x;
		y = data.y;
		vx = data.vx;
		vy = data.vy;
	}.bind(this));

	socket.on("die", function(data) {
	  	console.log('Data: ' + data);
		die(data);
	}.bind(this));

	socket.on("u", function(data) {
		update(data);
	}.bind(this));
}

function sendDataToServer(trigger, data){
	socket.emit(trigger, data);
}

function setup(){
	g = new createjs.Graphics();

	backgroundContainer = new createjs.Container();
	canvasStage.addChild(backgroundContainer);
	playerContainer = new createjs.Container();
	canvasStage.addChild(playerContainer);
	objectContainer = new createjs.Container();
	canvasStage.addChild(objectContainer);
 	guiContainer = new createjs.Container();
 	canvasStage.addChild(guiContainer);

	loadImages();

	$(document).bind('mousedown', function mouseDown(evt){
		mouseIsDown = true;
		console.log("Mouse down " + evt);
	}, false);

	$(document).bind('mouseup', function mouseUp(evt){
		mouseIsDown = false;
		sendDataToServer("v", {vx:0, vy:0});
		console.log("Mouse up " + evt);
	}, false);

	$(document).bind('mousemove', function(evt) {
        var mousePos = getMousePos(canvas, evt);
        if(mouseIsDown) {
			var deltaX = mousePos.x - canvas.width/2;
			var deltaY = mousePos.y - canvas.height/2;

			var len = Math.sqrt(deltaX*deltaX + deltaY*deltaY);

			deltaX = deltaX/len;
			deltaY = deltaY/len;

			var speedVect = {};

			speedVect.vx = -deltaX;
			speedVect.vy = -deltaY;

			sendDataToServer("v", speedVect);
		}
    }, false);

	//createPlayer();
}

function getMousePos(canvas, evt) {
	var rect = canvas.getBoundingClientRect();
	return {
	  x: evt.clientX - rect.left,
	  y: evt.clientY - rect.top
	};
}

function mouseButtonToggle(){
}

function setupAnimations(){

	createjs.Ticker.addListener(window);
	createjs.Ticker.useRAF = true;
	// Best Framerate targeted (60 FPS)
	createjs.Ticker.setFPS(30);
}

function tick() {
	//render();
	//renderPlayer();
	updateLocal();
    // update the stage:
    canvasStage.update();
}

function loadImages(){
	lionSpriteSheetImage = new Image();
	lionSpriteSheetImage.src = 'lion.png';
	numberOfImages++;
	lionSpriteSheetImage.onload = function() {
    	preloadStatus();
  	};

  	antilopeSpriteSheetImage = new Image();
	antilopeSpriteSheetImage.src = 'antilope.png';
	numberOfImages++;
	antilopeSpriteSheetImage.onload = function() {
    	preloadStatus();
  	};

  	objectsSpriteSheetImage = new Image();
	objectsSpriteSheetImage.src = 'objects.png';
	numberOfImages++;
	objectsSpriteSheetImage.onload = function() {
    	preloadStatus();
  	};

  	logoImage = new Image();
	logoImage.src = 'logo.png';
	numberOfImages++;
	logoImage.onload = function() {
    	preloadStatus();
  	};

  	pressanyImage = new Image();
	pressanyImage.src = 'pressanykey.png';
	numberOfImages++;
	pressanyImage.onload = function() {
    	preloadStatus();
  	};
}

function preloadStatus(){
	loaded++;
	console.log('done loading image ' + loaded + '/' + numberOfImages);
	if(loaded == numberOfImages){
		console.log('Done loading!');
		createSpriteSheets();
		createBackground();
		createLogo();

		setupAnimations();
		timeloaded = new Date().getTime();
		connect();
	}
}

function createSpriteSheets(){
	createLionSpriteSheet();
	createAntilopeSpriteSheet();
	createObjectsSpriteSheet();
}

function createLionSpriteSheet(){
	//example code:
	lionSpriteSheet = new createjs.SpriteSheet({
      // image to use
      images: [lionSpriteSheetImage],
      // width, height & registration point of each sprite
      frames: {width: 128, height: 128, regX: 64, regY: 64},
      animations: {
          left: [0, 3, "left", 3],
          right: [4, 7, "right", 3],
          up: [8, 11, "up", 3],
          down: [12, 15, "down", 3]
          //water: [32, 33, "water", 30]
      }
  });
  //lionSpriteSheet.img.gotoAndPlay("attack");

}

function createAntilopeSpriteSheet(){
	//example code:
	antilopeSpriteSheet = new createjs.SpriteSheet({
      // image to use
      images: [antilopeSpriteSheetImage],
      // width, height & registration point of each sprite
      frames: {width: 128, height: 128, regX: 64, regY: 64},
      animations: {
          run: [0, 0, "run", 10]
          //attack: [8, 15, "attack", 5],
          //idle: [16, 17, "idle", 50],
          //die: [24, 31, "die", 10],
          //water: [32, 33, "water", 30]
      }
  });
  //antilopeSpriteSheet.img.gotoAndPlay("attack");
}

function createObjectsSpriteSheet(){
	objectsSpriteSheet = new createjs.SpriteSheet({
      images: [objectsSpriteSheetImage],
      frames: [
      	[0,0,256,256, 0,128,128]
      ],
      animations: {
      	tree: [0, 0, "tree", 30]
      }
  });
}

function createSprite(spriteSheet){

  return new createjs.BitmapAnimation(spriteSheet);

}

function createBackground(){
	//g.beginFill(createjs.Graphics.getRGB(224,195,29));

	var shape = new createjs.Shape();
	shape.graphics.beginFill("#E7E7E7").drawRect(0, 0, canvas.width, canvas.height);

	//background = new createjs.Rectangle(0, 0, canvas.width, canvas.height);
	backgroundContainer.addChild(shape);
}

function loadMap(){
	for(var i = 0; i < map.length; i++){
		var def = map[i];
		if(def){
			var tree = new createjs.BitmapAnimation(objectsSpriteSheet);
			tree.gotoAndPlay(def.type);
			tree.x = def.x;
			tree.y = def.y;
			objectContainer.addChild(tree);
			objects.push(tree);
		}
	}
}

function createLogo(){
	var bitmap = new createjs.Bitmap(logoImage);
	bitmap.x = 400 - 512/2;
	bitmap.y = 240 - 512/2 - 30;
	guiContainer.addChild(bitmap);

	var imgaa = new Image(objectsSpriteSheet.getFrame(0).img);
	var pressany = new createjs.Bitmap(imgaa);
	pressany.x = 400 - 256/2;
	pressany.y = 240 - 256/2 + 175;
	pressany.alpha = 0;
	guiContainer.addChild(pressany);

	setTimeout(function() {
    	fade(pressany, 0, true, true);
	}, 25);
}

function showLogo(show){
	guiContainer.visible = show;
}

function fade(image, value, fadeIn, loop){
	image.alpha = value;
	var done = false;
	if(fadeIn){
		value += 1/30;
		if(value >= 1){
			fadeIn = false;
			done = true;
		}
	}else{
		value -= 1/30;
		if(value <= 0){
			fadeIn = true;
			done = true;
		}
	}
	if(!done || loop){
		setTimeout(function() {
	    	fade(image, value, fadeIn, loop);
		}, 25);
	}
}

function createPlayer(player){
	//var x = canvas.width/2;
	//var y = canvas.height/2;

	var sprite;

	if (player.animal == LIONID) {
		sprite = createSprite(lionSpriteSheet);
	}else{
		sprite = createSprite(antilopeSpriteSheet);
	}

	if (player.id == ID) {

		var x = canvas.width/2;
		var y = canvas.height/2;

		sprite.x = x;
		sprite.y = y;

		playerSprite = sprite;
	}
	else{
		sprite.x = player.x;
		sprite.y = player.y;
	}
	sprite.scaleX = scale;
	sprite.scaleY = scale;

	sprite.gotoAndPlay("run")

	player.sprite = sprite;

	playerContainer.addChild(sprite);
}

function die(data){
	var player = players[data.id];
	if(player){
		player.vx = 0;
		player.vy = 0;

		if(data.id == ID){
			console.log('We died :(');
			ingame = false;
			showLogo(true);
		}
	}
}

function updatePlayer(data){
	var id = data.id;

	if (!players[id]){

		var player = {
			id:data.id,
			animal:data.animal,
			x:relativeX(data.x),
			y:relativeY(data.y)
		}
		players[player.id] = player;
		createPlayer(player);
	}

	players[id].sprite.x = relativeX(data.x);
	players[id].sprite.y = relativeY(data.y);
	players[id].vx = data.vx;
	players[id].vy = data.vy;

	if(id == ID){
		x = data.x;
		y = data.y;
		players[id].sprite.x = 400;//canvas.width/2;
		players[id].sprite.y = 240;//canvas.heigth/2;
	}

}

function update(data){
	for(var i = 0; i < data.length;i++){
		var player = data[i];
		if (player) {
			updatePlayer(player);
		}
	}
}

function animate(player){
	var vx = player.vx;
	var vy = player.vy;
	if(Math.abs(vx) > Math.abs(vy)){
			if(vx > 0){
				if(player.sprite.currentAnimation !== 'left'){
					player.sprite.gotoAndPlay('left');
				}
			}else{
				if(player.sprite.currentAnimation !== 'right'){
					player.sprite.gotoAndPlay('right');
				}
			}
		}else{
			if(vy > 0){
				if(player.sprite.currentAnimation !== 'up'){
					player.sprite.gotoAndPlay('up');
				}

			}else{
				if(player.sprite.currentAnimation !== 'down'){
					player.sprite.gotoAndPlay('down');
				}

			}
		}
}

function updateLocal(){
	var myplayer = players[ID];
	if (myplayer) {
		var vx = myplayer.vx;
		var vy = myplayer.vy;
		animate(myplayer);
		//x = x + myplayer.vx*10;
		//y = y + myplayer.vy*10;

		//myplayer.sprite.x = 400;//canvas.width/2;
		//myplayer.sprite.y = 240;//canvas.heigth/2;
	}else{
		return;
	}
	//console.log('player speed ' + myplayer.vx + ' ' + myplayer.vy);
	for(var key in players){
		var player = players[key];
		if (player) {
			if(player.id != ID){
				/*
				var absoluteX = (x + player.sprite.x) + player.vx*10;
				var absoluteY = (y + player.sprite.y) + player.vy*10;
				player.sprite.x = relativeX(absoluteX);
				player.sprite.y = relativeY(absoluteY);
				*/
				player.sprite.x += myplayer.vx*10;
				player.sprite.y += myplayer.vy*10;
				animate(player);
			}
		}
	}
	for(var i = 0; i < objects.length; i++){
		var object = objects[i];
		if(object){
			object.x += myplayer.vx*10;
			object.y += myplayer.vy*10;
		}
	}
}

function relativeX(otherX){
	return canvas.width/2 + (x - otherX);
}

function relativeY(otherY){
	return canvas.height/2 + (y - otherY);
}<|endoftext|>


<commit_before>export function fireEvent(node, eventName) {
  let doc = {};
  if (node.ownerDocument) {
    doc = node.ownerDocument;
  } else if (node.nodeType === 9) {
    doc = node;
  }
  if (node.dispatchEvent) {
    let eventClass = '';
    switch (eventName) {
      case 'click':
      case 'mousedown':
      case 'mouseup':
        eventClass = 'MouseEvents';
        break;
      case 'focus':
      case 'change':
      case 'blur':
      case 'select':
        eventClass = 'HTMLEvents';
        break;
      default:
        break;
    }
    const event = doc.createEvent(eventClass);
    event.initEvent(eventName, true, true); // All events created as bubbling and cancelable.

    event.synthetic = true; // allow detection of synthetic events
    // The second parameter says go ahead with the default action
    node.dispatchEvent(event, true);
  } else if (node.fireEvent) {
    // IE-old school style
    const event = doc.createEventObject();
    event.synthetic = true; // allow detection of synthetic events
    node.fireEvent('on' + eventName, event);
  }
}

export function executionEnvironment() {
  const canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);

  return {
    canUseDOM,
    canUseWorkers: typeof Worker !== 'undefined',
    canUseEventListeners:
    canUseDOM && !!(window.addEventListener || window.attachEvent),
    canUseViewport: canUseDOM && !!window.screen
  };
}

export function getWindowHeight() {
  if (!executionEnvironment().canUseDOM) {
    return 0;
  }
  const w = window;
  const d = document;
  const e = d.documentElement;
  const g = d.getElementsByTagName('body')[0];
  return w.innerHeight || e.clientHeight || g.clientHeight;
}

export function getWindowWidth() {
  if (!executionEnvironment().canUseDOM) {
    return 0;
  }
  const w = window;
  const d = document;
  const e = d.documentElement;
  const g = d.getElementsByTagName('body')[0];
  return w.innerWidth || e.clientWidth || g.clientWidth;
}

export function getDeviceType() {
  if (!executionEnvironment().canUseDOM) {
    return 0;
  }
  const w = window || null;
  const d = document;
  const e = d.documentElement;
  const g = d.getElementsByTagName('body')[0];
  const witdh = w.innerWidth || e.clientWidth || g.clientWidth;
  if (witdh < 768) {
    return 'mobile';
  }
  if (witdh >= 768 && witdh < 1024) {
    return 'tablet';
  }
  return 'desktop';
}

/* eslint-disable */
// https://learn.javascript.ru/cookie#функция-getcookie-name
function getCookie(name) {
  if (!executionEnvironment().canUseDOM) return;

  var matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}

// https://learn.javascript.ru/cookie#функция-setcookie-name-value-options
function setCookie(name, value, options) {
  if (!executionEnvironment().canUseDOM) return;

  options = options || {};

  var expires = options.expires;

  if (typeof expires == "number" && expires) {
    var d = new Date();
    d.setTime(d.getTime() + expires * 1000);
    expires = options.expires = d;
  }
  if (expires && expires.toUTCString) {
    options.expires = expires.toUTCString();
  }

  value = encodeURIComponent(value);

  var updatedCookie = name + "=" + value;

  for (var propName in options) {
    updatedCookie += "; " + propName;
    var propValue = options[propName];
    if (propValue !== true) {
      updatedCookie += "=" + propValue;
    }
  }

  document.cookie = updatedCookie;
}

// https://learn.javascript.ru/cookie#функция-deletecookie-name
function deleteCookie(name) {
  setCookie(name, "", {
    expires: -1
  })
}
/* eslint-enable */
<commit_msg>[fix] add missing export for helpers<commit_after>export function fireEvent(node, eventName) {
  let doc = {};
  if (node.ownerDocument) {
    doc = node.ownerDocument;
  } else if (node.nodeType === 9) {
    doc = node;
  }
  if (node.dispatchEvent) {
    let eventClass = '';
    switch (eventName) {
      case 'click':
      case 'mousedown':
      case 'mouseup':
        eventClass = 'MouseEvents';
        break;
      case 'focus':
      case 'change':
      case 'blur':
      case 'select':
        eventClass = 'HTMLEvents';
        break;
      default:
        break;
    }
    const event = doc.createEvent(eventClass);
    event.initEvent(eventName, true, true); // All events created as bubbling and cancelable.

    event.synthetic = true; // allow detection of synthetic events
    // The second parameter says go ahead with the default action
    node.dispatchEvent(event, true);
  } else if (node.fireEvent) {
    // IE-old school style
    const event = doc.createEventObject();
    event.synthetic = true; // allow detection of synthetic events
    node.fireEvent('on' + eventName, event);
  }
}

export function executionEnvironment() {
  const canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);

  return {
    canUseDOM,
    canUseWorkers: typeof Worker !== 'undefined',
    canUseEventListeners:
    canUseDOM && !!(window.addEventListener || window.attachEvent),
    canUseViewport: canUseDOM && !!window.screen
  };
}

export function getWindowHeight() {
  if (!executionEnvironment().canUseDOM) {
    return 0;
  }
  const w = window;
  const d = document;
  const e = d.documentElement;
  const g = d.getElementsByTagName('body')[0];
  return w.innerHeight || e.clientHeight || g.clientHeight;
}

export function getWindowWidth() {
  if (!executionEnvironment().canUseDOM) {
    return 0;
  }
  const w = window;
  const d = document;
  const e = d.documentElement;
  const g = d.getElementsByTagName('body')[0];
  return w.innerWidth || e.clientWidth || g.clientWidth;
}

export function getDeviceType() {
  if (!executionEnvironment().canUseDOM) {
    return 0;
  }
  const w = window || null;
  const d = document;
  const e = d.documentElement;
  const g = d.getElementsByTagName('body')[0];
  const witdh = w.innerWidth || e.clientWidth || g.clientWidth;
  if (witdh < 768) {
    return 'mobile';
  }
  if (witdh >= 768 && witdh < 1024) {
    return 'tablet';
  }
  return 'desktop';
}

/* eslint-disable */
// https://learn.javascript.ru/cookie#функция-getcookie-name
export function getCookie(name) {
  if (!executionEnvironment().canUseDOM) return;

  var matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}

// https://learn.javascript.ru/cookie#функция-setcookie-name-value-options
export function setCookie(name, value, options) {
  if (!executionEnvironment().canUseDOM) return;

  options = options || {};

  var expires = options.expires;

  if (typeof expires == "number" && expires) {
    var d = new Date();
    d.setTime(d.getTime() + expires * 1000);
    expires = options.expires = d;
  }
  if (expires && expires.toUTCString) {
    options.expires = expires.toUTCString();
  }

  value = encodeURIComponent(value);

  var updatedCookie = name + "=" + value;

  for (var propName in options) {
    updatedCookie += "; " + propName;
    var propValue = options[propName];
    if (propValue !== true) {
      updatedCookie += "=" + propValue;
    }
  }

  document.cookie = updatedCookie;
}

// https://learn.javascript.ru/cookie#функция-deletecookie-name
export function deleteCookie(name) {
  setCookie(name, "", {
    expires: -1
  })
}
/* eslint-enable */
<|endoftext|>


<commit_before>const BasicNetwork = require(PATHS.NETWORKS + 'basic');
const BasicLayer = require(PATHS.LAYERS + 'basic');
const ActivationSigmoid = require(PATHS.ACTIVATION_FUNCTIONS + 'sigmoid');
const _ = require('lodash');
const NeuralNetworkError = require(PATHS.ERROR_HANDLING + 'neuralNetwork');
const ErrorUtil = require(PATHS.UTILS + 'error');

class NetworkUtil {

    /**
     * @return {Array}
     */
    static getXORDataset() {
        return {
            input: [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]],
            output: [[0.0], [1.0], [1.0], [0.0]]
        };
    }

    /**
     * @return {Array}
     */
    static getIrisDataset() {
        let irisDataset = require('ml-dataset-iris').getDataset();
        irisDataset = _.shuffle(irisDataset);

        let irisInput = [];
        let irisOutput = [];
        //split the dataset in input and output
        irisDataset.map(function (val) {
            irisInput.push(val.slice(0, -1));
            //convert the output column in to 3 independent columns
            switch (val[val.length - 1]) {
                case 'setosa':
                    irisOutput.push([0, 0, 1]);
                    break;
                case 'versicolor':
                    irisOutput.push([0, 1, 0]);
                    break;
                case 'virginica':
                    irisOutput.push([1, 0, 0]);
                    break;
            }
        });

        return {
            input: irisInput,
            output: irisOutput
        };
    }

    /**
     * @returns {Array}
     */
    static getHopfieldPatterns() {
        return [
            [
                0, 0, 0, 0, 0,
                0, 1, 1, 1, 0,
                0, 1, 0, 1, 0,
                0, 1, 1, 1, 0,
                0, 1, 0, 1, 0,
                0, 1, 0, 1, 0,
                0, 0, 0, 0, 0
            ],
            [
                0, 0, 0, 0, 0,
                0, 1, 1, 1, 0,
                0, 1, 0, 1, 0,
                0, 1, 1, 1, 0,
                0, 1, 0, 1, 0,
                0, 1, 1, 1, 0,
                0, 0, 0, 0, 0
            ],
            [
                0, 0, 0, 0, 0,
                0, 1, 1, 1, 0,
                0, 1, 0, 0, 0,
                0, 1, 0, 0, 0,
                0, 1, 0, 0, 0,
                0, 1, 1, 1, 0,
                0, 0, 0, 0, 0
            ],
            [
                0, 0, 0, 0, 0,
                0, 1, 1, 0, 0,
                0, 1, 0, 1, 0,
                0, 1, 0, 1, 0,
                0, 1, 0, 1, 0,
                0, 1, 1, 0, 0,
                0, 0, 0, 0, 0
            ],
            [
                0, 0, 0, 0, 0,
                0, 1, 1, 1, 0,
                0, 1, 0, 0, 0,
                0, 1, 1, 0, 0,
                0, 1, 0, 0, 0,
                0, 1, 1, 1, 0,
                0, 0, 0, 0, 0
            ],
            [
                0, 0, 0, 0, 0,
                0, 1, 1, 1, 0,
                0, 1, 0, 0, 0,
                0, 1, 1, 0, 0,
                0, 1, 0, 0, 0,
                0, 1, 0, 0, 0,
                0, 0, 0, 0, 0
            ],
            [
                0, 0, 0, 0, 0,
                0, 1, 0, 1, 0,
                0, 1, 0, 1, 0,
                0, 1, 1, 1, 0,
                0, 1, 0, 1, 0,
                0, 1, 0, 1, 0,
                0, 0, 0, 0, 0
            ],
            [
                0, 0, 0, 0, 0,
                0, 1, 1, 1, 0,
                0, 0, 1, 0, 0,
                0, 0, 1, 0, 0,
                0, 0, 1, 0, 0,
                0, 1, 1, 1, 0,
                0, 0, 0, 0, 0
            ],
            [
                0, 0, 0, 0, 0,
                0, 0, 1, 1, 0,
                0, 0, 0, 1, 0,
                0, 0, 0, 1, 0,
                0, 0, 0, 1, 0,
                0, 1, 1, 1, 0,
                0, 0, 0, 0, 0
            ],
            [
                0, 0, 0, 0, 0,
                0, 1, 0, 1, 0,
                0, 1, 1, 0, 0,
                0, 1, 0, 0, 0,
                0, 1, 1, 0, 0,
                0, 1, 0, 1, 0,
                0, 0, 0, 0, 0
            ]
        ];
    }

    /**
     * @return {BasicNetwork}
     */
    static createXORNetwork() {
        const network = new BasicNetwork();
        network.addLayer(new BasicLayer(null, true, 2));
        network.addLayer(new BasicLayer(new ActivationSigmoid(), true, 4));
        network.addLayer(new BasicLayer(new ActivationSigmoid(), false, 1));
        network.randomize();

        return network;
    }

    /**
     * @return {BasicNetwork}
     */
    static createIrisNetwork() {
        const network = new BasicNetwork();
        network.addLayer(new BasicLayer(null, true, 4));
        network.addLayer(new BasicLayer(new ActivationSigmoid(), true, 10));
        network.addLayer(new BasicLayer(new ActivationSigmoid(), true, 5));
        network.addLayer(new BasicLayer(new ActivationSigmoid(), false, 3));
        network.randomize();

        return network;
    }

    /**
     * @param train {Propagation}
     * @param options {Object}
     */
    static trainNetwork(train, options = {}) {
        let epoch = 1;
        let defaultOptions = {minError: 0.01, maxIterations: 100, minIterations: 1};
        options = _.merge(defaultOptions, options);

        do {
            train.iteration();
            EncogLog.debug("Epoch #" + epoch + " Error:" + train.error);

            if ((train.error < options.minError && options.minIterations == null) ||
                (train.error < options.minError && options.minIterations != null && epoch >= options.minIterations)) {
                break;
            }

            if (options.maxIterations != null && epoch >= options.maxIterations) {
                break;
            }

            epoch++;
        } while (true);
        train.finishTraining();

        EncogLog.print();
    }

    /**
     * @param network {BasicNetwork}
     * @param testDataset {Array}
     * @param idealOutput {Array}
     */
    static validateNetwork(network, testDataset, idealOutput) {
        if (testDataset.length != idealOutput.length) {
            throw new NeuralNetworkError('test and ideal dataset must have equal lengths');
        }

        EncogLog.debug("Neural Network Results:");

        let i = 0;
        let output;
        let accuratePredictions = 0;

        for (let input of testDataset) {
            output = network.compute(input);
            output = output.map(Math.round);

            if (_.isEqual(output, idealOutput[i])) {
                accuratePredictions++;
            }
            EncogLog.debug("input=" + input);
            EncogLog.debug("actual=" + output);
            EncogLog.debug("ideal=" + idealOutput[i]);
            EncogLog.debug("------------------------");
            i++;
        }

        let accuracy = accuratePredictions / testDataset.length * 100;
        let error = _.round(ErrorUtil.calculateRegressionError(network, testDataset, idealOutput) * 100, 4);

        EncogLog.debug('Total test size: ' + testDataset.length);
        EncogLog.debug('Accuracy: ' + accuracy + '%');
        EncogLog.debug('Error: ' + error + '%');

        EncogLog.print();
        return accuracy;
    }
}

module.exports = NetworkUtil;<commit_msg>removed unused methods<commit_after>const BasicNetwork = require(PATHS.NETWORKS + 'basic');
const BasicLayer = require(PATHS.LAYERS + 'basic');
const ActivationSigmoid = require(PATHS.ACTIVATION_FUNCTIONS + 'sigmoid');
const _ = require('lodash');
const NeuralNetworkError = require(PATHS.ERROR_HANDLING + 'neuralNetwork');
const ErrorUtil = require(PATHS.UTILS + 'error');

class NetworkUtil {

    /**
     * @return {BasicNetwork}
     */
    static createXORNetwork() {
        const network = new BasicNetwork();
        network.addLayer(new BasicLayer(null, true, 2));
        network.addLayer(new BasicLayer(new ActivationSigmoid(), true, 4));
        network.addLayer(new BasicLayer(new ActivationSigmoid(), false, 1));
        network.randomize();

        return network;
    }

    /**
     * @return {BasicNetwork}
     */
    static createIrisNetwork() {
        const network = new BasicNetwork();
        network.addLayer(new BasicLayer(null, true, 4));
        network.addLayer(new BasicLayer(new ActivationSigmoid(), true, 10));
        network.addLayer(new BasicLayer(new ActivationSigmoid(), true, 5));
        network.addLayer(new BasicLayer(new ActivationSigmoid(), false, 3));
        network.randomize();

        return network;
    }

    /**
     * @param train {Propagation}
     * @param options {Object}
     */
    static trainNetwork(train, options = {}) {
        let epoch = 1;
        let defaultOptions = {minError: 0.01, maxIterations: 100, minIterations: 1};
        options = _.merge(defaultOptions, options);

        do {
            train.iteration();
            EncogLog.debug("Epoch #" + epoch + " Error:" + train.error);

            if ((train.error < options.minError && options.minIterations == null) ||
                (train.error < options.minError && options.minIterations != null && epoch >= options.minIterations)) {
                break;
            }

            if (options.maxIterations != null && epoch >= options.maxIterations) {
                break;
            }

            epoch++;
        } while (true);
        train.finishTraining();

        EncogLog.print();
    }

    /**
     * @param network {BasicNetwork}
     * @param testDataset {Array}
     * @param idealOutput {Array}
     */
    static validateNetwork(network, testDataset, idealOutput) {
        if (testDataset.length != idealOutput.length) {
            throw new NeuralNetworkError('test and ideal dataset must have equal lengths');
        }

        EncogLog.debug("Neural Network Results:");

        let i = 0;
        let output;
        let accuratePredictions = 0;

        for (let input of testDataset) {
            output = network.compute(input);
            output = output.map(Math.round);

            if (_.isEqual(output, idealOutput[i])) {
                accuratePredictions++;
            }
            EncogLog.debug("input=" + input);
            EncogLog.debug("actual=" + output);
            EncogLog.debug("ideal=" + idealOutput[i]);
            EncogLog.debug("------------------------");
            i++;
        }

        let accuracy = accuratePredictions / testDataset.length * 100;
        let error = _.round(ErrorUtil.calculateRegressionError(network, testDataset, idealOutput) * 100, 4);

        EncogLog.debug('Total test size: ' + testDataset.length);
        EncogLog.debug('Accuracy: ' + accuracy + '%');
        EncogLog.debug('Error: ' + error + '%');

        EncogLog.print();
        return accuracy;
    }
}

module.exports = NetworkUtil;<|endoftext|>


<commit_before>import {
  heFengURL,
  heFengKey,
  heFengApiType,
} from '../constants/config';

const fetch = window.fetch;

const generateQuery = (data) => {
  const keys = Object.keys(data);
  let query = '';
  keys.forEach((item) => {
    query += `&${item}=${data[item]}`;
  });
  return `?${query.substr(1)}`;
};

class Request {
  constructor() {
    this.prefix = heFengURL;
    this.key = heFengKey;
    this.requestTypes = heFengApiType;
    this.data = {
      key: heFengKey,
    };
  }
  _fetchData(method, params, success, fail) {
    const isGet = method === 'GET';
    const data = Object.assign({}, this.data, params.data);
    const body = isGet ? {} : JSON.stringify(data);
    const query = isGet ? generateQuery(data) : '';
    const headers = params.header || {};
    const url = `${this.prefix}${params.url}${query}`;
    fetch(url, {
      method,
      headers,
      body,
    })
      .then(res => res.json())
      .then(res => success(res))
      .catch(error => fail(error));
  }
  /*
  ** @params params(Object)
      params: {
        url: '',
        data: {
          city:
        },
      }
  */
  get(params, success, fail) {
    this._fetchData('GET', params, success, fail);
  }
  post(params, success, fail) {
    this._fetchData('POST', params, success, fail);
  }
}

export default Request;
<commit_msg>fix:remove 'body' from 'GET' method<commit_after>import {
  heFengURL,
  heFengKey,
  heFengApiType,
} from '../constants/config';

const fetch = window.fetch;

const generateQuery = (data) => {
  const keys = Object.keys(data);
  let query = '';
  keys.forEach((item) => {
    query += `&${item}=${data[item]}`;
  });
  return `?${query.substr(1)}`;
};

class Request {
  constructor() {
    this.prefix = heFengURL;
    this.key = heFengKey;
    this.requestTypes = heFengApiType;
    this.data = {
      key: heFengKey,
    };
  }
  _fetchData(method, params, success, fail) {
    const isGet = method === 'GET';
    const data = Object.assign({}, this.data, params.data);
    const body = isGet ? {} : JSON.stringify(data);
    const query = isGet ? generateQuery(data) : '';
    const headers = params.header || {};
    const url = `${this.prefix}${params.url}${query}`;
    const requestInfo = {
      method,
      headers,
    };
    if (isGet) requestInfo.body = body;
    fetch(url, requestInfo)
      .then(res => res.json())
      .then(res => success(res))
      .catch(error => fail(error));
  }
  /*
  ** @params params(Object)
      params: {
        url: '',
        data: {
          city:
        },
      }
  */
  get(params, success, fail) {
    this._fetchData('GET', params, success, fail);
  }
  post(params, success, fail) {
    this._fetchData('POST', params, success, fail);
  }
}

export default Request;
<|endoftext|>


<commit_before><commit_msg>added viewer.getPickingPixels method<commit_after><|endoftext|>


<commit_before>import dat from "dat.gui/build/dat.gui.min"
import mainScheduler from "../scheduler"
import random from "../randomAdapter";
import path from "path";

import { Container } from "flux/utils";
import SchedulerStore from "../data/SchedulerStore";
import React, { Component } from 'react'
import * as d3 from "d3";
import guiStore from "../data/guiStore"
import {restartScheduler} from "../data/SchedulerActions"

//for removing folders thanks stack overflow! http://stackoverflow.com/questions/18085540/remove-folder-in-dat-gui
dat.GUI.prototype.removeFolder = function(name) {
  var folder = this.__folders[name];
  if (!folder) {
    return;
  }
  folder.close();
  this.__ul.removeChild(folder.domElement.parentNode);
  delete this.__folders[name];
  this.onResize();
}
//gui is the dat.gui instance
var gui
var currentLesson;

const config = {
  "Boost Time" : 10,
  "Number of Queues" : 8,
  "timeQuantums" : [],
  "Number of Jobs" : 10,
  "IO Frequency Min" : 10,
  'IO Frequency Max' : 10,
  "IO Length Min" : 10,
  "IO Length Max" : 10,
  "Duration": 10,
  "Jobs Start Time": 10,
  "generation": [],
  "Scheduler Height": 25,
  "Speed": 1,
}

const SimulationsPannel = {
	'Load' : function(){},
	'Save' : function(){},
	'Current Simulation': "Slot 1",
  'Share Link': "https://mlfq.tk/YGUuy768K",
};

var propsParameter;
const SchedulerParametersPannel = {
    get ["Number of Queues"](){
      return config["Number of Queues"];
    },
    set ["Number of Queues"](v){
      config["Number of Queues"] = v;

      if (currentLesson === "EXPLORE")
        render(gui)
      else
        renderGui(gui, propsParameter)
    },
    get ["Boost Time"]() {
      return config["Boost Time"];
    },
    set ["Boost Time"](v) {
      config["Boost Time"] = v;
    },
    'Trigger Boost': function(){
      mainScheduler.boostJobs();
    },
    get ["Speed"](){
        return config["Speed"]
        //return mainScheduler.speed;
    },
    set ["Speed"](v){
      config["Speed"] = v
      mainScheduler.speed = 2100 - 200 * config["Speed"];
      mainScheduler.config.speed = 2100 - 200 * config["Speed"];
    },
    get ["Scheduler Height"](){
        return config["Scheduler Height"]
    },
    set ["Scheduler Height"](v){
      config["Scheduler Height"] = v;
    }

};

var JobGeneratorPannel = {
    get ['Number of Jobs'](){
      return config['Number of Jobs'];
    },
    set ["Number of Jobs"](v){
      config["Number of Jobs"] = v;
    },
    get ['IO Frequency Min'](){
      return config["IO Frequency Min"];
    },
    set ["IO Frequency Min"](v){
      if (v < config['IO Frequency Max'])
        config['IO Frequency Min'] = v;
      else
        config['IO Frequency Min'] = config['IO Frequency Max'];
    },
    get ['IO Frequency Max'](){
      return config["IO Frequency Max"];
    },
    set ["IO Frequency Max"](v){
      if (v > config['IO Frequency Min'])
        config['IO Frequency Max'] = v;
      else
        config['IO Frequency Max'] = config['IO Frequency Min'];
    },
    get ['IO Length Min'](){
      return config["IO Length Min"];
    },
    set ["IO Length Min"](v){
      if (v < config['IO Length Max'])
        config['IO Length Min'] = v;
      else
        config['IO Length Min'] = config['IO Length Max'];
    },
    get ['IO Length Max'](){
      return config["IO Length Max"];
    },
    set ["IO Length Max"](v){
      if (v > config['IO Length Min'])
        config['IO Length Max'] = v;
      else
        config['IO Length Max'] = config['IO Length Min'];
    },
    get ["Duration"](){
      return config["Duration"];
    },
    set ["Duration"](v){
      config["Duration"] = v;
    },
    get ["Jobs Start Time"](){
      return config["Jobs Start Time"];
    },
    set ["Jobs Start Time"](v){
      config["Jobs Start Time"] = v;
    },
    'Generate Jobs': function() {
      refreshScheduler(config);
    }
  }

  var TimeQuantum ={
    'Queue 1': 1,
    'Queue 2': 2,
    'Queue 3': 3,
    'Queue 4': 4,
    'Queue 5': 5,
    'Queue 6': 6,
    'Queue 7': 7,
    'Queue 8': 8,
    'Queue 9': 9,
    'Queue 10': 10,
    'Queue 11': 11,
    'Queue 12': 12
  }

//2100 - 200 * config["Speed"];
//this is what is connected to the store
function datGui(props){
    propsParameter = props.parameter
    gui = props.gui;
    if (props.parameter["render"] === true) {
      currentLesson = props.lessonName
      renderGui(gui, propsParameter)
      SchedulerParametersPannel["Speed"] = props.simulation.speed / 1000
      retainSpeed(gui);
    }

    return null;
}

export default Container.createFunctional(datGui, () => [guiStore], () => {
   return guiStore.getState()
});

//------------------------------------- scheduler panel -------------------------------------------
  function displaySchedulerParams(gui, scheduler, TimeQuantum, numberOfQues){
    var menu2 = gui.addFolder("Scheduler Parameters");
      menu2.add(scheduler, 'Boost Time', 10, 100);
      menu2.add(scheduler, 'Trigger Boost')
      menu2.add(scheduler, 'Number of Queues',[1,2,3,4,5,6,7,8,9,10,11,12]);
      var Timequantum = menu2.addFolder("Time Quantums");
      for (var i = 1; i <= numberOfQues; i++)
        Timequantum.add(TimeQuantum,'Queue ' + i ,1,20);
      return gui;
  }
//-------------------------------------- work load panel ------------------------------------------
function displayJobGenerator(gui, workload){
    var gui3 = gui;
    var menu3 = gui3.addFolder("Job Generator");
    menu3.add(workload,'Number of Jobs', 1,10);
    menu3.add(workload,'IO Frequency Min', 1,10);
    menu3.add(workload,'IO Frequency Max', 1,10);
    menu3.add(workload,'Duration',1,10);
    menu3.add(workload,'IO Length Min',1,10);
    menu3.add(workload,'IO Length Max',1,10);
    menu3.add(workload,'Generate Jobs');
    return gui;
}

//--------------------------------------for clearing the pannels
function render(gui) {
  clearPanels(gui);
  gui = displaySchedulerParams(gui, SchedulerParametersPannel, TimeQuantum, config["Number of Queues"]);
  gui = displayJobGenerator(gui, JobGeneratorPannel);
  retainSpeed(gui);
}

function renderGui(gui, params) {
  clearPanels(gui);
  const panels = Object.getOwnPropertyNames(params);

  for (let i=0; i<panels.length; i++){

    if(panels[i] === "Scheduler Parameters") {
      const menu = gui.addFolder(panels[i]);
      const SchedulerAttributes = Object.getOwnPropertyNames(params[panels[i]]);

      for (let k = 0; k < SchedulerAttributes.length; k++){

        if (SchedulerAttributes[k] === "Number of Queues"){
          const arr = []
          const numberOfQues = params[panels[i]][SchedulerAttributes[k]];
          config["Number of Queues"] = numberOfQues;

          for (let i = 1; i <= numberOfQues; i++)
            arr.push(i);
          menu.add(SchedulerParametersPannel, SchedulerAttributes[k], arr)

          const Timequantum = menu.addFolder("Time Quantums");
          const tqVals = params[panels[i]]["timeQuantums"];
          const tqDisplayVals = Object.getOwnPropertyNames(TimeQuantum);

          for (let i = 1; i <= numberOfQues; i++) {
            TimeQuantum[tqDisplayVals[i-1]] = tqVals[i-1]
            Timequantum.add(TimeQuantum,'Queue ' + i , 1, 20);
          }

        } else if (SchedulerAttributes[k] === "Boost Time"){
          let boostTime = params[panels[i]][SchedulerAttributes[k]];
          config["Boost Time"] = boostTime;
          menu.add(SchedulerParametersPannel, SchedulerAttributes[k], 1, boostTime)
          menu.add(SchedulerParametersPannel, "Trigger Boost")
        } else if (SchedulerAttributes[k] === "Scheduler Height"){
          menu.add(SchedulerParametersPannel, SchedulerAttributes[k], 1, 50)
        }
      }
    }

    else if (panels[i] === "Job Generator"){
      const SchedulerAttributes = Object.getOwnPropertyNames(params[panels[i]]);
      const menu = gui.addFolder(panels[i]);

      for (let k = 0; k < SchedulerAttributes.length; k++){
        const displayValue = params[panels[i]][SchedulerAttributes[k]];
        config[SchedulerAttributes[k]] = displayValue;
        let max = 20
        if(SchedulerAttributes[k] === "Duration")
          max = 100;

        menu.add(JobGeneratorPannel, SchedulerAttributes[k], 1, max)
      }
      if(currentLesson === "EXPLORE")
        menu.add(JobGeneratorPannel, "Generate Jobs")

    }
  }
  retainSpeed(gui);
}

var reloadReference = 0;
function retainSpeed(gui){
  if (reloadReference === 0)
    reloadReference = gui.add(SchedulerParametersPannel,'Speed',1, 10);
  else {
    gui.remove(reloadReference);
    reloadReference = gui.add(SchedulerParametersPannel,'Speed',1, 10);
  }
}

function clearPanels(gui){
  gui.removeFolder("Scheduler Parameters");
  gui.removeFolder("Job Generator");
}

function createTQs() {
  const myArray = [];
  for (var i = 1; i <= config["Number of Queues"]; i++)
    myArray.push(TimeQuantum["Queue " + i]);
  return myArray;
}

//i suposed to restart the scheduler
function refreshScheduler(config){
    restartScheduler({
          timeQuantums: createTQs(),
          boostTime: config["Boost Time"],
          resetTQsOnIO: false,
          random,
          speed: mainScheduler.speed,
          generation: [{
            ioFrequencyRange: [config["IO Frequency Min"], config["IO Frequency Max"]],
            jobRuntimeRange: [1, config["Duration"]],
            numJobsRange: [config["Number of Jobs"], config["Number of Jobs"]],
            jobCreateTimeRange: [1, 15],
            ioLengthRange: [config["IO Length Min"], config["IO Length Max"]]
          }],
      });
}<commit_msg>added height<commit_after>import dat from "dat.gui/build/dat.gui.min"
import mainScheduler from "../scheduler"
import random from "../randomAdapter";
import path from "path";

import { Container } from "flux/utils";
import SchedulerStore from "../data/SchedulerStore";
import React, { Component } from 'react'
import * as d3 from "d3";
import guiStore from "../data/guiStore"
import {restartScheduler} from "../data/SchedulerActions"

//for removing folders thanks stack overflow! http://stackoverflow.com/questions/18085540/remove-folder-in-dat-gui
dat.GUI.prototype.removeFolder = function(name) {
  var folder = this.__folders[name];
  if (!folder) {
    return;
  }
  folder.close();
  this.__ul.removeChild(folder.domElement.parentNode);
  delete this.__folders[name];
  this.onResize();
}
//gui is the dat.gui instance
var gui
var currentLesson;

const config = {
  "Boost Time" : 10,
  "Number of Queues" : 8,
  "timeQuantums" : [],
  "Number of Jobs" : 10,
  "IO Frequency Min" : 10,
  'IO Frequency Max' : 10,
  "IO Length Min" : 10,
  "IO Length Max" : 10,
  "Duration": 10,
  "Jobs Start Time": 10,
  "generation": [],
  "Scheduler Height": 25,
  "Speed": 1,
}

const SimulationsPannel = {
	'Load' : function(){},
	'Save' : function(){},
	'Current Simulation': "Slot 1",
  'Share Link': "https://mlfq.tk/YGUuy768K",
};

var propsParameter;
const SchedulerParametersPannel = {
    get ["Number of Queues"](){
      return config["Number of Queues"];
    },
    set ["Number of Queues"](v){
      config["Number of Queues"] = v;

      if (currentLesson === "EXPLORE")
        render(gui)
      else
        renderGui(gui, propsParameter)
    },
    get ["Boost Time"]() {
      return config["Boost Time"];
    },
    set ["Boost Time"](v) {
      config["Boost Time"] = v;
    },
    'Trigger Boost': function(){
      mainScheduler.boostJobs();
    },
    get ["Speed"](){
        return config["Speed"]
        //return mainScheduler.speed;
    },
    set ["Speed"](v){
      config["Speed"] = v
      mainScheduler.speed = 2100 - 200 * config["Speed"];
      mainScheduler.config.speed = 2100 - 200 * config["Speed"];
    },
    get ["Scheduler Height"](){
        return config["Scheduler Height"]
    },
    set ["Scheduler Height"](v){
      config["Scheduler Height"] = v;
    }

};

var JobGeneratorPannel = {
    get ['Number of Jobs'](){
      return config['Number of Jobs'];
    },
    set ["Number of Jobs"](v){
      config["Number of Jobs"] = v;
    },
    get ['IO Frequency Min'](){
      return config["IO Frequency Min"];
    },
    set ["IO Frequency Min"](v){
      if (v < config['IO Frequency Max'])
        config['IO Frequency Min'] = v;
      else
        config['IO Frequency Min'] = config['IO Frequency Max'];
    },
    get ['IO Frequency Max'](){
      return config["IO Frequency Max"];
    },
    set ["IO Frequency Max"](v){
      if (v > config['IO Frequency Min'])
        config['IO Frequency Max'] = v;
      else
        config['IO Frequency Max'] = config['IO Frequency Min'];
    },
    get ['IO Length Min'](){
      return config["IO Length Min"];
    },
    set ["IO Length Min"](v){
      if (v < config['IO Length Max'])
        config['IO Length Min'] = v;
      else
        config['IO Length Min'] = config['IO Length Max'];
    },
    get ['IO Length Max'](){
      return config["IO Length Max"];
    },
    set ["IO Length Max"](v){
      if (v > config['IO Length Min'])
        config['IO Length Max'] = v;
      else
        config['IO Length Max'] = config['IO Length Min'];
    },
    get ["Duration"](){
      return config["Duration"];
    },
    set ["Duration"](v){
      config["Duration"] = v;
    },
    get ["Jobs Start Time"](){
      return config["Jobs Start Time"];
    },
    set ["Jobs Start Time"](v){
      config["Jobs Start Time"] = v;
    },
    'Generate Jobs': function() {
      refreshScheduler(config);
    }
  }

  var TimeQuantum ={
    'Queue 1': 1,
    'Queue 2': 2,
    'Queue 3': 3,
    'Queue 4': 4,
    'Queue 5': 5,
    'Queue 6': 6,
    'Queue 7': 7,
    'Queue 8': 8,
    'Queue 9': 9,
    'Queue 10': 10,
    'Queue 11': 11,
    'Queue 12': 12
  }

//2100 - 200 * config["Speed"];
//this is what is connected to the store
function datGui(props){
    propsParameter = props.parameter
    gui = props.gui;
    if (props.parameter["render"] === true) {
      currentLesson = props.lessonName
      renderGui(gui, propsParameter)
      SchedulerParametersPannel["Speed"] = props.simulation.speed / 1000
      retainSpeed(gui);
    }

    return null;
}

export default Container.createFunctional(datGui, () => [guiStore], () => {
   return guiStore.getState()
});

//------------------------------------- scheduler panel -------------------------------------------
  function displaySchedulerParams(gui, scheduler, TimeQuantum, numberOfQues){
    var menu2 = gui.addFolder("Scheduler Parameters");
      menu2.add(scheduler, 'Boost Time', 10, 100);
      menu2.add(scheduler, 'Trigger Boost')
      menu2.add(SchedulerParametersPannel, "Scheduler Height", 1, 50)
      menu2.add(scheduler, 'Number of Queues',[1,2,3,4,5,6,7,8,9,10,11,12]);
      var Timequantum = menu2.addFolder("Time Quantums");
      for (var i = 1; i <= numberOfQues; i++)
        Timequantum.add(TimeQuantum,'Queue ' + i ,1,20);
      return gui;
  }
//-------------------------------------- work load panel ------------------------------------------
function displayJobGenerator(gui, workload){
    var gui3 = gui;
    var menu3 = gui3.addFolder("Job Generator");
    menu3.add(workload,'Number of Jobs', 1,10);
    menu3.add(workload,'IO Frequency Min', 1,10);
    menu3.add(workload,'IO Frequency Max', 1,10);
    menu3.add(workload,'Duration',1,10);
    menu3.add(workload,'IO Length Min',1,10);
    menu3.add(workload,'IO Length Max',1,10);
    menu3.add(workload,'Generate Jobs');
    return gui;
}

//--------------------------------------for clearing the pannels
function render(gui) {
  clearPanels(gui);
  gui = displaySchedulerParams(gui, SchedulerParametersPannel, TimeQuantum, config["Number of Queues"]);
  gui = displayJobGenerator(gui, JobGeneratorPannel);
  retainSpeed(gui);
}

function renderGui(gui, params) {
  clearPanels(gui);
  const panels = Object.getOwnPropertyNames(params);

  for (let i=0; i<panels.length; i++){

    if(panels[i] === "Scheduler Parameters") {
      const menu = gui.addFolder(panels[i]);
      const SchedulerAttributes = Object.getOwnPropertyNames(params[panels[i]]);

      for (let k = 0; k < SchedulerAttributes.length; k++){

        if (SchedulerAttributes[k] === "Number of Queues"){
          const arr = []
          const numberOfQues = params[panels[i]][SchedulerAttributes[k]];
          config["Number of Queues"] = numberOfQues;

          for (let i = 1; i <= numberOfQues; i++)
            arr.push(i);
          menu.add(SchedulerParametersPannel, SchedulerAttributes[k], arr)

          const Timequantum = menu.addFolder("Time Quantums");
          const tqVals = params[panels[i]]["timeQuantums"];
          const tqDisplayVals = Object.getOwnPropertyNames(TimeQuantum);

          for (let i = 1; i <= numberOfQues; i++) {
            TimeQuantum[tqDisplayVals[i-1]] = tqVals[i-1]
            Timequantum.add(TimeQuantum,'Queue ' + i , 1, 20);
          }

        } else if (SchedulerAttributes[k] === "Boost Time"){
          let boostTime = params[panels[i]][SchedulerAttributes[k]];
          config["Boost Time"] = boostTime;
          menu.add(SchedulerParametersPannel, SchedulerAttributes[k], 1, boostTime)
          menu.add(SchedulerParametersPannel, "Trigger Boost")
        } else if (SchedulerAttributes[k] === "Scheduler Height"){
          menu.add(SchedulerParametersPannel, SchedulerAttributes[k], 1, 50)
        }
      }
    }

    else if (panels[i] === "Job Generator"){
      const SchedulerAttributes = Object.getOwnPropertyNames(params[panels[i]]);
      const menu = gui.addFolder(panels[i]);

      for (let k = 0; k < SchedulerAttributes.length; k++){
        const displayValue = params[panels[i]][SchedulerAttributes[k]];
        config[SchedulerAttributes[k]] = displayValue;
        let max = 20
        if(SchedulerAttributes[k] === "Duration")
          max = 100;

        menu.add(JobGeneratorPannel, SchedulerAttributes[k], 1, max)
      }
      if(currentLesson === "EXPLORE")
        menu.add(JobGeneratorPannel, "Generate Jobs")

    }
  }
  retainSpeed(gui);
}

var reloadReference = 0;
function retainSpeed(gui){
  if (reloadReference === 0)
    reloadReference = gui.add(SchedulerParametersPannel,'Speed',1, 10);
  else {
    gui.remove(reloadReference);
    reloadReference = gui.add(SchedulerParametersPannel,'Speed',1, 10);
  }
}

function clearPanels(gui){
  gui.removeFolder("Scheduler Parameters");
  gui.removeFolder("Job Generator");
}

function createTQs() {
  const myArray = [];
  for (var i = 1; i <= config["Number of Queues"]; i++)
    myArray.push(TimeQuantum["Queue " + i]);
  return myArray;
}

//i suposed to restart the scheduler
function refreshScheduler(config){
    restartScheduler({
          timeQuantums: createTQs(),
          boostTime: config["Boost Time"],
          resetTQsOnIO: false,
          random,
          speed: mainScheduler.speed,
          generation: [{
            ioFrequencyRange: [config["IO Frequency Min"], config["IO Frequency Max"]],
            jobRuntimeRange: [1, config["Duration"]],
            numJobsRange: [config["Number of Jobs"], config["Number of Jobs"]],
            jobCreateTimeRange: [1, 15],
            ioLengthRange: [config["IO Length Min"], config["IO Length Max"]]
          }],
      });
}<|endoftext|>


<commit_before>/*jslint node: true */
/*global require */

module.exports = function (util, events, http) {
    "use strict";

    var getFilterTypes = function (input) {
        var type = [];

        if (input !== undefined) {
            if (typeof input === "string") {
                type.push(input);
            } else if (Array.isArray(input)) {
                var isArrayOfStrings = input.every(function (element) {
                    return (typeof element === "string");
                });

                if (isArrayOfStrings) {
                    type = input;
                }
            }
        }

        return type;
    };

    var search = function () {
        events.EventEmitter.call(this);
    };

    util.inherits(search, events.EventEmitter);

    search.prototype.query = function (query) {
        var that = this;

        var filter = {
            "and" : [
            ]
        };

        var highlight = {
            "fields" : {
                "title" : {}
            },
            "encoder" : "html"
        };

        var requestData = {
            "query" : {
                "filtered" : {
                    query : {}
                }
            },
            "highlight" : highlight
        };

        var q = "";
        var qSuggestion = "";

        if (query.q !== undefined && typeof query.q === "string" && query.q !== "") {
            if (query.suggestion !== undefined) {
                q = "*";
                qSuggestion = query.q;
            } else {
                q = query.q;
                qSuggestion = q;
            }
        } else {
            q = "*";
            qSuggestion = "*";
        }

        requestData.query.filtered.query.query_string = {
            "query" : q,
            "default_operator" : "AND"
        };

        var priceMin;
        var priceMax;

        if (query["price-min"] !== undefined && typeof query["price-min"] === "string") {
            priceMin = query["price-min"].replace(/[^\d]/g, "");
            priceMin = parseInt(priceMin, 10);
        }

        if (query["price-max"] !== undefined && typeof query["price-max"] === "string") {
            priceMax = parseInt(query["price-max"].replace(/[^\d]/g, ""), 10);
            priceMax = parseInt(priceMax, 10);
        }

        if (! isNaN(priceMin) || ! isNaN(priceMax)) {
            var filterPrice = {};
            filterPrice.numeric_range = {};
            filterPrice.numeric_range.price = {};
            if (! isNaN(priceMin)) {
                filterPrice.numeric_range.price.from = priceMin;
            }

            if (! isNaN(priceMax)) {
                filterPrice.numeric_range.price.to = priceMax;
            }

            filter.and.push(filterPrice);
        }

        var filterTypesList = getFilterTypes(query.type);

        if (filterTypesList.length !== 0) {
            var filterTypes = {
                "terms" : {
                    "type" : filterTypesList
                }
            };

            filter.and.push(filterTypes);
        }

        if (filter.and.length !== 0) {
            requestData.query.filtered.filter = filter;
        }

        if (query.sort !== undefined) {
            if (query.sort === "price-min" || query.sort === "price-max") {
                var priceSort;

                if (query.sort === "price-min") {
                    priceSort = "asc";
                } else {
                    priceSort = "desc";
                }

                requestData.sort = [
                    {
                        "price" : {
                            "order" : priceSort,
                            "missing" : "_last",
                            "ignore_unmapped" : true
                        }
                    }
                ];
            }
        }

        if (query.suggestion !== undefined) {
            // see http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
            var qSuggestionEscaped = qSuggestion.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
            requestData.facets = {
                "title_suggestions":{
                    "terms" : {
                        "field" : "title.suggestions",
                        "regex" : "^" + qSuggestionEscaped.toLowerCase() + ".*",
                        "size" : 10
                    }
                }
            };
        }

        var sendBuffer = JSON.stringify(requestData);

        var from = 0;
        var size = 10;

        if (query.suggestion !== undefined) {
            size = 0;
        } else if (query.size !== undefined && ! isNaN(query.size)) {
            size = parseInt(query.size, 10);
        }

        if (query.from !== undefined && ! isNaN(query.from)) {
            from = parseInt(query.from, 10) - 1;
        }

        var postRequest = {
            hostname: "localhost",
            path: "/posts/post/_search?size=" + encodeURIComponent(size) + "&from=" + encodeURIComponent(from),
            port: 9200,
            method: "GET",
            headers: {
                "Content-Length": sendBuffer.length
            }
        };

        var buffer = "";

        var req = http.request(postRequest, function (res) {
            res.on("data", function (data) {
                buffer += data;
            });
            res.on("end", function() {
                if (res.statusCode === 200) {
                    var searchResponse;

                    try {
                        searchResponse = JSON.parse(buffer);
                    } catch (e) {
                        console.error("Error parsing the expected JSON response");

                        that.emit("failure", {
                            errorCode: "parsing-response"
                        });

                        return;
                    }

                    that.emit("success", searchResponse);
                } else {
                    console.warn("Request status code is %s", res.statusCode);
                    that.emit("failure", {
                        errorCode: res.statusCode
                    });
                }
            });
        });
        req.on("error", function (error) {
            that.emit("failure", {
                error: true,
                errorCode: "requestError"
            });
            console.log("elasticsearch request error");
        });
        req.write(sendBuffer);
        req.end();
    };

    exports.search = search;

    return exports;
};
<commit_msg>add facets to the query object<commit_after>/*jslint node: true */
/*global require */

module.exports = function (util, events, http) {
    "use strict";

    var getFilterTypes = function (input) {
        var type = [];

        if (input !== undefined) {
            if (typeof input === "string") {
                type.push(input);
            } else if (Array.isArray(input)) {
                var isArrayOfStrings = input.every(function (element) {
                    return (typeof element === "string");
                });

                if (isArrayOfStrings) {
                    type = input;
                }
            }
        }

        return type;
    };

    var search = function () {
        events.EventEmitter.call(this);
    };

    util.inherits(search, events.EventEmitter);

    search.prototype.query = function (query) {
        var that = this;

        var filter = {
            "and" : [
            ]
        };

        var highlight = {
            "fields" : {
                "title" : {}
            },
            "encoder" : "html"
        };

        var requestData = {
            "query" : {
                "filtered" : {
                    query : {}
                }
            },
            "highlight" : highlight
        };

        var q = "";
        var qSuggestion = "";

        if (query.q !== undefined && typeof query.q === "string" && query.q !== "") {
            if (query.suggestion !== undefined) {
                q = "*";
                qSuggestion = query.q;
            } else {
                q = query.q;
                qSuggestion = q;
            }
        } else {
            q = "*";
            qSuggestion = "*";
        }

        requestData.query.filtered.query.query_string = {
            "query" : q,
            "default_operator" : "AND"
        };

        var priceMin;
        var priceMax;

        if (query["price-min"] !== undefined && typeof query["price-min"] === "string") {
            priceMin = query["price-min"].replace(/[^\d]/g, "");
            priceMin = parseInt(priceMin, 10);
        }

        if (query["price-max"] !== undefined && typeof query["price-max"] === "string") {
            priceMax = parseInt(query["price-max"].replace(/[^\d]/g, ""), 10);
            priceMax = parseInt(priceMax, 10);
        }

        if (! isNaN(priceMin) || ! isNaN(priceMax)) {
            var filterPrice = {};
            filterPrice.numeric_range = {};
            filterPrice.numeric_range.price = {};
            if (! isNaN(priceMin)) {
                filterPrice.numeric_range.price.from = priceMin;
            }

            if (! isNaN(priceMax)) {
                filterPrice.numeric_range.price.to = priceMax;
            }

            filter.and.push(filterPrice);
        }

        var filterTypesList = getFilterTypes(query.type);

        if (filterTypesList.length !== 0) {
            var filterTypes = {
                "terms" : {
                    "type" : filterTypesList
                }
            };

            filter.and.push(filterTypes);
        }

        if (filter.and.length !== 0) {
            requestData.query.filtered.filter = filter;
        }

        if (query.sort !== undefined) {
            if (query.sort === "price-min" || query.sort === "price-max") {
                var priceSort;

                if (query.sort === "price-min") {
                    priceSort = "asc";
                } else {
                    priceSort = "desc";
                }

                requestData.sort = [
                    {
                        "price" : {
                            "order" : priceSort,
                            "missing" : "_last",
                            "ignore_unmapped" : true
                        }
                    }
                ];
            }
        }

        if (query.suggestion !== undefined) {
            // see http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
            var qSuggestionEscaped = qSuggestion.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
            requestData.facets = {
                "title_suggestions":{
                    "terms" : {
                        "field" : "title.suggestions",
                        "regex" : "^" + qSuggestionEscaped.toLowerCase() + ".*",
                        "size" : 10
                    }
                }
            };
        } else {
            requestData.facets = {
                "type" : {
                    "terms" : {
                        "field" : "type"
                    }
                },
                "make": {
                    "terms" : {
                        "field" : "make",
                        "size" : 10
                    }
                },
                "model" : {
                    "terms" : {
                        "field" : "model",
                        "size" : 10
                    }
                },
                "price" : {
                    "range" : {
                        "price" : [
                            { "from" : 0, "to" : 999999 },
                            { "from" : 1000000, "to" : 1999999 },
                            { "from" : 2000000, "to" : 2999999 },
                            { "from" : 3000000, "to" : 3999999 },
                            { "from" : 4000000, "to" : 4999999 },
                            { "from" : 5000000, "to" : 7999999 },
                            { "from" : 8000000, "to" : 8999999 },
                            { "from" : 9000000, "to" : 9999999 },
                            { "from" : 10000000 }
                        ]
                    }
                },
                "model_year": {
                    "terms" : {
                        "field" : "model_year",
                            "size" : 10
                    }
                },
                "where" : {
                    "terms" : {
                        "script_field" : "_source.user.address.locality + ' - ' + _source.user.address.region",
                        "size" : 10
                    }
                }
            };
        }

        var sendBuffer = JSON.stringify(requestData);

        var from = 0;
        var size = 10;

        if (query.suggestion !== undefined) {
            size = 0;
        } else if (query.size !== undefined && ! isNaN(query.size)) {
            size = parseInt(query.size, 10);
        }

        if (query.from !== undefined && ! isNaN(query.from)) {
            from = parseInt(query.from, 10) - 1;
        }

        var postRequest = {
            hostname: "localhost",
            path: "/posts/post/_search?size=" + encodeURIComponent(size) + "&from=" + encodeURIComponent(from),
            port: 9200,
            method: "GET",
            headers: {
                "Content-Length": sendBuffer.length
            }
        };

        var buffer = "";

        var req = http.request(postRequest, function (res) {
            res.on("data", function (data) {
                buffer += data;
            });
            res.on("end", function() {
                if (res.statusCode === 200) {
                    var searchResponse;

                    try {
                        searchResponse = JSON.parse(buffer);
                    } catch (e) {
                        console.error("Error parsing the expected JSON response");

                        that.emit("failure", {
                            errorCode: "parsing-response"
                        });

                        return;
                    }

                    that.emit("success", searchResponse);
                } else {
                    console.warn("Request status code is %s", res.statusCode);
                    that.emit("failure", {
                        errorCode: res.statusCode
                    });
                }
            });
        });
        req.on("error", function (error) {
            that.emit("failure", {
                error: true,
                errorCode: "requestError"
            });
            console.log("elasticsearch request error");
        });
        req.write(sendBuffer);
        req.end();
    };

    exports.search = search;

    return exports;
};
<|endoftext|>


<commit_before>var async = require('async'),
    Path = require('path'),
    fs = require('fs');

class Processor {
    constructor(settings, logger, plugins, memcached, items) {
        this.settings = settings;
        this.logger = logger;
        this.plugins = plugins;
        this.items = items;
        this.memcached = memcached;
        if(!Processor.emojis) {
            try {
                Processor.emojis = JSON.parse(fs.readFileSync(Path.join(__dirname, 'emoji', 'db.json')));
            } catch(ex) {
                this.logger.error('parser', 'Error preloading emoji database. Mayhem is on its way!');
                Processor.emojis = null;
            }
        }
    }

    getEmojiUnicode(name) {
        var result = name;
        if(Processor.emojis) {
            var item = Processor.emojis.find((e) => e.aliases.indexOf(name) > -1);
            if(item) {
                result = item.emoji;
            } else {
                this.logger.warn('getEmojiUnicode', `Unknown emoji: ${name}`);
            }
        }
        return result;
    }

    addMeta(result, doc) {
        var copiable = ['user', 'date', 'channel'];
        var obj = doc[1];
        copiable.forEach((k) => result[k] = obj[k]);
        result.url = doc[0];
        result.id = obj._id;
        this.memcached.set(['d-', doc[1].ts].join(''), JSON.stringify(result), 2592000, (err) => {
            if(err) {
                this.logger.error('memcached', 'Error storing cache data: ', err);
            }
        });
        return result;
    }

    runPlugins(doc, callback, index) {
        index = index || 0;
        var plug = this.plugins[index];
        if(!plug) {
            // Plugin list is over, and yet document could not be processed.
            callback(null, this.addMeta({
                type: 'poor-link',
                url: doc[0]
            }, doc));
            return;
        } else {
            if(plug.canHandle(doc[0])) {
                plug.process(doc[0], (result) => {
                    if(!result) {
                        this.runPlugins(doc, callback, ++index);
                    } else {
                        if(plug.constructor.isUrlTransformer) {
                            doc[0] = result;
                            this.runPlugins(doc, callback, ++index);
                        } else {
                            callback(null, this.addMeta(result, doc));
                        }
                    }
                });
            } else {
                this.runPlugins(doc, callback, ++index);
            }
        }
    }

    getCached(processable, cached, callback) {
        var item = this.items.shift();
        if(!item) {
            callback();
        } else {
            this.memcached.get(['d-', item[1].ts].join(''), (err, r) => {
                if(err || !r) {
                    if(err) {
                        this.logger.error('memcached', 'Error getting item from cache: ', err);
                    }
                    processable.push(item);
                } else {
                    var c = JSON.parse(r);
                    c.reactions = item[1].reactions;
                    cached.push(c);
                }
                this.getCached(processable, cached, callback);
            });
        }
    }

    process(callback) {
        var processable = [],
            cached = [];
        this.getCached(processable, cached, () => {
            this.logger.verbose('processor', `Process result: ${cached.length} cached item(s), ${processable.length} processable items.`);
            async.map(processable, this.runPlugins.bind(this), (err, result) => {
                if(err) {
                    this.logger.error('processor', 'Error running async plugns:', err);
                }
                result = (result || []).filter((r) => r);
                this.digest([].concat(cached, result), callback);
            });
        });
    }

    digest(result, callback) {
        var context = { users: [], items: [], itemsForUser: { } };
        result.forEach((i) => {
            i.reactions = Object.keys(i.reactions)
                .map(r => ({ name: r, count: obj.reactions[r], repr: this.getEmojiUnicode(r) }))
                .sort((a, b) => b.count - a.count);

            if(!context.users.some(u => u.username === i.user.username)) {
                context.users.push(i.user);
            }
            if(!context.itemsForUser[i.user.username]) {
                context.itemsForUser[i.user.username] = [];
            }
            var totalReactions = i.reactions
                .map(r => r.count);
            if(totalReactions.length) {
                totalReactions = totalReactions.reduce((a, b) => a + b);
            } else {
                totalReactions = 0;
            }
            i.totalReactions = totalReactions;
            context.itemsForUser[i.user.username].push(i);
            context.items.push(i);
            var u = context.users.find(u => u.username === i.user.username);
            if(!u.emojis) {
                u.emojis = {};
            }
            i.reactions.forEach(r => {
                if(!u.emojis[r.name]) {
                    u.emojis[r.name] = {
                        name: r.name,
                        repr: this.getEmojiUnicode(r.name),
                        count: 0
                    };
                }
                u.emojis[r.name].count += r.count;
            });
        });
        context.users = context.users.map(u => {
            u.emojis = Object.keys(u.emojis)
                .map((k) => u.emojis[k])
                .sort((a, b) => b.count - a.count)
                .map((o) => o.repr);
            return u;
        });
        context.items = context.items.sort((a, b) => b.totalReactions - a.totalReactions);
        callback(null, context);
    }
}

module.exports = Processor;
<commit_msg>Ensure cached items receive new reactions<commit_after>var async = require('async'),
    Path = require('path'),
    fs = require('fs');

class Processor {
    constructor(settings, logger, plugins, memcached, items) {
        this.settings = settings;
        this.logger = logger;
        this.plugins = plugins;
        this.items = items;
        this.memcached = memcached;
        if(!Processor.emojis) {
            try {
                Processor.emojis = JSON.parse(fs.readFileSync(Path.join(__dirname, 'emoji', 'db.json')));
            } catch(ex) {
                this.logger.error('parser', 'Error preloading emoji database. Mayhem is on its way!');
                Processor.emojis = null;
            }
        }
    }

    getEmojiUnicode(name) {
        var result = name;
        if(Processor.emojis) {
            var item = Processor.emojis.find((e) => e.aliases.indexOf(name) > -1);
            if(item) {
                result = item.emoji;
            } else {
                this.logger.warn('getEmojiUnicode', `Unknown emoji: ${name}`);
            }
        }
        return result;
    }

    addMeta(result, doc) {
        var copiable = ['user', 'date', 'channel', 'reactions'];
        var obj = doc[1];
        copiable.forEach((k) => result[k] = obj[k]);
        result.url = doc[0];
        result.id = obj._id;
        this.memcached.set(['d-', doc[1].ts].join(''), JSON.stringify(result), 2592000, (err) => {
            if(err) {
                this.logger.error('memcached', 'Error storing cache data: ', err);
            }
        });
        return result;
    }

    runPlugins(doc, callback, index) {
        index = index || 0;
        var plug = this.plugins[index];
        if(!plug) {
            // Plugin list is over, and yet document could not be processed.
            callback(null, this.addMeta({
                type: 'poor-link',
                url: doc[0]
            }, doc));
            return;
        } else {
            if(plug.canHandle(doc[0])) {
                plug.process(doc[0], (result) => {
                    if(!result) {
                        this.runPlugins(doc, callback, ++index);
                    } else {
                        if(plug.constructor.isUrlTransformer) {
                            doc[0] = result;
                            this.runPlugins(doc, callback, ++index);
                        } else {
                            callback(null, this.addMeta(result, doc));
                        }
                    }
                });
            } else {
                this.runPlugins(doc, callback, ++index);
            }
        }
    }

    getCached(processable, cached, callback) {
        var item = this.items.shift();
        if(!item) {
            callback();
        } else {
            this.memcached.get(['d-', item[1].ts].join(''), (err, r) => {
                if(err || !r) {
                    if(err) {
                        this.logger.error('memcached', 'Error getting item from cache: ', err);
                    }
                    processable.push(item);
                } else {
                    var c = JSON.parse(r);
                    c.reactions = item[1].reactions;
                    cached.push(c);
                }
                this.getCached(processable, cached, callback);
            });
        }
    }

    process(callback) {
        var processable = [],
            cached = [];
        this.getCached(processable, cached, () => {
            this.logger.verbose('processor', `Process result: ${cached.length} cached item(s), ${processable.length} processable items.`);
            async.map(processable, this.runPlugins.bind(this), (err, result) => {
                if(err) {
                    this.logger.error('processor', 'Error running async plugns:', err);
                }
                result = (result || []).filter((r) => r);
                this.digest([].concat(cached, result), callback);
            });
        });
    }

    digest(result, callback) {
        var context = { users: [], items: [], itemsForUser: { } };
        result.forEach((i) => {
            i.reactions = Object.keys(i.reactions)
                .map(r => ({ name: r, count: i.reactions[r], repr: this.getEmojiUnicode(r) }))
                .sort((a, b) => b.count - a.count);

            if(!context.users.some(u => u.username === i.user.username)) {
                context.users.push(i.user);
            }
            if(!context.itemsForUser[i.user.username]) {
                context.itemsForUser[i.user.username] = [];
            }
            var totalReactions = i.reactions
                .map(r => r.count);
            if(totalReactions.length) {
                totalReactions = totalReactions.reduce((a, b) => a + b);
            } else {
                totalReactions = 0;
            }
            i.totalReactions = totalReactions;
            context.itemsForUser[i.user.username].push(i);
            context.items.push(i);
            var u = context.users.find(u => u.username === i.user.username);
            if(!u.emojis) {
                u.emojis = {};
            }
            i.reactions.forEach(r => {
                if(!u.emojis[r.name]) {
                    u.emojis[r.name] = {
                        name: r.name,
                        repr: this.getEmojiUnicode(r.name),
                        count: 0
                    };
                }
                u.emojis[r.name].count += r.count;
            });
        });
        context.users = context.users.map(u => {
            u.emojis = Object.keys(u.emojis)
                .map((k) => u.emojis[k])
                .sort((a, b) => b.count - a.count)
                .map((o) => o.repr);
            return u;
        });
        context.items = context.items.sort((a, b) => b.totalReactions - a.totalReactions);
        callback(null, context);
    }
}

module.exports = Processor;
<|endoftext|>


<commit_before>/*
 * @name Restreamer
 * @namespace https://github.com/datarhei/restreamer
 * @copyright 2015 datarhei.org
 * @license Apache-2.0
 */

'use strict';

/*
    libraries
 */
//auth stuff
const passport = require('passport');
const flash    = require('connect-flash');

//express
const express = require('express');
const session = require('express-session');
const i18n = require('i18n');
const favicon = require('serve-favicon');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const compression = require("compression");

//other
const path = require('path');
const Q = require("q");
const request = require("request");

/*
    modules
 */
const packageJson = require("../../package.json");
const Logger = require("../classes/Logger");
const logger = new Logger("Webserver");
//middlewares
const expressLogger = require("./middlewares/expressLogger");

//create express app
const app = express();

app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true})); // session secret

//create promise for "websockets ready"
app.set("websocketsReady", Q.defer());

//add passport auth
app.use(passport.initialize());
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(passport.session()); // persistent login sessions
require("./config/passport")(passport);

//configure i18n
i18n.configure({
    locales:['en','de'],
    directory: __dirname + '/locales',
    defaultLocale: 'en',
    cookie: 'locale',
    updateFiles: false
});

//configure express app
app.use(favicon(__dirname + '/public/images/favicon.ico'));
app.use(i18n.init);
app.use(bodyParser.json());
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(compression());
app.set('json spaces', 4);

require("./controllers/index")(app, passport);
app.use('/', expressLogger);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found ' + req.url);
    err.status = 404;
    next(err);
});

// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.send({
        message: err.message,
        error: {}
    });
});

var checkForAppUpdates = function(){
    logger.debug("checking app for updates...");
    const url = 'http://datarhei.org/apps.json';
    request(url, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            var updateCheck = JSON.parse(body);
            var updateAvailable = false;
            if (updateCheck.restreamer.version === packageJson.version){
                updateAvailable = false;
                logger.debug("checking app for updates successful. update is not available (remote: " + updateCheck.restreamer.version + ", local: " + packageJson.version + ")");
            }else{
                updateAvailable = updateCheck.restreamer.version;
                logger.debug("checking app for updates successful. update is available (remote: " + updateCheck.restreamer.version + ", local: " + packageJson.version + ")");
            }
            logger.info("checking app for updates successful.");
            app.set("updateAvailable", updateAvailable);
        } else {
            logger.info("Update check failed", false);
        }
    });
};

//start interval to check for updates
checkForAppUpdates();
setInterval(checkForAppUpdates, 24 * 60 * 60 * 1000);

module.exports = app;
<commit_msg>MOD: create random session key on app start as suggested in issue #2<commit_after>/*
 * @name Restreamer
 * @namespace https://github.com/datarhei/restreamer
 * @copyright 2015 datarhei.org
 * @license Apache-2.0
 */

'use strict';

/*
    libraries
 */
//auth stuff
const passport = require('passport');
const flash    = require('connect-flash');

//express
const express = require('express');
const session = require('express-session');
const i18n = require('i18n');
const favicon = require('serve-favicon');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const compression = require("compression");

//other
const path = require('path');
const Q = require("q");
const request = require("request");
const crypto = require("crypto");

/*
 modules
 */
const packageJson = require("../../package.json");
const Logger = require("../classes/Logger");
const logger = new Logger("Webserver");
//middlewares
const expressLogger = require("./middlewares/expressLogger");

//create express app
const app = express();

//generate random key
const secretKey = crypto.randomBytes(64).toString('hex');

app.use(session({
    secret: secretKey,
    resave: false,
    saveUninitialized: true})); // session secret

//create promise for "websockets ready"
app.set("websocketsReady", Q.defer());

//add passport auth
app.use(passport.initialize());
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(passport.session()); // persistent login sessions
require("./config/passport")(passport);

//configure i18n
i18n.configure({
    locales:['en','de'],
    directory: __dirname + '/locales',
    defaultLocale: 'en',
    cookie: 'locale',
    updateFiles: false
});

//configure express app
app.use(favicon(__dirname + '/public/images/favicon.ico'));
app.use(i18n.init);
app.use(bodyParser.json());
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(compression());
app.set('json spaces', 4);

require("./controllers/index")(app, passport);
app.use('/', expressLogger);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found ' + req.url);
    err.status = 404;
    next(err);
});

// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.send({
        message: err.message,
        error: {}
    });
});

var checkForAppUpdates = function(){
    logger.debug("checking app for updates...");
    const url = 'http://datarhei.org/apps.json';
    request(url, function (error, response, body) {
        if (!error && response.statusCode === 200) {
            var updateCheck = JSON.parse(body);
            var updateAvailable = false;
            if (updateCheck.restreamer.version === packageJson.version){
                updateAvailable = false;
                logger.debug("checking app for updates successful. update is not available (remote: " + updateCheck.restreamer.version + ", local: " + packageJson.version + ")");
            }else{
                updateAvailable = updateCheck.restreamer.version;
                logger.debug("checking app for updates successful. update is available (remote: " + updateCheck.restreamer.version + ", local: " + packageJson.version + ")");
            }
            logger.info("checking app for updates successful.");
            app.set("updateAvailable", updateAvailable);
        } else {
            logger.info("Update check failed", false);
        }
    });
};

//start interval to check for updates
checkForAppUpdates();
setInterval(checkForAppUpdates, 24 * 60 * 60 * 1000);

module.exports = app;
<|endoftext|>