<commit_before>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2010-2012 Zynga Inc.
  Copyright 2012-2013 Sebastian Werner
==================================================================================================
*/

"use strict";

(function() {

	function raise(message) {
		throw new Error(message);
	}

	/**
	 * Collection of assertions which could be used to verify incoming arguments, etc.
	 *
	 * Modelled after the Python API at http://docs.python.org/library/unittest.html
	 */
	core.Module("core.Assert",
	{
		/**
		 * Raises an exception when the two values @a {var} and @b {var} are not equal (`!=`)
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		equal: function(a, b, message)
		{
			if (a != b) {
				raise(message || "Values must be equal: " + a + " and " + b + "!");
			}
		},

		/**
		 * Raises an exception when the two values @a {var} and @b {var} are equal (`==`).
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		notEqual: function(a, b, message)
		{
			if (a == b) {
				raise(message || "Values must not be equal: " + a + " and " + b + "!");
			}
		},

		/**
		 * Raises an exception when the two values @a {var} and @b {var} are not identical (`!==`)
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		identical: function(a, b, message)
		{
			if (a !== b) {
				raise(message || "Values must be identical: " + a + " and " + b + "!");
			}
		},

		/**
		 * Raises an exception when the two values @a {var} and @b {var} are identical (`===`).
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		notIdentical: function(a, b, message)
		{
			if (a === b) {
				raise(message || "Values must not be identical: " + a + " and " + b + "!");
			}
		},

		/**
		 * Raises an exception when the value @a {var} is not trueish (`!= true`).
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isTrue: function(a, message)
		{
			if (a != true) {
				raise(message || "Value must be true: " + a + "!");
			}
		},

		/**
		 * Raises an exception when the value @a {var} is not falsy (`!= false`).
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isFalse: function(a, message)
		{
			if (a != false) {
				raise(message || "Value must be false: " + a + "!");
			}
		},

		/**
		 * Raises an exception when the value @a {var} is not `null`.
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isNull: function(a, message)
		{
			if (a != null) {
				raise(message || "Value " + a + " must be null!");
			}
		},

		/**
		 * Raises an exception when the value @a {var} is `null`.
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isNotNull: function(a, message)
		{
			if (a == null) {
				raise(message || "Value " + a + " must not be null!");
			}
		},

		/**
		 * Raises an exception when the value @a {var} is not in @object {Object|Array|String}.
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isIn: function(a, object, message)
		{
			if (!(a in object || object.indexOf && object.indexOf(a) != -1)) {
				raise(message || "Value " + a + " is not in given object!");
			}
		},

		/**
		 * Raises an exception when the value @a {var} is in @object {Object|Array|String}.
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isNotIn: function(a, object, message)
		{
			if (a in object || object.indexOf && object.indexOf(a) != -1) {
				raise(message || "Value " + a + " must not be in given object!");
			}
		},

		/**
		 * Raises an exception when the value @a {var} does not match the regular expression @regexp {RegExp}.
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		matches: function(a, regexp, message)
		{
			if (!regexp.match(a)) {
				raise(message || "Value " + a + " must match " + regexp);
			}
		},

		/**
		 * Raises an exception when the value @a {var} matches the regular expression @regexp {RegExp}.
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		notMatches: function(a, regexp, message)
		{
			if (regexp.match(a)) {
				raise(message || "Value " + a + " must not match " + regexp);
			}
		},

		/**
		 * Raises an exception when the value @a {var} is not an instance of @clazz {String}
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isInstance: function(a, clazz, message)
		{
			if (!(a instanceof clazz)) {
				raise(message || "Value " + a + " must be instance of: " + clazz);
			}
		},

		/**
		 * Raises an exception when the value @a {var} is not of @type {String} (checked via {core.Main#isTypeOf})
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isType: function(a, type, message)
		{
			if (!core.Main.isTypeOf(a, type)) {
				raise(message || "Value " + a + " must match type: " + type);
			}
		},

		/**
		 * Raises an exception when the value @a {var} is of @type {String} (checked via {core.Main#isTypeOf})
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isNotType: function(a, type, message)
		{
			if (core.Main.isTypeOf(a, type)) {
				raise(message || "Value " + a + " must not match type: " + type);
			}
		},

		/**
		 * Raises an exception when the given value @a {var} is not empty.
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isNotEmpty: function(a, message)
		{
			// Strings, Arrays
			if (Object.prototype.hasOwnProperty(a, "length"))
			{
				if (a.length === 0) {
					raise(message || "Value " + a + " must not be empty: " + type);
				}
			}
			else if (core.Main.isTypeOf(a, "Map"))
			{
				for (var key in a) {
					return;
				}

				raise(message || "Value " + a + " must not be empty: " + type);
			}
		}

	});

})();

<commit_msg>Added test for not being undefined<commit_after>/*
==================================================================================================
  Core - JavaScript Foundation
  Copyright 2010-2012 Zynga Inc.
  Copyright 2012-2013 Sebastian Werner
==================================================================================================
*/

"use strict";

(function(undef)
{
	function raise(message) {
		throw new Error(message);
	}

	/**
	 * Collection of assertions which could be used to verify incoming arguments, etc.
	 *
	 * Modelled after the Python API at http://docs.python.org/library/unittest.html
	 */
	core.Module("core.Assert",
	{
		/**
		 * Raises an exception when the two values @a {var} and @b {var} are not equal (`!=`)
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		equal: function(a, b, message)
		{
			if (a != b) {
				raise(message || "Values must be equal: " + a + " and " + b + "!");
			}
		},

		/**
		 * Raises an exception when the two values @a {var} and @b {var} are equal (`==`).
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		notEqual: function(a, b, message)
		{
			if (a == b) {
				raise(message || "Values must not be equal: " + a + " and " + b + "!");
			}
		},

		/**
		 * Raises an exception when the two values @a {var} and @b {var} are not identical (`!==`)
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		identical: function(a, b, message)
		{
			if (a !== b) {
				raise(message || "Values must be identical: " + a + " and " + b + "!");
			}
		},

		/**
		 * Raises an exception when the two values @a {var} and @b {var} are identical (`===`).
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		notIdentical: function(a, b, message)
		{
			if (a === b) {
				raise(message || "Values must not be identical: " + a + " and " + b + "!");
			}
		},

		/**
		 * Raises an exception when the value @a {var} is not trueish (`!= true`).
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isTrue: function(a, message)
		{
			if (a != true) {
				raise(message || "Value must be true: " + a + "!");
			}
		},

		/**
		 * Raises an exception when the value @a {var} is not falsy (`!= false`).
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isFalse: function(a, message)
		{
			if (a != false) {
				raise(message || "Value must be false: " + a + "!");
			}
		},

		/**
		 * Raises an exception when the value @a {var} is `undefined`.
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isNotUndefined : function(a, message)
		{
			if (a === undef) {
				raise(message || "Value " + a + " must not be undefined!");
			}
		},

		/**
		 * Raises an exception when the value @a {var} is not `null`.
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isNull: function(a, message)
		{
			if (a != null) {
				raise(message || "Value " + a + " must be null!");
			}
		},

		/**
		 * Raises an exception when the value @a {var} is `null`.
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isNotNull: function(a, message)
		{
			if (a == null) {
				raise(message || "Value " + a + " must not be null!");
			}
		},

		/**
		 * Raises an exception when the value @a {var} is not in @object {Object|Array|String}.
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isIn: function(a, object, message)
		{
			if (!(a in object || object.indexOf && object.indexOf(a) != -1)) {
				raise(message || "Value " + a + " is not in given object!");
			}
		},

		/**
		 * Raises an exception when the value @a {var} is in @object {Object|Array|String}.
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isNotIn: function(a, object, message)
		{
			if (a in object || object.indexOf && object.indexOf(a) != -1) {
				raise(message || "Value " + a + " must not be in given object!");
			}
		},

		/**
		 * Raises an exception when the value @a {var} does not match the regular expression @regexp {RegExp}.
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		matches: function(a, regexp, message)
		{
			if (!regexp.match(a)) {
				raise(message || "Value " + a + " must match " + regexp);
			}
		},

		/**
		 * Raises an exception when the value @a {var} matches the regular expression @regexp {RegExp}.
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		notMatches: function(a, regexp, message)
		{
			if (regexp.match(a)) {
				raise(message || "Value " + a + " must not match " + regexp);
			}
		},

		/**
		 * Raises an exception when the value @a {var} is not an instance of @clazz {String}
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isInstance: function(a, clazz, message)
		{
			if (!(a instanceof clazz)) {
				raise(message || "Value " + a + " must be instance of: " + clazz);
			}
		},

		/**
		 * Raises an exception when the value @a {var} is not of @type {String} (checked via {core.Main#isTypeOf})
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isType: function(a, type, message)
		{
			if (!core.Main.isTypeOf(a, type)) {
				raise(message || "Value " + a + " must match type: " + type);
			}
		},

		/**
		 * Raises an exception when the value @a {var} is of @type {String} (checked via {core.Main#isTypeOf})
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isNotType: function(a, type, message)
		{
			if (core.Main.isTypeOf(a, type)) {
				raise(message || "Value " + a + " must not match type: " + type);
			}
		},

		/**
		 * Raises an exception when the given value @a {var} is not empty.
		 * Customizable with a custom @message {String?} for the exception text.
		 */
		isNotEmpty: function(a, message)
		{
			// Strings, Arrays
			if (Object.prototype.hasOwnProperty(a, "length"))
			{
				if (a.length === 0) {
					raise(message || "Value " + a + " must not be empty: " + type);
				}
			}
			else if (core.Main.isTypeOf(a, "Map"))
			{
				for (var key in a) {
					return;
				}

				raise(message || "Value " + a + " must not be empty: " + type);
			}
		}
	});

})();

<|endoftext|>


<commit_before>"use babel";
// @flow

import type { Diagnostic } from "../../Types/types.js.flow";

export let gulpBuild1Log1: Diagnostic = {
  type: "info",
  message: "a message",
  task: "gulpBuild1",
  date: 1477601049,
  step: 1,
};

export let gulpBuild1Log2: Diagnostic = {
  type: "info",
  message: "a message 2",
  task: "gulpBuild1",
  date: 1477601049,
  step: 1,
};

export let gulpDiagnostics: Array<Diagnostic> = [
  gulpBuild1Log1,
  gulpBuild1Log2,
];

export let dockerWeb1Log1: Diagnostic = {
  type: "info",
  message: "a message",
  task: "dockerWeb1",
  date: 1477601049,
  step: 1,
};

export let dockerWeb1Error1: Diagnostic = {
  type: "error",
  message: "a message",
  task: "dockerWeb1",
  date: 1477601049,
  step: 1,
};

export let dockerWeb1Error2: Diagnostic = {
  type: "error",
  message: "a message",
  task: "dockerWeb1",
  date: 1477601049,
  step: 1,
};

export let dockerWeb1Warning1: Diagnostic = {
  type: "warning",
  message: "a message",
  task: "dockerWeb1",
  date: 1477601049,
  step: 1,
};

export let dockerWeb2Warning1: Diagnostic = {
  type: "warning",
  message: "a message",
  task: "dockerWeb2",
  date: 1477601049,
  step: 1,
};

export let dockerDBInfo1: Diagnostic = {
  type: "info",
  message: "a message",
  task: "dockerDB1",
  date: 1477601049,
  step: 1,
};

export let dockerDiagnostics: Array<Diagnostic> = [
  dockerWeb1Log1,
  dockerWeb1Error1,
  dockerWeb1Error2,
  dockerWeb1Warning1,
  dockerWeb2Warning1,
  dockerDBInfo1,
];

let diagnostics: Array<Diagnostic> = [...gulpDiagnostics, ...dockerDiagnostics];

export default diagnostics;
<commit_msg>fake diagnostics to fit new diagnostic type<commit_after>"use babel";
// @flow

import type { Diagnostic } from "../../Types/types.js.flow";

export let gulpBuild1Log1: Diagnostic = {
  severity: 3,
  message: "a message",
  task: "gulpBuild1",
  date: 1477601049,
  step: 1,
};

export let gulpBuild1Log2: Diagnostic = {
  severity: 3,
  message: "a message 2",
  task: "gulpBuild1",
  date: 1477601049,
  step: 1,
};

export let gulpDiagnostics: Array<Diagnostic> = [
  gulpBuild1Log1,
  gulpBuild1Log2,
];

export let dockerWeb1Log1: Diagnostic = {
  severity: 3,
  message: "a message",
  task: "dockerWeb1",
  date: 1477601049,
  step: 1,
};

export let dockerWeb1Error1: Diagnostic = {
  severity: 1,
  message: "a message",
  task: "dockerWeb1",
  date: 1477601049,
  step: 1,
};

export let dockerWeb1Error2: Diagnostic = {
  severity: 1,
  message: "a message",
  task: "dockerWeb1",
  date: 1477601049,
  step: 1,
};

export let dockerWeb1Warning1: Diagnostic = {
  severity: 2,
  message: "a message",
  task: "dockerWeb1",
  date: 1477601049,
  step: 1,
};

export let dockerWeb2Warning1: Diagnostic = {
  severity: 2,
  message: "a message",
  task: "dockerWeb2",
  date: 1477601049,
  step: 1,
};

export let dockerDBInfo1: Diagnostic = {
  severity: 3,
  message: "a message",
  task: "dockerDB1",
  date: 1477601049,
  step: 1,
};

export let dockerDiagnostics: Array<Diagnostic> = [
  dockerWeb1Log1,
  dockerWeb1Error1,
  dockerWeb1Error2,
  dockerWeb1Warning1,
  dockerWeb2Warning1,
  dockerDBInfo1,
];

let diagnostics: Array<Diagnostic> = [...gulpDiagnostics, ...dockerDiagnostics];

export default diagnostics;
<|endoftext|>


<commit_before>
$(document).ready(function() {
	update_credits();
	update_shares();
});

/*
	Create a block with given width and background color,
	and append it to the given bar element.
*/
function create_block(username, width, isShare) {
	var block = $(document.createElement('td'));
	block.css({
		'width': width + '%',
		'background-color': '#' + color_generator(username)
	});
	var percent = $(document.createElement('span'));
	percent.text(width + '%');

	if (isShare) {
		block.attr("id", "usage" + username);
		if (username == "Free" && width > 0) {
			var get = $(document.createElement('a'));
			get.attr('id','getresourcesbutton');
			get.attr('href', '../control/myvessels');
			get.text('get');
			// get.click(get_resources_dialog);
			block.append(get);

			var share = $(document.createElement('a'));
			share.attr('id','shareresourcesbutton');
			share.attr('href','#');
			share.text('share');
			share.click(share_resources_dialog);
			block.append(share);

		} else if (username != "Me" && username != "Others" ) {
			var close = $(document.createElement('a'));
			close.attr('href','#');
			close.text('x');
			close.click(function() {
				$.post("../control/ajax_editshare",
						{ username: username, percent: 0 },
						function (data) {
							var json = eval('(' + data + ')');
							if (json.success) {
								update_shares();
							} else {
								alert(json.error);
							}
						});
			});
			block.append(close);
			percent.attr("title", "Click to change percent");
			percent.tooltip({cssClass:"tooltip"});
			percent.css("cursor", "pointer");
			percent.click(function() {
				change_percent(username, width);
			});
		}
	}

	if (username == "Others") {
		percent.attr("title", "Click to reveal");
		percent.tooltip({cssClass:"tooltip"});
		percent.css("cursor", "pointer");
		percent.click(function () { show_table(isShare) });
		// block.attr("id", "creditOthers");
	}
	block.append(percent);
	return block;
}

/*
	Create a name label with given width and append it to
	the given name table.
*/
function create_label(username, width, isShare) {
	var label = $(document.createElement('td'));
	if (isShare) {
		label.attr("id", "labelusage" + username);
	}
	label.text(username);
	label.css({
		'width': width + '%'
	});
	return label;
}

function add_other(type, username, percent) {
	var table;
	if (type == "credits") {
		table = $("#creditotherstable");
	} else if (type == "shares") {
		table = $("#usageotherstable");
	}
	var tr = $(document.createElement("tr"));
	tr.html("" + username + "	" + percent + "	");
	if (type == "shares") {
		var control = $(document.createElement("td"));
		var edit = $(document.createElement("button"));
		edit.text("Edit");
		edit.click(function() {
			change_percent(username, percent);
		});
		var close = $(document.createElement("button"));
		close.text("Delete");
		close.click(function() {
			$.post("../control/ajax_editshare",
					{ username: username, percent: 0 },
					function(data) {
						var json = eval('(' + data + ')');
						if (json.success) {
							update_shares();
						} else {
							alert(json.error);
						}
					});
			tr.remove();
		});
		control.append(edit);
		control.append(close);
		tr.append(control);
	}
	table.append(tr);
}

/*
	Display the change percent dialog box
*/
function change_percent(username, percent) {
	var dialog = $(document.createElement("div"));
	dialog.attr("id", "changepercentdialog");
	dialog.html('
Change Percent
');
	var input = $(document.createElement("input"));
	input.attr("type", "text");
	input.val(percent);
	input.click(function () { $(this).val("") });
	var symbol = $(document.createElement("span"));
	symbol.html(" %
");
	var cancel = $(document.createElement("button"));
	cancel.text("Cancel");
	var save = $(document.createElement("button"));
	save.text("Save");
	cancel.click(function () {
		close_dialog();
		$(this).parent().remove();
	});
	save.click(function() {
		validate();
		save_percent(username, parseInt(input.val()));
	});
	dialog.append(input);
	dialog.append(symbol);
	dialog.append(cancel);
	dialog.append(save);
	$("#dialogframe").append(dialog);
	$("#dialogframe").fadeIn("fast");
	$("#overlay").fadeIn("fast");
	$("#changepercentdialog").fadeIn("fast");
}

/*
	Save the percent of the the block when click "save" on the
	change_percent dialog box
*/
function save_percent(username, percent) {
	$.post("../control/ajax_editshare",
			{ username: username, percent: percent },
			function (data) {
				var json = eval(data);
				if (json.success) {
					$("#changepercentdialog").remove();
					$("#dialogframe").hide();
					$("#overlay").hide();
					update_shares();
				} else {
					create_warning(json.error, $("#changepercentdialog h3"));
				}
	   		},
			"json");
}

function validate() {
	var free = parseInt($("#usageFree span").text());
	alert(free);
}

/*
	Toggle display the tables for small percent users
*/
function show_table(isShare) {
	if (isShare) {
		$("#usageotherstable").toggle();
	} else {
		$("#creditotherstable").toggle();
	}
}

function get_resources_dialog() {
	$("#dialogframe").fadeIn("fast");
	$("#overlay").fadeIn("fast");
	$("#getresourcesdialog").fadeIn("fast");
	$(".cancel").click(close_dialog);
	$("#getresourcesaction").click(get_resources);
}

function share_resources_dialog() {
	$("#dialogframe").fadeIn("fast");
	$("#overlay").fadeIn("fast");
	$("#shareresourcesdialog").fadeIn("fast");
	$(".cancel").click(close_dialog);
	$("#shareresources").click(share_resources);
}

function close_dialog() {
    if ($(this).parent().children(".warning")) {
		$(this).parent().children(".warning").remove();
    }
	$(this).parent().hide();
	$("#dialogframe").hide();
	$("#overlay").hide();
}

function post_ajax(url, args, func) {
	$.post(url, args, function(data) {
		// check data
		// if data ok then:
		func(data)
		// else:
		// display content as raw html in a new popup
	});
}

function share_resources() {
	var username = $("#shareresourcesdialog #username").val();
	var percent = parseInt($("#shareresourcesdialog #percent").val());
	if ($("#shareresourcesdialog .warning")) {
	    $("#shareresourcesdialog .warning").remove();
	}
	if (percent > 0) {
		post_ajax("../control/ajax_createshare",
				{ username: username, percent: percent },
				function(data) {
					var json = eval('(' + data + ')');
					if (json.success) {
						$("#shareresourcesdialog").hide();
						$("#dialogframe").hide();
						$("#overlay").hide();
						update_shares();
					} else {
						create_warning(json.error, $("#shareresourcesdialog h3"));
					}
				});
	} else {
		create_warning("Percent must greater than 0", $("#shareresourcesdialog h3"));
	}
}

function get_resources() {
	var numvessels = parseInt($("#numvessels").val());
	var env = parseInt($("#environment").val());
	if ($("#getresourcesdialog .warning")) {
	    $("#getresourcesdialog .warning").remove();
	}
	$.post("../control/ajax_getvessels",
			{ num: numvessels, env: env },
			function (data) {
				var json = eval('(' + data + ')');
				// alert(json.mypercent);
				// alert(json.success);
				if (json.success) {
					$("#getresourcesdialog").hide();
					$("#dialogframe").hide();
					$("#overlay").hide();
					update_shares();
				} else {
					create_warning(json.error, $("#getresourcesdialog h3"));
				}
			});
}

/*
	Create and insert a warning sign after the given position
*/

function create_warning(error, position) {
	var warning = $(document.createElement("p"));
	warning.html(error);
	warning.addClass("warning");
	warning.insertAfter(position);
}

/*
	Generate a color in hex notation for a username, which assigns different
	colors to different usernames.
*/
function color_generator(username) {
	var seeds = ['cc','ff'];
	var color = seeds[username.charCodeAt(0) % 2] +
				seeds[username.charCodeAt(1) % 2] +
				seeds[username.charCodeAt(username.length - 1) % 2];
	if (color == "ffffff") {
		color = "ffffcc";
	} else if (color == "cccccc") {
		color = "ccccff";
	}
	if (username == "Free") {
		color = "ffffff";
	} else if (username == "Me") {
		color = "cccccc";
	}
	return color;
}

function update_credits() {
	$.post("../control/ajax_getcredits",
			function (data) {
				$("#credits").empty();
				$("#creditnames").empty();
				$("#creditotherstable tr:gt(0)").empty();
				var json = eval('(' + data + ')');
				var total_others = 0;
				for (var i = 0; i < json[0].length; i++) {
					add_cell("credits", json[0][i].username, json[0][i].percent);
				}
				for (var i = 0; i < json[1].length; i++) {
					add_other("credits", json[1][i].username, json[1][i].percent);
					total_others += json[1][i].percent;
				}
				if (total_others > 0) {
					add_cell("credits", "Others", total_others);
				}
				add_cell("credits", json[2][0].username, json[2][0].percent);
				$("#vesselscredits").text(json[3] + " vessels credits");
				$("#creditotherstable tr:odd").addClass("odd");
				$("#creditotherstable tr:even").addClass("even");
			},
			"json");
}

function update_shares() {
	$.post("../control/ajax_getshares",
			function (data) {
				$("#usage").empty();
				$("#usagenames").empty();
				$("#usageotherstable tr:gt(0)").empty();
				var json = eval('(' + data + ')');
				var total_percent = 0;
				var total_others = 0;
				for (var i = 0; i < json[0].length; i++) {
					add_cell("shares", json[0][i].username, json[0][i].percent);
					total_percent += json[0][i].percent;
				}
				for (var i = 0; i < json[1].length; i++) {
					add_other("shares", json[1][i].username, json[1][i].percent);
					total_others += json[1][i].percent;
				}
				total_percent += total_others + json[2][0].percent;
				if (total_others > 0) {
					add_cell("shares", "Others", total_others);
				}
				add_cell("shares", json[2][0].username, json[2][0].percent);
				add_cell("shares", "Free", 100 - total_percent);
				$("#vesselsavailable").text(json[3] + " vessels available");
				update_numvessels(json[3]);
				$("#usageotherstable tr:odd").addClass("odd");
				$("#usageotherstable tr:even").addClass("even");
			},
			"json");
}

function add_cell(type, username, percent) {
	if (type == "credits") {
		var block = create_block(username, percent, false);
		var label = create_label(username, percent, false);
		$("#credits").append(block);
		$("#creditnames").append(label);
	} else if (type == "shares") {
		var block = create_block(username, percent, true);
		var label = create_label(username, percent, true);
		$("#usage").append(block);
		$("#usagenames").append(label);
	}
}

function update_numvessels(number) {
	$("#numvessels").empty();
	for (var i = 1; i <= number; i++) {
		var option = $(document.createElement("option"));
		option.val(i);
		option.text(i);
		$("#numvessels").append(option);
	}
}
<commit_msg>refactored mygeni.js a little to make warning work better and check for invalid input values<commit_after>
$(document).ready(function() {
	update_credits();
	update_shares();
});

/*
	Create a block with given width and background color,
	and append it to the given bar element.
*/
function create_block(username, width, isShare) {
	var block = $(document.createElement('td'));
	block.css({
		'width': width + '%',
		'background-color': '#' + color_generator(username)
	});
	var percent = $(document.createElement('span'));
	percent.text(width + '%');

	if (isShare) {
		block.attr("id", "usage" + username);
		if (username == "Free" && width > 0) {
			var get = $(document.createElement('a'));
			get.attr('id','getresourcesbutton');
			get.attr('href', '../control/myvessels');
			get.text('get');
			// get.click(get_resources_dialog);
			block.append(get);

			var share = $(document.createElement('a'));
			share.attr('id','shareresourcesbutton');
			share.attr('href','#');
			share.text('share');
			share.click(share_resources_dialog);
			block.append(share);

		} else if (username != "Me" && username != "Others" ) {
			var close = $(document.createElement('a'));
			close.attr('href','#');
			close.text('x');
			close.click(function() {
				$.post("../control/ajax_editshare",
						{ username: username, percent: 0 },
						function (data) {
							var json = eval('(' + data + ')');
							if (json.success) {
								update_shares();
							} else {
								alert(json.error);
							}
						});
			});
			block.append(close);
			percent.attr("title", "Click to change percent");
			percent.tooltip({cssClass:"tooltip"});
			percent.css("cursor", "pointer");
			percent.click(function() {
				change_percent(username, width);
			});
		}
	}

	if (username == "Others") {
		percent.attr("title", "Click to reveal");
		percent.tooltip({cssClass:"tooltip"});
		percent.css("cursor", "pointer");
		percent.click(function () { show_table(isShare) });
		// block.attr("id", "creditOthers");
	}
	block.append(percent);
	return block;
}

/*
	Create a name label with given width and append it to
	the given name table.
*/
function create_label(username, width, isShare) {
	var label = $(document.createElement('td'));
	if (isShare) {
		label.attr("id", "labelusage" + username);
	}
	label.text(username);
	label.css({
		'width': width + '%'
	});
	return label;
}

function add_other(type, username, percent) {
	var table;
	if (type == "credits") {
		table = $("#creditotherstable");
	} else if (type == "shares") {
		table = $("#usageotherstable");
	}
	var tr = $(document.createElement("tr"));
	tr.html("" + username + "	" + percent + "	");
	if (type == "shares") {
		var control = $(document.createElement("td"));
		var edit = $(document.createElement("button"));
		edit.text("Edit");
		edit.click(function() {
			change_percent(username, percent);
		});
		var close = $(document.createElement("button"));
		close.text("Delete");
		close.click(function() {
			$.post("../control/ajax_editshare",
					{ username: username, percent: 0 },
					function(data) {
						var json = eval('(' + data + ')');
						if (json.success) {
							update_shares();
						} else {
							alert(json.error);
						}
					});
			tr.remove();
		});
		control.append(edit);
		control.append(close);
		tr.append(control);
	}
	table.append(tr);
}

/*
	Display the change percent dialog box
*/
function change_percent(username, current_percent) {
	var dialog = $(document.createElement("div"));
	dialog.attr("id", "changepercentdialog");
	dialog.html('
Change Percent
');
	var input = $(document.createElement("input"));
	input.attr("type", "text");
	input.val(current_percent);
	input.click(function () { $(this).val("") });
	var symbol = $(document.createElement("span"));
	symbol.html(" %
");
	var cancel = $(document.createElement("button"));
	cancel.text("Cancel");
	var save = $(document.createElement("button"));
	save.text("Save");
	cancel.click(function () {
		close_dialog();
		$(this).parent().remove();
	});
	save.click(function() {
		new_percent = parseInt(input.val());
		if (validate(current_percent, new_percent)) {
			save_percent(username, new_percent));
		}
	});
	dialog.append(input);
	dialog.append(symbol);
	dialog.append(cancel);
	dialog.append(save);
	$("#dialogframe").append(dialog);
	$("#dialogframe").fadeIn("fast");
	$("#overlay").fadeIn("fast");
	$("#changepercentdialog").fadeIn("fast");
}

/*
	Save the percent of the the block when click "save" on the
	change_percent dialog box
*/
function save_percent(username, percent) {
	$.post("../control/ajax_editshare",
			{ username: username, percent: percent },
			function (data) {
				var json = eval(data);
				if (json.success) {
					$("#changepercentdialog").remove();
					$("#dialogframe").hide();
					$("#overlay").hide();
					update_shares();
				} else {
					create_warning(json.error, $("#changepercentdialog h3"));
				}
	   		},
			"json");
}

/*
	make sure the new percent is within range of validity
*/
function validate(current_percent, new_percent) {
	var free = parseInt($("#usageFree span").text());
	return (new_percent - current_percent > free) && (new_percent >= 0);
}

/*
	Toggle display the tables for small percent users
*/
function show_table(isShare) {
	if (isShare) {
		$("#usageotherstable").toggle();
	} else {
		$("#creditotherstable").toggle();
	}
}

function get_resources_dialog() {
	$("#dialogframe").fadeIn("fast");
	$("#overlay").fadeIn("fast");
	$("#getresourcesdialog").fadeIn("fast");
	$(".cancel").click(close_dialog);
	$("#getresourcesaction").click(get_resources);
}

function share_resources_dialog() {
	$("#dialogframe").fadeIn("fast");
	$("#overlay").fadeIn("fast");
	$("#shareresourcesdialog").fadeIn("fast");
	$(".cancel").click(close_dialog);
	var username = $("#shareresourcesdialog #username").val();
	var percent = parseInt($("#shareresourcesdialog #percent").val());
	if ($("#shareresourcesdialog .warning")) {
	    $("#shareresourcesdialog .warning").remove();
	}
	if (validate(0, percent)) {
		$("#shareresources").click(share_resources);
	} else {
		create_warning("Percent must be a valid number", $("#shareresourcesdialog h3"));
	}
}

function close_dialog() {
    if ($(this).parent().children(".warning")) {
		$(this).parent().children(".warning").remove();
    }
	$(this).parent().hide();
	$("#dialogframe").hide();
	$("#overlay").hide();
}

function post_ajax(url, args, func) {
	$.post(url, args, function(data) {
		// check data
		// if data ok then:
		func(data)
		// else:
		// display content as raw html in a new popup
	});
}

function share_resources() {
	post_ajax("../control/ajax_createshare",
			{ username: username, percent: percent },
			function(data) {
				var json = eval('(' + data + ')');
				if (json.success) {
					$("#shareresourcesdialog").hide();
					$("#dialogframe").hide();
					$("#overlay").hide();
					update_shares();
				} else {
					create_warning(json.error, $("#shareresourcesdialog h3"));
				}
			});
}

function get_resources() {
	var numvessels = parseInt($("#numvessels").val());
	var env = parseInt($("#environment").val());
	if ($("#getresourcesdialog .warning")) {
	    $("#getresourcesdialog .warning").remove();
	}
	$.post("../control/ajax_getvessels",
			{ num: numvessels, env: env },
			function (data) {
				var json = eval('(' + data + ')');
				// alert(json.mypercent);
				// alert(json.success);
				if (json.success) {
					$("#getresourcesdialog").hide();
					$("#dialogframe").hide();
					$("#overlay").hide();
					update_shares();
				} else {
					create_warning(json.error, $("#getresourcesdialog h3"));
				}
			});
}

/*
	Create and insert a warning sign after the given position
*/

function create_warning(error, position) {
	var warning = $(document.createElement("p"));
	warning.html(error);
	warning.addClass("warning");
	warning.insertAfter(position);
}

/*
	Generate a color in hex notation for a username, which assigns different
	colors to different usernames.
*/
function color_generator(username) {
	var seeds = ['cc','ff'];
	var color = seeds[username.charCodeAt(0) % 2] +
				seeds[username.charCodeAt(1) % 2] +
				seeds[username.charCodeAt(username.length - 1) % 2];
	if (color == "ffffff") {
		color = "ffffcc";
	} else if (color == "cccccc") {
		color = "ccccff";
	}
	if (username == "Free") {
		color = "ffffff";
	} else if (username == "Me") {
		color = "cccccc";
	}
	return color;
}

function update_credits() {
	$.post("../control/ajax_getcredits",
			function (data) {
				$("#credits").empty();
				$("#creditnames").empty();
				$("#creditotherstable tr:gt(0)").empty();
				var json = eval('(' + data + ')');
				var total_others = 0;
				for (var i = 0; i < json[0].length; i++) {
					add_cell("credits", json[0][i].username, json[0][i].percent);
				}
				for (var i = 0; i < json[1].length; i++) {
					add_other("credits", json[1][i].username, json[1][i].percent);
					total_others += json[1][i].percent;
				}
				if (total_others > 0) {
					add_cell("credits", "Others", total_others);
				}
				add_cell("credits", json[2][0].username, json[2][0].percent);
				$("#vesselscredits").text(json[3] + " vessels credits");
				$("#creditotherstable tr:odd").addClass("odd");
				$("#creditotherstable tr:even").addClass("even");
			},
			"json");
}

function update_shares() {
	$.post("../control/ajax_getshares",
			function (data) {
				$("#usage").empty();
				$("#usagenames").empty();
				$("#usageotherstable tr:gt(0)").empty();
				var json = eval('(' + data + ')');
				var total_percent = 0;
				var total_others = 0;
				for (var i = 0; i < json[0].length; i++) {
					add_cell("shares", json[0][i].username, json[0][i].percent);
					total_percent += json[0][i].percent;
				}
				for (var i = 0; i < json[1].length; i++) {
					add_other("shares", json[1][i].username, json[1][i].percent);
					total_others += json[1][i].percent;
				}
				total_percent += total_others + json[2][0].percent;
				if (total_others > 0) {
					add_cell("shares", "Others", total_others);
				}
				add_cell("shares", json[2][0].username, json[2][0].percent);
				add_cell("shares", "Free", 100 - total_percent);
				$("#vesselsavailable").text(json[3] + " vessels available");
				update_numvessels(json[3]);
				$("#usageotherstable tr:odd").addClass("odd");
				$("#usageotherstable tr:even").addClass("even");
			},
			"json");
}

function add_cell(type, username, percent) {
	if (type == "credits") {
		var block = create_block(username, percent, false);
		var label = create_label(username, percent, false);
		$("#credits").append(block);
		$("#creditnames").append(label);
	} else if (type == "shares") {
		var block = create_block(username, percent, true);
		var label = create_label(username, percent, true);
		$("#usage").append(block);
		$("#usagenames").append(label);
	}
}

function update_numvessels(number) {
	$("#numvessels").empty();
	for (var i = 1; i <= number; i++) {
		var option = $(document.createElement("option"));
		option.val(i);
		option.text(i);
		$("#numvessels").append(option);
	}
}
<|endoftext|>


<commit_before>//Imports
import React from "react";
import { Container, Row, Col } from "reactstrap";
import i18n from "/imports/both/i18n/en/";
import DCSBalloon from '/imports/client/ui/components/DCSBalloon/index.js'

const Content = (props) => {
  return (
    <React.Fragment>
      <Container className="mt-5">

Looking for answers?

          Take a look at frequently asked questions

      </Container>
      {i18n.Whitepaper.Why.faq.map((item, index) => {
        return (
          <Col key={index} className="ml-5 pl-5 mt-5" xs={11}>

{item.heading}

{item.text}

            <DCSBalloon title=" " subtitle="discuss" balloonId="bal1" display="inline" dcsTags={props.dcsTags} />
          </Col>
        );
      })}
    </React.Fragment>
  );
};

export default Content;
<commit_msg>changed header<commit_after>//Imports
import React from "react";
import { Container, Row, Col } from "reactstrap";
import i18n from "/imports/both/i18n/en/";
import DCSBalloon from '/imports/client/ui/components/DCSBalloon/index.js'

const Content = (props) => {
  return (
    <React.Fragment>
      <Container className="mt-5">

The World Needs a Public Happiness Economy Because:

      </Container>
      {i18n.Whitepaper.Why.faq.map((item, index) => {
        return (
          <Col key={index} className="ml-5 pl-5 mt-5" xs={11}>

{item.heading}

{item.text}

            <DCSBalloon title=" " subtitle="discuss" balloonId="bal1" display="inline" dcsTags={props.dcsTags} />
          </Col>
        );
      })}
    </React.Fragment>
  );
};

export default Content;
<|endoftext|>


<commit_before>/* eslint no-bitwise: ["error", { "allow": ["^=", "&"] }] */

angular.module('breadcrumb')
.controller('ProfileCtrl', function ($scope, ListFact, Data, store) {
  $scope.user = store.get('user');
  // $scope.user.pic = JSON.parse(localStorage.profile).picture;

  $scope.userPic = {
    'background-image': `url('${JSON.parse(localStorage.profile).picture}')`,
    'background-position': 'center',
    'background-size': 'cover',
  };

  $scope.userTrails = [
    Data.trail(),
    Data.trail(),
    Data.trail(),
  ];

  $scope.pastTrails = [
    Data.trail(),
    Data.trail(),
    Data.trail(),
  ];
});
<commit_msg>(feature) profile page now takes picture link form user object in localstorage`<commit_after>/* eslint no-bitwise: ["error", { "allow": ["^=", "&"] }] */

angular.module('breadcrumb')
.controller('ProfileCtrl', function ($scope, ListFact, Data, store) {
  $scope.user = store.get('user');
  // $scope.user.pic = JSON.parse(localStorage.profile).picture;

  $scope.userPic = {
    'background-image': `url('${store.get('user').profile_picture}')`,
    'background-position': 'center',
    'background-size': 'cover',
  };

  $scope.userTrails = [
    Data.trail(),
    Data.trail(),
    Data.trail(),
  ];

  $scope.pastTrails = [
    Data.trail(),
    Data.trail(),
    Data.trail(),
  ];
});
<|endoftext|>


<commit_before>
/*
	Object: ui.controller.window
		Window controller. It handles windows cascading position, minimize position, focusing, ...

	Arguments:
		options - (object)

	Options:
		zBase - (integer)
		zStep - (integer)
		cascade - (object)
		stack - (object)

	Requires:
		<UI.Window>

	Implied global:
		ui,
		window

	Discussion:
		Stacks should be better implemented

*/

ui.window = {
	options: {
		version: '0.1',
		zBase: 1000,
		zStep: 2,
		container: document.body,
		cascade: {
			start: {
				x: 51,
				y: 101
			},
			step: {
				x: 20,
				y: 20
			},
			offset : [170,50]
		},
		stack: {
			offset: {
				x: 16,
				y: 16
			}
		},
		underlay: {

		},
		minimized: {
			coord: {
				width: 160,
				height: 50,
				bottom: -10,
				left: 32,
				offset: {
					x: 16
				}
			}
		},
		maximized: {
			coord: {
				width: 960,
				height: 760,
				top: 'auto',
				left: 'auto'
			}
		},
		normalized: {
			coord: {
				width: 220,
				height: 360,
				bottom: 10,
				top: 'auto',
				left: ''
			}
		}
	},

	/*
	Constructor: initialize
		Construtor

	Arguments:
		options - (object) options

	Returns:
		(void)
	*/

	init: function(container){
		this.container = container;
		this.list = [];
		this.zIndex = this.options.zBase;
		this.group = {};

		//this.buildunderlay();

		window.addEvent('resize', function(){ this.resizeMaximizedWindow(); }.bind(this));
	},

	/*
	Function: register
		Add passing window to the manage list

	Arguments:
		win - (object) the window class instance to register

	Returns:
		(void)
	*/

	register: function(win, group) {
		_log('register', win);
		this.list.push(win);

		if (group) {
			if (this.group[group])
				this.group[group] = [];

			this.group[group].push(win);
		}

		if (win.options.zIndex == 'auto') {
			win.element.setStyle('zIndex', this.zIndex);
			win.altitude = this.zIndex;
		}
		else {
			win.element.setStyle('zIndex', win.options.zIndex);
		}
		this.zIndex += this.options.zStep;
	},

	/*
	Function: close
		Destroy the provided window and focus to next one

	Arguments:
		win - (object) the window class instance to close and destroy

	Returns:
		(void)
	*/

	close: function(win) {
		win = win || this.active;
		win.hide();
		win.fireEvent('onClose');
		for (var i = this.list.length - 1; i >= 0; i--) {
			if (this.list[i] == win) {
				win.destroy();
				delete this.list[i];
				this.list = this.list.clean();
			}
		}
		this.focus();
	},

	/*
	Function: focus
		Increment max z-index and focus provided window

	Arguments:
		win - (object) the window class instance to focus

	Returns:
		(void)
	*/
	focus: function(win) {
		//_log('focus', win);
		if (win === null) {
			//make next highest window focus
			var zIndex = 0;
			for (var i = this.list.length - 1; i >= 0; i--) {
				var windowZIndex = this.list[i].element.getStyle('zIndex');
				if (windowZIndex >= zIndex && !this.list[i].minimized) {
					win = this.list[i];
					zIndex = windowZIndex;
				}
			}

			if (win) {
				win.focus();
			}

			return;
		} else if (win && this.active != win) {
			if (this.active && !this.active.minimized) {
				this.blur(this.active);
			}

			this.zIndex += this.options.zStep;
			win.element.style.zIndex = this.zIndex;
			win.element.style.zoom = '1';

			this.active = win;
			win.fireEvent('focus');

			//_log('focus', win, win.grid, win.coord);
			if (win.grid) {
				this.list.each(function(w){
					win.setStyles(coord);
				});
			}

			return;
		}
	},

	/*
	Function: blur
		Blur active window

	Arguments:
		win - (object) the window class instance to blur

	Returns:
		(void)
	*/
	blur: function(win) {
		if ((win !== null) && !win.minimized) {
			win.setState('inactive');
			win.fireEvent('onBlur');
		} else if (this.active) {
			this.blur(this.active);
		}
	},

	minimize: function(win) {
		w = win || this.active;
		w.minimize();
	},

	/*
	Function: getMinimizedLocation
		Return the position of next minimized window

	Returns:
		location - (array) Array containing left and top position
	 */
	getcoord: function(etat) {
		var opts = ui.window.options;
		var x = 0;
		//_log('getcoord:', opts[etat]);
		var coord = opts[etat].coord;
		x += coord.left;

		this.list.each(function(w, i) {
			if (w.state == etat) {

				//_log('getStackCoord:', i, x, coord.width,coord.offset);

				x += (coord.width) + coord.offset.x;
			}
		});

	//	coord.offset = null;

	//	coord.left = x;

		return {
			width: coord.width,
			height: coord.height,
			bottom: coord.bottom,
			top: 'auto',
			left: x
		};
	},

	/*
	Function: resetMinimizedLocation
		Replace minimized windows

	Returns:
		(void)
	*/
	resetMinimized : function(){
		var etat = 'minimized',
			opts = ui.window.options,
			coord = opts[etat].coord;

		var x = 0;
		var y = coord.bottom;

		this.list.each(function(win, i) {
			if (win.state == 'minimized') {
				x += coord.width + coord.offset.x;
				win.setLocation(x, y);
			}
		});
	},

	/*
	Function: resizeMaximizedWindow
		Set new maximized size for all mamimized window

	Returns:
		(void)
	*/
	resizeMaximizedWindow: function(){
		this.list.each(function(win) {
			if (win.state == 'maximized') {
				win.setSize({
					height: window.getHeight()-32,
					width: window.getWidth()
				});
			}
		});
	},

	/*
	Function: getCascadeLocation
		Calculate the location of the window in the cascade

	Arguments:
		win - (object) the window class instance to get location

	Returns:
		location - (object) location coordinates { left : 100, top : 100 }
	*/
	getCascadeLocation: function(win){
		var location = {
			left : 71,
			top : 121
		};

		this.list.each(function(w,i) {
			if (w.state != 'minimized' && w.options.location == 'cascade') {
				location.left += this.options.cascade.step.x;
				location.top += this.options.cascade.step.y;
			}
		},this);
		return location;
	},

	/*
	Function: cascade
		Move every windows to its position in the cascade

	Returns:
		(void)
	*/
	cascade: function(group){
		var start = [51,101];
		var offset = [20,20];
		var zIndex = this.zIndex;
		var last;
		var list = [];

		if (group)
			list = this.group;
		else list = this.list;

		list.each(function(win){
			if (win.state == 'minimized')
				return;

			win.element.style.zIndex = zIndex++;

			start[0] += offset[0];
			start[1] += offset[1];

			win.element.morph({
				'left': start[0],
				'top': start[1]
			});

			win.location = 'cascade';
			last = win;
		});

		this.zIndex = zIndex;
	},

	/*
	Function: circle
		Move every windows to its position in the cascade

	Returns:
		(void)
	*/
	circle: function(group){
		//should be define in the skin sheet
		var center = [200,300];
		var offset = [];
		var radius = 200;
		var zIndex = this.zIndex;

		var i = 1;
		var length = (this.list.length);

		this.list.each(function(win){
			//if (win.state = 'minimized') return;

			win.element.style.zIndex = zIndex++;
			win.element.style.zoom = '1';

			var ratio = i/length*2;

			offset[0] = Math.cos(ratio*Math.PI);
			offset[1] = Math.sin(ratio*Math.PI);

			var left = center[0] + offset[0] * radius;
			var top = center[1] + offset[1] * radius;

			i++;

			win.element.morph({
				top: top,
				left: left
			});

			win.adaptLocation();
			win.location = 'circle';
		});

		this.zIndex = zIndex;
	},

	grid: function(group){
		//should be define in the skin sheet
		var size = [160,240],
			start = [100,100];
			offset = [20,20];
			zIndex = this.zIndex;
			row = 0;
			column = 0;
			coord= {};

		var length = (this.list.length);

		this.list.each(function(win, i){
			//if (win.state = 'minimized') return;

			win.element.style.zIndex = zIndex++;
			win.coord = win.getCoordinates();

			coord.left = start[0] + (offset[0] + size[0]) * column;

			//_log(column);

			if (coord.left > 1000) {
				coord.left = start[0];
				row++;
				column = 0;
			}

			coord.top = start[1] + (offset[1] + size[1]) * row;
			coord.width = size[0];
			coord.height = size[1];

			win.element.morph(coord);
			column++;
			win.adaptLocation();
			win.location = 'grid';

		});

		this.zIndex = zIndex;
	},

	closeall: function(){
		this.list.each(function(win){
			this.close(win);
		},this);
	},

	/*
	Function: buildunderlay
		_initElement an overlay for windows

	Arguments:

	Returns:
		(void)
	*/
	buildunderlay: function(container) {
		var  opts = this.options.underlay;

		// should use ui.builder

		this.underlay = new Element('div', {
			'class': 'ui-underlay'
		}).inject(this.container);

		this.underlay.hide();
	},

	/*
	Function: buildunderlay
		_initElement an overlay for windows

	Arguments:

	Returns:
		(void)
	*/
	showunderlay: function(win) {
		this.underlay.setStyles({
			display: 'block',
			'zIndex': win.altitude
		});
	}
};

window.addEvent('domready', function() {
    ui.window.init(document.body);
});

<commit_msg>Improve mailing send + fix mailing when a contact node is removed + remove consoles<commit_after>
/*
	Object: ui.controller.window
		Window controller. It handles windows cascading position, minimize position, focusing, ...

	Arguments:
		options - (object)

	Options:
		zBase - (integer)
		zStep - (integer)
		cascade - (object)
		stack - (object)

	Requires:
		<UI.Window>

	Implied global:
		ui,
		window

	Discussion:
		Stacks should be better implemented

*/

ui.window = {
	options: {
		version: '0.1',
		zBase: 1000,
		zStep: 2,
		container: document.body,
		cascade: {
			start: {
				x: 51,
				y: 101
			},
			step: {
				x: 20,
				y: 20
			},
			offset : [170,50]
		},
		stack: {
			offset: {
				x: 16,
				y: 16
			}
		},
		underlay: {

		},
		minimized: {
			coord: {
				width: 160,
				height: 50,
				bottom: -10,
				left: 32,
				offset: {
					x: 16
				}
			}
		},
		maximized: {
			coord: {
				width: 960,
				height: 760,
				top: 'auto',
				left: 'auto'
			}
		},
		normalized: {
			coord: {
				width: 220,
				height: 360,
				bottom: 10,
				top: 'auto',
				left: ''
			}
		}
	},

	/*
	Constructor: initialize
		Construtor

	Arguments:
		options - (object) options

	Returns:
		(void)
	*/

	init: function(container){
		this.container = container;
		this.list = [];
		this.zIndex = this.options.zBase;
		this.group = {};

		//this.buildunderlay();

		window.addEvent('resize', function(){ this.resizeMaximizedWindow(); }.bind(this));
	},

	/*
	Function: register
		Add passing window to the manage list

	Arguments:
		win - (object) the window class instance to register

	Returns:
		(void)
	*/

	register: function(win, group) {
		//_log('register', win);
		this.list.push(win);

		if (group) {
			if (this.group[group])
				this.group[group] = [];

			this.group[group].push(win);
		}

		if (win.options.zIndex == 'auto') {
			win.element.setStyle('zIndex', this.zIndex);
			win.altitude = this.zIndex;
		}
		else {
			win.element.setStyle('zIndex', win.options.zIndex);
		}
		this.zIndex += this.options.zStep;
	},

	/*
	Function: close
		Destroy the provided window and focus to next one

	Arguments:
		win - (object) the window class instance to close and destroy

	Returns:
		(void)
	*/

	close: function(win) {
		win = win || this.active;
		win.hide();
		win.fireEvent('onClose');
		for (var i = this.list.length - 1; i >= 0; i--) {
			if (this.list[i] == win) {
				win.destroy();
				delete this.list[i];
				this.list = this.list.clean();
			}
		}
		this.focus();
	},

	/*
	Function: focus
		Increment max z-index and focus provided window

	Arguments:
		win - (object) the window class instance to focus

	Returns:
		(void)
	*/
	focus: function(win) {
		//_log('focus', win);
		if (win === null) {
			//make next highest window focus
			var zIndex = 0;
			for (var i = this.list.length - 1; i >= 0; i--) {
				var windowZIndex = this.list[i].element.getStyle('zIndex');
				if (windowZIndex >= zIndex && !this.list[i].minimized) {
					win = this.list[i];
					zIndex = windowZIndex;
				}
			}

			if (win) {
				win.focus();
			}

			return;
		} else if (win && this.active != win) {
			if (this.active && !this.active.minimized) {
				this.blur(this.active);
			}

			this.zIndex += this.options.zStep;
			win.element.style.zIndex = this.zIndex;
			win.element.style.zoom = '1';

			this.active = win;
			win.fireEvent('focus');

			//_log('focus', win, win.grid, win.coord);
			if (win.grid) {
				this.list.each(function(w){
					win.setStyles(coord);
				});
			}

			return;
		}
	},

	/*
	Function: blur
		Blur active window

	Arguments:
		win - (object) the window class instance to blur

	Returns:
		(void)
	*/
	blur: function(win) {
		if ((win !== null) && !win.minimized) {
			win.setState('inactive');
			win.fireEvent('onBlur');
		} else if (this.active) {
			this.blur(this.active);
		}
	},

	minimize: function(win) {
		w = win || this.active;
		w.minimize();
	},

	/*
	Function: getMinimizedLocation
		Return the position of next minimized window

	Returns:
		location - (array) Array containing left and top position
	 */
	getcoord: function(etat) {
		var opts = ui.window.options;
		var x = 0;
		//_log('getcoord:', opts[etat]);
		var coord = opts[etat].coord;
		x += coord.left;

		this.list.each(function(w, i) {
			if (w.state == etat) {

				//_log('getStackCoord:', i, x, coord.width,coord.offset);

				x += (coord.width) + coord.offset.x;
			}
		});

	//	coord.offset = null;

	//	coord.left = x;

		return {
			width: coord.width,
			height: coord.height,
			bottom: coord.bottom,
			top: 'auto',
			left: x
		};
	},

	/*
	Function: resetMinimizedLocation
		Replace minimized windows

	Returns:
		(void)
	*/
	resetMinimized : function(){
		var etat = 'minimized',
			opts = ui.window.options,
			coord = opts[etat].coord;

		var x = 0;
		var y = coord.bottom;

		this.list.each(function(win, i) {
			if (win.state == 'minimized') {
				x += coord.width + coord.offset.x;
				win.setLocation(x, y);
			}
		});
	},

	/*
	Function: resizeMaximizedWindow
		Set new maximized size for all mamimized window

	Returns:
		(void)
	*/
	resizeMaximizedWindow: function(){
		this.list.each(function(win) {
			if (win.state == 'maximized') {
				win.setSize({
					height: window.getHeight()-32,
					width: window.getWidth()
				});
			}
		});
	},

	/*
	Function: getCascadeLocation
		Calculate the location of the window in the cascade

	Arguments:
		win - (object) the window class instance to get location

	Returns:
		location - (object) location coordinates { left : 100, top : 100 }
	*/
	getCascadeLocation: function(win){
		var location = {
			left : 71,
			top : 121
		};

		this.list.each(function(w,i) {
			if (w.state != 'minimized' && w.options.location == 'cascade') {
				location.left += this.options.cascade.step.x;
				location.top += this.options.cascade.step.y;
			}
		},this);
		return location;
	},

	/*
	Function: cascade
		Move every windows to its position in the cascade

	Returns:
		(void)
	*/
	cascade: function(group){
		var start = [51,101];
		var offset = [20,20];
		var zIndex = this.zIndex;
		var last;
		var list = [];

		if (group)
			list = this.group;
		else list = this.list;

		list.each(function(win){
			if (win.state == 'minimized')
				return;

			win.element.style.zIndex = zIndex++;

			start[0] += offset[0];
			start[1] += offset[1];

			win.element.morph({
				'left': start[0],
				'top': start[1]
			});

			win.location = 'cascade';
			last = win;
		});

		this.zIndex = zIndex;
	},

	/*
	Function: circle
		Move every windows to its position in the cascade

	Returns:
		(void)
	*/
	circle: function(group){
		//should be define in the skin sheet
		var center = [200,300];
		var offset = [];
		var radius = 200;
		var zIndex = this.zIndex;

		var i = 1;
		var length = (this.list.length);

		this.list.each(function(win){
			//if (win.state = 'minimized') return;

			win.element.style.zIndex = zIndex++;
			win.element.style.zoom = '1';

			var ratio = i/length*2;

			offset[0] = Math.cos(ratio*Math.PI);
			offset[1] = Math.sin(ratio*Math.PI);

			var left = center[0] + offset[0] * radius;
			var top = center[1] + offset[1] * radius;

			i++;

			win.element.morph({
				top: top,
				left: left
			});

			win.adaptLocation();
			win.location = 'circle';
		});

		this.zIndex = zIndex;
	},

	grid: function(group){
		//should be define in the skin sheet
		var size = [160,240],
			start = [100,100];
			offset = [20,20];
			zIndex = this.zIndex;
			row = 0;
			column = 0;
			coord= {};

		var length = (this.list.length);

		this.list.each(function(win, i){
			//if (win.state = 'minimized') return;

			win.element.style.zIndex = zIndex++;
			win.coord = win.getCoordinates();

			coord.left = start[0] + (offset[0] + size[0]) * column;

			//_log(column);

			if (coord.left > 1000) {
				coord.left = start[0];
				row++;
				column = 0;
			}

			coord.top = start[1] + (offset[1] + size[1]) * row;
			coord.width = size[0];
			coord.height = size[1];

			win.element.morph(coord);
			column++;
			win.adaptLocation();
			win.location = 'grid';

		});

		this.zIndex = zIndex;
	},

	closeall: function(){
		this.list.each(function(win){
			this.close(win);
		},this);
	},

	/*
	Function: buildunderlay
		_initElement an overlay for windows

	Arguments:

	Returns:
		(void)
	*/
	buildunderlay: function(container) {
		var  opts = this.options.underlay;

		// should use ui.builder

		this.underlay = new Element('div', {
			'class': 'ui-underlay'
		}).inject(this.container);

		this.underlay.hide();
	},

	/*
	Function: buildunderlay
		_initElement an overlay for windows

	Arguments:

	Returns:
		(void)
	*/
	showunderlay: function(win) {
		this.underlay.setStyles({
			display: 'block',
			'zIndex': win.altitude
		});
	}
};

window.addEvent('domready', function() {
    ui.window.init(document.body);
});

<|endoftext|>


<commit_before>var Backbone = require('backbone');
var cdb = require('internal-carto.js');
var _ = require('underscore');
var moment = require('moment');
var checkAndBuildOpts = require('builder/helpers/required-opts');
var QUERY_TEMPLATE = _.template('SELECT MAX(<%= column %>), MIN(<%= column %>) FROM (<%= table %>) __wrapped');

var STATUS = {
  unavailable: 'unavailable',
  unfetched: 'unfetched',
  fetching: 'fetching',
  fetched: 'fetched'
};

var DEFAULT_MAX_BUCKETS = 367;

var REQUIRED_OPTS = [
  'configModel',
  'querySchemaModel'
];

module.exports = Backbone.Model.extend({
  defaults: {
    status: STATUS.unfetched,
    buckets: []
  },

  initialize: function (attrs, opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);

    if (!_.has(attrs, 'column')) {
      throw new Error('Column is required');
    }

    this._SQL = new cdb.SQL({
      user: this._configModel.get('user_name'),
      sql_api_template: this._configModel.get('sql_api_template'),
      api_key: this._configModel.get('api_key')
    });

    this._initBinds();

    if (this._querySchemaModel.get('status') === STATUS.fetched) {
      this._queryData();
    }
  },

  _initBinds: function () {
    this.on('change:column', this._queryData, this);
    this.listenTo(this._querySchemaModel, 'change:status', this._onQuerySchemaStatusChanged);
  },

  _onQuerySchemaStatusChanged: function () {
    if (this._querySchemaModel.get('status') === STATUS.fetched) {
      this._queryData();
    }
  },

  _queryData: function () {
    if (this._querySchemaModel.getColumnType(this.get('column')) !== 'date') {
      return;
    }

    var query = QUERY_TEMPLATE({
      column: this.get('column'),
      table: this._querySchemaModel.get('query')
    });

    var callback = {
      success: this._onQuerySuccess.bind(this),
      error: this._onQueryError.bind(this)
    };

    this.set('status', STATUS.fetching);
    this._SQL.execute(query, null, callback);
  },

  _onQuerySuccess: function (data) {
    this.set('status', STATUS.fetched);
    var row = data.rows && data.rows[0];
    var max = row && row.max ? row.max : 0;
    var min = row && row.min ? row.min : 0;
    this._calculateBuckets(max, min);
  },

  _onQueryError: function () {
    this.set('status', STATUS.unavailable);
  },

  _calculateDecadesDiff: function (start, end) {
    var startYear = start.year();
    var endYear = end.year();
    var startDecade = Math.floor(startYear / 10);
    var endDecade = Math.floor((endYear + 10) / 10);

    return endDecade - startDecade;
  },

  _calculateBuckets: function (max, min) {
    var end = moment(max);
    var start = moment(min);
    var BUCKET_INCREMENT = 1;

    var buckets = [{
      bins: end.diff(start, 'minutes', true),
      val: 'minute',
      label: 'Minutes'
    }, {
      bins: end.diff(start, 'hours', true),
      val: 'hour',
      label: 'Hours'
    }, {
      bins: end.diff(start, 'days', true),
      val: 'day',
      label: 'Days'
    }, {
      bins: end.diff(start, 'weeks', true),
      val: 'week',
      label: 'Weeks'
    }, {
      bins: end.diff(start, 'months', true),
      val: 'month',
      label: 'Months'
    }, {
      bins: end.diff(start, 'quarters', true),
      val: 'quarter',
      label: 'Quarters'
    }, {
      bins: end.diff(start, 'years', true),
      val: 'year',
      label: 'Years'
    }, {
      bins: this._calculateDecadesDiff(start, end),
      val: 'decade',
      label: 'Decades'
    }];

    var incrementedBuckets = _.map(buckets, function (bucket) {
      var increment = bucket.val === 'decade'
        ? 0
        : BUCKET_INCREMENT;

      return _.extend(_.clone(bucket), {
        bins: Math.ceil(bucket.bins) + increment
      });
    });

    this.set('buckets', incrementedBuckets);
  },

  getFilteredBuckets: function (max) {
    var limit = max || DEFAULT_MAX_BUCKETS;
    var buckets = _.filter(this.get('buckets'), function (bucket) {
      return bucket.bins <= limit;
    });

    return buckets;
  },

  getPreferredBucket: function (max) {
    var sortedBuckets = _.sortBy(this.getFilteredBuckets(max), 'bins');
    return sortedBuckets.length > 0 ? sortedBuckets[sortedBuckets.length - 1] : {};
  }
});
<commit_msg>Fix date calculations affected by local times<commit_after>var Backbone = require('backbone');
var cdb = require('internal-carto.js');
var _ = require('underscore');
var moment = require('moment');
var checkAndBuildOpts = require('builder/helpers/required-opts');
var QUERY_TEMPLATE = _.template('SELECT MAX(<%= column %>), MIN(<%= column %>) FROM (<%= table %>) __wrapped');

var STATUS = {
  unavailable: 'unavailable',
  unfetched: 'unfetched',
  fetching: 'fetching',
  fetched: 'fetched'
};

var DEFAULT_MAX_BUCKETS = 367;

var REQUIRED_OPTS = [
  'configModel',
  'querySchemaModel'
];

module.exports = Backbone.Model.extend({
  defaults: {
    status: STATUS.unfetched,
    buckets: []
  },

  initialize: function (attrs, opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);

    if (!_.has(attrs, 'column')) {
      throw new Error('Column is required');
    }

    this._SQL = new cdb.SQL({
      user: this._configModel.get('user_name'),
      sql_api_template: this._configModel.get('sql_api_template'),
      api_key: this._configModel.get('api_key')
    });

    this._initBinds();

    if (this._querySchemaModel.get('status') === STATUS.fetched) {
      this._queryData();
    }
  },

  _initBinds: function () {
    this.on('change:column', this._queryData, this);
    this.listenTo(this._querySchemaModel, 'change:status', this._onQuerySchemaStatusChanged);
  },

  _onQuerySchemaStatusChanged: function () {
    if (this._querySchemaModel.get('status') === STATUS.fetched) {
      this._queryData();
    }
  },

  _queryData: function () {
    if (this._querySchemaModel.getColumnType(this.get('column')) !== 'date') {
      return;
    }

    var query = QUERY_TEMPLATE({
      column: this.get('column'),
      table: this._querySchemaModel.get('query')
    });

    var callback = {
      success: this._onQuerySuccess.bind(this),
      error: this._onQueryError.bind(this)
    };

    this.set('status', STATUS.fetching);
    this._SQL.execute(query, null, callback);
  },

  _onQuerySuccess: function (data) {
    this.set('status', STATUS.fetched);
    var row = data.rows && data.rows[0];
    var max = row && row.max ? row.max : 0;
    var min = row && row.min ? row.min : 0;
    this._calculateBuckets(max, min);
  },

  _onQueryError: function () {
    this.set('status', STATUS.unavailable);
  },

  _calculateDecadesDiff: function (start, end) {
    var startYear = start.year();
    var endYear = end.year();
    var startDecade = Math.floor(startYear / 10);
    var endDecade = Math.floor((endYear + 10) / 10);

    return endDecade - startDecade;
  },

  _calculateBuckets: function (max, min) {
    var end = moment(max).utc();
    var start = moment(min).utc();
    var BUCKET_INCREMENT = 1;

    var buckets = [{
      bins: end.diff(start, 'minutes', true),
      val: 'minute',
      label: 'Minutes'
    }, {
      bins: end.diff(start, 'hours', true),
      val: 'hour',
      label: 'Hours'
    }, {
      bins: end.diff(start, 'days', true),
      val: 'day',
      label: 'Days'
    }, {
      bins: end.diff(start, 'weeks', true),
      val: 'week',
      label: 'Weeks'
    }, {
      bins: end.diff(start, 'months', true),
      val: 'month',
      label: 'Months'
    }, {
      bins: end.diff(start, 'quarters', true),
      val: 'quarter',
      label: 'Quarters'
    }, {
      bins: end.diff(start, 'years', true),
      val: 'year',
      label: 'Years'
    }, {
      bins: this._calculateDecadesDiff(start, end),
      val: 'decade',
      label: 'Decades'
    }];

    var incrementedBuckets = _.map(buckets, function (bucket) {
      var increment = bucket.val === 'decade'
        ? 0
        : BUCKET_INCREMENT;

      return _.extend(_.clone(bucket), {
        bins: Math.ceil(bucket.bins) + increment
      });
    });

    this.set('buckets', incrementedBuckets);
  },

  getFilteredBuckets: function (max) {
    var limit = max || DEFAULT_MAX_BUCKETS;
    var buckets = _.filter(this.get('buckets'), function (bucket) {
      return bucket.bins <= limit;
    });

    return buckets;
  },

  getPreferredBucket: function (max) {
    var sortedBuckets = _.sortBy(this.getFilteredBuckets(max), 'bins');
    return sortedBuckets.length > 0 ? sortedBuckets[sortedBuckets.length - 1] : {};
  }
});
<|endoftext|>


<commit_before><commit_msg>added starts with extension<commit_after>(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('localforage')) :
    typeof define === 'function' && define.amd ? define(['exports', 'localforage'], factory) :
    (factory((global.localforageStartsWith = global.localforageStartsWith || {}),global.localforage));
}(this, function (exports,localforage) { 'use strict';

    localforage = 'default' in localforage ? localforage['default'] : localforage;

    function getSerializerPromise(localForageInstance) {
        if (getSerializerPromise.result) {
            return getSerializerPromise.result;
        }
        if (!localForageInstance || typeof localForageInstance.getSerializer !== 'function') {
            return Promise.reject(new Error('localforage.getSerializer() was not available! ' + 'localforage v1.4+ is required!'));
        }
        getSerializerPromise.result = localForageInstance.getSerializer();
        return getSerializerPromise.result;
    }

    function executeCallback(promise, callback) {
        if (callback) {
            promise.then(function (result) {
                callback(null, result);
            }, function (error) {
                callback(error);
            });
        }
    }

    function getItemKeyValue(key, callback) {
        var localforageInstance = this;
        var promise = localforageInstance.getItem(key).then(function (value) {
            return {
                key: key,
                value: value
            };
        });
        executeCallback(promise, callback);
        return promise;
    }

    function getIDBKeyRange() {
        /* global IDBKeyRange, webkitIDBKeyRange, mozIDBKeyRange */
        if (typeof IDBKeyRange !== 'undefined') {
            return IDBKeyRange;
        }
        if (typeof webkitIDBKeyRange !== 'undefined') {
            return webkitIDBKeyRange;
        }
        if (typeof mozIDBKeyRange !== 'undefined') {
            return mozIDBKeyRange;
        }
    }

    var idbKeyRange = getIDBKeyRange();

    function startsWith(prefix, callback) {
        var localforageInstance = this;
        var promise = new Promise(function (resolve, reject) {
            localforageInstance.ready().then(function () {
                // Thanks https://hacks.mozilla.org/2014/06/breaking-the-borders-of-indexeddb/
                var dbInfo = localforageInstance._dbInfo;
                var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);

                var keyRangeValue = idbKeyRange.bound(prefix, prefix + 'uffff', false, false);

                var result = {};
                var req = store.openCursor(keyRangeValue);
                req.onsuccess = function () /*event*/{
                    var cursor = req.result; // event.target.result;

                    if (cursor) {
                        var value = cursor.value;
                        if (value === undefined) {
                            value = null;
                        }

                        result[cursor.key] = value;

                        cursor.continue();
                    } else {
                        resolve(result);
                    }
                };

                req.onerror = function () /*event*/{
                    reject(req.error);
                };
            }).catch(reject);
        });
        executeCallback(promise, callback);
        return promise;
    }

    function keysStartingWith(prefix, callback) {
        var localforageInstance = this;
        var promise = new Promise(function (resolve, reject) {
            localforageInstance.ready().then(function () {
                // Thanks https://hacks.mozilla.org/2014/06/breaking-the-borders-of-indexeddb/
                var dbInfo = localforageInstance._dbInfo;
                var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName);

                var keyRangeValue = idbKeyRange.bound(prefix, prefix + 'uffff', false, false);

                var result = [];

                if (typeof store.getAllKeys === 'function') {
                    (function () {
                        var req = store.getAllKeys(keyRangeValue);
                        req.onsuccess = function () /*event*/{
                            resolve(req.result);
                        };

                        req.onerror = function () /*event*/{
                            reject(req.error);
                        };
                    })();
                } else {
                    (function () {
                        var req = store.openCursor(keyRangeValue);
                        req.onsuccess = function () /*event*/{
                            var cursor = req.result; // event.target.result;

                            if (cursor) {
                                result.push(cursor.key);

                                cursor.continue();
                            } else {
                                resolve(result);
                            }
                        };

                        req.onerror = function () /*event*/{
                            reject(req.error);
                        };
                    })();
                }
            }).catch(reject);
        });
        executeCallback(promise, callback);
        return promise;
    }

    function startsWith$1(prefix, callback) {
        var localforageInstance = this;
        var promise = new Promise(function (resolve, reject) {
            localforageInstance.ready().then(function () {
                return getSerializerPromise(localforageInstance);
            }).then(function (serializer) {
                var dbInfo = localforageInstance._dbInfo;
                dbInfo.db.transaction(function (t) {
                    t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE (key LIKE ?)', [prefix + '%'], function (t, results) {

                        var result = {};

                        var rows = results.rows;
                        for (var i = 0, len = rows.length; i < len; i++) {
                            var item = rows.item(i);
                            var value = item.value;

                            // Check to see if this is serialized content we need to
                            // unpack.
                            if (value) {
                                value = serializer.deserialize(value);
                            }

                            result[item.key] = value;
                        }

                        resolve(result);
                    }, function (t, error) {
                        reject(error);
                    });
                });
            }).catch(reject);
        });
        executeCallback(promise, callback);
        return promise;
    }

    function keysStartingWith$1(prefix, callback) {
        var localforageInstance = this;
        var promise = new Promise(function (resolve, reject) {
            localforageInstance.ready().then(function () {
                var dbInfo = localforageInstance._dbInfo;
                dbInfo.db.transaction(function (t) {
                    t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE (key LIKE ?)', [prefix + '%'], function (t, results) {

                        var result = [];

                        var rows = results.rows;
                        for (var i = 0, len = rows.length; i < len; i++) {
                            var item = rows.item(i);

                            result.push(item.key);
                        }

                        resolve(result);
                    }, function (t, error) {
                        reject(error);
                    });
                });
            }).catch(reject);
        });
        executeCallback(promise, callback);
        return promise;
    }

    function startsWith$2(prefix, callback) {
        var localforageInstance = this;
        var promise = new Promise(function (resolve, reject) {
            localforageInstance.keys().then(function (keys) {

                var itemPromises = [];

                var prefixLength = prefix.length;
                for (var i = 0, len = keys.length; i < len; i++) {
                    var key = keys[i];

                    if (key.slice(0, prefixLength) === prefix) {
                        itemPromises.push(getItemKeyValue.call(localforageInstance, key));
                    }
                }

                Promise.all(itemPromises).then(function (keyValuePairs) {
                    var result = {};
                    for (var i = 0, len = keyValuePairs.length; i < len; i++) {
                        var keyValuePair = keyValuePairs[i];

                        result[keyValuePair.key] = keyValuePair.value;
                    }
                    resolve(result);
                }).catch(reject);
            }).catch(reject);
        });
        executeCallback(promise, callback);
        return promise;
    }

    function keysStartingWith$2(prefix, callback) {
        var localforageInstance = this;
        var promise = new Promise(function (resolve, reject) {
            localforageInstance.keys().then(function (keys) {

                var result = [];

                var prefixLength = prefix.length;
                for (var i = 0, len = keys.length; i < len; i++) {
                    var key = keys[i];

                    if (key.slice(0, prefixLength) === prefix) {
                        result.push(key);
                    }
                }

                resolve(result);
            }).catch(reject);
        });
        executeCallback(promise, callback);
        return promise;
    }

    function localforageStartsWith(prefix, callback) {
        var localforageInstance = this;
        var currentDriver = localforageInstance.driver();

        if (currentDriver === localforageInstance.INDEXEDDB) {
            return startsWith.call(localforageInstance, prefix, callback);
        } else if (currentDriver === localforageInstance.WEBSQL) {
            return startsWith$1.call(localforageInstance, prefix, callback);
        } else {
            return startsWith$2.call(localforageInstance, prefix, callback);
        }
    }

    function localforageKeysStartingWith(prefix, callback) {
        var localforageInstance = this;
        var currentDriver = localforageInstance.driver();

        if (currentDriver === localforageInstance.INDEXEDDB) {
            return keysStartingWith.call(localforageInstance, prefix, callback);
        } else if (currentDriver === localforageInstance.WEBSQL) {
            return keysStartingWith$1.call(localforageInstance, prefix, callback);
        } else {
            return keysStartingWith$2.call(localforageInstance, prefix, callback);
        }
    }

    function extendPrototype(localforage) {
        var localforagePrototype = Object.getPrototypeOf(localforage);
        if (localforagePrototype) {
            localforagePrototype.startsWith = localforageStartsWith;
            localforagePrototype.keysStartingWith = localforageKeysStartingWith;
        }
    }

    var extendPrototypeResult = extendPrototype(localforage);

    exports.localforageStartsWith = localforageStartsWith;
    exports.localforageKeysStartingWith = localforageKeysStartingWith;
    exports.extendPrototype = extendPrototype;
    exports.extendPrototypeResult = extendPrototypeResult;
    exports.startsWithGeneric = startsWith$2;
    exports.keysStartingWithGeneric = keysStartingWith$2;

}));<|endoftext|>


<commit_before>"use strict";

var utils = require( "../utils" );

module.exports = [ "$compile", function ( $compile )
{
    return {
        scope: {
            definition: "=rhDefinition",
            save: "=rhOnSave",
            delete: "=rhOnDelete",
            cancel: "=rhOnCancel",
            model: "=rhModel",
            titleVisible: "=rhTitleVisible"
        },
        link: function ( scope, element )
        {
            var render = function ()
            {
                if( typeof( scope.definition ) !== "object" )
                {
                    element.html( "" );
                    $compile( element.contents() )( scope );
                    return;
                }

                var keys = Object.keys( scope.definition );
                var inputs = [];
                scope.definition.meta = scope.definition.meta || {};
                scope.model = scope.model || {};
                scope.toggleDeletePending = function ()
                {
                    scope.deletePending = !scope.deletePending;
                };
                scope.deleteClick = function ()
                {
                    scope.delete( scope.model );
                };
                scope.saveClick = function ( form )
                {
                    if( form.$valid )
                    {
                        scope.save( scope.model );
                    }
                };

                scope.formFields = keys.filter( function ( key )
                {
                    var def = scope.definition[ key ];
                    return key !== "meta" && def.canView !== false && def.type !== "link";
                } )
                .map( function ( key )
                {
                    var def = scope.definition[ key ];
                    def.key = key;
                    return def;
                } );

                scope.formName = "rh" + ( scope.definition.meta.title || "" ).replace( /[^\w\d]*/g, "" ) + "Form";
                scope.canDelete = scope.model.id && utils.runIfFunc( scope.definition.meta.canDelete ) !== false;

                var form = '<form name="{{ formName }}" class="rh-form" data-ng-submit="saveClick( ' + scope.formName + ' )">'
                + "
"
                + '    {{ !definition.id || model.id ? "Edit " : "Add "}}'
                + '    {{ scope.definition.meta.title || "" }}'
                + "
"
                + '

'
                + '
'
                + '    <button type="button" class="btn btn-default" data-ng-click="cancel()">Cancel</button>'
                + '    <button type="button" class="btn btn-danger" data-ng-if="canDelete"'
                + '      data-ng-click="toggleDeletePending()">Delete</button>'
                + '    <button id="add-item-submit" type="submit" class="btn btn-primary">Save</button>'
                + "
"
                + '
'
                + "    Do you really want to delete this?"
                + '    <button type="button" class="btn btn-danger" data-ng-click="deleteClick()">Yes, Delete</button>'
                + '    <button type="button" class="btn btn-default" data-ng-click="toggleDeletePending()">Cancel</button>'
                + "
"
                + "</form>";

                element.html( form );
                $compile( element.contents() )( scope );
            };

            scope.$watch( "definition", render );
            scope.$watch( "model", render );
            render();
        }
    };
} ];
<commit_msg>fix title binding<commit_after>"use strict";

var utils = require( "../utils" );

module.exports = [ "$compile", function ( $compile )
{
    return {
        scope: {
            definition: "=rhDefinition",
            save: "=rhOnSave",
            delete: "=rhOnDelete",
            cancel: "=rhOnCancel",
            model: "=rhModel",
            titleVisible: "=rhTitleVisible"
        },
        link: function ( scope, element )
        {
            var render = function ()
            {
                if( typeof( scope.definition ) !== "object" )
                {
                    element.html( "" );
                    $compile( element.contents() )( scope );
                    return;
                }

                var keys = Object.keys( scope.definition );
                var inputs = [];
                scope.definition.meta = scope.definition.meta || {};
                scope.model = scope.model || {};
                scope.toggleDeletePending = function ()
                {
                    scope.deletePending = !scope.deletePending;
                };
                scope.deleteClick = function ()
                {
                    scope.delete( scope.model );
                };
                scope.saveClick = function ( form )
                {
                    if( form.$valid )
                    {
                        scope.save( scope.model );
                    }
                };

                scope.formFields = keys.filter( function ( key )
                {
                    var def = scope.definition[ key ];
                    return key !== "meta" && def.canView !== false && def.type !== "link";
                } )
                .map( function ( key )
                {
                    var def = scope.definition[ key ];
                    def.key = key;
                    return def;
                } );

                scope.formName = "rh" + ( scope.definition.meta.title || "" ).replace( /[^\w\d]*/g, "" ) + "Form";
                scope.canDelete = scope.model.id && utils.runIfFunc( scope.definition.meta.canDelete ) !== false;

                var form = '<form name="{{ formName }}" class="rh-form" data-ng-submit="saveClick( ' + scope.formName + ' )">'
                + "
"
                + '    {{ !definition.id || model.id ? "Edit " : "Add "}}'
                + '    {{ definition.meta.title || "" }}'
                + "
"
                + '

'
                + '
'
                + '    <button type="button" class="btn btn-default" data-ng-click="cancel()">Cancel</button>'
                + '    <button type="button" class="btn btn-danger" data-ng-if="canDelete"'
                + '      data-ng-click="toggleDeletePending()">Delete</button>'
                + '    <button id="add-item-submit" type="submit" class="btn btn-primary">Save</button>'
                + "
"
                + '
'
                + "    Do you really want to delete this?"
                + '    <button type="button" class="btn btn-danger" data-ng-click="deleteClick()">Yes, Delete</button>'
                + '    <button type="button" class="btn btn-default" data-ng-click="toggleDeletePending()">Cancel</button>'
                + "
"
                + "</form>";

                element.html( form );
                $compile( element.contents() )( scope );
            };

            scope.$watch( "definition", render );
            scope.$watch( "model", render );
            render();
        }
    };
} ];
<|endoftext|>


<commit_before>/*
* mvcActionResults
* author: ronglin
* create date: 2014.6.30
*/

'use strict';

var utils = require('./utilities'),
    mvcHelperUrl = require('./mvcHelperUrl');

/* baseResult
***************************************/
var baseResult = exports.baseResult = function(set) {
    var self = this;
    utils.each(set, function (key, val) {
        if (val) { self[key] = val;}
    });
};

baseResult.prototype = {
    constructor: baseResult,
    execute: function(context) {
        throw new Error('"execute" function needs override by sub classes.');
    }
};

/* emptyResult
***************************************/
var emptyResult = exports.emptyResult = function(set) {
    emptyResult.superclass.constructor.call(this, set);
};

utils.inherit(emptyResult, baseResult, {

    execute: function(context) {
        context.response.set('Content-Type', 'text/html');
        context.response.send('');
    }
});

/* jsonResult
***************************************/
var jsonResult = exports.jsonResult = function(set) {
    jsonResult.superclass.constructor.call(this, set);
};

utils.inherit(jsonResult, baseResult, {

    data: null, contentType: 'application/json',

    execute: function(context) {
        context.response.set('Content-Type', this.contentType);
        context.response.json(this.data);
    }
});

/* jsonpResult
***************************************/
var jsonpResult = exports.jsonpResult = function(set) {
    jsonpResult.superclass.constructor.call(this, set);
};

utils.inherit(jsonpResult, baseResult, {

    data: null, contentType: 'application/json', callbackName: 'callback',

    execute: function(context) {
        var old = context.response.app.get('jsonp callback name');
        context.response.app.set('jsonp callback name', this.callbackName);
        context.response.set('Content-Type', this.contentType);
        context.response.jsonp(this.data);
        context.response.app.set('jsonp callback name', old);
    }
});

/* partialViewResult
***************************************/
var partialViewResult = exports.partialViewResult = function(set) {
    partialViewResult.superclass.constructor.call(this, set);
};

utils.inherit(partialViewResult, baseResult, {

    viewName: null,

    execute: function(context) {
        //TODO:
    }
});

/* viewResult
***************************************/
var viewResult = exports.viewResult = function(set) {
    viewResult.superclass.constructor.call(this, set);
};

utils.inherit(viewResult, baseResult, {

    viewName: null, model: null,

    execute: function(context) {
        //TODO:
    }
});

/* fileResult
***************************************/
var fileResult = exports.fileResult = function(set) {
    fileResult.superclass.constructor.call(this, set);
};

utils.inherit(fileResult, baseResult, {

    filePath: null, fileDownloadName: null,

    execute: function(context) {
        context.response.download(this.filePath, this.fileDownloadName);
    }
});

/* contentResult
***************************************/
var contentResult = exports.contentResult = function(set) {
    contentResult.superclass.constructor.call(this, set);
};

utils.inherit(contentResult, baseResult, {

    content: null, contentType: 'text/html',

    execute: function(context) {
        context.response.set('Content-Type', this.contentType);
        context.response.send(this.content);
    }
});

/* httpStatusCodeResult
***************************************/
var httpStatusCodeResult = exports.httpStatusCodeResult = function(set) {
    httpStatusCodeResult.superclass.constructor.call(this, set);
};

utils.inherit(httpStatusCodeResult, baseResult, {

    statusCode: null, statusDescription: null,

    execute: function(context) {
        context.response.send(this.statusDescription, this.statusCode);
    }
});

/* httpNotFoundResult
***************************************/
var httpNotFoundResult = exports.httpNotFoundResult = function(set) {
    httpNotFoundResult.superclass.constructor.call(this, set);
    this.statusCode = 404;
};

utils.inherit(httpNotFoundResult, httpStatusCodeResult, {});

/* redirectResult
***************************************/
var redirectResult = exports.redirectResult = function(set) {
    redirectResult.superclass.constructor.call(this, set);
};

utils.inherit(redirectResult, baseResult, {

    url: null, permanent: false,

    execute: function(context) {
        if (this.permanent) {
            context.response.redirect(this.url, 301);
        } else {
            context.response.redirect(this.url, 302);
        }
    }
});

/* redirectToRouteResult
***************************************/
var redirectToRouteResult = exports.redirectToRouteResult = function(set) {
    redirectToRouteResult.superclass.constructor.call(this, set);
};

utils.inherit(redirectToRouteResult, baseResult, {

    routeValues: null, permanent: false,

    execute: function(context) {
        var url = mvcHelperUrl.generateUrl(null, null, this.routeValues, context.request.routeSet, context.request, false);
        if (this.permanent) {
            context.response.redirect(url, 301);
        } else {
            context.response.redirect(url, 302);
        }
    }
});

<commit_msg>update<commit_after>/*
* mvcActionResults
* author: ronglin
* create date: 2014.6.30
*/

'use strict';

var utils = require('./utilities'),
    mvcHelperUrl = require('./mvcHelperUrl');

/* baseResult
***************************************/
var baseResult = exports.baseResult = function(set) {
    var self = this;
    utils.each(set, function (key, val) {
        if (val) { self[key] = val;}
    });
};

baseResult.prototype = {
    constructor: baseResult,
    execute: function(context) {
        throw new Error('"execute" function needs override by sub classes.');
    }
};

/* emptyResult
***************************************/
var emptyResult = exports.emptyResult = function(set) {
    emptyResult.superclass.constructor.call(this, set);
};

utils.inherit(emptyResult, baseResult, {
    execute: function(context) {
        context.response.set('Content-Type', 'text/html');
        context.response.send('');
    }
});

/* jsonResult
***************************************/
var jsonResult = exports.jsonResult = function(set) {
    jsonResult.superclass.constructor.call(this, set);
};

utils.inherit(jsonResult, baseResult, {
    data: null, contentType: 'application/json',
    execute: function(context) {
        context.response.set('Content-Type', this.contentType);
        context.response.json(this.data);
    }
});

/* jsonpResult
***************************************/
var jsonpResult = exports.jsonpResult = function(set) {
    jsonpResult.superclass.constructor.call(this, set);
};

utils.inherit(jsonpResult, baseResult, {
    data: null, contentType: 'application/json', callbackName: 'callback',
    execute: function(context) {
        var old = context.response.app.get('jsonp callback name');
        context.response.app.set('jsonp callback name', this.callbackName);
        context.response.set('Content-Type', this.contentType);
        context.response.jsonp(this.data);
        context.response.app.set('jsonp callback name', old);
    }
});

/* partialViewResult
***************************************/
var partialViewResult = exports.partialViewResult = function(set) {
    partialViewResult.superclass.constructor.call(this, set);
};

utils.inherit(partialViewResult, baseResult, {
    viewName: null,
    execute: function(context) {
        //TODO:
    }
});

/* viewResult
***************************************/
var viewResult = exports.viewResult = function(set) {
    viewResult.superclass.constructor.call(this, set);
};

utils.inherit(viewResult, baseResult, {
    viewName: null, model: null,
    execute: function(context) {
        //TODO:
    }
});

/* fileResult
***************************************/
var fileResult = exports.fileResult = function(set) {
    fileResult.superclass.constructor.call(this, set);
};

utils.inherit(fileResult, baseResult, {
    filePath: null, fileDownloadName: null,
    execute: function(context) {
        context.response.download(this.filePath, this.fileDownloadName);
    }
});

/* contentResult
***************************************/
var contentResult = exports.contentResult = function(set) {
    contentResult.superclass.constructor.call(this, set);
};

utils.inherit(contentResult, baseResult, {
    content: null, contentType: 'text/html',
    execute: function(context) {
        context.response.set('Content-Type', this.contentType);
        context.response.send(this.content);
    }
});

/* httpStatusCodeResult
***************************************/
var httpStatusCodeResult = exports.httpStatusCodeResult = function(set) {
    httpStatusCodeResult.superclass.constructor.call(this, set);
};

utils.inherit(httpStatusCodeResult, baseResult, {
    statusCode: null, statusDescription: null,
    execute: function(context) {
        context.response.send(this.statusDescription, this.statusCode);
    }
});

/* httpNotFoundResult
***************************************/
var httpNotFoundResult = exports.httpNotFoundResult = function(set) {
    httpNotFoundResult.superclass.constructor.call(this, set);
    this.statusCode = 404;
};

utils.inherit(httpNotFoundResult, httpStatusCodeResult, {
    execute: function(context) {
        httpNotFoundResult.superclass.execute.call(this, context);
    }
});

/* redirectResult
***************************************/
var redirectResult = exports.redirectResult = function(set) {
    redirectResult.superclass.constructor.call(this, set);
};

utils.inherit(redirectResult, baseResult, {
    url: null, permanent: false,
    execute: function(context) {
        if (this.permanent) {
            context.response.redirect(this.url, 301);
        } else {
            context.response.redirect(this.url, 302);
        }
    }
});

/* redirectToRouteResult
***************************************/
var redirectToRouteResult = exports.redirectToRouteResult = function(set) {
    redirectToRouteResult.superclass.constructor.call(this, set);
};

utils.inherit(redirectToRouteResult, baseResult, {
    routeValues: null, permanent: false,
    execute: function(context) {
        var url = mvcHelperUrl.generateUrl(null, null, this.routeValues, context.request.routeSet, context.request, false);
        if (this.permanent) {
            context.response.redirect(url, 301);
        } else {
            context.response.redirect(url, 302);
        }
    }
});

<|endoftext|>


<commit_before>// limit the post categories to those that the user has pemission to see
function userCategories (parameters, terms) {

    var categoriesIds = [];
    var find = {};
    var userCats = Users.getCategoriesById(terms.userId);

  if (typeof userCats !== 'undefined' && !terms.cat ) {//&& parameters.find.categories === 'undefined') {

    if (userCats.length === 1) { // One Category
      find = {"_id": userCats};
    } else { // cat is an array
      find = {"_id": { $in : userCats}};
    }

    // get all categories passed in terms
    var categories = Categories.find(find).fetch();

    // for each category, add its ID and the IDs of its children to categoriesId array
    categories.forEach(function (category) {
      categoriesIds.push(category._id);
      categoriesIds = categoriesIds.concat(_.pluck(category.getChildren(), "_id"));
    });

    parameters.find.categories = {$in: categoriesIds};
  }
  return parameters;
}
Telescope.callbacks.add("postsParameters", userCategories);

Telescope.callbacks.remove("postsParameters", "addCategoryParameter");

function addCategoryIntersectionParameter (parameters, terms) {
  // filter by category if category slugs are provided
  if (!!terms.cat) {

    var categoriesIds = [];
    var find = {};

    if (typeof terms.cat === "string") { // cat is a string
      find = {slug: terms.cat};
    } else { // cat is an array
      find = {slug: {$in: terms.cat}};
    }

    // get all categories passed in terms
    var categories = Categories.find(find).fetch();

    var categoriesIds = _.pluck(categories, "_id");

    parameters.find.categories = {$all: categoriesIds};
  }
  return parameters;
}
Telescope.callbacks.add("postsParameters", addCategoryIntersectionParameter);<commit_msg>cahnge to category parameters<commit_after>// limit the post categories to those that the user has pemission to see
function userCategories (parameters, terms) {

    var categoriesIds = [];
    var find = {};
    var userCats = Users.getCategoriesById(terms.userId);

  if (typeof userCats !== 'undefined' && !terms.cat ) {//&& parameters.find.categories === 'undefined') {

    if (userCats.length === 1) { // One Category
      find = {"_id": userCats};
    } else { // cat is an array
      find = {"_id": { $in : userCats}};
    }

    // get all categories passed in terms
    var categories = Categories.find(find).fetch();

    // for each category, add its ID and the IDs of its children to categoriesId array
    categories.forEach(function (category) {
      categoriesIds.push(category._id);
      categoriesIds = categoriesIds.concat(_.pluck(category.getChildren(), "_id"));
    });

    parameters.find.categories = {$in: categoriesIds};
  }
  return parameters;
}
Telescope.callbacks.add("postsParameters", userCategories);

// Telescope.callbacks.remove("postsParameters", "addCategoryParameter");

// function addCategoryIntersectionParameter (parameters, terms) {
//   // filter by category if category slugs are provided
//   if (!!terms.cat) {

//     var categoriesIds = [];
//     var find = {};

//     if (typeof terms.cat === "string") { // cat is a string
//       find = {slug: terms.cat};
//     } else { // cat is an array
//       find = {slug: {$in: terms.cat}};
//     }

//     // get all categories passed in terms
//     var categories = Categories.find(find).fetch();

//     var categoriesIds = _.pluck(categories, "_id");

//     parameters.find.categories = {$all: categoriesIds};
//   }
//   return parameters;
// }
// Telescope.callbacks.add("postsParameters", addCategoryIntersectionParameter);<|endoftext|>


<commit_before>module.exports = {
  'extends': [
    'eslint-config-airbnb/base',
    'eslint-config-airbnb/rules/react',
  ].map(require.resolve),
  rules: {}
};
<commit_msg>Preserve strict rule for default export<commit_after>module.exports = {
  'extends': [
    'eslint-config-airbnb/base',
    'eslint-config-airbnb/rules/strict',
    'eslint-config-airbnb/rules/react',
  ].map(require.resolve),
  rules: {}
};
<|endoftext|>