<commit_before>var map;

//Initialize the map
function initMap() {
	map = new google.maps.Map(document.getElementById('map'), {
		zoom: 1,
		center: {lat: 0, lng: 0}
	});

	//https://nominatim.openstreetmap.org/search/Austin%20TX%20?format=xml&addressdetails=1&limit=1&polygon_kml=1

	document.getElementById('genPoly').onclick = function genPoly() {
		//Indicate Loading
		document.getElementById("coords").innerHTML="";
		var check = 0;
		var info = [];
		info.push(document.getElementById('street').value);
		info.push(document.getElementById('city').value);
		info.push(document.getElementById('county').value);
		info.push(document.getElementById('state').value);
		info.push(document.getElementById('country').value);
		info.push(document.getElementById('postalcode').value);

		var nominatimCall = "https://nominatim.openstreetmap.org/search/";
		var endCall = "?format=xml&limit=1&polygon_kml=1&email=bab178@txstate.edu";

		//Create nominatim URL
		for(var i = 0; i < info.length; i++)
			if(info[i] !== '')
			{
				//Change spaces to %20
				for(var j = 0; j < info[i].length; j++)
					if(info[i][j] === ' ')
						info[i] = info[i].slice(0, j) + "%20" + info[i].slice(j+1,info[i].length);
				//Add to nominatim URL
				if(check === 0)
					nominatimCall = nominatimCall.concat(info[i]);
				else
					nominatimCall = nominatimCall.concat('%20'+info[i]);

				check = 1;
			}
		if(check === 0)
		{
			alert("Nothing entered. Enter something to generate a Polygon.");
			return;
		}
		//Finish URL
		nominatimCall = nominatimCall.concat(endCall);

		var coordinates, place;
		var paths = [], finalPath = [];

		//https://stackoverflow.com/questions/6375461/get-html-code-using-javascript-with-a-url
		function makeHttpObject() {
		  try {return new XMLHttpRequest();}
		  catch (error) {}
		  try {return new ActiveXObject("Msxml2.XMLHTTP");}
		  catch (error) {}
		  try {return new ActiveXObject("Microsoft.XMLHTTP");}
		  catch (error) {}

		  throw new Error("Could not create HTTP request object.");
		}
		var request = makeHttpObject();
		request.open("GET", nominatimCall, true);
		request.send(null);
		request.onreadystatechange = function() {
			//HTML Request ready
		  if (request.readyState === 4 && request.status === 200)
		  {
			document.getElementById("coords").innerHTML=request.responseText;
			if($("coordinates").html() === null)
			{
				document.getElementById("coords").innerHTML = "No results found.";
				return;
			}
			//Get coordinates from jQuery call
			coordinates = $("coordinates").html();
			place = $("searchresults").html();
			document.getElementById("coords").innerHTML=$("coordinates").html();

			//Get place name from searchresults
			place = place.split("display_name=\"");
			place = place[1].split("\" class");
			place = place[0];
			console.log(place);
			document.getElementById("place").innerHTML='
'+place+'
';

			//Parse HTML into Google Maps LatLng Objects
			paths = coordinates.split(" ");
			for(var i = 0; i < paths.length; i++)
			{
				x = paths[i].split(",");
				finalPath.push(new google.maps.LatLng(x[1],x[0]));
			}

			//DRAW THE POLYGON OR POLYLINE
			var CityHightlight = new google.maps.Polygon({
				paths: finalPath,
				strokeColor: 'red',
				strokeOpacity: 1,
				strokeWeight: 1,
				fillColor: 'white',
				fillOpacity: 0
			});
			CityHightlight.setMap(map);

			//clear HTML
			document.getElementById("coords").innerHTML = "";
			//Add to HTML
			for(var i = 0; i < finalPath.length-1; i++)
				document.getElementById("coords").innerHTML+=('
'+'new google.maps.LatLng'+finalPath[i]+',
');
			//Remove last comma
			document.getElementById("coords").innerHTML+=('
'+'new google.maps.LatLng'+finalPath[finalPath.length-1]+'
');

		  }
		};
	}
}
google.maps.event.addDomListener(window, 'load', initMap);<commit_msg>Add auto-zoom in<commit_after>var map;

//Initialize the map
function initMap() {
	map = new google.maps.Map(document.getElementById('map'), {
		zoom: 1,
		center: {lat: 0, lng: 0}
	});

	//https://nominatim.openstreetmap.org/search/Austin%20TX%20?format=xml&addressdetails=1&limit=1&polygon_kml=1

	document.getElementById('genPoly').onclick = function genPoly() {
		//Indicate Loading
		document.getElementById("coords").innerHTML="";
		var check = 0;
		var info = [];
		info.push(document.getElementById('street').value);
		info.push(document.getElementById('city').value);
		info.push(document.getElementById('county').value);
		info.push(document.getElementById('state').value);
		info.push(document.getElementById('country').value);
		info.push(document.getElementById('postalcode').value);

		var nominatimCall = "https://nominatim.openstreetmap.org/search/";
		var endCall = "?format=xml&limit=1&polygon_kml=1&email=bab178@txstate.edu";

		//Create nominatim URL
		for(var i = 0; i < info.length; i++)
			if(info[i] !== '')
			{
				//Change spaces to %20
				for(var j = 0; j < info[i].length; j++)
					if(info[i][j] === ' ')
						info[i] = info[i].slice(0, j) + "%20" + info[i].slice(j+1,info[i].length);
				//Add to nominatim URL
				if(check === 0)
					nominatimCall = nominatimCall.concat(info[i]);
				else
					nominatimCall = nominatimCall.concat('%20'+info[i]);

				check = 1;
			}
		if(check === 0)
		{
			alert("Nothing entered. Enter something to generate a Polygon.");
			return;
		}
		//Finish URL
		nominatimCall = nominatimCall.concat(endCall);

		var coordinates, place;
		var paths = [], finalPath = [];

		//https://stackoverflow.com/questions/6375461/get-html-code-using-javascript-with-a-url
		function makeHttpObject() {
		  try {return new XMLHttpRequest();}
		  catch (error) {}
		  try {return new ActiveXObject("Msxml2.XMLHTTP");}
		  catch (error) {}
		  try {return new ActiveXObject("Microsoft.XMLHTTP");}
		  catch (error) {}

		  throw new Error("Could not create HTTP request object.");
		}
		var request = makeHttpObject();
		request.open("GET", nominatimCall, true);
		request.send(null);
		request.onreadystatechange = function() {
			//HTML Request ready
		  if (request.readyState === 4 && request.status === 200)
		  {
			document.getElementById("coords").innerHTML=request.responseText;
			if($("coordinates").html() === null)
			{
				document.getElementById("coords").innerHTML = "No results found.";
				return;
			}
			//Get coordinates from jQuery call
			coordinates = $("coordinates").html();
			place = $("searchresults").html();
			document.getElementById("coords").innerHTML=$("coordinates").html();

			//Get place name from searchresults
			place = place.split("display_name=\"");
			place = place[1].split("\" class");
			place = place[0];
			console.log(place);
			document.getElementById("place").innerHTML='
'+place+'
';

			//Parse HTML into Google Maps LatLng Objects
			paths = coordinates.split(" ");
			for(var i = 0; i < paths.length; i++)
			{
				x = paths[i].split(",");
				finalPath.push(new google.maps.LatLng(x[1],x[0]));
			}

			//DRAW THE POLYGON OR POLYLINE
			var CityHightlight = new google.maps.Polygon({
				paths: finalPath,
                clickable:false,
				strokeColor: 'red',
				strokeOpacity: 1,
				strokeWeight: 1,
				fillColor: 'white',
				fillOpacity: 0
			});
			CityHightlight.setMap(map);

            if (!google.maps.Polygon.prototype.getBounds) {

            google.maps.Polygon.prototype.getBounds=function(){
                var bounds = new google.maps.LatLngBounds()
                this.getPath().forEach(function(element,index){bounds.extend(element)})
                return bounds
            }

            }

            map.fitBounds(CityHightlight.getBounds());

			//clear HTML
			document.getElementById("coords").innerHTML = "";
			//Add to HTML
			for(var i = 0; i < finalPath.length-1; i++)
				document.getElementById("coords").innerHTML+=('
'+'new google.maps.LatLng'+finalPath[i]+',
');
			//Remove last comma
			document.getElementById("coords").innerHTML+=('
'+'new google.maps.LatLng'+finalPath[finalPath.length-1]+'
');

		  }
		};
	}
}
google.maps.event.addDomListener(window, 'load', initMap);<|endoftext|>


<commit_before>'use strict';

var hl = require("./hl")
var http = require('http');
var fs = require("fs");
var url  = require('url');

if (process.argv[2]) {
	var fileName = process.argv[2];
	var fileContents = fs.readFileSync(fileName, "utf8");
	var result = hl.execute(fileContents);

	var server = http.createServer(function (request, response) {
		try {
			var filePath = url.parse(request.url.substring(1)).pathname;

			if (filePath == null) {
				response.writeHead(404);
				response.end();
				return;
			}

			filePath = filePath.split("/");
			console.log("\t\t FILEPATH", filePath);

			var scopeIndex;

			for (var i in filePath) {
				var serviceName = filePath[i];

				var scopeIndex = hl.searchScope(serviceName);

				if (scopeIndex.scope) scopeIndex = scopeIndex.scope;

				console.log("___________", serviceName, scopeIndex);

				if (scopeIndex == undefined) {
					break;
				}

				hl.setScope(scopeIndex);
			}

			if (scopeIndex == undefined) {
				result = "Could not find " + serviceName + " in scope";
				var returnCode = 404;
			} else {
				var result = hl.evaluate({service:serviceName, action:"handleRequest", args: null}, true, false);
				var returnCode = 200;
			}
		} catch (e) {
			var result = JSON.stringify(e);
			var returnCode = 503;
		}

		response.writeHead(returnCode, {"Content-Type": "text/plain"});
		response.end(result);
	});

	server.listen(8080);
	console.log("Server running at http://127.0.0.1:8080/");
} else {
	throw Error("No args given");
}
<commit_msg>Small refactoring of HiTTP.js to make it possible to run it from other js code<commit_after>'use strict';

var hl = require("./hl")
var http = require('http');
var fs = require("fs");
var url  = require('url');

var HiTTP = {};
HiTTP.startServer = function(fileName) {
	if (!fileName) throw Error("No args given: webapp filename");

	var fileContents = fs.readFileSync(fileName, "utf8");
	var result = hl.execute(fileContents);

	var server = http.createServer(function (request, response) {
		try {
			var filePath = url.parse(request.url.substring(1)).pathname;

			if (filePath == null) {
				response.writeHead(404);
				response.end();
				return;
			}

			filePath = filePath.split("/");
			console.log("\t\t FILEPATH", filePath);

			var scopeIndex;

			for (var i in filePath) {
				var serviceName = filePath[i];

				var scopeIndex = hl.searchScope(serviceName);

				if (scopeIndex.scope) scopeIndex = scopeIndex.scope;

				console.log("___________", serviceName, scopeIndex);

				if (scopeIndex == undefined) {
					break;
				}

				hl.setScope(scopeIndex);
			}

			if (scopeIndex == undefined) {
				result = "Could not find " + serviceName + " in scope";
				var returnCode = 404;
			} else {
				var result = hl.evaluate({service:serviceName, action:"handleRequest", args: null}, true, false);
				var returnCode = 200;
			}
		} catch (e) {
			var result = JSON.stringify(e);
			var returnCode = 503;
		}

		response.writeHead(returnCode, {"Content-Type": "text/plain"});
		response.end(result);
	});

	server.listen(8080);
	console.log("\n" + "Server running at http://127.0.0.1:8080/");
}

if (process.argv[2]) {
	HiTTP.startServer(process.argv[2])
}
<|endoftext|>


<commit_before>function JsPNG(width, height, isGrey) {
    "use strict";
    function write(buffer, offset, byteAry) {
        for (var i = 0; i < byteAry.length; i++) {
            buffer[offset + i] = byteAry[i];
        }
    }

    var numChannels = 3;
    if(isGrey) numChannels = 1;

    /* helper functions */
    var intBuf = new Uint32Array(1);
    //var shortBuf = new Uint16Array(1);
    var bufSize4 = new Uint8Array(intBuf.buffer);
    //var bufSize2 = new Uint8Array(shortBuf.buffer);
    var intToBytes = function(someInt) {
        intBuf[0] = swap32(someInt);
        return bufSize4.slice();
    }

    var swap32 = function(val) {
        return ((val & 0xFF) << 24)
               | ((val & 0xFF00) << 8)
               | ((val >> 8) & 0xFF00)
               | ((val >> 24) & 0xFF);
    }
    var swap16 = function(val) {
        return ((val & 0xFF) << 8)
               | ((val >> 8) & 0xFF);
    }

    var scanWidth = (width * numChannels) + 1;
    var pxData = new Uint8Array(height * scanWidth);//add one for filter byte

    var mask1 = 255; //R
    var mask2 = mask1 << 8; //G
    var mask3 = mask1 << 16; //B

	if(isGrey){
		this.setPixel = function (x, y, pxVal) {
			var yOffset = y * scanWidth;
			pxData[yOffset + x + 1] = pxVal;
		}
	}else{
		this.setPixel = function (x, y, r, g, b) {
			var yOffset = y * scanWidth;
			var xOffset = x * 3;
			if (g === void (0)) { //see if r is an RGB integer
				var val = r;
				r = val & mask1;
				g = (val & mask2) >> 8;
				b = (val & mask3) >> 16;
			}
			pxData[yOffset + xOffset + 1] = r;
			pxData[yOffset + xOffset + 2] = g;
			pxData[yOffset + xOffset + 3] = b;
		}
    }

    var IHDRdataLen = 33;
    var IHDRdata = new Uint8Array(IHDRdataLen);
    //each is an array of byte values
    var magicNumberHdr = [137, 80, 78, 71, 13, 10, 26, 10];
    var IHDRlen = intToBytes(13);
    var IHDR = [73, 72, 68, 82];
    var widthBytes = intToBytes(width);
    var heightBytes = intToBytes(height);
    var bitDepth = [8];
    var colorType = [numChannels-1];//PNG color code
    var compMethod = [0];
    var filter = [0];
    var interlace = [0];
    write(IHDRdata, 0, magicNumberHdr);
    write(IHDRdata, 8, IHDRlen);
    write(IHDRdata, 12, IHDR);
    write(IHDRdata, 16, widthBytes);
    write(IHDRdata, 20, heightBytes);
    write(IHDRdata, 24, bitDepth);
    write(IHDRdata, 25, colorType);
    write(IHDRdata, 26, compMethod);
    write(IHDRdata, 27, filter);
    write(IHDRdata, 28, interlace);
    var IHDRchunk = IHDRdata.slice(12, 29);
    var IHDRcrc = intToBytes(crc32(IHDRchunk));
    write(IHDRdata, 29, IHDRcrc);

    //Palette - NOT USED RIGHT NOW
    //var PLTEdata = new Uint8Array(4 + 4 + 256 * 3 + 4);
    //var PLTELen = intToBytes(PLTEdata.length -4);
    //var PLTE = [80, 76, 84, 69];
    //write(PLTEdata, 0, PLTELen);
    //write(PLTEdata, 4, PLTE);
    //for (var p = 0; p < 256; p++) {
    //    write(PLTEdata, 8 + p * 3, [p, p, p]);
    //}
    //var PLTEcrc = intToBytes(crc32(PLTEdata.slice(4, PLTEdata.length - 4)));
    //write(PLTEdata, PLTEdata.length - 4, PLTEcrc);

    this.getBytes = function (compLevel) {
        //deflate pixeldata
        if (compLevel === void(0)) compLevel = 1;
        var defBytes = pako["deflate"](pxData, { level: compLevel });// , { level: 0 } no compression, level 1 is almost as fast
        var IDATlen = intToBytes(defBytes.length);
        var IDAT = [73, 68, 65, 84];

        var IENDlen = intToBytes(0);
        var IEND = [73, 69, 78, 68];
        var IENDcrc = intToBytes(crc32(IEND));

        var plteDataLen = 0;
        //var plteDataLen = PLTEdata.length;

        var dataLen = IHDRdata.length + IDATlen.length + IDAT.length + defBytes.length + 4 + IENDlen.length + IEND.length + IENDcrc.length;
        dataLen += plteDataLen;
        var data = new Uint8Array(dataLen);

        write(data, 0, IHDRdata);
        //write(data, 33, PLTEdata);
        write(data, 33 + plteDataLen, IDATlen);
        write(data, 37 + plteDataLen, IDAT);
        write(data, 41 + plteDataLen, defBytes);

        var idatData = new Uint8Array(37 + plteDataLen, data.length - 16);//includes the IDAT header

        var idatCRCposition = data.length - 16;
        var IDATcrc = intToBytes(crc32(idatData));

        write(data, idatCRCposition, IDATcrc);
        write(data, data.length - 12, IENDlen);
        write(data, data.length - 8, IEND);
        write(data, data.length - 4, IENDcrc);

        return data;
    }
}

//from https://stackoverflow.com/questions/18638900/javascript-crc32
var crc32 = (function () {
    var table = new Uint32Array(256);
    // Pre-generate crc32 polynomial lookup table
    for (var i = 256; i--;) {
        var tmp = i;
        for (var k = 8; k--;) {
            tmp = tmp & 1 ? 3988292384 ^ tmp >>> 1 : tmp >>> 1;
        }
        table[i] = tmp;
    }
    // crc32b
    return function (data) {
        var len = data.length;
        var crc = -1; // Begin with all bits set ( 0xffffffff )
        for (var i = 0, l = len; i < l; i++) {
            crc = crc >>> 8 ^ table[(crc ^ data[i]) & 255];
        }
        return (crc ^ -1) >>> 0; // Apply binary NOT
    };
})();
<commit_msg>fix bug in idat crc calc<commit_after>function JsPNG(width, height, isGrey) {
    "use strict";
    function write(buffer, offset, byteAry) {
        for (var i = 0; i < byteAry.length; i++) {
            buffer[offset + i] = byteAry[i];
        }
    }

    var numChannels = 3;
    if(isGrey) numChannels = 1;

    /* helper functions */
    var intBuf = new Uint32Array(1);
    //var shortBuf = new Uint16Array(1);
    var bufSize4 = new Uint8Array(intBuf.buffer);
    //var bufSize2 = new Uint8Array(shortBuf.buffer);
    var intToBytes = function(someInt) {
        intBuf[0] = swap32(someInt);
        return bufSize4.slice();
    }

    var swap32 = function(val) {
        return ((val & 0xFF) << 24)
               | ((val & 0xFF00) << 8)
               | ((val >> 8) & 0xFF00)
               | ((val >> 24) & 0xFF);
    }
    var swap16 = function(val) {
        return ((val & 0xFF) << 8)
               | ((val >> 8) & 0xFF);
    }

    var scanWidth = (width * numChannels) + 1;
    var pxData = new Uint8Array(height * scanWidth);//add one for filter byte

    var mask1 = 255; //R
    var mask2 = mask1 << 8; //G
    var mask3 = mask1 << 16; //B

	if(isGrey){
		this.setPixel = function (x, y, pxVal) {
			var yOffset = y * scanWidth;
			pxData[yOffset + x + 1] = pxVal;
		}
	}else{
		this.setPixel = function (x, y, r, g, b) {
			var yOffset = y * scanWidth;
			var xOffset = x * 3;
			if (g === void (0)) { //see if r is an RGB integer
				var val = r;
				r = val & mask1;
				g = (val & mask2) >> 8;
				b = (val & mask3) >> 16;
			}
			pxData[yOffset + xOffset + 1] = r;
			pxData[yOffset + xOffset + 2] = g;
			pxData[yOffset + xOffset + 3] = b;
		}
    }

    var IHDRdataLen = 33;
    var IHDRdata = new Uint8Array(IHDRdataLen);
    //each is an array of byte values
    var magicNumberHdr = [137, 80, 78, 71, 13, 10, 26, 10];
    var IHDRlen = intToBytes(13);
    var IHDR = [73, 72, 68, 82];
    var widthBytes = intToBytes(width);
    var heightBytes = intToBytes(height);
    var bitDepth = [8];
    var colorType = [numChannels-1];//PNG color code
    var compMethod = [0];
    var filter = [0];
    var interlace = [0];
    write(IHDRdata, 0, magicNumberHdr);
    write(IHDRdata, 8, IHDRlen);
    write(IHDRdata, 12, IHDR);
    write(IHDRdata, 16, widthBytes);
    write(IHDRdata, 20, heightBytes);
    write(IHDRdata, 24, bitDepth);
    write(IHDRdata, 25, colorType);
    write(IHDRdata, 26, compMethod);
    write(IHDRdata, 27, filter);
    write(IHDRdata, 28, interlace);
    var IHDRchunk = IHDRdata.slice(12, 29);
    var IHDRcrc = intToBytes(crc32(IHDRchunk));
    write(IHDRdata, 29, IHDRcrc);

    //Palette - NOT USED RIGHT NOW
    //var PLTEdata = new Uint8Array(4 + 4 + 256 * 3 + 4);
    //var PLTELen = intToBytes(PLTEdata.length -4);
    //var PLTE = [80, 76, 84, 69];
    //write(PLTEdata, 0, PLTELen);
    //write(PLTEdata, 4, PLTE);
    //for (var p = 0; p < 256; p++) {
    //    write(PLTEdata, 8 + p * 3, [p, p, p]);
    //}
    //var PLTEcrc = intToBytes(crc32(PLTEdata.slice(4, PLTEdata.length - 4)));
    //write(PLTEdata, PLTEdata.length - 4, PLTEcrc);

    this.getBytes = function (compLevel) {
        //deflate pixeldata
        if (compLevel === void(0)) compLevel = 1;
        var defBytes = pako["deflate"](pxData, { level: compLevel });// , { level: 0 } no compression, level 1 is almost as fast
        var IDATlen = intToBytes(defBytes.length);
        var IDAT = [73, 68, 65, 84];

        var IENDlen = intToBytes(0);
        var IEND = [73, 69, 78, 68];
        var IENDcrc = intToBytes(crc32(IEND));

        var plteDataLen = 0;
        //var plteDataLen = PLTEdata.length;

        var dataLen = IHDRdata.length + IDATlen.length + IDAT.length + defBytes.length + 4 + IENDlen.length + IEND.length + IENDcrc.length;
        dataLen += plteDataLen;
        var data = new Uint8Array(dataLen);

        write(data, 0, IHDRdata);
        //write(data, 33, PLTEdata);
        write(data, 33 + plteDataLen, IDATlen);
        write(data, 37 + plteDataLen, IDAT);
        write(data, 41 + plteDataLen, defBytes);

        var idatData = new Uint8Array(data.buffer.slice(37 + plteDataLen, data.length - 16));//includes the IDAT header

        var idatCRCposition = data.length - 16;
        var IDATcrc = intToBytes(crc32(idatData));

        write(data, idatCRCposition, IDATcrc);
        write(data, data.length - 12, IENDlen);
        write(data, data.length - 8, IEND);
        write(data, data.length - 4, IENDcrc);

        return data;
    }
}

//from https://stackoverflow.com/questions/18638900/javascript-crc32
var crc32 = (function () {
    var table = new Uint32Array(256);
    // Pre-generate crc32 polynomial lookup table
    for (var i = 256; i--;) {
        var tmp = i;
        for (var k = 8; k--;) {
            tmp = tmp & 1 ? 3988292384 ^ tmp >>> 1 : tmp >>> 1;
        }
        table[i] = tmp;
    }
    // crc32b
    return function (data) {
        var len = data.length;
        var crc = -1; // Begin with all bits set ( 0xffffffff )
        for (var i = 0, l = len; i < l; i++) {
            crc = crc >>> 8 ^ table[(crc ^ data[i]) & 255];
        }
        return (crc ^ -1) >>> 0; // Apply binary NOT
    };
})();
<|endoftext|>


<commit_before>(function(args)
{
	'use strict';
	var [obj,prop]=args,
		cherub=obj[prop]={},
		assertions=
		{
			equal:(actual,expected)=>actual===expected,
			stringify:(...args)=>assertions.equal(...args.map(JSON.stringify))
		},
		next=args=>args,
		defaults=
		{
			assert:assertions.stringify,
			cleanup:next,
			name:'',
			rtn:undefined,
			setup:next
		};
	cherub.assign=function(obj,defaults)
	{
		return Object.keys(defaults).reduce(function(obj,prop)
		{
			!obj.hasOwnProperty(prop)?obj[prop]=defaults[prop]:'';
			return obj;
		},obj);
	};
	cherub.build=function(test,inherits=defaults)
	{
		var tests=[];
		test=cherub.inherit(test,inherits);
		//don't add containers meant to pass on functions
		!test.tests.length&&test.func?tests.push(test):
		test.tests.forEach(function(subtest)//containers have tests or an empty array
		{
			tests.push(...cherub.build(subtest,test));
		});
		return tests;
	};
	cherub.config=
	{
		hidePassed:true,
		output:console.log,
		parallel:true,
		perf:
		{
			now:()=>Date.now(),
			precision:4,
			units:'ms'
		},
		shuffle:true
	};
	cherub.reportTime=function(time)
	{
		var {precision,units}=cherub.config.perf;
		return time.toFixed(precision)+units;
	};
	cherub.inherit=function(test,parent)
	{
		var {assert,cleanup,func,rtn,setup}=parent,
			parentProps={assert,cleanup,func,rtn,setup},
			minProps={name:'',notes:'',tests:[]};
		test=cherub.assign(test,minProps);
		test=cherub.assign(test,parentProps);
		test.name=(parent.name+'/'+test.name).replace(/^\//,'');//inherit parent's base name
		return test;
	};
	cherub.num2percent=num=>((num*100).toFixed(2)).replace(/\.00|0$/,'')+'%';
	cherub.run=function(test)///use rest parameters
	{
		var {build,config,fail,pass,shuffle}=cherub,
			{output,parallel,perf}=config,
			tests=build(test),
			passed=0,
			start=perf.now();
		var run=function(test)
		{
			var {args,assert,cleanup,func,name,notes,rtn,setup}=test,
				start=perf.now();
			return Promise.resolve()
			.then(setup)
			.then(()=>args?func(...args):func())//run tests
			.then(val=>({func:assert(val,rtn)?pass:fail,val}))//eval tests
			.catch(err=>({func:fail,val:err}))
			.then(obj=>Object.assign(obj,{name,notes,rtn,time:perf.now()-start}))//compile info
			.then(obj=>passed+=obj.func(obj))//report info
			.then(cleanup)
			.catch(next);
		};
		tests=config.shuffle?shuffle(tests):tests;
		return (parallel?Promise.all(tests.map(run)):
		tests.reduce((promise,test)=>promise.then(()=>run(test)),Promise.resolve()))
		.then(function()//score
		{
			var {num2percent,reportTime}=cherub,
				time=perf.now()-start,
				total=tests.length,
				failed=total-passed,//failed can be infered from totals & passed
				percentPassed=total?num2percent(passed/total):0;
			output(percentPassed+' Passed: '+passed+'/'+total+' '+reportTime(time)+'\n');
		});
	};
	cherub.fail=function(obj)///merge with pass
	{
		var {output,perf}=cherub.config,
			{name,rtn,time,val}=obj;
		output(name+': failed ('+cherub.reportTime(time)+') '+val+'!='+rtn+'\n');
		return 0;
	};
	cherub.pass=function(obj)
	{
		var {output,perf}=cherub.config,
			{name,time}=obj;///if (cherub.config.hidePassed)
		output(name+': passed ('+cherub.reportTime(time)+')');
		return 1;
	};
	cherub.shuffle=function(old)
	{
		return old.reduce(function(arr,item,i)
		{
			var j=~~(Math.random()*(arr.length));
			[arr[i],arr[j]]=[arr[j],arr[i]];
			return arr;
		},old.slice(0));
	};
	return cherub;
})(typeof exports==='undefined'?[window,'cherub']:[module,'exports']);<commit_msg>made passed/failed outputs consistent<commit_after>(function(args)
{
	'use strict';
	var [obj,prop]=args,
		cherub=obj[prop]={},
		assertions=
		{
			equal:(actual,expected)=>actual===expected,
			stringify:(...args)=>assertions.equal(...args.map(JSON.stringify))
		},
		next=args=>args,
		defaults=
		{
			assert:assertions.stringify,
			cleanup:next,
			name:'',
			rtn:undefined,
			setup:next
		};
	cherub.assign=function(obj,defaults)
	{
		return Object.keys(defaults).reduce(function(obj,prop)
		{
			!obj.hasOwnProperty(prop)?obj[prop]=defaults[prop]:'';
			return obj;
		},obj);
	};
	cherub.build=function(test,inherits=defaults)
	{
		var tests=[];
		test=cherub.inherit(test,inherits);
		//don't add containers meant to pass on functions
		!test.tests.length&&test.func?tests.push(test):
		test.tests.forEach(function(subtest)//containers have tests or an empty array
		{
			tests.push(...cherub.build(subtest,test));
		});
		return tests;
	};
	cherub.config=
	{
		hidePassed:true,
		output:console.log,
		parallel:true,
		perf:
		{
			now:()=>Date.now(),
			precision:4,
			units:'ms'
		},
		shuffle:true
	};
	cherub.reportTime=function(time)
	{
		var {precision,units}=cherub.config.perf;
		return time.toFixed(precision)+units;
	};
	cherub.inherit=function(test,parent)
	{
		var {assert,cleanup,func,rtn,setup}=parent,
			parentProps={assert,cleanup,func,rtn,setup},
			minProps={name:'',notes:'',tests:[]};
		test=cherub.assign(test,minProps);
		test=cherub.assign(test,parentProps);
		test.name=(parent.name+'/'+test.name).replace(/^\//,'');//inherit parent's base name
		return test;
	};
	cherub.num2percent=num=>((num*100).toFixed(2)).replace(/\.00|0$/,'')+'%';
	cherub.run=function(test)///use rest parameters
	{
		var {build,config,fail,pass,shuffle}=cherub,
			{output,parallel,perf}=config,
			tests=build(test),
			passed=0,
			start=perf.now();
		var run=function(test)
		{
			var {args,assert,cleanup,func,name,notes,rtn,setup}=test,
				start=perf.now();
			return Promise.resolve()
			.then(setup)
			.then(()=>args?func(...args):func())//run tests
			.then(val=>({func:assert(val,rtn)?pass:fail,val}))//eval tests
			.catch(err=>({func:fail,val:err}))
			.then(obj=>Object.assign(obj,{name,notes,rtn,time:perf.now()-start}))//compile info
			.then(obj=>passed+=obj.func(obj))//report info
			.then(cleanup)
			.catch(next);
		};
		tests=config.shuffle?shuffle(tests):tests;
		return (parallel?Promise.all(tests.map(run)):
		tests.reduce((promise,test)=>promise.then(()=>run(test)),Promise.resolve()))
		.then(function()//score
		{
			var {num2percent,reportTime}=cherub,
				time=perf.now()-start,
				total=tests.length,
				failed=total-passed,//failed can be infered from totals & passed
				percentPassed=total?num2percent(passed/total):0,
				name=passed+'/'+total+' ('+percentPassed+')';
			output('passed: '+name+' ('+reportTime(time)+')\n');
		});
	};
	cherub.fail=function(obj)///merge with pass
	{
		var {output,perf}=cherub.config,
			{name,rtn,time,val}=obj;
		output('failed: '+name+' ('+cherub.reportTime(time)+') '+val+'!='+rtn+'\n');
		return 0;
	};
	cherub.pass=function(obj)
	{
		var {output,perf}=cherub.config,
			{name,time}=obj;///if (cherub.config.hidePassed)
		output('passed: '+name+' ('+cherub.reportTime(time)+')');
		return 1;
	};
	cherub.shuffle=function(old)
	{
		return old.reduce(function(arr,item,i)
		{
			var j=~~(Math.random()*(arr.length));
			[arr[i],arr[j]]=[arr[j],arr[i]];
			return arr;
		},old.slice(0));
	};
	return cherub;
})(typeof exports==='undefined'?[window,'cherub']:[module,'exports']);<|endoftext|>


<commit_before>import { arr, obj, promise } from "lively.lang";
import { pt, Color, Rectangle } from "lively.graphics";
import { morph, Morph, Window, show } from "./index.js";
import { FilterableList } from "./list.js";
import { GridLayout } from "lively.morphic/layout.js";
import CodeEditor from "./ide/code-editor.js";

export class ObjectDrawer extends Morph {

  constructor(props) {
    super({
      name: "object-drawer",
      position: pt(20, 20),
      extent: pt(4 * (140 + 10) + 15, 140),
      fill: Color.white,
      borderWidth: 1,
      borderColor: Color.gray,
      ...props
    });
    this.setup();
  }

  setup() {
    var n = 4,
        margin = pt(5,5),
        objExt = pt(((this.width - margin.x) / n) - margin.x, this.height - margin.y*2),
        pos = margin;

    this.addMorph({
      type: "ellipse",
      position: pos, extent: objExt,
      fill: Color.random(), grabbable: false,
      onDrag: doCopy,
      init() { this.fill = Color.random(); }
    });

    pos = arr.last(this.submorphs).topRight.addXY(margin.x, 0);

    this.addMorph({
      position: pos, extent: objExt,
      fill: Color.random(), grabbable: false,
      onDrag: doCopy,
      init() { this.fill = Color.random(); }
    });

    pos = arr.last(this.submorphs).topRight.addXY(margin.x, 0);

    this.addMorph({
      type: "image",
      position: pos, extent: objExt,
      fill: null, grabbable: false,
      onDrag: doCopy
    });

    pos = arr.last(this.submorphs).topRight.addXY(margin.x, 0);

    this.addMorph({
      type: "text",
      textString: "Lively rocks!",
      position: pos, extent: objExt,
      fill: Color.white, grabbable: false,
      readOnly: true,
      fontSize: 16,
      onDrag: doCopy,
      draggable: true,
      init() {
        this.draggable = false;
        this.grabbable = false;
        this.readOnly = false;
      }
    });

    function doCopy(evt) {
      evt.stop();
      var copy = Object.assign(this.copy(), {position: evt.positionIn(this).negated()});
      var name = copy.constructor.name.toLowerCase();
      name = (name[0].match(/[aeiou]/) ? "an " : "a ") + name;
      var i = 1; while (this.world().get(name + " " + i)) i++
      copy.name = name + " " + i;
      evt.hand.grab(copy);
      delete copy.onDrag;
      copy.init && copy.init();
    }
  }
}

export class Workspace extends Window {

  constructor(props = {}) {
    super({
      title: "Workspace",
      targetMorph: {
        type: CodeEditor,
        textString: props.content || "var i = 2 + 3",
        mode: "javascript"
      },
      extent: pt(400,300),
      ...obj.dissoc(props, ["content"])
    });
  }

}
<commit_msg>customizable doitContext for workspace<commit_after>import { arr, obj, promise } from "lively.lang";
import { pt, Color, Rectangle } from "lively.graphics";
import { morph, Morph, Window, show } from "./index.js";
import { FilterableList } from "./list.js";
import { GridLayout } from "lively.morphic/layout.js";
import CodeEditor from "./ide/code-editor.js";

export class ObjectDrawer extends Morph {

  constructor(props) {
    super({
      name: "object-drawer",
      position: pt(20, 20),
      extent: pt(4 * (140 + 10) + 15, 140),
      fill: Color.white,
      borderWidth: 1,
      borderColor: Color.gray,
      ...props
    });
    this.setup();
  }

  setup() {
    var n = 4,
        margin = pt(5,5),
        objExt = pt(((this.width - margin.x) / n) - margin.x, this.height - margin.y*2),
        pos = margin;

    this.addMorph({
      type: "ellipse",
      position: pos, extent: objExt,
      fill: Color.random(), grabbable: false,
      onDrag: doCopy,
      init() { this.fill = Color.random(); }
    });

    pos = arr.last(this.submorphs).topRight.addXY(margin.x, 0);

    this.addMorph({
      position: pos, extent: objExt,
      fill: Color.random(), grabbable: false,
      onDrag: doCopy,
      init() { this.fill = Color.random(); }
    });

    pos = arr.last(this.submorphs).topRight.addXY(margin.x, 0);

    this.addMorph({
      type: "image",
      position: pos, extent: objExt,
      fill: null, grabbable: false,
      onDrag: doCopy
    });

    pos = arr.last(this.submorphs).topRight.addXY(margin.x, 0);

    this.addMorph({
      type: "text",
      textString: "Lively rocks!",
      position: pos, extent: objExt,
      fill: Color.white, grabbable: false,
      readOnly: true,
      fontSize: 16,
      onDrag: doCopy,
      draggable: true,
      init() {
        this.draggable = false;
        this.grabbable = false;
        this.readOnly = false;
      }
    });

    function doCopy(evt) {
      evt.stop();
      var copy = Object.assign(this.copy(), {position: evt.positionIn(this).negated()});
      var name = copy.constructor.name.toLowerCase();
      name = (name[0].match(/[aeiou]/) ? "an " : "a ") + name;
      var i = 1; while (this.world().get(name + " " + i)) i++
      copy.name = name + " " + i;
      evt.hand.grab(copy);
      delete copy.onDrag;
      copy.init && copy.init();
    }
  }
}

export class Workspace extends Window {

  constructor(props = {}) {
    super({
      title: "Workspace",
      targetMorph: {
        type: CodeEditor,
        textString: props.content || "var i = 2 + 3",
        mode: "javascript"
      },
      extent: pt(400,300),
      ...obj.dissoc(props, ["content"])
    });
    this.targetMorph.text.__defineGetter__("evalEnvironment", function () {
      return {
        targetModule: "lively://lively.next-workspace/" + this.id,
        context: this.doitContext || this.owner.doitContext || this
      }
    })
  }

}
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const http = require('http');

let regdateCache = {};
try {
	regdateCache = JSON.parse(fs.readFileSync('config/regdate.json', 'utf8'));
} catch (e) {}

module.exports = {
	sanitize: function (message) {
		if (message.charAt(0) === '/') message = '/' + message;
		if (message.charAt(0) === '!' || message.substr(0, 2) === '>>') message = ' ' + message;
		return message.replace(/\n/g, '');
	},
	log: function (text, serverid, error) {
		if (error) {
			fs.appendFileSync('logs/error.txt', '[' + serverid + '] ' + text);
		}
		fs.appendFileSync('logs/' + serverid + '.log', text + '\n');
		console.log(text);
	},
	randomString: function (length) {
		return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
	},
	toTimeStamp: function (date, options) {
		// Return a timestamp in the form {yyyy}-{MM}-{dd} {hh}:{mm}:{ss}.
		// Optionally reports hours in mod-12 format.
		const isHour12 = options && options.hour12;
		let parts = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()];
		if (isHour12) {
			parts.push(parts[3] >= 12 ? 'pm' : 'am');
			parts[3] = parts[3] % 12 || 12;
		}
		parts = parts.map(val => val < 10 ? '0' + val : '' + val);
		return parts.slice(0, 3).join("-") + " " + parts.slice(3, 6).join(":") + (isHour12 ? " " + parts[6] : "");
	},
	regdate: function (target, callback) {
		target = toId(target);
		if (regdateCache[target]) return callback(regdateCache[target]);
		let options = {
			host: 'pokemonshowdown.com',
			port: 80,
			path: '/users/' + target + '.json',
			method: 'GET',
		};
		http.get(options, function (res) {
			let data = '';
			res.on('data', function (chunk) {
				data += chunk;
			}).on('end', function () {
				if (data.charAt(0) !== '{') data = JSON.stringify({registertime: 0});
				data = JSON.parse(data);
				let date = data['registertime'];
				if (date !== 0 && date.toString().length < 13) {
					while (date.toString().length < 13) {
						date = Number(date.toString() + '0');
					}
				}
				if (date !== 0) {
					regdateCache[target] = date;
					fs.writeFileSync('config/regdate.json', JSON.stringify(regdateCache));
				}
				callback((date === 0 ? false : date));
			});
		});
	},
	// toDurationString from: https://github.com/Zarel/Pokemon-Showdown/blob/master/chat.js
	toDurationString: function (number, options) {
		// TODO: replace by Intl.DurationFormat or equivalent when it becomes available (ECMA-402)
		// https://github.com/tc39/ecma402/issues/47
		const date = new Date(+number);
		const parts = [date.getUTCFullYear() - 1970, date.getUTCMonth(), date.getUTCDate() - 1, date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()];
		const unitNames = ["second", "minute", "hour", "day", "month", "year"];
		const positiveIndex = parts.findIndex(elem => elem > 0);
		if (options && options.hhmmss) {
			let string = parts.slice(positiveIndex).map(value => value < 10 ? "0" + value : "" + value).join(":");
			return string.length === 2 ? "00:" + string : string;
		}
		return parts.slice(positiveIndex).reverse().map((value, index) => value ? value + " " + unitNames[index] + (value > 1 ? "s" : "") : "").reverse().join(" ").trim();
	},
	// uploadToHastebin function by TalkTakesTime (https://github.com/TalkTakesTime/Pokemon-Showdown-Bot)
	uploadToHastebin: function (toUpload, callback) {
		if (typeof callback !== 'function') return false;
		let reqOpts = {
			hostname: 'hastebin.com',
			method: 'POST',
			path: '/documents',
		};

		let req = http.request(reqOpts, function (res) {
			res.on('data', function (chunk) {
				// CloudFlare can go to hell for sending the body in a header request like this
				if (typeof chunk === 'string' && chunk.substr(0, 15) === '<!DOCTYPE html>') return callback('Error uploading to Hastebin.');
				let filename = JSON.parse(chunk.toString()).key;
				callback('http://hastebin.com/raw/' + filename);
			});
		});
		req.on('error', function (e) {
			callback('Error uploading to Hastebin: ' + e.message);
		});

		req.write(toUpload);
		req.end();
	},
};
<commit_msg>Uploading to hastebin now requires https<commit_after>'use strict';

const fs = require('fs');
const http = require('http');
const https = require('https');

let regdateCache = {};
try {
	regdateCache = JSON.parse(fs.readFileSync('config/regdate.json', 'utf8'));
} catch (e) {}

module.exports = {
	sanitize: function (message) {
		if (message.charAt(0) === '/') message = '/' + message;
		if (message.charAt(0) === '!' || message.substr(0, 2) === '>>') message = ' ' + message;
		return message.replace(/\n/g, '');
	},
	log: function (text, serverid, error) {
		if (error) {
			fs.appendFileSync('logs/error.txt', '[' + serverid + '] ' + text);
		}
		fs.appendFileSync('logs/' + serverid + '.log', text + '\n');
		console.log(text);
	},
	randomString: function (length) {
		return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
	},
	toTimeStamp: function (date, options) {
		// Return a timestamp in the form {yyyy}-{MM}-{dd} {hh}:{mm}:{ss}.
		// Optionally reports hours in mod-12 format.
		const isHour12 = options && options.hour12;
		let parts = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()];
		if (isHour12) {
			parts.push(parts[3] >= 12 ? 'pm' : 'am');
			parts[3] = parts[3] % 12 || 12;
		}
		parts = parts.map(val => val < 10 ? '0' + val : '' + val);
		return parts.slice(0, 3).join("-") + " " + parts.slice(3, 6).join(":") + (isHour12 ? " " + parts[6] : "");
	},
	regdate: function (target, callback) {
		target = toId(target);
		if (regdateCache[target]) return callback(regdateCache[target]);
		let options = {
			host: 'pokemonshowdown.com',
			port: 80,
			path: '/users/' + target + '.json',
			method: 'GET',
		};
		http.get(options, function (res) {
			let data = '';
			res.on('data', function (chunk) {
				data += chunk;
			}).on('end', function () {
				if (data.charAt(0) !== '{') data = JSON.stringify({registertime: 0});
				data = JSON.parse(data);
				let date = data['registertime'];
				if (date !== 0 && date.toString().length < 13) {
					while (date.toString().length < 13) {
						date = Number(date.toString() + '0');
					}
				}
				if (date !== 0) {
					regdateCache[target] = date;
					fs.writeFileSync('config/regdate.json', JSON.stringify(regdateCache));
				}
				callback((date === 0 ? false : date));
			});
		});
	},
	// toDurationString from: https://github.com/Zarel/Pokemon-Showdown/blob/master/chat.js
	toDurationString: function (number, options) {
		// TODO: replace by Intl.DurationFormat or equivalent when it becomes available (ECMA-402)
		// https://github.com/tc39/ecma402/issues/47
		const date = new Date(+number);
		const parts = [date.getUTCFullYear() - 1970, date.getUTCMonth(), date.getUTCDate() - 1, date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()];
		const unitNames = ["second", "minute", "hour", "day", "month", "year"];
		const positiveIndex = parts.findIndex(elem => elem > 0);
		if (options && options.hhmmss) {
			let string = parts.slice(positiveIndex).map(value => value < 10 ? "0" + value : "" + value).join(":");
			return string.length === 2 ? "00:" + string : string;
		}
		return parts.slice(positiveIndex).reverse().map((value, index) => value ? value + " " + unitNames[index] + (value > 1 ? "s" : "") : "").reverse().join(" ").trim();
	},
	// uploadToHastebin function by TalkTakesTime (https://github.com/TalkTakesTime/Pokemon-Showdown-Bot)
	uploadToHastebin: function (toUpload, callback) {
		if (typeof callback !== 'function') return false;
		let reqOpts = {
			hostname: 'hastebin.com',
			port: 443,
			method: 'POST',
			path: '/documents',
		};

		let req = https.request(reqOpts, function (res) {
			res.on('data', function (chunk) {
				// CloudFlare can go to hell for sending the body in a header request like this
				if (typeof chunk === 'string' && chunk.substr(0, 15) === '<!DOCTYPE html>') return callback('Error uploading to Hastebin.');
				let filename = JSON.parse(chunk.toString()).key;
				callback('http://hastebin.com/raw/' + filename);
			});
		});
		req.on('error', function (e) {
			callback('Error uploading to Hastebin: ' + e.message);
		});

		req.write(toUpload);
		req.end();
	},
};
<|endoftext|>


<commit_before>function loadView(){
	document.getElementById("welcomeView").innerHTML = document.getElementById("welcomeBody").innerHTML;
}

function validateLogin(){
	var bool=true;
	var x = document.forms["login"]["username"].value;
	if (x==null||x=="")
	{
		changeBorderColor(document.getElementById("username"), 2);
		bool=false;
	}
	else{
	}

	x = document.forms["login"]["password"].value;
	if (x==null||x=="")
	{
		changeBorderColor(document.getElementById("password"), 2);
		bool=false;
	}
	else{
	}
	return bool;
}

function validateSignup(){
	var bool=true;
	var x = document.forms["signup"]["firstName"].value;
	if(x==null||x=="")
	{
		changeBorderColor(document.getElementById("firstName"), 2);
		bool=false;
	}

	x = document.forms["signup"]["familyName"].value;
	if(x==null||x=="")
	{
		changeBorderColor(document.getElementById("familyName"), 2);
		bool=false;
	}

	x = document.forms["signup"]["city"].value;
	if(x==null||x=="")
	{
		changeBorderColor(document.getElementById("city"), 2);
		bool=false;
	}

	x = document.forms["signup"]["country"].value;
	if(x==null||x=="")
	{
		changeBorderColor(document.getElementById("country"), 2);
		bool=false;
	}

	x = document.forms["signup"]["email"].value;
	if(x==null||x=="")
	{
		changeBorderColor(document.getElementById("email"), 2);
		bool=false;
	}

	x = document.forms["signup"]["newPassword"].value;
	if(x==null||x=="")
	{
		changeBorderColor(document.getElementById("newPassword"), 2);
		bool=false;
	}

	y = document.forms["signup"]["confirmPassword"].value;
	if(y==null||y=="")
	{
		changeBorderColor(document.getElementById("confirmPassword"), 2);
		bool=false;
	}

	if (x!=y)
		{
			changeBorderColor(document.getElementById("newPassword"), 2);
			changeBorderColor(document.getElementById("confirmPassword"), 2);
			bool=false;
		};

return bool;

}

function changeBorderColor(inputfield, color){
	if (color==1)  //1 gives the standard black border color
	{
		inputfield.className="dotBorder";
	}
	else 		//anything else and we change to red border color
	{
		inputfield.className="invalidEntry";
	}
}

// displayView = function(){
//    // the code required to display a view.
// };
// document.onload = function(){
//     //code that is executed as the page is loaded.
// };<commit_msg>Changed the signup validation js so that the password fields are reset when their value differ.<commit_after>function loadView(){
	document.getElementById("welcomeView").innerHTML = document.getElementById("welcomeBody").innerHTML;
}

function validateLogin(){
	var bool=true;
	var x = document.forms["login"]["username"].value;
	if (x==null||x=="")
	{
		changeBorderColor(document.getElementById("username"), 2);
		bool=false;
	}
	else{
	}

	x = document.forms["login"]["password"].value;
	if (x==null||x=="")
	{
		changeBorderColor(document.getElementById("password"), 2);
		bool=false;
	}
	else{
	}
	return bool;
}

function validateSignup(){
	var bool=true;
	var x = document.forms["signup"]["firstName"].value;
	if(x==null||x=="")
	{
		changeBorderColor(document.getElementById("firstName"), 2);
		bool=false;
	}

	x = document.forms["signup"]["familyName"].value;
	if(x==null||x=="")
	{
		changeBorderColor(document.getElementById("familyName"), 2);
		bool=false;
	}

	x = document.forms["signup"]["city"].value;
	if(x==null||x=="")
	{
		changeBorderColor(document.getElementById("city"), 2);
		bool=false;
	}

	x = document.forms["signup"]["country"].value;
	if(x==null||x=="")
	{
		changeBorderColor(document.getElementById("country"), 2);
		bool=false;
	}

	x = document.forms["signup"]["email"].value;
	if(x==null||x=="")
	{
		changeBorderColor(document.getElementById("email"), 2);
		bool=false;
	}

	x = document.forms["signup"]["newPassword"].value;
	if(x==null||x=="")
	{
		changeBorderColor(document.getElementById("newPassword"), 2);
		bool=false;
	}

	y = document.forms["signup"]["confirmPassword"].value;
	if(y==null||y=="")
	{
		changeBorderColor(document.getElementById("confirmPassword"), 2);
		bool=false;
	}

	if (x!=y)
		{
			changeBorderColor(document.getElementById("newPassword"), 2);
			changeBorderColor(document.getElementById("confirmPassword"), 2);
			document.forms["signup"]["newPassword"].value="";
			document.forms["signup"]["confirmPassword"].value="";
			bool=false;
		};

return bool;

}

function changeBorderColor(inputfield, color){
	if (color==1)  //1 gives the standard black border color
	{
		inputfield.className="dotBorder";
	}
	else 		//anything else and we change to red border color
	{
		inputfield.className="invalidEntry";
	}
}

// displayView = function(){
//    // the code required to display a view.
// };
// document.onload = function(){
//     //code that is executed as the page is loaded.
// };<|endoftext|>


<commit_before>module.exports = {
  init: function() {
  	function isClient(name) {
  		var agent = window.navigator.userAgent,
  			index = agent.indexOf(name)
  		if (index < 0) { return false }
  		this.version = parseInt(agent.substr(index + name.length + 1))
  		return true
  	}
  	this.isIE = isClient('MSIE')
  	this.isFirefox = isClient('Firefox')
  	this.isWebKit = isClient('WebKit')
  	this.isChrome = isClient('Chrome')
  	this.isSafari = !this.isChrome && isClient('Safari')
  },

  isQuirksMode: function(doc) {
  	// in IE, if compatMode is undefined (early ie) or explicitly set to BackCompat, we're in quirks
  	return this.isIE && (!doc.compatMode || doc.compatMode == 'BackCompat')
  }
}

module.exports.init()
<commit_msg>Whitespace and bug fix in client<commit_after>module.exports = {
	init: function() {
		var client = this
		function isClient(name) {
			var agent = window.navigator.userAgent,
				index = agent.indexOf(name)
			if (index < 0) { return false }
			client.version = parseInt(agent.substr(index + name.length + 1))
			return true
		}
		client.isIE = isClient('MSIE')
		client.isFirefox = isClient('Firefox')
		client.isWebKit = isClient('WebKit')
		client.isChrome = isClient('Chrome')
		client.isSafari = !client.isChrome && isClient('Safari')
	},

	isQuirksMode: function(doc) {
		// in IE, if compatMode is undefined (early ie) or explicitly set to BackCompat, we're in quirks
		return this.isIE && (!doc.compatMode || doc.compatMode == 'BackCompat')
	}
}

module.exports.init()
<|endoftext|>


<commit_before>pipe.once('package:initialize', function (pagelet) {
  'use strict';

  //
  // We don't need to have any other information from the pagelet then the
  // placeholders/elements that contain our packages-pagelet placeholders.
  //
  pagelet = $(pagelet.placeholders);

  //
  // Show more rows when we click on the table footer.
  //
  pagelet.on('click', '.details .show-all', function click(e) {
    if (!~this.href.indexOf('#')) return; // We have a dependencies pagelet.

    e.preventDefault();

    var element = $(this)
      , text = element.text()
      , state = element.data('state')
      , parent = element.parents('.fourcol');

    //
    // Show the rows that were hidden and remove the table foot as we're already
    // showing all the fields now.
    //
    parent.find('.gone')[state ? 'fadeOut' : 'fadeIn']();
    element.text(element.data('text')).data('text', text).data('state', !state);
  });
});
<commit_msg>[fix] Adjust to the new layout<commit_after>pipe.once('package:initialize', function (pagelet) {
  'use strict';

  //
  // We don't need to have any other information from the pagelet then the
  // placeholders/elements that contain our packages-pagelet placeholders.
  //
  pagelet = $(pagelet.placeholders);

  //
  // Show more rows when we click on the table footer.
  //
  pagelet.on('click', '.details .show-all', function click(e) {
    if (!~this.href.indexOf('#')) return; // We have a dependencies pagelet.

    e.preventDefault();

    var element = $(this)
      , text = element.text()
      , state = element.data('state')
      , parent = element.parents('.sixcol');

    //
    // Show the rows that were hidden and remove the table foot as we're already
    // showing all the fields now.
    //
    parent.find('.gone')[state ? 'fadeOut' : 'fadeIn']();
    element.text(element.data('text')).data('text', text).data('state', !state);
  });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var minimist = require('minimist')
var compact2string = require('compact2string')
var dgram = require('dgram')
var os = require('os')

var argv = minimist(process.argv.slice(2), {alias: {'hole-puncher': 'h', channel: 'c', name: 'n'}})
var me = argv.name || os.hostname()
var hp = argv.h || 'dev.mathiasbuus.eu:23232'
var channel = new Buffer(argv.channel || 'broadcast')

if (argv.help) {
  console.log('Usage: telephone [options]')
  console.log('')
  console.log('  --hole-puncher, -h  [%s]', hp)
  console.log('  --name, -n          [%s]', os.hostname())
  console.log('  --channel, -c       [%s]', channel.toString())
  console.log()
  process.exit()
}

var sock = dgram.createSocket('udp4')
var peers = []

var PING = new Buffer([0])

var ping = function() {
  sock.send(PING, 0, PING.length, hp.split(':')[1] || 23232, hp.split(':')[0])
}

sock.once('message', function (message, rinfo) {
  if (message.length === 1 && message[0] === 0) return // ping
  setInterval(ping, 5000)

  // quick'n'dirty - first message is from the hole puncher

  peers = compact2string.multi(message).slice(0, -1)

  console.log('found %d peer(s) in channel: %s', peers.length, channel.toString())
  console.log('write a message and press <enter> to send')

  process.stdin.emit('data', new Buffer('(connected)'))
  sock.on('message', function (message, rinfo) {
    if (message.length === 1 && message[0] === 0) return // ping
    if (peers.indexOf(rinfo.address + ':' + rinfo.port) === -1) peers.push(rinfo.address + ':' + rinfo.port)
    console.log('[%s:%d] %s', rinfo.address, rinfo.port, message.toString().trim())
  })
})

process.stdin.on('data', function (data) {
  data = Buffer.concat([new Buffer(me + ': '), data])
  peers.forEach(function (peer) {
    sock.send(data, 0, data.length, Number(peer.split(':')[1]), peer.split(':')[0])
  })
})

sock.send(channel, 0, channel.length, hp.split(':')[1] || 23232, hp.split(':')[0])<commit_msg>fix tests<commit_after>#!/usr/bin/env node

var minimist = require('minimist')
var compact2string = require('compact2string')
var dgram = require('dgram')
var os = require('os')

var argv = minimist(process.argv.slice(2), {alias: {'hole-puncher': 'h', channel: 'c', name: 'n'}})
var me = argv.name || os.hostname()
var hp = argv.h || 'dev.mathiasbuus.eu:23232'
var channel = new Buffer(argv.channel || 'broadcast')

if (argv.help) {
  console.log('Usage: telephone [options]')
  console.log('')
  console.log('  --hole-puncher, -h  [%s]', hp)
  console.log('  --name, -n          [%s]', os.hostname())
  console.log('  --channel, -c       [%s]', channel.toString())
  console.log()
  process.exit()
}

var sock = dgram.createSocket('udp4')
var peers = []

var PING = new Buffer([0])

var ping = function() {
  sock.send(PING, 0, PING.length, hp.split(':')[1] || 23232, hp.split(':')[0])
}

sock.once('message', function (message, rinfo) {
  if (message.length === 1 && message[0] === 0) return // ping
  setInterval(ping, 5000)

  // quick'n'dirty - first message is from the hole puncher

  peers = compact2string.multi(message).slice(0, -1)

  console.log('found %d peer(s) in channel: %s', peers.length, channel.toString())
  console.log('write a message and press <enter> to send')

  process.stdin.emit('data', new Buffer('(connected)'))
  sock.on('message', function (message, rinfo) {
    if (message.length === 1 && message[0] === 0) return // ping
    if (peers.indexOf(rinfo.address + ':' + rinfo.port) === -1) peers.push(rinfo.address + ':' + rinfo.port)
    console.log('[%s:%d] %s', rinfo.address, rinfo.port, message.toString().trim())
  })
})

process.stdin.on('data', function (data) {
  data = Buffer.concat([new Buffer(me + ': '), data])
  peers.forEach(function (peer) {
    sock.send(data, 0, data.length, Number(peer.split(':')[1]), peer.split(':')[0])
  })
})

sock.send(channel, 0, channel.length, hp.split(':')[1] || 23232, hp.split(':')[0])
<|endoftext|>


<commit_before>var shoe = require('shoe');
var dnode = require('dnode');

var $ = require('jquery-browserify');

var displayedPosts = {};

function createPost(post) {
    switch (post.type) {
        case 'twitter':
            var t = $('<blockquote/>').addClass('twitter-tweet').append(
                $('<p/>').text(post.data.text)
            ).append(
                $('<a/>').attr('href', 'https://twitter.com/' + post.data.from_user + '/status/' + post.foreign_id).attr('data-datetime', post.foreign_timestamp)
            );

            if (post.data.in_reply_to_status_id) {
                t.attr('data-in-reply-to', post.data.in_reply_to_status_id);
            }

            return $('<div/>').addClass('post').append(t);
        case 'facebook':
            var t = $('<blockquote/>').addClass('facebook-post').append(
                $('<p/>').text('Facebook post')
            ).append(
                $('<p/>').text(post.data.message)
            ).append(
                $('<p/>').text('From: ').append(
                    $('<a/>').attr('href', 'https://www.facebook.com/' + post.data.from.id).text(post.data.from.name)
                )
            );

            return $('<div/>').addClass('post').append(t);
        default:
            console.error("Unknown post type: %s", post.type, post);
            return null;
    }
}

function displayNewPost(post) {
    if (displayedPosts[post.type + '-' + post.foreign_id]) {
        return;
    }

    var t = createPost(post);
    if (t) {
        t.prependTo('#posts');
        twttr.widgets.load();
    }
}

function displayOldPosts(posts) {
    $.each(posts, function (i, post) {
        if (displayedPosts[post.type + '-' + post.foreign_id]) {
            return;
        }

        var t = createPost(post);
        if (t) {
            t.appendTo('#posts');
        }
    });

    twttr.widgets.load();
}

$(document).ready(function () {
    var stream = shoe('/dnode');

    var d = dnode({
        'newPost': function (post) {
            displayNewPost(post);
        }
    });
    d.on('remote', function (remote) {
        remote.getPosts(null, 10, function (err, posts) {
            if (err) {
                console.error(err);
                return;
            }

            displayOldPosts(posts);
        });
    }).on('end', function () {
        // TODO: Handle better?
        alert("Connection to server failed. Please reload to continue with real-time updates.");
    }).pipe(stream).pipe(d);
});
<commit_msg>Improved error message.<commit_after>var shoe = require('shoe');
var dnode = require('dnode');

var $ = require('jquery-browserify');

var displayedPosts = {};

function createPost(post) {
    switch (post.type) {
        case 'twitter':
            var t = $('<blockquote/>').addClass('twitter-tweet').append(
                $('<p/>').text(post.data.text)
            ).append(
                $('<a/>').attr('href', 'https://twitter.com/' + post.data.from_user + '/status/' + post.foreign_id).attr('data-datetime', post.foreign_timestamp)
            );

            if (post.data.in_reply_to_status_id) {
                t.attr('data-in-reply-to', post.data.in_reply_to_status_id);
            }

            return $('<div/>').addClass('post').append(t);
        case 'facebook':
            var t = $('<blockquote/>').addClass('facebook-post').append(
                $('<p/>').text('Facebook post')
            ).append(
                $('<p/>').text(post.data.message)
            ).append(
                $('<p/>').text('From: ').append(
                    $('<a/>').attr('href', 'https://www.facebook.com/' + post.data.from.id).text(post.data.from.name)
                )
            );

            return $('<div/>').addClass('post').append(t);
        default:
            console.error("Unknown post type: %s", post.type, post);
            return null;
    }
}

function displayNewPost(post) {
    if (displayedPosts[post.type + '-' + post.foreign_id]) {
        return;
    }

    var t = createPost(post);
    if (t) {
        t.prependTo('#posts');
        twttr.widgets.load();
    }
}

function displayOldPosts(posts) {
    $.each(posts, function (i, post) {
        if (displayedPosts[post.type + '-' + post.foreign_id]) {
            return;
        }

        var t = createPost(post);
        if (t) {
            t.appendTo('#posts');
        }
    });

    twttr.widgets.load();
}

$(document).ready(function () {
    var stream = shoe('/dnode');

    var d = dnode({
        'newPost': function (post) {
            displayNewPost(post);
        }
    });
    d.on('remote', function (remote) {
        remote.getPosts(null, 10, function (err, posts) {
            if (err) {
                console.error(err);
                return;
            }

            displayOldPosts(posts);
        });
    }).on('end', function () {
        // TODO: Handle better?
        alert("Connection to the server failed. Please reload to continue with real-time updates.");
    }).pipe(stream).pipe(d);
});
<|endoftext|>


<commit_before>var map = null;
var legend = document.getElementById('legend');

function initMap() {
  // Create a map object and specify the DOM element for display.
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 38.922239,
      lng: -95.794675
    },
    disableDefaultUI: true,
    styles: styles,
    zoom: 5
  });
  map.controls[google.maps.ControlPosition.RIGHT_TOP].push(legend);

}

var styles = [{
    "elementType": "geometry",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "elementType": "labels.icon",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "elementType": "labels.text.stroke",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "featureType": "administrative.country",
    "elementType": "geometry.stroke",
    "stylers": [{
      "color": "#666666"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#bdbdbd"
    }]
  },
  {
    "featureType": "administrative.neighborhood",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "administrative.province",
    "elementType": "geometry.stroke",
    "stylers": [{
      "color": "#808080"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "road",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road",
    "elementType": "geometry",
    "stylers": [{
      "color": "#ffffff"
    }]
  },
  {
    "featureType": "road",
    "elementType": "labels",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road.arterial",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "geometry",
    "stylers": [{
      "color": "#dadada"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "featureType": "road.local",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "transit.line",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "transit.station",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "water",
    "elementType": "geometry",
    "stylers": [{
      "color": "#c9c9c9"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  }
];

var pointStyles = {
  'view': {
    'color': 'rgb(33, 150, 243)',
    'fillColor': 'rgb(33, 150, 243)',
    'fillOpacity': 0.2,
    'radius': 35000,
    'pane': 'overlayPane'
  },
  'commitment': {
    'color': 'rgb(29, 41, 114)',
    'fillColor': 'rgb(29, 41, 114)',
    'fillOpacity': 0.6,
    'radius': 55000,
    'pane': 'markerPane'
  }
};

var pageviews = 0;
var commitments = 0;

var from;

var lastEvaluatedKey;

// Displays the points data provided.
function displayPoints(data) {

  return new Promise(function(resolve, reject) {

    if (data.hasOwnProperty('LastEvaluatedKey')) {
      lastEvaluatedKey = data.LastEvaluatedKey.Id;
    } else {
      lastEvaluatedKey = 'finished';
      from = new Date() / 1000;
    }

    for (var i = 0; i < data.Items.length; i++) {

      // Create LatLng object
      var LatLng = new google.maps.LatLng({
        lat: data.Items[i].Coordinates[0],
        lng: data.Items[i].Coordinates[1]
      });

      var circle = new google.maps.Circle({
        fillColor: pointStyles[data.Items[i].Action].fillColor,
        fillOpacity: pointStyles[data.Items[i].Action].fillOpacity,
        map: map,
        center: LatLng,
        radius: pointStyles[data.Items[i].Action].radius,
        strokeWeight: 0
      });

      if (data.Items[i].Action === 'view') {
        pageviews++;
      }
      if (data.Items[i].Action === 'commitment') {
        commitments++;
      }
    }
    document.getElementById("pageviews").innerText = pageviews;
    document.getElementById("commitments").innerText = commitments;
    resolve('All points processed');
  });

}

// Updates map with latest real time data
// https://developers.google.com/web/fundamentals/getting-started/primers/promises
function get(url) {

  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);
    req.setRequestHeader('Content-Type', 'application/json');
    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      } else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        statusBad('Disconnected, server error');
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      statusBad('Disconnected, network error');
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

function delay(t) {
   return new Promise(function(resolve) {
       setTimeout(resolve, t);
   });
}

// https://medium.com/adobe-io/how-to-combine-rest-api-calls-with-javascript-promises-in-node-js-or-openwhisk-d96cbc10f299
// https://gist.github.com/trieloff/168312d4dd4d149afdd55cde3d3724cabea
var promiseChain = {
  runChain: function() {
    var timeString = '';
    if (from == null) {
      var d = new Date();
      d.setHours(0,0,0,0);
      d = d.getTime() / 1000;
      timeString = 'from=' + d + '&'; // If from is not set, set to midnight local time in seconds (accurate to the millisecond)
    } else {
      timeString = 'from=' + from + '&';
    }

    var exclusiveStartKeyString = '';
    if (lastEvaluatedKey != undefined && lastEvaluatedKey != 'finished') {
      exclusiveStartKeyString = '&exclusivestartkey=' + lastEvaluatedKey + '&';
    }

    get('/rest/live/read?' + timeString + exclusiveStartKeyString).then(JSON.parse).then(displayPoints).then(function() {
      if (lastEvaluatedKey !== 'finished') {
        promiseChain.runChain();
      } else {
        return delay(3000).then(function() {
          promiseChain.runChain();
        });
      }
    }, function(error) {
      console.error("callPromise Failed!", error);
      return delay(3000).then(function() {
        promiseChain.runChain();
      });
    }); // Anonymous function
    } // runChain
  }; // promiseChain

// Set a timer to reload the page at midnight.
// https://stackoverflow.com/questions/26387052/best-way-to-detect-midnight-and-reset-data
setTimeout(
  midnightTask,
  moment("24:00:00", "hh:mm:ss").diff(moment().tz('America/Denver'), 'milliseconds')
);

function midnightTask() {
  window.location.reload(true);
}

promiseChain.runChain(); // execute function
<commit_msg>Add statusGood call<commit_after>var map = null;
var legend = document.getElementById('legend');

function initMap() {
  // Create a map object and specify the DOM element for display.
  map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 38.922239,
      lng: -95.794675
    },
    disableDefaultUI: true,
    styles: styles,
    zoom: 5
  });
  map.controls[google.maps.ControlPosition.RIGHT_TOP].push(legend);

}

var styles = [{
    "elementType": "geometry",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "elementType": "labels.icon",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "elementType": "labels.text.stroke",
    "stylers": [{
      "color": "#f5f5f5"
    }]
  },
  {
    "featureType": "administrative.country",
    "elementType": "geometry.stroke",
    "stylers": [{
      "color": "#666666"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "administrative.land_parcel",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#bdbdbd"
    }]
  },
  {
    "featureType": "administrative.neighborhood",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "administrative.province",
    "elementType": "geometry.stroke",
    "stylers": [{
      "color": "#808080"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "poi",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "poi.park",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "road",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road",
    "elementType": "geometry",
    "stylers": [{
      "color": "#ffffff"
    }]
  },
  {
    "featureType": "road",
    "elementType": "labels",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "road.arterial",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#757575"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "geometry",
    "stylers": [{
      "color": "#dadada"
    }]
  },
  {
    "featureType": "road.highway",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#616161"
    }]
  },
  {
    "featureType": "road.local",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  },
  {
    "featureType": "transit.line",
    "elementType": "geometry",
    "stylers": [{
      "color": "#e5e5e5"
    }]
  },
  {
    "featureType": "transit.station",
    "elementType": "geometry",
    "stylers": [{
      "color": "#eeeeee"
    }]
  },
  {
    "featureType": "water",
    "elementType": "geometry",
    "stylers": [{
      "color": "#c9c9c9"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text",
    "stylers": [{
      "visibility": "off"
    }]
  },
  {
    "featureType": "water",
    "elementType": "labels.text.fill",
    "stylers": [{
      "color": "#9e9e9e"
    }]
  }
];

var pointStyles = {
  'view': {
    'color': 'rgb(33, 150, 243)',
    'fillColor': 'rgb(33, 150, 243)',
    'fillOpacity': 0.2,
    'radius': 35000,
    'pane': 'overlayPane'
  },
  'commitment': {
    'color': 'rgb(29, 41, 114)',
    'fillColor': 'rgb(29, 41, 114)',
    'fillOpacity': 0.6,
    'radius': 55000,
    'pane': 'markerPane'
  }
};

var pageviews = 0;
var commitments = 0;

var from;

var lastEvaluatedKey;

// Displays the points data provided.
function displayPoints(data) {

  return new Promise(function(resolve, reject) {

    if (data.hasOwnProperty('LastEvaluatedKey')) {
      lastEvaluatedKey = data.LastEvaluatedKey.Id;
    } else {
      lastEvaluatedKey = 'finished';
      from = new Date() / 1000;
    }

    for (var i = 0; i < data.Items.length; i++) {

      // Create LatLng object
      var LatLng = new google.maps.LatLng({
        lat: data.Items[i].Coordinates[0],
        lng: data.Items[i].Coordinates[1]
      });

      var circle = new google.maps.Circle({
        fillColor: pointStyles[data.Items[i].Action].fillColor,
        fillOpacity: pointStyles[data.Items[i].Action].fillOpacity,
        map: map,
        center: LatLng,
        radius: pointStyles[data.Items[i].Action].radius,
        strokeWeight: 0
      });

      if (data.Items[i].Action === 'view') {
        pageviews++;
      }
      if (data.Items[i].Action === 'commitment') {
        commitments++;
      }
    }
    document.getElementById("pageviews").innerText = pageviews;
    document.getElementById("commitments").innerText = commitments;
    resolve('All points processed');
  });

}

// Updates map with latest real time data
// https://developers.google.com/web/fundamentals/getting-started/primers/promises
function get(url) {

  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);
    req.setRequestHeader('Content-Type', 'application/json');
    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      } else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        statusBad('Disconnected, server error');
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      statusBad('Disconnected, network error');
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

function delay(t) {
   return new Promise(function(resolve) {
       setTimeout(resolve, t);
   });
}

// https://medium.com/adobe-io/how-to-combine-rest-api-calls-with-javascript-promises-in-node-js-or-openwhisk-d96cbc10f299
// https://gist.github.com/trieloff/168312d4dd4d149afdd55cde3d3724cabea
var promiseChain = {
  runChain: function() {
    var timeString = '';
    if (from == null) {
      var d = new Date();
      d.setHours(0,0,0,0);
      d = d.getTime() / 1000;
      timeString = 'from=' + d + '&'; // If from is not set, set to midnight local time in seconds (accurate to the millisecond)
    } else {
      timeString = 'from=' + from + '&';
    }

    var exclusiveStartKeyString = '';
    if (lastEvaluatedKey != undefined && lastEvaluatedKey != 'finished') {
      exclusiveStartKeyString = '&exclusivestartkey=' + lastEvaluatedKey + '&';
    }

    get('/rest/live/read?' + timeString + exclusiveStartKeyString).then(JSON.parse).then(displayPoints).then(function() {
      if (lastEvaluatedKey !== 'finished') {
        promiseChain.runChain();
      } else {
        statusGood('Map connected live');
        return delay(3000).then(function() {
          promiseChain.runChain();
        });
      }
    }, function(error) {
      console.error("callPromise Failed!", error);
      return delay(3000).then(function() {
        promiseChain.runChain();
      });
    }); // Anonymous function
    } // runChain
  }; // promiseChain

// Set a timer to reload the page at midnight.
// https://stackoverflow.com/questions/26387052/best-way-to-detect-midnight-and-reset-data
setTimeout(
  midnightTask,
  moment("24:00:00", "hh:mm:ss").diff(moment().tz('America/Denver'), 'milliseconds')
);

function midnightTask() {
  window.location.reload(true);
}

promiseChain.runChain(); // execute function
<|endoftext|>


<commit_before>(function(win){

  var Config = {};
  Config.help = "?";
  Config.helpTitle = "Keyboard Shortcuts";
  Config.helpHref = "https://dokumenty.internetguru.cz/zkratky";
  Config.appDisable = "×";
  Config.appDisableTitle = "Deactivate CodeMirror (F4)";
  Config.appEnable = "Activate CodeMirror";
  Config.appEnableTitle = "F4";
  Config.format = "Beautify";
  Config.formatTitle = "Ctrl+Shift+B";
  Config.fullscreenDisable = "▫";
  Config.fullscreenDisableTitle = "Disable Fullscreen (Shift+F11)";
  Config.fullscreenEnable = "□";
  Config.fullScreenEnableTitle = "Maximalize (Shift+F11)";
  Config.find = "Find";
  Config.findTitle = "Ctrl+F";
  Config.replace = "Replace";
  Config.replaceTitle = "Ctrl+H";
  Config.appName = "CodeMirror";

  var SyntaxCodeMirror = function() {
    // private
    var
    cm = null,
    scm = null,
    textarea = null,
    visible = true,
    active = true,
    activateUl = null,
    appendButton = function(text, ul, href) {
      var li = document.createElement("li");
      ul.appendChild(li);
      var b;
      if(typeof href == "undefined") {
        b = document.createElement("button");
      } else {
        b = document.createElement("a");
        b.href = href;
      }
      li.appendChild(b);
      b.type = "button";
      b.textContent = text;
      return b;
    },
    toggleApp = function() {
      if(cm.getOption("fullScreen")) toggleFullScreen(cm);
      if(active) {
        cm.toTextArea();
        activateUl.style.display = "";
        textarea.focus();
      } else {
        _init();
        activateUl.style.display = "none";
        cm.focus();
      }
      active = !active;
    },
    autoFormatSelection = function(c) {
      var range = c.execCommand("getSelectedRange");
      c.autoFormatRange(range.from, range.to);
    },
    autoIndentSelection = function(c) {
      var range = c.execCommand("getSelectedRange");
      c.autoIndentRange(range.from, range.to);
    },
    toggleFullScreen = function(c, off) {
      if(typeof off === "undefined") off = false;
      if(!active) return;
      if(c.getOption("fullScreen") || off) {
        c.setOption("fullScreen", false);
        fullScreenButton.textContent = Config.fullscreenEnable;
        fullScreenButton.title = Config.fullScreenEnableTitle;
      } else {
        c.setOption("fullScreen", true);
        fullScreenButton.textContent = Config.fullscreenDisable;
        fullScreenButton.title = Config.fullscreenDisableTitle;
      }
    },
    scrollWin = function(step) {
      var doc = document.documentElement;
      var top = (win.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
      var height = document.body.scrollHeight;
      var scrollTo = top + step;
      if(scrollTo < 0 || scrollTo > height ) return;
      win.scrollTo(0, scrollTo);
    },
    fireEvents = function() {
      win.onkeydown = function(e) {
        var key;
        var isShift;
        if (win.event) {
          key = win.event.keyCode;
          isShift = !!win.event.shiftKey; // typecast to boolean
          isCtrl = !!win.event.ctrlKey; // typecast to boolean
        } else {
          key = e.which;
          isShift = !!e.shiftKey;
          isCtrl = !!e.ctrlKey;
        }
        switch (key) {
          // F4
          case 115:
          if (textarea.closest("form.hideable-hide")) {
            break;
          }
          toggleApp(cm);
          break;
          // Shift + F11
          case 122:
          if(isShift) {
            if (textarea.closest("form.hideable-hide")) {
              break;
            }
            toggleFullScreen(cm);
            cm.focus();
            break;
          }
          // Tab, Shift+Tab
          case 9:
          toggleFullScreen(cm, true);
          default: return true;
        }
        return false;
      }
    },
    initEditor = function() {
      cm = CodeMirror.fromTextArea(textarea, {
        tabMode: "default",
        keyMap:"sublime",
        theme:"tomorrow-night-eighties",
        lineNumbers: true,
        mode: textarea.classList.item(1),
        width:"100%",
        lineWrapping: true,
        matchTags: { bothTags: true },
        //tabSize: 2,
        styleActiveLine: true,
        styleSelectedText: true,
        autoCloseTags: {
          whenClosing: true,
          whenOpening: false
        },
        extraKeys: CodeMirror.normalizeKeyMap({
          "Tab": false,
          "Shift-Tab": false,
	        "Ctrl-Shift-R": false,
          "Ctrl-Up": function(c) {
            if(c.getOption("fullScreen"))
              c.execCommand("scrollLineUp");
            else scrollWin(-32);
          },
          "Ctrl-Down": function(c) {
            if(c.getOption("fullScreen"))
              c.execCommand("scrollLineDown");
            else scrollWin(32);
          },
          "Ctrl--": "toggleComment",
          "Ctrl-G": "jumpToLine",
          "Ctrl-E": "deleteLine",
          "End": "goLineRight",
          "Home": "goLineLeftSmart",
          "Ctrl-Shift-H": "replaceAll",
          "Ctrl-Shift-B": function(c) { autoFormatSelection(c); },
          "Ctrl-Shift-I": function(c) { autoIndentSelection(c); },
          "F3": function(c) { c.execCommand("findNext"); },
          "Shift-F3": function(c) { c.execCommand("findPrev"); },
        })
      });
    },
    initActivateButton = function() {
      activateUl = document.createElement("ul");
      var activateButton = appendButton(Config.appEnable, activateUl);
      activateButton.title = Config.appEnableTitle;
      textarea.parentNode.insertBefore(activateUl, textarea);
      activateUl.style.display = "none";
      activateButton.addEventListener("click", toggleApp, false);
    },
    initUserMenu = function() {
      var ul = document.createElement("ul");
      ul.className="codemirror-user-controll";

      var findButton = appendButton(Config.find, ul);
      findButton.title = Config.findTitle;
      var replaceButton = appendButton(Config.replace, ul);
      replaceButton.title = Config.replaceTitle;
      var formatButton = appendButton(Config.format, ul);
      formatButton.title = Config.formatTitle;
      var helpButton = appendButton(Config.help, ul, Config.helpHref);
      helpButton.title = Config.helpTitle;
      var fullScreenButton = appendButton(Config.fullscreenEnable, ul);
      fullScreenButton.title = Config.fullScreenEnableTitle;
      var disableButton = appendButton(Config.appDisable, ul);
      disableButton.title = Config.appDisableTitle;
      textarea.nextSibling.insertBefore(ul, textarea.nextSibling.firstChild);

      findButton.onclick = function() {
        CodeMirror.commands.find(cm);
      }
      replaceButton.onclick = function() {
        CodeMirror.commands.replace(cm);
      }
      fullScreenButton.onclick = function() {
        toggleFullScreen(cm);
      }
      formatButton.onclick = function() {
        autoFormatSelection(cm);
      }
      disableButton.onclick = function() {
        toggleApp(cm);
      }
    },
    _init = function() {
      initEditor();
      initUserMenu();
    }
    // public
    return {
      init : function(newTextarea, newScm) {
        // initCfg(cfg);
        scm = newScm;
        textarea = newTextarea;
        _init();
        initActivateButton();
        fireEvents();
      },
      getInstance : function() {
        return cm;
      }
    }
  };

  var textareas = document.querySelectorAll('textarea.codemirror');
  var cm = new SyntaxCodeMirror();
  cm.init(textareas[0], cm);
  win.CodeMirrorInstance = cm.getInstance();

})(window);
<commit_msg>fix toggle fullscreen<commit_after>(function(win){

  var Config = {};
  Config.help = "?";
  Config.helpTitle = "Keyboard Shortcuts";
  Config.helpHref = "https://dokumenty.internetguru.cz/zkratky";
  Config.appDisable = "×";
  Config.appDisableTitle = "Deactivate CodeMirror (F4)";
  Config.appEnable = "Activate CodeMirror";
  Config.appEnableTitle = "F4";
  Config.format = "Beautify";
  Config.formatTitle = "Ctrl+Shift+B";
  Config.fullscreenDisable = "▫";
  Config.fullscreenDisableTitle = "Disable Fullscreen (Shift+F11)";
  Config.fullscreenEnable = "□";
  Config.fullScreenEnableTitle = "Maximalize (Shift+F11)";
  Config.find = "Find";
  Config.findTitle = "Ctrl+F";
  Config.replace = "Replace";
  Config.replaceTitle = "Ctrl+H";
  Config.appName = "CodeMirror";

  var SyntaxCodeMirror = function() {
    // private
    var
    cm = null,
    scm = null,
    textarea = null,
    fullScreenButton = null,
    visible = true,
    active = true,
    activateUl = null,
    appendButton = function(text, ul, href) {
      var li = document.createElement("li");
      ul.appendChild(li);
      var b;
      if(typeof href == "undefined") {
        b = document.createElement("button");
      } else {
        b = document.createElement("a");
        b.href = href;
      }
      li.appendChild(b);
      b.type = "button";
      b.textContent = text;
      return b;
    },
    toggleApp = function() {
      if(cm.getOption("fullScreen")) toggleFullScreen(cm);
      if(active) {
        cm.toTextArea();
        activateUl.style.display = "";
        textarea.focus();
      } else {
        _init();
        activateUl.style.display = "none";
        cm.focus();
      }
      active = !active;
    },
    autoFormatSelection = function(c) {
      var range = c.execCommand("getSelectedRange");
      c.autoFormatRange(range.from, range.to);
    },
    autoIndentSelection = function(c) {
      var range = c.execCommand("getSelectedRange");
      c.autoIndentRange(range.from, range.to);
    },
    toggleFullScreen = function(c, off) {
      if(typeof off === "undefined") off = false;
      if(!active) return;
      if(c.getOption("fullScreen") || off) {
        c.setOption("fullScreen", false);
        fullScreenButton.textContent = Config.fullscreenEnable;
        fullScreenButton.title = Config.fullScreenEnableTitle;
      } else {
        c.setOption("fullScreen", true);
        fullScreenButton.textContent = Config.fullscreenDisable;
        fullScreenButton.title = Config.fullscreenDisableTitle;
      }
    },
    scrollWin = function(step) {
      var doc = document.documentElement;
      var top = (win.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
      var height = document.body.scrollHeight;
      var scrollTo = top + step;
      if(scrollTo < 0 || scrollTo > height ) return;
      win.scrollTo(0, scrollTo);
    },
    fireEvents = function() {
      win.onkeydown = function(e) {
        var key;
        var isShift;
        if (win.event) {
          key = win.event.keyCode;
          isShift = !!win.event.shiftKey; // typecast to boolean
          isCtrl = !!win.event.ctrlKey; // typecast to boolean
        } else {
          key = e.which;
          isShift = !!e.shiftKey;
          isCtrl = !!e.ctrlKey;
        }
        switch (key) {
          // F4
          case 115:
          if (textarea.closest("form.hideable-hide")) {
            break;
          }
          toggleApp(cm);
          break;
          // Shift + F11
          case 122:
          if(isShift) {
            if (textarea.closest("form.hideable-hide")) {
              break;
            }
            toggleFullScreen(cm);
            cm.focus();
            break;
          }
          // Tab, Shift+Tab
          case 9:
          toggleFullScreen(cm, true);
          default: return true;
        }
        return false;
      }
    },
    initEditor = function() {
      cm = CodeMirror.fromTextArea(textarea, {
        tabMode: "default",
        keyMap:"sublime",
        theme:"tomorrow-night-eighties",
        lineNumbers: true,
        mode: textarea.classList.item(1),
        width:"100%",
        lineWrapping: true,
        matchTags: { bothTags: true },
        //tabSize: 2,
        styleActiveLine: true,
        styleSelectedText: true,
        autoCloseTags: {
          whenClosing: true,
          whenOpening: false
        },
        extraKeys: CodeMirror.normalizeKeyMap({
          "Tab": false,
          "Shift-Tab": false,
          "Ctrl-Shift-R": false,
          "Ctrl-Up": function(c) {
            if(c.getOption("fullScreen"))
              c.execCommand("scrollLineUp");
            else scrollWin(-32);
          },
          "Ctrl-Down": function(c) {
            if(c.getOption("fullScreen"))
              c.execCommand("scrollLineDown");
            else scrollWin(32);
          },
          "Ctrl--": "toggleComment",
          "Ctrl-G": "jumpToLine",
          "Ctrl-E": "deleteLine",
          "End": "goLineRight",
          "Home": "goLineLeftSmart",
          "Ctrl-Shift-H": "replaceAll",
          "Ctrl-Shift-B": function(c) { autoFormatSelection(c); },
          "Ctrl-Shift-I": function(c) { autoIndentSelection(c); },
          "F3": function(c) { c.execCommand("findNext"); },
          "Shift-F3": function(c) { c.execCommand("findPrev"); },
        })
      });
    },
    initActivateButton = function() {
      activateUl = document.createElement("ul");
      var activateButton = appendButton(Config.appEnable, activateUl);
      activateButton.title = Config.appEnableTitle;
      textarea.parentNode.insertBefore(activateUl, textarea);
      activateUl.style.display = "none";
      activateButton.addEventListener("click", toggleApp, false);
    },
    initUserMenu = function() {
      var ul = document.createElement("ul");
      ul.className="codemirror-user-controll";

      var findButton = appendButton(Config.find, ul);
      findButton.title = Config.findTitle;
      var replaceButton = appendButton(Config.replace, ul);
      replaceButton.title = Config.replaceTitle;
      var formatButton = appendButton(Config.format, ul);
      formatButton.title = Config.formatTitle;
      var helpButton = appendButton(Config.help, ul, Config.helpHref);
      helpButton.title = Config.helpTitle;
      fullScreenButton = appendButton(Config.fullscreenEnable, ul);
      fullScreenButton.title = Config.fullScreenEnableTitle;
      var disableButton = appendButton(Config.appDisable, ul);
      disableButton.title = Config.appDisableTitle;
      textarea.nextSibling.insertBefore(ul, textarea.nextSibling.firstChild);

      findButton.onclick = function() {
        CodeMirror.commands.find(cm);
      }
      replaceButton.onclick = function() {
        CodeMirror.commands.replace(cm);
      }
      fullScreenButton.onclick = function() {
        toggleFullScreen(cm);
      }
      formatButton.onclick = function() {
        autoFormatSelection(cm);
      }
      disableButton.onclick = function() {
        toggleApp(cm);
      }
    },
    _init = function() {
      initEditor();
      initUserMenu();
    }
    // public
    return {
      init : function(newTextarea, newScm) {
        // initCfg(cfg);
        scm = newScm;
        textarea = newTextarea;
        _init();
        initActivateButton();
        fireEvents();
      },
      getInstance : function() {
        return cm;
      }
    }
  };

  var textareas = document.querySelectorAll('textarea.codemirror');
  var cm = new SyntaxCodeMirror();
  cm.init(textareas[0], cm);
  win.CodeMirrorInstance = cm.getInstance();

})(window);
<|endoftext|>