<commit_before>/*******************************************************************************
 * Copyright 2012 University of Southern California
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * This code was developed by the Information Integration Group as part
 * of the Karma project at the Information Sciences Institute of the
 * University of Southern California.  For more information, publications,
 * and related projects, please see: http://www.isi.edu/integration
 ******************************************************************************/

var D3ModelManager = (function() {
	var instance = null;

	function PrivateConstructor() {
		var models;

		function init() {
			models = [];

			window.onscroll = function(event){
				for (var worksheetId in models) {
					models[worksheetId].onscroll(event);
				}
			};

			window.onresize = function(event) {
				for (var worksheetId in models) {
					models[worksheetId].onresize(event);
				}
			};
		}

		function getModelManager(worksheetId, layoutElement, layoutClass, width, force) {
			if(models[worksheetId]) {
				//This is temporary. Comment this out when the D3ModelLayout can handle updates.
				if(force)
					models[worksheetId] = new D3ModelLayout(layoutElement, layoutClass, width, worksheetId);
			} else {
				models[worksheetId] = new D3ModelLayout(layoutElement, layoutClass, width, worksheetId);
			}
			return models[worksheetId];
		};

		function displayModel(json) {
			var worksheetId = json["worksheetId"];
			var mainWorksheetDiv = $("div#" + worksheetId);
			var wsVisible = mainWorksheetDiv.data("worksheetVisible");
			if (!wsVisible) {
				return;
			}

			var w = 0;
			var mainWorksheetDiv = $("div#" + worksheetId);
			var layoutElement = "div#svgDiv_" + worksheetId;

			if ($(mainWorksheetDiv).data("svgVis") != null) {
				//$(layoutElement).remove();
			} else {
				$("<div>").attr("id", "svgDiv_" + worksheetId).addClass("svg-model").insertBefore('div#' + worksheetId + " > div.table-container");
			}

			if (w == 0)
				w = $("div#" + worksheetId).width();

			var tableLeftOffset = mainWorksheetDiv.offset().left;

			var alignJson;
			var nodesMap;
			if(json.alignObject) {
				var maxX = 0;
				alignJson = json.alignObject;
				nodesMap = [];
				$.each(alignJson.anchors, function(index, node) {
					var hNodeId = node["hNodeId"];
					var columnNode = $("td#" + hNodeId);
					var leftX = $(columnNode).offset().left - tableLeftOffset;
					node.xPos = leftX + ($(columnNode).width()/2);
					var nodeMax = leftX + $(columnNode).width();
					if(nodeMax > maxX)
						maxX = nodeMax;
					nodesMap[node["id"]] = node;
				});
				alignJson.width = maxX + 100;

				$.each(alignJson.nodes, function(index, node) {
					nodesMap[node["id"]] = node;
				});

				$.each(alignJson.links, function(index, link) {
					if(link.label == "classLink")
						link.label = "uri";
				});
			} else {
				alignJson = json;
			}
			var layout;
			try {
				layout = getModelManager(worksheetId, layoutElement, "col-sm-10", w);
				console.log(JSON.stringify(alignJson));
				layout.generateLayoutForJson(alignJson);
			} catch(err) {
				console.log("Got exception in D3ModelLayout:" + err.message);
				//Try again generating a new D3Layout
				layout = getModelManager(worksheetId, layoutElement, "col-sm-10", w, true);
				console.log(JSON.stringify(alignJson));
				layout.generateLayoutForJson(alignJson);
			}
			var alignmentId = json["alignmentId"];
			$(mainWorksheetDiv).data("alignmentId", alignmentId);
			$(mainWorksheetDiv).data("svgVis", {"svgVis":true});

			layout.setNodeClickListener(function(d, event) {
				console.log("This function is called when the node is clicked");
				if (d["nodeType"] == "InternalNode" || d["nodeType"] == "LiteralNode") {
					var nodeCategory = "";
					if (d.isForcedByUser)
						nodeCategory = "forcedAdded";
					var id;
					if(d.nodeId)
						id = d.nodeId;
					else
						id = d.id;
					ClassDropdownMenu.getInstance().show(worksheetId, id, d.label, id, d.nodeDomain, nodeCategory,
							alignmentId, d.nodeType, d.isUri, event);
				}

			});

			layout.setLinkClickListener(function(d, event) {
				console.log("This function is called when the link is clicked");
				var sourceObj, targetObj;
				if(nodesMap) {
					sourceObj = nodesMap[d.source];
					targetObj = nodesMap[d.target];
				} else {
					sourceObj = d.source;
					targetObj = d.target;
				}
				PropertyDropdownMenu.getInstance().show(
						worksheetId,
						alignmentId,
						d.id,
						d.linkUri,
						d.sourceNodeId,
						sourceObj.nodeType,
						sourceObj.label,
						sourceObj.nodeDomain,
						d.sourceNodeId,
						d.source.isUri,
						d.targetNodeId,
						targetObj.nodeType,
						targetObj.label,
						targetObj.nodeDomain,
						d.targetNodeId,
						d.target.isUri,
						event);
			});
		};

		function refreshModel(worksheetId) {
			var mainWorksheetDiv = $("div#" + worksheetId);
			var svg = $(mainWorksheetDiv).data("svgVis");
			if (svg) {
				var alignmentId = $(mainWorksheetDiv).data("alignmentId");
				console.log("RefreshSVGAlignmentCommand: " + worksheetId, alignmentId);
				var info = generateInfoObject(worksheetId, "", "RefreshSVGAlignmentCommand");
				info["alignmentId"] = alignmentId;
				showLoading(worksheetId);
				sendRequest(info, worksheetId);
			}
		};

		function printModel(worksheetId) {
			var layout = getModelManager(worksheetId);
			if(layout.printExtented) {
				showLoading(worksheetId);
				layout.printExtented(3, function() {
					hideLoading(worksheetId);
				});
			} else {
				alert("The Model Manager does not support printing");
			}
		}

		return { //Return back the public methods
			init: init,
			getModelManager: getModelManager,
			displayModel: displayModel,
			refreshModel: refreshModel,
			printModel: printModel
		};
	};

	function getInstance() {
		if (!instance) {
			instance = new PrivateConstructor();
			instance.init();
		}
		return instance;
	}

	return {
		getInstance: getInstance
	};

})();

<commit_msg>clear the layout div when there is an error so that you don't get 2 models<commit_after>/*******************************************************************************
 * Copyright 2012 University of Southern California
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * This code was developed by the Information Integration Group as part
 * of the Karma project at the Information Sciences Institute of the
 * University of Southern California.  For more information, publications,
 * and related projects, please see: http://www.isi.edu/integration
 ******************************************************************************/

var D3ModelManager = (function() {
	var instance = null;

	function PrivateConstructor() {
		var models;

		function init() {
			models = [];

			window.onscroll = function(event){
				for (var worksheetId in models) {
					models[worksheetId].onscroll(event);
				}
			};

			window.onresize = function(event) {
				for (var worksheetId in models) {
					models[worksheetId].onresize(event);
				}
			};
		}

		function getModelManager(worksheetId, layoutElement, layoutClass, width, force) {
			if(models[worksheetId]) {
				//This is temporary. Comment this out when the D3ModelLayout can handle updates.
				if(force)
					models[worksheetId] = new D3ModelLayout(layoutElement, layoutClass, width, worksheetId);
			} else {
				models[worksheetId] = new D3ModelLayout(layoutElement, layoutClass, width, worksheetId);
			}
			return models[worksheetId];
		};

		function displayModel(json) {
			var worksheetId = json["worksheetId"];
			var mainWorksheetDiv = $("div#" + worksheetId);
			var wsVisible = mainWorksheetDiv.data("worksheetVisible");
			if (!wsVisible) {
				return;
			}

			var w = 0;
			var mainWorksheetDiv = $("div#" + worksheetId);
			var layoutElement = "div#svgDiv_" + worksheetId;

			if ($(mainWorksheetDiv).data("svgVis") != null) {
				//$(layoutElement).remove();
			} else {
				$("<div>").attr("id", "svgDiv_" + worksheetId).addClass("svg-model").insertBefore('div#' + worksheetId + " > div.table-container");
			}

			if (w == 0)
				w = $("div#" + worksheetId).width();

			var tableLeftOffset = mainWorksheetDiv.offset().left;

			var alignJson;
			var nodesMap;
			if(json.alignObject) {
				var maxX = 0;
				alignJson = json.alignObject;
				nodesMap = [];
				$.each(alignJson.anchors, function(index, node) {
					var hNodeId = node["hNodeId"];
					var columnNode = $("td#" + hNodeId);
					var leftX = $(columnNode).offset().left - tableLeftOffset;
					node.xPos = leftX + ($(columnNode).width()/2);
					var nodeMax = leftX + $(columnNode).width();
					if(nodeMax > maxX)
						maxX = nodeMax;
					nodesMap[node["id"]] = node;
				});
				alignJson.width = maxX + 100;

				$.each(alignJson.nodes, function(index, node) {
					nodesMap[node["id"]] = node;
				});

				$.each(alignJson.links, function(index, link) {
					if(link.label == "classLink")
						link.label = "uri";
				});
			} else {
				alignJson = json;
			}
			var layout;
			try {
				layout = getModelManager(worksheetId, layoutElement, "col-sm-10", w);
				console.log(JSON.stringify(alignJson));
				layout.generateLayoutForJson(alignJson);
			} catch(err) {
				console.log("Got exception in D3ModelLayout:" + err.message);
				console.log(err.stack);
				//Try again generating a new D3Layout
				$(layoutElement).empty();
				layout = getModelManager(worksheetId, layoutElement, "col-sm-10", w, true);
				console.log(JSON.stringify(alignJson));
				layout.generateLayoutForJson(alignJson);
			}
			var alignmentId = json["alignmentId"];
			$(mainWorksheetDiv).data("alignmentId", alignmentId);
			$(mainWorksheetDiv).data("svgVis", {"svgVis":true});

			layout.setNodeClickListener(function(d, event) {
				console.log("This function is called when the node is clicked");
				if (d["nodeType"] == "InternalNode" || d["nodeType"] == "LiteralNode") {
					var nodeCategory = "";
					if (d.isForcedByUser)
						nodeCategory = "forcedAdded";
					var id;
					if(d.nodeId)
						id = d.nodeId;
					else
						id = d.id;
					ClassDropdownMenu.getInstance().show(worksheetId, id, d.label, id, d.nodeDomain, nodeCategory,
							alignmentId, d.nodeType, d.isUri, event);
				}

			});

			layout.setLinkClickListener(function(d, event) {
				console.log("This function is called when the link is clicked");
				var sourceObj, targetObj;
				if(nodesMap) {
					sourceObj = nodesMap[d.source];
					targetObj = nodesMap[d.target];
				} else {
					sourceObj = d.source;
					targetObj = d.target;
				}
				PropertyDropdownMenu.getInstance().show(
						worksheetId,
						alignmentId,
						d.id,
						d.linkUri,
						d.sourceNodeId,
						sourceObj.nodeType,
						sourceObj.label,
						sourceObj.nodeDomain,
						d.sourceNodeId,
						d.source.isUri,
						d.targetNodeId,
						targetObj.nodeType,
						targetObj.label,
						targetObj.nodeDomain,
						d.targetNodeId,
						d.target.isUri,
						event);
			});
		};

		function refreshModel(worksheetId) {
			var mainWorksheetDiv = $("div#" + worksheetId);
			var svg = $(mainWorksheetDiv).data("svgVis");
			if (svg) {
				var alignmentId = $(mainWorksheetDiv).data("alignmentId");
				console.log("RefreshSVGAlignmentCommand: " + worksheetId, alignmentId);
				var info = generateInfoObject(worksheetId, "", "RefreshSVGAlignmentCommand");
				info["alignmentId"] = alignmentId;
				showLoading(worksheetId);
				sendRequest(info, worksheetId);
			}
		};

		function printModel(worksheetId) {
			var layout = getModelManager(worksheetId);
			if(layout.printExtented) {
				showLoading(worksheetId);
				layout.printExtented(3, function() {
					hideLoading(worksheetId);
				});
			} else {
				alert("The Model Manager does not support printing");
			}
		}

		return { //Return back the public methods
			init: init,
			getModelManager: getModelManager,
			displayModel: displayModel,
			refreshModel: refreshModel,
			printModel: printModel
		};
	};

	function getInstance() {
		if (!instance) {
			instance = new PrivateConstructor();
			instance.init();
		}
		return instance;
	}

	return {
		getInstance: getInstance
	};

})();

<|endoftext|>


<commit_before>(function () {
    "use strict";

    window.App.videos = [
        {
            title: '13 часов: Тайные солдаты Бенгази (2016)',
            url: 'http://www.ex.ua/get/262240597',
            type: 'vod'
        },

        {
            title: 'Gotham.S02E18',
            url: 'http://fs.to/get/dl/6jw62suuowh2h5cu1j110xqba.0.521872670.974127405.1461398148/Gotham.S02E18.1080p.rus.LostFilm.mkv',
            type: 'vod'
        },
        {
            title: 'Redbull',
            url: 'http://live.iphone.redbull.de.edgesuite.net/webtvHD.m3u8',
            type: 'hls'
        }
    ];
})();

<commit_msg>Update videos.js<commit_after>(function () {
    "use strict";

    window.App.videos = [
        {
            title: 'Mjehanik.Voskrjeshenije.2016.D.BDRip 720p.mkv',
            url: 'http://www.ex.ua/get/285854084',
            type: 'vod'
        },

        {
            title: 'Gotham.S02E18',
            url: 'http://fs.to/get/dl/6jw62suuowh2h5cu1j110xqba.0.521872670.974127405.1461398148/Gotham.S02E18.1080p.rus.LostFilm.mkv',
            type: 'vod'
        },
        {
            title: 'Redbull',
            url: 'http://live.iphone.redbull.de.edgesuite.net/webtvHD.m3u8',
            type: 'hls'
        }
    ];
})();

<|endoftext|>


<commit_before>/**
 * GET /threesixty
 * Threesixty site
 */
exports.index = function(req, res) {
	// get show frontpage graph URL
	res.render('graph/show', {
		layout: 'threesixty',
		graphSrc: '/threesixty/featured',
		graphMinUrl: '/threesixty/featured',
		autoplay: true,
		hideEditButton: false,
		hideShareButton: false,
		hidePlayButton: true,
		meta : {
			bodyclass : 'bThreesixty b360'
		},
		noHeader: false,
		graph: {
			hasAudio: false
		},
		startMode : 1
	});
}

exports.featured = function(req,res) {
	var featuredGraph = '/data/graph/eesn/flamingofront.json'
	switch (process.env.FQDN) {
		case '360.vizor.io':
		case 'rc.vizor.io':
		case 'vizor.io':
		case '360vr.io':
			featuredGraph = '/data/graph/v/hrpfbjje86s5.json'
			break;
	}
	res.redirect(featuredGraph)
}<commit_msg>change default threesixty graph to use lower-resolution JPEG<commit_after>/**
 * GET /threesixty
 * Threesixty site
 */
exports.index = function(req, res) {
	// get show frontpage graph URL
	res.render('graph/show', {
		layout: 'threesixty',
		graphSrc: '/threesixty/featured',
		graphMinUrl: '/threesixty/featured',
		autoplay: true,
		hideEditButton: false,
		hideShareButton: false,
		hidePlayButton: true,
		meta : {
			bodyclass : 'bThreesixty b360'
		},
		noHeader: false,
		graph: {
			hasAudio: false
		},
		startMode : 1
	});
}

exports.featured = function(req,res) {
	var featuredGraph = '/data/graph/eesn/flamingofront.json'
	switch (process.env.FQDN) {
		case '360.vizor.io':
		case 'rc.vizor.io':
		case 'vizor.io':
		case '360vr.io':
			featuredGraph = '/data/graph/vizor/threesixty.json'
			break;
	}
	res.redirect(featuredGraph)
}<|endoftext|>


<commit_before><commit_msg>fix the minified jquery-domPath<commit_after><|endoftext|>


<commit_before>"use strict";

angular.module("hikeio").
	directive("contenteditable", ["$timeout", "capabilities", "filterParser", function($timeout, capabilities, filterParser) {

		return {
			require: "ngModel",
			link: function(scope, element, attributes, controller) {

				var storeViewValueInModel = function() {
					scope.$apply(function() {
						var viewValue = "";
						if (attributes.type === "text") {
							viewValue = element.text();
						} else if (attributes.type === "numeric") {
							viewValue = parseFloat(element.html()) + "";
							if (isNaN(viewValue)) {
								element.html("");
								viewValue = 0;
							} else if (viewValue !== element.html() && !element.html().match(/[0-9\.]*/)) { // Firefox adds
's everywehre, this cleans them up
								element.html(viewValue);
							}
						} else {
							viewValue = element.html();
							if (element.text() === "" && viewValue !== "") {
								viewValue = "";
								element.html("");
							}
						}

						if (attributes.filterModel) {
							viewValue = filterParser.filter(attributes.filterModel, viewValue);
						}

						controller.$setViewValue(viewValue);
					});

					if (attributes.change) {
						scope.$apply(attributes.change);
					}
				};

				// view -> model
				element.on("input", function() {
					storeViewValueInModel();
				});

				element.on("paste", function(event) {
					var clipboardData = event.originalEvent.clipboardData || window.clipboardData;
					if (clipboardData) {
						var pastedData = clipboardData.getData("text/plain");
						if (attributes.type === "numeric") {
							if (($.isNumeric(pastedData) && (!attributes.positive || parseFloat(pastedData) > 0)) || pastedData === ".") {
								// programmatically paste to ensure that result will be numeric
								var before = element.html();
								document.execCommand("insertText", false, pastedData);
								var after = element.html();
								if ($.isNumeric(after) && (!attributes.positive || parseFloat(after) > 0)) {
									element.trigger("change");
								} else {
									element.html(before);
									element.blur();
									if (!capabilities.contentEditableSupportsInput) {
										storeViewValueInModel();
									}
								}
							}
						} else {
							document.execCommand("insertText", false, pastedData);
							element.trigger("change");
						}
					}
					return false;
				});

				element.keypress(function(event) {
					if (attributes.change) {
						scope.$apply(attributes.change);
					}
					var charCode = (typeof event.which === "number") ? event.which : event.keyCode;
					if (charCode === 13 && attributes.singleLine) { // Return
						event.preventDefault();
						element.blur();
						return true;
					} else if (event.metaKey || // On firefox, the meta key, delete, and arrows need to be ignored.
						charCode === 8 ||
						charCode === 0) {
						return true;
					} else if (attributes.type === "numeric" &&
						(charCode !== 46 && (charCode < 48 || charCode > 57) || // Is anything other than 0-9, a dash, or a period
						(charCode === 46 && element.text().indexOf(".") > -1))) { // Make sure if we're adding a period, we don't already have one

						if (charCode === 45 && element.text().indexOf("-") === -1) {
							var before = element.text();
							setTimeout(function(){
								if (!$.isNumeric(element.text())) {
									element.html(before);
								}
							});
							return true;
						}
						return false;
					}
					return true;
				});

				// Redundant in most browsers, but in IE, input doesn't fire for delete.
				element.keydown(function(event) {
					var charCode = (typeof event.which === "number") ? event.which : event.keyCode;
					if (charCode === 8 && attributes.change) {
						scope.$apply(attributes.change);
					}
				});

				if (!capabilities.contentEditableSupportsInput) {
					element.keyup(function() {
						storeViewValueInModel();
					});
				}

				// model -> view
				controller.$render = function() {

					// Delay reading of attributes.filterView, otherwise it will appear to be undefined
					// http://stackoverflow.com/questions/14547425/angularjs-cant-read-dynamically-set-attributes
					$timeout(function() {
						var viewValue = controller.$viewValue;
						if (attributes.filterView) {
							viewValue = filterParser.filter(attributes.filterView, viewValue);
						}
						element.html(viewValue);

						// Workaround for issue with medium-editor
						if (viewValue && viewValue.length > 0 && element.hasClass("medium-editor-placeholder")) {
							element.removeClass("medium-editor-placeholder");
						}
					});
				};

				// Load init value from DOM
				controller.$setViewValue(element.html());
			}
		};
	}]);<commit_msg>Ignore control key when sending IE, keyup event.<commit_after>"use strict";

angular.module("hikeio").
	directive("contenteditable", ["$timeout", "capabilities", "filterParser", function($timeout, capabilities, filterParser) {

		return {
			require: "ngModel",
			link: function(scope, element, attributes, controller) {

				var storeViewValueInModel = function() {
					scope.$apply(function() {
						var viewValue = "";
						if (attributes.type === "text") {
							viewValue = element.text();
						} else if (attributes.type === "numeric") {
							viewValue = parseFloat(element.html()) + "";
							if (isNaN(viewValue)) {
								element.html("");
								viewValue = 0;
							} else if (viewValue !== element.html() && !element.html().match(/[0-9\.]*/)) { // Firefox adds
's everywehre, this cleans them up
								element.html(viewValue);
							}
						} else {
							viewValue = element.html();
							if (element.text() === "" && viewValue !== "") {
								viewValue = "";
								element.html("");
							}
						}

						if (attributes.filterModel) {
							viewValue = filterParser.filter(attributes.filterModel, viewValue);
						}

						controller.$setViewValue(viewValue);
					});

					if (attributes.change) {
						scope.$apply(attributes.change);
					}
				};

				// view -> model
				element.on("input", function() {
					storeViewValueInModel();
				});

				element.on("paste", function(event) {
					var clipboardData = event.originalEvent.clipboardData || window.clipboardData;
					if (clipboardData) {
						var pastedData = clipboardData.getData("text/plain");
						if (attributes.type === "numeric") {
							if (($.isNumeric(pastedData) && (!attributes.positive || parseFloat(pastedData) > 0)) || pastedData === ".") {
								// programmatically paste to ensure that result will be numeric
								var before = element.html();
								document.execCommand("insertText", false, pastedData);
								var after = element.html();
								if ($.isNumeric(after) && (!attributes.positive || parseFloat(after) > 0)) {
									element.trigger("change");
								} else {
									element.html(before);
									element.blur();
									if (!capabilities.contentEditableSupportsInput) {
										storeViewValueInModel();
									}
								}
							}
						} else {
							document.execCommand("insertText", false, pastedData);
							element.trigger("change");
						}
					}
					return false;
				});

				element.keypress(function(event) {
					if (attributes.change) {
						scope.$apply(attributes.change);
					}
					var charCode = (typeof event.which === "number") ? event.which : event.keyCode;
					if (charCode === 13 && attributes.singleLine) { // Return
						event.preventDefault();
						element.blur();
						return true;
					} else if (event.metaKey || // On firefox, the meta key, delete, and arrows need to be ignored.
						charCode === 8 ||
						charCode === 0) {
						return true;
					} else if (attributes.type === "numeric" &&
						(charCode !== 46 && (charCode < 48 || charCode > 57) || // Is anything other than 0-9, a dash, or a period
						(charCode === 46 && element.text().indexOf(".") > -1))) { // Make sure if we're adding a period, we don't already have one

						if (charCode === 45 && element.text().indexOf("-") === -1) {
							var before = element.text();
							setTimeout(function(){
								if (!$.isNumeric(element.text())) {
									element.html(before);
								}
							});
							return true;
						}
						return false;
					}
					return true;
				});

				// Redundant in most browsers, but in IE, input doesn't fire for delete.
				element.keydown(function(event) {
					var charCode = (typeof event.which === "number") ? event.which : event.keyCode;
					if (charCode === 8 && attributes.change) {
						scope.$apply(attributes.change);
					}
				});

				if (!capabilities.contentEditableSupportsInput ) {
					element.keyup(function(event) {
						var charCode = (typeof event.which === "number") ? event.which : event.keyCode;
						if (!event.ctrlKey && charCode !== 17) {
							storeViewValueInModel();
						}
					});
				}

				// model -> view
				controller.$render = function() {

					// Delay reading of attributes.filterView, otherwise it will appear to be undefined
					// http://stackoverflow.com/questions/14547425/angularjs-cant-read-dynamically-set-attributes
					$timeout(function() {
						var viewValue = controller.$viewValue;
						if (attributes.filterView) {
							viewValue = filterParser.filter(attributes.filterView, viewValue);
						}
						element.html(viewValue);

						// Workaround for issue with medium-editor
						if (viewValue && viewValue.length > 0 && element.hasClass("medium-editor-placeholder")) {
							element.removeClass("medium-editor-placeholder");
						}
					});
				};

				// Load init value from DOM
				controller.$setViewValue(element.html());
			}
		};
	}]);<|endoftext|>


<commit_before>(
  function Annotation(properties){
    this['@context'] = "http://www.w3.org/ns/oa-context-20130208.json"
    this['@type'] = "oa:Annotation"
    // @id optional

    for (var prop in properties) {
      this[prop] = properties[prop]
    }
  }

  Annotation.prototype.toRdf = function() {
    // should print in format:
    //
    // <MyAnnoId> a oa:Annotation ;
    // oa:hasBody <urn:uuid:6C97B503-25EE-4E37-875C-B7C850E13194> ;
    // oa:hasTarget <http://en.wikipedia.org/> .

    // <urn:uuid:6C97B503-25EE-4E37-875C-B7C850E13194> a oa:SpecificResource ;
    // oa:hasSource <http://www.youtube.com/watch?v=uPh81LIe7B8> ;
    // oa:hasSelector <urn:uuid:40F2B17E-7CA2-42C2-B5AF-5F35E5992B8B> .

    // <urn:uuid:40F2B17E-7CA2-42C2-B5AF-5F35E5992B8B> a oa:FragmentSelector ;

    // rdf:value "t=npt:35,60" .
    //
    // example from: http://www.w3.org/community/openannotation/wiki/Cookbook

  }

  function Annotator(options){
    // annotations have a target & a body
    // preferably these will be URIs but a body can be plain text with guid
    // if loaded into a web page, target is current url
    // else URI must be supplied

    if (typeof options === 'undefined') { options = {} }

    var TYPES = {
      dataset: 'dctypes:Dataset',
      image: 'dctypes:Image',
      movingImage: 'dctypes:MovingImage',
      text: 'dctypes:Text',
      sound: 'dctypes:Sound'
    }

    this.targetDocument = options.target || window.location.href
    // this.targetType = options.targetType || TYPES.dataset
    this.annotations = options.dataSource || []
    this.serializer = options.serializer || 'https://github.com/ritchiea/foster'
  }

  Annotator.prototype.createAnnotation = function (properties, callback) {

    var newAnnotation = new Annotation(properties)
    this.annotations.push(newAnnotation)
    return newAnnotation
  }

  Reader = function(options) {

  }

  Annotateable = function(options) {

    if (typeof options === 'undefined') { var options = {} }

    // create custom event
    if (window.CustomEvent) {
      var annotationClickEvent = new CustomEvent('foster.clickAnnotateable', {detail: {createAnnotationFromSource: 'true'}});
    } else {
      var annotationClickEvent = document.createEvent('CustomEvent');
      annotationClickEvent.initCustomEvent('foster.clickAnnotateable', true, true, {createAnnotationFromSource: 'true'});
    }

    this.writer = new Annotator(options)

    var annotationClassName = options.annotationClass || 'annotation-element'
    var annotatationElements = document.getElementsByClassName(annotationClassName)
    for (var i = 0; i < annotationElements.length; i++) {
      annotationElements[i].addEventListener('click', function(event) {

        event.target.dispatchEvent(annotationClickEvent);
      })
    }

    var targetEl = document.getElementById(options.selector) || document.getElementByTagName('html')[0]

    targetEl.addEventListener('dragend', function (event){

      event.preventDefault()
      event.stopPropagation()

      // the dropped element requires a data attribute with annotation data
      // e.g. <id='stats' data-annotation='{hasBody: "...", annotatedBy: "..."}'>
      //
      // format:
      /*
       "annotatedBy": {
          "@id": "http://www.example.org/people/person1",
          "@type": "foaf:Person",
          "mbox": {
              "@id": "mailto:person1@example.org"
          },
          "name": "Person One"
        },

        "hasBody": "http://www.example.org/body1"
      */
      // examples available:
      // http://www.openannotation.org/spec/core/publishing.html
      //
      var dropped = JSON.parse(event.srcElement.dataset.annotation),
      var elem = event.toElement
      dropped.hasTarget = {
        "@id": "", // generate uuid here
        "@type": "oa:SpecificResource",
        conformsTo: "http://tools.ietf.org/rfc/rfc3236",
        value: elem.id
      }

      writer.createAnnotation(dropped)
    })

    targetEl.addEventListener('mouseup', function (event){

      if (typeof window.getSelection !== 'undefined') {

        var listener = function (evt){
          var selection = window.getSelection
          var exact = selection.toString(),
            prefix = selection.anchorNode.data.substring(0,selection.anchorOffset),
            suffix = selection.focusNode.data.substring(selection.focusOffset,0),
            annotationData = JSON.parse(evt.srcElement.dataset.annotation)
          annotationData.hasTarget = {
            "@type": "oa:SpecificResource",
            selector: 'oa:TextQuoteSelector',
            exact: exact,
            prefix: prefix,
            suffix: suffix
          }

          writer.createAnnotation(annotationData)
        }

        document.addEventListener('foster.clickAnnotateable', listener, false)

        document.addEventListener('mousedown', function(e) {
          document.removeEventListener('foster.clickAnnotateable', listener, false)
        })
      }
    })
  }

  Annotateable.prototype.getAnnotations = function() {
    return this.writer.annotations
  }

  Annotateable.prototype.getAnnotationsAsRdf = function() {
    var rdf = []
    var annotations = this.writer.annotations
    for (var i = 0; i < annotations.length; i++) {
      rdf.push(annotations[i].toRdf())
    }
    return rdf
  }

  window.Foster = Annotateable

)();
<commit_msg>better<commit_after>(
  function Annotation(properties){
    this['@context'] = "http://www.w3.org/ns/oa-context-20130208.json"
    this['@type'] = "oa:Annotation"
    this['annotatedAt'] = new Date
    // @id optional

    for (var prop in properties) {
      this[prop] = properties[prop]
    }
  }

  Annotation.prototype.toRdf = function() {
    // should print in format:
    //
    // <MyAnnoId> a oa:Annotation ;
    // oa:hasBody <urn:uuid:6C97B503-25EE-4E37-875C-B7C850E13194> ;
    // oa:hasTarget <http://en.wikipedia.org/> .

    // <urn:uuid:6C97B503-25EE-4E37-875C-B7C850E13194> a oa:SpecificResource ;
    // oa:hasSource <http://www.youtube.com/watch?v=uPh81LIe7B8> ;
    // oa:hasSelector <urn:uuid:40F2B17E-7CA2-42C2-B5AF-5F35E5992B8B> .

    // <urn:uuid:40F2B17E-7CA2-42C2-B5AF-5F35E5992B8B> a oa:FragmentSelector ;

    // rdf:value "t=npt:35,60" .
    //
    // example from: http://www.w3.org/community/openannotation/wiki/Cookbook

  }

  function Annotator(options){
    // annotations have a target & a body
    // preferably these will be URIs but a body can be plain text with guid
    // if loaded into a web page, target is current url
    // else URI must be supplied

    if (typeof options === 'undefined') { options = {} }

    var TYPES = {
      dataset: 'dctypes:Dataset',
      image: 'dctypes:Image',
      movingImage: 'dctypes:MovingImage',
      text: 'dctypes:Text',
      sound: 'dctypes:Sound'
    }

    this.targetDocument = options.target || window.location.href
    // this.targetType = options.targetType || TYPES.dataset
    this.annotations = options.dataSource || []
    this.serializer = options.serializer || 'https://github.com/ritchiea/foster'
  }

  Annotator.prototype.createAnnotation = function (properties, callback) {

    var newAnnotation = new Annotation(properties)
    this.annotations.push(newAnnotation)
    return newAnnotation
  }

  Reader = function(options) {

  }

  Annotateable = function(options) {

    if (typeof options === 'undefined') { var options = {} }

    // create custom event
    if (window.CustomEvent) {
      var annotationClickEvent = new CustomEvent('foster.clickAnnotateable', {detail: {createAnnotationFromSource: 'true'}})
    } else {
      var annotationClickEvent = document.createEvent('CustomEvent')
      annotationClickEvent.initCustomEvent('foster.clickAnnotateable', true, true, {createAnnotationFromSource: 'true'})
    }

    var annotationClassName = options.annotationClass || 'annotation-element'
    var annotatationElements = document.getElementsByClassName(annotationClassName)
    if (annotationElements.length) {
      for (var i = 0; i < annotationElements.length; i++) {
        annotationElements[i].addEventListener('click', function(event) {

          event.target.dispatchEvent(annotationClickEvent)
        })
      }
    }

    this.writer = new Annotator(options)

    var targetEl = document.getElementById(options.selector) || document.getElementByTagName('html')[0]

    targetEl.addEventListener('dragend', function (event){

      event.preventDefault()
      event.stopPropagation()

      // the dropped element requires a data attribute with annotation data
      // e.g. <id='stats' data-annotation='{hasBody: "...", annotatedBy: "..."}'>
      //
      // format:
      /*
       "annotatedBy": {
          "@id": "http://www.example.org/people/person1",
          "@type": "foaf:Person",
          "mbox": {
              "@id": "mailto:person1@example.org"
          },
          "name": "Person One"
        },

        "hasBody": "http://www.example.org/body1"
      */
      // examples available:
      // http://www.openannotation.org/spec/core/publishing.html
      //
      var dropped = JSON.parse(event.srcElement.dataset.annotation),
      var elem = event.toElement
      dropped.hasTarget = {
        '@type': 'oa:SpecificResource',
        hasSelector: {
          // '@id': uuid
          '@type': 'oa:FragmentSelector',
          conformsTo: 'http://tools.ietf.org/rfc/rfc3236',
          value: elem.id
        }
      }

      writer.createAnnotation(dropped)
    })

    targetEl.addEventListener('mouseup', function (event){

      if (typeof window.getSelection !== 'undefined') {

        var listener = function (evt){
          var selection = window.getSelection
          var exact = selection.toString(),
            prefix = selection.anchorNode.data.substring(0,selection.anchorOffset),
            suffix = selection.focusNode.data.substring(selection.focusOffset,0),
            annotationData = JSON.parse(evt.srcElement.dataset.annotation)
          annotationData.hasTarget = {
            '@type': 'oa:SpecificResource',
            hasSelector: {
              // '@id': uuid
              '@type': 'oa:TextQuoteSelector',
              exact: exact,
              prefix: prefix,
              suffix: suffix
            }
          }

          writer.createAnnotation(annotationData)
        }

        document.addEventListener('foster.clickAnnotateable', listener, false)

        document.addEventListener('mousedown', function(e) {
          document.removeEventListener('foster.clickAnnotateable', listener, false)
        })
      }
    })
  }

  Annotateable.prototype.getAnnotations = function() {
    if (this.writer.annotations.length) { return this.writer.annotations }
  }

  Annotateable.prototype.getAnnotationsAsRdf = function() {

    if (!this.writer.annotations.length) {
      return false
    } else {

      var rdf = []
      var annotations = this.writer.annotations
      for (var i = 0; i < annotations.length; i++) {
        rdf.push(annotations[i].toRdf())
      }
      return rdf
    }
  }

  window.Foster = Annotateable

)();
<|endoftext|>


<commit_before>//
// Test the widget framework.
//
casper.notebook_test(function () {
    //this.test.begin("widget tests (notebook)", 2, function(test) {

    // Utility function that allows us to easily execute a cell of python code
    // and wait for the results.
    var that = this;
    var run_python_code = function(code){
        var index = that.evaluate(function (code) {
            var index = IPython.notebook.ncells();
            var cell = IPython.notebook.insert_cell_at_index('code', index);
            cell.set_text(code);
            cell.execute();
            return index;
        }, code);

        that.wait_for_output(index);
        return index;
    };

    // Test widget dependencies ////////////////////////////////////////////////
    this.then(function () {

        // Check if the WidgetManager class is defined.
        this.test.assert(this.evaluate(function() {
            return IPython.WidgetManager != undefined;
        }), 'WidgetManager class is defined');
    });

    run_python_code('from IPython.html import widgets\n' +
                    'from IPython.display import display, clear_output\n' +
                    'print("Success")');
    this.wait(500); // Wait for require.js async callbacks to load dependencies.

    this.then(function () {
        // Check if the widget manager has been instanciated.
        this.test.assert(this.evaluate(function() {
            return IPython.widget_manager != undefined;
        }), 'Notebook widget manager instanciated');
    });

    // Check widget mapping ////////////////////////////////////////////////////
    var names_cell_index = run_python_code('names = [name for name in dir(widgets)' +
        ' if name.endswith("Widget") and name!= "Widget"]\n' +
        'for name in names:\n' +
        '    print(name)\n');

    this.then(function () {
        // Get the widget names that are registered with the widget manager.  Assume
        // a 1 to 1 mapping of model and widgets names (model names just have 'model'
        // suffixed).
        var javascript_names = this.evaluate(function () {
            names = [];
            for (var name in IPython.widget_manager.widget_model_types) {
                names.push(name.replace('Model',''));
            }
            return names;
        });

        // Get the widget names registered in python.
        var python_names = this.get_output_cell(names_cell_index).text.split('\n');

        // Make sure the two lists have the same items.
        for (var i in javascript_names) {
            var javascript_name = javascript_names[i];
            var found = false;
            for (var j in python_names) {
                var python_name = python_names[j];
                if (python_name==javascript_name) {
                    found = true;
                    break;
                }
            }
            this.test.assert(found, javascript_name + ' exists in python');
        }
        for (var i in python_names) {
            var python_name = python_names[i];
            if (python_name.length > 0) {
                var found = false;
                for (var j in javascript_names) {
                    var javascript_name = javascript_names[j];
                    if (python_name==javascript_name) {
                        found = true;
                        break;
                    }
                }
                this.test.assert(found, python_name + ' exists in javascript');
            }
        }
    });

    // Test button widget //////////////////////////////////////////////////////
    button_cell_index = run_python_code('button = widgets.ButtonWidget(description="Title")\n' +
        'display(button)\n'+
        'print("Success")\n' +
        'def handle_click(sender):\n' +
        '    print("Clicked")\n' +
        'button.on_click(handle_click)');

    this.then(function () {
        var button_output = this.get_output_cell(button_cell_index).text;
        this.test.assert(button_output == 'Success\n', 'Create button widget, cell executed with correct output.');

        this.test.assert(casper.evaluate(function (i) {
            var $cell = IPython.notebook.get_cell(i).element;
            return $cell.find('.widget-area').find('.widget-subarea').length > 0;
        },
        {i : button_cell_index}), 'Create button widget, widget subarea exist.');

        this.test.assert(casper.evaluate(function (i) {
            var $cell = IPython.notebook.get_cell(i).element;
            return $cell.find('.widget-area').find('.widget-subarea').find('button').length > 0;
        },
        {i : button_cell_index}), 'Create button widget, widget button exist.');

        this.test.assert(casper.evaluate(function (i) {
            var $cell = IPython.notebook.get_cell(i).element;
            return $cell.find('.widget-area').find('.widget-subarea').find('button').html() == 'Title';
        },
        {i : button_cell_index}), 'Set button description.');

        casper.evaluate(function (i) {
            var $cell = IPython.notebook.get_cell(i).element;
            $cell.find('.widget-area').find('.widget-subarea').find('button').click();
        },
        {i : button_cell_index});
    });

    this.wait(1000); // Wait for click to execute in kernel and write output

    this.then(function () {
        var button_output = this.get_output_cell(button_cell_index, 1).text;
        this.test.assert(button_output == 'Clicked\n', 'Button click event fires.');
    });

    //}); // end of test.begin
});

<commit_msg>Cleaned up utilities in widget casper js tests<commit_after>// Test the widget framework.
casper.notebook_test(function () {
    var index;

    // Test widget dependencies ////////////////////////////////////////////////
    this.then(function () {

        // Check if the WidgetManager class is defined.
        this.test.assert(this.evaluate(function() {
            return IPython.WidgetManager != undefined;
        }), 'WidgetManager class is defined');
    });

    index = append_cell(
        'from IPython.html import widgets\n' +
        'from IPython.display import display, clear_output\n' +
        'print("Success")');
    execute_cell_then(index);

    this.wait(500); // Wait for require.js async callbacks to load dependencies.

    this.then(function () {
        // Check if the widget manager has been instanciated.
        this.test.assert(this.evaluate(function() {
            return IPython.widget_manager != undefined;
        }), 'Notebook widget manager instanciated');
    });

    // Check widget mapping ////////////////////////////////////////////////////
    index = append_cell(
        'names = [name for name in dir(widgets)' +
        ' if name.endswith("Widget") and name!= "Widget"]\n' +
        'for name in names:\n' +
        '    print(name)\n');
    execute_cell_then(index, function(index){

        // Get the widget names that are registered with the widget manager.  Assume
        // a 1 to 1 mapping of model and widgets names (model names just have 'model'
        // suffixed).
        var javascript_names = this.evaluate(function () {
            names = [];
            for (var name in IPython.widget_manager.widget_model_types) {
                names.push(name.replace('Model',''));
            }
            return names;
        });

        // Get the widget names registered in python.
        var python_names = this.get_output_cell(index).text.split('\n');

        // Make sure the two lists have the same items.
        for (var i in javascript_names) {
            var javascript_name = javascript_names[i];
            var found = false;
            for (var j in python_names) {
                var python_name = python_names[j];
                if (python_name==javascript_name) {
                    found = true;
                    break;
                }
            }
            this.test.assert(found, javascript_name + ' exists in python');
        }
        for (var i in python_names) {
            var python_name = python_names[i];
            if (python_name.length > 0) {
                var found = false;
                for (var j in javascript_names) {
                    var javascript_name = javascript_names[j];
                    if (python_name==javascript_name) {
                        found = true;
                        break;
                    }
                }
                this.test.assert(found, python_name + ' exists in javascript');
            }
        }
    });

    // Test button widget //////////////////////////////////////////////////////
    var button_cell_index = append_cell(
        'button = widgets.ButtonWidget(description="Title")\n' +
        'display(button)\n'+
        'print("Success")\n' +
        'def handle_click(sender):\n' +
        '    print("Clicked")\n' +
        'button.on_click(handle_click)');
    execute_cell_then(button_cell_index, function(index){

        var button_output = this.get_output_cell(index).text;
        this.test.assert(button_output == 'Success\n',
            'Create button widget, cell executed with correct output.');

        this.test.assert(cell_element_exists(index,
            '.widget-area .widget-subarea'),
            'Create button widget, widget subarea exist.');

        this.test.assert(cell_element_exists(index,
            '.widget-area .widget-subarea button'),
            'Create button widget, widget button exist.');

        this.test.assert(cell_element_function(index,
            '.widget-area .widget-subarea button', 'html')=='Title',
            'Set button description.');

        cell_element_function(index,
            '.widget-area .widget-subarea button', 'click');
    });

    this.wait(500); // Wait for click to execute in kernel and write output

    this.then(function () {
        this.test.assert(this.get_output_cell(button_cell_index, 1).text == 'Clicked\n',
            'Button click event fires.');
    });

    index = append_cell(
        'button.close()\n'+
        'print("Success")\n');
    execute_cell_then(index, function(index){

        var button_output = this.get_output_cell(index).text;
        this.test.assert(button_output == 'Success\n',
            'Close button, cell executed with correct output.');

        this.test.assert(! cell_element_exists(button_cell_index,
            '.widget-area .widget-subarea button'),
            'Remove button, widget button doesn\'t exist.');
    });
});

<|endoftext|>


<commit_before>var input, button, greeting;

function setup() {
  var myCanvas = createCanvas(400,400);
  myCanvas.parent("p5Canvas");
  greeting = createElement('h2', 'What is your birthday?');
  //greeting.position(input.x, input.y);
  input = createInput("format DD-MM-YY");
  button = createButton('Generate!');
  button.position(input.x + input.width, input.y);
  button.mousePressed(drawTurtle);

}

function drawTurtle() {
  background(0);
      var turtle = makeTurtle(130, 80);
      turtle.penDown();
      turtle.setColor(255);
      for (var i = 0; i < 1000; i++) {
          turtle.forward(150);
          turtle.right(141.5);
          turtle.forward(60);
          if (i % 20 === 0) {
              turtle.forward(70);
          }
      }
}

//=======================================================
// TURTLE GRAPHICS IMPLEMENTATION
// Roger Dannenberg, 2016
//
// makeTurtle(x, y) -- make a turtle at x, y, facing right, pen down
// left(d) -- turn left by d degrees
// right(d) -- turn right by d degrees
// forward(p) -- move forward by p pixels
// back(p) -- move back by p pixels
// penDown() -- pen down
// penUp() -- pen up
// goto(x, y) -- go straight to this location
// setColor(color) -- set the drawing color
// setWeight(w) -- set line width to w
// face(d) -- turn to this absolute direction in degrees
// angleTo(x, y) -- what is the angle from my heading to location x, y?
// turnToward(x, y, d) -- turn by d degrees toward location x, y
// distanceTo(x, y) -- how far is it to location x, y?

function turtleLeft(d) {
    this.angle -= d;
}

function turtleRight(d) {
    this.angle += d;
}

function turtleForward(p) {
    var rad = radians(this.angle);
    var newx = this.x + cos(rad) * p;
    var newy = this.y + sin(rad) * p;
    this.goto(newx, newy);
}

function turtleBack(p) {
    this.forward(-p);
}

function turtlePenDown() {
    this.penIsDown = true;
}

function turtlePenUp() {
    this.penIsDown = false;
}

function turtleGoTo(x, y) {
    if (this.penIsDown) {
      stroke(this.color);
      strokeWeight(this.weight);
      line(this.x, this.y, x, y);
    }
    this.x = x;
    this.y = y;
}

function turtleDistTo(x, y) {
    return sqrt(sq(this.x - x) + sq(this.y - y));
}

function turtleAngleTo(x, y) {
    var absAngle = degrees(atan2(y - this.y, x - this.x));
    var angle = ((absAngle - this.angle) + 360) % 360.0;
    return angle;
}

function turtleTurnToward(x, y, d) {
    var angle = this.angleTo(x, y);
    if (angle < 180) {
        this.angle += d;
    } else {
        this.angle -= d;
    }
}

function turtleSetColor(c) {
    this.color = c;
}

function turtleSetWeight(w) {
    this.weight = w;
}

function turtleFace(angle) {
    this.angle = angle;
}

function makeTurtle(tx, ty) {
    var turtle = {x: tx, y: ty,
                  angle: 0.0,
                  penIsDown: true,
                  color: color(128),
                  weight: 1,
                  left: turtleLeft, right: turtleRight,
                  forward: turtleForward, back: turtleBack,
                  penDown: turtlePenDown, penUp: turtlePenUp,
                  goto: turtleGoTo, angleto: turtleAngleTo,
                  turnToward: turtleTurnToward,
                  distanceTo: turtleDistTo, angleTo: turtleAngleTo,
                  setColor: turtleSetColor, setWeight: turtleSetWeight,
                  face: turtleFace};
    return turtle;
}
<commit_msg>push test<commit_after>var input, button, greeting;

function setup() {
  var myCanvas = createCanvas(400,400);
  myCanvas.parent("p5Canvas");
  greeting = createElement('h2', 'What is your birthday?');
  //greeting.position(input.x, input.y);
  input = createInput("format DD-MM-YY");
  button = createButton('Generate!');
  button.position(input.x + input.width, input.y);
  button.mousePressed(drawTurtle);

}

function drawTurtle() {
  background(0);
      var turtle = makeTurtle(130, 80);
      turtle.penDown();
      turtle.setColor(255, 0, 0);
      for (var i = 0; i < 1000; i++) {
          turtle.forward(150);
          turtle.right(141.5);
          turtle.forward(60);
          if (i % 20 === 0) {
              turtle.forward(70);
          }
      }
}

//=======================================================
// TURTLE GRAPHICS IMPLEMENTATION
// Roger Dannenberg, 2016
//
// makeTurtle(x, y) -- make a turtle at x, y, facing right, pen down
// left(d) -- turn left by d degrees
// right(d) -- turn right by d degrees
// forward(p) -- move forward by p pixels
// back(p) -- move back by p pixels
// penDown() -- pen down
// penUp() -- pen up
// goto(x, y) -- go straight to this location
// setColor(color) -- set the drawing color
// setWeight(w) -- set line width to w
// face(d) -- turn to this absolute direction in degrees
// angleTo(x, y) -- what is the angle from my heading to location x, y?
// turnToward(x, y, d) -- turn by d degrees toward location x, y
// distanceTo(x, y) -- how far is it to location x, y?

function turtleLeft(d) {
    this.angle -= d;
}

function turtleRight(d) {
    this.angle += d;
}

function turtleForward(p) {
    var rad = radians(this.angle);
    var newx = this.x + cos(rad) * p;
    var newy = this.y + sin(rad) * p;
    this.goto(newx, newy);
}

function turtleBack(p) {
    this.forward(-p);
}

function turtlePenDown() {
    this.penIsDown = true;
}

function turtlePenUp() {
    this.penIsDown = false;
}

function turtleGoTo(x, y) {
    if (this.penIsDown) {
      stroke(this.color);
      strokeWeight(this.weight);
      line(this.x, this.y, x, y);
    }
    this.x = x;
    this.y = y;
}

function turtleDistTo(x, y) {
    return sqrt(sq(this.x - x) + sq(this.y - y));
}

function turtleAngleTo(x, y) {
    var absAngle = degrees(atan2(y - this.y, x - this.x));
    var angle = ((absAngle - this.angle) + 360) % 360.0;
    return angle;
}

function turtleTurnToward(x, y, d) {
    var angle = this.angleTo(x, y);
    if (angle < 180) {
        this.angle += d;
    } else {
        this.angle -= d;
    }
}

function turtleSetColor(c) {
    this.color = c;
}

function turtleSetWeight(w) {
    this.weight = w;
}

function turtleFace(angle) {
    this.angle = angle;
}

function makeTurtle(tx, ty) {
    var turtle = {x: tx, y: ty,
                  angle: 0.0,
                  penIsDown: true,
                  color: color(128),
                  weight: 1,
                  left: turtleLeft, right: turtleRight,
                  forward: turtleForward, back: turtleBack,
                  penDown: turtlePenDown, penUp: turtlePenUp,
                  goto: turtleGoTo, angleto: turtleAngleTo,
                  turnToward: turtleTurnToward,
                  distanceTo: turtleDistTo, angleTo: turtleAngleTo,
                  setColor: turtleSetColor, setWeight: turtleSetWeight,
                  face: turtleFace};
    return turtle;
}
<|endoftext|>


<commit_before>/*globals define, WebGMEGlobal*/
/*jshint browser: true*/
/**
 * Generated by VisualizerGenerator 0.1.0 from webgme on Sat Apr 16 2016 08:51:41 GMT-0700 (PDT).
 */

define(['js/Constants',
    'js/Utils/GMEConcepts',
    'js/NodePropertyNames'
], function (CONSTANTS,
             GMEConcepts,
             nodePropertyNames) {

    'use strict';

    var CodeEditorControl;

    // the final leaf is a 'mode' object for the CodeMirror to use
    var TypeToAttributeMap = {};

    CodeEditorControl = function (options) {

        this._logger = options.logger.fork('Control');
        this._client = options.client;

        // Initialize core collections and variables
        this._widget = options.widget;

	// the component config comes from widget._config
	this._config = this._widget._config;
	TypeToAttributeMap = this._config.attrToSyntaxMap;

        this.currentNodeInfo = {id: null, children: [], parentId: null};
        this._selfPatterns = {};

        this._initWidgetEventHandlers();

        this._logger.debug('ctor finished');
    };

    CodeEditorControl.prototype._initWidgetEventHandlers = function () {
        this._widget.onNodeClick = function (id) {
            // Change the current active object
            WebGMEGlobal.State.registerActiveObject(id);
        };
    };

    /* * * * * * * * Visualizer content update callbacks * * * * * * * */
    // One major concept here is with managing the territory. The territory
    // defines the parts of the project that the visualizer is interested in
    // (this allows the browser to then only load those relevant parts).
    CodeEditorControl.prototype.selectedObjectChanged = function (nodeId) {
        var self = this,
	desc,
	nodeName;

        self._logger.debug('activeObject nodeId \'' + nodeId + '\'');

        if (nodeId && nodeId != this.currentNodeInfo.id) {
            // Remove current territory patterns
            if (self._territoryId) {
		            self._client.removeUI(self._territoryId);
            }

            this.currentNodeInfo.id = nodeId;
            this.currentNodeInfo.parentId = undefined;

            desc = this._getObjectDescriptor(nodeId);
            nodeName = (desc && desc.name);
            if (desc) {
                this.currentNodeInfo.parentId = desc.parentId;
            }

            this._refreshBtnModelHierarchyUp();

            // Put new node's info into territory rules
            // TODO: Update to get depth of children to load from component config
            // TODO: Update to get parents as well?
            self._selfPatterns[nodeId] = {children: self._config.loadDepth};  // Territory "rule"

            self._territoryId = self._client.addUI(self, function (events) {
                self._eventCallback(events);
            });

            // Update the territory
            self._client.updateTerritory(self._territoryId, self._selfPatterns);
        }
    };

    CodeEditorControl.prototype._refreshBtnModelHierarchyUp = function () {
        if (this.currentNodeInfo.id) {
            this.$btnModelHierarchyUp.show();
        } else {
            this.$btnModelHierarchyUp.hide();
        }
    };

    // This next function retrieves the relevant node information for the widget
    CodeEditorControl.prototype._getObjectDescriptor = function (nodeId) {
	var self = this;
	var client = this._client;
        var nodeObj = client.getNode(nodeId),
            objDescriptor;

        if (nodeObj) {
            objDescriptor = {
                'id': undefined,
		'type': undefined,
                'name': undefined,
                'childrenIds': undefined,
                'parentId': undefined,
                'isConnection': false,
		'iconPath': null,
		'codeAttributes': {}
            };

	    var nodeMetaName = undefined;
	    var baseId = nodeObj.getMetaTypeId();
	    var baseObj = client.getNode(baseId);
	    if (baseObj) {
		nodeMetaName = baseObj.getAttribute('name');
		if (nodeMetaName && TypeToAttributeMap[nodeMetaName]) {
		    var attrNames = Object.keys(TypeToAttributeMap[nodeMetaName]);
		    attrNames.map(function(attrName) {
			var value = nodeObj.getAttribute(attrName);
			if (!value) value = '';
			objDescriptor.codeAttributes[attrName] = {
			    value: value,
			    mode: TypeToAttributeMap[nodeMetaName][attrName]
			};
		    });
		}
	    }

            objDescriptor.id = nodeObj.getId();
            objDescriptor.type = nodeMetaName;
            objDescriptor.name = nodeObj.getAttribute('name');
            objDescriptor.childrenIds = nodeObj.getChildrenIds();
            objDescriptor.childrenNum = objDescriptor.childrenIds.length;
            objDescriptor.parentId = nodeObj.getParentId();
	    objDescriptor.iconPath = nodeObj.getRegistry('TreeItemCollapsedIcon');
            objDescriptor.isConnection = GMEConcepts.isConnection(nodeId);  // GMEConcepts can be helpful

	    if (objDescriptor.type != self._config.rootType) {
		// load parent until we get to rootType
		self._selfPatterns[objDescriptor.parentId] = {children: self._config.loadDepth};
		self._client.updateTerritory(self._territoryId, self._selfPatterns);
	    }
        }
        return objDescriptor;
    };

    /* * * * * * * * Node Event Handling * * * * * * * */
    CodeEditorControl.prototype._eventCallback = function (events) {
        var i = events ? events.length : 0,
            event;

        this._logger.debug('_eventCallback \'' + i + '\' items');

        while (i--) {
            event = events[i];
            switch (event.etype) {
                case CONSTANTS.TERRITORY_EVENT_LOAD:
                    this._onLoad(event.eid);
                    break;
                case CONSTANTS.TERRITORY_EVENT_UPDATE:
                    this._onUpdate(event.eid);
                    break;
                case CONSTANTS.TERRITORY_EVENT_UNLOAD:
                    this._onUnload(event.eid);
                    break;
                default:
                    break;
            }
        }

        this._logger.debug('_eventCallback \'' + events.length + '\' items - DONE');
    };

    CodeEditorControl.prototype._onLoad = function (gmeId) {
        var description = this._getObjectDescriptor(gmeId);
        this._widget.addNode(description);
    };

    CodeEditorControl.prototype._onUpdate = function (gmeId) {
        var description = this._getObjectDescriptor(gmeId);
        this._widget.updateNode(description);
    };

    CodeEditorControl.prototype._onUnload = function (gmeId) {
        this._widget.removeNode(gmeId);
    };

    CodeEditorControl.prototype._stateActiveObjectChanged = function (model, activeObjectId) {
        this.selectedObjectChanged(activeObjectId);
    };

    /* * * * * * * * Visualizer life cycle callbacks * * * * * * * */
    CodeEditorControl.prototype.destroy = function () {
        this._detachClientEventListeners();
        this._removeToolbarItems();
    };

    CodeEditorControl.prototype._attachClientEventListeners = function () {
        this._detachClientEventListeners();
        WebGMEGlobal.State.on('change:' + CONSTANTS.STATE_ACTIVE_OBJECT, this._stateActiveObjectChanged, this);
    };

    CodeEditorControl.prototype._detachClientEventListeners = function () {
        WebGMEGlobal.State.off('change:' + CONSTANTS.STATE_ACTIVE_OBJECT, this._stateActiveObjectChanged);
    };

    CodeEditorControl.prototype.onActivate = function () {
        this._attachClientEventListeners();
        this._displayToolbarItems();

        if (this.currentNodeInfo && typeof this.currentNodeInfo.id === 'string') {
            WebGMEGlobal.State.registerActiveObject(this.currentNodeInfo.id, {
                suppressVisualizerFromNode: true
            });
        }
    };

    CodeEditorControl.prototype.onDeactivate = function () {
        this._detachClientEventListeners();
        this._hideToolbarItems();
    };

    /* * * * * * * * * * Updating the toolbar * * * * * * * * * */
    CodeEditorControl.prototype._displayToolbarItems = function () {

        if (this._toolbarInitialized === true) {
            for (var i = this._toolbarItems.length; i--;) {
                this._toolbarItems[i].show();
            }
        } else {
            this._initializeToolbar();
        }
    };

    CodeEditorControl.prototype._hideToolbarItems = function () {

        if (this._toolbarInitialized === true) {
            for (var i = this._toolbarItems.length; i--;) {
                this._toolbarItems[i].hide();
            }
        }
    };

    CodeEditorControl.prototype._removeToolbarItems = function () {

        if (this._toolbarInitialized === true) {
            for (var i = this._toolbarItems.length; i--;) {
                this._toolbarItems[i].destroy();
            }
        }
    };

    CodeEditorControl.prototype._onModelHierarchyUp = function () {
        var myId = this.currentNodeInfo.id;
        if (this.currentNodeInfo.parentId ||
            this.currentNodeInfo.parentId === CONSTANTS.PROJECT_ROOT_ID) {
            WebGMEGlobal.State.registerActiveObject(this.currentNodeInfo.parentId);
            WebGMEGlobal.State.registerActiveSelection([myId]);
        }
    };

    CodeEditorControl.prototype._initializeToolbar = function () {
        var self = this,
            toolBar = WebGMEGlobal.Toolbar;

        this._toolbarItems = [];

        this._toolbarItems.push(toolBar.addSeparator());

        /************** GOTO PARENT IN HIERARCHY BUTTON ****************/
        this.$btnModelHierarchyUp = toolBar.addButton({
            title: 'Go to parent',
            icon: 'glyphicon glyphicon-circle-arrow-up',
            clickFn: function (/*data*/) {
                self._onModelHierarchyUp();
            }
        });
        this._toolbarItems.push(this.$btnModelHierarchyUp);

        this.$btnModelHierarchyUp.hide();

        this._toolbarInitialized = true;
    };

    return CodeEditorControl;
});
<commit_msg>working on fixing iconPath.<commit_after>/*globals define, WebGMEGlobal*/
/*jshint browser: true*/
/**
 * Generated by VisualizerGenerator 0.1.0 from webgme on Sat Apr 16 2016 08:51:41 GMT-0700 (PDT).
 */

define(['js/Constants',
    'js/Utils/GMEConcepts',
    'js/NodePropertyNames'
], function (CONSTANTS,
             GMEConcepts,
             nodePropertyNames) {

    'use strict';

    var CodeEditorControl;

    // the final leaf is a 'mode' object for the CodeMirror to use
    var TypeToAttributeMap = {};

    CodeEditorControl = function (options) {

        this._logger = options.logger.fork('Control');
        this._client = options.client;

        // Initialize core collections and variables
        this._widget = options.widget;

	// the component config comes from widget._config
	this._config = this._widget._config;
	TypeToAttributeMap = this._config.attrToSyntaxMap;

        this.currentNodeInfo = {id: null, children: [], parentId: null};
        this._selfPatterns = {};

        this._initWidgetEventHandlers();

        this._logger.debug('ctor finished');
    };

    CodeEditorControl.prototype._initWidgetEventHandlers = function () {
        this._widget.onNodeClick = function (id) {
            // Change the current active object
            WebGMEGlobal.State.registerActiveObject(id);
        };
    };

    /* * * * * * * * Visualizer content update callbacks * * * * * * * */
    // One major concept here is with managing the territory. The territory
    // defines the parts of the project that the visualizer is interested in
    // (this allows the browser to then only load those relevant parts).
    CodeEditorControl.prototype.selectedObjectChanged = function (nodeId) {
        var self = this,
	desc,
	nodeName;

        self._logger.debug('activeObject nodeId \'' + nodeId + '\'');

        if (nodeId && nodeId != this.currentNodeInfo.id) {
            // Remove current territory patterns
            if (self._territoryId) {
		            self._client.removeUI(self._territoryId);
            }

            this.currentNodeInfo.id = nodeId;
            this.currentNodeInfo.parentId = undefined;

            desc = this._getObjectDescriptor(nodeId);
            nodeName = (desc && desc.name);
            if (desc) {
                this.currentNodeInfo.parentId = desc.parentId;
            }

            this._refreshBtnModelHierarchyUp();

            // Put new node's info into territory rules
            // TODO: Update to get depth of children to load from component config
            // TODO: Update to get parents as well?
            self._selfPatterns[nodeId] = {children: self._config.loadDepth};  // Territory "rule"

            self._territoryId = self._client.addUI(self, function (events) {
                self._eventCallback(events);
            });

            // Update the territory
            self._client.updateTerritory(self._territoryId, self._selfPatterns);
        }
    };

    CodeEditorControl.prototype._refreshBtnModelHierarchyUp = function () {
        if (this.currentNodeInfo.id) {
            this.$btnModelHierarchyUp.show();
        } else {
            this.$btnModelHierarchyUp.hide();
        }
    };

    // This next function retrieves the relevant node information for the widget
    CodeEditorControl.prototype._getObjectDescriptor = function (nodeId) {
	var self = this;
	var client = this._client;
        var nodeObj = client.getNode(nodeId),
            objDescriptor;

        if (nodeObj) {
            objDescriptor = {
                'id': undefined,
		'type': undefined,
                'name': undefined,
                'childrenIds': undefined,
                'parentId': undefined,
                'isConnection': false,
		'iconPath': null,
		'codeAttributes': {}
            };

	    var nodeMetaName = undefined;
	    var baseId = nodeObj.getMetaTypeId();
	    var baseObj = client.getNode(baseId);
	    if (baseObj) {
		nodeMetaName = baseObj.getAttribute('name');
		if (nodeMetaName && TypeToAttributeMap[nodeMetaName]) {
		    var attrNames = Object.keys(TypeToAttributeMap[nodeMetaName]);
		    attrNames.map(function(attrName) {
			var value = nodeObj.getAttribute(attrName);
			if (!value) value = '';
			objDescriptor.codeAttributes[attrName] = {
			    value: value,
			    mode: TypeToAttributeMap[nodeMetaName][attrName]
			};
		    });
		}
	    }

            objDescriptor.id = nodeObj.getId();
            objDescriptor.type = nodeMetaName;
            objDescriptor.name = nodeObj.getAttribute('name');
            objDescriptor.childrenIds = nodeObj.getChildrenIds();
            objDescriptor.childrenNum = objDescriptor.childrenIds.length;
            objDescriptor.parentId = nodeObj.getParentId();
	    objDescriptor.iconPath = '/assets/DecoratorSVG/' + nodeObj.getRegistry('TreeItemCollapsedIcon');
            objDescriptor.isConnection = GMEConcepts.isConnection(nodeId);  // GMEConcepts can be helpful

	    if (objDescriptor.type != self._config.rootType) {
		// load parent until we get to rootType
		self._selfPatterns[objDescriptor.parentId] = {children: self._config.loadDepth};
		self._client.updateTerritory(self._territoryId, self._selfPatterns);
	    }
        }
        return objDescriptor;
    };

    /* * * * * * * * Node Event Handling * * * * * * * */
    CodeEditorControl.prototype._eventCallback = function (events) {
        var i = events ? events.length : 0,
            event;

        this._logger.debug('_eventCallback \'' + i + '\' items');

        while (i--) {
            event = events[i];
            switch (event.etype) {
                case CONSTANTS.TERRITORY_EVENT_LOAD:
                    this._onLoad(event.eid);
                    break;
                case CONSTANTS.TERRITORY_EVENT_UPDATE:
                    this._onUpdate(event.eid);
                    break;
                case CONSTANTS.TERRITORY_EVENT_UNLOAD:
                    this._onUnload(event.eid);
                    break;
                default:
                    break;
            }
        }

        this._logger.debug('_eventCallback \'' + events.length + '\' items - DONE');
    };

    CodeEditorControl.prototype._onLoad = function (gmeId) {
        var description = this._getObjectDescriptor(gmeId);
        this._widget.addNode(description);
    };

    CodeEditorControl.prototype._onUpdate = function (gmeId) {
        var description = this._getObjectDescriptor(gmeId);
        this._widget.updateNode(description);
    };

    CodeEditorControl.prototype._onUnload = function (gmeId) {
        this._widget.removeNode(gmeId);
    };

    CodeEditorControl.prototype._stateActiveObjectChanged = function (model, activeObjectId) {
        this.selectedObjectChanged(activeObjectId);
    };

    /* * * * * * * * Visualizer life cycle callbacks * * * * * * * */
    CodeEditorControl.prototype.destroy = function () {
        this._detachClientEventListeners();
        this._removeToolbarItems();
    };

    CodeEditorControl.prototype._attachClientEventListeners = function () {
        this._detachClientEventListeners();
        WebGMEGlobal.State.on('change:' + CONSTANTS.STATE_ACTIVE_OBJECT, this._stateActiveObjectChanged, this);
    };

    CodeEditorControl.prototype._detachClientEventListeners = function () {
        WebGMEGlobal.State.off('change:' + CONSTANTS.STATE_ACTIVE_OBJECT, this._stateActiveObjectChanged);
    };

    CodeEditorControl.prototype.onActivate = function () {
        this._attachClientEventListeners();
        this._displayToolbarItems();

        if (this.currentNodeInfo && typeof this.currentNodeInfo.id === 'string') {
            WebGMEGlobal.State.registerActiveObject(this.currentNodeInfo.id, {
                suppressVisualizerFromNode: true
            });
        }
    };

    CodeEditorControl.prototype.onDeactivate = function () {
        this._detachClientEventListeners();
        this._hideToolbarItems();
    };

    /* * * * * * * * * * Updating the toolbar * * * * * * * * * */
    CodeEditorControl.prototype._displayToolbarItems = function () {

        if (this._toolbarInitialized === true) {
            for (var i = this._toolbarItems.length; i--;) {
                this._toolbarItems[i].show();
            }
        } else {
            this._initializeToolbar();
        }
    };

    CodeEditorControl.prototype._hideToolbarItems = function () {

        if (this._toolbarInitialized === true) {
            for (var i = this._toolbarItems.length; i--;) {
                this._toolbarItems[i].hide();
            }
        }
    };

    CodeEditorControl.prototype._removeToolbarItems = function () {

        if (this._toolbarInitialized === true) {
            for (var i = this._toolbarItems.length; i--;) {
                this._toolbarItems[i].destroy();
            }
        }
    };

    CodeEditorControl.prototype._onModelHierarchyUp = function () {
        var myId = this.currentNodeInfo.id;
        if (this.currentNodeInfo.parentId ||
            this.currentNodeInfo.parentId === CONSTANTS.PROJECT_ROOT_ID) {
            WebGMEGlobal.State.registerActiveObject(this.currentNodeInfo.parentId);
            WebGMEGlobal.State.registerActiveSelection([myId]);
        }
    };

    CodeEditorControl.prototype._initializeToolbar = function () {
        var self = this,
            toolBar = WebGMEGlobal.Toolbar;

        this._toolbarItems = [];

        this._toolbarItems.push(toolBar.addSeparator());

        /************** GOTO PARENT IN HIERARCHY BUTTON ****************/
        this.$btnModelHierarchyUp = toolBar.addButton({
            title: 'Go to parent',
            icon: 'glyphicon glyphicon-circle-arrow-up',
            clickFn: function (/*data*/) {
                self._onModelHierarchyUp();
            }
        });
        this._toolbarItems.push(this.$btnModelHierarchyUp);

        this.$btnModelHierarchyUp.hide();

        this._toolbarInitialized = true;
    };

    return CodeEditorControl;
});
<|endoftext|>


<commit_before>var TaskScheduler = require("./task").TaskScheduler;
var colors = require("colors");

exports.execute = function(initialStep, context, cb) {
	var completedSteps = 0;
	var estimatedSteps = initialStep.remaining;

	var scheduler = new TaskScheduler({
		maxConcurrency: 5,
		mode: "lifo"
	}, cb);

	scheduler.schedule(execute_step, initialStep.weight, initialStep.name, [initialStep, null]);

	function execute_step(step, item, cb) {
		step.handler(item, step.args, context, step_complete);

		function step_complete(err, items) {
			++completedSteps;

			if(step.next) {
				if(err == null) {
					if(items == null) {
						items = [];
					} else if(items.length == undefined) {
						items = [items];
					}

					estimatedSteps += (items.length - 1) * step.next.remaining;
				} else {
					estimatedSteps -= step.next.remaining;
				}
			}

			console.log("Completed %d steps of %d".green, completedSteps, estimatedSteps);

			if(step.next && err == null) {
				items.forEach(function(i) {
					scheduler.schedule(execute_step, step.next.weight, step.next.name, [step.next, i]);
				});
			}

			cb(err);
		}
	}
}
<commit_msg>Add current date to polling log messages.<commit_after>var TaskScheduler = require("./task").TaskScheduler;
var colors = require("colors");

exports.execute = function(initialStep, context, cb) {
	var completedSteps = 0;
	var estimatedSteps = initialStep.remaining;

	var scheduler = new TaskScheduler({
		maxConcurrency: 5,
		mode: "lifo"
	}, cb);

	scheduler.schedule(execute_step, initialStep.weight, initialStep.name, [initialStep, null]);

	function execute_step(step, item, cb) {
		step.handler(item, step.args, context, step_complete);

		function step_complete(err, items) {
			++completedSteps;

			if(step.next) {
				if(err == null) {
					if(items == null) {
						items = [];
					} else if(items.length == undefined) {
						items = [items];
					}

					estimatedSteps += (items.length - 1) * step.next.remaining;
				} else {
					estimatedSteps -= step.next.remaining;
				}
			}

			console.log("%s Completed %d steps of %d".green, new Date(), completedSteps, estimatedSteps);

			if(step.next && err == null) {
				items.forEach(function(i) {
					scheduler.schedule(execute_step, step.next.weight, step.next.name, [step.next, i]);
				});
			}

			cb(err);
		}
	}
}
<|endoftext|>


<commit_before>
// https://github.com/jdewit/bootstrap-timepicker
// https://github.com/kla/bootstrap-timepicker

var TIME_REGEXP = '((?:(?:[0-1][0-9])|(?:[2][0-3])|(?:[0-9])):(?:[0-5][0-9])(?::[0-5][0-9])?(?:\\s?(?:am|AM|pm|PM))?)'

angular.module('$strap.directives')

.directive('bsTimepicker', ['$timeout', function($timeout) {

  return {
    restrict: 'A',
    require: '?ngModel',
    link: function postLink(scope, element, attrs, controller) {

      // If we have a controller (i.e. ngModelController) then wire it up
      if(controller) {
        element.on('change', function(ev) {
          scope.$apply(function () {
            controller.$setViewValue(element.val());
          });
        });
      }

      // Handle input time validity
      var timeRegExp = new RegExp('^' + TIME_REGEXP + '$', ['i']);
      controller.$parsers.unshift(function(viewValue) {
        //console.warn('viewValue', viewValue, timeRegExp,  timeRegExp.test(viewValue));
        if (!viewValue || timeRegExp.test(viewValue)) {
          controller.$setValidity('time', true);
          return viewValue;
        } else {
          controller.$setValidity('time', false);
          return undefined;
        }
      });

      // Popover GarbageCollection
      var $popover = element.closest('.popover');
      if($popover) {
        $popover.on('hide', function(e) {
          var timepicker = element.data('timepicker');
          if(timepicker) {
            timepicker.$widget.remove();
            element.data('timepicker', null);
          }
        });
      }

      // Create datepicker
      element.attr('data-toggle', 'timepicker');
      //$timeout(function () {
        element.timepicker();
      //});

    }
  }

}]);
<commit_msg>feat(timepicker): support addon<commit_after>
// https://github.com/jdewit/bootstrap-timepicker
// https://github.com/kla/bootstrap-timepicker

var TIME_REGEXP = '((?:(?:[0-1][0-9])|(?:[2][0-3])|(?:[0-9])):(?:[0-5][0-9])(?::[0-5][0-9])?(?:\\s?(?:am|AM|pm|PM))?)'

angular.module('$strap.directives')

.directive('bsTimepicker', ['$timeout', function($timeout) {

  return {
    restrict: 'A',
    require: '?ngModel',
    link: function postLink(scope, element, attrs, controller) {

      // If we have a controller (i.e. ngModelController) then wire it up
      if(controller) {
        element.on('change', function(ev) {
          scope.$apply(function () {
            controller.$setViewValue(element.val());
          });
        });
      }

      // Handle input time validity
      var timeRegExp = new RegExp('^' + TIME_REGEXP + '$', ['i']);
      controller.$parsers.unshift(function(viewValue) {
        //console.warn('viewValue', viewValue, timeRegExp,  timeRegExp.test(viewValue));
        if (!viewValue || timeRegExp.test(viewValue)) {
          controller.$setValidity('time', true);
          return viewValue;
        } else {
          controller.$setValidity('time', false);
          return undefined;
        }
      });

      // Support add-on
      var component = element.next('[data-toggle="timepicker"]');
      if(component.length) {
        component.on('click', function() { element.trigger('focus'); });
      }

      // Popover GarbageCollection
      var $popover = element.closest('.popover');
      if($popover) {
        $popover.on('hide', function(e) {
          var timepicker = element.data('timepicker');
          if(timepicker) {
            timepicker.$widget.remove();
            element.data('timepicker', null);
          }
        });
      }

      // Create datepicker
      element.attr('data-toggle', 'timepicker');
      //$timeout(function () {
        element.timepicker();
      //});

    }
  }

}]);
<|endoftext|>


<commit_before>import translate from 'translatr';

const Loc = ({ currentLanguage, locKey, number, dictionary }) => {
    return
        { translate( dictionary, currentLanguage, locKey, number ) }
    ;
};

export default Loc;<commit_msg>React added to presentational component<commit_after>import translate from 'translatr';
import React from 'react';

const Loc = ({ currentLanguage, locKey, number, dictionary }) => {
    return
        { translate( dictionary, currentLanguage, locKey, number ) }
    ;
};

export default Loc;<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

import ReactAudioPlayer from 'react-audio-player';
import axios from "axios";

class availableDatalist extends React.Component {
   availableDatalist(props) {
    return(

{props.all_songs.map(c =>

c.name

c.album

 )}

    )

  }
}

class SongBoard extends React.Component {
getAllSongs() {
  axios
  .get("http://localhost:8000/song/")
  .then(response => {
    const songs = response.data.map(c => {
      return{
        name: c.name,
        album: c.album
      };

    });

    const newState = Object.assign({}, this.state, {
          all_songs: songs
        });

    this.setState(newState);
    console.log(this.state)

  })
  .catch(error => console.log(error));
}

  render() {
    return(

            <button className="song">
              Song
            </button>
            <button className="album">
              Album
            </button>

          <availableDatalist />

    )
  }
}

class Player extends React.Component {
  render() {
    return(
      <ReactAudioPlayer
        src="my_audio_file.ogg"
        autoPlay
        controls
      />
    )
  }
}

class Site extends React.Component {
  render() {
    return (

          <Player />

          <SongBoard />

    )
  }
}

ReactDOM.render(
  <Site />,
  document.getElementById('root')
);
<commit_msg>conosle.log<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

import ReactAudioPlayer from 'react-audio-player';
import axios from "axios";

class availableDatalist extends React.Component {
   availableDatalist(props) {
    return(

{props.all_songs.map(c =>

c.name

c.album

 )}

    )

  }
}

class SongBoard extends React.Component {
getAllSongs() {
  axios
  .get("http://localhost:8000/song/")
  .then(response => {
    const songs = response.data.map(c => {
      return{
        name: c.name,
        album: c.album
      };

    });

    const newState = Object.assign({}, this.state, {
          all_songs: songs
        });

    this.setState(newState)
    console.log("HEllo Word");

  })
  .catch(error => console.log(error));
}

  render() {
    return(

            <button className="song">
              Song
            </button>
            <button className="album">
              Album
            </button>

          <availableDatalist />

    )
  }
}

class Player extends React.Component {
  render() {
    return(
      <ReactAudioPlayer
        src="my_audio_file.ogg"
        autoPlay
        controls
      />
    )
  }
}

class Site extends React.Component {
  render() {
    return (

          <Player />

          <SongBoard />

    )
  }
}

ReactDOM.render(
  <Site />,
  document.getElementById('root')
);
<|endoftext|>


<commit_before>(function () {
    "use strict";

    window.App.videos = [
        {
            title: 'Teenage Mutant Ninja Turtles',
            url: 'http://fs.to/get/dl/6jw62sx93srfw13ejj1l2j2c6.0.521872670.0.1414844737/Teenage+Mutant+Ninja+Turtles+%282014%29+1080p.x264+AC3.mkv',
            type: 'vod'
        },
        {
            title: '2Elephants Dream',
            url: 'https://archive.org/download/ElephantsDream/ed_1024_512kb.mp4',
            type: 'vod'
        },
        {
            title: '3Europa plus',
            url: 'http://europaplus.cdnvideo.ru/europaplus-live/eptv_main.sdp/playlist.m3u8',
            type: 'hls'
        },
        {
            title: '4PIK TV',
            url: 'http://phone.pik-tv.com/live/mp4:piktv3pik3tv/playlist.m3u8',
            type: 'hls'
        },
        {
            title: '5Redbull',
            url: 'http://live.iphone.redbull.de.edgesuite.net/webtvHD.m3u8',
            type: 'hls'
        }
    ];
})();
<commit_msg>Update videos.js<commit_after>(function () {
    "use strict";

    window.App.videos = [
        {
            title: 'Физрук сезон 2 серия 9',
            url: 'http://fs.to/get/dl/6jw62sx93s2u06gz8xwbc6oba.0.521872670.0.1416603483/Fizruk.s02e09.2014.WEB-DL.720%D1%80.mkv',
            type: 'vod'
        },
        {
            title: '2Elephants Dream',
            url: 'https://archive.org/download/ElephantsDream/ed_1024_512kb.mp4',
            type: 'vod'
        },
        {
            title: '3Europa plus',
            url: 'http://europaplus.cdnvideo.ru/europaplus-live/eptv_main.sdp/playlist.m3u8',
            type: 'hls'
        },
        {
            title: '4PIK TV',
            url: 'http://phone.pik-tv.com/live/mp4:piktv3pik3tv/playlist.m3u8',
            type: 'hls'
        },
        {
            title: '5Redbull',
            url: 'http://live.iphone.redbull.de.edgesuite.net/webtvHD.m3u8',
            type: 'hls'
        }
    ];
})();
<|endoftext|>