<commit_before>// The MIT License (MIT)

// Copyright (c) 2013 Matt DuVall Original: https://github.com/mduvall/grande.js/
// Copyright (c) 2014 @kosjoli    Fork: https://github.com/knutole/grande.js/

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
//
//
// _______grande.js____________________________________________________________________________
//
// This is a small Javascript library that implements features from Medium's editing experience.
// Dependencies: grande.class.js
//
//
G.Rande = G.Class.extend({

	EDGE : -999,

	editNode : document.querySelectorAll(".g-body article")[0], // TODO: cross el support for imageUpload

	isFirefox : navigator.userAgent.toLowerCase().indexOf('firefox') > -1,

	options : {
		animate: true,
		imageUpload : true,
		events : {
			// fired on changes to text. should be overridden by user, like G.rande.events.change = fn();
			change : function (e) {
				console.log('change options.event!', e);
			}
		}

	},

	tagClassMap : {
		"b": "bold",
		"i": "italic",
		"h1": "header1",
		"h2": "header2",
		"a": "url",
		"blockquote": "quote"
	},

	events : {
		// fired on changes to text. should be overridden by user, like G.rande.events.change = fn();
		change : function (e) {
			console.log('change event!', e);
		}
	},

	initialize : function (options, nodes) {

		// cheatcode
		G.r = this;

		// set options
		G.setOptions(this, options);

		// create toolbar
		this.initToolbarLayout();

		// init plugins
		this.initPlugins();

		// bind nodes
		if (nodes) this.bind(nodes);

		return this;
	},

	bind : function(nodes) {

		// get nodes
		this.editableNodes = G.Util.castArray(nodes) || document.querySelectorAll(".g-body article");

		// add event listeners
		this.addHooks();
	},

	unbind : function () {

		// remove event listeners
		this.removeHooks();

		// fire remove on plugins
		this.removePlugins();
	},

	addToolbarButton : function (button) {
		// append next to last in buttonsContainer
		this.buttonsContainer.insertBefore(button, this.buttonsContainer.lastChild);
	},

	initPlugins : function (fn, context) {

		// get plugins from options
		this.plugins = this.options.plugins;

		// plug in plugins
		for (p in this.plugins) {
			var plugin = this.plugins[p];
			plugin.plugin(this);
		}

	},

	select: function() {
		this.triggerTextSelection();
	},

	addToOptions : function (div) {
		this.optionsNode.appendChild(div);
	},

	addHooks : function () {
		this._setHooks(true);
	},

	removeHooks : function () {
		this._setHooks(false);
	},

	_setHooks : function (on) {
		on = (on) ? 'addEventListener' : 'removeEventListener';

		// bind interaction to document
		document[on]('mousedown', this.triggerTextSelection, false);
		document[on]('keydown', this.preprocessKeyDown, false);
		document[on]('keyup', this.handleKeyUp, false);

		// bind resize to window
		window[on]('resize', this.triggerTextSelection, false);

		// bind blur to urlInput
		this.urlInput[on]('blur', this.triggerUrlBlur, false);
		this.urlInput[on]('keydown', this.triggerUrlSet, false);

		// bind image upload
		if (this.options.allowImages) {
			this.imageTooltip[on]('mousedown', this.triggerImageUpload, false);
			this.imageInput[on]('change', this.uploadImage, false);
			document[on]('mousemove', this.triggerOverlayStyling, false);
		}

		// bind nodes
		for (var i = 0, len = this.editableNodes.length; i < len; i++) {
			var node = this.editableNodes[i];
			node.contentEditable = true;
			node[on]('mousedown', this.triggerTextSelection, false);
			node[on]('mouseup', this.triggerTextSelection, false);
			node[on]('keyup', this.triggerTextSelection, false);
		}

		// bind text styling events, ie. toolbar button clicks
		var that = this;
		this.iterateTextMenuButtons(function(node) {
			node[on]('mousedown', function(event) {
				that.triggerTextStyling(node);
			}, false);
		});
	},

	initToolbarLayout : function () {

		// create toolbar container
		this.toolbarContainer = document.createElement("div");
		this.toolbarContainer.className = "g-body";
		document.body.appendChild(this.toolbarContainer);

		// create image tooltip
		this.imageTooltipTemplate = document.createElement("div");
		this.imageTooltipTemplate.innerHTML = "
Insert image
 \																				<input class='file-hidden pos-abs' type='file' id='files' name='files[]' accept='image/*' multiple/>";
		this.imageTooltipTemplate.className = "image-tooltip hide";

		// create toolbar template
		this.toolbarTemplate = "
 \
			 \
				 \
					<button class='bold'>B</button> \
					<button class='italic'>i</button> \
					<button class='header1'>h1</button> \
					<button class='header2'>h2</button> \
					<button class='quote'>”</button> \
					<button class='url useicons'></button> \
					<input class='url-input' type='text' placeholder='Paste or type a link'/> \
				 \
			 \

";

		// create toolbar wrapper
		var div = document.createElement("div");
		div.className = "text-menu hide";
		div.innerHTML = this.toolbarTemplate;

		// append to container
		if (document.querySelectorAll(".text-menu").length === 0) {
			this.toolbarContainer.appendChild(div);
			this.toolbarContainer.appendChild(this.imageTooltipTemplate);
		}

		// get elems
		this.imageInput 	= document.querySelectorAll(".file-label + input")[0];
		this.imageTooltip 	= document.querySelectorAll(".image-tooltip")[0];
		this.textMenu 		= document.querySelectorAll(".text-menu")[0];
		this.optionsNode 	= document.querySelectorAll(".text-menu .options")[0];
		this.urlInput 		= document.querySelectorAll(".text-menu .url-input")[0];
		this.uiInputs 		= document.querySelectorAll(".ui-inputs")[0];
		this.buttons 		= this.uiInputs.childNodes;
		this.buttonsContainer   = this.uiInputs;

	},

	handleKeyUp : function (event) {
		var that = G.r;
		var sel = window.getSelection();

		// FF will return sel.anchorNode to be the parentNode when the triggered keyCode is 13
		if (sel.anchorNode && sel.anchorNode.nodeName !== "ARTICLE") {
			that.triggerNodeAnalysis(event);
			if (sel.isCollapsed) {
				that.triggerTextParse(event);
			}
		}
	},

	triggerOverlayStyling : function (event) {
		this.toggleImageTooltip(event, event.target);
	},

	triggerImageUpload : function (event) {
		// Cache the bound that was originally clicked on before the image upload
		var childrenNodes = editNode.children
		var editBounds = editNode.getBoundingClientRect();
		this.imageBound = this.getHorizontalBounds(childrenNodes, editBounds, event);
	},

	triggerNodeAnalysis : function (event) {
		var sel = window.getSelection(),
		    anchorNode,
		    parentParagraph;

		if (event.keyCode === 13) {

			// Enters should replace it's parent
 with a

			if (sel.anchorNode.nodeName === "DIV") {
				this.toggleFormatBlock("p");
			}

			parentParagraph = this.getParentWithTag(sel.anchorNode, "p");

			if (parentParagraph) {
				this.insertHorizontalRule(parentParagraph);
			}
		}
	},

	triggerTextParse : function (event) {
		var sel = window.getSelection(),
		    textProp,
		    subject,
		    insertedNode,
		    unwrap,
		    node,
		    parent,
		    range;

		// FF will return sel.anchorNode to be the parentNode when the triggered keyCode is 13
		if (!sel.isCollapsed || !sel.anchorNode || sel.anchorNode.nodeName === "ARTICLE") {
			return;
		}

		textProp = this.getTextProp(sel.anchorNode);
		subject = sel.anchorNode[textProp];

		if (subject.match(/^[-*]\s/) && sel.anchorNode.parentNode.nodeName !== "LI") {
			insertedNode = insertListOnSelection(sel, textProp, "ul");
		}

		if (subject.match(/^1\.\s/) && sel.anchorNode.parentNode.nodeName !== "LI") {
			insertedNode = insertListOnSelection(sel, textProp, "ol");
		}

		unwrap = insertedNode &&
			 ["ul", "ol"].indexOf(insertedNode.nodeName.toLocaleLowerCase()) >= 0 &&
			 ["p", "div"].indexOf(insertedNode.parentNode.nodeName.toLocaleLowerCase()) >= 0;

		if (unwrap) {
			node = sel.anchorNode;
			parent = insertedNode.parentNode;
			parent.parentNode.insertBefore(insertedNode, parent);
			parent.parentNode.removeChild(parent);
			this.moveCursorToBeginningOfSelection(sel, node);
		}
	},

	triggerTextStyling : function (node) {

		var className = node.className,
		    sel = window.getSelection(),
		    selNode = sel.anchorNode,
		    tagClass,
		    reTag;

		for (var tag in this.tagClassMap) {
			tagClass = this.tagClassMap[tag];
			reTag = new RegExp(tagClass);

			if (reTag.test(className)) {

				switch(tag) {

					case "b": return document.execCommand(tagClass, false);
					case "i": return document.execCommand(tagClass, false);
					case "h1":
					case "h2":
					case "h3":
					case "blockquote": return this.toggleFormatBlock(tag);
					case "a":
						this.toggleUrlInput();
						this.optionsNode.className = "options url-mode";
						return;

				}
			}
		}
	},

	triggerUrlBlur : function (event) {

		// set global scope, as 'this' is event context here
		var that = G.r;

		// get url
		var url = that.urlInput.value;

		// clear url-mode
		that.optionsNode.className = "options";

		// return if no url
		if (url === "") return that.removeLink();

		// add http to links
		if (!url.match("^(http://|https://|mailto:)")) url = "http://" + url;

		// create link
		that.createLink(url)

		// clear input
		that.urlInput.value = "";
	},

	triggerUrlSet : function (event) {
		var that = G.r;
		if (event.keyCode === 13) {
			event.preventDefault();
			event.stopPropagation();
			that.urlInput.blur();
		}
	},

	// listen for text selection on every mousedown
	triggerTextSelection : function (e, f) {
		var that = G.r;
		var selectedText = window.getSelection(),
		    target = e.target || e.srcElement;

		// if target is one of buttons, reload menu state
		var buttons = that.buttons;
		for (var n = 0; n < buttons.length; n++) {
			if (buttons[n] == target) return that.reloadMenuState();
		}

		// if target is buttons wrapper, reload menu state
		if (target == that.optionsNode) return that.reloadMenuState();

		// if target is anything not editable, hide buttons
		if (!target.isContentEditable) {

			that.hideToolbar();
			that.textMenu.className = "text-menu hide";
			that.reloadMenuState();

			// fire change event
			return that.options.events.change();

		}

		// if selected text is collapsed, hide buttons
		if (selectedText.isCollapsed) {

			that.hideToolbar();
			that.textMenu.className = "text-menu hide";
			that.reloadMenuState();
			return;
		}

		// get selected text and move menu
		that.showToolbar(selectedText);

		// refresh buttons
		that.reloadMenuState();

		// fire change event
		return that.options.events.change();
	},

	showToolbar : function (selectedText) {
		var range = selectedText.getRangeAt(0);
		var clientRectBounds = range.getBoundingClientRect();
		this.setTextMenuPosition(
			clientRectBounds.top - 45 + window.pageYOffset,
			(clientRectBounds.left + clientRectBounds.right) / 2
		);

		// bool
		this.toolbarOpen = true;
	},

	hideToolbar : function () {

		// bool
		if (!this.toolbarOpen) return;
		this.toolbarOpen = false;

		// hide toolbar
		this.setTextMenuPosition(this.EDGE, this.EDGE);

		// fire hide event to plugins
		this._fireHiddenToolbar();

	},

	_fireHiddenToolbar : function () {

		// get plugins from options
		var plugins = this.plugins;

		// fire event on plugins
		for (p in plugins) {
			var plugin = plugins[p];
			plugin.onToolbarHide();
		}

	},

	createLink : function (url) {

		// clear existing
		this.removeLink();

		// create link
		document.execCommand("createLink", false, url);
	},

	removeLink : function () {

		// get previosly selected text
		var prev = this.previouslySelectedText;
		if (!prev) return;

		// get selection
		window.getSelection().addRange(prev);

		// clear prev link
		document.execCommand("unlink", false);
	},

	getHorizontalBounds : function (nodes, target, event) {
		var bounds = [],
		    bound,
		    i,
		    len,
		    preNode,
		    postNode,
		    bottomBound,
		    topBound,
		    coordY;

		// Compute top and bottom bounds for each child element
		for (i = 0, len = nodes.length - 1; i < len; i++) {
			preNode = nodes[i];
			postNode = nodes[i+1] || null;

			bottomBound = preNode.getBoundingClientRect().bottom - 5;
			topBound = postNode.getBoundingClientRect().top;

			bounds.push({
				top: topBound,
				bottom: bottomBound,
				topElement: preNode,
				bottomElement: postNode,
				index: i+1
			});
		}

		coordY = event.pageY - root.scrollY;

		// Find if there is a range to insert the image tooltip between two elements
		for (i = 0, len = bounds.length; i < len; i++) {
			bound = bounds[i];
			if (coordY < bound.top && coordY > bound.bottom) {
				return bound;
			}
		}

		return null;
	},

	getTextProp : function (el) {
		var textProp;

		if (el.nodeType === Node.TEXT_NODE) {
			textProp = "data";
		} else if (this.isFirefox) {
			textProp = "textContent";
		} else {
			textProp = "innerText";
		}

		return textProp;
	},

	getFocusNode : function () {
		return window.getSelection().focusNode;
	},

	getParent : function (node, condition, returnCallback) {
		if (node === null) {
			return;
		}

		while (node.parentNode) {
			if (condition(node)) {
				return returnCallback(node);
			}

			node = node.parentNode;
		}
	},

	getParentWithTag : function (node, nodeType) {
		var checkNodeType = function(node) { return node.nodeName.toLowerCase() === nodeType; }
		var returnNode = function(node) { return node; };
		return this.getParent(node, checkNodeType, returnNode);
	},

	getParentHref : function (node) {
		var checkHref = function(node) { return typeof node.href !== "undefined"; };
		var returnHref = function(node) { return node.href; };
		return this.getParent(node, checkHref, returnHref);
	},

	hasParentWithTag : function (node, nodeType) {
		return !!this.getParentWithTag(node, nodeType);
	},

	toggleFormatBlock : function (tag) {

		if (this.hasParentWithTag(this.getFocusNode(), tag)) {
			document.execCommand("formatBlock", false, "p");
			document.execCommand("outdent");
		} else {
			document.execCommand("formatBlock", false, tag);
		}
	},

	toggleUrlInput : function () {
		var that = this;
		setTimeout(function() {
			var url = that.getParentHref(that.getFocusNode());

			if (typeof url !== "undefined") {
				that.urlInput.value = url;
			}

			that.previouslySelectedText = window.getSelection().getRangeAt(0);
			that.urlInput.focus();
		}, 150);
	},

	toggleImageTooltip : function (event, element) {
		var childrenNodes = editNode.children;
		var editBounds = editNode.getBoundingClientRect();
		var bound = getHorizontalBounds(childrenNodes, editBounds, event);

		if (bound) {
			this.imageTooltip.style.left = (editBounds.left - 90 ) + "px";
			this.imageTooltip.style.top = (bound.top - 17) + "px";
		} else {
			this.imageTooltip.style.left = EDGE + "px";
			this.imageTooltip.style.top = EDGE + "px";
		}
	},

	setTextMenuPosition : function (top, left) {

		this.textMenu.style.top = top + "px";
		this.textMenu.style.left = left + "px";

		if (this.options.animate) {
			if (top === this.EDGE) {
				this.textMenu.className = "text-menu hide";
			} else {
				this.textMenu.className = "text-menu active";
			}
		}
	},

	insertHorizontalRule : function (parentParagraph) {
		var prevSibling,
		    prevPrevSibling,
		    hr;

		prevSibling = parentParagraph.previousSibling;
		prevPrevSibling = prevSibling;

		while (prevPrevSibling) {
			if (prevPrevSibling.nodeType != Node.TEXT_NODE) {
				break;
			}

			prevPrevSibling = prevPrevSibling.previousSibling;
		}

		if (!prevSibling || !prevPrevSibling) return;
		if (prevSibling.nodeName === "P" && !prevSibling.textContent.length && prevPrevSibling.nodeName !== "HR") {

			hr = document.createElement("hr");
			hr.contentEditable = false;
			parentParagraph.parentNode.replaceChild(hr, prevSibling);
		}
	},

	insertListOnSelection : function (sel, textProp, listType) {
		var execListCommand = listType === "ol" ? "insertOrderedList" : "insertUnorderedList",
		    nodeOffset = listType === "ol" ? 3 : 2;

		document.execCommand(this[execListCommand]);
		sel.anchorNode[textProp] = sel.anchorNode[textProp].substring(nodeOffset);

		return this.getParentWithTag(sel.anchorNode, listType);
	},

	insertImage : function (url) {

		var image = document.createElement('img');
		image.src = url;
		image.style.width = '200px';
		image.style.height = 'auto';

		var range = window.getSelection().getRangeAt(0);
		range.collapse(true);
		range.insertNode(image);

	},

	reloadMenuState : function () {

		var className,
		    focusNode = this.getFocusNode(),
		    tagClass,
		    reTag,
		    that = this;

		this.iterateTextMenuButtons(function(node) {
			className = node.className;

			for (var tag in that.tagClassMap) {
				tagClass = that.tagClassMap[tag];
				reTag = new RegExp(tagClass);

				if (reTag.test(className)) {
					// console.log('if has parent etc: focusNode, tag', focusNode, tag);
					if (that.hasParentWithTag(focusNode, tag)) {
						node.className = tagClass + " active";
					} else {
						node.className = tagClass;
					}

					break;
				}
			}
		});

	},

	preprocessKeyDown : function (event) {

		var that = G.r;
		var sel = window.getSelection(),
		    parentParagraph = that.getParentWithTag(sel.anchorNode, "p"),
		    p,
		    isHr;

		if (event.keyCode === 13 && parentParagraph) {
			prevSibling = parentParagraph.previousSibling;
			isHr = prevSibling && prevSibling.nodeName === "HR" &&
				!parentParagraph.textContent.length;

			// Stop enters from creating another
 after a
 on enter
			if (isHr) event.preventDefault();
		}
	},

	iterateTextMenuButtons : function (callback) {
		var textMenuButtons = document.querySelectorAll(".text-menu button"),
		    i,
		    len,
		    node,
		    fnCallback = function(n) {
		    	callback(n);
		    };

		for (i = 0, len = textMenuButtons.length; i < len; i++) {
			node = textMenuButtons[i];
			fnCallback(node);
		}
	},

	moveCursorToBeginningOfSelection : function (selection, node) {
		range = document.createRange();
		range.setStart(node, 0);
		range.setEnd(node, 0);
		selection.removeAllRanges();
		selection.addRange(range);
	},

	uploadImage : function (event) {
		// Only allow uploading of 1 image for now, this is the first file
		var file = this.files[0],
				reader = new FileReader(),
				figEl;

		reader.onload = (function(f) {
			return function(e) {
				figEl = document.createElement("figure");
				figEl.innerHTML = "";
				editNode.insertBefore(figEl, imageBound.bottomElement);
			};
		}(file));

		reader.readAsDataURL(file);
	},

});

// grande shorthand
G.rande = function (nodes, options) {
	return new G.Rande(options, nodes);
};<commit_msg>Delete grande.dev.js<commit_after><|endoftext|>


<commit_before>"use strict";

var socketIo = require("socket.io").listen(8080);
var pg = require("pg");

var connectionString = process.env.DATABASE_URL || "postgres://localhost/hikeio";

var client = new pg.Client(connectionString);
client.connect();

socketIo.set("log level", 2);

// Heroku requires long polling https://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku
socketIo.set("transports", ["xhr-polling"]);
socketIo.set("polling duration", 10);

socketIo.sockets.on("connection", function (socket) {
	socket.on("get-hikes-in-bounds", function (data) {

		// Longitude is tricky because it can jump from 179 to -179 across the international date line
		var longitudeWhereClause;
		if (data.sw.longitude < data.ne.longitude) {
			longitudeWhereClause = "(locations.longitude >= $3 AND locations.longitude <= $4)";
		} else {
			longitudeWhereClause = "(locations.longitude >= $3 OR locations.longitude <= $4)";
		}

		var queryString =  "SELECT hikes.string_id, hikes.name, locations.latitude, locations.longitude \
							FROM hikes, locations \
							WHERE locations.latitude >= $1 AND \
								locations.latitude <= $2 AND " + longitudeWhereClause + " AND \
								hikes.location_id = locations.id \
							ORDER BY locations.latitude, locations.longitude;";
		client.query(queryString, [data.sw.latitude, data.ne.latitude, data.sw.longitude, data.ne.longitude], function(err, result) {
			if (!result) {
				console.log(err);
				return;
			}
			socket.emit("get-hikes-in-bounds", result.rows);
		});
	});
});<commit_msg>Retrieve port from environment if it is set.<commit_after>"use strict";

var port = process.env.PORT || 8080;
var socketIo = require("socket.io").listen(port);
var pg = require("pg");

var connectionString = process.env.DATABASE_URL || "postgres://localhost/hikeio";

var client = new pg.Client(connectionString);
client.connect();

socketIo.set("log level", 2);

// Heroku requires long polling https://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku
socketIo.set("transports", ["xhr-polling"]);
socketIo.set("polling duration", 10);

socketIo.sockets.on("connection", function (socket) {
	socket.on("get-hikes-in-bounds", function (data) {

		// Longitude is tricky because it can jump from 179 to -179 across the international date line
		var longitudeWhereClause;
		if (data.sw.longitude < data.ne.longitude) {
			longitudeWhereClause = "(locations.longitude >= $3 AND locations.longitude <= $4)";
		} else {
			longitudeWhereClause = "(locations.longitude >= $3 OR locations.longitude <= $4)";
		}

		var queryString =  "SELECT hikes.string_id, hikes.name, locations.latitude, locations.longitude \
							FROM hikes, locations \
							WHERE locations.latitude >= $1 AND \
								locations.latitude <= $2 AND " + longitudeWhereClause + " AND \
								hikes.location_id = locations.id \
							ORDER BY locations.latitude, locations.longitude;";
		client.query(queryString, [data.sw.latitude, data.ne.latitude, data.sw.longitude, data.ne.longitude], function(err, result) {
			if (!result) {
				console.log(err);
				return;
			}
			socket.emit("get-hikes-in-bounds", result.rows);
		});
	});
});<|endoftext|>


<commit_before>var uniq = require('uniq');
console.log(uniq([1, 1, 2]));
<commit_msg>js: split into multiple lines to be able to demo the debugger<commit_after>var uniq = require('uniq');
var a = [ 1, 1, 2 ];
a = uniq(a);
console.log(a);
<|endoftext|>


<commit_before>var count = 0;
var interval_id = null;

var schedule = null;
var schedule_index = null;

$(document).ready(function() {
	$('#start').click(start);
	$('#stop').click({'now': true}, stop);
	$('#settings-fields > input[type="text"]').blur(clean_input);

	$('#settings-fields').tooltip({
      selector: "a[rel=tooltip]"
    })
});

function start() {
	toggle_buttons();
	build_schedule();

	count = schedule[0].seconds;
	$('#section-title').html(schedule[0].title);
	$('#countdown').html(count);
	interval_id = setInterval(tick, 1000);
}

function stop(now) {
	clearInterval(interval_id);

	$('#countdown-area').removeClass();
	$('#section-title').html('Done');
	$('#countdown').html(0);
	toggle_buttons();
}

function toggle_buttons() {
	$('#start').toggle();
	$('#stop').toggle();
}

function build_schedule() {
	delay = $('#delay').val();
	warm_up = $('#warm_up').val();
	high = $('#high').val();
	normal = $('#normal').val();
	reps = $('#reps').val();
	cool_down = $('#cool_down').val();

	schedule = [];
	if (delay > 0) {
	    schedule.push({'title': 'Get ready', 'class': 'delay', 'seconds': delay});
	}
	if (warm_up > 0) {
		schedule.push({'title': 'Warm up', 'class': 'warmup', 'seconds': warm_up});
	}
	for (reps = reps; reps > 0; reps--) {
		if (high > 0) {
			schedule.push({'title': 'High intensity', 'class': 'high', 'seconds': high});
		}
		if (normal > 0) {
			schedule.push({'title': 'Normal intensity', 'class': 'normal', 'seconds': normal});
		}
	}
	if (cool_down > 0) {
		schedule.push({'title': 'Cool down', 'class': 'cooldown', 'seconds': cool_down});
	}

	schedule_index = 0;
}

function tick() {
	if (--count == 0) {
		schedule_index++;
		$('#countdown-area').removeClass();

		if (schedule_index == schedule.length) {
			stop();
		} else {
			count = schedule[schedule_index].seconds;
			$('#countdown-area').addClass(schedule[schedule_index].class);
			$('#section-title').html(schedule[schedule_index].title);
		}
	}
	$('#countdown').html(count);
}

function clean_input() {
	input = $(this);
	value = input.val();

	value = parseInt(value);
	if (isNaN(value)) {
		value = 0;
	}

	input.val(value);
}
<commit_msg>Tidy up hiit-timer.js code<commit_after>var count = 0;
var interval_id = null;

var schedule = null;
var schedule_index = null;

$(document).ready(function () {
	$('#start').click(start);
	$('#stop').click({'now': true}, stop);

	$('#settings-fields > input[type="text"]').blur(clean_input);
	$('#settings-fields').tooltip({selector: "a[rel=tooltip]"});
});

function start() {
	toggle_buttons();
	build_schedule();

	count = schedule[0].seconds;
	$('#section-title').html(schedule[0].title);
	$('#countdown').html(count);
	interval_id = setInterval(tick, 1000);
}

function stop() {
	clearInterval(interval_id);

	$('#countdown-area').removeClass();
	$('#section-title').html('Done');
	$('#countdown').html(0);
	toggle_buttons();
}

function toggle_buttons() {
	$('#start').toggle();
	$('#stop').toggle();
}

function build_schedule() {
	delay = $('#delay').val();
	warm_up = $('#warm_up').val();
	high = $('#high').val();
	normal = $('#normal').val();
	reps = $('#reps').val();
	cool_down = $('#cool_down').val();

	schedule = [];
	if (delay > 0) {
	    schedule.push(
		    {'title': 'Get ready', 'class': 'delay', 'seconds': delay}
		);
	}
	if (warm_up > 0) {
		schedule.push(
		    {'title': 'Warm up', 'class': 'warmup', 'seconds': warm_up}
		);
	}
	for (reps = reps; reps > 0; reps--) {
		if (high > 0) {
			schedule.push(
			    {'title': 'High intensity', 'class': 'high', 'seconds': high}
			);
		}
		if (normal > 0) {
			schedule.push(
		        {'title': 'Normal intensity', 'class': 'normal', 'seconds': normal}
		    );
		}
	}
	if (cool_down > 0) {
		schedule.push(
		    {'title': 'Cool down', 'class': 'cooldown', 'seconds': cool_down}
		);
	}

	schedule_index = 0;
}

function tick() {
	if (--count == 0) {
		schedule_index++;
		$('#countdown-area').removeClass();

		if (schedule_index == schedule.length) {
			stop();
		} else {
			count = schedule[schedule_index].seconds;
			$('#countdown-area').addClass(schedule[schedule_index].class);
			$('#section-title').html(schedule[schedule_index].title);
		}
	}
	$('#countdown').html(count);
}

function clean_input() {
	input = $(this);
	value = input.val();

	value = parseInt(value);
	if (isNaN(value)) {
		value = 0;
	}

	input.val(value);
}
<|endoftext|>


<commit_before><commit_msg>re error<commit_after><|endoftext|>


<commit_before>'use strict';

function draw_logic(){
    buffer.save();
    buffer.translate(
      x,
      y
    );

    // Draw corridor over background.
    buffer.fillStyle = '#333';
    buffer.fillRect(
      -x,
      -half_corridor_height,
      width,
      settings['corridor-height']
    );

    // Draw player body.
    buffer.fillStyle = settings['color'];
    buffer.fillRect(
      0,
      -player['y'] - 25,
      25,
      50
    );

    // Draw jetpack.
    buffer.fillStyle = '#aaa';
    buffer.fillRect(
      -25,
      -player['y'] - 15,
      25,
      20
    );

    // Draw activated jetpack fire.
    if(game_running
      && key_jetpack){
        buffer.fillStyle = '#f00';
        buffer.fillRect(
          -22,
          -player['y'] + 5,
          18,
          10
        );
    }

    buffer.font = '18pt sans-serif';
    // Draw obstacles.
    for(var obstacle in obstacles){
        buffer.fillStyle = '#555';
        buffer.fillRect(
          obstacles[obstacle]['x'],
          obstacles[obstacle]['y'],
          obstacles[obstacle]['width'] * 2,
          obstacles[obstacle]['height'] * 2
        );
        buffer.fillStyle = '#fff';
        buffer.fillText(
          obstacles[obstacle]['counter'],
          obstacles[obstacle]['x'],
          obstacles[obstacle]['y']
        );
    }

    // Draw smoke trails behind the player.
    buffer.fillStyle = '#777';
    for(var id in smoke){
        buffer.fillRect(
          smoke[id]['x'],
          -smoke[id]['y'],
          10,
          10
        );
    }

    buffer.restore();

    // Setup text display.
    buffer.fillStyle = '#fff';
    buffer.font = '23pt sans-serif';

    // If game is over, display game over messages.
    if(!game_running){
        if(!played_explosion_sound){
            if(settings['audio-volume'] > 0){
                // play_audio('explosion');
            }
            played_explosion_sound = true;
        }

        if(frame_counter > best){
            buffer.fillText(
              'NEW BEST SCORE!',
              5,
              height - 100
            );
        }
        buffer.fillText(
          'You crashed... ☹',
          5,
          height - 70
        );
        buffer.fillText(
          settings['restart-key'] + ' = Restart',
          5,
          height - 40
        );
        buffer.fillText(
          'ESC = Main Menu',
          5,
          height - 10
        );
    }

    // If frame counter is enabled, draw current frame count.
    if(settings['frame-counter']){
        // Top frame counter and best text displays.
        buffer.fillText(
          frame_counter,
          5,
          25
        );
        buffer.fillText(
          best,
          5,
          50
        );
    }
}

function logic(){
    if(!game_running){
        return;
    }

    // Check if player is outside of game boundaries.
    if(player['y'] + 25 > half_corridor_height
      || player['y'] - 25 < -half_corridor_height){
        game_running = false;
        update_best();
        return;
    }

    frame_counter += 1;

    // If new obstacle should be added this frame, add one.
    if(frame_counter % frames_per_obstacle === 0){
        var obstacle_width = Math.floor(Math.random() * 15) + 20;
        obstacles.push({
          'counter': obstacle_counter,
          'height': Math.floor(Math.random() * 15) + 20,
          'width': obstacle_width,
          'x': x + obstacle_width,
          'y': Math.floor(Math.random() * settings['corridor-height'])
            - half_corridor_height,
        });
        obstacle_counter += 1;
    }

    // If obstacle frequency increase should happen this frame, do it.
    if(settings['obstacle-frequency'] > 0
      && frames_per_obstacle > 1
      && frame_counter % settings['obstacle-increase'] === 0){
        // obstacle frequency increase
        frames_per_obstacle -= 1;
    }

    // If the player has activated jetpack, increase y speed and add smoke...
    if(key_jetpack){
        player['speed'] += settings['jetpack-power'];
        smoke.push({
          'x': -20,
          'y': player['y'] - 10,
        });

    // ...else apply gravity.
    }else{
        player['speed'] -= settings['gravity'];
    }

    player['y'] += player['speed'];

    for(var obstacle in obstacles){
        // Delete obstacles that are past left side of screen.
        if(obstacles[obstacle]['x'] < -x - 70){
            obstacles.splice(
              obstacle,
              1
            );
            continue;
        }

        // Move obstacles left at speed.
        obstacles[obstacle]['x'] -= settings['speed'];

        // Check for player collision with obstacle.
        if(obstacles[obstacle]['x'] <= -obstacles[obstacle]['width'] * 2
          || obstacles[obstacle]['x'] >= obstacles[obstacle]['width']
          || obstacles[obstacle]['y'] <= -player['y'] - 25 - obstacles[obstacle]['height'] * 2
          || obstacles[obstacle]['y'] >= -player['y'] + 25){
            continue;
        }

        game_running = false;
        update_best();
    }

    // Delete smoke trails past left side of screen.
    for(var id in smoke){
        smoke[id]['x'] -= settings['speed'];

        if(smoke[id]['x'] < -x){
            smoke.splice(
              id,
              1
            );
        }
    }
}

function reset_best(){
    if(!window.confirm('Reset best?')){
        return;
    }

    best = 0;
    frame_counter = 0;
    update_best();
    setmode(
      0,
      true
    );
}

function setmode_logic(newgame){
    obstacle_counter = 0;
    obstacles = [];
    smoke = [];

    // Main menu mode.
    if(mode === 0){
        document.body.innerHTML = '

Cave Corridor

Best: '
          + best
          + '
Reset Best

Jetpack:

<input disabled value=Click>Activate
<input id=jetpack-key maxlength=1 value='
          + settings['jetpack-key'] + '>Activate
<input disabled value=ESC>Main Menu
<input id=restart-key maxlength=1 value='
          + settings['restart-key'] + '>Restart

<input id=audio-volume max=1 min=0 step=0.01 type=range value='
          + settings['audio-volume'] + '>Audio
<input id=color type=color value='
          + settings['color'] + '>Color
<input id=corridor-height value='
          + settings['corridor-height'] + '>Corridor Height
<input '
          + (settings['frame-counter'] ? 'checked ' : '') + 'id=frame-counter type=checkbox>Frame Counter
<input id=gravity value='
          + settings['gravity'] + '>Gravity
Jetpack:

<input id=jetpack-power value='
          + settings['jetpack-power'] + '>Power
<input id=speed value='
          + settings['speed'] + '>Speed
<input id=ms-per-frame value='
          + settings['ms-per-frame'] + '>ms/Frame
Obstacle:

<input id=obstacle-frequency value='
          + settings['obstacle-frequency'] + '>Frequency
<input id=obstacle-increase value='
          + settings['obstacle-increase'] + '>Increase
Reset Settings

';

    // Play game mode.
    }else{
        if(newgame){
            save();
        }

        frame_counter = 0;
        frames_per_obstacle = settings['obstacle-frequency'];
        game_running = true;
        half_corridor_height = settings['corridor-height'] / 2;
        played_explosion_sound = false;
        player = {
          'speed': 0,
          'y': 0,
        };
    }
}

function update_best(){
    if(!settings['frame-counter']){
        return;
    }

    if(frame_counter > best){
        best = frame_counter;
    }

    if(best > 0){
        window.localStorage.setItem(
          'Jetpack-2D.htm-best',
          best
        );

    }else{
        window.localStorage.removeItem('Jetpack-2D.htm-best');
    }
}

var best = parseInt(
  window.localStorage.getItem('Jetpack-2D.htm-best'),
  10
) || 0;
var frame_counter = 0;
var frames_per_obstacle = 0;
var game_running = false;
var half_corridor_height = 0;
var key_jetpack = false;
var obstacle_counter = 0;
var obstacles = [];
var played_explosion_sound = false;
var player = {};
var smoke = [];

window.onkeydown = function(e){
    if(mode <= 0){
        return;
    }

    var key = e.keyCode || e.which;

    // ESC: update best and return to main menu.
    if(key === 27){
        update_best();
        setmode(
          0,
          true
        );
        return;
    }

    key = String.fromCharCode(key);

    if(key === settings['jetpack-key']){
        key_jetpack = true;

    }else if(key === settings['restart-key']){
        update_best();
        setmode(1);
    }
};

window.onkeyup = function(e){
    var key = String.fromCharCode(e.keyCode || e.which);

    if(key === settings['jetpack-key']){
        key_jetpack = false;
    }
};

window.onload = function(){
    init_settings(
      'Jetpack-2D.htm-',
      {
        'audio-volume': 1,
        'color': '#009900',
        'corridor-height': 500,
        'frame-counter': true,
        'gravity': 1,
        'jetpack-key': 'W',
        'jetpack-power': 2,
        'ms-per-frame': 30,
        'obstacle-frequency': 23,
        'obstacle-increase': 115,
        'restart-key': 'H',
        'speed': 10,
      }
    );
    init_canvas();
};

window.onmousedown
  = window.ontouchstart = function(e){
    if(mode <= 0){
        return;
    }

    e.preventDefault();
    key_jetpack = true;
};

window.onmouseup
  = window.ontouchend = function(e){
    key_jetpack = false;
};
<commit_msg>simplified main menu code<commit_after>'use strict';

function draw_logic(){
    buffer.save();
    buffer.translate(
      x,
      y
    );

    // Draw corridor over background.
    buffer.fillStyle = '#333';
    buffer.fillRect(
      -x,
      -half_corridor_height,
      width,
      settings['corridor-height']
    );

    // Draw player body.
    buffer.fillStyle = settings['color'];
    buffer.fillRect(
      0,
      -player['y'] - 25,
      25,
      50
    );

    // Draw jetpack.
    buffer.fillStyle = '#aaa';
    buffer.fillRect(
      -25,
      -player['y'] - 15,
      25,
      20
    );

    // Draw activated jetpack fire.
    if(game_running
      && key_jetpack){
        buffer.fillStyle = '#f00';
        buffer.fillRect(
          -22,
          -player['y'] + 5,
          18,
          10
        );
    }

    buffer.font = '18pt sans-serif';
    // Draw obstacles.
    for(var obstacle in obstacles){
        buffer.fillStyle = '#555';
        buffer.fillRect(
          obstacles[obstacle]['x'],
          obstacles[obstacle]['y'],
          obstacles[obstacle]['width'] * 2,
          obstacles[obstacle]['height'] * 2
        );
        buffer.fillStyle = '#fff';
        buffer.fillText(
          obstacles[obstacle]['counter'],
          obstacles[obstacle]['x'],
          obstacles[obstacle]['y']
        );
    }

    // Draw smoke trails behind the player.
    buffer.fillStyle = '#777';
    for(var id in smoke){
        buffer.fillRect(
          smoke[id]['x'],
          -smoke[id]['y'],
          10,
          10
        );
    }

    buffer.restore();

    // Setup text display.
    buffer.fillStyle = '#fff';
    buffer.font = '23pt sans-serif';

    // If game is over, display game over messages.
    if(!game_running){
        if(!played_explosion_sound){
            if(settings['audio-volume'] > 0){
                // play_audio('explosion');
            }
            played_explosion_sound = true;
        }

        if(frame_counter > best){
            buffer.fillText(
              'NEW BEST SCORE!',
              5,
              height - 100
            );
        }
        buffer.fillText(
          'You crashed... ☹',
          5,
          height - 70
        );
        buffer.fillText(
          settings['restart-key'] + ' = Restart',
          5,
          height - 40
        );
        buffer.fillText(
          'ESC = Main Menu',
          5,
          height - 10
        );
    }

    // If frame counter is enabled, draw current frame count.
    if(settings['frame-counter']){
        // Top frame counter and best text displays.
        buffer.fillText(
          frame_counter,
          5,
          25
        );
        buffer.fillText(
          best,
          5,
          50
        );
    }
}

function logic(){
    if(!game_running){
        return;
    }

    // Check if player is outside of game boundaries.
    if(player['y'] + 25 > half_corridor_height
      || player['y'] - 25 < -half_corridor_height){
        game_running = false;
        update_best();
        return;
    }

    frame_counter += 1;

    // If new obstacle should be added this frame, add one.
    if(frame_counter % frames_per_obstacle === 0){
        var obstacle_width = Math.floor(Math.random() * 15) + 20;
        obstacles.push({
          'counter': obstacle_counter,
          'height': Math.floor(Math.random() * 15) + 20,
          'width': obstacle_width,
          'x': x + obstacle_width,
          'y': Math.floor(Math.random() * settings['corridor-height'])
            - half_corridor_height,
        });
        obstacle_counter += 1;
    }

    // If obstacle frequency increase should happen this frame, do it.
    if(settings['obstacle-frequency'] > 0
      && frames_per_obstacle > 1
      && frame_counter % settings['obstacle-increase'] === 0){
        // obstacle frequency increase
        frames_per_obstacle -= 1;
    }

    // If the player has activated jetpack, increase y speed and add smoke...
    if(key_jetpack){
        player['speed'] += settings['jetpack-power'];
        smoke.push({
          'x': -20,
          'y': player['y'] - 10,
        });

    // ...else apply gravity.
    }else{
        player['speed'] -= settings['gravity'];
    }

    player['y'] += player['speed'];

    for(var obstacle in obstacles){
        // Delete obstacles that are past left side of screen.
        if(obstacles[obstacle]['x'] < -x - 70){
            obstacles.splice(
              obstacle,
              1
            );
            continue;
        }

        // Move obstacles left at speed.
        obstacles[obstacle]['x'] -= settings['speed'];

        // Check for player collision with obstacle.
        if(obstacles[obstacle]['x'] <= -obstacles[obstacle]['width'] * 2
          || obstacles[obstacle]['x'] >= obstacles[obstacle]['width']
          || obstacles[obstacle]['y'] <= -player['y'] - 25 - obstacles[obstacle]['height'] * 2
          || obstacles[obstacle]['y'] >= -player['y'] + 25){
            continue;
        }

        game_running = false;
        update_best();
    }

    // Delete smoke trails past left side of screen.
    for(var id in smoke){
        smoke[id]['x'] -= settings['speed'];

        if(smoke[id]['x'] < -x){
            smoke.splice(
              id,
              1
            );
        }
    }
}

function reset_best(){
    if(!window.confirm('Reset best?')){
        return;
    }

    best = 0;
    frame_counter = 0;
    update_best();
    setmode(
      0,
      true
    );
}

function setmode_logic(newgame){
    obstacle_counter = 0;
    obstacles = [];
    smoke = [];

    // Main menu mode.
    if(mode === 0){
        document.body.innerHTML = '

Cave Corridor

Best: '
          + best
          + '
Reset Best

'
          + '

Jetpack:

<input disabled value=Click>Activate'
          + '
<input id=jetpack-key maxlength=1>Activate
'
          + '<input disabled value=ESC>Main Menu
'
          + '<input id=restart-key maxlength=1>Restart

'
          + '
<input id=audio-volume max=1 min=0 step=0.01 type=range>Audio
'
          + '<input id=color type=color>Color
'
          + '<input id=corridor-height>Corridor Height
'
          + '<input id=frame-counter type=checkbox>Frame Counter
'
          + '<input id=gravity>Gravity
'
          + 'Jetpack:

<input id=jetpack-power>Power'
          + '
<input id=speed>Speed
'
          + '<input id=ms-per-frame>ms/Frame
'
          + 'Obstacle:

<input id=obstacle-frequency>Frequency'
          + '
<input id=obstacle-increase>Increase
'
          + 'Reset Settings

';
        update_settings();

    // Play game mode.
    }else{
        if(newgame){
            save();
        }

        frame_counter = 0;
        frames_per_obstacle = settings['obstacle-frequency'];
        game_running = true;
        half_corridor_height = settings['corridor-height'] / 2;
        played_explosion_sound = false;
        player = {
          'speed': 0,
          'y': 0,
        };
    }
}

function update_best(){
    if(!settings['frame-counter']){
        return;
    }

    if(frame_counter > best){
        best = frame_counter;
    }

    if(best > 0){
        window.localStorage.setItem(
          'Jetpack-2D.htm-best',
          best
        );

    }else{
        window.localStorage.removeItem('Jetpack-2D.htm-best');
    }
}

var best = parseInt(
  window.localStorage.getItem('Jetpack-2D.htm-best'),
  10
) || 0;
var frame_counter = 0;
var frames_per_obstacle = 0;
var game_running = false;
var half_corridor_height = 0;
var key_jetpack = false;
var obstacle_counter = 0;
var obstacles = [];
var played_explosion_sound = false;
var player = {};
var smoke = [];

window.onkeydown = function(e){
    if(mode <= 0){
        return;
    }

    var key = e.keyCode || e.which;

    // ESC: update best and return to main menu.
    if(key === 27){
        update_best();
        setmode(
          0,
          true
        );
        return;
    }

    key = String.fromCharCode(key);

    if(key === settings['jetpack-key']){
        key_jetpack = true;

    }else if(key === settings['restart-key']){
        update_best();
        setmode(1);
    }
};

window.onkeyup = function(e){
    var key = String.fromCharCode(e.keyCode || e.which);

    if(key === settings['jetpack-key']){
        key_jetpack = false;
    }
};

window.onload = function(){
    init_settings(
      'Jetpack-2D.htm-',
      {
        'audio-volume': 1,
        'color': '#009900',
        'corridor-height': 500,
        'frame-counter': true,
        'gravity': 1,
        'jetpack-key': 'W',
        'jetpack-power': 2,
        'ms-per-frame': 30,
        'obstacle-frequency': 23,
        'obstacle-increase': 115,
        'restart-key': 'H',
        'speed': 10,
      }
    );
    init_canvas();
};

window.onmousedown
  = window.ontouchstart = function(e){
    if(mode <= 0){
        return;
    }

    e.preventDefault();
    key_jetpack = true;
};

window.onmouseup
  = window.ontouchend = function(e){
    key_jetpack = false;
};
<|endoftext|>


<commit_before>/** @jsx React.DOM */

// Bring in jQuery and React as a Bower component in the global namespace
require("script!react/react-with-addons.js")
require("script!jquery/jquery.js")

var PhoneCatWrapper = require("./components/PhoneCatWrapper.js")

React.renderComponent(<PhoneCatWrapper />, document.getElementById('app'))
<commit_msg>added routes<commit_after>/** @jsx React.DOM */

// Bring in jQuery and React as a Bower component in the global namespace
require("script!react/react-with-addons.js")
require("script!jquery/jquery.js")
require('script!react-router/dist/react-router.js')

var Route = ReactRouter.Route;
var Link = ReactRouter.Link;
var PhoneCatWrapper = require("./components/PhoneCatWrapper.js")
var PhoneDetailsWrapper = require("./components/PhoneDetailsWrapper.js")

App = React.createClass({
  render: function(){
    return(

<Link to="phones">Home</Link>

        <this.props.activeRouteHandler/>

    )
  }
})

React.renderComponent(
  (<Route handler={App}>
      <Route name="phones" handler={PhoneCatWrapper}/>
      <Route name="phone" path="/phones/:phoneId" handler={PhoneDetailsWrapper} />
    </Route>), document.getElementById('app'));
<|endoftext|>


<commit_before>var CloudCmd, Util, DOM, CloudFunc, ace, DiffProto, diff_match_patch, Zip, MenuIO;
(function(CloudCmd, Util, DOM, CloudFunc) {
    'use strict';

    CloudCmd.Edit = EditProto;

    function EditProto() {
        var Name        = 'Edit',
            Loading     = false,
            DIR         = CloudCmd.LIBDIRCLIENT + 'edit/',
            LIBDIR      = CloudCmd.LIBDIR,
            Info        = DOM.CurrentInfo,
            Menu,
            Value,
            Edit        = this,
            Diff,
            Emmet,
            Ace,
            Session,
            Modelist,
            Msg,
            Events      = DOM.Events,
            Dialog      = DOM.Dialog,
            Images      = DOM.Images,
            Element, JSHintConfig, EditConfig;

       function init() {
            Loading   = true;
            Util.exec.series([
                CloudCmd.View,
                load,
                Edit.show
            ]);
        }

        this.show                       = function(value) {
            var mode, htmlMode, jsMode, isHTML, isJS, modesByName,
                onMenu,
                isStr       = Util.isString(value),
                name        = Info.name,
                isDir       = Info.isDir,
                focus       = function() {
                    Ace.clearSelection();
                    Ace.moveCursorTo(0, 0);
                    Ace.focus();
                };

            if (!Loading) {
                Images.showLoad();

                if (!Element) {
                    Element         = DOM.load({
                        name        : 'div',
                        style   :
                            'width      : 100%;'    +
                            'height     : 100%;'    +
                            'font       : 16px "Droid Sans Mono";' +
                            'position   : absolute;',
                        notAppend : true
                    });

                    onMenu          = Util.exec.with(setMenu, Element);

                    initAce();

                    Events.addOnce('contextmenu', Element, onMenu)
                        .add(Element, {
                            drop          : onDrop,
                            dragover      : function(event) {
                                event.preventDefault();
                            }
                        });
                }

                modesByName = Modelist.modesByName;

                if (isDir)
                    mode    = modesByName.json.mode;
                else
                    mode    = Modelist.getModeForPath(name).mode;

                htmlMode    = modesByName.html.mode;
                jsMode      = modesByName.javascript.mode;

                isHTML      = mode === htmlMode;
                isJS        = mode === jsMode;

                Session.setMode(mode);
                setUseOfWorker(mode);

                setEmmet(isHTML);

                Util.exec.if(isStr, function() {
                    var UndoManager = ace.require('ace/undomanager').UndoManager;

                    Ace.setValue(Value);
                    CloudCmd.View.show(Element, {
                        beforeClose: function() {
                            isChanged();

                            if (Menu)
                                Menu.hide();
                        },
                        afterShow: focus
                    });

                    Session.setUndoManager(new UndoManager());
                }, function(callback) {
                    Info.getData(function(data) {
                        Value = data;

                        if (isJS && Session.getUseWorker())
                            setJsHintConfig();

                        callback();
                    });
                });
            }
        };

        this.hide                       =  function() {
            CloudCmd.View.hide();
        };

        this.goToLine                   = function() {
            var msg     = 'Enter line number:',
                cursor  = Ace.selection.getCursor(),
                number  = cursor.row + 1,
                line    = Dialog.prompt(msg, number);

            number      = line - 0;

            if (number)
                Ace.gotoLine(number);
        };

        function isChanged() {
            var is,
                value   = Ace.getValue(),
                isEqual = value === Value,
                msg     = 'Do you want to save changes to ' + name + '?';

            if (!isEqual) {
                is = Dialog.confirm(msg);

                if (is)
                    save();
            }
        }

        function setEmmet(isHTML) {
            getEditConfig(function(config) {
                var extensions  = config.extensions,
                    isEmmet     = extensions.emmet;

                if (isEmmet)
                    Util.exec.if(Emmet, function() {
                            if (Emmet)
                                Ace.setOption('enableEmmet', isHTML);
                        }, function(callback) {
                            var url;

                            if (!isHTML)
                                Util.exec(callback);
                            else {
                                url = CloudFunc.getJoinURL([
                                    DIR + 'emmet.js',
                                    DIR + 'ext-emmet.js'
                                ]);

                                DOM.load.js(url, function() {
                                    Emmet = ace.require('ace/ext/emmet');
                                    Emmet.setCore(window.emmet);
                                    Util.exec(callback);
                                });
                            }
                        });
                });
        }

        function setUseOfWorker(mode) {
            var isMatch,
                isStr   = Util.isString(mode),
                regStr  = 'coffee|css|html|javascript|json|lua|php|xquery',
                regExp  = new RegExp(regStr);

            if (isStr)
                isMatch = mode.match(regExp);

            Session.setUseWorker(isMatch);
        }

        function initAce() {
            Ace     = ace.edit(Element);
            Session = Ace.getSession();

            Ace.commands.addCommand({
                name    : 'hide',
                bindKey : { win: 'Esc',  mac: 'Esc' },
                exec    : function () {
                    Edit.hide();
                }
            });

            Ace.commands.addCommand({
                name    : 'goToLine',
                bindKey : { win: 'Ctrl-G',  mac: 'Command-G' },
                exec    : function () {
                    Edit.goToLine();
                }
            });

            Ace.commands.addCommand({
                name    : 'save',
                bindKey : { win: 'Ctrl-S',  mac: 'Command-S' },
                exec    : save
            });

            Ace.commands.addCommand({
                name    : 'saveMC',
                bindKey : { win: 'F2',  mac: 'F2' },
                exec    : save
            });

            ace.require('ace/ext/language_tools');
            Modelist = ace.require('ace/ext/modelist');

            getEditConfig(function(config) {
                var options      = config.options;

                Ace.setOptions(options);
            });
        }

        function save () {
            var path    = Info.path,
                value   = Ace.getValue();

            CloudCmd.getConfig(function(config) {
                var isDiff      = config.diff,
                    isZip       = config.zip;

                Util.exec.if(!isDiff, function(patch) {
                    var query           = '',
                        MAX_SIZE        = CloudFunc.MAX_FILE_SIZE,
                        patchLength     = patch.length,
                        length          = Value.length,
                        isLessMaxLength = length < MAX_SIZE,
                        isLessLength    = isLessMaxLength && patchLength < length,
                        isStr           = Util.isString(patch);

                    Value               = value;

                    if (isStr && patch && isLessLength)
                        query           = '?patch';
                    else
                        patch           = false;

                    Util.exec.if(!isZip || query, function(equal, data) {
                        var result  = data || patch || Value,
                            url     = path + query;

                        DOM.RESTful.write(url, result , onSave);
                    }, function(func) {
                        zip(value, function(error, data) {
                            if (error)
                                Util.log(error);

                            query = '?unzip';
                            func(null, data);
                        });
                    });

                }, Util.exec.with(doDiff, path));
            });
        }

        function doDiff(path, callback) {
            var value = Ace.getValue();

            diff(value, function(patch) {
                var isAllowed = DOM.Storage.isAllowed();

                Util.exec.if(!isAllowed, callback, function(func) {
                        DOM.checkStorageHash(path, function(error, equal) {
                            if (!equal)
                                patch = '';

                            func(patch);
                        });
                });
            });
        }

        function diff(newValue, callback) {
            var libs            = [
                    LIBDIR + 'diff/diff-match-patch.js',
                    LIBDIR + 'diff.js'
                ],
                url             = CloudFunc.getJoinURL(libs);

            DOM.load.js(url, function() {
                var patch,
                    isAllowed   = DOM.Storage.isAllowed();

                if (!Diff)
                    Diff        = new DiffProto(diff_match_patch);

                Util.exec.if(!isAllowed, function() {
                    patch       = Diff.createPatch(Value, newValue);
                    Util.exec(callback, patch);
                }, function(func) {
                    var path = Info.path;

                    DOM.getDataFromStorage(path, function(data) {
                        if (data)
                            Value   = data;

                        func();
                    });
                });
            });
        }

        function zip(value, callback) {
            var dir             = CloudCmd.LIBDIRCLIENT,
                libs            = [
                    dir + 'zip/dist/pako.js',
                    dir + 'zip.js'
                ],
                url             = CloudFunc.getJoinURL(libs);

            DOM.load.js(url, function() {
                Zip.pack(value, callback);
            });
        }

        function setJsHintConfig(callback) {
            var JSHINT_PATH = '/.jshintrc',
                func        = function() {
                    var worker  = Session.$worker;

                    if (worker)
                        worker.send('changeOptions', [JSHintConfig]);

                    Util.exec(callback);
                };

            Util.exec.if(JSHintConfig, func, function() {
                DOM.load.ajax({
                    url     :  JSHINT_PATH,
                    success : function(data) {
                        JSHintConfig = Util.parseJSON(data);
                        func();
                    }
                });
            });
        }

        function getEditConfig(callback) {
            var CONFIG_PATH = '/json/edit.json',
                func        = Util.exec.ret(callback);

            Util.exec.if(EditConfig, function() {
                func(EditConfig);
            }, function() {
                DOM.load.ajax({
                    url     : CONFIG_PATH,
                    success : function(data) {
                        EditConfig = data;
                        func(EditConfig);
                    }
                });
            });
        }

        function setMenu(element) {
            DOM.loadMenu(function() {
                var position    = CloudCmd.MousePosition,
                    options     = {
                        beforeShow: function(params) {
                            params.x -= 18;
                            params.y -= 27;
                        },
                        afterClick: function() {
                            Ace.focus();
                        }
                },
                menuData    = {
                    'Save           Ctrl+S' : save,
                    'Go To Line     Ctrl+G' : function() {
                        Edit.goToLine();
                    },
                    'Select All     Ctrl+A' : function() {
                        Ace.selectAll();
                    },
                    'Delete         Del'    : function() {
                        Ace.remove('right');
                    },
                    'Close          Esc'    : Edit.hide
                };

                Menu        = new MenuIO(element, options, menuData);

                Menu.show(position.x, position.y);
            });
        }

        function load(callback) {
            var files  = [
                    DIR + 'theme-tomorrow_night_blue.js',
                    DIR + 'ext-language_tools.js',
                    DIR + 'ext-searchbox.js',
                    DIR + 'ext-modelist.js'
                ],

                ace     = DIR + 'ace.js',
                url     = CloudFunc.getJoinURL(files);

            Util.time(Name + ' load');

            DOM.load.series([ace, url], function() {
                Util.timeEnd(Name + ' load');
                Loading = false;
                Util.exec(callback);
            });
        }

        function onSave(text) {
            var ret,
                isError = Util.isContainStrAtBegin(text, 'error'),
                path    = Info.path,
                msg     = '\nShould I save file anyway?';

            if (!isError) {
                Edit.showMessage(text);
                DOM.saveDataToStorage(path, Value);
                DOM.setCurrentSize(Value.length);
            } else {
                ret     = Dialog.confirm(text + msg);

                if (ret)
                    DOM.RESTful.write(path, Value, onSave);
            }
        }

         function onDrop(event) {
            var reader, files,
                onLoad   =  function(event) {
                    var data    = event.target.result;

                    Ace.setValue(data);
                };

            event.preventDefault();

            files   = event.dataTransfer.files;

            if (files)
                files.forEach(function(file) {
                    reader  = new FileReader();
                    DOM.Events.addLoad(reader, onLoad);
                    reader.readAsBinaryString(file);
                });
        }

        this.showMessage    = function(text) {
            var parent,
                HIDE_TIME = 2000;

            if (!Msg) {
                DOM.load.style({
                    id      : 'msg-css',
                    inner   : '#js-view .msg {'     +
                                'z-index'           + ': 1;'                    +
                                'background-color'  + ': #7285B7;'              +
                                'color'             + ': #D1F1A9;'              +
                                'position'          + ': fixed;'                +
                                'left'              + ': 40%;'                  +
                                'top'               + ': 25px;'                 +
                                'padding'           + ': 5px;'                  +
                                'opacity'           + ': 0.9;'                  +
                                'transition'        + ': ease 0.5s;'            +
                            '}'
                });
                parent  = Element;

                Msg     = DOM.load({
                    name        : 'div',
                    className   : 'msg',
                    parent      : parent
                });
            }

            Msg.innerHTML = text;
            DOM.show(Msg);
            setTimeout(Util.exec.ret(DOM.hide, Msg), HIDE_TIME);
        };

        init();
    }

})(CloudCmd, Util, DOM, CloudFunc);
<commit_msg>chore(edit) add " "<commit_after>var CloudCmd, Util, DOM, CloudFunc, ace, DiffProto, diff_match_patch, Zip, MenuIO;
(function(CloudCmd, Util, DOM, CloudFunc) {
    'use strict';

    CloudCmd.Edit = EditProto;

    function EditProto() {
        var Name        = 'Edit',
            Loading     = false,
            DIR         = CloudCmd.LIBDIRCLIENT + 'edit/',
            LIBDIR      = CloudCmd.LIBDIR,
            Info        = DOM.CurrentInfo,
            Menu,
            Value,
            Edit        = this,
            Diff,
            Emmet,
            Ace,
            Session,
            Modelist,
            Msg,
            Events      = DOM.Events,
            Dialog      = DOM.Dialog,
            Images      = DOM.Images,
            Element, JSHintConfig, EditConfig;

       function init() {
            Loading   = true;
            Util.exec.series([
                CloudCmd.View,
                load,
                Edit.show
            ]);
        }

        this.show                       = function(value) {
            var mode, htmlMode, jsMode, isHTML, isJS, modesByName,
                onMenu,
                isStr       = Util.isString(value),
                name        = Info.name,
                isDir       = Info.isDir,
                focus       = function() {
                    Ace.clearSelection();
                    Ace.moveCursorTo(0, 0);
                    Ace.focus();
                };

            if (!Loading) {
                Images.showLoad();

                if (!Element) {
                    Element         = DOM.load({
                        name        : 'div',
                        style   :
                            'width      : 100%;'    +
                            'height     : 100%;'    +
                            'font       : 16px "Droid Sans Mono";' +
                            'position   : absolute;',
                        notAppend : true
                    });

                    onMenu          = Util.exec.with(setMenu, Element);

                    initAce();

                    Events.addOnce('contextmenu', Element, onMenu)
                        .add(Element, {
                            drop          : onDrop,
                            dragover      : function(event) {
                                event.preventDefault();
                            }
                        });
                }

                modesByName = Modelist.modesByName;

                if (isDir)
                    mode    = modesByName.json.mode;
                else
                    mode    = Modelist.getModeForPath(name).mode;

                htmlMode    = modesByName.html.mode;
                jsMode      = modesByName.javascript.mode;

                isHTML      = mode === htmlMode;
                isJS        = mode === jsMode;

                Session.setMode(mode);
                setUseOfWorker(mode);
                setEmmet(isHTML);

                Util.exec.if(isStr, function() {
                    var UndoManager = ace.require('ace/undomanager').UndoManager;

                    Ace.setValue(Value);
                    CloudCmd.View.show(Element, {
                        beforeClose: function() {
                            isChanged();

                            if (Menu)
                                Menu.hide();
                        },
                        afterShow: focus
                    });

                    Session.setUndoManager(new UndoManager());
                }, function(callback) {
                    Info.getData(function(data) {
                        Value = data;

                        if (isJS && Session.getUseWorker())
                            setJsHintConfig();

                        callback();
                    });
                });
            }
        };

        this.hide                       =  function() {
            CloudCmd.View.hide();
        };

        this.goToLine                   = function() {
            var msg     = 'Enter line number:',
                cursor  = Ace.selection.getCursor(),
                number  = cursor.row + 1,
                line    = Dialog.prompt(msg, number);

            number      = line - 0;

            if (number)
                Ace.gotoLine(number);
        };

        function isChanged() {
            var is,
                value   = Ace.getValue(),
                isEqual = value === Value,
                msg     = 'Do you want to save changes to ' + name + '?';

            if (!isEqual) {
                is = Dialog.confirm(msg);

                if (is)
                    save();
            }
        }

        function setEmmet(isHTML) {
            getEditConfig(function(config) {
                var extensions  = config.extensions,
                    isEmmet     = extensions.emmet;

                if (isEmmet)
                    Util.exec.if(Emmet, function() {
                            if (Emmet)
                                Ace.setOption('enableEmmet', isHTML);
                        }, function(callback) {
                            var url;

                            if (!isHTML)
                                Util.exec(callback);
                            else {
                                url = CloudFunc.getJoinURL([
                                    DIR + 'emmet.js',
                                    DIR + 'ext-emmet.js'
                                ]);

                                DOM.load.js(url, function() {
                                    Emmet = ace.require('ace/ext/emmet');
                                    Emmet.setCore(window.emmet);
                                    Util.exec(callback);
                                });
                            }
                        });
                });
        }

        function setUseOfWorker(mode) {
            var isMatch,
                isStr   = Util.isString(mode),
                regStr  = 'coffee|css|html|javascript|json|lua|php|xquery',
                regExp  = new RegExp(regStr);

            if (isStr)
                isMatch = mode.match(regExp);

            Session.setUseWorker(isMatch);
        }

        function initAce() {
            Ace     = ace.edit(Element);
            Session = Ace.getSession();

            Ace.commands.addCommand({
                name    : 'hide',
                bindKey : { win: 'Esc',  mac: 'Esc' },
                exec    : function () {
                    Edit.hide();
                }
            });

            Ace.commands.addCommand({
                name    : 'goToLine',
                bindKey : { win: 'Ctrl-G',  mac: 'Command-G' },
                exec    : function () {
                    Edit.goToLine();
                }
            });

            Ace.commands.addCommand({
                name    : 'save',
                bindKey : { win: 'Ctrl-S',  mac: 'Command-S' },
                exec    : save
            });

            Ace.commands.addCommand({
                name    : 'saveMC',
                bindKey : { win: 'F2',  mac: 'F2' },
                exec    : save
            });

            ace.require('ace/ext/language_tools');
            Modelist = ace.require('ace/ext/modelist');

            getEditConfig(function(config) {
                var options      = config.options;

                Ace.setOptions(options);
            });
        }

        function save () {
            var path    = Info.path,
                value   = Ace.getValue();

            CloudCmd.getConfig(function(config) {
                var isDiff      = config.diff,
                    isZip       = config.zip;

                Util.exec.if(!isDiff, function(patch) {
                    var query           = '',
                        MAX_SIZE        = CloudFunc.MAX_FILE_SIZE,
                        patchLength     = patch.length,
                        length          = Value.length,
                        isLessMaxLength = length < MAX_SIZE,
                        isLessLength    = isLessMaxLength && patchLength < length,
                        isStr           = Util.isString(patch);

                    Value               = value;

                    if (isStr && patch && isLessLength)
                        query           = '?patch';
                    else
                        patch           = false;

                    Util.exec.if(!isZip || query, function(equal, data) {
                        var result  = data || patch || Value,
                            url     = path + query;

                        DOM.RESTful.write(url, result , onSave);
                    }, function(func) {
                        zip(value, function(error, data) {
                            if (error)
                                Util.log(error);

                            query = '?unzip';
                            func(null, data);
                        });
                    });

                }, Util.exec.with(doDiff, path));
            });
        }

        function doDiff(path, callback) {
            var value = Ace.getValue();

            diff(value, function(patch) {
                var isAllowed = DOM.Storage.isAllowed();

                Util.exec.if(!isAllowed, callback, function(func) {
                        DOM.checkStorageHash(path, function(error, equal) {
                            if (!equal)
                                patch = '';

                            func(patch);
                        });
                });
            });
        }

        function diff(newValue, callback) {
            var libs            = [
                    LIBDIR + 'diff/diff-match-patch.js',
                    LIBDIR + 'diff.js'
                ],
                url             = CloudFunc.getJoinURL(libs);

            DOM.load.js(url, function() {
                var patch,
                    isAllowed   = DOM.Storage.isAllowed();

                if (!Diff)
                    Diff        = new DiffProto(diff_match_patch);

                Util.exec.if(!isAllowed, function() {
                    patch       = Diff.createPatch(Value, newValue);
                    Util.exec(callback, patch);
                }, function(func) {
                    var path = Info.path;

                    DOM.getDataFromStorage(path, function(data) {
                        if (data)
                            Value   = data;

                        func();
                    });
                });
            });
        }

        function zip(value, callback) {
            var dir             = CloudCmd.LIBDIRCLIENT,
                libs            = [
                    dir + 'zip/dist/pako.js',
                    dir + 'zip.js'
                ],
                url             = CloudFunc.getJoinURL(libs);

            DOM.load.js(url, function() {
                Zip.pack(value, callback);
            });
        }

        function setJsHintConfig(callback) {
            var JSHINT_PATH = '/.jshintrc',
                func        = function() {
                    var worker  = Session.$worker;

                    if (worker)
                        worker.send('changeOptions', [JSHintConfig]);

                    Util.exec(callback);
                };

            Util.exec.if(JSHintConfig, func, function() {
                DOM.load.ajax({
                    url     :  JSHINT_PATH,
                    success : function(data) {
                        JSHintConfig = Util.parseJSON(data);
                        func();
                    }
                });
            });
        }

        function getEditConfig(callback) {
            var CONFIG_PATH = '/json/edit.json',
                func        = Util.exec.ret(callback);

            Util.exec.if(EditConfig, function() {
                func(EditConfig);
            }, function() {
                DOM.load.ajax({
                    url     : CONFIG_PATH,
                    success : function(data) {
                        EditConfig = data;
                        func(EditConfig);
                    }
                });
            });
        }

        function setMenu(element) {
            DOM.loadMenu(function() {
                var position    = CloudCmd.MousePosition,
                    options     = {
                        beforeShow: function(params) {
                            params.x -= 18;
                            params.y -= 27;
                        },
                        afterClick: function() {
                            Ace.focus();
                        }
                },
                menuData    = {
                    'Save           Ctrl+S' : save,
                    'Go To Line     Ctrl+G' : function() {
                        Edit.goToLine();
                    },
                    'Select All     Ctrl+A' : function() {
                        Ace.selectAll();
                    },
                    'Delete         Del'    : function() {
                        Ace.remove('right');
                    },
                    'Close          Esc'    : Edit.hide
                };

                Menu        = new MenuIO(element, options, menuData);

                Menu.show(position.x, position.y);
            });
        }

        function load(callback) {
            var files  = [
                    DIR + 'theme-tomorrow_night_blue.js',
                    DIR + 'ext-language_tools.js',
                    DIR + 'ext-searchbox.js',
                    DIR + 'ext-modelist.js'
                ],

                ace     = DIR + 'ace.js',
                url     = CloudFunc.getJoinURL(files);

            Util.time(Name + ' load');

            DOM.load.series([ace, url], function() {
                Util.timeEnd(Name + ' load');
                Loading = false;
                Util.exec(callback);
            });
        }

        function onSave(text) {
            var ret,
                isError = Util.isContainStrAtBegin(text, 'error'),
                path    = Info.path,
                msg     = '\nShould I save file anyway?';

            if (!isError) {
                Edit.showMessage(text);
                DOM.saveDataToStorage(path, Value);
                DOM.setCurrentSize(Value.length);
            } else {
                ret     = Dialog.confirm(text + msg);

                if (ret)
                    DOM.RESTful.write(path, Value, onSave);
            }
        }

         function onDrop(event) {
            var reader, files,
                onLoad   =  function(event) {
                    var data    = event.target.result;

                    Ace.setValue(data);
                };

            event.preventDefault();

            files   = event.dataTransfer.files;

            if (files)
                files.forEach(function(file) {
                    reader  = new FileReader();
                    DOM.Events.addLoad(reader, onLoad);
                    reader.readAsBinaryString(file);
                });
        }

        this.showMessage    = function(text) {
            var parent,
                HIDE_TIME = 2000;

            if (!Msg) {
                DOM.load.style({
                    id      : 'msg-css',
                    inner   : '#js-view .msg {'     +
                                'z-index'           + ': 1;'                    +
                                'background-color'  + ': #7285B7;'              +
                                'color'             + ': #D1F1A9;'              +
                                'position'          + ': fixed;'                +
                                'left'              + ': 40%;'                  +
                                'top'               + ': 25px;'                 +
                                'padding'           + ': 5px;'                  +
                                'opacity'           + ': 0.9;'                  +
                                'transition'        + ': ease 0.5s;'            +
                            '}'
                });
                parent  = Element;

                Msg     = DOM.load({
                    name        : 'div',
                    className   : 'msg',
                    parent      : parent
                });
            }

            Msg.innerHTML = text;
            DOM.show(Msg);
            setTimeout(Util.exec.ret(DOM.hide, Msg), HIDE_TIME);
        };

        init();
    }

})(CloudCmd, Util, DOM, CloudFunc);
<|endoftext|>


<commit_before><commit_msg>check support sw & writable<commit_after><|endoftext|>


<commit_before>var alloc = require('tcp-bind')
var minimist = require('minimist')
var argv = minimist(process.argv.slice(2), {
  alias: { p: 'port', u: 'uid', g: 'gid' },
  default: { port: require('is-root')() ? 80 : 8000 }
})
var fd = alloc(argv.port)
if (argv.gid) process.setgid(argv.gid)
if (argv.uid) process.setuid(argv.uid)

var http = require('http')
var st = require('st')
var body = require('body/any')
var xtend = require('xtend')
var trumpet = require('trumpet')
var through = require('through2')
var encode = require('he').encode
var fs = require('fs')
var path = require('path')
var HttpHashRouter = require('http-hash-router')
var methods = require('http-methods')
var path = require('path')
var favicon = require('serve-favicon')

var router = HttpHashRouter()

var static = path.join(__dirname, 'static')

router.set('/static/*', st({
  path: static,
  url: '/static'
}))

router.set('/favicon.ico', function serverFavicon(req, res, opts, cb) {
  var iconPath = path.join(static, 'favicon.ico')
  favicon(iconPath)(req, res, cb)
})

var server = http.createServer(function (req, res) {
  router(req, res, xtend({}, {beep: 'boop'}), onError)

  function onError (err) {
    if (err) {
      res.statusCode = err.statusCode || 500
      res.end(err.message)
    }
  }
})

server.listen({ fd: fd }, function () {
  console.log('listening on :' + server.address().port)
})
<commit_msg>Fixed naming<commit_after>var alloc = require('tcp-bind')
var minimist = require('minimist')
var argv = minimist(process.argv.slice(2), {
  alias: { p: 'port', u: 'uid', g: 'gid' },
  default: { port: require('is-root')() ? 80 : 8000 }
})
var fd = alloc(argv.port)
if (argv.gid) process.setgid(argv.gid)
if (argv.uid) process.setuid(argv.uid)

var http = require('http')
var st = require('st')
var body = require('body/any')
var xtend = require('xtend')
var trumpet = require('trumpet')
var through = require('through2')
var encode = require('he').encode
var fs = require('fs')
var path = require('path')
var HttpHashRouter = require('http-hash-router')
var methods = require('http-methods')
var path = require('path')
var favicon = require('serve-favicon')

var router = HttpHashRouter()

var staticPath = path.join(__dirname, 'static')

router.set('/static/*', st({
  path: staticPath,
  url: '/static'
}))

router.set('/favicon.ico', function serverFavicon (req, res, opts, cb) {
  var iconPath = path.join(staticPath, 'favicon.ico')
  favicon(iconPath)(req, res, cb)
})

var server = http.createServer(function (req, res) {
  router(req, res, xtend({}, {beep: 'boop'}), onError)

  function onError (err) {
    if (err) {
      res.statusCode = err.statusCode || 500
      res.end(err.message)
    }
  }
})

server.listen({ fd: fd }, function () {
  console.log('listening on :' + server.address().port)
})
<|endoftext|>