<commit_before>"use strict";

var sj = new function(endpoint) {

	// General endpoint for client-server interaction
	this.setEndpoint = function(url) { endpoint = url };
	this.setRequestWait = function(callback) { onRequestWait = callback };
	this.setRequestComplete = function(callback) { onRequestComplete = callback };
	this.setClickCallback = function(callback) { onClickCallback = callback };
	this.setRequestError = function(callback) { onRequestError = callback };
	this.setBeforeAction = function(callback) { onBeforeAction = callback };
	this.setDefaultAction = function(callback) { onDefaultAction = callback };
	this.setFallbackAction = function(callback) { onFallbackAction = callback };
	this.setBeforeRequest = function(callback) { onBeforeRequest = callback };

	// Render function
	// p = { k: { dataid: v } }
	function renderSingle(el, p, opt) {
		for (var k in p) {
			var a = p[k];
			if (typeof a == "string" || typeof a == "number") a = { _: a };
			else if (typeof a == "boolean") a = { hidden: !a };

			var list = k == "_" ? [el] : Array.from(el.querySelectorAll("[data-id="+k+"]"));
			if (!list.length) throw "Element `"+k+"` not found";

			list.forEach(function(l) {
				if (a instanceof Array) {
					renderArray(l, a, opt);
				} else if (a instanceof HTMLElement) {
					l.parentNode.replaceChild(a, l);
				} else {
					for (var i in a) {
						if (i == "_") {
							if (l.tagName == "INPUT" && (l.type == "radio" || l.type == "checkbox")) {
								l.checked = (l.value == a[i]);
							} else if (l.tagName == "INPUT" || l.tagName == "TEXTAREA") {
								l.value = a[i];
							} else if (l.tagName == "SELECT") {
								for (var j = 0; j < l.options.length; j++) l.options[j].selected = (l.options[j].value == a[i]);
							} else if (l.hasAttribute('data-html')) {
								l.innerHTML = a[i];
							} else {
								l.innerHTML = "";
								l.appendChild(document.createTextNode(a[i]));
							}
						} else if (i == "style") {
							for (var j in a[i]) l.style[j] = a[i][j];
						} else if (i == "data") {
							for (var j in a[i]) l.dataset[j] = a[i][j];
						} else if (i == "visible") {
							l.hidden = !a[i];
						} else if (i == "hidden") {
							l.hidden = a[i];
						} else if (i == "className") {
							l.className = a[i];
						} else if (i == "classList") {
							if (a[i] instanceof Array == false) a[i] = [a[i]];
							for (var j in a[i]) {
								if (!a[i][j]) continue;
								if (a[i][j][0] == "-") {
									l.classList.remove(a[i][j].substring(1));
								} else if (a[i][j][0] == "+") {
									l.classList.add(a[i][j].substring(1));
								} else {
									l.classList.toggle(a[i][j]);
								}
							}
						} else if (a[i] === false) {
							l.removeAttribute(i);
						} else if (a[i] === true) {
							l.setAttribute(i, "");
						} else {
							l.setAttribute(i, a[i]);
						}
					}
				}
			});
		}
	}

	function renderArray(el, p, opt) {
		if (!opt.append) while (!el.lastElementChild.hidden) el.removeChild(el.lastElementChild);
		p.forEach(function(i) {
			if (i instanceof HTMLElement) {
				el.appendChild(i);
			} else {
				var clone = el.firstElementChild.cloneNode(true);
				clone.hidden = false;
				renderSingle(clone, i, opt);
				el.appendChild(clone);
			}
		});
	}

	var componentClass = function(id, obj) {

		this.oncreate = function() {}
		this.onshow = function() {}
		this.onpostshow = function() {}
		this.onprehide = function() {}
		this.onhide = function() {}
		this.onclick = function(ev, target) { onClickCallback(ev, this.el, target) }
		this.onaction = function(action, target) {
			if (this[action.identry]) {
				this[action.identry](action, target, this);
				return true;
			} else {
				return onDefaultAction(action, target, this);
			}
		}
		this.onsubmit = function(ev, target) { onSubmitCallback(ev, this.el, target) }
		this.onrequest = function() {}
		this.onresponse = function() {}
		this.onerror = function(json) { onRequestError(json) }

		this.hide = function() {
			this.onprehide();
			this.el.hidden = true;
			this.onhide();
		}
		this.show = function() {
			this.onshow();
			this.el.hidden = false;
			this.onpostshow();
		}
		this.visible = function(b) {
			if (b) this.show(); else this.hide();
		}

		this.action = function(q) {
			sj.request(q);
		},

		this.render = function(p, opt) {
			if (!loaded || !p || typeof p != "object") return;
			if (!opt) opt = {};

			var el;
			if (!opt.sub) {
				el = this.el;
			} else if (typeof opt.sub == "string") {
				el = this.el.querySelector("[data-id="+opt.sub+"]");
			} else if (typeof opt.sub == "object") {
				var t = opt.sub;
				while (t != document.body && t != this.el) t = t.parentNode;
				if (t == this.el) {
					el = opt.sub;
				} else {
					throw "Element outside the Component";
				}
			}
			if (!el) throw "Root element not found";

			renderSingle(el, p, opt);

			if (this.onrender) this.onrender();
		}

		this.getElement = function(id) {
			return this.el.querySelector("[data-id="+id+"]");
		},

		this.id = id;
		this.el = document.getElementById(id);
		if (!this.el) throw "Component `"+id+"` not found";
		this.el.setAttribute("data-component", "");
		this.loop = this.el;

		for (var i in obj) {
			if (i == "loop") obj[i] = document.getElementById(obj[i]);
			this[i] = obj[i];
		}

	}

	this.component = function(id, obj) {
		components[id] = (obj ? obj : {});
		if (loaded) {
			components[id] = new componentClass(id, obj);
			components[id].oncreate();
		}
	}

	function containerClass(id, start, obj) {
		this.current = start;
		this.onChange = function(current) {}

		this.set = function(id) {
			this.current = id;
			for (var i = 0; i < this.el.children.length; i++) {
				var el = this.el.children[i];
				if (el.hasAttribute("data-component")) {
					sj.$(el.id).visible(el.id == id);
				}
			}
			this.onChange(this.current);
		}

		this.get = function() {
			return this.current;
		}

		this.el = document.getElementById(id);
		if (!this.el) throw "Container `"+id+"` not found";
		this.el.setAttribute("data-container", "");

		for (var i = 0; i < this.el.children.length; i++) {
			var el = this.el.children[i];
			sj.$(el.id).visible(el.id == start);
		}

		if (obj) for (var i in obj) {
			this[i] = obj[i];
		}
	}

	this.container = function(id, start, obj) {
		containers[id] = [start, obj];
		if (loaded) {
			containers[id] = new containerClass(id, start, obj);
		}
	}

	this.$ = function(id) {
		if (components[id]) {
			return components[id];
		} else if (containers[id]) {
			return containers[id];
		} else {
			console.error("`"+id+"` not found");
		}
	}

	function parseHash(hash) {
		var q = {}, method;

		var n = hash.search(/#[!\?>]/);
		if (n > -1) {
			hash = hash.substring(n+2);
			method = hash.substring(1, 1);
		}

		var p = hash.split(/[&=]/);
		for (var i = 0; i < p.length; i+=2) q[p[i]] = (p[i+1] ? p[i+1] : null);
		return { q: q, m: method };
	}

	function onaction(ev) {
		var el = ev.target;
		if (!el || el.hasAttribute("target")) return;
		while (el && !el.hasAttribute("data-component") && el != document.body) el = el.parentNode;
		if (!el || el == document.body) {
			onFallbackAction(el);
			return;
		}
		var id = el.id;
		var target = ev.target;

		while (target.tagName != "A" && target.tagName != "AREA" && target.tagName != "FORM" && target != el) target = target.parentNode;
		if (target.tagName == "A" || target.tagName == "AREA") {
			sj.call(target.hash, target);
			ev.preventDefault();
		} else if (target.tagName == "FORM" && ev.type == 'submit') {
			var hash = target.action;
			var n = hash.search(/#[!\?]/);
			if (n > -1) hash = hash.substring(n);
			sj.call(hash, target);
			ev.preventDefault();
		} else {
			onFallbackAction(el, ev);
		}
	}

	this.call = function(query, element) {
		var params = {}, ps = query.substring(2).split(/[&=]/);
		for (var i = 0; i < ps.length; i+=2) params[ps[i]] = ps[i+1];
		params.mode = query.substring(0, 2);

		if (params.mode == "#?") {
			components[params.do].onrequest(params, element);
			sj.request(query, element);
		} else if (params.mode == "#!") {
			if (!params.action) params.action = "action";
			params.method = "internal"
			params.identry = params.method+"/"+params.action;
			params.params = {};
			onBeforeAction(params);
			var res = components[params.do].onaction(params, element);
			if (typeof res == "undefined" || res === false) {
				onDefaultAction(params);
			}
		}
	}

	this.request = function(query, form) {
		if (!endpoint) throw "No endpoint defined!";
		var xhr = new XMLHttpRequest();
		xhr.addEventListener("load", function(ev) {
			try {
				var json = JSON.parse(ev.target.responseText);
			} catch (e) {
				console.debug(ev.target.responseText);
				return;
			}
			if (!json.action) json.action = "action";
			if (!json.method) json.method = "internal";
			if (!json.do) json.do = json.component;
			json.identry = json.method+"/"+json.action;
			if (json.error) {
				components[json.component].onerror(json);
			} else if (json.component && components[json.component]) {
				onBeforeAction(json);
				var res = components[json.component].onaction(json);
				if (typeof res == "undefined" || res === false) {
					onDefaultAction(json);
				}
			} else {
				throw "Component `"+json.component+"` not found";
			}
			if (onRequestComplete) onRequestComplete();
			document.body.classList.remove("wait");
		}, false);
		xhr.addEventListener("error", function(ev) {
			onRequestError(ev);
			console.error(ev.message, ev);
		}, false);

		if (typeof query == "string") query = parseHash(query);
		if (onBeforeRequest) onBeforeRequest(query.q, form);
		var q = [];
		for (var i in query.q) q.push(i+"="+encodeURIComponent(query.q[i]));
		var url = endpoint+"?"+q.join("&");

		xhr.withCredentials = true;
		if (form && (form.tagName == "FORM" || form instanceof FormData)) {
			if (form instanceof FormData) {
				xhr.open('POST', url);
				xhr.send(form);
			} else if (form.method == "post") {
				form = new FormData(form);
				xhr.open('POST', url);
				xhr.send(form);
			} else {
				var p = [];
				for (var i = 0; i < form.elements.length; i++) {
					var el = form.elements[i];
					if (el.hasAttribute("name")) {
						switch (el.type) {
							case "select":
								p.push(el.name+"="+el.options[el.selectedIndex].value);
								break;
							case "checkbox":
								// TODO
								break;
							case "radio":
								// TODO
								break;
							default:
								p.push(el.name+"="+encodeURIComponent(el.value));
						}
					}
				}
				xhr.open('GET', url+"&"+p.join("&"));
				xhr.send();
			}
		} else {
			if (query.m == '>') {
				xhr.open('PUT', url);
			} else {
				xhr.open('GET', url);
			}
			xhr.send();
		}

		if (onRequestWait) onRequestWait();
	}

	var loaded = false;
	var endpoint = null;
	var components = {};
	var containers = {};

	// Called before request to server is executed. Useful to add common params or to log history
	var onBeforeRequest = function() {};
	// Called when request is executed. Useful to show spinner.
	var onRequestWait = function() {};
	// Called when request is completed. Useful to hide spinner.
	var onRequestComplete = function() {};

	// Called before the onAction slot is called. Useful to log history.
	var onBeforeAction = function() {};
	// Called when Component does not override his onAction slot.
	var onDefaultAction = function() {};
	// Called when no action Component is defined
	var onFallbackAction = function() {};
	// Called when Component does not override his onClick slot.
	var onClickCallback = function() {};
	// Called when Component does not override his onSubmit slot.
	var onSubmitCallback = function() {};
	// Called when Component does not override his onError slot.
	var onRequestError = function(json) { console.error(json) };

	document.addEventListener('DOMContentLoaded', function() {
		document.body.addEventListener("click", onaction, false);
		document.body.addEventListener("submit", onaction, false);

		loaded = true;
		for (var i in components) {
			sj.component(i, components[i]);
		}
		for (var i in containers) {
			sj.container(i, containers[i][0], containers[i][1]);
		}

		var event = document.createEvent('Event');
		event.initEvent('SjStarted', true, true);
		document.dispatchEvent(event);
	}, false);
};
<commit_msg>Loop must be always visible<commit_after>"use strict";

var sj = new function(endpoint) {

	// General endpoint for client-server interaction
	this.setEndpoint = function(url) { endpoint = url };
	this.setRequestWait = function(callback) { onRequestWait = callback };
	this.setRequestComplete = function(callback) { onRequestComplete = callback };
	this.setClickCallback = function(callback) { onClickCallback = callback };
	this.setRequestError = function(callback) { onRequestError = callback };
	this.setBeforeAction = function(callback) { onBeforeAction = callback };
	this.setDefaultAction = function(callback) { onDefaultAction = callback };
	this.setFallbackAction = function(callback) { onFallbackAction = callback };
	this.setBeforeRequest = function(callback) { onBeforeRequest = callback };

	// Render function
	// p = { k: { dataid: v } }
	function renderSingle(el, p, opt) {
		for (var k in p) {
			var a = p[k];
			if (typeof a == "string" || typeof a == "number") a = { _: a };
			else if (typeof a == "boolean") a = { hidden: !a };

			var list = k == "_" ? [el] : Array.from(el.querySelectorAll("[data-id="+k+"]"));
			if (!list.length) throw "Element `"+k+"` not found";

			list.forEach(function(l) {
				if (a instanceof Array) {
					renderArray(l, a, opt);
				} else if (a instanceof HTMLElement) {
					l.parentNode.replaceChild(a, l);
				} else {
					for (var i in a) {
						if (i == "_") {
							if (l.tagName == "INPUT" && (l.type == "radio" || l.type == "checkbox")) {
								l.checked = (l.value == a[i]);
							} else if (l.tagName == "INPUT" || l.tagName == "TEXTAREA") {
								l.value = a[i];
							} else if (l.tagName == "SELECT") {
								for (var j = 0; j < l.options.length; j++) l.options[j].selected = (l.options[j].value == a[i]);
							} else if (l.hasAttribute('data-html')) {
								l.innerHTML = a[i];
							} else {
								l.innerHTML = "";
								l.appendChild(document.createTextNode(a[i]));
							}
						} else if (i == "style") {
							for (var j in a[i]) l.style[j] = a[i][j];
						} else if (i == "data") {
							for (var j in a[i]) l.dataset[j] = a[i][j];
						} else if (i == "visible") {
							l.hidden = !a[i];
						} else if (i == "hidden") {
							l.hidden = a[i];
						} else if (i == "className") {
							l.className = a[i];
						} else if (i == "classList") {
							if (a[i] instanceof Array == false) a[i] = [a[i]];
							for (var j in a[i]) {
								if (!a[i][j]) continue;
								if (a[i][j][0] == "-") {
									l.classList.remove(a[i][j].substring(1));
								} else if (a[i][j][0] == "+") {
									l.classList.add(a[i][j].substring(1));
								} else {
									l.classList.toggle(a[i][j]);
								}
							}
						} else if (a[i] === false) {
							l.removeAttribute(i);
						} else if (a[i] === true) {
							l.setAttribute(i, "");
						} else {
							l.setAttribute(i, a[i]);
						}
					}
				}
			});
		}
	}

	function renderArray(el, p, opt) {
		if (!opt.append) while (!el.lastElementChild.hidden) el.removeChild(el.lastElementChild);
		el.hidden = false;
		p.forEach(function(i) {
			if (i instanceof HTMLElement) {
				el.appendChild(i);
			} else {
				var clone = el.firstElementChild.cloneNode(true);
				clone.hidden = false;
				renderSingle(clone, i, opt);
				el.appendChild(clone);
			}
		});
	}

	var componentClass = function(id, obj) {

		this.oncreate = function() {}
		this.onshow = function() {}
		this.onpostshow = function() {}
		this.onprehide = function() {}
		this.onhide = function() {}
		this.onclick = function(ev, target) { onClickCallback(ev, this.el, target) }
		this.onaction = function(action, target) {
			if (this[action.identry]) {
				this[action.identry](action, target, this);
				return true;
			} else {
				return onDefaultAction(action, target, this);
			}
		}
		this.onsubmit = function(ev, target) { onSubmitCallback(ev, this.el, target) }
		this.onrequest = function() {}
		this.onresponse = function() {}
		this.onerror = function(json) { onRequestError(json) }

		this.hide = function() {
			this.onprehide();
			this.el.hidden = true;
			this.onhide();
		}
		this.show = function() {
			this.onshow();
			this.el.hidden = false;
			this.onpostshow();
		}
		this.visible = function(b) {
			if (b) this.show(); else this.hide();
		}

		this.action = function(q) {
			sj.request(q);
		},

		this.render = function(p, opt) {
			if (!loaded || !p || typeof p != "object") return;
			if (!opt) opt = {};

			var el;
			if (!opt.sub) {
				el = this.el;
			} else if (typeof opt.sub == "string") {
				el = this.el.querySelector("[data-id="+opt.sub+"]");
			} else if (typeof opt.sub == "object") {
				var t = opt.sub;
				while (t != document.body && t != this.el) t = t.parentNode;
				if (t == this.el) {
					el = opt.sub;
				} else {
					throw "Element outside the Component";
				}
			}
			if (!el) throw "Root element not found";

			renderSingle(el, p, opt);

			if (this.onrender) this.onrender();
		}

		this.getElement = function(id) {
			return this.el.querySelector("[data-id="+id+"]");
		},

		this.id = id;
		this.el = document.getElementById(id);
		if (!this.el) throw "Component `"+id+"` not found";
		this.el.setAttribute("data-component", "");
		this.loop = this.el;

		for (var i in obj) {
			if (i == "loop") obj[i] = document.getElementById(obj[i]);
			this[i] = obj[i];
		}

	}

	this.component = function(id, obj) {
		components[id] = (obj ? obj : {});
		if (loaded) {
			components[id] = new componentClass(id, obj);
			components[id].oncreate();
		}
	}

	function containerClass(id, start, obj) {
		this.current = start;
		this.onChange = function(current) {}

		this.set = function(id) {
			this.current = id;
			for (var i = 0; i < this.el.children.length; i++) {
				var el = this.el.children[i];
				if (el.hasAttribute("data-component")) {
					sj.$(el.id).visible(el.id == id);
				}
			}
			this.onChange(this.current);
		}

		this.get = function() {
			return this.current;
		}

		this.el = document.getElementById(id);
		if (!this.el) throw "Container `"+id+"` not found";
		this.el.setAttribute("data-container", "");

		for (var i = 0; i < this.el.children.length; i++) {
			var el = this.el.children[i];
			sj.$(el.id).visible(el.id == start);
		}

		if (obj) for (var i in obj) {
			this[i] = obj[i];
		}
	}

	this.container = function(id, start, obj) {
		containers[id] = [start, obj];
		if (loaded) {
			containers[id] = new containerClass(id, start, obj);
		}
	}

	this.$ = function(id) {
		if (components[id]) {
			return components[id];
		} else if (containers[id]) {
			return containers[id];
		} else {
			console.error("`"+id+"` not found");
		}
	}

	function parseHash(hash) {
		var q = {}, method;

		var n = hash.search(/#[!\?>]/);
		if (n > -1) {
			hash = hash.substring(n+2);
			method = hash.substring(1, 1);
		}

		var p = hash.split(/[&=]/);
		for (var i = 0; i < p.length; i+=2) q[p[i]] = (p[i+1] ? p[i+1] : null);
		return { q: q, m: method };
	}

	function onaction(ev) {
		var el = ev.target;
		if (!el || el.hasAttribute("target")) return;
		while (el && !el.hasAttribute("data-component") && el != document.body) el = el.parentNode;
		if (!el || el == document.body) {
			onFallbackAction(el);
			return;
		}
		var id = el.id;
		var target = ev.target;

		while (target.tagName != "A" && target.tagName != "AREA" && target.tagName != "FORM" && target != el) target = target.parentNode;
		if (target.tagName == "A" || target.tagName == "AREA") {
			sj.call(target.hash, target);
			ev.preventDefault();
		} else if (target.tagName == "FORM" && ev.type == 'submit') {
			var hash = target.action;
			var n = hash.search(/#[!\?]/);
			if (n > -1) hash = hash.substring(n);
			sj.call(hash, target);
			ev.preventDefault();
		} else {
			onFallbackAction(el, ev);
		}
	}

	this.call = function(query, element) {
		var params = {}, ps = query.substring(2).split(/[&=]/);
		for (var i = 0; i < ps.length; i+=2) params[ps[i]] = ps[i+1];
		params.mode = query.substring(0, 2);

		if (params.mode == "#?") {
			components[params.do].onrequest(params, element);
			sj.request(query, element);
		} else if (params.mode == "#!") {
			if (!params.action) params.action = "action";
			params.method = "internal"
			params.identry = params.method+"/"+params.action;
			params.params = {};
			onBeforeAction(params);
			var res = components[params.do].onaction(params, element);
			if (typeof res == "undefined" || res === false) {
				onDefaultAction(params);
			}
		}
	}

	this.request = function(query, form) {
		if (!endpoint) throw "No endpoint defined!";
		var xhr = new XMLHttpRequest();
		xhr.addEventListener("load", function(ev) {
			try {
				var json = JSON.parse(ev.target.responseText);
			} catch (e) {
				console.debug(ev.target.responseText);
				return;
			}
			if (!json.action) json.action = "action";
			if (!json.method) json.method = "internal";
			if (!json.do) json.do = json.component;
			json.identry = json.method+"/"+json.action;
			if (json.error) {
				components[json.component].onerror(json);
			} else if (json.component && components[json.component]) {
				onBeforeAction(json);
				var res = components[json.component].onaction(json);
				if (typeof res == "undefined" || res === false) {
					onDefaultAction(json);
				}
			} else {
				throw "Component `"+json.component+"` not found";
			}
			if (onRequestComplete) onRequestComplete();
			document.body.classList.remove("wait");
		}, false);
		xhr.addEventListener("error", function(ev) {
			onRequestError(ev);
			console.error(ev.message, ev);
		}, false);

		if (typeof query == "string") query = parseHash(query);
		if (onBeforeRequest) onBeforeRequest(query.q, form);
		var q = [];
		for (var i in query.q) q.push(i+"="+encodeURIComponent(query.q[i]));
		var url = endpoint+"?"+q.join("&");

		xhr.withCredentials = true;
		if (form && (form.tagName == "FORM" || form instanceof FormData)) {
			if (form instanceof FormData) {
				xhr.open('POST', url);
				xhr.send(form);
			} else if (form.method == "post") {
				form = new FormData(form);
				xhr.open('POST', url);
				xhr.send(form);
			} else {
				var p = [];
				for (var i = 0; i < form.elements.length; i++) {
					var el = form.elements[i];
					if (el.hasAttribute("name")) {
						switch (el.type) {
							case "select":
								p.push(el.name+"="+el.options[el.selectedIndex].value);
								break;
							case "checkbox":
								// TODO
								break;
							case "radio":
								// TODO
								break;
							default:
								p.push(el.name+"="+encodeURIComponent(el.value));
						}
					}
				}
				xhr.open('GET', url+"&"+p.join("&"));
				xhr.send();
			}
		} else {
			if (query.m == '>') {
				xhr.open('PUT', url);
			} else {
				xhr.open('GET', url);
			}
			xhr.send();
		}

		if (onRequestWait) onRequestWait();
	}

	var loaded = false;
	var endpoint = null;
	var components = {};
	var containers = {};

	// Called before request to server is executed. Useful to add common params or to log history
	var onBeforeRequest = function() {};
	// Called when request is executed. Useful to show spinner.
	var onRequestWait = function() {};
	// Called when request is completed. Useful to hide spinner.
	var onRequestComplete = function() {};

	// Called before the onAction slot is called. Useful to log history.
	var onBeforeAction = function() {};
	// Called when Component does not override his onAction slot.
	var onDefaultAction = function() {};
	// Called when no action Component is defined
	var onFallbackAction = function() {};
	// Called when Component does not override his onClick slot.
	var onClickCallback = function() {};
	// Called when Component does not override his onSubmit slot.
	var onSubmitCallback = function() {};
	// Called when Component does not override his onError slot.
	var onRequestError = function(json) { console.error(json) };

	document.addEventListener('DOMContentLoaded', function() {
		document.body.addEventListener("click", onaction, false);
		document.body.addEventListener("submit", onaction, false);

		loaded = true;
		for (var i in components) {
			sj.component(i, components[i]);
		}
		for (var i in containers) {
			sj.container(i, containers[i][0], containers[i][1]);
		}

		var event = document.createEvent('Event');
		event.initEvent('SjStarted', true, true);
		document.dispatchEvent(event);
	}, false);
};
<|endoftext|>


<commit_before>/**
 * WordPress dependencies
 */
import { activatePlugin, visitAdminPage } from '@wordpress/e2e-test-utils';

/**
 * Internal dependencies
 */
import {
	deactivateAllOtherPlugins,
	resetSiteKit,
	setAnalyticsExistingPropertyId,
	setAuthToken,
	setClientConfig,
	setSearchConsoleProperty,
	setSiteVerification,
	useRequestInterception,
} from '../../../utils';

async function proceedToSetUpAnalytics() {
	await Promise.all( [
		expect( page ).toClick( '.googlesitekit-cta-link', { text: /set up analytics/i } ),
		page.waitForSelector( '.googlesitekit-setup-module--analytics' ),
		page.waitForResponse( ( res ) => res.url().match( 'analytics/data' ) ),
	] );
}

const EXISTING_PROPERTY_ID = 'UA-00000001-1';
const EXISTING_ACCOUNT_ID = '100';

let getAccountsRequestHandler;
let tagPermissionRequestHandler;

describe( 'setting up the Analytics module with an existing account and existing tag', () => {
	beforeAll( async () => {
		await page.setRequestInterception( true );
		useRequestInterception( ( request ) => {
			if ( request.url().match( 'modules/analytics/data/accounts-properties-profiles' ) && getAccountsRequestHandler ) {
				getAccountsRequestHandler( request );
			} else if ( request.url().match( 'modules/analytics/data/tag-permission' ) && tagPermissionRequestHandler ) {
				tagPermissionRequestHandler( request );
			} else if ( request.url().match( '/wp-json/google-site-kit/v1/data/' ) ) {
				request.respond( {
					status: 200,
				} );
			}

			if ( ! request._interceptionHandled ) {
				request.continue();
			}
		} );
	} );

	beforeEach( async () => {
		await activatePlugin( 'e2e-tests-auth-plugin' );
		await activatePlugin( 'e2e-tests-analytics-existing-tag' );
		await activatePlugin( 'e2e-tests-module-setup-analytics-api-mock' );

		await setClientConfig();
		await setAuthToken();
		await setSiteVerification();
		await setSearchConsoleProperty();

		await visitAdminPage( 'admin.php', 'page=googlesitekit-settings' );
		await page.waitForSelector( '.mdc-tab-bar' );
		await expect( page ).toClick( '.mdc-tab', { text: /connect more services/i } );
		await page.waitForSelector( '.googlesitekit-settings-connect-module--analytics' );
	} );

	afterEach( async () => {
		await deactivateAllOtherPlugins();
		await resetSiteKit();
	} );

	it( 'pre-selects account and property if an existing tag is found that matches one belonging to the user and prevents them from being changed', async () => {
		tagPermissionRequestHandler = ( request ) => {
			request.respond( {
				status: 200,
				body: JSON.stringify( {
					accountId: EXISTING_ACCOUNT_ID,
					propertyId: EXISTING_PROPERTY_ID,
				} ),
			} );
		};
		await setAnalyticsExistingPropertyId( EXISTING_PROPERTY_ID );
		await proceedToSetUpAnalytics();

		await expect( page ).toMatchElement( '.googlesitekit-setup-module--analytics p', { text: new RegExp( `An existing analytics tag was found on your site with the id ${ EXISTING_PROPERTY_ID }`, 'i' ) } );

		await expect( page ).toMatchElement( '.mdc-select--disabled .mdc-select__selected-text', { text: /test account a/i } );
		await expect( page ).toMatchElement( '.mdc-select--disabled .mdc-select__selected-text', { text: /test property x/i } );
		await expect( page ).toMatchElement( '.mdc-select:not(.mdc-select--disabled) .mdc-select__selected-text', { text: /test profile x/i } );

		// Ensure that Views dropdown is not disabled
		await expect( page ).toClick( '.mdc-select', { text: /test profile x/i } );
		await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test profile x/i } );

		await Promise.all( [
			expect( page ).toClick( 'button', { text: /configure analytics/i } ),
			page.waitForSelector( '.googlesitekit-publisher-win__title' ),
		] );

		await expect( page ).toMatchElement( '.googlesitekit-publisher-win__title', { text: /Congrats on completing the setup for Analytics!/i } );
	} );

	it( 'does not allow Analytics to be set up with an existing tag that does not match a property of the user', async () => {
		getAccountsRequestHandler = ( request ) => {
			request.respond( {
				status: 500,
				body: JSON.stringify( {
					code: 'google_analytics_existing_tag_permission',
					message: 'google_analytics_existing_tag_permission',
				} ),
			} );
		};

		await proceedToSetUpAnalytics();

		await expect( page ).toMatchElement( '.googlesitekit-setup-module--analytics p', { text: /google_analytics_existing_tag_permission/i } );
		await expect( page ).not.toMatchElement( '.googlesitekit-setup-module--analytics button', { text: /create an account/i } );
		await expect( page ).not.toMatchElement( '.googlesitekit-setup-module--analytics button', { text: /re-fetch my account/i } );
	} );
} );
<commit_msg>update analytics setup test for stability<commit_after>/**
 * WordPress dependencies
 */
import { activatePlugin, visitAdminPage } from '@wordpress/e2e-test-utils';

/**
 * Internal dependencies
 */
import {
	deactivateAllOtherPlugins,
	resetSiteKit,
	setAnalyticsExistingPropertyId,
	setAuthToken,
	setClientConfig,
	setSearchConsoleProperty,
	setSiteVerification,
	useRequestInterception,
} from '../../../utils';

async function proceedToSetUpAnalytics() {
	await Promise.all( [
		expect( page ).toClick( '.googlesitekit-cta-link', { text: /set up analytics/i } ),
		page.waitForSelector( '.googlesitekit-setup-module--analytics' ),
		page.waitForResponse( ( res ) => res.url().match( 'analytics/data' ) ),
	] );
}

const EXISTING_PROPERTY_ID = 'UA-00000001-1';
const EXISTING_ACCOUNT_ID = '100';

let getAccountsRequestHandler;
let tagPermissionRequestHandler;

describe( 'setting up the Analytics module with an existing account and existing tag', () => {
	beforeAll( async () => {
		await page.setRequestInterception( true );
		useRequestInterception( ( request ) => {
			if ( request.url().match( 'modules/analytics/data/accounts-properties-profiles' ) && getAccountsRequestHandler ) {
				getAccountsRequestHandler( request );
			} else if ( request.url().match( 'modules/analytics/data/tag-permission' ) && tagPermissionRequestHandler ) {
				tagPermissionRequestHandler( request );
			} else if ( request.url().match( '/wp-json/google-site-kit/v1/data/' ) ) {
				request.respond( {
					status: 200,
				} );
			}

			if ( ! request._interceptionHandled ) {
				request.continue();
			}
		} );
	} );

	beforeEach( async () => {
		await activatePlugin( 'e2e-tests-auth-plugin' );
		await activatePlugin( 'e2e-tests-analytics-existing-tag' );
		await activatePlugin( 'e2e-tests-module-setup-analytics-api-mock' );

		await setClientConfig();
		await setAuthToken();
		await setSiteVerification();
		await setSearchConsoleProperty();

		await visitAdminPage( 'admin.php', 'page=googlesitekit-settings' );
		await page.waitForSelector( '.mdc-tab-bar' );
		await expect( page ).toClick( '.mdc-tab', { text: /connect more services/i } );
		await page.waitForSelector( '.googlesitekit-settings-connect-module--analytics' );
	} );

	afterEach( async () => {
		await deactivateAllOtherPlugins();
		await resetSiteKit();
	} );

	it( 'pre-selects account and property if an existing tag is found that matches one belonging to the user and prevents them from being changed', async () => {
		tagPermissionRequestHandler = ( request ) => {
			request.respond( {
				status: 200,
				body: JSON.stringify( {
					accountId: EXISTING_ACCOUNT_ID,
					propertyId: EXISTING_PROPERTY_ID,
				} ),
			} );
		};
		await setAnalyticsExistingPropertyId( EXISTING_PROPERTY_ID );
		await proceedToSetUpAnalytics();

		await page.waitForResponse( ( res ) => res.url().match( 'modules/analytics/data/accounts-properties-profiles' ) );
		await expect( page ).toMatchElement( '.googlesitekit-setup-module--analytics p', { text: new RegExp( `An existing analytics tag was found on your site with the id ${ EXISTING_PROPERTY_ID }`, 'i' ) } );

		await expect( page ).toMatchElement( '.mdc-select--disabled .mdc-select__selected-text', { text: /test account a/i } );
		await expect( page ).toMatchElement( '.mdc-select--disabled .mdc-select__selected-text', { text: /test property x/i } );
		await expect( page ).toMatchElement( '.mdc-select:not(.mdc-select--disabled) .mdc-select__selected-text', { text: /test profile x/i } );

		// Ensure that Views dropdown is not disabled
		await expect( page ).toClick( '.mdc-select', { text: /test profile x/i } );
		await expect( page ).toClick( '.mdc-menu-surface--open .mdc-list-item', { text: /test profile x/i } );

		await Promise.all( [
			expect( page ).toClick( 'button', { text: /configure analytics/i } ),
			page.waitForSelector( '.googlesitekit-publisher-win__title' ),
		] );

		await expect( page ).toMatchElement( '.googlesitekit-publisher-win__title', { text: /Congrats on completing the setup for Analytics!/i } );
	} );

	it( 'does not allow Analytics to be set up with an existing tag that does not match a property of the user', async () => {
		getAccountsRequestHandler = ( request ) => {
			request.respond( {
				status: 500,
				body: JSON.stringify( {
					code: 'google_analytics_existing_tag_permission',
					message: 'google_analytics_existing_tag_permission',
				} ),
			} );
		};

		await proceedToSetUpAnalytics();

		await expect( page ).toMatchElement( '.googlesitekit-setup-module--analytics p', { text: /google_analytics_existing_tag_permission/i } );
		await expect( page ).not.toMatchElement( '.googlesitekit-setup-module--analytics button', { text: /create an account/i } );
		await expect( page ).not.toMatchElement( '.googlesitekit-setup-module--analytics button', { text: /re-fetch my account/i } );
	} );
} );
<|endoftext|>


<commit_before>var system = require('system');
if (system.args.length != 3) {
  console.log("USAGE: <cmd> <source> <dest>" + system.args.length);
  phantom.exit(1);
}

// Load the GoogleCodeWikiParser.js.
phantom.injectJs('./GoogleCodeWikiParser.js');
var parser = new GoogleCodeWikiParser();

// Variables for managing the FileSystem operations.
var fs = require('fs'),
source_path, source_fp,
destination_path, destination_fp,
source_content, destination_content,
pre_lang = 'php';

// Handle the arguments.
source_path = system.args[1];
destination_path = system.args[2];

try {
    source_fp = fs.open(source_path, "r");
    source_content = source_fp.read();
    source_content = source_content.replace(/\n==/g, "\n\n==");
    source_content = source_content.replace(/http:\/\/code.google.com\/p\/[^\/]+\/wiki\/([^ ]+)/g, '$1.md');
    destination_content = parser.parse(source_content);
//    destination_content = destination_content.replace(/\n==(.*)==\n/, "\n$1\n======\n");
    destination_fp = fs.open(destination_path, "w");
    destination_fp.write(destination_content);
} catch (e) {
    console.log(e);
}
if (source_fp) {
  source_fp.close();
}
if (destination_fp) {
  destination_fp.close();
}
phantom.exit();
<commit_msg>Removed disabled code.<commit_after>var system = require('system');
if (system.args.length != 3) {
  console.log("USAGE: <cmd> <source> <dest>" + system.args.length);
  phantom.exit(1);
}

// Load the GoogleCodeWikiParser.js.
phantom.injectJs('./GoogleCodeWikiParser.js');
var parser = new GoogleCodeWikiParser();

// Variables for managing the FileSystem operations.
var fs = require('fs'),
source_path, source_fp,
destination_path, destination_fp,
source_content, destination_content,
pre_lang = 'php';

// Handle the arguments.
source_path = system.args[1];
destination_path = system.args[2];

try {
    source_fp = fs.open(source_path, "r");
    source_content = source_fp.read();
    source_content = source_content.replace(/\n==/g, "\n\n==");
    source_content = source_content.replace(/http:\/\/code.google.com\/p\/[^\/]+\/wiki\/([^ ]+)/g, '$1.md');
    destination_content = parser.parse(source_content);
    destination_fp = fs.open(destination_path, "w");
    destination_fp.write(destination_content);
} catch (e) {
    console.log(e);
}
if (source_fp) {
  source_fp.close();
}
if (destination_fp) {
  destination_fp.close();
}
phantom.exit();
<|endoftext|>


<commit_before>import {extname, dirname, relative, resolve, sep} from 'path';
import {stat} from 'mz/fs';
import throat from 'throat';
import {debuglog} from 'util';

import readTree from '../filesystem/read-tree';

export default async function getArtifactMtimes(search, patterns) {
	const debug = debuglog('artifact-mtimes');
	const distributionDirectory = resolve(search);

	const types = Object.keys(patterns.formats)
		.map(extension => patterns.formats[extension].name);

	const typedFiles = await Promise.all([...new Set(types)].map(async type => {
		const files = await readTree(resolve(search, type));
		return files.filter(path => extname(path));
	}));

	const artifactPaths = typedFiles
		.reduce((flattened, files) => [...flattened, ...files], []);

	const artifactMtimes = await Promise.all(artifactPaths
		.map(throat(1, async path => {
			const relativeArtifactPath = relative(distributionDirectory, path);
			const artifactId = dirname(relativeArtifactPath.split(sep).join('/'));
			const patternId = artifactId.split('/').slice(1).join('/');
			const stats = await stat(path);

			return {
				id: artifactId,
				path,
				patternId,
				mtime: stats.mtime
			};
		})));

	const artifactRegistry = artifactMtimes.reduce((registry, artifact) => {
		const item = registry[artifact.patternId] || {
			id: artifact.patternId,
			artifacts: [],
			files: [],
			mtimes: [],
			types: []
		};

		item.artifacts.push(artifact.id);
		item.files.push(artifact.path);
		item.mtimes.push(artifact.mtime);
		item.types.push(artifact.id.split('/')[0]);
		registry[artifact.patternId] = item;
		return registry;
	}, {});

	return Object.values(artifactRegistry).map(item => {
		const times = item.mtimes.map(time => {
			return {
				stamp: time.getTime(),
				date: time
			};
		}).sort((a, b) => a.stamp - b.stamp);

		item.mtime = times[0].date;
		debug('mtime for artifact %s is %s', item.id, item.mtime);
		return item;
	});
}
<commit_msg>chore: simplify linked development by resolving from cwd<commit_after>import {extname, dirname, relative, resolve, sep} from 'path';
import {stat} from 'mz/fs';
import throat from 'throat';
import {debuglog} from 'util';

import readTree from '../filesystem/read-tree';

export default async function getArtifactMtimes(search, patterns) {
	const debug = debuglog('artifact-mtimes');
	const distributionDirectory = resolve(process.cwd(), search);

	const types = Object.keys(patterns.formats)
		.map(extension => patterns.formats[extension].name);

	const typedFiles = await Promise.all([...new Set(types)].map(async type => {
		const files = await readTree(resolve(search, type));
		return files.filter(path => extname(path));
	}));

	const artifactPaths = typedFiles
		.reduce((flattened, files) => [...flattened, ...files], []);

	const artifactMtimes = await Promise.all(artifactPaths
		.map(throat(1, async path => {
			const relativeArtifactPath = relative(distributionDirectory, path);
			const artifactId = dirname(relativeArtifactPath.split(sep).join('/'));
			const patternId = artifactId.split('/').slice(1).join('/');
			const stats = await stat(path);

			return {
				id: artifactId,
				path,
				patternId,
				mtime: stats.mtime
			};
		})));

	const artifactRegistry = artifactMtimes.reduce((registry, artifact) => {
		const item = registry[artifact.patternId] || {
			id: artifact.patternId,
			artifacts: [],
			files: [],
			mtimes: [],
			types: []
		};

		item.artifacts.push(artifact.id);
		item.files.push(artifact.path);
		item.mtimes.push(artifact.mtime);
		item.types.push(artifact.id.split('/')[0]);
		registry[artifact.patternId] = item;
		return registry;
	}, {});

	return Object.values(artifactRegistry).map(item => {
		const times = item.mtimes.map(time => {
			return {
				stamp: time.getTime(),
				date: time
			};
		}).sort((a, b) => a.stamp - b.stamp);

		item.mtime = times[0].date;
		debug('mtime for artifact %s is %s', item.id, item.mtime);
		return item;
	});
}
<|endoftext|>


<commit_before>const refresh = require('./lib/refresh');
const bot = require('./bot.js');
const settings = require('./../settings.json');
const modules = require('./modules.js');
const Message = require('./../orm/Message')
const commands = require('./commands');
const request = require('request-promise-native');
const influx = require('./../influx');

let lock = false;
let ready = false;
bot.on('error', (err) => {
    /**
     * Catch errors here
     */
    console.log("Stack Trace: " + err.stack);
})
process.on('unhandledRejection', (err) => {
    console.log("UNHANDLED REJECTION AT " + err.stack);
    if (err.toString().includes('Request to use token, but token was unavailable to the client'))
        process.exit();//restart
});
process.on('uncaughtException', (err) => console.log("UNHANDLED EXCEPTION AT " + err.stack));
bot.on('message', async function (message) {
    /**
     * if locked, reject everything except dm
     */
    new Message({
        messageID: message.id,
        channel: message.channel.id
    }).save();
    if (lock) {
        if (!settings.owners.includes(message.author.id))
            //  if (message.channel.guild)
            return;//not DM
    }
    /**
     * Listen to messages and convert into params
     */
    if (message.member && message.member != null) {
        let muted = message.member.roles.find(function (r) {
            if (r.name.toLowerCase().includes('mute') && !r.name.toLowerCase().includes('non') && !r.name.toLowerCase().includes('test')) return r
        })
        if (muted && message.deletable )
            message.delete();
    }

    if (message.author.bot) return;

    if (message.content.startsWith(settings.identifier)) {
        /**Extracting params */
        let params = message.content.substring(settings.identifier.length).trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift().trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else {
        //ignore because normal message
    }
});
bot.on('lock', () => { lock = true; });
bot.on('unlock', () => { lock = false; });
bot.on("guildMemberAdd", async function (member) {
    var user = member.user;
    if (member.guild.id === "184536578654339072") {
        if (member.user.bot) return console.log(member.user.tag + " is a bot who joined " + member.guild.name)
        if (refresh(user, true)) {
            user.send("Welcome to the Revive Network\nBecome a verified member and get exclusive benefits by linking your discord account with your Revive account\nTo link, please follow this link\nhttps://battlelog.co/discord_link.php");
        }
    }
});
bot.on("guildMemberRemove", async function (member) {
    var user = member.user;
});
/**
bot.on('disconnect', function(event) {
    if (event.code === 0) return console.error(event);
    process.exit();//force restart
});*/

bot.on('ready', async function () {
    console.log("ReviveBot Ready");
    let dbs = await influx.getDatabaseNames();
    console.log(dbs);
    if (!dbs || dbs === null)
        console.log("Cant connect to influx")
    if (!dbs.includes('discord')) {
        console.log("Creating Dicord DB");
    }
    ready = true;
});
bot.on("guildMemberUpdate", async function (member, newMem) {
    let user = member.user;
    if (member.guild && (member.guild.id === "184536578654339072")) {
        let oldMem = member;
        if (!oldMem.roles.has("273105185566359562") && newMem.roles.has("273105185566359562")) return;
        if (!oldMem.roles.has("275317218911322112") && newMem.roles.has("275317218911322112")) return;
        if ((!oldMem.roles.has("184684916833779712") && newMem.roles.has("184684916833779712")) || (!oldMem.roles.has("200849956796497920") && newMem.roles.has("200849956796497920")) || (!oldMem.roles.has("184676864630063104") && newMem.roles.has("184676864630063104")) || (!oldMem.roles.has("286646245198528523") && newMem.roles.has("286646245198528523"))) {
            await request({ uri: 'http://localhost/v0/discord/reverse_link/' + user.id, method: "POST" });
        }
    }
});
setInterval(async function () {
    if (!ready) return;
    const guild = bot.guilds.get("184536578654339072");
    influx.writePoints([
        {
            measurement: 'statistics',
            fields: { count: guild.memberCount },
            tags: { type: 'members' }
        }
    ]).catch(console.log);
    let count = await Message.count();
    if (count)
        influx.writePoints([
            {
                measurement: 'statistics',
                fields: { count: count },
                tags: { type: 'messages' }
            }
        ]).catch(console.log);
    guild.roles.map(r => {
        influx.writePoints([
            {
                measurement: 'statistics',
                fields: { count: r.members.size },
                tags: { type: r.id }
            }
        ]).catch(console.log);
    });
    influx.writePoints([
        {
            measurement: 'statistics',
            fields: { count: guild.presences.map(p => p.status != 'offline').length },
            tags: { type: "online" }
        }
    ]).catch(console.log);
}, 1000)
<commit_msg>Update listen.js<commit_after>const refresh = require('./lib/refresh');
const bot = require('./bot.js');
const settings = require('./../settings.json');
const modules = require('./modules.js');
const Message = require('./../orm/Message')
const commands = require('./commands');
const request = require('request-promise-native');
const influx = require('./../influx');

let lock = false;
let ready = false;
bot.on('error', (err) => {
    /**
     * Catch errors here
     */
    console.log("Stack Trace: " + err.stack);
})
process.on('unhandledRejection', (err) => {
    console.log("UNHANDLED REJECTION AT " + err.stack);
    if (err.toString().includes('Request to use token, but token was unavailable to the client'))
        process.exit();//restart
});
process.on('uncaughtException', (err) => console.log("UNHANDLED EXCEPTION AT " + err.stack));
bot.on('message', async function (message) {
    /**
     * if locked, reject everything except dm
     */
    new Message({
        messageID: message.id,
        channel: message.channel.id
    }).save();
    if (lock) {
        if (!settings.owners.includes(message.author.id))
            //  if (message.channel.guild)
            return;//not DM
    }
    /**
     * Listen to messages and convert into params
     */
    if (message.member && message.member != null) {
        let muted = message.member.roles.find(function (r) {
            if (r.name.toLowerCase().includes('mute') && !r.name.toLowerCase().includes('non') && !r.name.toLowerCase().includes('test')) return r
        })
        if (muted && message.deletable )
            message.delete();
    }

    if (message.author.bot) return;

    if (message.content.startsWith(settings.identifier)) {
        /**Extracting params */
        let params = message.content.substring(settings.identifier.length).trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift().trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else {
        //ignore because normal message
    }
});
bot.on('lock', () => { lock = true; });
bot.on('unlock', () => { lock = false; });
bot.on("guildMemberAdd", async function (member) {
    var user = member.user;
    if (member.guild.id === "184536578654339072") {
        if (member.user.bot) return console.log(member.user.tag + " is a bot who joined " + member.guild.name)
        if (refresh(user, true)) {
            user.send("Welcome to the Revive Network\nBecome a verified member and get exclusive benefits by linking your discord account with your Revive account\nTo link, please follow this link\nhttps://battlelog.co/discord_link.php");
        }
    }
});
bot.on("guildMemberRemove", async function (member) {
    var user = member.user;
});
/**
bot.on('disconnect', function(event) {
    if (event.code === 0) return console.error(event);
    process.exit();//force restart
});*/

bot.on('ready', async function () {
    console.log("ReviveBot Ready");
    console.log(process.versions);
    let dbs = await influx.getDatabaseNames();
    console.log(dbs);
    if (!dbs || dbs === null)
        console.log("Cant connect to influx")
    if (!dbs.includes('discord')) {
        console.log("Creating Dicord DB");
    }
    ready = true;
});
bot.on("guildMemberUpdate", async function (member, newMem) {
    let user = member.user;
    if (member.guild && (member.guild.id === "184536578654339072")) {
        let oldMem = member;
        if (!oldMem.roles.has("273105185566359562") && newMem.roles.has("273105185566359562")) return;
        if (!oldMem.roles.has("275317218911322112") && newMem.roles.has("275317218911322112")) return;
        if ((!oldMem.roles.has("184684916833779712") && newMem.roles.has("184684916833779712")) || (!oldMem.roles.has("200849956796497920") && newMem.roles.has("200849956796497920")) || (!oldMem.roles.has("184676864630063104") && newMem.roles.has("184676864630063104")) || (!oldMem.roles.has("286646245198528523") && newMem.roles.has("286646245198528523"))) {
            await request({ uri: 'http://localhost/v0/discord/reverse_link/' + user.id, method: "POST" });
        }
    }
});
setInterval(async function () {
    if (!ready) return;
    const guild = bot.guilds.get("184536578654339072");
    influx.writePoints([
        {
            measurement: 'statistics',
            fields: { count: guild.memberCount },
            tags: { type: 'members' }
        }
    ]).catch(console.log);
    let count = await Message.count();
    if (count)
        influx.writePoints([
            {
                measurement: 'statistics',
                fields: { count: count },
                tags: { type: 'messages' }
            }
        ]).catch(console.log);
    guild.roles.map(r => {
        influx.writePoints([
            {
                measurement: 'statistics',
                fields: { count: r.members.size },
                tags: { type: r.id }
            }
        ]).catch(console.log);
    });
    influx.writePoints([
        {
            measurement: 'statistics',
            fields: { count: guild.presences.map(p => p.status != 'offline').length },
            tags: { type: "online" }
        }
    ]).catch(console.log);
}, 1000)
<|endoftext|>


<commit_before>
namespace('env', function () {
  task('init', ['model', 'controller', 'app'], function () {
    jake.addListener('complete', function (e) {
      jake.Task['env:cleanup'].invoke();
    });
  });

  task('config', function () {
    var cfg = {};
    if (process.env.environment) {
      cfg.environment = process.env.environment;
    }
    geddy.config = require('../../lib/config').readConfig(cfg);
  });

  task('model', ['config'], function () {
    geddy.model = require('model');
  });

  task('controller', ['config'], function () {
    geddy.controller = require('../../lib/controller');
  });

  task('app', ['config'], {async: true}, function () {
    var opts = {
          initItems: [
            'model'
          , 'controller'
          , 'router'
          , 'i18n'
          , 'mailer'
          , 'localAppInit'
          ]
        };
    require('../../lib/init').init(geddy, opts, function () {
      complete();
    });
  });

  task('cleanup', {async: true}, function () {
    // Disconnect all the adapters
    var adapters = geddy.model.loadedAdapters
      , adapter
      , keys = Object.keys(adapters)
      , doIt = function () {
          var key;
          if ((key = keys.shift())) {
            adapter = adapters[key];
            // Try to disconnect nicely
            if (typeof adapter.disconnect == 'function') {
              // If there's a disconnect error, don't flip out about it
              adapter.on('error', function () {});
              adapter.disconnect(function () {
                doIt();
              });
            }
          }
          else {
            complete();
          }
        };
    doIt();
  });

});

<commit_msg>Issue #587 Don't need to add a bunch of no-op error handlers to the same adapter<commit_after>
namespace('env', function () {
  task('init', ['model', 'controller', 'app'], function () {
    jake.addListener('complete', function (e) {
      jake.Task['env:cleanup'].invoke();
    });
  });

  task('config', function () {
    var cfg = {};
    if (process.env.environment) {
      cfg.environment = process.env.environment;
    }
    geddy.config = require('../../lib/config').readConfig(cfg);
  });

  task('model', ['config'], function () {
    geddy.model = require('model');
  });

  task('controller', ['config'], function () {
    geddy.controller = require('../../lib/controller');
  });

  task('app', ['config'], {async: true}, function () {
    var opts = {
          initItems: [
            'model'
          , 'controller'
          , 'router'
          , 'i18n'
          , 'mailer'
          , 'localAppInit'
          ]
        };
    require('../../lib/init').init(geddy, opts, function () {
      complete();
    });
  });

  task('cleanup', {async: true}, function () {
    // Disconnect all the adapters
    var adapters = geddy.model.loadedAdapters
      , adapter
      , keys = Object.keys(adapters)
      , doIt = function () {
          var key;
          if ((key = keys.shift())) {
            adapter = adapters[key];
            // Try to disconnect nicely
            if (typeof adapter.disconnect == 'function') {
              // If there's a disconnect error, don't flip out about it
              if (!adapter.listeners('error').length) {
                adapter.on('error', function () {});
              }
              adapter.disconnect(function () {
                doIt();
              });
            }
          }
          else {
            complete();
          }
        };
    doIt();
  });

});

<|endoftext|>


<commit_before>function getLatestTimestamp(metricSnaps) {
    var latestTs = "1999-01-01T00:00:00.000000";
    for (ts in metricSnaps) {
        if (ts > latestTs) {
            latestTs = ts
        }
    }
    return latestTs
}

function sortByMetricValueDesc(metric1, metric2){
  if (metric1.value < metric2.value)
     return 1;
  if (metric1.value > metric2.value)
    return -1;
  return 0;
}

function renderItem(item){
    item.metricsArr = [];
    for (metricName in item.metrics){
        thisMetric = item.metrics[metricName];
        thisMetric.name = metricName;
        var latestTs = getLatestTimestamp(item.metrics[metricName].values);
        if (latestTs) {
            var latestVal = item.metrics[metricName].values[latestTs];
            thisMetric.ts = latestTs;
            thisMetric.value = latestVal
        }

        // if no values, no point in printing
        if (thisMetric.value) {
            item.metricsArr.push(thisMetric);
        }
    }

    item.metricsArr.sort(sortByMetricValueDesc);

    if (typeof ich.itemtemplate == "undefined"){
        ich.addTemplate("itemtemplate", '
\r\n
<\/div>\r\n
{{#metricsArr}}\r\n
\r\n      \r\n        {{ ts }}<\/span>\r\n        {{ value }}<\/span>\r\n        \r\n          \r\n          {{ static_meta.provider }} {{ static_meta.display_name }}<\/span>\r\n        <\/span>\r\n      <\/a>\r\n    <\/li>\r\n    {{\/metricsArr}}\r\n  <\/ul>\r\n<\/div>')
    }

    return ich.itemtemplate(item);
}

function addDataToPage(data) {
    $("#total-impact div#ti-data").empty();
    $("#total-impact div#ti-data").append(renderItem(data));
}

function getNewItemAndUpdateReport(tiid, interval) {

    $.ajax({
        url: 'http://api.total-impact.org/item/'+tiid,
        type: "GET",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        statusCode: {
            210: function(data){
                console.log("still updating")
                addDataToPage(data)
                setTimeout(function(){
                    getNewItemsAndUpdateReport(interval)
                })
            },
            200: function(data) {
                console.log("done with updating")
                addDataToPage(data)
                return false;
            }
        }
    });
}

function getAlias(id_string) {
   // split the user-supplied alias string into namespace and id parts
    var alias = []
    if (id_string.indexOf(":") > 0) {
        alias[0] = id_string.split(':')[0]; // namespace
        alias[1] = id_string.substr(alias[0].length + 1); // id

        // handle urls:
        if (alias[0] == "http"){
            alias[0] = "url";
            alias[1] = id_string
        }
    }
    return alias
}

// Based on http://drnicwilliams.com/2006/11/21/diy-widgets/
function requestStylesheet(stylesheet_url) {
    var stylesheet = document.createElement("link");
    stylesheet.rel = "stylesheet";
    stylesheet.type = "text/css";
    stylesheet.href = stylesheet_url;
    stylesheet.media = "all";
    document.lastChild.firstChild.appendChild(stylesheet);
}

// Based on http://drnicwilliams.com/2006/11/21/diy-widgets/
function requestScript(script_url) {
    var script = document.createElement('script');
    script.src = script_url;
    // IE7 doesn't like this: document.body.appendChild(script);
    // Instead use:
    document.getElementsByTagName('head')[0].appendChild(script);
}

$.ajaxSetup ({
    cache: false
});
var tiids = []
var ajax_load = '';

$(document).ready(function(){
    //requestStylesheet("http://total-impact-webapp.herokuapp.com/static/embed.css")
    //requestScript("http://total-impact-webapp.herokuapp.com/static/js/icanhaz.min.js")

    $("span#ti-id").hide()
    $("#total-impact div#ti-data").html(ajax_load+" Loading...")
    var alias = getAlias($("span#ti-id").html());

    console.log("creating new item")
    $.ajax({
        url: "http://api.total-impact.org/item/"+alias[0]+"/"+alias[1],
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(alias),
        success: function(returnedTiid){
            // make a new collection, populated by our freshly-minted tiids
            console.log("item created. ")
            getNewItemAndUpdateReport(returnedTiid, 500)
        }
    });
});<commit_msg>Encapsulates embed script, avoiding conflicts with host page JS vars including jQuery.<commit_after>(function () {

    var jQuery;

    /******** Load jQuery if not present *********/
    // this embed pattern is from http://alexmarandon.com/articles/web_widget_jquery/
    if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
        var script_tag = document.createElement('script');
        script_tag.setAttribute("type", "text/javascript");
        script_tag.setAttribute("src",
                                "https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js");
        if (script_tag.readyState) {
            script_tag.onreadystatechange = function () { // For old versions of IE
                if (this.readyState == 'complete' || this.readyState == 'loaded') {
                    scriptLoadHandler();
                }
            };
        } else {
            script_tag.onload = scriptLoadHandler;
        }
        // Try to find the head, otherwise default to the documentElement
        (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
    } else {
        // The jQuery version on the window is the one we want to use
        jQuery = window.jQuery;
        main();
    }

    /******** Called once jQuery has loaded ******/
    function scriptLoadHandler() {
        // Restore $ and window.jQuery to their previous values and store the
        // new jQuery in our local jQuery variable
        jQuery = window.jQuery.noConflict(true);
        // Call our main function
        main();
    }

    /******** Our main function ********/

    function main() {

        function getLatestTimestamp(metricSnaps) {
            var latestTs = "1999-01-01T00:00:00.000000";
            for (ts in metricSnaps) {
                if (ts > latestTs) {
                    latestTs = ts
                }
            }
            return latestTs
        }

        function sortByMetricValueDesc(metric1, metric2) {
            if (metric1.value < metric2.value)
                return 1;
            if (metric1.value > metric2.value)
                return -1;
            return 0;
        }

        function renderItem(item) {
            item.metricsArr = [];
            for (metricName in item.metrics) {
                thisMetric = item.metrics[metricName];
                thisMetric.name = metricName;
                var latestTs = getLatestTimestamp(item.metrics[metricName].values);
                if (latestTs) {
                    var latestVal = item.metrics[metricName].values[latestTs];
                    thisMetric.ts = latestTs;
                    thisMetric.value = latestVal
                }

                // if no values, no point in printing
                if (thisMetric.value) {
                    item.metricsArr.push(thisMetric);
                }
            }

            item.metricsArr.sort(sortByMetricValueDesc);

            if (typeof ich.itemtemplate == "undefined") {
                ich.addTemplate("itemtemplate", '
\r\n
<\/div>\r\n
{{#metricsArr}}\r\n
\r\n      \r\n        {{ ts }}<\/span>\r\n        {{ value }}<\/span>\r\n        \r\n          \r\n          {{ static_meta.provider }} {{ static_meta.display_name }}<\/span>\r\n        <\/span>\r\n      <\/a>\r\n    <\/li>\r\n    {{\/metricsArr}}\r\n  <\/ul>\r\n<\/div>')
            }

            return ich.itemtemplate(item);
        }

        function addDataToPage(data) {
            jQuery("div#ti-data")
                .empty()
                .append(renderItem(data));
        }

        function getNewItemAndUpdateReport(tiid, interval) {
            jQuery.ajax({
                       url:'http://api.total-impact.org/item/' + tiid,
                       type:"GET",
                       dataType:"json",
                       contentType:"application/json; charset=utf-8",
                       statusCode:{
                           210:function (data) {
                               console.log("still updating");
                               addDataToPage(data);
                               setTimeout(function () {
                                   getNewItemsAndUpdateReport(interval)
                               })
                           },
                           200:function (data) {
                               console.log("done with updating");
                               addDataToPage(data);
                               return false;
                           }
                       }
                   });
        }

        function getAlias(id_string) {
            // split the user-supplied alias string into namespace and id parts
            var alias = [];
            if (id_string.indexOf(":") > 0) {
                alias[0] = id_string.split(':')[0]; // namespace
                alias[1] = id_string.substr(alias[0].length + 1); // id

                // handle urls:
                if (alias[0] == "http") {
                    alias[0] = "url";
                    alias[1] = id_string
                }
            }
            return alias
        }

        // Based on http://drnicwilliams.com/2006/11/21/diy-widgets/
        function requestStylesheet(stylesheet_url) {
            var stylesheet = document.createElement("link");
            stylesheet.rel = "stylesheet";
            stylesheet.type = "text/css";
            stylesheet.href = stylesheet_url;
            stylesheet.media = "all";
            document.lastChild.firstChild.appendChild(stylesheet);
        }

        // Based on http://drnicwilliams.com/2006/11/21/diy-widgets/
        function requestScript(script_url) {
            var script = document.createElement('script');
            script.src = script_url;
            // IE7 doesn't like this: document.body.appendChild(script);
            // Instead use:
            document.getElementsByTagName('head')[0].appendChild(script);
        }

        jQuery.ajaxSetup({ cache:false });
        var ajax_load = '';

        jQuery(document).ready(function ($) {
            requestStylesheet("http://total-impact.org/static/embed.css");
            requestScript("http://total-impact.org/static/js/icanhaz.min.js");

            $("span#ti-id").hide();
            $("div#ti-data").html(ajax_load + " Loading...");
            var alias = getAlias($("span#ti-id").html());

            console.log("getting the item tiid");
            $.ajax({
                url:"http://api.total-impact.org/item/" + alias[0] + "/" + alias[1],
                type:"POST",
                dataType:"json",
                contentType:"application/json; charset=utf-8",
                data:JSON.stringify(alias),
                success:function (returnedTiid) {
                   // make a new collection, populated by our freshly-minted tiids
                   console.log("item created. ");
                   getNewItemAndUpdateReport(returnedTiid, 500);
                }
           });
        });
    }
})()<|endoftext|>


<commit_before>'use strict';
define(function () {
	let chs = {
			back: '返回',
			loading: '加载中...',
			ok: '确定',
			yes: '是',
			no: '否',
			error: '加载 ${res} 时发生了一个错误: ',
			update: '服务刚完成更新, 该页需要先重新加载才能访问. 是否立即刷新?'
		},
		cht = {
			back: '返回',
			loading: '載入中...',
			ok: '確認',
			yes: '是',
			no: '否',
			error: '載入 ${res} 時發生了一個錯誤: ',
			update: '服務剛完成更新, 該頁需要先重新載入才能訪問. 是否立即刷新?'
		},
		eng = {
			back: 'back',
			loading: 'Loading...',
			ok: 'OK',
			yes: 'Yes',
			no: 'No',
			error: 'An error occured while loading ${res}: ',
			update: 'The service is just updated. This page requires a reload to be accessible. Would you like to continue?'
		};
	return {
		zh: chs,
		'zh-CN': chs,
		'zh-TW': cht,
		'zh-HK': cht,
		en: eng,
		'en-US': eng,
		'en-AU': eng,
		'en-CA': eng,
		'en-IN': eng,
		'en-NZ': eng,
		'en-ZA': eng,
		'en-GB': eng
	};
});<commit_msg>no message<commit_after>'use strict';
define(function () {
	let chs = {
		back: '返回',
		loading: '加载中...',
		close: '关闭',
		yes: '是',
		no: '否',
		error: '加载 ${res} 时发生了一个错误: ',
		update: '服务刚完成更新, 该页需要先重新加载才能访问. 是否立即刷新?'
	},
		cht = {
			back: '返回',
			loading: '載入中...',
			close: '關閉',
			yes: '是',
			no: '否',
			error: '載入 ${res} 時發生了一個錯誤: ',
			update: '服務剛完成更新, 該頁需要先重新載入才能訪問. 是否立即刷新?'
		},
		eng = {
			back: 'back',
			loading: 'Loading...',
			close: 'Close',
			yes: 'Yes',
			no: 'No',
			error: 'An error occured while loading ${res}: ',
			update: 'The service is just updated. This page requires a reload to be accessible. Would you like to continue?'
		};
	return {
		zh: chs,
		'zh-CN': chs,
		'zh-TW': cht,
		'zh-HK': cht,
		en: eng,
		'en-US': eng,
		'en-AU': eng,
		'en-CA': eng,
		'en-IN': eng,
		'en-NZ': eng,
		'en-ZA': eng,
		'en-GB': eng
	};
});<|endoftext|>


<commit_before>/*globals require, describe, it*/
var expect    = require("chai").expect;
var utilities = require("faces/strategy/imageRecognition/graphics/util");

describe("Color Code Converter", function() {
    'use strict';
    describe("Hex to RGB conversion", function() {
        it("converts the basic colors", function() {

        });
    });
});<commit_msg>testing 4 simple boxes<commit_after>/*globals require, describe, it*/
var expect    = require("chai").expect;
var utilities = require("faces/strategy/imageRecognition/graphics/util");

describe("Image partitioning process", function() {
    'use strict';
    describe("Partition Images in 4 Quadrants", function() {
        it("Returns 4 parallelograms of X1,X2,Y1,Y2 vertices that are inside an Image", function() {
            var portraitParallelograms = utilities.partitionSquareIntoFour({width: 100, height: 200});
            var landscapeParallelograms = utilities.partitionSquareIntoFour({width: 200, height: 100});
            var squareParallelograms = utilities.partitionSquareIntoFour({width: 200, height: 200});
            var testbed = [portraitParallelograms, landscapeParallelograms, squareParallelograms];
            var results = [
                [
                    {X1: 0,X2: 50,Y1: 0,Y2: 100},
                    {X1: 50,X2: 100,Y1: 0,Y2: 100},
                    {X1: 0,X2: 50,Y1: 100,Y2: 200},
                    {X1: 50,X2: 100,Y1: 100,Y2: 200}
                ],
                [
                    {X1: 0,X2: 100,Y1: 0,Y2: 50},
                    {X1: 100,X2: 200,Y1: 0,Y2: 50},
                    {X1: 0,X2: 100,Y1: 50,Y2: 100},
                    {X1: 100,X2: 200,Y1: 50,Y2: 100}
                ],
                [
                    {X1: 0,X2: 100,Y1: 0,Y2: 100},
                        {X1: 100,X2: 200,Y1: 0,Y2: 100},
                    {X1: 0,X2: 100,Y1: 100,Y2: 200},
                    {X1: 100,X2: 200,Y1: 100,Y2: 200}
                ]
            ];
            for(var j = 0;j !== testbed.length; ++j) {
                var currentTest = testbed[j];
                var currentResults = results[j];
                for (var i = 0; i !== currentResults.length; ++i) {
                    var resultParallelogram = currentResults[i];
                    var parallelogram = currentTest[i];
                    for (var key in resultParallelogram) {
                        if (resultParallelogram.hasOwnProperty(key)) {
                            expect(parallelogram[key]).to.equal(resultParallelogram[key]);
                        }
                    }
                }
            }
        });
    });
});<|endoftext|>


<commit_before>var superagent  = require('superagent');
var superagentQ = require('superagent-promises');

class NationalPlanMapper {

    //============================================================
    //
    //
    //============================================================
    async query () {

    	var url = "https://chm.cbd.int/api/v2013/index/select?fl=id,title_t,government_s,createdDate_dt,updatedDate_dt,url_ss,reportType_s,documentLinks_s&q=NOT+version_s:*+AND+realm_ss:chm+AND+schema_s:*+AND+(+schema_s:nationalReport+)+AND+(+reportType_s:B0EBAE91-9581-4BB2-9C02-52FCF9D82721+)&rows=9999&start=0&wt=json"

    	var res = await superagent.get(url).use(superagentQ).end();

    	return res.body.response.docs.map(document => new NationalPlan({
			protocolVersion: 1,
			id: document.id,
			treaty: 'cbd',
			country: document.government_s,
			type: 'nbsap',
			title: [{ language: 'en', value: document.title_t }],
			url: document.url_ss[0],
            files: JSON.parse(document.documentLinks_s||'[]').map(link => new File({
                filename: link.name,
                url: link.url
            })),
			submission: document.createdDate_dt,
			updated: document.updatedDate_dt

        }));
	}
}

export default new NationalPlanMapper();

///
<commit_msg>housekeeping<commit_after>var superagent  = require('superagent');
var superagentQ = require('superagent-promises');

class NationalPlanMapper {

    //============================================================
    //
    //
    //============================================================
    async query () {

    	var url = "https://chm.cbd.int/api/v2013/index/select?fl=id,title_t,government_s,createdDate_dt,updatedDate_dt,url_ss,reportType_s,documentLinks_s&q=NOT+version_s:*+AND+realm_ss:chm+AND+schema_s:*+AND+(+schema_s:nationalReport+)+AND+(+reportType_s:B0EBAE91-9581-4BB2-9C02-52FCF9D82721+)&rows=9999&start=0&wt=json"

    	var res = await superagent.get(url).use(superagentQ).end();

    	return res.body.response.docs.map(document => new NationalPlan({
			protocolVersion: 1,
			id: document.id,
			treaty: 'cbd',
			country: document.government_s,
			type: 'nbsap',
			title: [{ language: 'en', value: document.title_t }],
			url: document.url_ss[0],
            files: JSON.parse(document.documentLinks_s||'[]').map(link => new File({
                filename: link.name,
                url: link.url
            })),
			submission: document.createdDate_dt,
			updated: document.updatedDate_dt

        }));
	}
}

export default new NationalPlanMapper();
<|endoftext|>


<commit_before>// Geometries
Map.setCenter(-88, 41.8, 9);
// Load Feature Collection of the dissolved boundary of Chicago stored in assets
var chic = ee.FeatureCollection('users/tirthankar25/chicago_diss');
// Load Feature Collection of the neighborhood-scale Chicago data stored in assets
var chicColl = ee.FeatureCollection('users/tirthankar25/chicago');
// Add the layer to the map
// Map.addLayer(Res);
Map.addLayer(chic, {color:'red'}, 'Chicago dissolved');
// Find the rectangle that emcompasses the southernmost, westernmost, easternmost, and northernmost
// points of the feature
var bound = chic.geometry().bounds();
Map.addLayer(bound, {color:'yellow'},'Bounds');
// Find the polygon covering the extremities of the feature
var convex = chic.geometry().convexHull();
Map.addLayer(convex, {color:'blue'},'Convex Hull');
// Find the area common to two or more features
var intersect = bound.intersection(convex,100);
Map.addLayer(intersect, {color:'green'},'Bound and convex intersection');
// Find the area encompassing two or more features; number is the maximum error in meters
var union = bound.union(convex,100);
Map.addLayer(union, {color:'purple'},'Bound and convex union');
// Find the difference between two geometries
var diff=bound.difference(convex,100);
Map.addLayer(diff, {color:'purple'},'Bound and convex difference');
// Find area of feature
var ar = chic.geometry().area();
print (ar)
// Find length of line geometry (You get zero since this is a polygon)
var length = chic.geometry().length();
print (length)
// Find permeter of feature
var peri = chic.geometry().perimeter();
print (peri)

function performMap(feature) {
 // Reduce number of vertices in geometry; the number is to specify maximum error in meters
 var simple = feature.simplify(1000);
 // Find centroid of geometry
 var center = simple.centroid();
 // Create buffer around geometry; the number represents the width of buffer in meters
 var buff = center.buffer(500);
 // return variable from function
 return buff;
}
// Map function over Feature Collection
var mappedCentroid = chicColl.map(performMap);
Map.addLayer(mappedCentroid,{},"Mapped centroids")

// Features
// Create Geometry
var varGeometry = ee.Geometry.Polygon(0, 0, 40, 30, 20, 20, 0, 0);
// Create Feature from Geometry
var varFeature = ee.Feature(varGeometry, {
 Name: ['Feature name', 'Supreme'],
 Size: [500, 1000]
});
// Get values of a property
var arr=varFeature.get('Size');
print (arr);
// Select a subset of properties and rename them
var varFeaturenew = varFeature.select(['Name'], ['Descriptor']);
print(varFeaturenew);

// Images
Map.setCenter(-88, 41.8, 9);
var raw = ee.ImageCollection('MODIS/006/MYD11A2');
var roi = ee.FeatureCollection('users/tirthankar25/chicago');
print(raw);
// Select a band of the image collection using either indexing or band name
var bandSel1 = raw.select(0);
var bandSel2=raw.select('LST_Day_1km');
// Filter the image collection by a date range
var filtered=raw.filterDate('2002-12-30','2004-4-27');
print(filtered);
// Limit the image collection to the first 50 elements
var limited = raw.limit(50);
print(limited);
print(bandSel1);
// Calculate mean of all images (pixel-by-pixel) in the collection
var mean = bandSel1.mean();
// Calculate image of region of interest
var clipped = mean.clip(roi);
// mathematical operation on image pixels to convert from digital number of satellite observations to degree Celsius
var calculate = clipped.multiply(.02).subtract(273.15);
Map.addLayer(calculate,{min: 20, max: 30, palette: ['blue', 'green', 'red']},'LST');
// Select pixel in the image that are greater than 30.8
var mask = calculate.gt(30.8);
Map.addLayer(mask,{},"mask");
// Use selected pixels to mask the whole image
var masked = clipped.mask(mask);
Map.addLayer(masked,{min: 10, max: 30, palette: ['blue', 'green', 'red']},'LST_masked');

// Image to table example
// Function to find mean of pixels in region of interest
var getRegions = function(image) {
  // Load feature collection
  var urban = ee.FeatureCollection('users/tirthankar25/chicago');
 return image.reduceRegions({
  // Collection to run operation over
    collection: urban,
  // Reducer to use
  reducer: ee.Reducer.mean(),
  // Pixel resolution used for the calculations
  scale: 1000,
 });
};
// Load image
var image = ee.ImageCollection('MODIS/MYD13A1').filterDate('2002-07-08', '2017-07-08')
 .mean().select('NDVI');
print(image);
// Call function
var Final = getRegions(image);
// Export image to Google Drive
Export.table.toDrive({
 collection: Final,
 description: 'NDVI_all',
 fileFormat: 'CSV'
});

// Timelapse example (based on google API example);
var geometry = ee.Geometry.Rectangle([55.1, 25, 55.4, 25.4]);
Map.addLayer(geometry);
var allImages = ee.ImageCollection('LANDSAT/LT05/C01/T1_TOA')
 // Filter row and path such that they cover Dubai
 .filter(ee.Filter.eq('WRS_PATH', 160))
 .filter(ee.Filter.eq('WRS_ROW', 43))
 // Filter cloudy scenes
 .filter(ee.Filter.lt('CLOUD_COVER', 30))
 // Get required years of imagery
 .filterDate('1984-01-01', '2012-12-30')
 // Select 3-band imagery for the video
 .select(['B4', 'B3', 'B2'])
 // Make the data 8 bit
 .map(function(image) {
  return image.multiply(512).uint8();
 });
Export.video.toDrive({
 collection: allImages,
 // Name of file
 description: 'dubaiTimelapse',
 // Quality of video
 dimensions: 720,
 // FPS of video
 framesPerSecond: 8,
 // Region of export
 region: geometry
});
<commit_msg>Update sample.js<commit_after>// Geometries
Map.setCenter(-88, 41.8, 9);
// Load Feature Collection of the dissolved boundary of Chicago stored in assets
var chic = ee.FeatureCollection('users/tirthankar25/chicago_diss');
// Load Feature Collection of the neighborhood-scale Chicago data stored in assets
var chicColl = ee.FeatureCollection('users/tirthankar25/chicago');
// Add the layer to the map
// Map.addLayer(Res);
Map.addLayer(chic, {color: 'red'}, 'Chicago dissolved');
// Find the rectangle that emcompasses the southernmost, westernmost, easternmost, and northernmost
// points of the feature
var bound = chic.geometry().bounds();
Map.addLayer(bound, {color: 'yellow'}, 'Bounds');
// Find the polygon covering the extremities of the feature
var convex = chic.geometry().convexHull();
Map.addLayer(convex, {color: 'blue'}, 'Convex Hull');
// Find the area common to two or more features
var intersect = bound.intersection(convex,100);
Map.addLayer(intersect, {color: 'green'}, 'Bound and convex intersection');
// Find the area encompassing two or more features; number is the maximum error in meters
var union = bound.union(convex,100);
Map.addLayer(union, {color: 'purple'}, 'Bound and convex union');
// Find the difference between two geometries
var diff=bound.difference(convex,100);
Map.addLayer(diff, {color: 'purple'}, 'Bound and convex difference');
// Find area of feature
var ar = chic.geometry().area();
print (ar)
// Find length of line geometry (You get zero since this is a polygon)
var length = chic.geometry().length();
print (length)
// Find permeter of feature
var peri = chic.geometry().perimeter();
print (peri)

function performMap(feature) {
 // Reduce number of vertices in geometry; the number is to specify maximum error in meters
 var simple = feature.simplify(1000);
 // Find centroid of geometry
 var center = simple.centroid();
 // Create buffer around geometry; the number represents the width of buffer in meters
 var buff = center.buffer(500);
 // return variable from function
 return buff;
}
// Map function over Feature Collection
var mappedCentroid = chicColl.map(performMap);
Map.addLayer(mappedCentroid,{},'Mapped centroids')

// Features
// Create Geometry
var varGeometry = ee.Geometry.Polygon(0, 0, 40, 30, 20, 20, 0, 0);
// Create Feature from Geometry
var varFeature = ee.Feature(varGeometry, {
 Name: ['Feature name', 'Supreme'],
 Size: [500, 1000]
});
// Get values of a property
var arr=varFeature.get('Size');
print (arr);
// Select a subset of properties and rename them
var varFeaturenew = varFeature.select(['Name'], ['Descriptor']);
print(varFeaturenew);

// Images
Map.setCenter(-88, 41.8, 9);
var raw = ee.ImageCollection('MODIS/006/MYD11A2');
var roi = ee.FeatureCollection('users/tirthankar25/chicago');
print(raw);
// Select a band of the image collection using either indexing or band name
var bandSel1 = raw.select(0);
var bandSel2=raw.select('LST_Day_1km');
// Filter the image collection by a date range
var filtered=raw.filterDate('2002-12-30','2004-4-27');
print(filtered);
// Limit the image collection to the first 50 elements
var limited = raw.limit(50);
print(limited);
print(bandSel1);
// Calculate mean of all images (pixel-by-pixel) in the collection
var mean = bandSel1.mean();
// Calculate image of region of interest
var clipped = mean.clip(roi);
// mathematical operation on image pixels to convert from digital number of satellite observations to degree Celsius
var calculate = clipped.multiply(.02).subtract(273.15);
Map.addLayer(calculate, {min: 20, max: 30, palette: ['blue', 'green', 'red']},'LST');
// Select pixel in the image that are greater than 30.8
var mask = calculate.gt(30.8);
Map.addLayer(mask, {}, 'mask');
// Use selected pixels to mask the whole image
var masked = clipped.mask(mask);
Map.addLayer(masked, {min: 10, max: 30, palette: ['blue', 'green', 'red']}, 'LST_masked');

// Image to table example
// Function to find mean of pixels in region of interest
var getRegions = function(image) {
  // Load feature collection
  var urban = ee.FeatureCollection('users/tirthankar25/chicago');
 return image.reduceRegions({
  // Collection to run operation over
    collection: urban,
  // Reducer to use
  reducer: ee.Reducer.mean(),
  // Pixel resolution used for the calculations
  scale: 1000,
 });
};
// Load image
var image = ee.ImageCollection('MODIS/MYD13A1').filterDate('2002-07-08', '2017-07-08')
 .mean().select('NDVI');
print(image);
// Call function
var Final = getRegions(image);
// Export image to Google Drive
Export.table.toDrive({
 collection: Final,
 description: 'NDVI_all',
 fileFormat: 'CSV'
});

// Timelapse example (based on google API example);
var geometry = ee.Geometry.Rectangle([55.1, 25, 55.4, 25.4]);
Map.addLayer(geometry);
var allImages = ee.ImageCollection('LANDSAT/LT05/C01/T1_TOA')
 // Filter row and path such that they cover Dubai
 .filter(ee.Filter.eq('WRS_PATH', 160))
 .filter(ee.Filter.eq('WRS_ROW', 43))
 // Filter cloudy scenes
 .filter(ee.Filter.lt('CLOUD_COVER', 30))
 // Get required years of imagery
 .filterDate('1984-01-01', '2012-12-30')
 // Select 3-band imagery for the video
 .select(['B4', 'B3', 'B2'])
 // Make the data 8 bit
 .map(function(image) {
  return image.multiply(512).uint8();
 });
Export.video.toDrive({
 collection: allImages,
 // Name of file
 description: 'dubaiTimelapse',
 // Quality of video
 dimensions: 720,
 // FPS of video
 framesPerSecond: 8,
 // Region of export
 region: geometry
});
<|endoftext|>