<commit_before>// ==UserScript==
// @name            TagPro Telestrator
// @version         1.0.1
// @description     Use a telestrator while spectating TagPro!
// @include         http://tagpro-*.koalabeast.com:*
// @include         http://tangent.jukejuice.com:*
// @include         http://maptest.newcompte.fr:*
// @author          BBQchicken
// ==/UserScript==

tagpro.ready(function() {

// ---------- KICK TOGGLE ---------- \\
var noClick = true;

// ---------- HELPER METHODS ---------- \\
	function canvasMousePosition(click) {
		var boundBox = viewPort.getBoundingClientRect();
		return {
			x: click.clientX  - 9 - boundBox.left,
			y: click.clientY - 12 - boundBox.top
		};
	}

	//converts canvas coordinates to the corresponding in-game coordinates
	function canvasToTagpro(click) {
		//canvas coordinates of mouse click
		var canvasCoords = canvasMousePosition(click);

		//canvas coordinates of camera target
		var srcCoords = {x: viewPort.width / 2 - 20 / tagpro.zoom, y: viewPort.height / 2 - 20 / tagpro.zoom};

		//vector from camera target to mouse click in canvas pixels
		var canvasDiff = {x: canvasCoords.x - srcCoords.x, y: canvasCoords.y - srcCoords.y};

		//vector from camera target to mouse click in in-game pixels
		var tpDiff = {x: canvasDiff.x * tagpro.zoom, y: canvasDiff.y * tagpro.zoom};

		return {
			x: tagpro.viewPort.source.x + tpDiff.x,
			y: tagpro.viewPort.source.y + tpDiff.y
		};
	}

// ---------- POINT CLASS ---------- \\

	//represents a point in the game's coordinates.
	//constructor takes a pair of canvas coordinates, i.e. from a click event.
	var Point = function(click) {
		var coords = canvasToTagpro(click);

		this.x = coords.x;
		this.y = coords.y;

		//the inverse operation of canvasToTagpro
		this.toCanvas = function() {
			//in-game coordinates of camera target
			var tpSrcCoords = {x: tagpro.viewPort.source.x, y: tagpro.viewPort.source.y};

			//canvas coordinates of camera target
			var canvasSrcCoords = {x: viewPort.width / 2 - 20 / tagpro.zoom, y: viewPort.height / 2 - 20 / tagpro.zoom};

			//vector from camera target to click in in-game pixels
			var tpDiff = {x: this.x - tpSrcCoords.x, y: this.y - tpSrcCoords.y};

			//vector from camera target to click in canvas pixels
			var canvasDiff = {x: tpDiff.x / tagpro.zoom, y: tpDiff.y / tagpro.zoom};

			return {
				x: canvasSrcCoords.x + canvasDiff.x,
				y: canvasSrcCoords.y + canvasDiff.y
			};
		}
	}

// ---------- CURVE CLASS ---------- \\

	var Curve = function(start) {
		var points = [new Point(start)];

		this.addPoint = function(point) {
			points.push(new Point(point));
		}

		function drawSmooth(context, points) {
			context.beginPath();

			context.strokeStyle = 'rgba(245, 221, 0, 0.6)';
			context.lineWidth = 5;

			//http://stackoverflow.com/questions/7054272/how-to-draw-smooth-curve-through-n-points-using-javascript-html5-canvas
			context.moveTo(points[0].x, points[0].y);
			var i = 1;
			for(var control = {x: 0, y: 0}; i < points.length - 2; i++) {
				control.x = (points[i].x + points[i + 1].x) / 2;
				control.y = (points[i].y + points[i + 1].y) / 2;
				context.quadraticCurveTo(points[i].x, points[i].y, control.x, control.y);
			}
			context.quadraticCurveTo(points[i].x, points[i].y, points[i+1].x, points[i+1].y);

			context.stroke();
		}

		this.draw = function(context) {
			if(points.length < 3) { return false; }

			context.save();
			drawSmooth(context, points.map(function(point) { return point.toCanvas(); }));
			context.restore();
		}
	};

// ---------- ARROW CLASS ---------- \\
var Arrow = function(_start) {
	var headAngle = .4;  // ~22.5 degrees in radians
	var wingLength = 45; //length in TagPro pixels

	var start = new Point(_start), end = new Point(_start), rightWing = new Point(_start), leftWing = new Point(_start);
	var angle = 0;

	function rotateHead() {
		var phiRight = angle + headAngle;
		rightWing.x = end.x - wingLength * Math.cos(phiRight);
		rightWing.y = end.y - wingLength * Math.sin(phiRight);

		var phiLeft = angle - headAngle;
		leftWing.x = end.x - wingLength * Math.cos(phiLeft);
		leftWing.y = end.y - wingLength * Math.sin(phiLeft);
	}

	this.moveEnd = function(_end) {
		end = new Point(_end);
		angle = Math.atan2(end.y - start.y, end.x - start.x);
		rotateHead();
	}

	//takes a context and canvas coordinates
	function drawLine(context, start, end) {
		context.beginPath();

		context.strokeStyle = 'rgba(200, 0, 250, 0.6)';
		context.lineWidth = 5;
		context.lineCap = 'round';

		context.moveTo(start.x, start.y);
		context.lineTo(end.x, end.y);

		context.stroke();
	}

	this.draw = function(context) {
		context.save();
		drawLine(context, end.toCanvas(), start.toCanvas());
		drawLine(context, end.toCanvas(), rightWing.toCanvas());
		drawLine(context, end.toCanvas(), leftWing.toCanvas());
		context.restore();
	}
};

// ---------- HIGH LEVEL LOGIC ----------\\

	tpkick = tagpro.kick.clickBall;
	tagpro.kick.clickBall = function(event) {
		if (!noClick) { tpkick (event); }
	}

	var curves = [], arrows = [];
	var drawCurve = false, drawArrow = false, shift = false;

	var tpUiDraw = tagpro.ui.draw;
	tagpro.ui.draw = function(context) {
		curves.forEach(function(element) {
			element.draw(context);
		});

		arrows.forEach(function(element) {
			element.draw(context);
		});

		tpUiDraw(context);
	};

	$(document).on("keydown keyup", function (event) { shift = event.shiftKey; });

	$("canvas#viewPort").mousedown(function(click) {
		if (tagpro.spectator !== "watching") { return false; }
		if (shift) {
			drawArrow = true;
			arrows.push(new Arrow(click));
		} else {
			drawCurve = true;
			curves.push(new Curve(click));
		}
	});

	$("canvas#viewPort").mousemove(function(event) {
		if (drawArrow) {
			arrows[arrows.length -1].moveEnd(event);
		} else if (drawCurve) {
			curves[curves.length - 1].addPoint(event);
		}
	});

	$("canvas#viewPort").mouseup(function(event) {
		drawCurve = false;
		drawArrow = false;
	});

	$("canvas#viewPort").dblclick(function(event) {
		curves = [];
		arrows = [];
	});

});<commit_msg>Donate Button bug fix<commit_after>// ==UserScript==
// @name            TagPro Telestrator
// @version         1.0.2
// @description     Use a telestrator while spectating TagPro!
// @include         http://tagpro-*.koalabeast.com:*
// @include         http://tangent.jukejuice.com:*
// @include         http://maptest.newcompte.fr:*
// @author          BBQchicken
// ==/UserScript==

tagpro.ready(function() {

// ---------- KICK TOGGLE ---------- \\
var noClick = true;

// ---------- HELPER METHODS ---------- \\
	function canvasMousePosition(click) {
		var boundBox = viewPort.getBoundingClientRect();
		return {
			x: click.clientX  - 9 - boundBox.left,
			y: click.clientY - 12 - boundBox.top
		};
	}

	//converts canvas coordinates to the corresponding in-game coordinates
	function canvasToTagpro(click) {
		//canvas coordinates of mouse click
		var canvasCoords = canvasMousePosition(click);

		//canvas coordinates of camera target
		var srcCoords = {x: viewPort.width / 2 - 20 / tagpro.zoom, y: viewPort.height / 2 - 20 / tagpro.zoom};

		//vector from camera target to mouse click in canvas pixels
		var canvasDiff = {x: canvasCoords.x - srcCoords.x, y: canvasCoords.y - srcCoords.y};

		//vector from camera target to mouse click in in-game pixels
		var tpDiff = {x: canvasDiff.x * tagpro.zoom, y: canvasDiff.y * tagpro.zoom};

		return {
			x: tagpro.viewPort.source.x + tpDiff.x,
			y: tagpro.viewPort.source.y + tpDiff.y
		};
	}

// ---------- POINT CLASS ---------- \\

	//represents a point in the game's coordinates.
	//constructor takes a pair of canvas coordinates, i.e. from a click event.
	var Point = function(click) {
		var coords = canvasToTagpro(click);

		this.x = coords.x;
		this.y = coords.y;

		//the inverse operation of canvasToTagpro
		this.toCanvas = function() {
			//in-game coordinates of camera target
			var tpSrcCoords = {x: tagpro.viewPort.source.x, y: tagpro.viewPort.source.y};

			//canvas coordinates of camera target
			var canvasSrcCoords = {x: viewPort.width / 2 - 20 / tagpro.zoom, y: viewPort.height / 2 - 20 / tagpro.zoom};

			//vector from camera target to click in in-game pixels
			var tpDiff = {x: this.x - tpSrcCoords.x, y: this.y - tpSrcCoords.y};

			//vector from camera target to click in canvas pixels
			var canvasDiff = {x: tpDiff.x / tagpro.zoom, y: tpDiff.y / tagpro.zoom};

			return {
				x: canvasSrcCoords.x + canvasDiff.x,
				y: canvasSrcCoords.y + canvasDiff.y
			};
		}
	}

// ---------- CURVE CLASS ---------- \\

	var Curve = function(start) {
		var points = [new Point(start)];

		this.addPoint = function(point) {
			points.push(new Point(point));
		}

		function drawSmooth(context, points) {
			context.beginPath();

			context.strokeStyle = 'rgba(245, 221, 0, 0.6)';
			context.lineWidth = 5;

			//http://stackoverflow.com/questions/7054272/how-to-draw-smooth-curve-through-n-points-using-javascript-html5-canvas
			context.moveTo(points[0].x, points[0].y);
			var i = 1;
			for(var control = {x: 0, y: 0}; i < points.length - 2; i++) {
				control.x = (points[i].x + points[i + 1].x) / 2;
				control.y = (points[i].y + points[i + 1].y) / 2;
				context.quadraticCurveTo(points[i].x, points[i].y, control.x, control.y);
			}
			context.quadraticCurveTo(points[i].x, points[i].y, points[i+1].x, points[i+1].y);

			context.stroke();
		}

		this.draw = function(context) {
			if(points.length < 3) { return false; }

			context.save();
			drawSmooth(context, points.map(function(point) { return point.toCanvas(); }));
			context.restore();
		}
	};

// ---------- ARROW CLASS ---------- \\
var Arrow = function(_start) {
	var headAngle = .4;  // ~22.5 degrees in radians
	var wingLength = 45; //length in TagPro pixels

	var start = new Point(_start), end = new Point(_start), rightWing = new Point(_start), leftWing = new Point(_start);
	var angle = 0;

	function rotateHead() {
		var phiRight = angle + headAngle;
		rightWing.x = end.x - wingLength * Math.cos(phiRight);
		rightWing.y = end.y - wingLength * Math.sin(phiRight);

		var phiLeft = angle - headAngle;
		leftWing.x = end.x - wingLength * Math.cos(phiLeft);
		leftWing.y = end.y - wingLength * Math.sin(phiLeft);
	}

	this.moveEnd = function(_end) {
		end = new Point(_end);
		angle = Math.atan2(end.y - start.y, end.x - start.x);
		rotateHead();
	}

	//takes a context and canvas coordinates
	function drawLine(context, start, end) {
		context.beginPath();

		context.strokeStyle = 'rgba(200, 0, 250, 0.6)';
		context.lineWidth = 5;
		context.lineCap = 'round';

		context.moveTo(start.x, start.y);
		context.lineTo(end.x, end.y);

		context.stroke();
	}

	this.draw = function(context) {
		context.save();
		drawLine(context, end.toCanvas(), start.toCanvas());
		drawLine(context, end.toCanvas(), rightWing.toCanvas());
		drawLine(context, end.toCanvas(), leftWing.toCanvas());
		context.restore();
	}
};

// ---------- HIGH LEVEL LOGIC ----------\\

	tpkick = tagpro.kick.clickBall;
	tagpro.kick.clickBall = function(event) {
		if (!noClick) { tpkick (event); }
	}

	var curves = [], arrows = [];
	var drawCurve = false, drawArrow = false, shift = false;

	var tpUiDraw = tagpro.ui.draw;
	tagpro.ui.draw = function(context) {
		curves.forEach(function(element) {
			element.draw(context);
		});

		arrows.forEach(function(element) {
			element.draw(context);
		});

		tpUiDraw(context);
	};

	$(document).on("keydown keyup", function (event) { shift = event.shiftKey; });

	$("canvas#viewPort").mousedown(function(click) {
		if (tagpro.spectator !== "watching") { return false; }
		if (shift) {
			drawArrow = true;
			arrows.push(new Arrow(click));
		} else {
			drawCurve = true;
			curves.push(new Curve(click));
		}
	});

	$("canvas#viewPort").mousemove(function(event) {
		if (drawArrow) {
			arrows[arrows.length -1].moveEnd(event);
		} else if (drawCurve) {
			curves[curves.length - 1].addPoint(event);
		}
	});

	$("canvas#viewPort").mouseup(function(event) {
		drawCurve = false;
		drawArrow = false;
	});

	$("canvas#viewPort").dblclick(function(event) {
		curves = [];
		arrows = [];

		//clear the selection on the donate button which sometimes keeps you from redrawing.
		window.getSelection().removeAllRanges();

	});

});<|endoftext|>


<commit_before>/*
 *
 * Description:
 * This file holds the controller logic.  It manages the connection to the Atmega328.
 *
 */
var path = require('path')
  , spawn = require('child_process').spawn
  , CONFIG = require('./config')
  , StatusReader = require('./StatusReader')
  , ArduinoPhysics = require('./ArduinoPhysics')
  , logger = require('./logger').create(CONFIG)
  , EventEmitter = require('events').EventEmitter
  , Hardware = require('../' + CONFIG.Hardware);

var setup_serial = function(){
    var location = path.join(__dirname, '..', './linux')
    logger.log('Starting the script from ' + location +' to setup UART1...');
    var setuart_process = spawn('sudo', [ path.join(location,'setuart.sh') ]);
};

var navdata = {
    roll: 0,
    pitch: 0,
    yaw: 0,
    thrust: 0,
    deapth : 0,
    hdgd: 0
}

var settingsCollection = {
    smoothingIncriment: 0,
    deadZone_min: 0,
    deadZone_max: 0
}

var rovsys = {
    capabilities: 0
}

var OpenROVController = function(eventLoop) {
  var serial;
  var globalEventLoop = eventLoop;
  var reader = new StatusReader();
  var physics = new ArduinoPhysics();
  var hardware = new Hardware();
  var controller = new EventEmitter();

  setInterval((function() {
    controller.emit('navdata',navdata);
  }), 100);

  hardware.on('status', function(status) {
    controller.emit('status',status);

    if ('ver' in status) {
      controller.ArduinoFirmwareVersion = status.ver;
    }
    if ('TSET' in status) {
      console.log(status.settings);
      var setparts = status.settings.split(",");
      settingsCollection.smoothingIncriment = setparts[0];
      settingsCollection.deadZone_min = setparts[1];
      settingsCollection.deadZone_max = setparts[2];
      controller.emit('Arduino-settings-reported',settingsCollection)
    }
    if ('CAPA' in status) {
      var s = rovsys;
      console.log("RovSys: " + status.CAPA)
      s.capabilities = parseInt(status.CAPA);
      controller.Capabilities= s.capabilities;
      controller.emit('rovsys',s);
    }
    if ('cmd' in status) {
      var s = rovsys;
      console.log("cmd: " + status.cmd)
    }
    if ('log' in status) {
      var s = rovsys;
      console.log("log: " + status.log)
    }
    if ('hdgd' in status) {
      navdata.hdgd=status.hdgd;
    }
    if ('deap' in status) {
      navdata.deapth=status.deap;
    }
    if ('pitc' in status) {
      navdata.pitch=status.pitc;
    }
    if ('roll' in status) {
      navdata.roll=status.roll;
    }
    if ('yaw' in status) {
      navdata.yaw=status.yaw;
    }
    if ('fthr' in status) {
      navdata.thrust=status.fthr;
    }
  });

  setup_serial();

  hardware.connect();

  controller.ArduinoFirmwareVersion = 0;
  controller.Capabilities = 0;

  controller.requestCapabilities = function(){
    console.log("Sending rcap to arduino");
    var command = 'rcap();';
    hardware.write(command);
  };

  controller.requestSettings = function(){
    var command = 'reportSetting();';
    hardware.write(command);
  };

  controller.updateSetting = function(){
    var command = 'updateSetting(' + CONFIG.preferences.get('smoothingIncriment') + ',' + physics.mapMotor(CONFIG.preferences.get('deadzone_neg')) + ','+ physics.mapMotor(CONFIG.preferences.get('deadzone_pos')) + ');';
    hardware.write(command);
  };

  controller.notSafeToControl = function(){ //Arduino is OK to accept commands
    if (this.ArduinoFirmwareVersion >= .20130314034859) return false;
    if (this.Capabilities != 0) return false; //This feature added after the swap to ms on the Arduino
    console.log('Audrino is at an incompatible version of firmware. Upgrade required before controls will respond');
    console.log(this.ArduinoFirmwareVersion);
    console.log(this.Capabilities);
    return true;
  };

  controller.send = function(cmd) {
    var command = cmd + ';';
    if(CONFIG.debug_commands) console.error("command", command);
    if(CONFIG.production) serial.write(command);
  };

  controller.sendMotorTest = function(port, starbord, vertical) {
    if (this.notSafeToControl()) return;
    var command = 'go(' + physics.mapRawMotor(port) + ',' + physics.mapRawMotor(vertical) + ',' + physics.mapRawMotor(starbord) + ',1);'; //the 1 bypasses motor smoothing
    hardware.write(command);
  };

  controller.sendCommand = function(throttle, yaw, vertical) {
    if (this.notSafeToControl()) return;
    var motorCommands = physics.mapMotors(throttle, yaw, vertical);
    var command = 'go(' + motorCommands.port + ',' + motorCommands.vertical + ',' + motorCommands.starbord + ');';
    hardware.write(command);
  };

  controller.sendTilt = function(value) {
    if (this.notSafeToControl()) return;
    var servoTilt = physics.mapTiltServo(value);
    var command = 'tilt(' + servoTilt +');';
    hardware.write(command);
  };

  controller.sendLight = function(value) {
    if (this.notSafeToControl()) return;
    var light = physics.mapLight(value);
    var command = 'light(' + light +');';
    hardware.write(command);
  };

  var claserstate = 0;
  controller.sendLaser = function(value) {
    if (this.notSafeToControl()) return;
    if (claserstate === 0) {
      claserstate = 255;
    }
    else {
      claserstate = 0;
    }

    var command = 'claser(' + claserstate +');';
    hardware.write(command);
  };

    controller.stop = function(value) {
        if (this.notSafeToControl()) return;
        var command = 'stop();';
        hardware.write(command);
    };

    controller.start = function(value) {
        if (this.notSafeToControl()) return;
        var command = 'start();';
        hardware.write(command);
    };

  globalEventLoop.on('register-ArdunoFirmwareVersion', function(val){
        controller.ArduinoFirmwareVersion = val;
  });

  globalEventLoop.on('register-ArduinoCapabilities', function(val){
        controller.Capabilities = val;
  });

  globalEventLoop.on('serial-stop', function(){
	logger.log("Closing serial connection for firmware upload");
	hardware.close();
	 });

  globalEventLoop.on('serial-start', function(){
	hardware.connect();
	controller.updateSetting();
	logger.log("Opened serial connection after firmware upload");
	});

  return controller;
}

module.exports = OpenROVController;
<commit_msg>Fixed browser performance issue<commit_after>/*
 *
 * Description:
 * This file holds the controller logic.  It manages the connection to the Atmega328.
 *
 */
var path = require('path')
  , spawn = require('child_process').spawn
  , CONFIG = require('./config')
  , StatusReader = require('./StatusReader')
  , ArduinoPhysics = require('./ArduinoPhysics')
  , logger = require('./logger').create(CONFIG)
  , EventEmitter = require('events').EventEmitter
  , Hardware = require('../' + CONFIG.Hardware);

var setup_serial = function(){
    var location = path.join(__dirname, '..', './linux')
    logger.log('Starting the script from ' + location +' to setup UART1...');
    var setuart_process = spawn('sudo', [ path.join(location,'setuart.sh') ]);
};

var navdata = {
    roll: 0,
    pitch: 0,
    yaw: 0,
    thrust: 0,
    deapth : 0,
    hdgd: 0
}

var statusdata = new Object();

var settingsCollection = {
    smoothingIncriment: 0,
    deadZone_min: 0,
    deadZone_max: 0
}

var rovsys = {
    capabilities: 0
}

var OpenROVController = function(eventLoop) {
  var serial;
  var globalEventLoop = eventLoop;
  var reader = new StatusReader();
  var physics = new ArduinoPhysics();
  var hardware = new Hardware();
  var controller = new EventEmitter();

  setInterval((function() {
    controller.emit('navdata',navdata);
  }), 100);

  setInterval((function() {
    controller.emit('status',statusdata);
  }), 1000);

  hardware.on('status', function(status) {
    for (i in status){
	statusdata[i] = status[i];
    }

    if ('ver' in status) {
      controller.ArduinoFirmwareVersion = status.ver;
    }
    if ('TSET' in status) {
      console.log(status.settings);
      var setparts = status.settings.split(",");
      settingsCollection.smoothingIncriment = setparts[0];
      settingsCollection.deadZone_min = setparts[1];
      settingsCollection.deadZone_max = setparts[2];
      controller.emit('Arduino-settings-reported',settingsCollection)
    }
    if ('CAPA' in status) {
      var s = rovsys;
      console.log("RovSys: " + status.CAPA)
      s.capabilities = parseInt(status.CAPA);
      controller.Capabilities= s.capabilities;
      controller.emit('rovsys',s);
    }
    if ('cmd' in status) {
      var s = rovsys;
      console.log("cmd: " + status.cmd)
    }
    if ('log' in status) {
      var s = rovsys;
      console.log("log: " + status.log)
    }
    if ('hdgd' in status) {
      navdata.hdgd=status.hdgd;
    }
    if ('deap' in status) {
      navdata.deapth=status.deap;
    }
    if ('pitc' in status) {
      navdata.pitch=status.pitc;
    }
    if ('roll' in status) {
      navdata.roll=status.roll;
    }
    if ('yaw' in status) {
      navdata.yaw=status.yaw;
    }
    if ('fthr' in status) {
      navdata.thrust=status.fthr;
    }
  });

  setup_serial();

  hardware.connect();

  controller.ArduinoFirmwareVersion = 0;
  controller.Capabilities = 0;

  controller.requestCapabilities = function(){
    console.log("Sending rcap to arduino");
    var command = 'rcap();';
    hardware.write(command);
  };

  controller.requestSettings = function(){
    var command = 'reportSetting();';
    hardware.write(command);
  };

  controller.updateSetting = function(){
    var command = 'updateSetting(' + CONFIG.preferences.get('smoothingIncriment') + ',' + physics.mapMotor(CONFIG.preferences.get('deadzone_neg')) + ','+ physics.mapMotor(CONFIG.preferences.get('deadzone_pos')) + ');';
    hardware.write(command);
  };

  controller.notSafeToControl = function(){ //Arduino is OK to accept commands
    if (this.ArduinoFirmwareVersion >= .20130314034859) return false;
    if (this.Capabilities != 0) return false; //This feature added after the swap to ms on the Arduino
    console.log('Audrino is at an incompatible version of firmware. Upgrade required before controls will respond');
    console.log(this.ArduinoFirmwareVersion);
    console.log(this.Capabilities);
    return true;
  };

  controller.send = function(cmd) {
    var command = cmd + ';';
    if(CONFIG.debug_commands) console.error("command", command);
    if(CONFIG.production) serial.write(command);
  };

  controller.sendMotorTest = function(port, starbord, vertical) {
    if (this.notSafeToControl()) return;
    var command = 'go(' + physics.mapRawMotor(port) + ',' + physics.mapRawMotor(vertical) + ',' + physics.mapRawMotor(starbord) + ',1);'; //the 1 bypasses motor smoothing
    hardware.write(command);
  };

  controller.sendCommand = function(throttle, yaw, vertical) {
    if (this.notSafeToControl()) return;
    var motorCommands = physics.mapMotors(throttle, yaw, vertical);
    var command = 'go(' + motorCommands.port + ',' + motorCommands.vertical + ',' + motorCommands.starbord + ');';
    hardware.write(command);
  };

  controller.sendTilt = function(value) {
    if (this.notSafeToControl()) return;
    var servoTilt = physics.mapTiltServo(value);
    var command = 'tilt(' + servoTilt +');';
    hardware.write(command);
  };

  controller.sendLight = function(value) {
    if (this.notSafeToControl()) return;
    var light = physics.mapLight(value);
    var command = 'light(' + light +');';
    hardware.write(command);
  };

  var claserstate = 0;
  controller.sendLaser = function(value) {
    if (this.notSafeToControl()) return;
    if (claserstate === 0) {
      claserstate = 255;
    }
    else {
      claserstate = 0;
    }

    var command = 'claser(' + claserstate +');';
    hardware.write(command);
  };

    controller.stop = function(value) {
        if (this.notSafeToControl()) return;
        var command = 'stop();';
        hardware.write(command);
    };

    controller.start = function(value) {
        if (this.notSafeToControl()) return;
        var command = 'start();';
        hardware.write(command);
    };

  globalEventLoop.on('register-ArdunoFirmwareVersion', function(val){
        controller.ArduinoFirmwareVersion = val;
  });

  globalEventLoop.on('register-ArduinoCapabilities', function(val){
        controller.Capabilities = val;
  });

  globalEventLoop.on('serial-stop', function(){
	logger.log("Closing serial connection for firmware upload");
	hardware.close();
	 });

  globalEventLoop.on('serial-start', function(){
	hardware.connect();
	controller.updateSetting();
	logger.log("Opened serial connection after firmware upload");
	});

  return controller;
}

module.exports = OpenROVController;
<|endoftext|>


<commit_before>/***********************************************************************************/
/*
 File:    weathernode.js
 Purpose: AngularJs controller for the node hosted weather page
 Author:  Christian Kuster, CH-8342 Wernetshausen, www.kusti.ch, 22.9.14
 Github:  https://github.com/ancasicolica/qwesta

 ----------------------------------------------------------------------------------

 This is free and unencumbered software released into the public domain.

 Anyone is free to copy, modify, publish, use, compile, sell, or
 distribute this software, either in source code form or as a compiled
 binary, for any purpose, commercial or non-commercial, and by any
 means.

 In jurisdictions that recognize copyright laws, the author or authors
 of this software dedicate any and all copyright interest in the
 software to the public domain. We make this dedication for the benefit
 of the public at large and to the detriment of our heirs and
 successors. We intend this dedication to be an overt act of
 relinquishment in perpetuity of all present and future rights to this
 software under copyright law.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.

 For more information, please refer to <http://unlicense.org/>

 */
/***********************************************************************************/

var weatherApp = angular.module('weatherApp', []);

weatherApp.controller('WeatherCtrl',['$scope', '$http', '$interval', function($scope, $http, $interval) {

  this.stationName = "Wetterstation";
  this.iconFolder = "./img/icon32/";
  // This entry contains the current record
  this.currentRecord = {
    humidity: 0,
    isRaining: false,
    rain: 0,
    temperature: 0.0,
    timestamp: "2000-01-01T00:00:00.000Z",
    wind          : 0.0,
    rainDifference: 0.0
  };

  this.records;

  this.temperatureTrendImage = this.iconFolder + "arrow456.png";
  this.humidityTrendImage = this.iconFolder + "arrow456.png";

  this.getCurrentRecordTime = function() {
    var d = new Date(this.currentRecord.timestamp);
    var s = d.toLocaleTimeString();
    return s;
  }
  /**
   * The interval timer retrieving the data
   */
  var timer = $interval(function() {
    $scope.data.getCurrentData(null, null);
  }, 10000);

  /**
   * Sets the data read from the ajax call
   * @param data
   */
  this.setData = function(data) {
    $scope.parent.records = data;
    var cr = data[data.length - 1]
    $scope.parent.currentRecord = cr;

    // Analysis
    if (data.length > 3) {
      // Evaluate average of temperature and humidity while removing the highest
      // and lowest value
      var temperatureAvg = 0.0;
      var humidityAvg = 0.0;
      var humidityMax = 0.0;
      var humidityMin = 99.9;
      var temperatureMax = -50.0;
      var temperatureMin = 99.0;

      for (var i = 0; i < data.length; i++) {
        temperatureAvg += data[i].temperature;
        humidityAvg += data[i].humidity;
        if (humidityMax < data[i].humidity) {
          humidityMax = data[i].humidity;
        }
        if (humidityMin > data[i].humidity) {
          humidityMin = data[i].humidity;
        }
        if (temperatureMax < data[i].temperature) {
          temperatureMax = data[i].temperature;
        }
        if (temperatureMin > data[i].temperature) {
          temperatureMin = data[i].temperature;
        }

      }
      temperatureAvg = (temperatureAvg - temperatureMax - temperatureMin) / (data.length - 2);
      humidityAvg = (humidityAvg - humidityMax - humidityMin) / (data.length - 2);

      // TODO: better algorithm, is to exact now
      console.log("avg temp: " + temperatureAvg);
      console.log("cur temp: " + cr.temperature);
      if (cr.temperature > temperatureAvg) {
        $scope.parent.temperatureTrendImage = $scope.parent.iconFolder + "arrow448.png";
      }
      else if (cr.temperature < temperatureAvg) {
        $scope.parent.temperatureTrendImage = $scope.parent.iconFolder + "arrow453.png";
      }
      else {
        $scope.parent.temperatureTrendImage = $scope.parent.iconFolder + "arrow456.png";
      }

      if (cr.humidity > temperatureAvg) {
        $scope.parent.humidityTrendImage = $scope.parent.iconFolder + "arrow448.png";
      }
      else if (cr.humidity < temperatureAvg) {
        $scope.parent.humidityTrendImage = $scope.parent.iconFolder + "arrow453.png";
      }
      else {
        $scope.parent.humidityTrendImage = $scope.parent.iconFolder + "arrow456.png";
      }
    }
  };

  $scope.SuccessCallback = this.setData;
  $scope.parent = this;
  $scope.data = {};
  /**
   * Gets the current data from the webserver over an ajax call
   * @param item
   * @param event
   * @returns {boolean}
   */
  $scope.data.getCurrentData = function(item, event) {

    var responsePromise = $http.get("ajax/current.html", null);
    // Success handling
    responsePromise.success(function(data, status, headers, config) {
      $scope.data.fromServer = "Text: " + data + "
status:" + status;
      $scope.SuccessCallback(data);
      $scope.tab = 5;
    });
    // Error handling
    responsePromise.error(function(data, status, headers, config) {
      //alert("AJAX failed!");
    });
    return true;
  }
  // immediately request current data
  $scope.data.getCurrentData(null, null);
}]);
<commit_msg>- Temperature Chart, first draft<commit_after>/***********************************************************************************/
/*
 File:    weathernode.js
 Purpose: AngularJs controller for the node hosted weather page
 Author:  Christian Kuster, CH-8342 Wernetshausen, www.kusti.ch, 22.9.14
 Github:  https://github.com/ancasicolica/qwesta

 ----------------------------------------------------------------------------------

 This is free and unencumbered software released into the public domain.

 Anyone is free to copy, modify, publish, use, compile, sell, or
 distribute this software, either in source code form or as a compiled
 binary, for any purpose, commercial or non-commercial, and by any
 means.

 In jurisdictions that recognize copyright laws, the author or authors
 of this software dedicate any and all copyright interest in the
 software to the public domain. We make this dedication for the benefit
 of the public at large and to the detriment of our heirs and
 successors. We intend this dedication to be an overt act of
 relinquishment in perpetuity of all present and future rights to this
 software under copyright law.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.

 For more information, please refer to <http://unlicense.org/>

 */
/***********************************************************************************/

var weatherApp = angular.module('weatherApp', []);

weatherApp.controller('WeatherCtrl',['$scope', '$http', '$interval', function($scope, $http, $interval) {

  this.stationName = "Wetterstation";
  this.iconFolder = "./img/icon32/";
  // This entry contains the current record
  this.currentRecord = {
    humidity: 0,
    isRaining: false,
    rain: 0,
    temperature: 0.0,
    timestamp: "2000-01-01T00:00:00.000Z",
    wind          : 0.0,
    rainDifference: 0.0
  };

  this.records;

  this.temperatureTrendImage = this.iconFolder + "arrow456.png";
  this.humidityTrendImage = this.iconFolder + "arrow456.png";

  this.getCurrentRecordTime = function() {
    var d = new Date(this.currentRecord.timestamp);
    var s = d.toLocaleTimeString();
    return s;
  }
  /**
   * The interval timer retrieving the data
   */
  var timer = $interval(function() {
    $scope.data.getCurrentData('ajax/current.html', $scope.currentDataCallback);
  }, 10000);

  /**
   * Sets the data read from the ajax call
   * @param data
   */
  this.setData = function(data) {
    $scope.parent.records = data;
    var cr = data[data.length - 1]
    $scope.parent.currentRecord = cr;

    // Analysis
    if (data.length > 3) {
      // Evaluate average of temperature and humidity while removing the highest
      // and lowest value
      var temperatureAvg = 0.0;
      var humidityAvg = 0.0;
      var humidityMax = 0.0;
      var humidityMin = 99.9;
      var temperatureMax = -50.0;
      var temperatureMin = 99.0;

      for (var i = 0; i < data.length; i++) {
        temperatureAvg += data[i].temperature;
        humidityAvg += data[i].humidity;
        if (humidityMax < data[i].humidity) {
          humidityMax = data[i].humidity;
        }
        if (humidityMin > data[i].humidity) {
          humidityMin = data[i].humidity;
        }
        if (temperatureMax < data[i].temperature) {
          temperatureMax = data[i].temperature;
        }
        if (temperatureMin > data[i].temperature) {
          temperatureMin = data[i].temperature;
        }

      }
      temperatureAvg = (temperatureAvg - temperatureMax - temperatureMin) / (data.length - 2);
      humidityAvg = (humidityAvg - humidityMax - humidityMin) / (data.length - 2);

      // TODO: better algorithm, is to exact now
      console.log("avg temp: " + temperatureAvg);
      console.log("cur temp: " + cr.temperature);
      if (cr.temperature > temperatureAvg) {
        $scope.parent.temperatureTrendImage = $scope.parent.iconFolder + "arrow448.png";
      }
      else if (cr.temperature < temperatureAvg) {
        $scope.parent.temperatureTrendImage = $scope.parent.iconFolder + "arrow453.png";
      }
      else {
        $scope.parent.temperatureTrendImage = $scope.parent.iconFolder + "arrow456.png";
      }

      if (cr.humidity > temperatureAvg) {
        $scope.parent.humidityTrendImage = $scope.parent.iconFolder + "arrow448.png";
      }
      else if (cr.humidity < temperatureAvg) {
        $scope.parent.humidityTrendImage = $scope.parent.iconFolder + "arrow453.png";
      }
      else {
        $scope.parent.humidityTrendImage = $scope.parent.iconFolder + "arrow456.png";
      }
    }
  };

  this.loadTemperatureChart = function () {
    $scope.data.getCurrentData('ajax/temperature.html', $scope.temperatureDataCallback);
  }
  this.drawTemperatureChart = function (data) {
    console.log(data);
    drawTemperatureChart(data);
  };

  $scope.currentDataCallback = this.setData;
  $scope.temperatureDataCallback = this.drawTemperatureChart;
  $scope.parent = this;
  $scope.data = {};
  /**
   * Gets the current data from the webserver over an ajax call
   * @param url the url to retrieve
   * @param callback will be called afterwards
   * @returns {boolean}
   */
  $scope.data.getCurrentData = function (url, callback) {

    var responsePromise = $http.get(url, null);
    // Success handling
    responsePromise.success(function(data, status, headers, config) {
      $scope.data.fromServer = "Text: " + data + "
status:" + status;
      callback(data);
    });
    // Error handling
    responsePromise.error(function(data, status, headers, config) {
      //alert("AJAX failed!");
    });
    return true;
  };
  // immediately request current data
  $scope.data.getCurrentData('ajax/current.html', $scope.currentDataCallback);
}]);
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const Busboy = require('busboy');
const concat = require('concat-stream');
const options = {
	method: 'diskstorage',
	directory: '',
	filename: '',
	mimetype: '',
	limits: {

	},
	keys: {

	}
};

const fileHandler = (req, res, next) => {
	if(req.method == "POST") {
		if(req._body) {
			return next();
		}
		req.body = {};
		req.files = {};
		let busboy = new Busboy({
			headers: req.headers,
			limits: options.limits
		});
		busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
			let save_filename = options.filename || filename;
			let uploadInfo = {
				options: options,
				filename: save_filename,
				mimetype: mimetype,
				fieldname: fieldname,
				file: file,
				encoding: encoding
			}
			let file_contents = require(path.join(__dirname, options.method))
													(uploadInfo, req, next);
			file.on('data', (data) => {
				if (!req._file) {
					req._file = true; // setting req._file to true to show at least 1 file has valid buffer
				}
				if (!req.files[fieldname]) {
					req.files[fieldname] = {
						_file: true // there is data in this particular file
					};
				}
				file_contents.write(data);
			});
			file.on('limit', () => {
				console.log("Limit reached");
			});
			file.on('end', () => {
				if (!file.truncated && req._file) {
					file_contents.end();
				} else {
					// File upload failed from limit being reached
				}
				req._body = true;
			});
		});

		busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => {
			req.body[fieldname] = val;
		});
		busboy.on('finish', () => {
			if(!req._file) {
				// no file was uploaded
				return next();
			}
			console.log("Finished receiving user input, actions depends on method");
		});
		req.pipe(busboy);
	} else {
		return next();
	}
}

module.exports = (user_options) => {
	options.method = user_options.method || "diskstorage";
	options.directory = user_options.directory || "";
	options.filename = user_options.filename || "";
	options.mimetype = user_options.mimetype || "";
	options.limits.fileSize = user_options.maxfileSize || "";
	options.keys = user_options.keys || "";

	return fileHandler;
}
<commit_msg>express-form-post converted to object model<commit_after>const fs = require('fs');
const path = require('path');
const Busboy = require('busboy');
const concat = require('concat-stream');

var ExpressFormPost = function(user_options) {
	this.options = {
		method: user_options.method || "diskstorage",
		directory: user_options.directory || "",
		filename: user_options.filename || "",
		mimetype: user_options.mimetype || "",
		limits: {
			fileSize: user_options.maxfileSize || ""
		},
		keys: user_options.keys || ""
	};
}

const fileHandler = function(req, res, next) {
	if(req.method == "POST") {
		if(req._body) {
			return next();
		}
		req.body = {};
		req.files = {};
		let busboy = new Busboy({
			headers: req.headers,
			limits: this.options.limits
		});
		busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
			let save_filename = this.options.filename || filename;
			let uploadInfo = {
				options: this.options,
				filename: save_filename,
				mimetype: mimetype,
				fieldname: fieldname,
				file: file,
				encoding: encoding
			}
			let file_contents = require(path.join(__dirname, this.options.method))
													(uploadInfo, req, next);
			file.on('data', (data) => {
				if (!req._file) {
					req._file = true; // setting req._file to true to show at least 1 file has valid buffer
				}
				if (!req.files[fieldname]) {
					req.files[fieldname] = {
						_file: true // there is data in this particular file
					};
				}
				file_contents.write(data);
			});
			file.on('limit', () => {
				console.log("Limit reached");
			});
			file.on('end', () => {
				if (!file.truncated && req._file) {
					file_contents.end();
				} else {
					// File upload failed from limit being reached
				}
				req._body = true;
			});
		});

		busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => {
			req.body[fieldname] = val;
		});
		busboy.on('finish', () => {
			if(!req._file) {
				// no file was uploaded
				return next();
			}
			console.log("Finished receiving user input, actions depends on method");
		});
		req.pipe(busboy);
	} else {
		return next();
	}
}

ExpressFormPost.prototype.default  = function() {
	return fileHandler.bind(this);
}

module.exports = ExpressFormPost;<|endoftext|>


<commit_before>/**
 * @file xsdwebform.parser.js
 * XSD Schema to HTML5 Web Form
 * @author George Bouris <gb@eworx.gr>
 * @copyright Copyright (C) 2017 EEA, Eworx, George Bouris. All rights reserved.
 */
'use strict';

import { XmlDocument } from 'xmldoc';
import XsdTagParser from './xsdwebform.parser.xsd.js';
import HtmlTagParser from './xsdwebform.parser.html.js';
import XsltGenerator from './xsdwebform.parser.xslt.js';
import DocGenerator from './xsdwebform.parser.doc.js';
import XSDWebFormParserLog from './xsdwebform.parser.log.js';

/**
 * Class XSDWebFormParser
 * Parser for XSD Schema to HTML5
 */
class XSDWebFormParser {
	/**
	 * Class constructor
	 * @param showlog
	 * @param verbose
	 */
	constructor(baseFileName, showlog = false, verbose = false,  showXSDLog  = true) {
		this.xsdTagParser = new XsdTagParser();
		this.htmlTagParser = new HtmlTagParser();
		this.xsltGenerator = new XsltGenerator();
		this.docGenerator = new DocGenerator();
		this.logger = new XSDWebFormParserLog();
		this.baseFileName = baseFileName;

		this.htmlOutput = {
			content: '',
			HTMLObjects: []
		};

		this.showLog = showlog;
		this.verbose = verbose;
		this.showXSDLog = showXSDLog;

		this.xsdTagParser.setLogger(this.logger);
		this.xsdTagParser.setLog(this.showLog);
		this.xsdTagParser.setVerbose((this.showLog && this.verbose));
		this.htmlTagParser.setLogger(this.logger);
		this.htmlTagParser.setLog(this.showLog);
		this.htmlTagParser.setVerbose((this.showLog && this.verbose));
		this.xsltGenerator.setLogger(this.logger);
		this.xsltGenerator.setLog(this.showLog);
		this.xsltGenerator.setVerbose((this.showLog && this.verbose));
		this.docGenerator.setLogger(this.logger);
		this.docGenerator.setLog(this.showLog);
		this.docGenerator.setVerbose((this.showLog && this.verbose));
	}

	/**
	 * parse - Parse XML Document
	 * @param xml
	 */
	parse(xObject) {
		if (this.showLog && this.showXSDLog)
			this.logger.logXSD(xObject);

		// Create XML Document for XSD
		var xsdItem = new XmlDocument(xObject.xdata);
		xsdItem.level = 0;

		if (this.showLog && this.showXSDLog)
			this.xsdTagParser.xsdParse(xsdItem);

		if (this.showLog)
			this.logger.logHTML(xObject);

		// Create XML Document for FORM.XML
		var htmlItem = new XmlDocument(xObject.hdata);
		htmlItem.level = 0;
		this.htmlTagParser.htmlParse(htmlItem, xsdItem);

		// Create HTML output
		this.htmlOutput.HTMLObjects = this.htmlTagParser.HTMLObjects;
		this.htmlOutput.content = this.createHTMLOutput();

		// Create XSLT output
		this.xslt = this.xsltGenerator.createXSLTOutput(htmlItem);
		this.xsltXml = this.xsltGenerator.createXMLOutput(htmlItem, this.baseFileName);

		// Create Doc output
		this.doc = this.docGenerator.createDocOutput(htmlItem);

		if (this.showLog)
			this.logger.showLogs(this);
	}

	/**
	 * createHTMLOutput
	 */
	createHTMLOutput() {
		var html = [];

		for (let f = 0, t = this.htmlOutput.HTMLObjects.length; f < t; f++) {
			let form = this.htmlOutput.HTMLObjects[f];
			let formHtml = [];

			html.splice(html.length + 1, 0, "\t\t" + form.itemObject.tagToHtml(this, 1));
			let groups = this.htmlOutput.HTMLObjects[f].itemObject.groups;
			html.splice(groups.length + html.length + 1, 0, "\t\t</" + form.itemObject.tag + ">");

			for (let i = 0, l = groups.length; i < l; i++) {
				let group = groups[i];

				formHtml.push(`\t\t<div id="form-area-${form.itemObject.name}">`);
				formHtml.push(`\t\t
 0">`);

				if (group.itemObject.prepend)
					formHtml.push("\t\t" + group.itemObject.prepend);

				formHtml.push("\t\t\t\t" + group.itemObject.tagToHtml(this.htmlTagParser, 3));

				let groupPlaceholders = [];

				for (let i2 = 0, l2 = groups[i].itemObject.items.length; i2 < l2; i2++) {
					let ngshow = '';
					if (groups[i].itemObject.items[i2].hide && groups[i].itemObject.items[i2].attrs.hideonautoselect == 1) {
						ngshow = ' ng-show="' + groups[i].itemObject.items[i2].hide + '"';
					}

					if (groups[i].itemObject.items[i2].appendAfter)
						groupPlaceholders.push({ pos: i2 + groups[i].itemObject.items[i2].appendAfter, content: groups[i].itemObject.items[i2].appendAfterContent  });

					if (!groups[i].itemObject.items[i2].noDiv)
						formHtml.push("\t\t\t
\n\t\t\t\t" + groups[i].itemObject.items[i2].tagToHtml(this.htmlTagParser) + "\n\t\t\t
");
					else
						formHtml.push(groups[i].itemObject.items[i2].tagToHtml(this.htmlTagParser, 3));

					groupPlaceholders.forEach((item) =>{
						if (item.pos === i2) {
							formHtml.push("\n\t\t\t" + item.content);
						}

					});
				}

				formHtml.push("\t\t</" + group.itemObject.tag + ">");

				formHtml.push('\t\t
');
				formHtml.push('\t\t
');

				if (group.itemObject.append)
					formHtml.push("\t\t\t" + group.itemObject.append);
			}

			if (form.itemObject.append)
				formHtml.push("\t\t\t" + form.itemObject.append);

			html.splice(html.length - 1, 0, formHtml.join('\n\n'));
		}
		return html.join("\n\n");
	}

	/**
	 * getHTMLOutput - Return HTML5 Document
	 */
	getHTMLOutput() {
		return this.htmlOutput.content ;
	}

	/**
	 * getXSLTOutput - Return XSLT Document
	 */
	getXSLTOutput() {
		return this.xslt;
	}

	/**
	 * getXSLTXMLOutput - Return XSLT Document
	 */
	getXSLTXMLOutput() {
		return this.xsltXml;
	}

	/**
	 * getDocOutput - Return Document
	 */
	getDocOutput() {
		return this.doc;
	}

	/**
	 * getLanguageContent - Return Text Content
	 */
	getLanguageContent() {
		// Remove duplicate labels
		let exists = {};
		let filteredLabels = this.htmlTagParser.LabelContentObjects.filter((item) => {
			if (exists[item.label])
				return false;

			exists[item.label] = 1;
			return true;
		});

		exists = {};
		let filteredText = this.htmlTagParser.TextContentObjects.filter((item) => {
			if (exists[item.label])
				return false;

			exists[item.label] = 1;
			return true;
		});

		let TextContentObjectsLength = filteredText.length - 1;
		filteredLabels.push( { "text" : filteredText.map((label, index) => {
			if (index < TextContentObjectsLength)
				return `\t\t\t\t\t\t\t\t\t"${label.label}" : \t\t${JSON.stringify(label.text.toString())},`;
			else
				return `\t\t\t\t\t\t\t\t\t"${label.label}" : \t\t${JSON.stringify(label.text.toString())}`;
		}).join("\n") } );

		let labelContentObjectsLength = filteredLabels.length - 1;
		let LabelContentObjects =  filteredLabels.map((label, index) => {
			if (!label.label)
				return `\t\t\t\t\t"text" : \t\t {\n ${label.text} \n\t\t\t\t\t\t\t\t}`;
			if (index < labelContentObjectsLength)
				return `\t\t\t\t\t"${label.label}" : \t\t${JSON.stringify(label.text.toString())},`;
			else
				return `\t\t\t\t\t"${label.label}" : \t\t${JSON.stringify(label.text.toString())}`;
		}).join("\n");

		return LabelContentObjects;
	}

	/**
	 * getFullTextContent - getLanguageContent - Return Full JSON Text Content
	 */
	getFullTextContent() {
		let textContent = this.getLanguageContent();
		var fullTextContent = `{
	"language" 		: "Selected Language English",
	"isrequired"		: "is mandatory",
	"addrow"		: "Add Row",
	"deleterow"		: "Delete Row",
	"number" 		: "#",
	"submitform" 		: "Submit",
	"edit" 		: "Edit",
	"chooselanguage" 	: "Choose Language",
	"validation" 		: "Validation",
	"on" 			: "On",
	"off" 			: "Off",
	"save" 			: "Save",
	"printpreview" 		: "Print Preview",
	"close" 		: "Close",
	"labels"		: {
${textContent}
				}
}`;
		return fullTextContent;
	}

}

module.exports = XSDWebFormParser;<commit_msg>Code Cleanup<commit_after>/**
 * @file xsdwebform.parser.js
 * XSD Schema to HTML5 Web Form
 * @author George Bouris <gb@eworx.gr>
 * @copyright Copyright (C) 2017 EEA, Eworx, George Bouris. All rights reserved.
 */
'use strict';

import { XmlDocument } from 'xmldoc';
import XsdTagParser from './xsdwebform.parser.xsd.js';
import HtmlTagParser from './xsdwebform.parser.html.js';
import XsltGenerator from './xsdwebform.parser.xslt.js';
import DocGenerator from './xsdwebform.parser.doc.js';
import XSDWebFormParserLog from './xsdwebform.parser.log.js';

/**
 * Class XSDWebFormParser
 * Parser for XSD Schema to HTML5
 */
class XSDWebFormParser {
	/**
	 * Class constructor
	 * @param showlog
	 * @param verbose
	 */
	constructor(baseFileName, showlog = false, verbose = false,  showXSDLog = true) {
		this.xsdTagParser = new XsdTagParser();
		this.htmlTagParser = new HtmlTagParser();
		this.xsltGenerator = new XsltGenerator();
		this.docGenerator = new DocGenerator();
		this.logger = new XSDWebFormParserLog();
		this.baseFileName = baseFileName;

		this.htmlOutput = {
			content: '',
			HTMLObjects: []
		};

		this.showLog = showlog;
		this.verbose = verbose;
		this.showXSDLog = showXSDLog;

		this.xsdTagParser.setLogger(this.logger);
		this.xsdTagParser.setLog(this.showLog);
		this.xsdTagParser.setVerbose((this.showLog && this.verbose));
		this.htmlTagParser.setLogger(this.logger);
		this.htmlTagParser.setLog(this.showLog);
		this.htmlTagParser.setVerbose((this.showLog && this.verbose));
		this.xsltGenerator.setLogger(this.logger);
		this.xsltGenerator.setLog(this.showLog);
		this.xsltGenerator.setVerbose((this.showLog && this.verbose));
		this.docGenerator.setLogger(this.logger);
		this.docGenerator.setLog(this.showLog);
		this.docGenerator.setVerbose((this.showLog && this.verbose));
	}

	/**
	 * parse - Parse XML Document
	 * @param xml
	 */
	parse(xObject) {
		if (this.showLog && this.showXSDLog)
			this.logger.logXSD(xObject);

		// Create XML Document for XSD
		var xsdItem = new XmlDocument(xObject.xdata);
		xsdItem.level = 0;

		if (this.showLog && this.showXSDLog)
			this.xsdTagParser.xsdParse(xsdItem);

		if (this.showLog)
			this.logger.logHTML(xObject);

		// Create XML Document for FORM.XML
		var htmlItem = new XmlDocument(xObject.hdata);
		htmlItem.level = 0;
		this.htmlTagParser.htmlParse(htmlItem, xsdItem);

		// Create HTML output
		this.htmlOutput.HTMLObjects = this.htmlTagParser.HTMLObjects;
		this.htmlOutput.content = this.createHTMLOutput();

		// Create XSLT output
		this.xslt = this.xsltGenerator.createXSLTOutput(htmlItem);
		this.xsltXml = this.xsltGenerator.createXMLOutput(htmlItem, this.baseFileName);

		// Create Doc output
		this.doc = this.docGenerator.createDocOutput(htmlItem);

		if (this.showLog)
			this.logger.showLogs(this);
	}

	/**
	 * createHTMLOutput
	 */
	createHTMLOutput() {
		var html = [];

		for (let f = 0, t = this.htmlOutput.HTMLObjects.length; f < t; f++) {
			let form = this.htmlOutput.HTMLObjects[f];
			let formHtml = [];

			html.splice(html.length + 1, 0, "\t\t" + form.itemObject.tagToHtml(this, 1));
			let groups = this.htmlOutput.HTMLObjects[f].itemObject.groups;
			html.splice(groups.length + html.length + 1, 0, "\t\t</" + form.itemObject.tag + ">");

			for (let i = 0, l = groups.length; i < l; i++) {
				let group = groups[i];

				formHtml.push(`\t\t<div id="form-area-${form.itemObject.name}">`);
				formHtml.push(`\t\t
 0">`);

				if (group.itemObject.prepend)
					formHtml.push("\t\t" + group.itemObject.prepend);

				formHtml.push("\t\t\t\t" + group.itemObject.tagToHtml(this.htmlTagParser, 3));

				let groupPlaceholders = [];

				for (let i2 = 0, l2 = groups[i].itemObject.items.length; i2 < l2; i2++) {
					let ngshow = '';
					if (groups[i].itemObject.items[i2].hide && groups[i].itemObject.items[i2].attrs.hideonautoselect == 1) {
						ngshow = ' ng-show="' + groups[i].itemObject.items[i2].hide + '"';
					}

					if (groups[i].itemObject.items[i2].appendAfter)
						groupPlaceholders.push({ pos: i2 + groups[i].itemObject.items[i2].appendAfter, content: groups[i].itemObject.items[i2].appendAfterContent  });

					if (!groups[i].itemObject.items[i2].noDiv)
						formHtml.push("\t\t\t
\n\t\t\t\t" + groups[i].itemObject.items[i2].tagToHtml(this.htmlTagParser) + "\n\t\t\t
");
					else
						formHtml.push(groups[i].itemObject.items[i2].tagToHtml(this.htmlTagParser, 3));

					groupPlaceholders.forEach((item) =>{
						if (item.pos === i2) {
							formHtml.push("\n\t\t\t" + item.content);
						}

					});
				}

				formHtml.push("\t\t</" + group.itemObject.tag + ">");

				formHtml.push('\t\t
');
				formHtml.push('\t\t
');

				if (group.itemObject.append)
					formHtml.push("\t\t\t" + group.itemObject.append);
			}

			if (form.itemObject.append)
				formHtml.push("\t\t\t" + form.itemObject.append);

			html.splice(html.length - 1, 0, formHtml.join('\n\n'));
		}
		return html.join("\n\n");
	}

	/**
	 * getHTMLOutput - Return HTML5 Document
	 */
	getHTMLOutput() {
		return this.htmlOutput.content ;
	}

	/**
	 * getXSLTOutput - Return XSLT Document
	 */
	getXSLTOutput() {
		return this.xslt;
	}

	/**
	 * getXSLTXMLOutput - Return XSLT Document
	 */
	getXSLTXMLOutput() {
		return this.xsltXml;
	}

	/**
	 * getDocOutput - Return Document
	 */
	getDocOutput() {
		return this.doc;
	}

	/**
	 * getLanguageContent - Return Text Content
	 */
	getLanguageContent() {
		// Remove duplicate labels
		let exists = {};
		let filteredLabels = this.htmlTagParser.LabelContentObjects.filter((item) => {
			if (exists[item.label])
				return false;

			exists[item.label] = 1;
			return true;
		});

		exists = {};
		let filteredText = this.htmlTagParser.TextContentObjects.filter((item) => {
			if (exists[item.label])
				return false;

			exists[item.label] = 1;
			return true;
		});

		let TextContentObjectsLength = filteredText.length - 1;
		filteredLabels.push( { "text" : filteredText.map((label, index) => {
			if (index < TextContentObjectsLength)
				return `\t\t\t\t\t\t\t\t\t"${label.label}" : \t\t${JSON.stringify(label.text.toString())},`;
			else
				return `\t\t\t\t\t\t\t\t\t"${label.label}" : \t\t${JSON.stringify(label.text.toString())}`;
		}).join("\n") } );

		let labelContentObjectsLength = filteredLabels.length - 1;
		let LabelContentObjects =  filteredLabels.map((label, index) => {
			if (!label.label)
				return `\t\t\t\t\t"text" : \t\t {\n ${label.text} \n\t\t\t\t\t\t\t\t}`;
			if (index < labelContentObjectsLength)
				return `\t\t\t\t\t"${label.label}" : \t\t${JSON.stringify(label.text.toString())},`;
			else
				return `\t\t\t\t\t"${label.label}" : \t\t${JSON.stringify(label.text.toString())}`;
		}).join("\n");

		return LabelContentObjects;
	}

	/**
	 * getFullTextContent - getLanguageContent - Return Full JSON Text Content
	 */
	getFullTextContent() {
		let textContent = this.getLanguageContent();
		var fullTextContent = `{
	"language" 		: "Selected Language English",
	"isrequired"		: "is mandatory",
	"addrow"		: "Add Row",
	"deleterow"		: "Delete Row",
	"number" 		: "#",
	"submitform" 		: "Submit",
	"edit" 		: "Edit",
	"chooselanguage" 	: "Choose Language",
	"validation" 		: "Validation",
	"on" 			: "On",
	"off" 			: "Off",
	"save" 			: "Save",
	"printpreview" 		: "Print Preview",
	"close" 		: "Close",
	"labels"		: {
${textContent}
				}
}`;
		return fullTextContent;
	}

}

module.exports = XSDWebFormParser;<|endoftext|>


<commit_before>temp.failCounter = 0;
temp.errCounter = 0;

temp.update = function () {
	var timer = new interval(3 * 1000, temp.aux_update);
	timer.run();
}

temp.aux_update = function () {
	var field = $("#indoorTempData");
	$.getJSON({
		url: temp.url,
		success: function (response) {
			if (temp.errCounter !== 0) {
				temp.errCounter = 0;
			}
			if (response.status === "yes") {
				if (temp.failCounter !== 0) {
					temp.failCounter = 0;
				}
				field.html(response.temp);
			}
			else {
				handleFail();
			}
		},
		error: function (response) {
			handleError();
		}
	});

	function handleFail() {
		if (temp.failCounter < 4) {
			++gas.failCounter;
		}
		else if (field.html() !== "--.-") {
			field.html("--.-");
		}
	}

	function handleError() {
		if (temp.errCounter < 4) {
			++gas.errCounter;
		}
		else if (field.html() !== "err") {
			field.html("err");
		}
	}
}
<commit_msg>indoor temp now with fixed decimal<commit_after>temp.failCounter = 0;
temp.errCounter = 0;

temp.update = function () {
	var timer = new interval(3 * 1000, temp.aux_update);
	timer.run();
}

temp.aux_update = function () {
	var field = $("#indoorTempData");
	$.getJSON({
		url: temp.url,
		success: function (response) {
			if (temp.errCounter !== 0) {
				temp.errCounter = 0;
			}
			if (response.status === "yes") {
				if (temp.failCounter !== 0) {
					temp.failCounter = 0;
				}
				field.html(response.temp.toFixed(1));
			}
			else {
				handleFail();
			}
		},
		error: function (response) {
			handleError();
		}
	});

	function handleFail() {
		if (temp.failCounter < 4) {
			++temp.failCounter;
		}
		else if (field.html() !== "--.-") {
			field.html("--.-");
		}
	}

	function handleError() {
		if (temp.errCounter < 4) {
			++temp.errCounter;
		}
		else if (field.html() !== "err") {
			field.html("err");
		}
	}
}
<|endoftext|>


<commit_before>var creep_assattacker = {

    /** @param {Creep} creep **/
    run: function(creep) {
        if (Game.flags[creep.memory.homeRoom + "RunningAssault"]) {

            var unboostedTough = 0;
            var unboostedAttack = 0;
            var unboostedMove = 0;
            var unboostedWork = 0;
            var unboostedRanged = 0;

            creep.body.forEach(function(thisPart) {
                if (thisPart.type == ATTACK && !thisPart.boost) {
                    unboostedAttack = unboostedAttack + 1;
                } else if (thisPart.type == TOUGH && !thisPart.boost) {
                    unboostedTough = unboostedTough + 1;
                } else if (thisPart.type == MOVE && !thisPart.boost) {
                    unboostedMove = unboostedMove + 1;
                } else if (thisPart.type == WORK && !thisPart.boost) {
                    unboostedWork = unboostedWork + 1;
                } else if (thisPart.type == RANGED_ATTACK && !thisPart.boost) {
                    unboostedRanged = unboostedRanged + 1;
                }
            });

            var targetFlag = Game.flags[creep.memory.homeRoom + "Assault"];
            if (!targetFlag) {
                for (i = 2; i < 6; i++) {
                    targetFlag = Game.flags[creep.memory.homeRoom + "Assault" + i]
                    if (targetFlag) {
                        break;
                    }
                }
                if (!targetFlag) {
                    //Abort Assault
                    Game.flags[creep.memory.homeRoom + "RunningAssault"].remove();
                    console.log(creep.memory.homeRoom + " unable to find any more marks.");
                }
            }

            var wallFlag = Game.flags[creep.memory.homeRoom + "WallFlag"];
            if (!wallFlag) {
                for (i = 2; i < 6; i++) {
                    wallFlag = Game.flags[creep.memory.homeRoom + "WallFlag" + i]
                    if (wallFlag) {
                        break;
                    }
                }
            }

            if (!creep.memory.healerID && !creep.spawning) {
                var nearbyHealer = creep.pos.findInRange(FIND_MY_CREEPS, 2, {
                    filter: (mCreep) => (mCreep.memory.priority == "asshealer" && mCreep.memory.attackerID == creep.id)
                });
                if (nearbyHealer.length) {
                    creep.memory.healerID = nearbyHealer[0].id;
                }
            }

            var closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
                filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username) && eCreep.owner.username != 'Eiskalt')
            });

            var thisHealer = Game.getObjectById(creep.memory.healerID);
            var healerIsNear = false;
            if (thisHealer) {
                healerIsNear = creep.pos.isNearTo(thisHealer);
            }

            if (Game.flags[creep.memory.homeRoom + "DoBoost"] && unboostedMove > 0 && Game.flags[creep.memory.homeRoom + "RunningAssault"]) {
                var MoveLab = creep.room.find(FIND_MY_STRUCTURES, {
                    filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_ZYNTHIUM_ALKALIDE)
                });
                if (MoveLab.length && MoveLab[0].mineralAmount > 0) {
                    creep.travelTo(MoveLab[0]);
                    MoveLab[0].boostCreep(creep);
                }
            } else if (Game.flags[creep.memory.homeRoom + "DoBoost"] && unboostedTough > 0 && Game.flags[creep.memory.homeRoom + "RunningAssault"]) {
                var ToughLab = creep.room.find(FIND_MY_STRUCTURES, {
                    filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_GHODIUM_ALKALIDE)
                });
                if (ToughLab.length && ToughLab[0].mineralAmount > 0) {
                    creep.travelTo(ToughLab[0], {
                        ignoreRoads: true
                    });
                    ToughLab[0].boostCreep(creep);
                }
            } else if (Game.flags[creep.memory.homeRoom + "DoBoost"] && unboostedAttack > 0 && Game.flags[creep.memory.homeRoom + "RunningAssault"]) {
                var AttackLab = creep.room.find(FIND_MY_STRUCTURES, {
                    filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_UTRIUM_ACID)
                });
                if (AttackLab.length && AttackLab[0].mineralAmount > 0) {
                    creep.travelTo(AttackLab[0], {
                        ignoreRoads: true
                    });
                    AttackLab[0].boostCreep(creep);
                }
            } else if (Game.flags[creep.memory.homeRoom + "DoBoost"] && unboostedWork > 0 && Game.flags[creep.memory.homeRoom + "RunningAssault"]) {
                var WorkLab = creep.room.find(FIND_MY_STRUCTURES, {
                    filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_ZYNTHIUM_ACID)
                });
                if (WorkLab.length && WorkLab[0].mineralAmount > 0) {
                    creep.travelTo(WorkLab[0], {
                        ignoreRoads: true
                    });
                    WorkLab[0].boostCreep(creep);
                }
            } else if (Game.flags[creep.memory.homeRoom + "DoBoost"] && unboostedRanged > 0 && Game.flags[creep.memory.homeRoom + "RunningAssault"]) {
                var RangedLab = creep.room.find(FIND_MY_STRUCTURES, {
                    filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_KEANIUM_ALKALIDE)
                });
                if (RangedLab.length && RangedLab[0].mineralAmount > 0) {
                    creep.travelTo(RangedLab[0], {
                        ignoreRoads: true
                    });
                    RangedLab[0].boostCreep(creep);
                }
            } else {
                if (targetFlag.pos.roomName == creep.pos.roomName) {
                    //In target room
                    var somethingNearby = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                        filter: (structure) => (structure.structureType != STRUCTURE_ROAD)
                    });
                    if (somethingNearby) {
                        creep.dismantle(somethingNearby);
                        creep.attack(somethingNearby)
                    }

                    creep.rangedMassAttack();
                    if (creep.hits < creep.hitsMax - 1700 && Game.flags[creep.memory.homeRoom + "FallBack"] && Game.flags[creep.memory.homeRoom + "FallBack"].pos) {
                        //Fall back
                        creep.travelTo(Game.flags[creep.memory.homeRoom + "FallBack"], {
                            ignoreRoads: true
                        });
                    } else if (!healerIsNear) {
                        if (creep.pos.x == 0 || creep.pos.x == 49 || creep.pos.y == 0 || creep.pos.y == 49) {
                            var xTarget = 0;
                            var yTarget = 0;
                            if (creep.pos.x == 0) {
                                xTarget = 2;
                                yTarget = creep.pos.y;
                            } else if (creep.pos.x == 49) {
                                xTarget = 47;
                                yTarget = creep.pos.y;
                            }
                            if (creep.pos.y == 0) {
                                yTarget = 2;
                                xTarget = creep.pos.x;
                            } else if (creep.pos.y == 49) {
                                yTarget = 47;
                                xTarget = creep.pos.x;
                            }
                            creep.moveTo(xTarget, yTarget);
                        }
                    } else if (healerIsNear) {
                        if (wallFlag && wallFlag.pos.roomName == creep.pos.roomName) {
                            var thisWall = wallFlag.pos.lookFor(LOOK_STRUCTURES);
                            if (thisWall.length) {
                                creep.travelTo(thisWall[0], {
                                    maxRooms: 1
                                });
                                creep.dismantle(thisWall[0]);
                                creep.attack(thisWall[0]);
                            } else {
                                wallFlag.remove();
                            }
                        } else {
                            var eSpawns = creep.room.find(FIND_HOSTILE_SPAWNS)
                            if (eSpawns.length) {
                                creep.travelTo(eSpawns[0], {
                                    ignoreRoads: true,
                                    maxRooms: 1
                                });
                                creep.dismantle(eSpawns[0]);
                                creep.attack(eSpawns[0]);
                            } else {
                                var eStructures = creep.pos.findClosestByRange(FIND_HOSTILE_STRUCTURES, {
                                    filter: (structure) => (structure.structureType != STRUCTURE_CONTROLLER && structure.structureType != STRUCTURE_WALL && structure.structureType != STRUCTURE_RAMPART && structure.structureType != STRUCTURE_KEEPER_LAIR && structure.structureType != STRUCTURE_EXTRACTOR)
                                });
                                if (eStructures) {
                                    creep.travelTo(eStructures, {
                                        ignoreRoads: true,
                                        maxRooms: 1
                                    });
                                    creep.dismantle(eStructures);
                                    creep.attack(eStructures);
                                } else if (closeFoe) {
                                    creep.moveTo(closeFoe, {
                                        ignoreRoads: true,
                                        maxRooms: 1
                                    });
                                } else if (targetFlag) {
                                    targetFlag.remove();
                                }
                            }

                        }
                    }
                } else if (!healerIsNear) {
                    if (creep.memory.getOutOfStartRoom) {
                        var thisPortal = undefined;
                        if (Game.flags["TakePortal"] && Game.flags["TakePortal"].pos.roomName == creep.pos.roomName) {
                            var thisPortal = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                                filter: (structure) => (structure.structureType == STRUCTURE_PORTAL)
                            });
                        }
                        if (thisPortal) {
                            creep.memory.destination = undefined;
                            creep.memory.usedPortal = true;
                            creep.travelTo(thisPortal);
                        } else if (creep.pos.x == 0 || creep.pos.x == 49 || creep.pos.y == 0 || creep.pos.y == 49) {
                            var xTarget = 0;
                            var yTarget = 0;
                            if (creep.pos.x == 0) {
                                xTarget = 2;
                                yTarget = creep.pos.y;
                            } else if (creep.pos.x == 49) {
                                xTarget = 47;
                                yTarget = creep.pos.y;
                            }
                            if (creep.pos.y == 0) {
                                yTarget = 2;
                                xTarget = creep.pos.x;
                            } else if (creep.pos.y == 49) {
                                yTarget = 47;
                                xTarget = creep.pos.x;
                            }
                            creep.moveTo(xTarget, yTarget);
                        }
                    } else if (Game.flags[creep.memory.homeRoom + "RallyHere"] && Game.flags[creep.memory.homeRoom + "RallyHere"].pos) {
                        creep.travelTo(Game.flags[creep.memory.homeRoom + "RallyHere"], {
                            ignoreRoads: true
                        });
                    }
                } else if (healerIsNear) {
                    if (!creep.memory.getOutOfStartRoom) {
                        creep.memory.getOutOfStartRoom = true;
                    }
                    if (creep.memory.usedPortal == undefined) {
                        creep.memory.usedPortal = false
                    }
                    if (Game.flags["TakePortal"] && Game.flags["TakePortal"].pos.roomName != creep.pos.roomName) {
                        creep.memory.destination = Game.flags["TakePortal"].pos.roomName;
                    }

                    var thisPortal = undefined;
                    if (Game.flags["TakePortal"] && Game.flags["TakePortal"].pos.roomName == creep.pos.roomName) {
                        var thisPortal = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                            filter: (structure) => (structure.structureType == STRUCTURE_PORTAL)
                        });
                    }
                    if (thisPortal) {
                        creep.memory.destination = undefined;
                        creep.memory.usedPortal = true;
                        if (creep.memory.path && creep.memory.path.length && creep.memory.path[0] == creep.room.name) {
                            creep.memory.path.splice(0, 1);
                        }
                        creep.travelTo(thisPortal, {
                            ignoreRoads: true
                        });
                    } else if (targetFlag.pos.roomName != creep.pos.roomName) {
                        /*if (creep.memory.destination && !creep.memory.usedPortal) {
                            creep.travelTo(new RoomPosition(25, 25, creep.memory.destination))
                        } else*/
                        if (creep.memory.path && creep.memory.path.length) {
                            if (creep.memory.path[0] == creep.room.name) {
                                creep.memory.path.splice(0, 1);
                            }
                            creep.travelTo(new RoomPosition(25, 25, creep.memory.path[0]), {
                                ignoreRoads: true
                            });
                        } else if (targetFlag.pos) {
                            if (wallFlag.pos && wallFlag.pos.roomName == targetFlag.pos.roomName) {
                                creep.travelTo(wallFlag, {
                                    ignoreRoads: true
                                });
                            } else {
                                creep.travelTo(targetFlag, {
                                    ignoreRoads: true
                                });
                            }
                        } else {
                            creep.travelTo(new RoomPosition(25, 25, targetFlag.pos.roomName), {
                                ignoreRoads: true
                            });
                        }
                    }
                }
            }

            if (closeFoe) {
                creep.rangedMassAttack();
                creep.attack(closeFoe);
                //prioritize foebashing
                /*var found = closeFoe.pos.lookFor(LOOK_STRUCTURES);
                var hasRampart = false;
                for (var building in found) {
                    if (found[building].structureType == STRUCTURE_RAMPART) {
                        hasRampart = true;
                        break;
                    }
                }
                if (!hasRampart) {
                    creep.attack(closeFoe);
                }*/
            }
        }

    }

};

module.exports = creep_assattacker;<commit_msg>Just target the nearest structure<commit_after>var creep_assattacker = {

    /** @param {Creep} creep **/
    run: function(creep) {
        if (Game.flags[creep.memory.homeRoom + "RunningAssault"]) {

            var unboostedTough = 0;
            var unboostedAttack = 0;
            var unboostedMove = 0;
            var unboostedWork = 0;
            var unboostedRanged = 0;

            creep.body.forEach(function(thisPart) {
                if (thisPart.type == ATTACK && !thisPart.boost) {
                    unboostedAttack = unboostedAttack + 1;
                } else if (thisPart.type == TOUGH && !thisPart.boost) {
                    unboostedTough = unboostedTough + 1;
                } else if (thisPart.type == MOVE && !thisPart.boost) {
                    unboostedMove = unboostedMove + 1;
                } else if (thisPart.type == WORK && !thisPart.boost) {
                    unboostedWork = unboostedWork + 1;
                } else if (thisPart.type == RANGED_ATTACK && !thisPart.boost) {
                    unboostedRanged = unboostedRanged + 1;
                }
            });

            var targetFlag = Game.flags[creep.memory.homeRoom + "Assault"];
            if (!targetFlag) {
                for (i = 2; i < 6; i++) {
                    targetFlag = Game.flags[creep.memory.homeRoom + "Assault" + i]
                    if (targetFlag) {
                        break;
                    }
                }
                if (!targetFlag) {
                    //Abort Assault
                    Game.flags[creep.memory.homeRoom + "RunningAssault"].remove();
                    console.log(creep.memory.homeRoom + " unable to find any more marks.");
                }
            }

            var wallFlag = Game.flags[creep.memory.homeRoom + "WallFlag"];
            if (!wallFlag) {
                for (i = 2; i < 6; i++) {
                    wallFlag = Game.flags[creep.memory.homeRoom + "WallFlag" + i]
                    if (wallFlag) {
                        break;
                    }
                }
            }

            if (!creep.memory.healerID && !creep.spawning) {
                var nearbyHealer = creep.pos.findInRange(FIND_MY_CREEPS, 2, {
                    filter: (mCreep) => (mCreep.memory.priority == "asshealer" && mCreep.memory.attackerID == creep.id)
                });
                if (nearbyHealer.length) {
                    creep.memory.healerID = nearbyHealer[0].id;
                }
            }

            var closeFoe = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS, {
                filter: (eCreep) => (!Memory.whiteList.includes(eCreep.owner.username) && eCreep.owner.username != 'Eiskalt')
            });

            var thisHealer = Game.getObjectById(creep.memory.healerID);
            var healerIsNear = false;
            if (thisHealer) {
                healerIsNear = creep.pos.isNearTo(thisHealer);
            }

            if (Game.flags[creep.memory.homeRoom + "DoBoost"] && unboostedMove > 0 && Game.flags[creep.memory.homeRoom + "RunningAssault"]) {
                var MoveLab = creep.room.find(FIND_MY_STRUCTURES, {
                    filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_ZYNTHIUM_ALKALIDE)
                });
                if (MoveLab.length && MoveLab[0].mineralAmount > 0) {
                    creep.travelTo(MoveLab[0]);
                    MoveLab[0].boostCreep(creep);
                }
            } else if (Game.flags[creep.memory.homeRoom + "DoBoost"] && unboostedTough > 0 && Game.flags[creep.memory.homeRoom + "RunningAssault"]) {
                var ToughLab = creep.room.find(FIND_MY_STRUCTURES, {
                    filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_GHODIUM_ALKALIDE)
                });
                if (ToughLab.length && ToughLab[0].mineralAmount > 0) {
                    creep.travelTo(ToughLab[0], {
                        ignoreRoads: true
                    });
                    ToughLab[0].boostCreep(creep);
                }
            } else if (Game.flags[creep.memory.homeRoom + "DoBoost"] && unboostedAttack > 0 && Game.flags[creep.memory.homeRoom + "RunningAssault"]) {
                var AttackLab = creep.room.find(FIND_MY_STRUCTURES, {
                    filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_UTRIUM_ACID)
                });
                if (AttackLab.length && AttackLab[0].mineralAmount > 0) {
                    creep.travelTo(AttackLab[0], {
                        ignoreRoads: true
                    });
                    AttackLab[0].boostCreep(creep);
                }
            } else if (Game.flags[creep.memory.homeRoom + "DoBoost"] && unboostedWork > 0 && Game.flags[creep.memory.homeRoom + "RunningAssault"]) {
                var WorkLab = creep.room.find(FIND_MY_STRUCTURES, {
                    filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_ZYNTHIUM_ACID)
                });
                if (WorkLab.length && WorkLab[0].mineralAmount > 0) {
                    creep.travelTo(WorkLab[0], {
                        ignoreRoads: true
                    });
                    WorkLab[0].boostCreep(creep);
                }
            } else if (Game.flags[creep.memory.homeRoom + "DoBoost"] && unboostedRanged > 0 && Game.flags[creep.memory.homeRoom + "RunningAssault"]) {
                var RangedLab = creep.room.find(FIND_MY_STRUCTURES, {
                    filter: (structure) => (structure.structureType == STRUCTURE_LAB && structure.mineralType == RESOURCE_CATALYZED_KEANIUM_ALKALIDE)
                });
                if (RangedLab.length && RangedLab[0].mineralAmount > 0) {
                    creep.travelTo(RangedLab[0], {
                        ignoreRoads: true
                    });
                    RangedLab[0].boostCreep(creep);
                }
            } else {
                if (targetFlag.pos.roomName == creep.pos.roomName) {
                    //In target room
                    var somethingNearby = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                        filter: (structure) => (structure.structureType != STRUCTURE_ROAD)
                    });
                    if (somethingNearby) {
                        creep.dismantle(somethingNearby);
                        creep.attack(somethingNearby)
                    }

                    creep.rangedMassAttack();
                    if (creep.hits < creep.hitsMax - 1700 && Game.flags[creep.memory.homeRoom + "FallBack"] && Game.flags[creep.memory.homeRoom + "FallBack"].pos) {
                        //Fall back
                        creep.travelTo(Game.flags[creep.memory.homeRoom + "FallBack"], {
                            ignoreRoads: true
                        });
                    } else if (!healerIsNear) {
                        if (creep.pos.x == 0 || creep.pos.x == 49 || creep.pos.y == 0 || creep.pos.y == 49) {
                            var xTarget = 0;
                            var yTarget = 0;
                            if (creep.pos.x == 0) {
                                xTarget = 2;
                                yTarget = creep.pos.y;
                            } else if (creep.pos.x == 49) {
                                xTarget = 47;
                                yTarget = creep.pos.y;
                            }
                            if (creep.pos.y == 0) {
                                yTarget = 2;
                                xTarget = creep.pos.x;
                            } else if (creep.pos.y == 49) {
                                yTarget = 47;
                                xTarget = creep.pos.x;
                            }
                            creep.moveTo(xTarget, yTarget);
                        }
                    } else if (healerIsNear) {
                        if (wallFlag && wallFlag.pos.roomName == creep.pos.roomName) {
                            var thisWall = wallFlag.pos.lookFor(LOOK_STRUCTURES);
                            if (thisWall.length) {
                                creep.travelTo(thisWall[0], {
                                    maxRooms: 1
                                });
                                creep.dismantle(thisWall[0]);
                                creep.attack(thisWall[0]);
                            } else {
                                wallFlag.remove();
                            }
                        } else {
                            var eStructures = creep.pos.findClosestByRange(FIND_HOSTILE_STRUCTURES, {
                                filter: (structure) => (structure.structureType != STRUCTURE_CONTROLLER && structure.structureType != STRUCTURE_WALL && structure.structureType != STRUCTURE_RAMPART && structure.structureType != STRUCTURE_KEEPER_LAIR && structure.structureType != STRUCTURE_EXTRACTOR)
                            });
                            if (eStructures) {
                                creep.travelTo(eStructures, {
                                    ignoreRoads: true,
                                    maxRooms: 1
                                });
                                creep.dismantle(eStructures);
                                creep.attack(eStructures);
                            } else if (closeFoe) {
                                creep.moveTo(closeFoe, {
                                    ignoreRoads: true,
                                    maxRooms: 1
                                });
                            } else if (targetFlag) {
                                targetFlag.remove();
                            }
                        }
                    }
                } else if (!healerIsNear) {
                    if (creep.memory.getOutOfStartRoom) {
                        var thisPortal = undefined;
                        if (Game.flags["TakePortal"] && Game.flags["TakePortal"].pos.roomName == creep.pos.roomName) {
                            var thisPortal = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                                filter: (structure) => (structure.structureType == STRUCTURE_PORTAL)
                            });
                        }
                        if (thisPortal) {
                            creep.memory.destination = undefined;
                            creep.memory.usedPortal = true;
                            creep.travelTo(thisPortal);
                        } else if (creep.pos.x == 0 || creep.pos.x == 49 || creep.pos.y == 0 || creep.pos.y == 49) {
                            var xTarget = 0;
                            var yTarget = 0;
                            if (creep.pos.x == 0) {
                                xTarget = 2;
                                yTarget = creep.pos.y;
                            } else if (creep.pos.x == 49) {
                                xTarget = 47;
                                yTarget = creep.pos.y;
                            }
                            if (creep.pos.y == 0) {
                                yTarget = 2;
                                xTarget = creep.pos.x;
                            } else if (creep.pos.y == 49) {
                                yTarget = 47;
                                xTarget = creep.pos.x;
                            }
                            creep.moveTo(xTarget, yTarget);
                        }
                    } else if (Game.flags[creep.memory.homeRoom + "RallyHere"] && Game.flags[creep.memory.homeRoom + "RallyHere"].pos) {
                        creep.travelTo(Game.flags[creep.memory.homeRoom + "RallyHere"], {
                            ignoreRoads: true
                        });
                    }
                } else if (healerIsNear) {
                    if (!creep.memory.getOutOfStartRoom) {
                        creep.memory.getOutOfStartRoom = true;
                    }
                    if (creep.memory.usedPortal == undefined) {
                        creep.memory.usedPortal = false
                    }
                    if (Game.flags["TakePortal"] && Game.flags["TakePortal"].pos.roomName != creep.pos.roomName) {
                        creep.memory.destination = Game.flags["TakePortal"].pos.roomName;
                    }

                    var thisPortal = undefined;
                    if (Game.flags["TakePortal"] && Game.flags["TakePortal"].pos.roomName == creep.pos.roomName) {
                        var thisPortal = creep.pos.findClosestByRange(FIND_STRUCTURES, {
                            filter: (structure) => (structure.structureType == STRUCTURE_PORTAL)
                        });
                    }
                    if (thisPortal) {
                        creep.memory.destination = undefined;
                        creep.memory.usedPortal = true;
                        if (creep.memory.path && creep.memory.path.length && creep.memory.path[0] == creep.room.name) {
                            creep.memory.path.splice(0, 1);
                        }
                        creep.travelTo(thisPortal, {
                            ignoreRoads: true
                        });
                    } else if (targetFlag.pos.roomName != creep.pos.roomName) {
                        /*if (creep.memory.destination && !creep.memory.usedPortal) {
                            creep.travelTo(new RoomPosition(25, 25, creep.memory.destination))
                        } else*/
                        if (creep.memory.path && creep.memory.path.length) {
                            if (creep.memory.path[0] == creep.room.name) {
                                creep.memory.path.splice(0, 1);
                            }
                            creep.travelTo(new RoomPosition(25, 25, creep.memory.path[0]), {
                                ignoreRoads: true
                            });
                        } else if (targetFlag.pos) {
                            if (wallFlag.pos && wallFlag.pos.roomName == targetFlag.pos.roomName) {
                                creep.travelTo(wallFlag, {
                                    ignoreRoads: true
                                });
                            } else {
                                creep.travelTo(targetFlag, {
                                    ignoreRoads: true
                                });
                            }
                        } else {
                            creep.travelTo(new RoomPosition(25, 25, targetFlag.pos.roomName), {
                                ignoreRoads: true
                            });
                        }
                    }
                }
            }

            if (closeFoe) {
                creep.rangedMassAttack();
                creep.attack(closeFoe);
                //prioritize foebashing
                /*var found = closeFoe.pos.lookFor(LOOK_STRUCTURES);
                var hasRampart = false;
                for (var building in found) {
                    if (found[building].structureType == STRUCTURE_RAMPART) {
                        hasRampart = true;
                        break;
                    }
                }
                if (!hasRampart) {
                    creep.attack(closeFoe);
                }*/
            }
        }

    }

};

module.exports = creep_assattacker;<|endoftext|>


<commit_before>/**
 * @author mrdoob / http://mrdoob.com/
 */

import { RGBAFormat, RGBFormat } from '../constants.js';
import { ImageLoader } from './ImageLoader.js';
import { Texture } from '../textures/Texture.js';
import { DefaultLoadingManager } from './LoadingManager.js';

function TextureLoader( manager ) {

	this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;

}

Object.assign( TextureLoader.prototype, {

	crossOrigin: 'anonymous',

	load: function ( url, onLoad, onProgress, onError ) {

		var texture = new Texture();

		var loader = new ImageLoader( this.manager );
		loader.setCrossOrigin( this.crossOrigin );
		loader.setPath( this.path );

		loader.load( url, function ( image ) {

			texture.image = image;

			// JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
			var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;

			texture.format = isJPEG ? RGBFormat : RGBAFormat;
			texture.needsUpdate = true;

			if ( onLoad !== undefined ) {

				onLoad( texture );

			}

		}, onProgress, onError );

		return texture;

	},

	setCrossOrigin: function ( value ) {

		this.crossOrigin = value;
		return this;

	},

	setPath: function ( value ) {

		this.path = value;
		return this;

	}

} );

export { TextureLoader };
<commit_msg>#14675 | TextureLoader - Regex update<commit_after>/**
 * @author mrdoob / http://mrdoob.com/
 */

import { RGBAFormat, RGBFormat } from '../constants.js';
import { ImageLoader } from './ImageLoader.js';
import { Texture } from '../textures/Texture.js';
import { DefaultLoadingManager } from './LoadingManager.js';

function TextureLoader( manager ) {

	this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;

}

Object.assign( TextureLoader.prototype, {

	crossOrigin: 'anonymous',

	load: function ( url, onLoad, onProgress, onError ) {

		var texture = new Texture();

		var loader = new ImageLoader( this.manager );
		loader.setCrossOrigin( this.crossOrigin );
		loader.setPath( this.path );

		loader.load( url, function ( image ) {

			texture.image = image;

			// JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
			var isJPEG = url.search( /\.(?:jpe?g|JPE?G)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;

			texture.format = isJPEG ? RGBFormat : RGBAFormat;
			texture.needsUpdate = true;

			if ( onLoad !== undefined ) {

				onLoad( texture );

			}

		}, onProgress, onError );

		return texture;

	},

	setCrossOrigin: function ( value ) {

		this.crossOrigin = value;
		return this;

	},

	setPath: function ( value ) {

		this.path = value;
		return this;

	}

} );

export { TextureLoader };
<|endoftext|>


<commit_before><commit_msg>o3d-webgl: Avoid computation per element if ParamParamArray is bound.<commit_after><|endoftext|>


<commit_before>exports.config = {
    framework: 'jasmine',
    seleniumAddress: 'http://localhost:9515',
    // seleniumAddress: 'http://localhost:4444/wd/hub',
    specs: ['./specs/collections_spec.js','./specs/organization_spec.js'],
    capabilities: {
        'browserName': 'phantomjs'
        // 'browserName': 'chrome'
    },
    baseUrl: 'http://showcase.openconceptlab.org'
};
<commit_msg>Added user source e2e tests to conf file to run<commit_after>exports.config = {
    framework: 'jasmine',
    seleniumAddress: 'http://localhost:9515',
    // seleniumAddress: 'http://localhost:4444/wd/hub',
    specs: ['./specs/collections_spec.js','./specs/organization_spec.js', './specs/user_source_spec.js'],
    capabilities: {
        'browserName': 'phantomjs'
        // 'browserName': 'chrome'
    },
    baseUrl: 'http://showcase.openconceptlab.org'
};
<|endoftext|>