<commit_before>var paper = require('prototypo.js').paper;

function wheelHandler( event ) {
	// normalize the deltaY value. Expected values are ~40 pixels or 3 lines
	var factor = 1 + ( this.opts.zoomFactor *
			( Math.abs( event.deltaY / event.deltaMode ? 3 : 40 * 20 ) ) ),
		newZoom =
			event.deltaY < 0 ?
				this.view.zoom * factor :
				event.deltaY > 0 ?
					this.view.zoom / factor :
					this.view.zoom;

	if ( newZoom > 0.07 ) {
		var mousePosition = new paper.Point( event.offsetX, event.offsetY );
		var viewPosition = this.view.viewToProject( mousePosition );
		var pc = viewPosition.subtract( this.view.center );
		var newPosition = viewPosition.subtract(
			pc.multiply( this.view.zoom / newZoom )
		).subtract( this.view.center );

		this.zoom = newZoom;
		this.view.center = this.view.center.add(newPosition);
	}

	event.preventDefault();
}

function moveHandler(event) {
	if ( !this.isMousedown ) {
		return;
	}

	var currPos = new paper.Point( event.clientX, event.clientY ),
		delta = currPos.subtract( this.prevPos );

	this.prevPos = currPos;

	this.view.center = this.view.center.subtract(
			delta.divide( this.view.zoom * window.devicePixelRatio) );
}

function downHandler(event) {
	if (event.button && event.button !== 0) {
		return;
	}

	this.isMousedown = true;
	this.prevPos = new paper.Point( event.clientX, event.clientY );
}

function upHandler() {
	this.isMousedown = false;
}

function zoomIn() {
	this.zoom = this.view.zoom * 1 + this.opts.zoomFactor;
}

function zoomOut() {
	this.zoom = this.view.zoom / 1 + this.opts.zoomFactor;
}

module.exports = {
	onWheel: wheelHandler,
	onMove: moveHandler,
	onDown: downHandler,
	onUp: upHandler,
	zoomIn: zoomIn,
	zoomOut: zoomOut
};
<commit_msg>added pixel ratio to mouse event<commit_after>var paper = require('prototypo.js').paper;

function wheelHandler( event ) {
	// normalize the deltaY value. Expected values are ~40 pixels or 3 lines
	var factor = 1 + ( this.opts.zoomFactor *
			( Math.abs( event.deltaY / event.deltaMode ? 3 : 40 * 20 ) ) ),
		newZoom =
			event.deltaY < 0 ?
				this.view.zoom * factor :
				event.deltaY > 0 ?
					this.view.zoom / factor :
					this.view.zoom;

	if ( newZoom > 0.07 ) {
		var mousePosition = new paper.Point( event.offsetX / window.devicePixelRatio, event.offsetY / window.devicePixelRatio );
		var viewPosition = this.view.viewToProject( mousePosition );
		var pc = viewPosition.subtract( this.view.center );
		var newPosition = viewPosition.subtract(
			pc.multiply( this.view.zoom / newZoom )
		).subtract( this.view.center );

		this.zoom = newZoom;
		this.view.center = this.view.center.add(newPosition);
	}

	event.preventDefault();
}

function moveHandler(event) {
	if ( !this.isMousedown ) {
		return;
	}

	var currPos = new paper.Point( event.clientX, event.clientY ),
		delta = currPos.subtract( this.prevPos );

	this.prevPos = currPos;

	this.view.center = this.view.center.subtract(
			delta.divide( this.view.zoom * window.devicePixelRatio) );
}

function downHandler(event) {
	if (event.button && event.button !== 0) {
		return;
	}

	this.isMousedown = true;
	this.prevPos = new paper.Point( event.clientX, event.clientY );
}

function upHandler() {
	this.isMousedown = false;
}

function zoomIn() {
	this.zoom = this.view.zoom * 1 + this.opts.zoomFactor;
}

function zoomOut() {
	this.zoom = this.view.zoom / 1 + this.opts.zoomFactor;
}

module.exports = {
	onWheel: wheelHandler,
	onMove: moveHandler,
	onDown: downHandler,
	onUp: upHandler,
	zoomIn: zoomIn,
	zoomOut: zoomOut
};
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
* Licensed under Version: MPL 1.1/GPL 2.0/LGPL 2.1
* Full Terms at http://mozile.mozdev.org/license.html
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Playsophy code.
*
* The Initial Developer of the Original Code is Playsophy
* Portions created by the Initial Developer are Copyright (C) 2002-2003
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */

const BXE_VERSION = "0.1alpha";
const BXE_BUILD = "200310080330"

var DebugOutput = true;

mozile_js_files = new Array();

mozile_js_files.push("mozile/mozWrappers.js");
mozile_js_files.push("js/widget.js");

mozile_js_files.push("mozile/eDOM.js");
mozile_js_files.push("js/bxeConfig.js");
mozile_js_files.push("mozile/eDOMXHTML.js");
mozile_js_files.push("js/bxeXMLNode.js");
mozile_js_files.push("js/bxeNodeElements.js");
mozile_js_files.push("js/bxeXMLDocument.js");
mozile_js_files.push("mozile/mozileTransportDriver.js");
mozile_js_files.push("mozile/td/http.js");
mozile_js_files.push("mozile/domlevel3.js");
mozile_js_files.push("mozile/mozCE.js");
mozile_js_files.push("mozile/mozIECE.js");
//mozile_js_files.push("mozile/mozileModify.js");
mozile_js_files.push("js/eDOMEvents.js");
mozile_js_files.push("js/bxeFunctions.js");

var mozile_root_dir = "./";

// some global vars, no need to change them
var mozile_corescript_loaded = 0;
var mozile_script_loaded = 0;
var bxe_config = new Object();
var bxe_about_box = null;
var bxe_format_list = null;
var bxe_context_menu = null;
var bxe_delayedUpdate = false;
var eDOM_bxe_mode = true;

function bxe_start(config_file,fromUrl, configArray) {

	/*if (! (BX_checkUnsupportedBrowsers())) {
		return false;
	}*/

	if((navigator.product == 'Gecko') && (navigator.userAgent.indexOf("Safari") == -1))
	{
		// navigator.productSub > '20020801' (test to see what the date should be)

		// POST04: if document.documentElement != HTML then ... or no "head" ...
		var head = document.getElementsByTagName("head")[0];
		bxe_config.file = config_file;
		bxe_config.fromUrl = fromUrl;
		bxe_config.configArray = configArray;
		if(head)
		{
			// get the location of this script and reuse it for the others
			for(var i=0; i<head.childNodes.length; i++)
			{
				var mozileLoaderRE = /(.*)bxeLoader.js$/;
				if(head.childNodes[i].localName == "SCRIPT")
				{
					var src = head.childNodes[i].src;
					var result = mozileLoaderRE.exec(src);
					if(result)
					{
						mozile_root_dir = result[1];
						break;
					}
				}
			}
			for (var i=0; i < mozile_js_files.length; i++)
			{
				var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
				var src = mozile_root_dir + mozile_js_files[i];
				if (mozile_js_files[i] == "js/widget.js") {
					scr.onload = widget_loaded;
				} else {
					scr.onload = corescript_loaded;
				}
				scr.setAttribute("src", src);

				scr.setAttribute("language","JavaScript");
				head.appendChild(scr);
			}
			//when last include src is loaded, call onload handler

		}
		else {
			alert("*** ALERT: MozileLoader only works in XHTML - load Mozile JS explicitly in XML files");
		}
	}

}

// Detect Gecko but exclude Safari (for now); for now, only support XHTML

function bxe_load_xml (xmlfile) {

	var td = new mozileTransportDriver("webdav");
	function callback (e) {
		if (e.isError) {
			alert("Error loading xml file \n"+e.statusText);
			return false;
		}
		var xmldoc =  e.document;
		bxe_config.xmldoc = xmldoc;
		xmldoc.init();
		if (bxe_config.xhtmlfile) {
			xmldoc.importXHTMLDocument(bxe_config.xhtmlfile)
		} else if (bxe_config.xslfile) {
			xmldoc.transformToXPathMode(bxe_config.xslfile)
		} else {
			xmldoc.insertIntoHTMLDocument();
			xml_loaded(xmldoc);
		}

	}
	td.load(xmlfile,callback);

	return true;
}

function widget_loaded(e) {
	bxe_about_box = new Widget_AboutBox();
	bxe_about_box.draw();
	bxe_about_box.setText("Loading files ...");
	corescript_loaded(e);

}

function corescript_loaded(e) {
	mozile_corescript_loaded++;
	debug("from core script " + mozile_corescript_loaded + " of " + mozile_js_files.length  + "loaded: " + e.currentTarget.src);
	if ( mozile_js_files.length == mozile_corescript_loaded) {
		debug("call mozile_core_loaded()");
		mozile_core_loaded();
	} else {
		if (bxe_about_box) {
			bxe_about_box.addText(mozile_corescript_loaded );
		}
	}
}

function script_loaded(e) {
	mozile_script_loaded++;
	debug("from config script " + mozile_script_loaded + " loaded: " + e.currentTarget.src );
	if ( bxe_config.scriptfiles.length == mozile_script_loaded ) {
		debug("call mozile_loaded()");
		mozile_loaded();
	} else {
		bxe_about_box.addText(mozile_script_loaded );
	}
}

function mozile_core_loaded() {
	bxe_about_box.addText("Scripts loaded ...");
	bxe_about_box.addText("Load Config ");
	try {
		bxe_config = new bxeConfig(bxe_config.file, bxe_config.fromUrl, bxe_config.configArray);
	} catch (e) {
		bxe_catch_alert(e);
	}
}

function mozile_loaded() {
	bxe_about_box.addText("Load XML ...");
	bxe_load_xml(bxe_config.xmlfile);

}

function xml_loaded(xmldoc) {
	bxe_about_box.addText("Load RelaxNG ...");
	if (!(bxe_config.validationfile && xmldoc.XMLNode.loadSchema(bxe_config.validationfile,validation_loaded))) {
		bxe_about_box.addText("RelaxNG File was not found");
	}
	document.eDOMaddEventListener("toggleSourceMode",bxe_toggleSourceMode,false);
	document.eDOMaddEventListener("toggleTagMode",bxe_toggleTagMode,false);
	document.eDOMaddEventListener("toggleNormalMode",bxe_toggleNormalMode,false);
	document.eDOMaddEventListener("DocumentSave",__bxeSave,false);
	document.eDOMaddEventListener("ToggleTextClass",bxe_toggleTextClass,false);
	document.eDOMaddEventListener("appendNode",bxe_appendNode,false);
	document.eDOMaddEventListener("InsertLink",bxe_InsertLink,false);
	document.eDOMaddEventListener("InsertTable",bxe_InsertTable,false);
	document.eDOMaddEventListener("InsertImage",bxe_InsertImage,false);
	document.eDOMaddEventListener("OrderedList",bxe_OrderedList,false);
	document.eDOMaddEventListener("UnorderedList",bxe_UnorderedList,false);

	document.eDOMaddEventListener("changeLinesContainer",bxe_changeLinesContainer,false);
	document.eDOMaddEventListener("Exit",bxe_exit,false);

	document.eDOMaddEventListener("ClipboardCopy",function(e) { window.getSelection().copy()},false);
	document.eDOMaddEventListener("ClipboardPaste",function(e) { window.getSelection().paste()},false);
	document.eDOMaddEventListener("ClipboardCut",function(e) { window.getSelection().cut()},false);

	document.eDOMaddEventListener("Undo",function(e) { bxe_not_yet_implemented()}, false);
	document.eDOMaddEventListener("Redo",function(e) { bxe_not_yet_implemented()}, false);

	document.addEventListener("contextmenu",bxe_ContextMenuEvent, false);

	//document.eDOMaddEventListener("NodeInsertedParent",bxe_NodeInsertedParent, false);
	document.eDOMaddEventListener("NodeInsertedBefore",bxe_NodeInsertedBefore,false);
	document.eDOMaddEventListener("NodeBeforeDelete",bxe_NodeBeforeDelete,false);
	/*document.eDOMaddEventListener("NodeChanged",bxe_NodeChanged,false);

	document.eDOMaddEventListener("NodeRemovedChildOnly",bxe_NodeRemovedChildOnly,false);
	*/
	//document.eDOMaddEventListener("NodeAppendedChild",bxe_NodeAppendedChild,false);
	document.eDOMaddEventListener("NodePositionChanged",bxe_NodePositionChanged,false);

	document.eDOMaddEventListener("ContextPopup",bxe_ContextPopup,false);
	bxe_context_menu = new Widget_ContextMenu();
}

function validation_loaded(vdom) {
	bxe_about_box.addText("Validation Loaded ...");

	var vali = bxe_config.xmldoc.XMLNode.validateDocument();
	if (vali.isError) {
		bxe_about_box.addText("Document is *not* valid.");
		//alert(vali.getErrorMessagesAsText());
	}
	else {
		bxe_about_box.addText("Document is valid.");

	}
}

function config_loaded(bxe_config_in) {
	bxe_about_box.addText("& Parsed ...");

	bxe_config = bxe_config_in;
	var head = document.getElementsByTagName("head")[0];
	for (var i=0; i < bxe_config.cssfiles.length; i++)
	{
		var scr = document.createElementNS(XHTMLNS,"link");
		scr.setAttribute("type","text/css");
		scr.setAttribute("rel","stylesheet");
		scr.setAttribute("href",bxe_config.cssfiles[i]);
		head.appendChild(scr);
	}

	for (var i=0; i < bxe_config.scriptfiles.length; i++)
	{
		var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
		var src = mozile_root_dir + bxe_config.scriptfiles[i];
		scr.onload = script_loaded;
		scr.setAttribute("src", src);
		scr.setAttribute("language","JavaScript");
		head.appendChild(scr);
	}

}

debug = function (text, options) {

	if (DebugOutput) {

		fn =  bxe_getCaller(debug);

		dump( fn.getName() +  ": " + text + "\n");
		if (options) {

			if (options.evalArguments) {
				var fname= fn.getName();
					dump("  Arguments: (");
					for (var i = 0; i < fn.arguments.length; i++) {
						dump("[" + typeof fn.arguments[i] + "] ");
						switch( typeof( fn.arguments[i] )) {
							case "function":
								dump (fn.arguments[i].getName());
								break;
							case "string":
								dump('"' + fn.arguments[i] + '"');
								break;
							default:
								dump(fn.arguments[i]);
						}
						if (i < fn.arguments.length - 1 ) {
							dump(", ");
						}
					}
					dump (")\n");

			}

			if (options.callstack) {
				var callstack =  new Array();
				dump ("  Callstack: \n");
				dump ("  ----------\n");
				while (fn) {

					callstack.unshift(fn.getName() + "\n");
					var newfn = JsUtil_getCaller(fn);
					if (fn == newfn) {
						callstack.unshift ("  [javascript recursion]\n");
						break;
					}
					fn = newfn;
				}
				for (var i = 0; i < callstack.length; i++) {
					dump("  " +i +": " +callstack[i]);
				}
				dump ("  ----------\n");

			}

		}

	}
}

Function.prototype.getName = function () {
	var r = /function (\w*)([^\{\}]*\))/
	var s = new String( this);
	var m = s.match( r );
	if (m) {
		var f = "";
		if (m[1]) {
			f = m[1];
		} else {
			r = /var id = "(.+)"/;
			var n = s.match(r);
			if (n && n[1]) {
				f = n[1];
			} else {
				f = "anoynmous function";
			}
		}
		var args = m[2];
		return (f+args);
	} else {
		return "anonymous function";
	}
}
function bxe_getCaller( fn )
{
	switch( typeof( fn ))
	{
		case "undefined":
			return bxe_getCaller( bxe_getCaller );

		case "function":
			if( fn.caller )
				return fn.caller;
			if( fn.arguments && fn.arguments.caller )
				return fn.arguments.caller;
	}
	return undefined;
}

<commit_msg>automatic BuildDate Update<commit_after>/* ***** BEGIN LICENSE BLOCK *****
* Licensed under Version: MPL 1.1/GPL 2.0/LGPL 2.1
* Full Terms at http://mozile.mozdev.org/license.html
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Playsophy code.
*
* The Initial Developer of the Original Code is Playsophy
* Portions created by the Initial Developer are Copyright (C) 2002-2003
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */

const BXE_VERSION = "0.1alpha";
const BXE_BUILD = "200310090330"

var DebugOutput = true;

mozile_js_files = new Array();

mozile_js_files.push("mozile/mozWrappers.js");
mozile_js_files.push("js/widget.js");

mozile_js_files.push("mozile/eDOM.js");
mozile_js_files.push("js/bxeConfig.js");
mozile_js_files.push("mozile/eDOMXHTML.js");
mozile_js_files.push("js/bxeXMLNode.js");
mozile_js_files.push("js/bxeNodeElements.js");
mozile_js_files.push("js/bxeXMLDocument.js");
mozile_js_files.push("mozile/mozileTransportDriver.js");
mozile_js_files.push("mozile/td/http.js");
mozile_js_files.push("mozile/domlevel3.js");
mozile_js_files.push("mozile/mozCE.js");
mozile_js_files.push("mozile/mozIECE.js");
//mozile_js_files.push("mozile/mozileModify.js");
mozile_js_files.push("js/eDOMEvents.js");
mozile_js_files.push("js/bxeFunctions.js");

var mozile_root_dir = "./";

// some global vars, no need to change them
var mozile_corescript_loaded = 0;
var mozile_script_loaded = 0;
var bxe_config = new Object();
var bxe_about_box = null;
var bxe_format_list = null;
var bxe_context_menu = null;
var bxe_delayedUpdate = false;
var eDOM_bxe_mode = true;

function bxe_start(config_file,fromUrl, configArray) {

	/*if (! (BX_checkUnsupportedBrowsers())) {
		return false;
	}*/

	if((navigator.product == 'Gecko') && (navigator.userAgent.indexOf("Safari") == -1))
	{
		// navigator.productSub > '20020801' (test to see what the date should be)

		// POST04: if document.documentElement != HTML then ... or no "head" ...
		var head = document.getElementsByTagName("head")[0];
		bxe_config.file = config_file;
		bxe_config.fromUrl = fromUrl;
		bxe_config.configArray = configArray;
		if(head)
		{
			// get the location of this script and reuse it for the others
			for(var i=0; i<head.childNodes.length; i++)
			{
				var mozileLoaderRE = /(.*)bxeLoader.js$/;
				if(head.childNodes[i].localName == "SCRIPT")
				{
					var src = head.childNodes[i].src;
					var result = mozileLoaderRE.exec(src);
					if(result)
					{
						mozile_root_dir = result[1];
						break;
					}
				}
			}
			for (var i=0; i < mozile_js_files.length; i++)
			{
				var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
				var src = mozile_root_dir + mozile_js_files[i];
				if (mozile_js_files[i] == "js/widget.js") {
					scr.onload = widget_loaded;
				} else {
					scr.onload = corescript_loaded;
				}
				scr.setAttribute("src", src);

				scr.setAttribute("language","JavaScript");
				head.appendChild(scr);
			}
			//when last include src is loaded, call onload handler

		}
		else {
			alert("*** ALERT: MozileLoader only works in XHTML - load Mozile JS explicitly in XML files");
		}
	}

}

// Detect Gecko but exclude Safari (for now); for now, only support XHTML

function bxe_load_xml (xmlfile) {

	var td = new mozileTransportDriver("webdav");
	function callback (e) {
		if (e.isError) {
			alert("Error loading xml file \n"+e.statusText);
			return false;
		}
		var xmldoc =  e.document;
		bxe_config.xmldoc = xmldoc;
		xmldoc.init();
		if (bxe_config.xhtmlfile) {
			xmldoc.importXHTMLDocument(bxe_config.xhtmlfile)
		} else if (bxe_config.xslfile) {
			xmldoc.transformToXPathMode(bxe_config.xslfile)
		} else {
			xmldoc.insertIntoHTMLDocument();
			xml_loaded(xmldoc);
		}

	}
	td.load(xmlfile,callback);

	return true;
}

function widget_loaded(e) {
	bxe_about_box = new Widget_AboutBox();
	bxe_about_box.draw();
	bxe_about_box.setText("Loading files ...");
	corescript_loaded(e);

}

function corescript_loaded(e) {
	mozile_corescript_loaded++;
	debug("from core script " + mozile_corescript_loaded + " of " + mozile_js_files.length  + "loaded: " + e.currentTarget.src);
	if ( mozile_js_files.length == mozile_corescript_loaded) {
		debug("call mozile_core_loaded()");
		mozile_core_loaded();
	} else {
		if (bxe_about_box) {
			bxe_about_box.addText(mozile_corescript_loaded );
		}
	}
}

function script_loaded(e) {
	mozile_script_loaded++;
	debug("from config script " + mozile_script_loaded + " loaded: " + e.currentTarget.src );
	if ( bxe_config.scriptfiles.length == mozile_script_loaded ) {
		debug("call mozile_loaded()");
		mozile_loaded();
	} else {
		bxe_about_box.addText(mozile_script_loaded );
	}
}

function mozile_core_loaded() {
	bxe_about_box.addText("Scripts loaded ...");
	bxe_about_box.addText("Load Config ");
	try {
		bxe_config = new bxeConfig(bxe_config.file, bxe_config.fromUrl, bxe_config.configArray);
	} catch (e) {
		bxe_catch_alert(e);
	}
}

function mozile_loaded() {
	bxe_about_box.addText("Load XML ...");
	bxe_load_xml(bxe_config.xmlfile);

}

function xml_loaded(xmldoc) {
	bxe_about_box.addText("Load RelaxNG ...");
	if (!(bxe_config.validationfile && xmldoc.XMLNode.loadSchema(bxe_config.validationfile,validation_loaded))) {
		bxe_about_box.addText("RelaxNG File was not found");
	}
	document.eDOMaddEventListener("toggleSourceMode",bxe_toggleSourceMode,false);
	document.eDOMaddEventListener("toggleTagMode",bxe_toggleTagMode,false);
	document.eDOMaddEventListener("toggleNormalMode",bxe_toggleNormalMode,false);
	document.eDOMaddEventListener("DocumentSave",__bxeSave,false);
	document.eDOMaddEventListener("ToggleTextClass",bxe_toggleTextClass,false);
	document.eDOMaddEventListener("appendNode",bxe_appendNode,false);
	document.eDOMaddEventListener("InsertLink",bxe_InsertLink,false);
	document.eDOMaddEventListener("InsertTable",bxe_InsertTable,false);
	document.eDOMaddEventListener("InsertImage",bxe_InsertImage,false);
	document.eDOMaddEventListener("OrderedList",bxe_OrderedList,false);
	document.eDOMaddEventListener("UnorderedList",bxe_UnorderedList,false);

	document.eDOMaddEventListener("changeLinesContainer",bxe_changeLinesContainer,false);
	document.eDOMaddEventListener("Exit",bxe_exit,false);

	document.eDOMaddEventListener("ClipboardCopy",function(e) { window.getSelection().copy()},false);
	document.eDOMaddEventListener("ClipboardPaste",function(e) { window.getSelection().paste()},false);
	document.eDOMaddEventListener("ClipboardCut",function(e) { window.getSelection().cut()},false);

	document.eDOMaddEventListener("Undo",function(e) { bxe_not_yet_implemented()}, false);
	document.eDOMaddEventListener("Redo",function(e) { bxe_not_yet_implemented()}, false);

	document.addEventListener("contextmenu",bxe_ContextMenuEvent, false);

	//document.eDOMaddEventListener("NodeInsertedParent",bxe_NodeInsertedParent, false);
	document.eDOMaddEventListener("NodeInsertedBefore",bxe_NodeInsertedBefore,false);
	document.eDOMaddEventListener("NodeBeforeDelete",bxe_NodeBeforeDelete,false);
	/*document.eDOMaddEventListener("NodeChanged",bxe_NodeChanged,false);

	document.eDOMaddEventListener("NodeRemovedChildOnly",bxe_NodeRemovedChildOnly,false);
	*/
	//document.eDOMaddEventListener("NodeAppendedChild",bxe_NodeAppendedChild,false);
	document.eDOMaddEventListener("NodePositionChanged",bxe_NodePositionChanged,false);

	document.eDOMaddEventListener("ContextPopup",bxe_ContextPopup,false);
	bxe_context_menu = new Widget_ContextMenu();
}

function validation_loaded(vdom) {
	bxe_about_box.addText("Validation Loaded ...");

	var vali = bxe_config.xmldoc.XMLNode.validateDocument();
	if (vali.isError) {
		bxe_about_box.addText("Document is *not* valid.");
		//alert(vali.getErrorMessagesAsText());
	}
	else {
		bxe_about_box.addText("Document is valid.");

	}
}

function config_loaded(bxe_config_in) {
	bxe_about_box.addText("& Parsed ...");

	bxe_config = bxe_config_in;
	var head = document.getElementsByTagName("head")[0];
	for (var i=0; i < bxe_config.cssfiles.length; i++)
	{
		var scr = document.createElementNS(XHTMLNS,"link");
		scr.setAttribute("type","text/css");
		scr.setAttribute("rel","stylesheet");
		scr.setAttribute("href",bxe_config.cssfiles[i]);
		head.appendChild(scr);
	}

	for (var i=0; i < bxe_config.scriptfiles.length; i++)
	{
		var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
		var src = mozile_root_dir + bxe_config.scriptfiles[i];
		scr.onload = script_loaded;
		scr.setAttribute("src", src);
		scr.setAttribute("language","JavaScript");
		head.appendChild(scr);
	}

}

debug = function (text, options) {

	if (DebugOutput) {

		fn =  bxe_getCaller(debug);

		dump( fn.getName() +  ": " + text + "\n");
		if (options) {

			if (options.evalArguments) {
				var fname= fn.getName();
					dump("  Arguments: (");
					for (var i = 0; i < fn.arguments.length; i++) {
						dump("[" + typeof fn.arguments[i] + "] ");
						switch( typeof( fn.arguments[i] )) {
							case "function":
								dump (fn.arguments[i].getName());
								break;
							case "string":
								dump('"' + fn.arguments[i] + '"');
								break;
							default:
								dump(fn.arguments[i]);
						}
						if (i < fn.arguments.length - 1 ) {
							dump(", ");
						}
					}
					dump (")\n");

			}

			if (options.callstack) {
				var callstack =  new Array();
				dump ("  Callstack: \n");
				dump ("  ----------\n");
				while (fn) {

					callstack.unshift(fn.getName() + "\n");
					var newfn = JsUtil_getCaller(fn);
					if (fn == newfn) {
						callstack.unshift ("  [javascript recursion]\n");
						break;
					}
					fn = newfn;
				}
				for (var i = 0; i < callstack.length; i++) {
					dump("  " +i +": " +callstack[i]);
				}
				dump ("  ----------\n");

			}

		}

	}
}

Function.prototype.getName = function () {
	var r = /function (\w*)([^\{\}]*\))/
	var s = new String( this);
	var m = s.match( r );
	if (m) {
		var f = "";
		if (m[1]) {
			f = m[1];
		} else {
			r = /var id = "(.+)"/;
			var n = s.match(r);
			if (n && n[1]) {
				f = n[1];
			} else {
				f = "anoynmous function";
			}
		}
		var args = m[2];
		return (f+args);
	} else {
		return "anonymous function";
	}
}
function bxe_getCaller( fn )
{
	switch( typeof( fn ))
	{
		case "undefined":
			return bxe_getCaller( bxe_getCaller );

		case "function":
			if( fn.caller )
				return fn.caller;
			if( fn.arguments && fn.arguments.caller )
				return fn.arguments.caller;
	}
	return undefined;
}

<|endoftext|>


<commit_before>//TODO do we want Store and Price here, and how does that information get here?

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const schema = new Schema({
    date: {
        type: Date,
        required: true
    },
    store: {

    },
    price: {}
});

const Purchase = mongoose.model('Purchase', schema);
module.exports = Purchase;<commit_msg>eliminated redundant line<commit_after>//TODO do we want Store and Price here, and how does that information get here?

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const schema = new Schema({
    date: {
        type: Date,
        required: true
    },
    store: {

    },
    price: {}
});

module.exports = mongoose.model('Purchase', schema);<|endoftext|>


<commit_before>var ui = (function() {

	// Base elements
	var body, article, uiContainer, overlay, aboutButton, descriptionModal, header;

	// Buttons
	var screenSizeElement, colorLayoutElement, targetElement, saveElement;

	// Work Counter
	var wordCountValue, wordCountBox, wordCountElement, wordCounter, wordCounterProgress;

	//save support
	var supportSave, saveFormat, textToWrite;

	var expandScreenIcon = '';
	var shrinkScreenIcon = '';

	var darkLayout = false;

	function init() {

		supportsSave = !!new Blob()?true:false;

		bindElements();

		wordCountActive = false;

		if ( supportsHtmlStorage() ) {
			loadState();
		}

		console.log( "Checkin under the hood eh? We've probably got a lot in common. You should totally check out ZenPen on github! (https://github.com/tholman/zenpen)." );
	}

	function loadState() {

		// Activate word counter
		if ( localStorage['wordCount'] && localStorage['wordCount'] !== "0") {
			wordCountValue = parseInt(localStorage['wordCount']);
			wordCountElement.value = localStorage['wordCount'];
			wordCounter.className = "word-counter active";
			updateWordCount();
		}

		// Activate color switch
		if ( localStorage['darkLayout'] === 'true' ) {
			if ( darkLayout === false ) {
				document.body.className = 'yang';
			} else {
				document.body.className = 'yin';
			}
			darkLayout = !darkLayout;
		}

	}

	function saveState() {

		if ( supportsHtmlStorage() ) {
			localStorage[ 'darkLayout' ] = darkLayout;
			localStorage[ 'wordCount' ] = wordCountElement.value;
		}
	}

	function bindElements() {

		// Body element for light/dark styles
		body = document.body;

		uiContainer = document.querySelector( '.ui' );

		// UI element for color flip
		colorLayoutElement = document.querySelector( '.color-flip' );
		colorLayoutElement.onclick = onColorLayoutClick;

		// UI element for full screen
		screenSizeElement = document.querySelector( '.fullscreen' );
		screenSizeElement.onclick = onScreenSizeClick;

		targetElement = document.querySelector( '.target ');
		targetElement.onclick = onTargetClick;

		document.addEventListener( "fullscreenchange", function () {
			if ( document.fullscreenEnabled === false ) {
				exitFullscreen();
			}
		}, false);

		//init event listeners only if browser can save
		if (supportsSave) {

			saveElement = document.querySelector( '.save' );
			saveElement.onclick = onSaveClick;

			var formatSelectors = document.querySelectorAll( '.saveselection span' );
			for( var i in formatSelectors ) {
				formatSelectors[i].onclick = selectFormat;
			}

			document.querySelector('.savebutton').onclick = saveText;
		} else {
			document.querySelector('.save.useicons').style.display = "none";
		}

		// Overlay when modals are active
		overlay = document.querySelector( '.overlay' );
		overlay.onclick = onOverlayClick;

		article = document.querySelector( '.content' );
		article.onkeyup = onArticleKeyUp;

		wordCountBox = overlay.querySelector( '.wordcount' );
		wordCountElement = wordCountBox.querySelector( 'input' );
		wordCountElement.onchange = onWordCountChange;
		wordCountElement.onkeyup = onWordCountKeyUp;

		descriptionModal = overlay.querySelector( '.description' );

		saveModal = overlay.querySelector('.saveoverlay');

		wordCounter = document.querySelector( '.word-counter' );
		wordCounterProgress = wordCounter.querySelector( '.progress' );

		aboutButton = document.querySelector( '.about' );
		aboutButton.onclick = onAboutButtonClick;

		header = document.querySelector( '.header' );
		header.onkeypress = onHeaderKeyPress;
	}

	function onScreenSizeClick( event ) {

		if ( !document.fullscreenElement ) {
			enterFullscreen();
		} else {
			exitFullscreen();
		}
	}

	function enterFullscreen() {
		document.body.requestFullscreen( Element.ALLOW_KEYBOARD_INPUT );
		screenSizeElement.innerHTML = shrinkScreenIcon;
	}

	function exitFullscreen() {
		document.exitFullscreen();
		screenSizeElement.innerHTML = expandScreenIcon;
	}

	function onColorLayoutClick( event ) {
		if ( darkLayout === false ) {
			document.body.className = 'yang';
		} else {
			document.body.className = 'yin';
		}
		darkLayout = !darkLayout;

		saveState();
	}

	function onTargetClick( event ) {
		overlay.style.display = "block";
		wordCountBox.style.display = "block";
		wordCountElement.focus();
	}

	function onAboutButtonClick( event ) {
		overlay.style.display = "block";
		descriptionModal.style.display = "block";
	}

	function onSaveClick( event ) {
		overlay.style.display = "block";
		saveModal.style.display = "block";
	}

	function saveText( event ) {

		if (typeof saveFormat != 'undefined' && saveFormat != '') {
			var blob = new Blob([textToWrite], {type: "text/plain;charset=utf-8"});
			/* remove tabs and line breaks from header */
			var headerText = header.innerHTML.replace(/(\t|\n|\r)/gm,"");
			if (headerText === "") {
			    headerText = "ZenPen";
			}
			saveAs(blob, headerText + '.txt');
		} else {
			document.querySelector('.saveoverlay h1').style.color = '#FC1E1E';
		}
	}

	/* Allows the user to press enter to tab from the title */
	function onHeaderKeyPress( event ) {

		if ( event.keyCode === 13 ) {
			event.preventDefault();
			article.focus();
		}
	}

	/* Allows the user to press enter to tab from the word count modal */
	function onWordCountKeyUp( event ) {

		if ( event.keyCode === 13 ) {
			event.preventDefault();

			setWordCount( parseInt(this.value) );

			removeOverlay();

			article.focus();
		}
	}

	function onWordCountChange( event ) {

		setWordCount( parseInt(this.value) );
	}

	function setWordCount( count ) {

		// Set wordcount ui to active
		if ( count > 0) {

			wordCountValue = count;
			wordCounter.className = "word-counter active";
			updateWordCount();

		} else {

			wordCountValue = 0;
			wordCounter.className = "word-counter";
		}

		saveState();
	}

	function onArticleKeyUp( event ) {

		if ( wordCountValue > 0 ) {
			updateWordCount();
		}
	}

	function updateWordCount() {

		var wordCount = editor.getWordCount();
		var percentageComplete = wordCount / wordCountValue;
		wordCounterProgress.style.height = percentageComplete * 100 + '%';

		if ( percentageComplete >= 1 ) {
			wordCounterProgress.className = "progress complete";
		} else {
			wordCounterProgress.className = "progress";
		}
	}

	function selectFormat( e ) {

		if ( document.querySelectorAll('span.activesave').length > 0 ) {
			document.querySelector('span.activesave').className = '';
		}

		document.querySelector('.saveoverlay h1').style.cssText = '';

		var targ;
		if (!e) var e = window.event;
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;

		// defeat Safari bug
		if (targ.nodeType == 3) {
			targ = targ.parentNode;
		}

		targ.className ='activesave';

		saveFormat = targ.getAttribute('data-format');

		var header = document.querySelector('header.header');
		var headerText = header.innerHTML.replace(/(\r\n|\n|\r)/gm,"") + "\n";

		var body = document.querySelector('article.content');
		var bodyText = body.innerHTML;

		textToWrite = formatText(saveFormat,headerText,bodyText);

		var textArea = document.querySelector('.hiddentextbox');
		textArea.value = textToWrite;
		textArea.focus();
		textArea.select();

	}

	function formatText( type, header, body ) {

		var text;
		switch( type ) {

			case 'html':
				header = "
" + header + "
";
				text = header + body;
				text = text.replace(/\t/g, '');
			break;

			case 'markdown':
				header = header.replace(/\t/g, '');
				header = header.replace(/\n$/, '');
				header = "#" + header + "#";

				text = body.replace(/\t/g, '');

				text = text.replace(/|<\/b>/g,"**")
					.replace(/\r\n+|\r+|\n+|\t+/ig,"")
					.replace(/|<\/i>/g,"_")
					.replace(/
/g,"> ")
					.replace(/<\/blockquote>/g,"")
					.replace(/
|<\/p>/gi,"\n")
					.replace(/
/g,"\n");

				var links = text.match(/(.+)<\/a>/gi);

                                if (links !== null) {
                                        for ( var i = 0; i<links.length; i++ ) {
                                                var tmpparent = document.createElement('div');
                                                tmpparent.innerHTML = links[i];

                                                var tmp = tmpparent.firstChild;

                                                var href = tmp.getAttribute('href');
                                                var linktext = tmp.textContent || tmp.innerText || "";

                                                text = text.replace(links[i],'['+linktext+']('+href+')');
                                        }
                                }

				text = header +"\n\n"+ text;
			break;

			case 'plain':
				header = header.replace(/\t/g, '');

				var tmp = document.createElement('div');
				tmp.innerHTML = body;
				text = tmp.textContent || tmp.innerText || "";

				text = text.replace(/\t/g, '')
					.replace(/\n{3}/g,"\n")
					.replace(/\n/,""); //replace the opening line break

				text = header + text;
			break;
			default:
			break;
		}

		return text;
	}

	function onOverlayClick( event ) {

		if ( event.target.className === "overlay" ) {
			removeOverlay();
		}
	}

	function removeOverlay() {

		overlay.style.display = "none";
		wordCountBox.style.display = "none";
		descriptionModal.style.display = "none";
		saveModal.style.display = "none";

		if ( document.querySelectorAll('span.activesave' ).length > 0) {
			document.querySelector('span.activesave').className = '';
		}

		saveFormat='';
	}

	return {
		init: init
	}

})();
<commit_msg>Update ui.js<commit_after>// ui functions
ZenPen = window.ZenPen || {};
ZenPen.ui = (function() {

	// Base elements
	var body, article, uiContainer, overlay, aboutButton, descriptionModal, header;

	// Buttons
	var screenSizeElement, colorLayoutElement, targetElement, saveElement;

	// Work Counter
	var wordCountValue, wordCountBox, wordCountElement, wordCounter, wordCounterProgress;

	//save support
	var supportSave, saveFormat, textToWrite;

	var expandScreenIcon = '';
	var shrinkScreenIcon = '';

	var darkLayout = false;

	function init() {

		supportsSave = !!new Blob()?true:false;

		bindElements();

		wordCountActive = false;

		if ( ZenPen.util.supportsHtmlStorage() ) {
			loadState();
		}

		console.log( "Checkin under the hood eh? We've probably got a lot in common. You should totally check out ZenPen on github! (https://github.com/tholman/zenpen)." );
	}

	function loadState() {

		// Activate word counter
		if ( localStorage['wordCount'] && localStorage['wordCount'] !== "0") {
			wordCountValue = parseInt(localStorage['wordCount']);
			wordCountElement.value = localStorage['wordCount'];
			wordCounter.className = "word-counter active";
			updateWordCount();
		}

		// Activate color switch
		if ( localStorage['darkLayout'] === 'true' ) {
			if ( darkLayout === false ) {
				document.body.className = 'yang';
			} else {
				document.body.className = 'yin';
			}
			darkLayout = !darkLayout;
		}

	}

	function saveState() {

		if ( ZenPen.util.supportsHtmlStorage() ) {
			localStorage[ 'darkLayout' ] = darkLayout;
			localStorage[ 'wordCount' ] = wordCountElement.value;
		}
	}

	function bindElements() {

		// Body element for light/dark styles
		body = document.body;

		uiContainer = document.querySelector( '.ui' );

		// UI element for color flip
		colorLayoutElement = document.querySelector( '.color-flip' );
		colorLayoutElement.onclick = onColorLayoutClick;

		// UI element for full screen
		screenSizeElement = document.querySelector( '.fullscreen' );
		screenSizeElement.onclick = onScreenSizeClick;

		targetElement = document.querySelector( '.target ');
		targetElement.onclick = onTargetClick;

		document.addEventListener( "fullscreenchange", function () {
			if ( document.fullscreenEnabled === false ) {
				exitFullscreen();
			}
		}, false);

		//init event listeners only if browser can save
		if (supportsSave) {

			saveElement = document.querySelector( '.save' );
			saveElement.onclick = onSaveClick;

			var formatSelectors = document.querySelectorAll( '.saveselection span' );
			for( var i in formatSelectors ) {
				formatSelectors[i].onclick = selectFormat;
			}

			document.querySelector('.savebutton').onclick = saveText;
		} else {
			document.querySelector('.save.useicons').style.display = "none";
		}

		// Overlay when modals are active
		overlay = document.querySelector( '.overlay' );
		overlay.onclick = onOverlayClick;

		article = document.querySelector( '.content' );
		article.onkeyup = onArticleKeyUp;

		wordCountBox = overlay.querySelector( '.wordcount' );
		wordCountElement = wordCountBox.querySelector( 'input' );
		wordCountElement.onchange = onWordCountChange;
		wordCountElement.onkeyup = onWordCountKeyUp;

		descriptionModal = overlay.querySelector( '.description' );

		saveModal = overlay.querySelector('.saveoverlay');

		wordCounter = document.querySelector( '.word-counter' );
		wordCounterProgress = wordCounter.querySelector( '.progress' );

		aboutButton = document.querySelector( '.about' );
		aboutButton.onclick = onAboutButtonClick;

		header = document.querySelector( '.header' );
		header.onkeypress = onHeaderKeyPress;
	}

	function onScreenSizeClick( event ) {

		if ( !document.fullscreenElement ) {
			enterFullscreen();
		} else {
			exitFullscreen();
		}
	}

	function enterFullscreen() {
		document.body.requestFullscreen( Element.ALLOW_KEYBOARD_INPUT );
		screenSizeElement.innerHTML = shrinkScreenIcon;
	}

	function exitFullscreen() {
		document.exitFullscreen();
		screenSizeElement.innerHTML = expandScreenIcon;
	}

	function onColorLayoutClick( event ) {
		if ( darkLayout === false ) {
			document.body.className = 'yang';
		} else {
			document.body.className = 'yin';
		}
		darkLayout = !darkLayout;

		saveState();
	}

	function onTargetClick( event ) {
		overlay.style.display = "block";
		wordCountBox.style.display = "block";
		wordCountElement.focus();
	}

	function onAboutButtonClick( event ) {
		overlay.style.display = "block";
		descriptionModal.style.display = "block";
	}

	function onSaveClick( event ) {
		overlay.style.display = "block";
		saveModal.style.display = "block";
	}

	function saveText( event ) {

		if (typeof saveFormat != 'undefined' && saveFormat != '') {
			var blob = new Blob([textToWrite], {type: "text/plain;charset=utf-8"});
			/* remove tabs and line breaks from header */
			var headerText = header.innerHTML.replace(/(\t|\n|\r)/gm,"");
			if (headerText === "") {
			    headerText = "ZenPen";
			}
			saveAs(blob, headerText + '.txt');
		} else {
			document.querySelector('.saveoverlay h1').style.color = '#FC1E1E';
		}
	}

	/* Allows the user to press enter to tab from the title */
	function onHeaderKeyPress( event ) {

		if ( event.keyCode === 13 ) {
			event.preventDefault();
			article.focus();
		}
	}

	/* Allows the user to press enter to tab from the word count modal */
	function onWordCountKeyUp( event ) {

		if ( event.keyCode === 13 ) {
			event.preventDefault();

			setWordCount( parseInt(this.value) );

			removeOverlay();

			article.focus();
		}
	}

	function onWordCountChange( event ) {

		setWordCount( parseInt(this.value) );
	}

	function setWordCount( count ) {

		// Set wordcount ui to active
		if ( count > 0) {

			wordCountValue = count;
			wordCounter.className = "word-counter active";
			updateWordCount();

		} else {

			wordCountValue = 0;
			wordCounter.className = "word-counter";
		}

		saveState();
	}

	function onArticleKeyUp( event ) {

		if ( wordCountValue > 0 ) {
			updateWordCount();
		}
	}

	function updateWordCount() {

		var wordCount = ZenPen.editor.getWordCount();
		var percentageComplete = wordCount / wordCountValue;
		wordCounterProgress.style.height = percentageComplete * 100 + '%';

		if ( percentageComplete >= 1 ) {
			wordCounterProgress.className = "progress complete";
		} else {
			wordCounterProgress.className = "progress";
		}
	}

	function selectFormat( e ) {

		if ( document.querySelectorAll('span.activesave').length > 0 ) {
			document.querySelector('span.activesave').className = '';
		}

		document.querySelector('.saveoverlay h1').style.cssText = '';

		var targ;
		if (!e) var e = window.event;
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;

		// defeat Safari bug
		if (targ.nodeType == 3) {
			targ = targ.parentNode;
		}

		targ.className ='activesave';

		saveFormat = targ.getAttribute('data-format');

		var header = document.querySelector('header.header');
		var headerText = header.innerHTML.replace(/(\r\n|\n|\r)/gm,"") + "\n";

		var body = document.querySelector('article.content');
		var bodyText = body.innerHTML;

		textToWrite = formatText(saveFormat,headerText,bodyText);

		var textArea = document.querySelector('.hiddentextbox');
		textArea.value = textToWrite;
		textArea.focus();
		textArea.select();

	}

	function formatText( type, header, body ) {

		var text;
		switch( type ) {

			case 'html':
				header = "
" + header + "
";
				text = header + body;
				text = text.replace(/\t/g, '');
			break;

			case 'markdown':
				header = header.replace(/\t/g, '');
				header = header.replace(/\n$/, '');
				header = "#" + header + "#";

				text = body.replace(/\t/g, '');

				text = text.replace(/|<\/b>/g,"**")
					.replace(/\r\n+|\r+|\n+|\t+/ig,"")
					.replace(/|<\/i>/g,"_")
					.replace(/
/g,"> ")
					.replace(/<\/blockquote>/g,"")
					.replace(/
|<\/p>/gi,"\n")
					.replace(/
/g,"\n");

				var links = text.match(/(.+)<\/a>/gi);

                                if (links !== null) {
                                        for ( var i = 0; i<links.length; i++ ) {
                                                var tmpparent = document.createElement('div');
                                                tmpparent.innerHTML = links[i];

                                                var tmp = tmpparent.firstChild;

                                                var href = tmp.getAttribute('href');
                                                var linktext = tmp.textContent || tmp.innerText || "";

                                                text = text.replace(links[i],'['+linktext+']('+href+')');
                                        }
                                }

				text = header +"\n\n"+ text;
			break;

			case 'plain':
				header = header.replace(/\t/g, '');

				var tmp = document.createElement('div');
				tmp.innerHTML = body;
				text = tmp.textContent || tmp.innerText || "";

				text = text.replace(/\t/g, '')
					.replace(/\n{3}/g,"\n")
					.replace(/\n/,""); //replace the opening line break

				text = header + text;
			break;
			default:
			break;
		}

		return text;
	}

	function onOverlayClick( event ) {

		if ( event.target.className === "overlay" ) {
			removeOverlay();
		}
	}

	function removeOverlay() {

		overlay.style.display = "none";
		wordCountBox.style.display = "none";
		descriptionModal.style.display = "none";
		saveModal.style.display = "none";

		if ( document.querySelectorAll('span.activesave' ).length > 0) {
			document.querySelector('span.activesave').className = '';
		}

		saveFormat='';
	}

	return {
		init: init
	}

})();
<|endoftext|>


<commit_before>const normalizeCode = code => code
  .replace(/^((\s\s)+)/mg, (_, indentation) => (
    '  '.repeat(indentation.length / 2)
  ))

export default normalizeCode
<commit_msg>Fix normalizeCode to be more strict about tabs v spaces<commit_after>const indentRe = /^((\t|  )+)/mg
const tabRe = /\t/g

const normalizeCode = code => code.replace(indentRe, (_, indentation) => {
  return indentation.replace(tabRe, '  ')
})

export default normalizeCode
<|endoftext|>


<commit_before>/**
 *  Object.deepExtend(destination, source) -> Object
 *
 *  A "deep" version of `Object.extend`. Performs a recursive deep extension.
**/

Object.deepExtend = function(destination, source) {
  for (var property in source) {
    if (source[property] && source[property].constructor &&
     source[property].constructor === Object) {
      destination[property] = destination[property] || {};
      arguments.callee(destination[property], source[property]);
    } else {
      destination[property] = source[property];
    }
  }
  return destination;
};

/** section: scripty2 ui
 * S2.UI.Mixin
**/
S2.UI.Mixin = {};

/** section: scripty2 ui
 *  mixin S2.UI.Mixin.Configurable
 *
 *  A mixin for hassle-free blending of default options with user-defined
 *  options.
 *
 *  Expects default options to be defined in a `DEFAULT_OPTIONS` property
 *  on the class itself.
**/
S2.UI.Mixin.Configurable = {
  /**
   *  S2.UI.Mixin.Configurable#setOptions(options) -> Object
   *  - options (Object): A set of user-defined options that should override
   *    the defaults.
   *
   *  Sets options on the class.
  **/
  setOptions: function(options) {
    if (!this.options) {
      this.options = {};
      var constructor = this.constructor;
      if (constructor.superclass) {
        // Build the inheritance chain.
        var chain = [], klass = constructor;
        while (klass = klass.superclass)
          chain.push(klass);
        chain = chain.reverse();

        for (var i = 0, l = chain.length; i < l; i++)
          Object.deepExtend(this.options, chain[i].DEFAULT_OPTIONS || {});
      }

      Object.deepExtend(this.options, constructor.DEFAULT_OPTIONS || {});
    }
    return Object.deepExtend(this.options, options || {});
  }
};

/** section: scripty2 ui
 *  mixin S2.UI.Mixin.Trackable
**/
S2.UI.Mixin.Trackable = {
  register: function() {
    var klass = this.constructor;
    if (!klass.instances) {
      klass.instances = [];
    }
    if (!klass.instances.include(this)) {
      klass.instances.push(this);
    }

    if (Object.isFunction(klass.onRegister)) {
      klass.onRegister.call(klass, this);
    }
  },

  unregister: function() {
    var klass = this.constructor;
    klass.instances = klass.instances.without(this);
    if (Object.isFunction(klass.onRegister)) {
      klass.onUnregister.call(klass, this);
    }
  }
};<commit_msg>Add `S2.UI.Mixin.Shim` for placing an IFRAME shim in IE6. I hate IE6.<commit_after>/**
 *  Object.deepExtend(destination, source) -> Object
 *
 *  A "deep" version of `Object.extend`. Performs a recursive deep extension.
**/

Object.deepExtend = function(destination, source) {
  for (var property in source) {
    if (source[property] && source[property].constructor &&
     source[property].constructor === Object) {
      destination[property] = destination[property] || {};
      arguments.callee(destination[property], source[property]);
    } else {
      destination[property] = source[property];
    }
  }
  return destination;
};

/** section: scripty2 ui
 * S2.UI.Mixin
**/
S2.UI.Mixin = {};

/** section: scripty2 ui
 *  mixin S2.UI.Mixin.Configurable
 *
 *  A mixin for hassle-free blending of default options with user-defined
 *  options.
 *
 *  Expects default options to be defined in a `DEFAULT_OPTIONS` property
 *  on the class itself.
**/
S2.UI.Mixin.Configurable = {
  /**
   *  S2.UI.Mixin.Configurable#setOptions(options) -> Object
   *  - options (Object): A set of user-defined options that should override
   *    the defaults.
   *
   *  Sets options on the class.
  **/
  setOptions: function(options) {
    if (!this.options) {
      this.options = {};
      var constructor = this.constructor;
      if (constructor.superclass) {
        // Build the inheritance chain.
        var chain = [], klass = constructor;
        while (klass = klass.superclass)
          chain.push(klass);
        chain = chain.reverse();

        for (var i = 0, l = chain.length; i < l; i++)
          Object.deepExtend(this.options, chain[i].DEFAULT_OPTIONS || {});
      }

      Object.deepExtend(this.options, constructor.DEFAULT_OPTIONS || {});
    }
    return Object.deepExtend(this.options, options || {});
  }
};

/** section: scripty2 ui
 *  mixin S2.UI.Mixin.Trackable
**/
S2.UI.Mixin.Trackable = {
  register: function() {
    var klass = this.constructor;
    if (!klass.instances) {
      klass.instances = [];
    }
    if (!klass.instances.include(this)) {
      klass.instances.push(this);
    }

    if (Object.isFunction(klass.onRegister)) {
      klass.onRegister.call(klass, this);
    }
  },

  unregister: function() {
    var klass = this.constructor;
    klass.instances = klass.instances.without(this);
    if (Object.isFunction(klass.onRegister)) {
      klass.onUnregister.call(klass, this);
    }
  }
};

/** section: scripty2 ui
 *  mixin S2.UI.Mixin.Shim
**/
S2.UI.Mixin.Shim = {
  __SHIM_TEMPLATE: new Template(
    "<iframe frameborder='0' tabindex='-1' src='javascript:false;' " +
      "style='display:block;position:absolute;z-index:-1;overflow:hidden; " +
      "filter:Alpha(Opacity=\"0\");" +
      "top:expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\');" +
       "left:expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\');" +
       "width:expression(this.parentNode.offsetWidth+\'px\');" +
       "height:expression(this.parentNode.offsetHeight+\'px\');" +
    "' id='#{0}'></iframe>"
  ),

  /**
   *  S2.UI.Mixin.Shim#createShim([element]) -> undefined
   *  - element (Element): Optional element to shim. If omitted, will assume
   *    `this.element`.
   *
   *  Create an IFRAME "shim" underneath the positioned element.
   *
   *  Needed for IE6, which otherwise shows some UI controls (like SELECT
   *  boxes) _above_ an element, regardless of its CSS z-index.
   *
   *  Does nothing in other browsers.
  **/
  createShim: function(element) {
    // Only needed for IE 6.
    this.__shim_isie6 = (Prototype.Browser.IE &&
     (/6.0/).test(navigator.userAgent));
    if (!this.__shim_isie6) return;

    element = $(element || this.element);
    if (!element) return;

    // The element we're sticking a shim underneath.
    this.__shimmed = element;

    var id = element.identify() + '_iframeshim', shim = $(id);

    // Clean up any shim that may exist already.
    if (shim) shim.remove();

    element.insert({
      top: this.__SHIM_TEMPLATE.evaluate([id])
    });

    this.__shim_id = id;
  },

  /**
   *  S2.UI.Mixin.Shim.adjustShim() -> undefined
   *
   *  Reposition the shim, copying the dimensions and offsets of the target
   *  element.
   *
   *  Note that the [[S2.UI.Mixin.Shim]] mixin _attempts_ to do this
   *  automatically by using IE6's proprietary CSS expressions. But because
   *  such expressions can sometimes fail to update promptly, calling this
   *  method yourself may be necessary.
   *
   *  Once you've called `adjustShim`, the shim loses the ability to
   *  dynamically update its position on its own. Subsequently, you'll have
   *  to call `adjustShim` again each time you update the element's layout.
  **/
  adjustShim: function() {
    if (!this.__shim_isie6) return;
    var shim = this.__shimmed.down('iframe#' + this.__shim_id);
    var element = this.__shimmed;
    if (!shim) return;

    shim.setStyle({
      width:  element.offsetWidth  + 'px',
      height: element.offsetHeight + 'px'
    });
  },

  /**
   *  S2.UI.Mixin.Shim#destroyShim() -> undefined
   *
   *  Removes the shim.
  **/
  destroyShim: function() {
    if (!this.__shim_isie6) return;
    var shim = this.__shimmed.down('iframe#' + this.__shim_id);
    if (shim) {
      shim.remove();
    }

    this.__shimmed = null;
  }
};<|endoftext|>


<commit_before>// codepoints is an int array,
// tableId a string to a

// and buttons is an array of {
//   displayName: "Display name",
//   functionName: "function name",
//   require: function(idx, length) -> bool
// }, where each function name refers to a function taking a codepoint and an index into `codepoints`
function renderCodepointsInTable(codepoints, tableId, buttons) {
	var table = $('#' + tableId);
	if (codepoints.length == 0) {
		table.html('');
		return;
	}
	var html = ('
'
	    + '
	Codepoint (Hex)	Codepoint (Decimal)	Character	Category	Name
'
	    + '

');
	for (var i = 0; i < codepoints.length; ++i) {
		var codepoint = codepoints[i];
		var buttonStr = '';
		for (var j in buttons) {
			var buttonDescription = buttons[j];
			var disabled = '';
			if (buttonDescription.require) {
				if (!buttonDescription.require(i, codepoints.length)) {
					disabled = 'disabled '
				}
			}
			buttonStr += '<input type="button" ' + disabled + 'onclick="' + buttonDescription.functionName + '(' + codepoint + ', ' + i + ')" value="'
			    + buttonDescription.displayName
			    + '">';
		}
		html += '
'
		    + '' + buttonStr + '	'
		    + 'U+' + itos(codepoint, 16, 4) + '	'
		    + '' + codepoint + '	'
		    + '' + displayCodepoint(codepoint) + '	'
		    + '' + getCharacterCategoryName(codepoint) + '	'
		    + '' + getHtmlNameDescription(codepoint) + '	'
		    + '
';
	}
	if (i >= 256) {
		html += '
...	...	...	...	...	...
';
	}
	html += '
';
	table.html(html);
}

function randomColorForKey(key) {
	if (typeof colorMap == 'undefined')
		colorMap = [];
	if (colorMap[key])
		return colorMap[key];
	var color = randomColor({
		luminosity: 'light'
	});
	colorMap[key] = color;
	return color;
}

function updateRenderedCodepage() {
	var encoding = $('#codepageEncoding option:selected').text();
	var mapping = mappings[encoding];
	var ascii = isMapping7Bit(mapping);
	var html = '
	';
	for (var i = 0; i < 16; ++i)
		html += '_' + i.toString(16).toUpperCase() + '	';
	html += '

';
	for (var i = 0; i < (ascii ? 8 : 16); ++i) {
		html += '
' + i.toString(16).toUpperCase() + '_	';
		for (var j = 0; j < 16; ++j) {
			var byte = (i << 4) + j;
			var codepoint = codepointForByteUsingMapping(mapping, byte);
			var color = randomColorForKey(getCharacterCategoryName(codepoint));
			var displayedCodepoint = displayCodepoint(codepoint);
			if (displayedCodepoint) {
				html += ''
					+ i.toString(16).toUpperCase()
					+ j.toString(16).toUpperCase()
					+ '
'
					+ displayedCodepoint
					+ '	';
			} else {
				html += '' + i.toString(16).toUpperCase() + j.toString(16).toUpperCase() + '
 	';
			}
		}
		html += '
';
	}
	html += '
';
	$('#codepage').html(html);
}

function showCodepageDetail(codepoint) {
	$('#detail-codepoint-hex').text(itos(codepoint, 16, 4));
	$('#detail-codepoint-decimal').text(codepoint);
	$('#detail-name').html('"' + getName(codepoint) + '"');
	$('#detail-character').html(displayCodepoint(codepoint));
	$('#detail-category').text(getCharacterCategoryCode(codepoint) + ' (' + getCharacterCategoryName(codepoint) + ')');
	$('#detail-block').text(getBlockForCodepoint(codepoint).replace('_', ' '));
	$('#detail-script').text(getScriptForCodepoint(codepoint).replace('_', ' '));
	var aliases = [];
	for (var i = 0; i < aliases.length; ++i) {
		if (aliases[i].codepoint == codepoint)
			aliases.push(aliases[i].alias);
	}
	if (aliases.length == 0) {
		$('#detail-aliases').hide();
	} else {
		$('#detail-aliases').show();
		$('#detail-aliases-list').text(aliases.join(', '));
	}
	var meaning = getHanEntry(codepoint, '');
	if (meaning.length == 0) {
		$('#detail-meaning').hide();
	} else {
		$('#detail-meaning').show();
		$('#detail-meaning-content').text(meaning);
	}
	var mandarin = mandarin_readings[codepoint];
	if (mandarin) {
		$('#detail-mandarin').show();
		$('#detail-mandarin-content').text(mandarin);
	} else {
		$('#detail-mandarin').hide();
	}
	var kun = kun_readings[codepoint];
	if (kun) {
		$('#detail-kun').show();
		$('#detail-kun-content').text(kun);
	} else {
		$('#detail-kun').hide();
	}
	var on = on_readings[codepoint];
	if (on) {
		$('#detail-on').show();
		$('#detail-on-content').text(on);
	} else {
		$('#detail-on').hide();
	}
	var encodingsString = '';
	$('#outputEncoding option').each(function(i, e) {
		var encoding = $(e).text();
		var html = encodeOutput(
			$('#byteOrderMark option:selected').text(),
			encoding,
			$('#outputFormat option:selected').text(),
			$('#outputJoiner option:selected').text(),
			[codepoint]
		);
		if (html.startsWith('<span'))
			return;
		encodingsString += encoding + ': ' + html + '\n';
	});

	$('#detail-encoding-outputs').text(encodingsString);
	$('#codepoint-detail').modal('show');
}
<commit_msg>Fix escaping of html entities<commit_after>// codepoints is an int array,
// tableId a string to a

// and buttons is an array of {
//   displayName: "Display name",
//   functionName: "function name",
//   require: function(idx, length) -> bool
// }, where each function name refers to a function taking a codepoint and an index into `codepoints`
function renderCodepointsInTable(codepoints, tableId, buttons) {
	var table = $('#' + tableId);
	if (codepoints.length == 0) {
		table.html('');
		return;
	}
	var html = ('
'
	    + '
	Codepoint (Hex)	Codepoint (Decimal)	Character	Category	Name
'
	    + '

');
	for (var i = 0; i < codepoints.length; ++i) {
		var codepoint = codepoints[i];
		var buttonStr = '';
		for (var j in buttons) {
			var buttonDescription = buttons[j];
			var disabled = '';
			if (buttonDescription.require) {
				if (!buttonDescription.require(i, codepoints.length)) {
					disabled = 'disabled '
				}
			}
			buttonStr += '<input type="button" ' + disabled + 'onclick="' + buttonDescription.functionName + '(' + codepoint + ', ' + i + ')" value="'
			    + buttonDescription.displayName
			    + '">';
		}
		html += '
'
		    + '' + buttonStr + '	'
		    + 'U+' + itos(codepoint, 16, 4) + '	'
		    + '' + codepoint + '	'
		    + '' + displayCodepoint(codepoint) + '	'
		    + '' + getCharacterCategoryName(codepoint) + '	'
		    + '' + getHtmlNameDescription(codepoint) + '	'
		    + '
';
	}
	if (i >= 256) {
		html += '
...	...	...	...	...	...
';
	}
	html += '
';
	table.html(html);
}

function randomColorForKey(key) {
	if (typeof colorMap == 'undefined')
		colorMap = [];
	if (colorMap[key])
		return colorMap[key];
	var color = randomColor({
		luminosity: 'light'
	});
	colorMap[key] = color;
	return color;
}

function updateRenderedCodepage() {
	var encoding = $('#codepageEncoding option:selected').text();
	var mapping = mappings[encoding];
	var ascii = isMapping7Bit(mapping);
	var html = '
	';
	for (var i = 0; i < 16; ++i)
		html += '_' + i.toString(16).toUpperCase() + '	';
	html += '

';
	for (var i = 0; i < (ascii ? 8 : 16); ++i) {
		html += '
' + i.toString(16).toUpperCase() + '_	';
		for (var j = 0; j < 16; ++j) {
			var byte = (i << 4) + j;
			var codepoint = codepointForByteUsingMapping(mapping, byte);
			var color = randomColorForKey(getCharacterCategoryName(codepoint));
			var displayedCodepoint = displayCodepoint(codepoint);
			if (displayedCodepoint) {
				html += ''
					+ i.toString(16).toUpperCase()
					+ j.toString(16).toUpperCase()
					+ '
'
					+ displayedCodepoint
					+ '	';
			} else {
				html += '' + i.toString(16).toUpperCase() + j.toString(16).toUpperCase() + '
 	';
			}
		}
		html += '
';
	}
	html += '
';
	$('#codepage').html(html);
}

function showCodepageDetail(codepoint) {
	$('#detail-codepoint-hex').text(itos(codepoint, 16, 4));
	$('#detail-codepoint-decimal').text(codepoint);
	$('#detail-name').html('"' + getName(codepoint) + '"');
	$('#detail-character').html(displayCodepoint(codepoint));
	$('#detail-category').text(getCharacterCategoryCode(codepoint) + ' (' + getCharacterCategoryName(codepoint) + ')');
	$('#detail-block').text(getBlockForCodepoint(codepoint).replace('_', ' '));
	$('#detail-script').text(getScriptForCodepoint(codepoint).replace('_', ' '));
	var aliases = [];
	for (var i = 0; i < aliases.length; ++i) {
		if (aliases[i].codepoint == codepoint)
			aliases.push(aliases[i].alias);
	}
	if (aliases.length == 0) {
		$('#detail-aliases').hide();
	} else {
		$('#detail-aliases').show();
		$('#detail-aliases-list').text(aliases.join(', '));
	}
	var meaning = getHanEntry(codepoint, '');
	if (meaning.length == 0) {
		$('#detail-meaning').hide();
	} else {
		$('#detail-meaning').show();
		$('#detail-meaning-content').text(meaning);
	}
	var mandarin = mandarin_readings[codepoint];
	if (mandarin) {
		$('#detail-mandarin').show();
		$('#detail-mandarin-content').text(mandarin);
	} else {
		$('#detail-mandarin').hide();
	}
	var kun = kun_readings[codepoint];
	if (kun) {
		$('#detail-kun').show();
		$('#detail-kun-content').text(kun);
	} else {
		$('#detail-kun').hide();
	}
	var on = on_readings[codepoint];
	if (on) {
		$('#detail-on').show();
		$('#detail-on-content').text(on);
	} else {
		$('#detail-on').hide();
	}
	var encodingsString = '';
	$('#outputEncoding option').each(function(i, e) {
		var encoding = $(e).text();
		var html = encodeOutput(
			$('#byteOrderMark option:selected').text(),
			encoding,
			$('#outputFormat option:selected').text(),
			$('#outputJoiner option:selected').text(),
			[codepoint]
		);
		if (html.startsWith('<span'))
			return;
		encodingsString += encoding + ': ' + html + '\n';
	});

	$('#detail-encoding-outputs').html(encodingsString);
	$('#codepoint-detail').modal('show');
}
<|endoftext|>


<commit_before>// init the state and change the state
const Reducer =(state={
	errRegInfo:'',
	errLogInfo:'',
	errUpdateInfo:'',
    	errProfileInfo:'',
    	errLinkInfo:'',
	location:'',
	user:{},
	followerList: [],
	articles: [],
	articlesFilt: []
},action)=>{
	switch (action.type){
		case 'TO_OUT':{
			return {...state,
					location:"LANDING_PAGE",
					user:{},
                    articles:[],
                    articlesFilt:[],
                    followerList:[],
                    errRegInfo:'',
                    errLogInfo:'',
                    errUpdateInfo:'',
                    errProfileInfo:''
            }
        }
		case 'TO_MAIN_PAGE':{
			return {...state,
					location:"MAIN_PAGE"}
        }
        case 'TO_PROFILE_PAGE':
			return {...state,
					location:"PROFILE_PAGE",
					errUpdateInfo:''}
        case 'CLEAN': {
                return {
                    ...state,
                    followerList: [],
                    articles: []
                }
        }
		case 'IS_REG_ERROR':
			return {...state,
					errRegInfo: action.errRegInfo}
		case 'IS_LOG_ERROR':
			return {...state,
					errLogInfo:action.errLogInfo}
		case 'IS_UPDATE_ERROR':
			return {...state,
					errUpdateInfo:action.errUpdateInfo}
        case 'IS_PROFILE_ERROR':
			return {...state,
					errProfileInfo:action.errProfileInfo}
        case 'IS_LINK_ERROR':{
			return {...state,
					errLinkInfo:action.errLinkInfo}
        }
		case 'UPDATE_HEADLINE':
			return {...state,
					user:{
						...state.user,
						name:action.username,
					    headline:action.headline
					}
			}
		case 'UPDATE_ARTICLES': {
        //    console.log(action.articles)
            return {
                ...state,
                articles: action.articles,
                articlesFilt: action.articles
            }
        }
        case 'UPDATE_AVATAR': {
            return {
                ...state,
              user:{
						...state.user,
						avatar:action.avatar
			}
        }
        }
		case 'REGISTER':
			return {...state,
					user: action.user}
		case 'LOG_IN':
			return {...state,
					user: action.user}
		case 'ADD_ARTICLE':{
			 return {
                ...state,
                articles: [
                    ...state.articles,
                    {
                        author:'',
                        text: action.articles.text,
                        timestamp:'',
                        picture:action.articles.img
                    }
                ]
            }
        }
		case 'ADD_FOLLOWING':
            return {
                ...state,
                followerList: [
                    ...state.followerList,
                    action.followerList
                ]
        }
		case 'INIT_PROFILE': {
            return {
                ...state,
                user: {
                    ...state.user,
                    email: action.newuser.email,
                    zipcode: action.newuser.zipcode,
                    dob: action.newuser.dob,
                    avatar: action.newuser.avatar
                }
            }
        }
		case 'RESUME_ARTICLES': {
            return {
                ...state,
                articlesFilt: state.articles
            }
        }
        case 'FILTER_ARTICLES': {
            return {
                ...state,
                articlesFilt: state.articles.filter((article) => {
                    if(article.author.indexOf(action.keyWord) == -1 && article.text.indexOf(action.keyWord) == -1) {
                        return false;
                    }
                    return true;
                })
            }
        }
		default:
			return state
	}
}
export default Reducer
<commit_msg>Update reducers.js<commit_after>// init the state and change the state
const Reducer =(state={
	errRegInfo:'',
	errLogInfo:'',
	errUpdateInfo:'',
    	errProfileInfo:'',
    	errLinkInfo:'',
	location:'',
	user:{},
	followerList: [],
	articles: [],
	articlesFilt: []
},action)=>{
	switch (action.type){
		case 'TO_OUT':
			return {...state,
					location:"LANDING_PAGE",
					user:{},
					articles:[],
					articlesFilt:[],
					followerList:[],
					errRegInfo:'',
					errLogInfo:'',
					errUpdateInfo:'',
					errProfileInfo:''}
		case 'TO_MAIN_PAGE':
			return {...state,
					location:"MAIN_PAGE"}
        	case 'TO_PROFILE_PAGE':
			return {...state,
					location:"PROFILE_PAGE",
					errUpdateInfo:''}
        	case 'CLEAN':
                	return {...state,
                    			followerList: [],
                    			articles: []}
		case 'IS_REG_ERROR':
			return {...state,
					errRegInfo: action.errRegInfo}
		case 'IS_LOG_ERROR':
			return {...state,
					errLogInfo:action.errLogInfo}
		case 'IS_UPDATE_ERROR':
			return {...state,
					errUpdateInfo:action.errUpdateInfo}
        	case 'IS_PROFILE_ERROR':
			return {...state,
					errProfileInfo:action.errProfileInfo}
        	case 'IS_LINK_ERROR':
			return {...state,
					errLinkInfo:action.errLinkInfo}
		case 'UPDATE_HEADLINE':
			return {...state,
					user:{
						...state.user,
						name:action.username,
					    headline:action.headline
					}
			}
		case 'UPDATE_ARTICLES':
            		return {...state,
                			articles: action.articles,
                			articlesFilt: action.articles}
        	case 'UPDATE_AVATAR':
            		return {...state,
              				user:{
						...state.user,
						avatar:action.avatar}
        		}
		case 'REGISTER':
			return {...state,
					user: action.user}
		case 'LOG_IN':
			return {...state,
					user: action.user}
		case 'ADD_ARTICLE':
			 return {...state,
					articles: [...state.articles,
						{
							author:'',
							text: action.articles.text,
							timestamp:'',
							picture:action.articles.img
						}]
			}
		case 'ADD_FOLLOWING':
			return {...state,
					followerList: [
					    ...state.followerList,
					    action.followerList]
			}
		case 'INIT_PROFILE':
            		return {...state,
                			user: {
					    ...state.user,
					    email: action.newuser.email,
					    zipcode: action.newuser.zipcode,
					    dob: action.newuser.dob,
					    avatar: action.newuser.avatar
					}
			}
		case 'RESUME_ARTICLES':
			return {...state,
					articlesFilt: state.articles}
        	case 'FILTER_ARTICLES':
            		return {
				...state,
				articlesFilt: state.articles.filter((article) => {
				    if(article.author.indexOf(action.keyWord) == -1 && article.text.indexOf(action.keyWord) == -1) {
					return false;
				    }
				    return true;
				})
            		}
		default:
			return state
	}
}
export default Reducer
<|endoftext|>


<commit_before>var fs = require("fs");
var path = require("path");

var FILE_PATHS = {
    ROOT: "/sys/class/gpio",
    EXPORT_FILE: "export"
};
var GPIOReference = {

    gpios: [
        106, 107, 180, 181, 172, 173, 182, 124,
        25, 22, 14, 15, 16, 17, 18, 19,
        20, 21, 203, 202, 177, 176, 175, 174,
        119, 124, 127, 116, 7, 6, 5, 4
    ],

    DIRECTION: {
        INPUT: "in",
        OUTPUT: "out"
    },
    VALUE: {
        HIGH: "1",
        LOW: "0"
    },

    fromPin: function (pinNumber) {
        if (16 > pinNumber || pinNumber > 47) throw new Error("Invalid pin number.");
        return GPIOReference.gpios[pinNumber - 16];
    },
    isValid: function (gpioNumber) {
        return GPIOReference.gpios.indexOf(gpioNumber) > -1;
    }

};

function GPIO(num) {
    if (num) {
        this.fromGpio(num);
    }
}

GPIO.prototype = {

    currentGpioNumber: null,
    currentGPIO: function () {
        if (!this.currentGpioNumber) throw new Error("Missing GPIO number.");
        return this.currentGpioNumber;
    },

    fromPin: function (num) {
        this.currentGpioNumber = GPIOReference.fromPin(num);
        return this;
    },
    fromGpio: function (gpioNumber) {
        if (!GPIOReference.isValid(gpioNumber)) throw new Error("GPIO number (" + gpioNumber + ") is out of range.");
        this.currentGpioNumber = gpioNumber;
        return this;
    },

    export: function (callback) {
        var currentNum = this.currentGPIO();
        var exportFilePath = FILE_PATHS.ROOT + path.sep + FILE_PATHS.EXPORT_FILE;
        File.write(currentNum.toString(), exportFilePath, function () {
            if (callback) callback();
        }, "w");
    },
    setDirection: function (direction, callback) {
        if ([GPIOReference.DIRECTION.INPUT, GPIOReference.DIRECTION.OUTPUT].indexOf(direction) < 0) throw new Error("Invalid direction.");
        var currentGPIO = this.currentGPIO();
        this.export(function () {
            File.createDir(FILE_PATHS.ROOT + path.sep + "gpio" + currentGPIO, function () {
                var directionPath = FILE_PATHS.ROOT + path.sep + "gpio" + currentGPIO + path.sep + "direction";
                File.write(direction, directionPath, function () {
                    if (callback) callback();
                });
            });
        });
    },
    getDirection: function (callback) {
        var currentNum = this.currentGPIO();
        this.export(function () {
            var directionPath = FILE_PATHS.ROOT + path.sep + "gpio" + currentNum + path.sep + "direction";
            File.read(directionPath, function (data) {
                callback(data);
            });
        });
    },
    setValue: function (value, callback) {
        if ([GPIOReference.VALUE.HIGH, GPIOReference.VALUE.LOW].indexOf(value) < 0) throw new Error("Invalid value.");
        var currentNum = this.currentGPIO();
        this.export(function () {
            File.createDir(FILE_PATHS.ROOT + path.sep + "gpio" + currentNum, function () {
                var valuePath = FILE_PATHS.ROOT + path.sep + "gpio" + currentNum + path.sep + "value";
                File.write(value, valuePath, function () {
                    if (callback) callback();
                });
            });
        });
    },
    getValue: function (callback) {
        var currentNum = this.currentGPIO();
        var valuePath = FILE_PATHS.ROOT + path.sep + "gpio" + currentNum + path.sep + "value";
        this.export(function () {
            File.read(valuePath, function (data) {
                callback(data);
            });
        });
    },
    watchValue: function (callback) {
        var currentNum = this.currentGPIO();
        var valuePath = FILE_PATHS.ROOT + path.sep + "gpio" + currentNum + path.sep + "value";
        File.exists(valuePath,
            function () {
                File.watch(valuePath, function () {
                    callback();
                });
            },
            function () {
                this.export(function() {
                    File.watch(valuePath, function () {
                        callback();
                    });
                });
            }
        )

    }
};

var File = {
    createDir: function (path, callback) {
        fs.mkdir(path, function () {
            callback();
        })
    },
    exists: function (path, success, failure) {
        fs.access(path, function (err) {
            if (!err) success(); else failure();
        });
    },
    read: function (filename, callback) {
        fs.readFile(filename, "utf-8", function (err, data) {
            if (err) throw err;
            callback(data);
        });
    },
    watch: function (filename, callback) {
        fs.watch(filename, function (event, filename) {
            if ("change" === event) callback();
        });
    },
    write: function (data, filePath, callback, mode) {
        if (!mode) mode = "w";
        fs.open(filePath, mode, function (err, fd) {
            if (err) {
                console.log("Could not write " + data + " in " + filePath + " | " + mode);
                throw err;
            }
            fs.write(fd, data, "utf-8", function (err) {
                if (err) throw err;
                callback();
            });
        });
    }
};

module.exports = {
    gpios: GPIOReference.gpios,
    DIRECTION: GPIOReference.DIRECTION,
    VALUE: GPIOReference.VALUE,
    GPIO: GPIO
};
<commit_msg>Uses instance instead of this<commit_after>var fs = require("fs");
var path = require("path");

var FILE_PATHS = {
    ROOT: "/sys/class/gpio",
    EXPORT_FILE: "export"
};
var GPIOReference = {

    gpios: [
        106, 107, 180, 181, 172, 173, 182, 124,
        25, 22, 14, 15, 16, 17, 18, 19,
        20, 21, 203, 202, 177, 176, 175, 174,
        119, 124, 127, 116, 7, 6, 5, 4
    ],

    DIRECTION: {
        INPUT: "in",
        OUTPUT: "out"
    },
    VALUE: {
        HIGH: "1",
        LOW: "0"
    },

    fromPin: function (pinNumber) {
        if (16 > pinNumber || pinNumber > 47) throw new Error("Invalid pin number.");
        return GPIOReference.gpios[pinNumber - 16];
    },
    isValid: function (gpioNumber) {
        return GPIOReference.gpios.indexOf(gpioNumber) > -1;
    }

};

function GPIO(num) {
    if (num) {
        this.fromGpio(num);
    }
}

GPIO.prototype = {

    currentGpioNumber: null,
    currentGPIO: function () {
        if (!this.currentGpioNumber) throw new Error("Missing GPIO number.");
        return this.currentGpioNumber;
    },

    fromPin: function (num) {
        this.currentGpioNumber = GPIOReference.fromPin(num);
        return this;
    },
    fromGpio: function (gpioNumber) {
        if (!GPIOReference.isValid(gpioNumber)) throw new Error("GPIO number (" + gpioNumber + ") is out of range.");
        this.currentGpioNumber = gpioNumber;
        return this;
    },

    export: function (callback) {
        var currentNum = this.currentGPIO();
        var exportFilePath = FILE_PATHS.ROOT + path.sep + FILE_PATHS.EXPORT_FILE;
        File.write(currentNum.toString(), exportFilePath, function () {
            if (callback) callback();
        }, "w");
    },
    setDirection: function (direction, callback) {
        if ([GPIOReference.DIRECTION.INPUT, GPIOReference.DIRECTION.OUTPUT].indexOf(direction) < 0) throw new Error("Invalid direction.");
        var currentGPIO = this.currentGPIO();
        this.export(function () {
            File.createDir(FILE_PATHS.ROOT + path.sep + "gpio" + currentGPIO, function () {
                var directionPath = FILE_PATHS.ROOT + path.sep + "gpio" + currentGPIO + path.sep + "direction";
                File.write(direction, directionPath, function () {
                    if (callback) callback();
                });
            });
        });
    },
    getDirection: function (callback) {
        var currentNum = this.currentGPIO();
        this.export(function () {
            var directionPath = FILE_PATHS.ROOT + path.sep + "gpio" + currentNum + path.sep + "direction";
            File.read(directionPath, function (data) {
                callback(data);
            });
        });
    },
    setValue: function (value, callback) {
        if ([GPIOReference.VALUE.HIGH, GPIOReference.VALUE.LOW].indexOf(value) < 0) throw new Error("Invalid value.");
        var currentNum = this.currentGPIO();
        this.export(function () {
            File.createDir(FILE_PATHS.ROOT + path.sep + "gpio" + currentNum, function () {
                var valuePath = FILE_PATHS.ROOT + path.sep + "gpio" + currentNum + path.sep + "value";
                File.write(value, valuePath, function () {
                    if (callback) callback();
                });
            });
        });
    },
    getValue: function (callback) {
        var currentNum = this.currentGPIO();
        var valuePath = FILE_PATHS.ROOT + path.sep + "gpio" + currentNum + path.sep + "value";
        this.export(function () {
            File.read(valuePath, function (data) {
                callback(data);
            });
        });
    },
    watchValue: function (callback) {
        var currentNum = this.currentGPIO();
        var valuePath = FILE_PATHS.ROOT + path.sep + "gpio" + currentNum + path.sep + "value";
        var instance = this;
        File.exists(valuePath,
            function () {
                File.watch(valuePath, function () {
                    callback();
                });
            },
            function () {
                instance.export(function () {
                    File.watch(valuePath, function () {
                        callback();
                    });
                });
            }
        )

    }
};

var File = {
    createDir: function (path, callback) {
        fs.mkdir(path, function () {
            callback();
        })
    },
    exists: function (path, success, failure) {
        fs.access(path, function (err) {
            if (!err) success(); else failure();
        });
    },
    read: function (filename, callback) {
        fs.readFile(filename, "utf-8", function (err, data) {
            if (err) throw err;
            callback(data);
        });
    },
    watch: function (filename, callback) {
        fs.watch(filename, function (event, filename) {
            if ("change" === event) callback();
        });
    },
    write: function (data, filePath, callback, mode) {
        if (!mode) mode = "w";
        fs.open(filePath, mode, function (err, fd) {
            if (err) {
                console.log("Could not write " + data + " in " + filePath + " | " + mode);
                throw err;
            }
            fs.write(fd, data, "utf-8", function (err) {
                if (err) throw err;
                callback();
            });
        });
    }
};

module.exports = {
    gpios: GPIOReference.gpios,
    DIRECTION: GPIOReference.DIRECTION,
    VALUE: GPIOReference.VALUE,
    GPIO: GPIO
};
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var util = require('util')
  , OAuthStrategy = require('passport-oauth').OAuthStrategy
  , InternalOAuthError = require('passport-oauth').InternalOAuthError;

/**
 * `Strategy` constructor.
 *
 * The Xing authentication strategy authenticates requests by delegating to
 * Xing using the OAuth protocol.
 *
 * Applications must supply a `verify` callback which accepts a `token`,
 * `tokenSecret` and service-specific `profile`, and then calls the `done`
 * callback supplying a `user`, which should be set to `false` if the
 * credentials are not valid.  If an exception occured, `err` should be set.
 *
 * Options:
 *   - `consumerKey`     identifies client to Xing
 *   - `consumerSecret`  secret used to establish ownership of the consumer key
 *   - `callbackURL`     URL to which Xing will redirect the user after obtaining authorization
 *
 * Examples:
 *
 *     passport.use(new XingStrategy({
 *         consumerKey: '123-456-789',
 *         consumerSecret: 'shhh-its-a-secret'
 *         callbackURL: 'https://www.example.net/auth/xing/callback'
 *       },
 *       function(token, tokenSecret, profile, done) {
 *         User.findOrCreate(..., function (err, user) {
 *           done(err, user);
 *         });
 *       }
 *     ));
 *
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function Strategy(options, verify) {
  options = options || {};
  options.requestTokenURL = options.requestTokenURL || 'https://api.xing.com/v1/request_token';
  options.accessTokenURL = options.accessTokenURL || 'https://api.xing.com/v1/access_token';
  options.userAuthorizationURL = options.userAuthorizationURL || 'https://api.xing.com/v1/authorize';
  options.sessionKey = options.sessionKey || 'oauth:xing';

  OAuthStrategy.call(this, options, verify);
  this.name = 'xing';
  this._profileFields = options.profileFields || null;
}

/**
 * Inherit from `OAuthStrategy`.
 */
util.inherits(Strategy, OAuthStrategy);

/**
 * Authenticate request by delegating to Xing using OAuth.
 *
 * @param {Object} req
 * @api protected
 */
Strategy.prototype.authenticate = function(req) {
  // When a user denies authorization on Xing, they are presented with a
  // link to return to the application in the following format:
  //
  //     http://www.example.com/auth/xing/callback?oauth_problem=user_refused
  //
  // Following the link back to the application is interpreted as an
  // authentication failure.
  if (req.query && req.query.oauth_problem) {
    return this.fail();
  }

  // Call the base class for standard OAuth authentication.
  OAuthStrategy.prototype.authenticate.call(this, req);
}

/**
 * Retrieve user profile from Xing.
 *
 * This function constructs a normalized profile, with the following properties:
 *
 *   - `id`
 *   - `displayName`
 *   - `name.familyName`
 *   - `name.givenName`
 *
 * @param {String} token
 * @param {String} tokenSecret
 * @param {Object} params
 * @param {Function} done
 * @api protected
 */
Strategy.prototype.userProfile = function(token, tokenSecret, params, done) {
  var url = 'https://api.xing.com/v1/users/me.json?fields=id,first_name,last_name,display_name,active_email,page_name,permalink,gender,photo_urls,birth_date';
  if (this._profileFields) {
    var fields = this._convertProfileFields(this._profileFields);
    url = 'https://api.xing.com/v1/users/me.json?fields=' + fields;
  }
  this._oauth.get(url, token, tokenSecret, function (err, body, res) {
    if (err) { return done(new InternalOAuthError('failed to fetch user profile', err)); }

    try {
      var json = JSON.parse(body);
      var profile = { provider: 'xing' };
      // Xing returns an array of user, currently only the first is used
      var user = json.users[0];

      profile.id = user.id;
      profile.displayName = user.display_name;
      profile.name = { familyName: user.last_name,
                       givenName: user.first_name };

      // The following fields are optional and only populated if they are provided by Xing
      if (user.page_name) { profile.username = user.page_name };
      if (user.permalink) { profile.profileUrl = user.permalink };
      if (user.gender) { profile.gender = user.gender }
      if (user.birth_date && user.birth_date.year && user.birth_date.month && user.birth_date.day) {
          profile.birthday = new Date(user.birth_date.year+"-"+(user.birth_date.month < 10 ? "0"+user.birth_date.month : user.birth_date.month)+"-"+(user.birth_date.day < 10 ? "0"+user.birth_date.day : user.birth_date.day)+"T00:00:00");
      }

      profile.emails = [];
      if (user.active_email) { profile.emails.push({type: "home", value: user.active_email, primary: true}); };
      if (user.private_address) { profile.emails.push({type: "home", value: user.private_address.email}); };
      if (user.business_address) { profile.emails.push({type: "work", value: user.business_address.email}); };
      if (profile.emails.length === 0) { delete profile.emails };

      if (user.photo_urls) {
        profile.photos = [];
        Object.keys(user.photo_urls).forEach(function(key) {
          profile.photos.push({value: user.photo_urls[key],
                               type: key});
        });
      }

      profile._raw = body;
      profile._json = user;

      done(null, profile);
    } catch(e) {
      done(e);
    }
  });
}

Strategy.prototype._convertProfileFields = function(profileFields) {
  var map = {
    'id':          'id',
    'displayName': 'display_name',
    'name':       ['first_name', 'last_name'],
    'emails':      'active_email',
    'photos':      'photo_urls',
    'profileUrl':  'permalink',
    'gender':      'gender',
    'username':    'page_name',
    'birthday':    'birth_date'
  };

  var fields = ['id', 'first_name', 'last_name', 'display_name'];

  profileFields.forEach(function(f) {
    // return raw Xing profile field to support the many fields that don't
    // map cleanly to Portable Contacts
    if (typeof map[f] === 'undefined') { return fields.push(f); };

    if (Array.isArray(map[f])) {
      Array.prototype.push.apply(fields, map[f]);
    } else {
      fields.push(map[f]);
    }
  });

  // Make sure the fields are unique
  var unique = [];
  for (var i = 0; i < fields.length; i++) {
    if (unique.indexOf(fields[i]) == -1) {
      unique.push(fields[i]);
    }
  }

  return unique.join(',');
}

/**
 * Expose `Strategy`.
 */
module.exports = Strategy;
<commit_msg>Change to UTC<commit_after>/**
 * Module dependencies.
 */
var util = require('util')
  , OAuthStrategy = require('passport-oauth').OAuthStrategy
  , InternalOAuthError = require('passport-oauth').InternalOAuthError;

/**
 * `Strategy` constructor.
 *
 * The Xing authentication strategy authenticates requests by delegating to
 * Xing using the OAuth protocol.
 *
 * Applications must supply a `verify` callback which accepts a `token`,
 * `tokenSecret` and service-specific `profile`, and then calls the `done`
 * callback supplying a `user`, which should be set to `false` if the
 * credentials are not valid.  If an exception occured, `err` should be set.
 *
 * Options:
 *   - `consumerKey`     identifies client to Xing
 *   - `consumerSecret`  secret used to establish ownership of the consumer key
 *   - `callbackURL`     URL to which Xing will redirect the user after obtaining authorization
 *
 * Examples:
 *
 *     passport.use(new XingStrategy({
 *         consumerKey: '123-456-789',
 *         consumerSecret: 'shhh-its-a-secret'
 *         callbackURL: 'https://www.example.net/auth/xing/callback'
 *       },
 *       function(token, tokenSecret, profile, done) {
 *         User.findOrCreate(..., function (err, user) {
 *           done(err, user);
 *         });
 *       }
 *     ));
 *
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function Strategy(options, verify) {
  options = options || {};
  options.requestTokenURL = options.requestTokenURL || 'https://api.xing.com/v1/request_token';
  options.accessTokenURL = options.accessTokenURL || 'https://api.xing.com/v1/access_token';
  options.userAuthorizationURL = options.userAuthorizationURL || 'https://api.xing.com/v1/authorize';
  options.sessionKey = options.sessionKey || 'oauth:xing';

  OAuthStrategy.call(this, options, verify);
  this.name = 'xing';
  this._profileFields = options.profileFields || null;
}

/**
 * Inherit from `OAuthStrategy`.
 */
util.inherits(Strategy, OAuthStrategy);

/**
 * Authenticate request by delegating to Xing using OAuth.
 *
 * @param {Object} req
 * @api protected
 */
Strategy.prototype.authenticate = function(req) {
  // When a user denies authorization on Xing, they are presented with a
  // link to return to the application in the following format:
  //
  //     http://www.example.com/auth/xing/callback?oauth_problem=user_refused
  //
  // Following the link back to the application is interpreted as an
  // authentication failure.
  if (req.query && req.query.oauth_problem) {
    return this.fail();
  }

  // Call the base class for standard OAuth authentication.
  OAuthStrategy.prototype.authenticate.call(this, req);
}

/**
 * Retrieve user profile from Xing.
 *
 * This function constructs a normalized profile, with the following properties:
 *
 *   - `id`
 *   - `displayName`
 *   - `name.familyName`
 *   - `name.givenName`
 *
 * @param {String} token
 * @param {String} tokenSecret
 * @param {Object} params
 * @param {Function} done
 * @api protected
 */
Strategy.prototype.userProfile = function(token, tokenSecret, params, done) {
  var url = 'https://api.xing.com/v1/users/me.json?fields=id,first_name,last_name,display_name,active_email,page_name,permalink,gender,photo_urls,birth_date';
  if (this._profileFields) {
    var fields = this._convertProfileFields(this._profileFields);
    url = 'https://api.xing.com/v1/users/me.json?fields=' + fields;
  }
  this._oauth.get(url, token, tokenSecret, function (err, body, res) {
    if (err) { return done(new InternalOAuthError('failed to fetch user profile', err)); }

    try {
      var json = JSON.parse(body);
      var profile = { provider: 'xing' };
      // Xing returns an array of user, currently only the first is used
      var user = json.users[0];

      profile.id = user.id;
      profile.displayName = user.display_name;
      profile.name = { familyName: user.last_name,
                       givenName: user.first_name };

      // The following fields are optional and only populated if they are provided by Xing
      if (user.page_name) { profile.username = user.page_name };
      if (user.permalink) { profile.profileUrl = user.permalink };
      if (user.gender) { profile.gender = user.gender }
      if (user.birth_date && user.birth_date.year && user.birth_date.month && user.birth_date.day) {
          profile.birthday = new Date(Date.UTC(user.birth_date.year, (user.birth_date.month-1), user.birth_date.day));
      }

      profile.emails = [];
      if (user.active_email) { profile.emails.push({type: "home", value: user.active_email, primary: true}); };
      if (user.private_address) { profile.emails.push({type: "home", value: user.private_address.email}); };
      if (user.business_address) { profile.emails.push({type: "work", value: user.business_address.email}); };
      if (profile.emails.length === 0) { delete profile.emails };

      if (user.photo_urls) {
        profile.photos = [];
        Object.keys(user.photo_urls).forEach(function(key) {
          profile.photos.push({value: user.photo_urls[key],
                               type: key});
        });
      }

      profile._raw = body;
      profile._json = user;

      done(null, profile);
    } catch(e) {
      done(e);
    }
  });
}

Strategy.prototype._convertProfileFields = function(profileFields) {
  var map = {
    'id':          'id',
    'displayName': 'display_name',
    'name':       ['first_name', 'last_name'],
    'emails':      'active_email',
    'photos':      'photo_urls',
    'profileUrl':  'permalink',
    'gender':      'gender',
    'username':    'page_name',
    'birthday':    'birth_date'
  };

  var fields = ['id', 'first_name', 'last_name', 'display_name'];

  profileFields.forEach(function(f) {
    // return raw Xing profile field to support the many fields that don't
    // map cleanly to Portable Contacts
    if (typeof map[f] === 'undefined') { return fields.push(f); };

    if (Array.isArray(map[f])) {
      Array.prototype.push.apply(fields, map[f]);
    } else {
      fields.push(map[f]);
    }
  });

  // Make sure the fields are unique
  var unique = [];
  for (var i = 0; i < fields.length; i++) {
    if (unique.indexOf(fields[i]) == -1) {
      unique.push(fields[i]);
    }
  }

  return unique.join(',');
}

/**
 * Expose `Strategy`.
 */
module.exports = Strategy;
<|endoftext|>