<commit_before>import Utility from '../utility';

export default function Binder (options) {
	this.element = options.element;
	this.attribute = options.attribute;
	this.controller = options.controller;
	this.renderType = this.attribute.cmds[0] || 'default';

	if (this.renderType === 'on') {
		this.data = Utility.getByPath(this.controller.events, this.attribute.path).bind(this.controller.model.data);
	} else {
		this.modifiers = this.attribute.modifiers.map(function (modifier) {
			return this.controller.modifiers[modifier];
		}, this);

		this.paths = this.attribute.path.split('.');
		this.key = this.paths.slice(-1)[0];
		this.path = this.paths.slice(0, -1).join('.');
		this.data = this.path ? Utility.getByPath(this.controller.model.data, this.path) : this.controller.model.data;

		// dyncamically set observed property on model
		if (this.attribute.cmds[0] === 'value' && this.data && this.data[this.key] === undefined) {
			this.data.$set(this.key, null);
			this.updateModel();
		}

	}

	this.render();
}

Binder.prototype.setData = function (data) {
	if (this.data === undefined) return;

	if (data !== null) {
		for (var i = 0, l = this.modifiers.length; i < l; i++) {
			data = this.modifiers[i].call(data);
		}
	}

	return this.data[this.key] = data;
};

Binder.prototype.getData = function () {
	if (this.data === undefined) return;

	var data = this.data[this.key];

	if (data !== null) {
		for (var i = 0, l = this.modifiers.length; i < l; i++) {
			data = this.modifiers[i].call(data);
		}
	}

	return data;
};

Binder.prototype.updateModel = function () {
	if (this.element.type === 'checkbox') {
		this.element.value = this.element.checked;
		this.setData(this.element.checked);
	} else if (this.element.nodeName === 'SELECT' && this.element.multiple) {
		this.setData(Array.prototype.filter.call(this.element.options, function (option) {
			return option.selected;
		}).map(function (option) {
			return option.value;
		}));
	} else if (this.element.type === 'radio') {
		var elements = this.element.parentNode.querySelectorAll('input[type="radio"][type="radio"][j-value="' + this.attribute.value + '"]');
		for (var i = 0, l = elements.length, radio; i < l; i++) {
			radio = elements[i];
			if (radio === this.element) {
				this.setData(i);
			} else {
				radio.checked = false;
			}
		}
	} else {
		this.setData(this.element.value);
	}
};

Binder.prototype.renderMethods = {
	on: function (data) {
		var self = this;
		self.element.removeEventListener(self.attribute.cmds[1], data);
		self.element.addEventListener(self.attribute.cmds[1], data);
	},
	each: function (data) {
		var self = this;

		if (!self.clone) {
			self.variable = self.attribute.cmds.slice(1).join('.');
			self.clone = self.element.removeChild(self.element.children[0]).outerHTML;
			self.pattern = new RegExp('(((data-)?j(-(\\w)+)+="))' + self.variable + '(((\\.(\\w)+)+)?((\\s+)?\\|((\\s+)?(\\w)+)+)?(\\s+)?")', 'g');
		}

		if (self.element.children.length > data.length) {
			while (self.element.children.length > data.length) {
				self.element.removeChild(self.element.children[self.element.children.length-1]);
			}
		} else if (self.element.children.length < data.length) {
			while (self.element.children.length < data.length) {
				self.element.insertAdjacentHTML(
					'beforeend',
					self.clone.replace(
						self.pattern, '$1' + self.attribute.path + '.' + self.element.children.length + '$6'
					)
				);
			}
		}
	},
	value: function (data) {
		// NOTE triggered on every change
		if (this.isSetup) return;
		var self = this, i, l;

		if (self.element.type === 'checkbox') {
			if (self.element.checked !== data) {
				self.element.value = data;
				self.element.checked = data;
			}
		} if (self.element.nodeName === 'SELECT' && self.element.multiple) {
			if (self.element.options.length !== data.length) {
				var options = self.element.options;
				for (i = 0, l = options.length; i < l; i++) {
					var option = options[i];
					if (option.value === data[i]) {
						option.selected;
					}
				}
			}
		} else if (self.element.type === 'radio') {
			var elements = self.element.parentNode.querySelectorAll('input[type="radio"][type="radio"][j-value="' + self.attribute.value + '"]');
			for (i = 0, l = elements.length; i < l; i++) {
				var radio = elements[i];
				radio.checked = i === data;
			}
		} else {
			self.element.value = data;
		}

		self.isSetup = true;
	},
	html: function (data) {
		var self = this;
		// FIXME not rendering j-*
		self.element.innerHTML = data;
	},
	css: function (data) {
		var css = data;

		if (this.attribute.cmds.length > 1) {
			css = this.attribute.cmds.slice(1).join('-') + ': ' +  css + ';';
		}

		this.element.style.cssText += css;
	},
	class: function (data) {
		var className = this.attribute.cmds.slice(1).join('-');
		this.element.classList.toggle(className, data);
	},
	text: function (data) {
		this.element.innerText = data;
	},
	enable: function (data) {
		this.element.disabled = !data;
	},
	disable: function (data) {
		this.element.disabled = data;
	},
	show: function (data) {
		this.element.hidden = !data;
	},
	hide: function (data) {
		this.element.hidden = data;
	},
	write: function (data) {
		this.element.readOnly = !data;
	},
	read: function (data) {
		this.element.readOnly = data;
	},
	selected: function (data) {
		this.element.selectedIndex = data;
	},
	href: function (data) {
		this.element.href = data;
	},
	default: function (data) {
		var path = Utility.toCamelCase(this.attribute.cmds);
		Utility.setByPath(this.element, path, data);
	}
};

Binder.prototype.unrenderMethods = {
	on: function (data) {
		this.element.removeEventListener(this.attribute.cmds[1], data, false);
	},
	each: function () {
		while (this.element.lastChild) {
			this.element.removeChild(this.element.lastChild);
		}
	},
	html: function () {
		this.element.innerText = '';
	},
	text: function () {
		this.element.innerText = '';
	},
	default: function () {

	}
};

Binder.prototype.unrender = function () {
	var self = this;
	var data = self.renderType === 'on' ? self.data : undefined;
	self.unrenderMethods[self.renderType].call(self, data);
	return self;
};

Binder.prototype.render = function () {
	var self = this;
	var data = self.renderType === 'on' ? self.data : self.getData();
	if (data === undefined) return;
	self.renderMethods[self.renderType].call(self, data);
	return self;
};
<commit_msg>switched from map to for loop<commit_after>import Utility from '../utility';

export default function Binder (options) {
	var self = this;

	self.element = options.element;
	self.attribute = options.attribute;
	self.controller = options.controller;
	self.renderType = self.attribute.cmds[0] || 'default';

	if (self.renderType === 'on') {
		self.data = Utility.getByPath(self.controller.events, self.attribute.path).bind(self.controller.model.data);
	} else {
		self.modifiers = [];

		for (var i = 0, l = self.attribute.modifiers.length; i < l; i++) {
			self.modifiers[self.modifiers.length] = self.controller.modifiers[self.attribute.modifiers[i]];
		}

		self.paths = self.attribute.path.split('.');
		self.key = self.paths.slice(-1)[0];
		self.path = self.paths.slice(0, -1).join('.');
		self.data = self.path ? Utility.getByPath(self.controller.model.data, self.path) : self.controller.model.data;

		// dyncamically set observed property on model
		if (self.attribute.cmds[0] === 'value' && self.data && self.data[self.key] === undefined) {
			self.data.$set(self.key, null);
			self.updateModel();
		}

	}

	self.render();
}

Binder.prototype.setData = function (data) {
	if (this.data === undefined) return;

	if (data !== null) {
		for (var i = 0, l = this.modifiers.length; i < l; i++) {
			data = this.modifiers[i].call(data);
		}
	}

	return this.data[this.key] = data;
};

Binder.prototype.getData = function () {
	if (this.data === undefined) return;

	var data = this.data[this.key];

	if (data !== null) {
		for (var i = 0, l = this.modifiers.length; i < l; i++) {
			data = this.modifiers[i].call(data);
		}
	}

	return data;
};

Binder.prototype.updateModel = function () {
	if (this.element.type === 'checkbox') {
		this.element.value = this.element.checked;
		this.setData(this.element.checked);
	} else if (this.element.nodeName === 'SELECT' && this.element.multiple) {
		this.setData(Array.prototype.filter.call(this.element.options, function (option) {
			return option.selected;
		}).map(function (option) {
			return option.value;
		}));
	} else if (this.element.type === 'radio') {
		var elements = this.element.parentNode.querySelectorAll('input[type="radio"][type="radio"][j-value="' + this.attribute.value + '"]');
		for (var i = 0, l = elements.length, radio; i < l; i++) {
			radio = elements[i];
			if (radio === this.element) {
				this.setData(i);
			} else {
				radio.checked = false;
			}
		}
	} else {
		this.setData(this.element.value);
	}
};

Binder.prototype.renderMethods = {
	on: function (data) {
		var self = this;
		self.element.removeEventListener(self.attribute.cmds[1], data);
		self.element.addEventListener(self.attribute.cmds[1], data);
	},
	each: function (data) {
		var self = this;

		if (!self.clone) {
			self.variable = self.attribute.cmds.slice(1).join('.');
			self.clone = self.element.removeChild(self.element.children[0]).outerHTML;
			self.pattern = new RegExp('(((data-)?j(-(\\w)+)+="))' + self.variable + '(((\\.(\\w)+)+)?((\\s+)?\\|((\\s+)?(\\w)+)+)?(\\s+)?")', 'g');
		}

		if (self.element.children.length > data.length) {
			while (self.element.children.length > data.length) {
				self.element.removeChild(self.element.children[self.element.children.length-1]);
			}
		} else if (self.element.children.length < data.length) {
			while (self.element.children.length < data.length) {
				self.element.insertAdjacentHTML(
					'beforeend',
					self.clone.replace(
						self.pattern, '$1' + self.attribute.path + '.' + self.element.children.length + '$6'
					)
				);
			}
		}
	},
	value: function (data) {
		// NOTE triggered on every change
		if (this.isSetup) return;
		var self = this, i, l;

		if (self.element.type === 'checkbox') {
			if (self.element.checked !== data) {
				self.element.value = data;
				self.element.checked = data;
			}
		} if (self.element.nodeName === 'SELECT' && self.element.multiple) {
			if (self.element.options.length !== data.length) {
				var options = self.element.options;
				for (i = 0, l = options.length; i < l; i++) {
					var option = options[i];
					if (option.value === data[i]) {
						option.selected;
					}
				}
			}
		} else if (self.element.type === 'radio') {
			var elements = self.element.parentNode.querySelectorAll('input[type="radio"][type="radio"][j-value="' + self.attribute.value + '"]');
			for (i = 0, l = elements.length; i < l; i++) {
				var radio = elements[i];
				radio.checked = i === data;
			}
		} else {
			self.element.value = data;
		}

		self.isSetup = true;
	},
	html: function (data) {
		var self = this;
		// FIXME not rendering j-*
		self.element.innerHTML = data;
	},
	css: function (data) {
		var css = data;

		if (this.attribute.cmds.length > 1) {
			css = this.attribute.cmds.slice(1).join('-') + ': ' +  css + ';';
		}

		this.element.style.cssText += css;
	},
	class: function (data) {
		var className = this.attribute.cmds.slice(1).join('-');
		this.element.classList.toggle(className, data);
	},
	text: function (data) {
		this.element.innerText = data;
	},
	enable: function (data) {
		this.element.disabled = !data;
	},
	disable: function (data) {
		this.element.disabled = data;
	},
	show: function (data) {
		this.element.hidden = !data;
	},
	hide: function (data) {
		this.element.hidden = data;
	},
	write: function (data) {
		this.element.readOnly = !data;
	},
	read: function (data) {
		this.element.readOnly = data;
	},
	selected: function (data) {
		this.element.selectedIndex = data;
	},
	href: function (data) {
		this.element.href = data;
	},
	default: function (data) {
		var path = Utility.toCamelCase(this.attribute.cmds);
		Utility.setByPath(this.element, path, data);
	}
};

Binder.prototype.unrenderMethods = {
	on: function (data) {
		this.element.removeEventListener(this.attribute.cmds[1], data, false);
	},
	each: function () {
		while (this.element.lastChild) {
			this.element.removeChild(this.element.lastChild);
		}
	},
	html: function () {
		this.element.innerText = '';
	},
	text: function () {
		this.element.innerText = '';
	},
	default: function () {

	}
};

Binder.prototype.unrender = function () {
	var self = this;
	var data = self.renderType === 'on' ? self.data : undefined;
	self.unrenderMethods[self.renderType].call(self, data);
	return self;
};

Binder.prototype.render = function () {
	var self = this;
	var data = self.renderType === 'on' ? self.data : self.getData();
	if (data === undefined) return;
	self.renderMethods[self.renderType].call(self, data);
	return self;
};
<|endoftext|>


<commit_before>// Shape Constructors

function makePlane(width, height, x, y, z, rotX, rotY, rotZ, material) {
  var geometry = new THREE.PlaneGeometry( width, height);
  var mesh = new THREE.Mesh( geometry, material );
  if (x !== null) {mesh.position.x = x;}
  if (y !== null) {mesh.position.y = y;}
  if (z !== null) {mesh.position.z = z;}
  if (rotX !== null) {mesh.rotation.x = rotX;}
  if (rotY !== null) {mesh.rotation.y = rotY;}
  if (rotZ !== null) {mesh.rotation.z = rotZ;}
  return mesh;
}

function addArrowHelper(ax, ay, az, bx, by, bz, length, hex) {
  if (hex === undefined) {hex = 0x325EFF;}
  if (length === undefined) {length = Math.sqrt( Math.pow(ax-bx,2) + Math.pow(ay-by,2) + Math.pow(az-bz,2));}
  var dir = new THREE.Vector3( bx-ax, by-ay, bz-az );
  //normalize the direction vector (convert to vector of length 1)
  dir.normalize();
  var origin = new THREE.Vector3( ax, ay, az );
  scene.add(new THREE.ArrowHelper( dir, origin, length, hex));
}

function makeArrowHelper(ax, ay, az, bx, by, bz, length, hex) {
  if (hex === undefined) {hex = 0x325EFF;}
  if (length === undefined) {length = Math.sqrt( Math.pow(ax-bx,2) + Math.pow(ay-by,2) + Math.pow(az-bz,2));}
  var dir = new THREE.Vector3( bx-ax, by-ay, bz-az );
  //normalize the direction vector (convert to vector of length 1)
  dir.normalize();
  var origin = new THREE.Vector3( ax, ay, az );
  return new THREE.ArrowHelper( dir, origin, length, hex);
}

// Lights!

function addPointLight(x,y,z, color) {
  // create a point light
  var pointLight = new THREE.S(color);
  if (x !== null) {pointLight.position.x = x;}
  if (y !== null) {pointLight.position.y = y;}
  if (z !== null) {pointLight.position.z = z;}
  // add to the scene
  scene.add(pointLight);
}

function makePointLight(x,y,z,target,color) {
  // create a point light (color optional, defaults to 0xffffff)
  var pointLight = new THREE.PointLight(color, 2.5);
  pointLight.distance = 7;
  pointLight.decay = 2;
  if (target !== null) {pointLight.target = target;}
  if (x !== null) {pointLight.position.x = x;}
  if (y !== null) {pointLight.position.y = y;}
  if (z !== null) {pointLight.position.z = z;}
  var sphereSize = 0.3;
  var pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  scene.add( pointLightHelper );
  // add to the scene
  return pointLight;
}

// Vector ---> Geometry Helpers

function getPlaneCenterFromVector(A, B) {
  // Returns PLANECENTER, a point directly below the midpoint
  // Returns LOOKAT, the point along A,B that the plane's normal
  //         needs to point to for it to be perpendicular to AB
  // mid point
  var mx = (A.x+B.x)/2.0;
  var my = (A.y+B.y)/2.0;
  var mz = (A.z+B.z)/2.0;
  var M = new THREE.Vector3(mx, my, mz);
  // direction
  var AM = new THREE.Vector3().subVectors( M, A ); // not normalized
  var dir = AM.clone().normalize(); // normalized
  // We now generate other points (see diagram)
  var MC_len = 1.5;
  var planeCenter = new THREE.Vector3().subVectors( M, new THREE.Vector3(0,MC_len,0) );
  var m_lookAt_len = - dir.y * MC_len; // dir.y is equiv. to cos(theta) == CM.dot(CP) == (0,-1,0).dot(AB.normalized())
  var lookAt = new THREE.Vector3().addVectors( M, dir.clone().multiplyScalar(m_lookAt_len) );
  // Guide lines for debugging
  // addArrowHelper(planeCenter.x, planeCenter.y, planeCenter.z, lookAt.x, lookAt.y, lookAt.z, undefined, 0xffff00);
  // addArrowHelper(planeCenter.x, planeCenter.y, planeCenter.z, mx, my, mz, undefined, 0xffff00);
  // addArrowHelper(A.x, A.y, A.z, B.x, B.y, B.z, undefined, 0xffff00);
  // addArrowHelper(B.x, B.y, B.z, planeCenter.x, planeCenter.y, planeCenter.z, undefined, 0xffff00);
  return [planeCenter, lookAt, dir];
}

function makeSpaceAsVector(ax, ay, az, bx, by, bz, spaceFn) {
  var length = Math.sqrt( Math.pow(ax-bx,2) + Math.pow(ay-by,2) + Math.pow(az-bz,2));
  // Calculate orientation for floor
  var useful_vals = getPlaneCenterFromVector(new THREE.Vector3(ax, ay, az), new THREE.Vector3(bx, by, bz));
  var planeCenter = useful_vals[0];
  var lookAt = useful_vals[1];
  var dir = useful_vals[2];
  // Space
  var space = spaceFn(length);
  space.position.set(planeCenter.x,planeCenter.y,planeCenter.z);
  space.updateMatrixWorld();  // Get the "up" vector to look along vector
  space.up = planeCenter.add(space.worldToLocal(dir)).normalize();
  space.lookAt(lookAt);
  return space;
}<commit_msg>Changed variable name<commit_after>// Shape Constructors

function makePlane(width, height, x, y, z, rotX, rotY, rotZ, material) {
  var geometry = new THREE.PlaneGeometry( width, height);
  var mesh = new THREE.Mesh( geometry, material );
  if (x !== null) {mesh.position.x = x;}
  if (y !== null) {mesh.position.y = y;}
  if (z !== null) {mesh.position.z = z;}
  if (rotX !== null) {mesh.rotation.x = rotX;}
  if (rotY !== null) {mesh.rotation.y = rotY;}
  if (rotZ !== null) {mesh.rotation.z = rotZ;}
  return mesh;
}

function addArrowHelper(ax, ay, az, bx, by, bz, length, hex) {
  if (hex === undefined) {hex = 0x325EFF;}
  if (length === undefined) {length = Math.sqrt( Math.pow(ax-bx,2) + Math.pow(ay-by,2) + Math.pow(az-bz,2));}
  var dir = new THREE.Vector3( bx-ax, by-ay, bz-az );
  //normalize the direction vector (convert to vector of length 1)
  dir.normalize();
  var origin = new THREE.Vector3( ax, ay, az );
  scene.add(new THREE.ArrowHelper( dir, origin, length, hex));
}

function makeArrowHelper(ax, ay, az, bx, by, bz, length, hex) {
  if (hex === undefined) {hex = 0x325EFF;}
  if (length === undefined) {length = Math.sqrt( Math.pow(ax-bx,2) + Math.pow(ay-by,2) + Math.pow(az-bz,2));}
  var dir = new THREE.Vector3( bx-ax, by-ay, bz-az );
  //normalize the direction vector (convert to vector of length 1)
  dir.normalize();
  var origin = new THREE.Vector3( ax, ay, az );
  return new THREE.ArrowHelper( dir, origin, length, hex);
}

// Lights!

function addPointLight(x,y,z, color) {
  // create a point light
  var pointLight = new THREE.S(color);
  if (x !== null) {pointLight.position.x = x;}
  if (y !== null) {pointLight.position.y = y;}
  if (z !== null) {pointLight.position.z = z;}
  // add to the scene
  scene.add(pointLight);
}

function makePointLight(x,y,z,target,color) {
  // create a point light (color optional, defaults to 0xffffff)
  var pointLight = new THREE.PointLight(color, 2.5);
  pointLight.distance = 7;
  pointLight.decay = 2;
  if (target !== null) {pointLight.target = target;}
  if (x !== null) {pointLight.position.x = x;}
  if (y !== null) {pointLight.position.y = y;}
  if (z !== null) {pointLight.position.z = z;}
  var sphereSize = 0.3;
  var pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  scene.add( pointLightHelper );
  // add to the scene
  return pointLight;
}

// Vector ---> Geometry Helpers

function getPlaneCenterFromVector(A, B) {
  // Returns PLANECENTER, a point directly below the midpoint
  // Returns LOOKAT, the point along A,B that the plane's normal
  //         needs to point to for it to be perpendicular to AB
  // mid point
  var mx = (A.x+B.x)/2.0;
  var my = (A.y+B.y)/2.0;
  var mz = (A.z+B.z)/2.0;
  var M = new THREE.Vector3(mx, my, mz);
  // direction
  var AM = new THREE.Vector3().subVectors( M, A ); // not normalized
  var dir = AM.clone().normalize(); // normalized
  // We now generate other points (see diagram)
  var M_planeCenter_len = 1.25;
  var planeCenter = new THREE.Vector3().subVectors( M, new THREE.Vector3(0,M_planeCenter_len,0) );
  var m_lookAt_len = - dir.y * M_planeCenter_len; // dir.y is equiv. to cos(theta) == CM.dot(CP) == (0,-1,0).dot(AB.normalized())
  var lookAt = new THREE.Vector3().addVectors( M, dir.clone().multiplyScalar(m_lookAt_len) );
  // Guide lines for debugging
  // addArrowHelper(planeCenter.x, planeCenter.y, planeCenter.z, lookAt.x, lookAt.y, lookAt.z, undefined, 0xffff00);
  // addArrowHelper(planeCenter.x, planeCenter.y, planeCenter.z, mx, my, mz, undefined, 0xffff00);
  // addArrowHelper(A.x, A.y, A.z, B.x, B.y, B.z, undefined, 0xffff00);
  // addArrowHelper(B.x, B.y, B.z, planeCenter.x, planeCenter.y, planeCenter.z, undefined, 0xffff00);
  return [planeCenter, lookAt, dir];
}

function makeSpaceAsVector(ax, ay, az, bx, by, bz, spaceFn) {
  var length = Math.sqrt( Math.pow(ax-bx,2) + Math.pow(ay-by,2) + Math.pow(az-bz,2));
  // Calculate orientation for floor
  var useful_vals = getPlaneCenterFromVector(new THREE.Vector3(ax, ay, az), new THREE.Vector3(bx, by, bz));
  var planeCenter = useful_vals[0];
  var lookAt = useful_vals[1];
  var dir = useful_vals[2];
  // Space
  var space = spaceFn(length);
  space.position.set(planeCenter.x,planeCenter.y,planeCenter.z);
  space.updateMatrixWorld();  // Get the "up" vector to look along vector
  space.up = planeCenter.add(space.worldToLocal(dir)).normalize();
  space.lookAt(lookAt);
  return space;
}<|endoftext|>


<commit_before>/*
 *  Open Source Routing Machine (OSRM) - Web (GUI) Interface
 *	Copyright (C) Pascal Neis, 2011
 *
 *	This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU AFFERO General Public License as published by
 *	the Free Software Foundation; either version 3 of the License, or
 *	any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU Affero General Public License
 *	along with this program; if not, write to the Free Software
 *	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *	or see http://www.gnu.org/licenses/agpl.txt.
 */

/**
 * Title: Route.js
 * Description: JS file for routing
 *
 * @author Pascal Neis, pascal@neis-one.org
 * @version 0.1 2011-05-15
 */

//======================
// OBJECTS
//Map
var HOST_ROUTING_URL = 'http://routingdemo.geofabrik.de/route-de/';
var ISCALCULATING = false;
var EPSG_4326 = new OpenLayers.Projection("EPSG:4326");
var EPSG_900913 = new OpenLayers.Projection("EPSG:900913");

//======================
// FUNCTIONS
/*
 * routing()-Function to create and send route request
 */
function routing(isDragRoute){
	//Check if startpoint is set
	if(!isStartPointSet){
		//alert("Please set your Start location first!");
		document.getElementById('information').innerHTML =  '
Please set your Start location first!
';
		return;
	}
	//Check if endpoint is set
	if(!isEndPointSet){
		//alert("Please set your Destination first!");
		document.getElementById('information').innerHTML =  '
Please set your Destination first!
';
		return;
	}

	//Check if already a route is planning
	if(!isDragRoute){ ISCALCULATING = false; }
	if(ISCALCULATING){ return; }
	else{ ISCALCULATING = true; }

	//Get Coordinates of the Start and Endpoint
	var startFeat = getMarkerByName('start');
	var endFeat = getMarkerByName('end');
	var from = new OpenLayers.LonLat(startFeat.geometry.x,startFeat.geometry.y).transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
	var to = new OpenLayers.LonLat(endFeat.geometry.x,endFeat.geometry.y).transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));

	//Send Request
	var script = document.createElement('script');
    script.type = 'text/javascript';

    var callBackFunction = 'showResultsRoute';
    var instructions = '&instructions=true';
    if(isDragRoute){
       callBackFunction = 'showResultsDragRoute';
       instructions = '&instructions=false';
       document.getElementById('information').innerHTML =  '
Release mouse button to get Route Information!
(If no Route Summary is diplayed, press the Route!-button)';
    }
    else{
   		document.getElementById('information').innerHTML =  '
One moment please ...
';
    }

    script.src = HOST_ROUTING_URL + "&"+from.lat + '&' + from.lon + '&' + to.lat + '&' + to.lon +
    	'&z='+this.map.getZoom()+'&output=json&jsonp='+callBackFunction+instructions;//+'&simplified=yes';
    document.body.appendChild(script);
}

/*
 * reroute()-Function
 */
function reroute() {
	if(!isStartPointSet || !isEndPointSet){ return; }
	routing(false);
}

/*
 * showResultsDragRoute()-Function to show route result for drag-route
 */
function showResultsDragRoute(response) {
    if (response) {
    	//Display Route
    	showRouteGeometry(response);
    }
  	markersLayer.clearMarkers();
    ISCALCULATING = false;
}

/*
 * showResultsRoute()-Function to show route result
 */
function showResultsRoute(response) {
    if (response) {
    	//Display Route
		if(document.getElementById("cbNoNames").checked == true){
			showNoNameStreets(response);
		}
		else{
			showRouteGeometry(response);
		}

		//Create Link of the route
		var startFeat = getMarkerByName('start');
		var endFeat = getMarkerByName('end');
		var from = new OpenLayers.LonLat(startFeat.geometry.x,startFeat.geometry.y).transform(EPSG_900913,EPSG_4326);
		var to = new OpenLayers.LonLat(endFeat.geometry.x,endFeat.geometry.y).transform(EPSG_900913,EPSG_4326);
		var routeLink = document.URL+'?fr='+from.lat.toFixed(6)+','+from.lon.toFixed(6)+'&to='+to.lat.toFixed(6)+','+to.lon.toFixed(6);
		routeLink = 'Your link to the route ...';

        //Show Route Summary
        var output = '
Some information about your Way
 from \''+response.route_summary.start_point+'\' to \''+response.route_summary.end_point+'\'
';
        output += '
Distance: '+response.route_summary.total_distance/1000+' km - Duration: '+secondsToTime(response.route_summary.total_time)+'

'+routeLink+'
<pclass="routeInstructionsHL"> The Route-Instructions:
';
        //Show Route Instructions
        output += '
';
        var lengthOfArray = response.route_instructions.length;
        for (var i = 0; i < lengthOfArray; i++) {
        	//odd or even ?
        	var rowstyle='routeInstructionsOdd';
        	if(i%2==0){ rowstyle='routeInstructionsEven'; }

            var indexPos = response.route_instructions[i][3];
            var point = new OpenLayers.Geometry.Point(response.route_geometry[indexPos][1], response.route_geometry[indexPos][0]);

            output += '
'+(i+1)+'.	'+response.route_instructions[i][0]+' on '+response.route_instructions[i][1]+' for '+getDistanceWithUnit(response.route_instructions[i][2])+'
';
        }
        output += '
';
        //alert(vectorLayerRoute.features[0].geometry.getVertices());

        document.getElementById('information').innerHTML = output;
    }
    ISCALCULATING = false;
}

/*
 * showResultsRoute()-Function to show route result
 */
function showRouteGeometry(response) {
    if (response) {
    	vectorLayerRoute.removeFeatures(vectorLayerRoute.features);
    	var lengthOfArray = response.route_geometry.length;
        var points = [];
        points.length = lengthOfArray;

        //Create Route Layer for Display
        for (var i = 0; i < lengthOfArray; i++) {
            var point = new OpenLayers.Geometry.Point(
                    response.route_geometry[i][1], response.route_geometry[i][0]).transform(EPSG_4326, EPSG_900913);
            points.push(point);

			if(i % 1024 == 0 && i>0 || i==lengthOfArray-1){
				var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(points), null, {
					strokeColor: "#0033ff",
					strokeOpacity: 0.7,
					strokeWidth: 5
				});
				vectorLayerRoute.addFeatures([feature]);
				points = [];
				points.push(point);
			}
        }
        /*var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(points), null, {
					strokeColor: "#0033ff",
					strokeOpacity: 0.7,
					strokeWidth: 5
				});
		vectorLayerRoute.addFeatures([feature]);*/
   }
}

/*
 * showNoNameStreets()-Function to show route result
 */
function showNoNameStreets(response) {
    if (response) {
    	vectorLayerRoute.removeFeatures(vectorLayerRoute.features);
    	var lengthOfArray = response.route_geometry.length;
        var points = [];
        points.length = lengthOfArray;

        //Check if a instruction has no name !
        var colors = [];
        if(true){
        	var instrucLength = response.route_instructions.length;
        	for (var i = 0; i < instrucLength; i++) {
        		var indexPos = response.route_instructions[i][3];
        		var streetName = response.route_instructions[i][1];
				if(streetName == ''){ colors[indexPos] = "#FF00FF"; }
				else{ colors[indexPos] = "#0033ff"; }
        	}
        }

        //Create Route Layer for Display
        var color = "#0033ff";
        var changeColor = false;
        for (var i = 0; i < lengthOfArray; i++) {
            var point = new OpenLayers.Geometry.Point(
                    response.route_geometry[i][1], response.route_geometry[i][0]).transform(EPSG_4326, EPSG_900913);
            points.push(point);

            if(colors[i] != undefined){ changeColor=true;}

			if(i % 1024 == 0 && i>0 || i==lengthOfArray-1 || changeColor){
				var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(points), null, {
					strokeColor: color,
					strokeOpacity: 0.7,
					strokeWidth: 5
				});
				vectorLayerRoute.addFeatures([feature]);
				points = [];
				points.push(point);

				if(colors[i] != undefined){ color = colors[i]; }
				changeColor=false;
			}
        }
        /*var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(points), null, {
					strokeColor: "#0033ff",
					strokeOpacity: 0.7,
					strokeWidth: 5
				});
		vectorLayerRoute.addFeatures([feature]);*/
   }
}

function secondsToTime(seconds){
   seconds = parseInt(seconds);
   minutes = parseInt(seconds/60);
   seconds = seconds%60;
   hours = parseInt(minutes/60);
   minutes = minutes%60;
   //return stunden+':'+minuten+':'+seconds;
   if(hours==0){
   	return minutes+' min(s)';
   }
   else{
   	return hours+' h '+minutes+' min(s)';
   }
}

function getDistanceWithUnit(distance){
	distance = parseInt(distance);
	if(distance >= 1000){ return (parseInt(distance/1000))+' km'; }
	else{ return distance+' m'; }
}

function setMapCenter(lonlat){
	lonlat.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));

	//Add Marker
	markersLayer.clearMarkers();
	var size = new OpenLayers.Size(21,25);
    var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
    var icon = new OpenLayers.Icon('img/marker.png',size,offset);
    markersLayer.addMarker(new OpenLayers.Marker(lonlat,icon));

	//Hack - FIXME !
	map.setCenter(new OpenLayers.LonLat(lonlat.lon-200, lonlat.lat), 17);
}<commit_msg>Added RouteGeometryCompression and ShortLink support<commit_after>/*
 *  Open Source Routing Machine (OSRM) - Web (GUI) Interface
 *	Copyright (C) Pascal Neis, 2011
 *
 *	This program is free software; you can redistribute it and/or modify
 *	it under the terms of the GNU AFFERO General Public License as published by
 *	the Free Software Foundation; either version 3 of the License, or
 *	any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU Affero General Public License
 *	along with this program; if not, write to the Free Software
 *	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *	or see http://www.gnu.org/licenses/agpl.txt.
 */

/**
 * Title: Route.js
 * Description: JS file for routing
 *
 * @author Pascal Neis, pascal@neis-one.org
 * @version 0.2 2011-06-23
 */

//======================
// OBJECTS
//Map
var HOST_WEBSITE = 'http://map.project-osrm.org/';//location.host
var HOST_ROUTING_URL = 'http://routingdemo.geofabrik.de/route-de/';
var ISCALCULATING = false;
var EPSG_4326 = new OpenLayers.Projection("EPSG:4326");
var EPSG_900913 = new OpenLayers.Projection("EPSG:900913");

//======================
// FUNCTIONS
/*
 * routing()-Function to create and send route request
 */
function routing(isDragRoute){
	//Check if startpoint is set
	if(!isStartPointSet){
		//alert("Please set your Start location first!");
		document.getElementById('information').innerHTML =  '
Please set your Start location first!
';
		return;
	}
	//Check if endpoint is set
	if(!isEndPointSet){
		//alert("Please set your Destination first!");
		document.getElementById('information').innerHTML =  '
Please set your Destination first!
';
		return;
	}

	//Check if already a route is planning
	if(!isDragRoute){ ISCALCULATING = false; }
	if(ISCALCULATING){ return; }
	else{ ISCALCULATING = true; }

	//Get Coordinates of the Start and Endpoint
	var startFeat = getMarkerByName('start');
	var endFeat = getMarkerByName('end');
	var from = new OpenLayers.LonLat(startFeat.geometry.x,startFeat.geometry.y).transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
	var to = new OpenLayers.LonLat(endFeat.geometry.x,endFeat.geometry.y).transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));

	//Send Request
	var script = document.createElement('script');
    script.type = 'text/javascript';

    var callBackFunction = 'showResultsRoute';
    var instructions = '&instructions=true';
    if(isDragRoute){
       callBackFunction = 'showResultsDragRoute';
       instructions = '&instructions=false';
       document.getElementById('information').innerHTML =  '
Release mouse button to get Route Information!
(If no Route Summary is diplayed, press the Route!-button)';
    }
    else{
   		document.getElementById('information').innerHTML =  '
One moment please ...
';
    }

    script.src = HOST_ROUTING_URL + "&"+from.lat + '&' + from.lon + '&' + to.lat + '&' + to.lon +
    	'&z='+this.map.getZoom()+'&output=json&jsonp='+callBackFunction+instructions+'&geomformat=cmp';//+'&simplified=yes';
    document.body.appendChild(script);
}

/*
 * reroute()-Function
 */
function reroute() {
	if(!isStartPointSet || !isEndPointSet){ return; }
	routing(false);
}

/*
 * showResultsDragRoute()-Function to show route result for drag-route
 */
function showResultsDragRoute(response) {
    if (response) {
    	//Display Route
    	showRouteGeometry(response);
    }
  	markersLayer.clearMarkers();
    ISCALCULATING = false;
}

/*
 * showResultsRoute()-Function to show route result
 */
function showResultsRoute(response) {
    if (response) {
    	//Display Route
		if(document.getElementById("cbNoNames").checked == true){
			showNoNameStreets(response);
		}
		else{
			showRouteGeometry(response);
		}

		//Create Link of the route
		var startFeat = getMarkerByName('start');
		var endFeat = getMarkerByName('end');
		var from = new OpenLayers.LonLat(startFeat.geometry.x,startFeat.geometry.y).transform(EPSG_900913,EPSG_4326);
		var to = new OpenLayers.LonLat(endFeat.geometry.x,endFeat.geometry.y).transform(EPSG_900913,EPSG_4326);
		var routelink = '
<input name="routelink" type="submit" title="Get Link" onClick="createShortLink(\''+HOST_WEBSITE+'?fr='+from.lat.toFixed(6)+','+from.lon.toFixed(6)+'&to='+to.lat.toFixed(6)+','+to.lon.toFixed(6)+'\');" value="Get Link">
';

        //Show Route Summary
        var output = '
Some information about your Way
 from \''+response.route_summary.start_point+'\' to \''+response.route_summary.end_point+'\'
';
        output += '
Distance: '+response.route_summary.total_distance/1000+' km - Duration: '+secondsToTime(response.route_summary.total_time)+'

'+routelink+'
<pclass="routeInstructionsHL"> The Route-Instructions:
';
        //Show Route Instructions
        output += '
';
        var lengthOfArray = response.route_instructions.length;
        var geometry = decodeRouteGeometry(response.route_geometry, 5);
        for (var i = 0; i < lengthOfArray; i++) {
        	//odd or even ?
        	var rowstyle='routeInstructionsOdd';
        	if(i%2==0){ rowstyle='routeInstructionsEven'; }

            var indexPos = response.route_instructions[i][3];
            var point = new OpenLayers.Geometry.Point(geometry[indexPos][1], geometry[indexPos][0]);

            output += '
'+(i+1)+'.	'+response.route_instructions[i][0]+' on '+response.route_instructions[i][1]+' for '+getDistanceWithUnit(response.route_instructions[i][2])+'
';
        }
        output += '
';
        //alert(vectorLayerRoute.features[0].geometry.getVertices());

        document.getElementById('information').innerHTML = output;
    }
    ISCALCULATING = false;
}

/*
 * showResultsRoute()-Function to show route result
 */
function showRouteGeometry(response) {
    if (response) {
    	vectorLayerRoute.removeFeatures(vectorLayerRoute.features);

    	// now with compression of the route geometry
        var geometry = decodeRouteGeometry(response.route_geometry, 5);
       	var lengthOfArray = geometry.length;
        var points = [];
        points.length = lengthOfArray;

        //Create Route Layer for Display
        for (var i = 0; i < lengthOfArray; i++) {
            var point = new OpenLayers.Geometry.Point(geometry[i][1], geometry[i][0]).transform(EPSG_4326, EPSG_900913);
            points.push(point);

			if(i % 1024 == 0 && i>0 || i==lengthOfArray-1){
				var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(points), null, {
					strokeColor: "#0033ff",
					strokeOpacity: 0.7,
					strokeWidth: 5
				});
				vectorLayerRoute.addFeatures([feature]);
				points = [];
				points.push(point);
			}
        }
   }
}

/*
 * showNoNameStreets()-Function to show route result
 */
function showNoNameStreets(response) {
    if (response) {
    	vectorLayerRoute.removeFeatures(vectorLayerRoute.features);

    	// now with compression of the route geometry
        var geometry = decodeRouteGeometry(response.route_geometry, 5);
       	var lengthOfArray = geometry.length;
        var points = [];
        points.length = lengthOfArray;

        //Check if a instruction has no name !
        var colors = [];
        if(true){
        	var instrucLength = response.route_instructions.length;
        	for (var i = 0; i < instrucLength; i++) {
        		var indexPos = response.route_instructions[i][3];
        		var streetName = response.route_instructions[i][1];
				if(streetName == ''){ colors[indexPos] = "#FF00FF"; }
				else{ colors[indexPos] = "#0033ff"; }
        	}
        }

        //Create Route Layer for Display
        var color = "#0033ff";
        var changeColor = false;
        for (var i = 0; i < lengthOfArray; i++) {
            var point = new OpenLayers.Geometry.Point(geometry[i][1], geometry[i][0]).transform(EPSG_4326, EPSG_900913);
            points.push(point);

            if(colors[i] != undefined){ changeColor=true;}

			if(i % 1024 == 0 && i>0 || i==lengthOfArray-1 || changeColor){
				var feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(points), null, {
					strokeColor: color,
					strokeOpacity: 0.7,
					strokeWidth: 5
				});
				vectorLayerRoute.addFeatures([feature]);
				points = [];
				points.push(point);

				if(colors[i] != undefined){ color = colors[i]; }
				changeColor=false;
			}
        }
   }
}

/*
 * secondsToTime()-Function to transform seconds to a time string
 */
function secondsToTime(seconds){
   seconds = parseInt(seconds);
   minutes = parseInt(seconds/60);
   seconds = seconds%60;
   hours = parseInt(minutes/60);
   minutes = minutes%60;
   //return stunden+':'+minuten+':'+seconds;
   if(hours==0){
   	return minutes+' min(s)';
   }
   else{
   	return hours+' h '+minutes+' min(s)';
   }
}

/*
 * getDistanceWithUnit()-Function to return a distance with units
 */
function getDistanceWithUnit(distance){
	distance = parseInt(distance);
	if(distance >= 1000){ return (parseInt(distance/1000))+' km'; }
	else{ return distance+' m'; }
}

/*
 * setMapCenter()-Function to add a marker and center the map
 */
function setMapCenter(lonlat){
	lonlat.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));

	//Add Marker
	markersLayer.clearMarkers();
	var size = new OpenLayers.Size(21,25);
    var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
    var icon = new OpenLayers.Icon('img/marker.png',size,offset);
    markersLayer.addMarker(new OpenLayers.Marker(lonlat,icon));

	//Hack - FIXME !
	map.setCenter(new OpenLayers.LonLat(lonlat.lon-200, lonlat.lat), 17);
}

/*
 * decodeRouteGeometry()-Function to decode encoded Route Geometry
 */
function decodeRouteGeometry(encoded, precision) {
	precision = Math.pow(10, -precision);
	var len = encoded.length, index=0, lat=0, lng = 0, array = [];
	while (index < len) {
		var b, shift = 0, result = 0;
		do {
			b = encoded.charCodeAt(index++) - 63;
			result |= (b & 0x1f) << shift;
			shift += 5;
		} while (b >= 0x20);
		var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
		lat += dlat;
		shift = 0;
		result = 0;
		do {
			b = encoded.charCodeAt(index++) - 63;
			result |= (b & 0x1f) << shift;
			shift += 5;
		} while (b >= 0x20);
		var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
		lng += dlng;
		array.push([lat * precision, lng * precision]);
	}
	return array;
}

function createShortLink(str){
	var script = document.createElement('script');
    script.type = 'text/javascript';
    var callBackFunction = 'showRouteLink';
    script.src = 'http://map.project-osrm.org/shorten/'+str+'&jsonp=showRouteLink';
    document.body.appendChild(script);
}

function showRouteLink(response){
	document.getElementById('routelink').innerHTML = ' >> Your ShortLink: '+response.ShortURL+'';
}
<|endoftext|>


<commit_before>slate.log('Loading config')

var getKeystroke = function(key) {
    return key + ':ctrl,shift'
}

var screens = {
    laptop: '1280x800',
    thunderbolt: '2560x1440'
}

// Operations

var operations = {}
var windowMargin = 20

/**
 * Applies the operation or list of operations
 */
operations.apply = function(window, operation) {
    if (Array.isArray(operation)) {
        operation.forEach(function(subOperation) {
            operations.apply(window, subOperation)
        })
    } else {
        window.doOperation(operation)
    }
}

operations.moveToHalfLeft = function() {
    return slate.operation('move', {
        x: 'screenOriginX',
        y: 'screenOriginY',
        width: 'screenSizeX / 2',
        height: 'screenSizeY'
    })
}

operations.moveToHalfRight = function() {
    return slate.operation('move', {
        x: 'screenOriginX + screenSizeX / 2',
        y: 'screenOriginY',
        width: 'screenSizeX / 2',
        height: 'screenSizeY'
    })
}

operations.maximize = function() {
    return slate.operation('move', {
        x: 'screenOriginX',
        y: 'screenOriginY',
        width: 'screenSizeX',
        height: 'screenSizeY'
    })
}

operations.pad = function(top, right, bottom, left) {
    var xPadding = right + left
    var yPadding = top + bottom
    return [
        slate.operation('resize', {width: '-' + xPadding, height: '-' + yPadding}),
        slate.operation('nudge', {x: '+' + left, y: '+' + top})
    ]
}

// Application operation by screen count

var appsOperationsByScreenCount = {
    'Google Chrome': {
        1: operations.maximize(),
        2: [
            slate.operation('throw', {screen: screens.thunderbolt}),
            operations.moveToHalfLeft(),
            operations.pad(windowMargin, windowMargin / 2, windowMargin, windowMargin)
        ]
    },
    iTerm: {
        1: [
            operations.maximize(),
            operations.pad(windowMargin, windowMargin, windowMargin, windowMargin),
        ],
        2: [
            slate.operation('throw', {screen: screens.thunderbolt}),
            operations.moveToHalfRight(),
            operations.pad(windowMargin, windowMargin, windowMargin, windowMargin / 2)
        ]
    }
}

var refresh = function() {
    var screenCount = slate.screenCount()
    slate.eachApp(function(app) {
        var appOperationsByScreenCount = appsOperationsByScreenCount[app.name()] || []
        var appOperations = appOperationsByScreenCount[screenCount] || []
        app.eachWindow(function(window) {
            operations.apply(window, appOperations)
        })
    })
}

slate.on('screenConfigurationChanged', refresh)

refresh()

//

slate.bind(getKeystroke('r'), slate.operation('relaunch'))

slate.log('Config loaded')
<commit_msg>Include Firefox<commit_after>slate.log('Loading config')

var getKeystroke = function(key) {
    return key + ':ctrl,shift'
}

var screens = {
    laptop: '1280x800',
    thunderbolt: '2560x1440'
}

// Operations

var operations = {}
var windowMargin = 20

/**
 * Applies the operation or list of operations
 */
operations.apply = function(window, operation) {
    if (Array.isArray(operation)) {
        operation.forEach(function(subOperation) {
            operations.apply(window, subOperation)
        })
    } else {
        window.doOperation(operation)
    }
}

operations.moveToHalfLeft = function() {
    return slate.operation('move', {
        x: 'screenOriginX',
        y: 'screenOriginY',
        width: 'screenSizeX / 2',
        height: 'screenSizeY'
    })
}

operations.moveToHalfRight = function() {
    return slate.operation('move', {
        x: 'screenOriginX + screenSizeX / 2',
        y: 'screenOriginY',
        width: 'screenSizeX / 2',
        height: 'screenSizeY'
    })
}

operations.maximize = function() {
    return slate.operation('move', {
        x: 'screenOriginX',
        y: 'screenOriginY',
        width: 'screenSizeX',
        height: 'screenSizeY'
    })
}

operations.pad = function(top, right, bottom, left) {
    var xPadding = right + left
    var yPadding = top + bottom
    return [
        slate.operation('resize', {width: '-' + xPadding, height: '-' + yPadding}),
        slate.operation('nudge', {x: '+' + left, y: '+' + top})
    ]
}

// Application operation by screen count

var browserOperations = {
    1: operations.maximize(),
    2: [
        slate.operation('throw', {screen: screens.thunderbolt}),
        operations.moveToHalfLeft(),
        operations.pad(windowMargin, windowMargin / 2, windowMargin, windowMargin)
    ]
};

var appsOperationsByScreenCount = {
    'Google Chrome': browserOperations,
    'Firefox': browserOperations,
    iTerm: {
        1: [
            operations.maximize(),
            operations.pad(windowMargin, windowMargin, windowMargin, windowMargin),
        ],
        2: [
            slate.operation('throw', {screen: screens.thunderbolt}),
            operations.moveToHalfRight(),
            operations.pad(windowMargin, windowMargin, windowMargin, windowMargin / 2)
        ]
    }
}

var refresh = function() {
    var screenCount = slate.screenCount()
    slate.eachApp(function(app) {
        var appOperationsByScreenCount = appsOperationsByScreenCount[app.name()] || []
        var appOperations = appOperationsByScreenCount[screenCount] || []
        app.eachWindow(function(window) {
            operations.apply(window, appOperations)
        })
    })
}

slate.on('screenConfigurationChanged', refresh)

refresh()

//

slate.bind(getKeystroke('r'), slate.operation('relaunch'))

slate.log('Config loaded')
<|endoftext|>


<commit_before>// Backbone Models and Collections to be used both client/server side.
// Note that these models are read-only - no `PUT/POST/DELETE` expected.

// Requires for the server-side context. *TODO* Note that `var` is omitted here
// because even within the `if()` IE will wipe globally defined variables if
// `var` is included, leaving us with broken objects.
if (typeof require !== 'undefined') {
    _ = require('underscore')._,
    Backbone = require('backbone.js'),
    Bones = require('bones');
}

var Bones = Bones || {};
Bones.models = Bones.models || {};

// Tileset
// ---
// A single tileset, corresponding to an `.mbtiles` file. `model.id` is the
// file basename, e.g. `foo.mbtiles` has an `id` of `foo`.
Bones.models.Tileset = Backbone.Model.extend({
    initialize: function(attributes) {
        Backbone.Model.prototype.initialize.call(this, attributes);
        // Convert representation of baselayer into a true Tileset model.
        if (typeof this.get('baselayer') !== 'undefined') {
            this.set({ baselayer: new Tileset(this.get('baselayer')) });
        }
    },
    parse: function(response){
        var model = Backbone.Model.prototype.parse.call(this, response);
        // Convert representation of baselayer into a true Tileset model.
        if (typeof model.baselayer !== 'undefined') {
            model.baselayer = new Tileset(model.baselayer);
        }
        return model;
    },
    url: function() {
        return '/api/Tileset/' + this.id;
    },
    // Return the base URLs of TileStream tile servers including a single
    // trailing slash, e.g. http://localhost:8889/ or http://mapbox/tilestream/
    // in an Array.
    layerURL: function() {
        // Servers defined in `Bones.settings`.
        if (Bones.settings.tileHost.length) {
            return Bones.settings.tileHost;
        // Autodetect server from window object.
        } else if (window.location && window.location.hostname) {
            // Attempt to autodetect URL.
            var baseURL = window.location.protocol + '//' + window.location.hostname + ':' + Bones.settings.tilePort;
            var args = window.location.pathname.split('/');
            // Path already ends with trailing slash.
            if (args[args.length - 1] === '') {
                return [baseURL + args.join('/')];
            // index.html or similar trailing filename.
            } else if (args[args.length - 1].indexOf('.') !== -1) {
                args.pop();
                return [baseURL + args.join('/') + '/'];
            // Path beyond domain.
            } else {
                return [baseURL + args.join('/') + '/'];
            }
        // Server side, *TODO* needs a solution.
        } else {
            return ['http://localhost:9000/'];
        }
    },
    // Get ZXY of tile of tileset's center and minzoom. From [OSM wiki][1].
    // [1]: http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#lon.2Flat_to_tile_numbers_2
    toZXY: function() {
        var center = this.get('center');
        var z = this.get('minzoom');
        var lat_rad = center.lat * Math.PI / 180 * -1; // -1 for TMS (flipped from OSM)
        var x = parseInt((center.lon + 180.0) / 360.0 * Math.pow(2, z));
        var y = parseInt((1.0 - Math.log(Math.tan(lat_rad) + (1 / Math.cos(lat_rad))) / Math.PI) / 2.0 * Math.pow(2, z));
        return [z, x, y];
    },
    thumb: function(zxy) {
        zxy = zxy || this.toZXY();
        return this.layerURL()[0] + ['1.0.0', this.get('id'), zxy[0], zxy[1], zxy[2]].join('/') + '.png';
    }
});

// Tilesets
// --------
// Collection of all tileset models.
Bones.models.Tilesets = Backbone.Collection.extend({
    model: Bones.models.Tileset,
    url: '/api/Tileset'
});

(typeof module !== 'undefined') && (module.exports = Bones.models);

<commit_msg>Fix stale hardcoded port.<commit_after>// Backbone Models and Collections to be used both client/server side.
// Note that these models are read-only - no `PUT/POST/DELETE` expected.

// Requires for the server-side context. *TODO* Note that `var` is omitted here
// because even within the `if()` IE will wipe globally defined variables if
// `var` is included, leaving us with broken objects.
if (typeof require !== 'undefined') {
    _ = require('underscore')._,
    Backbone = require('backbone.js'),
    Bones = require('bones');
}

var Bones = Bones || {};
Bones.models = Bones.models || {};

// Tileset
// ---
// A single tileset, corresponding to an `.mbtiles` file. `model.id` is the
// file basename, e.g. `foo.mbtiles` has an `id` of `foo`.
Bones.models.Tileset = Backbone.Model.extend({
    initialize: function(attributes) {
        Backbone.Model.prototype.initialize.call(this, attributes);
        // Convert representation of baselayer into a true Tileset model.
        if (typeof this.get('baselayer') !== 'undefined') {
            this.set({ baselayer: new Tileset(this.get('baselayer')) });
        }
    },
    parse: function(response){
        var model = Backbone.Model.prototype.parse.call(this, response);
        // Convert representation of baselayer into a true Tileset model.
        if (typeof model.baselayer !== 'undefined') {
            model.baselayer = new Tileset(model.baselayer);
        }
        return model;
    },
    url: function() {
        return '/api/Tileset/' + this.id;
    },
    // Return the base URLs of TileStream tile servers including a single
    // trailing slash, e.g. http://localhost:8889/ or http://mapbox/tilestream/
    // in an Array.
    layerURL: function() {
        // Servers defined in `Bones.settings`.
        if (Bones.settings.tileHost.length) {
            return Bones.settings.tileHost;
        // Autodetect server from window object.
        } else if (window.location && window.location.hostname) {
            // Attempt to autodetect URL.
            var baseURL = window.location.protocol + '//' + window.location.hostname + ':' + Bones.settings.tilePort;
            var args = window.location.pathname.split('/');
            // Path already ends with trailing slash.
            if (args[args.length - 1] === '') {
                return [baseURL + args.join('/')];
            // index.html or similar trailing filename.
            } else if (args[args.length - 1].indexOf('.') !== -1) {
                args.pop();
                return [baseURL + args.join('/') + '/'];
            // Path beyond domain.
            } else {
                return [baseURL + args.join('/') + '/'];
            }
        // Server side, *TODO* needs a solution.
        } else {
            return ['http://localhost:8888/'];
        }
    },
    // Get ZXY of tile of tileset's center and minzoom. From [OSM wiki][1].
    // [1]: http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#lon.2Flat_to_tile_numbers_2
    toZXY: function() {
        var center = this.get('center');
        var z = this.get('minzoom');
        var lat_rad = center.lat * Math.PI / 180 * -1; // -1 for TMS (flipped from OSM)
        var x = parseInt((center.lon + 180.0) / 360.0 * Math.pow(2, z));
        var y = parseInt((1.0 - Math.log(Math.tan(lat_rad) + (1 / Math.cos(lat_rad))) / Math.PI) / 2.0 * Math.pow(2, z));
        return [z, x, y];
    },
    thumb: function(zxy) {
        zxy = zxy || this.toZXY();
        return this.layerURL()[0] + ['1.0.0', this.get('id'), zxy[0], zxy[1], zxy[2]].join('/') + '.png';
    }
});

// Tilesets
// --------
// Collection of all tileset models.
Bones.models.Tilesets = Backbone.Collection.extend({
    model: Bones.models.Tileset,
    url: '/api/Tileset'
});

(typeof module !== 'undefined') && (module.exports = Bones.models);

<|endoftext|>


<commit_before>'use strict';

System.register('flarum/auth/twitter/components/TwitterSettingsModal', ['flarum/components/SettingsModal'], function (_export, _context) {
  "use strict";

  var SettingsModal, TwitterSettingsModal;
  return {
    setters: [function (_flarumComponentsSettingsModal) {
      SettingsModal = _flarumComponentsSettingsModal.default;
    }],
    execute: function () {
      TwitterSettingsModal = function (_SettingsModal) {
        babelHelpers.inherits(TwitterSettingsModal, _SettingsModal);

        function TwitterSettingsModal() {
          babelHelpers.classCallCheck(this, TwitterSettingsModal);
          return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(TwitterSettingsModal).apply(this, arguments));
        }

        babelHelpers.createClass(TwitterSettingsModal, [{
          key: 'className',
          value: function className() {
            return 'TwitterSettingsModal Modal--small';
          }
        }, {
          key: 'title',
          value: function title() {
            return app.translator.trans('flarum-auth-twitter.admin.twitter_settings.title');
          }
        }, {
          key: 'form',
          value: function form() {
            return [m(
              'div',
              { className: 'Form-group' },
              m(
                'label',
                null,
                app.translator.trans('flarum-auth-twitter.admin.twitter_settings.api_key_label')
              ),
              m('input', { className: 'FormControl', bidi: this.setting('flarum-auth-twitter.api_key') })
            ), m(
              'div',
              { className: 'Form-group' },
              m(
                'label',
                null,
                app.translator.trans('flarum-auth-twitter.admin.twitter_settings.api_secret_label')
              ),
              m('input', { className: 'FormControl', bidi: this.setting('flarum-auth-twitter.api_secret') })
            )];
          }
        }]);
        return TwitterSettingsModal;
      }(SettingsModal);

      _export('default', TwitterSettingsModal);
    }
  };
});;
'use strict';

System.register('flarum/auth/twitter/main', ['flarum/app', 'flarum/auth/twitter/components/TwitterSettingsModal'], function (_export, _context) {
  "use strict";

  var app, TwitterSettingsModal;
  return {
    setters: [function (_flarumApp) {
      app = _flarumApp.default;
    }, function (_flarumAuthTwitterComponentsTwitterSettingsModal) {
      TwitterSettingsModal = _flarumAuthTwitterComponentsTwitterSettingsModal.default;
    }],
    execute: function () {

      app.initializers.add('flarum-auth-twitter', function () {
        app.extensionSettings['flarum-auth-twitter'] = function () {
          return app.modal.show(new TwitterSettingsModal());
        };
      });
    }
  };
});<commit_msg>Recompile JS<commit_after>'use strict';

System.register('flarum/auth/twitter/components/TwitterSettingsModal', ['flarum/components/SettingsModal'], function (_export, _context) {
  "use strict";

  var SettingsModal, TwitterSettingsModal;
  return {
    setters: [function (_flarumComponentsSettingsModal) {
      SettingsModal = _flarumComponentsSettingsModal.default;
    }],
    execute: function () {
      TwitterSettingsModal = function (_SettingsModal) {
        babelHelpers.inherits(TwitterSettingsModal, _SettingsModal);

        function TwitterSettingsModal() {
          babelHelpers.classCallCheck(this, TwitterSettingsModal);
          return babelHelpers.possibleConstructorReturn(this, (TwitterSettingsModal.__proto__ || Object.getPrototypeOf(TwitterSettingsModal)).apply(this, arguments));
        }

        babelHelpers.createClass(TwitterSettingsModal, [{
          key: 'className',
          value: function className() {
            return 'TwitterSettingsModal Modal--small';
          }
        }, {
          key: 'title',
          value: function title() {
            return app.translator.trans('flarum-auth-twitter.admin.twitter_settings.title');
          }
        }, {
          key: 'form',
          value: function form() {
            return [m(
              'div',
              { className: 'Form-group' },
              m(
                'label',
                null,
                app.translator.trans('flarum-auth-twitter.admin.twitter_settings.api_key_label')
              ),
              m('input', { className: 'FormControl', bidi: this.setting('flarum-auth-twitter.api_key') })
            ), m(
              'div',
              { className: 'Form-group' },
              m(
                'label',
                null,
                app.translator.trans('flarum-auth-twitter.admin.twitter_settings.api_secret_label')
              ),
              m('input', { className: 'FormControl', bidi: this.setting('flarum-auth-twitter.api_secret') })
            )];
          }
        }]);
        return TwitterSettingsModal;
      }(SettingsModal);

      _export('default', TwitterSettingsModal);
    }
  };
});;
'use strict';

System.register('flarum/auth/twitter/main', ['flarum/app', 'flarum/auth/twitter/components/TwitterSettingsModal'], function (_export, _context) {
  "use strict";

  var app, TwitterSettingsModal;
  return {
    setters: [function (_flarumApp) {
      app = _flarumApp.default;
    }, function (_flarumAuthTwitterComponentsTwitterSettingsModal) {
      TwitterSettingsModal = _flarumAuthTwitterComponentsTwitterSettingsModal.default;
    }],
    execute: function () {

      app.initializers.add('flarum-auth-twitter', function () {
        app.extensionSettings['flarum-auth-twitter'] = function () {
          return app.modal.show(new TwitterSettingsModal());
        };
      });
    }
  };
});<|endoftext|>


<commit_before>// Fluxex extra action

module.exports = {
    redirect: function (url) {
        if (!url) {
            throw new Error('call .redirect() without url!');
        }
        window.location.href = url;
    }
};
<commit_msg>lint fix<commit_after>// Fluxex extra action

module.exports = {
    redirect: function (url) {
        if (!url) {
            throw new Error('call .redirect() without url!');
        }
        /*global window*/
        window.location.href = url;
    }
};
<|endoftext|>


<commit_before>
function start() {
  console.log("Request handler 'start' was called.");
  return "Hello Start";
}

function upload() {
  console.log("Request handler 'upload' was called.");
  return "Hello Upload";
}

exports.start = start;
exports.upload = upload;<commit_msg>fixed milliSeconds camel case, the 10 second wait experiment now works<commit_after>
function start() {
  console.log("Request handler 'start' was called.");

  function sleep(milliSeconds) {
    var startTime = new Date().getTime();
    while (new Date().getTime() < startTime + milliSeconds);
  }

  sleep(10000);
  return "Hello Start";
}

function upload() {
  console.log("Request handler 'upload' was called.");
  return "Hello Upload";
}

exports.start = start;
exports.upload = upload;<|endoftext|>


<commit_before>define(["Tone/core/Tone", "Tone/component/LFO", "Tone/component/Filter", "Tone/effect/StereoEffect"],
function(Tone){

	"use strict";

	/**
	 *  @class A Phaser effect. inspiration from https://github.com/Dinahmoe/tuna/
	 *
	 *	@extends {Tone.StereoEffect}
	 *	@constructor
	 *	@param {number|Object} [rate=0.5] the speed of the phasing
	 *	@param {number} [depth=10] the depth of the effect
	 *	@param {number} [baseFrequency=400] the base frequency of the filters
	 */
	Tone.Phaser = function(){

		//set the defaults
		var options = this.optionsObject(arguments, ["rate", "depth", "baseFrequency"], Tone.Phaser.defaults);
		Tone.StereoEffect.call(this, options);

		/**
		 *  the lfo which controls the frequency on the left side
		 *  @type {Tone.LFO}
		 *  @private
		 */
		this._lfoL = new Tone.LFO(options.rate, 0, 1);

		/**
		 *  the lfo which controls the frequency on the right side
		 *  @type {Tone.LFO}
		 *  @private
		 */
		this._lfoR = new Tone.LFO(options.rate, 0, 1);
		this._lfoR.setPhase(180);

		/**
		 *  the base modulation frequency
		 *  @type {number}
		 *  @private
		 */
		this._baseFrequency = options.baseFrequency;

		/**
		 *  the depth of the phasing
		 *  @type {number}
		 *  @private
		 */
		this._depth = options.depth;

		/**
		 *  the array of filters for the left side
		 *  @type {Array.<Tone.Filter>}
		 *  @private
		 */
		this._filtersL = this._makeFilters(options.stages, this._lfoL, options.Q);

		/**
		 *  the array of filters for the left side
		 *  @type {Array.<Tone.Filter>}
		 *  @private
		 */
		this._filtersR = this._makeFilters(options.stages, this._lfoR, options.Q);

		//connect them up
		this.effectSendL.connect(this._filtersL[0]);
		this.effectSendR.connect(this._filtersR[0]);
		this._filtersL[options.stages - 1].connect(this.effectReturnL);
		this._filtersR[options.stages - 1].connect(this.effectReturnR);
		this.effectSendL.connect(this.effectReturnL);
		this.effectSendR.connect(this.effectReturnR);
		//control the frequency with one LFO
		this._lfoL.frequency.connect(this._lfoR.frequency);
		//set the options
		this.setBaseFrequency(options.baseFrequency);
		this.setDepth(options.depth);
		this.setRate(options.rate);
		//start the lfo
		this._lfoL.start();
		this._lfoR.start();
	};

	Tone.extend(Tone.Phaser, Tone.StereoEffect);

	/**
	 *  defaults
	 *  @static
	 *  @type {object}
	 */
	Tone.Phaser.defaults = {
		"rate" : 0.5,
		"depth" : 10,
		"stages" : 4,
		"Q" : 100,
		"baseFrequency" : 400,
	};

	/**
	 *  @param {number} stages
	 *  @returns {Array} the number of filters all connected together
	 *  @private
	 */
	Tone.Phaser.prototype._makeFilters = function(stages, connectToFreq, Q){
		var filters = new Array(stages);
		//make all the filters
		for (var i = 0; i < stages; i++){
			var filter = this.context.createBiquadFilter();
			filter.type = "allpass";
			filter.Q.value = Q;
			connectToFreq.connect(filter.frequency);
			filters[i] = filter;
		}
		this.connectSeries.apply(this, filters);
		return filters;
	};

	/**
	 *  set the depth of the chorus
	 *  @param {number} depth
	 */
	Tone.Phaser.prototype.setDepth = function(depth){
		this._depth = depth;
		var max = this._baseFrequency + this._baseFrequency * depth;
		this._lfoL.setMax(max);
		this._lfoR.setMax(max);
	};

	/**
	 *  set the base frequency of the filters
	 *  @param {number} freq
	 */
	Tone.Phaser.prototype.setBaseFrequency = function(freq){
		this._baseFrequency = freq;
		this._lfoL.setMin(freq);
		this._lfoR.setMin(freq);
		this.setDepth(this._depth);
	};

	/**
	 *  set the phaser rate
	 *  @param {number} rate in hertz
	 */
	Tone.Phaser.prototype.setRate = function(rate){
		this._lfoL.setFrequency(rate);
	};

	/**
	 *  bulk setter
	 *  @param {object} params
	 */
	Tone.Phaser.prototype.set = function(params){
		if (!this.isUndef(params.rate)) this.setRate(params.rate);
		if (!this.isUndef(params.baseFrequency)) this.setBaseFrequency(params.baseFrequency);
		if (!this.isUndef(params.depth)) this.setDepth(params.depth);
		Tone.StereoEffect.prototype.set.call(this, params);
	};

	/**
	 *  clean up
	 */
	Tone.Phaser.prototype.dispose = function(){
		Tone.StereoEffect.prototype.dispose.call(this);
		this._lfoL.dispose();
		this._lfoL = null;
		this._lfoR.dispose();
		this._lfoR = null;
		for (var i = 0; i < this._filtersL.length; i++){
			this._filtersL[i].disconnect();
			this._filtersL[i] = null;
		}
		this._filtersL = null;
		for (var j = 0; j < this._filtersR.length; j++){
			this._filtersR[j].disconnect();
			this._filtersR[j] = null;
		}
		this._filtersR = null;
	};

	return Tone.Phaser;
});<commit_msg>Phaser getter functions<commit_after>define(["Tone/core/Tone", "Tone/component/LFO", "Tone/component/Filter", "Tone/effect/StereoEffect"],
function(Tone){

	"use strict";

	/**
	 *  @class A Phaser effect. inspiration from https://github.com/Dinahmoe/tuna/
	 *
	 *	@extends {Tone.StereoEffect}
	 *	@constructor
	 *	@param {number|Object} [rate=0.5] the speed of the phasing
	 *	@param {number} [depth=10] the depth of the effect
	 *	@param {number} [baseFrequency=400] the base frequency of the filters
	 */
	Tone.Phaser = function(){

		//set the defaults
		var options = this.optionsObject(arguments, ["rate", "depth", "baseFrequency"], Tone.Phaser.defaults);
		Tone.StereoEffect.call(this, options);

		/**
		 *  the lfo which controls the frequency on the left side
		 *  @type {Tone.LFO}
		 *  @private
		 */
		this._lfoL = new Tone.LFO(options.rate, 0, 1);

		/**
		 *  the lfo which controls the frequency on the right side
		 *  @type {Tone.LFO}
		 *  @private
		 */
		this._lfoR = new Tone.LFO(options.rate, 0, 1);
		this._lfoR.setPhase(180);

		/**
		 *  the base modulation frequency
		 *  @type {number}
		 *  @private
		 */
		this._baseFrequency = options.baseFrequency;

		/**
		 *  the depth of the phasing
		 *  @type {number}
		 *  @private
		 */
		this._depth = options.depth;

		/**
		 *  the array of filters for the left side
		 *  @type {Array.<Tone.Filter>}
		 *  @private
		 */
		this._filtersL = this._makeFilters(options.stages, this._lfoL, options.Q);

		/**
		 *  the array of filters for the left side
		 *  @type {Array.<Tone.Filter>}
		 *  @private
		 */
		this._filtersR = this._makeFilters(options.stages, this._lfoR, options.Q);

		//connect them up
		this.effectSendL.connect(this._filtersL[0]);
		this.effectSendR.connect(this._filtersR[0]);
		this._filtersL[options.stages - 1].connect(this.effectReturnL);
		this._filtersR[options.stages - 1].connect(this.effectReturnR);
		this.effectSendL.connect(this.effectReturnL);
		this.effectSendR.connect(this.effectReturnR);
		//control the frequency with one LFO
		this._lfoL.frequency.connect(this._lfoR.frequency);
		//set the options
		this.setBaseFrequency(options.baseFrequency);
		this.setDepth(options.depth);
		this.setRate(options.rate);
		//start the lfo
		this._lfoL.start();
		this._lfoR.start();
	};

	Tone.extend(Tone.Phaser, Tone.StereoEffect);

	/**
	 *  defaults
	 *  @static
	 *  @type {object}
	 */
	Tone.Phaser.defaults = {
		"rate" : 0.5,
		"depth" : 10,
		"stages" : 4,
		"Q" : 100,
		"baseFrequency" : 400,
	};

	/**
	 *  @param {number} stages
	 *  @returns {Array} the number of filters all connected together
	 *  @private
	 */
	Tone.Phaser.prototype._makeFilters = function(stages, connectToFreq, Q){
		var filters = new Array(stages);
		//make all the filters
		for (var i = 0; i < stages; i++){
			var filter = this.context.createBiquadFilter();
			filter.type = "allpass";
			filter.Q.value = Q;
			connectToFreq.connect(filter.frequency);
			filters[i] = filter;
		}
		this.connectSeries.apply(this, filters);
		return filters;
	};

	/**
	 *  set the depth of the chorus
	 *  @param {number} depth
	 */
	Tone.Phaser.prototype.setDepth = function(depth){
		this._depth = depth;
		var max = this._baseFrequency + this._baseFrequency * depth;
		this._lfoL.setMax(max);
		this._lfoR.setMax(max);
	};

	/**
	 * @return {number} the depth of the chorus
	 */
	Tone.Phaser.prototype.getDepth = function(){
		return this._depth;
	};

	/**
	 *  set the base frequency of the filters
	 *  @param {number} freq
	 */
	Tone.Phaser.prototype.setBaseFrequency = function(freq){
		this._baseFrequency = freq;
		this._lfoL.setMin(freq);
		this._lfoR.setMin(freq);
		this.setDepth(this._depth);
	};

	/**
	 * @return {number} the base frequency of the filters
	 */
	Tone.Phaser.prototype.getBaseFrequency = function(){
		return this._baseFrequency;
	};

	/**
	 *  set the phaser rate
	 *  @param {number} rate in hertz
	 */
	Tone.Phaser.prototype.setRate = function(rate){
		this._lfoL.setFrequency(rate);
	};

	/**
	 * @return {number} the phaser rate
	 */
	Tone.Phaser.prototype.getRate = function(){
		return this._lfoL.getFrequency();
	};

	/**
	 *  bulk setter
	 *  @param {object} params
	 */
	Tone.Phaser.prototype.set = function(params){
		if (!this.isUndef(params.rate)) this.setRate(params.rate);
		if (!this.isUndef(params.baseFrequency)) this.setBaseFrequency(params.baseFrequency);
		if (!this.isUndef(params.depth)) this.setDepth(params.depth);
		Tone.StereoEffect.prototype.set.call(this, params);
	};

	/**
	 *  clean up
	 */
	Tone.Phaser.prototype.dispose = function(){
		Tone.StereoEffect.prototype.dispose.call(this);
		this._lfoL.dispose();
		this._lfoL = null;
		this._lfoR.dispose();
		this._lfoR = null;
		for (var i = 0; i < this._filtersL.length; i++){
			this._filtersL[i].disconnect();
			this._filtersL[i] = null;
		}
		this._filtersL = null;
		for (var j = 0; j < this._filtersR.length; j++){
			this._filtersR[j].disconnect();
			this._filtersR[j] = null;
		}
		this._filtersR = null;
	};

	return Tone.Phaser;
});<|endoftext|>


<commit_before>/**
 * jQuery UI custom widget: data range.
 * Author:
 *   Soichiro Miki
 * Depends:
 *   jquery-ui-1.8.x.js with Datepicker widget (or newer)
 *   layout.css
 */

$.widget('ui.daterange', {
	options: {
		dash: ' — ',
		icon: 'images/calendar_view_month.png',
		dateFormat: 'yy-mm-dd'
	},

	_types: [
		{label: 'all', from: '', to: '' },
		{label: 'today', from: '0', to: '0', stripe: true },
		{label: 'yesterday', from: '-1d', to: '-1d', stripe: true},
		{label: 'last 1 week', from: '-7d', to: '0' },
		{label: 'last 1 month', from: '-1m', to: '0'},
		{label: 'last 3 months', from: '-3m', to: '0'},
		{label: 'last 6 months', from: '-6m', to: '0'},
		{label: 'last 1 year', from: '-12m', to: '0' },
		{label: 'custom...', custom: true, stripe: true }
	],

	_create: function()
	{
		var self = this;
		var root = this.element.empty().addClass('ui-daterange')

		var datePickerOpts = {
			buttonText: 'select',
			buttonImage: self.options.icon,
			buttonImageOnly: true,
			showOn: 'button',
			constrainInput: false,
			dateFormat: this.options.dateFormat,
			changeMonth: true,
			changeYear: true
		};

		var refresh = function()
		{
			var selected = $('option:selected', kindSelect);
			var info = selected.data('info');
			if (info.custom)
			{
				$.each([from, to], function() {
					$(this).removeAttr('disabled')
					.datepicker('enable')
					.datepicker('option', {maxDate: '', minDate: ''});
				});
			}
			else
			{
				$.each([[from, info.from], [to, info.to]], function() {
					var target = $(this[0]);
					var value = this[1];
					if (value)
					{
						target.val(self._format(self._calcDateDiff(value)));
					}
					else
						target.val('');
					target.attr('disabled', 'disabled').datepicker('disable');
				});
			}
		};

		var kindSelect = $('<select>')
		.addClass('ui-daterange-kind')
		.appendTo(root);
		kindSelect.change(refresh);
		for (var i = 0; i < self._types.length; i++)
		{
			var item = self._types[i];
			var opt = $('<option>')
			.data('info', item)
			.attr('value', item.label)
			.append(item.label)
			.appendTo(kindSelect);
			if (item.stripe)
				opt.addClass('ui-daterange-stripe')
		}

		var customField = $('<span>')
		.addClass('ui-daterange-custom')
		.appendTo(root);

		// 'FROM' field
		var from = $('<input type="text">')
		.addClass('ui-daterange-from')
		.appendTo(customField)
		.datepicker(datePickerOpts)
		.datepicker('option', 'onSelect', function(text, inst) {
			to.datepicker('option', 'minDate', from.val());
		});
		if (this.options.fromName)
			from.attr('name', this.options.fromName);

		// ' - '
		customField.append(self.options.dash);

		// 'TO' field
		var to = $('<input type="text">')
		.addClass('ui-daterange-to')
		.appendTo(customField)
		.datepicker(datePickerOpts)
		.datepicker('option', 'onSelect', function(text, inst) {
			from.datepicker('option', 'maxDate', to.val());
		});
		if (this.options.toName)
			to.attr('name', this.options.toName);

		refresh();
	},

	_calcDateDiff: function(diff, from)
	{
		var m = diff.match(/^(\-?)(\d+)([dwmy]?)$/);
		if (!m) return null;

		var dt = new Date();
		if (from instanceof Date) dt = from;
		if (m[3] == 'd' || m[3] == 'w' || !m[3])
		{
			var days = m[3] == 'w' ? m[2] * 7 : m[2];
			if (m[1]) days = -days;
			dt.setTime(dt.getTime() + 86400000 * days);
			return dt;
		}
		else
		{
			var months = m[3] == 'y' ? m[2] * 12 : m[2];
			if (m[1]) months = -months;
			var year = dt.getFullYear();
			var month = dt.getMonth() + parseInt(months);
			var date = dt.getDate();
			// round date in such a way that '1 month before 2011/Mar/30' is
			// 2011/Feb/28
			var lastDayOfTargetMonth = new Date(year, month + 1, 0).getDate();
			if (date > lastDayOfTargetMonth) date = lastDayOfTargetMonth;
			return new Date(year, month, date);
		}
	},

	_format: function(date)
	{
		return $.datepicker.formatDate(this.options.dateFormat, date);
	},

	_setOptions: function(key, value, animated)
	{
		$.Widget.prototype._setOption.apply(this, arguments);
	}
});<commit_msg>daterange: Add getter/setter for values managed by the widget<commit_after>/**
 * jQuery UI custom widget: data range.
 * Author:
 *   Soichiro Miki
 * Depends:
 *   jquery-ui-1.8.x.js with Datepicker widget (or newer)
 *   layout.css
 */

$.widget('ui.daterange', {
	options: {
		dash: ' — ',
		icon: 'images/calendar_view_month.png',
		dateFormat: 'yy-mm-dd',
		fromDate: null,
		toDate: null,
		kind: null
	},

	_types: [
		{label: 'all', from: '', to: '' },
		{label: 'today', from: '0', to: '0', stripe: true },
		{label: 'yesterday', from: '-1d', to: '-1d', stripe: true},
		{label: 'last 1 week', from: '-7d', to: '0' },
		{label: 'last 1 month', from: '-1m', to: '0'},
		{label: 'last 3 months', from: '-3m', to: '0'},
		{label: 'last 6 months', from: '-6m', to: '0'},
		{label: 'last 1 year', from: '-12m', to: '0' },
		{label: 'custom...', custom: true, stripe: true }
	],

	_create: function()
	{
		var self = this;
		var root = this.element.empty().addClass('ui-daterange')

		var refresh = function()
		{
			var selected = $('option:selected', kindSelect);
			var info = selected.data('info');
			if (info.custom)
			{
				$.each([from, to], function() {
					$(this).removeAttr('disabled')
					.datepicker('enable')
					.datepicker('option', {maxDate: '', minDate: ''});
				});
			}
			else
			{
				$.each([[from, info.from], [to, info.to]], function() {
					var target = $(this[0]);
					var value = this[1];
					if (value)
					{
						target.val(self._format(self._calcDateDiff(value)));
					}
					else
						target.val('');
					target.attr('disabled', 'disabled').datepicker('disable');
				});
			}
			self._updateInternalValue();
		};

		var kindSelect = $('<select>')
		.addClass('ui-daterange-kind')
		.appendTo(root);
		kindSelect.change(refresh);
		for (var i = 0; i < self._types.length; i++)
		{
			var item = self._types[i];
			var opt = $('<option>')
			.data('info', item)
			.attr('value', item.label)
			.append(item.label)
			.appendTo(kindSelect);
			if (item.stripe)
				opt.addClass('ui-daterange-stripe')
		}
		self.kindSelect = kindSelect;

		var customField = $('<span>')
		.addClass('ui-daterange-custom')
		.appendTo(root);

		// 'FROM' field
		var from = self._createDateInput('ui-daterange-from').appendTo(customField);
		from.datepicker('option', 'onSelect', function(text, inst) {
			to.datepicker('option', 'minDate', from.val());
			self._updateInternalValue();
		});
		self.from = from;

		// ' - '
		customField.append(self.options.dash);

		// 'TO' field
		var to = self._createDateInput('ui-daterange-to').appendTo(customField);
		to.datepicker('option', 'onSelect', function(text, inst) {
			from.datepicker('option', 'maxDate', to.val());
			self._updateInternalValue();
		});
		self.to = to;

		refresh();
	},

	_updateInternalValue: function()
	{
		var self = this;
		self.options.fromDate = self.from.val();
		self.options.toDate = self.to.val();
		self.options.kind = self.kindSelect.val();
		// console.log('value updated', self.options.fromDate, self.options.toDate, self.options.kind);
	},

	_commitFromDate: function()
	{
		this.from.val(this.options.fromDate);
	},

	_commitToDate: function()
	{
		this.to.val(this.options.toDate);
	},

	_commitKind: function()
	{
		this.kindSelect.val(this.options.kind);
		this.options.kind = this.kindSelect.val(); // invalid assignment does not take effect
	},

	_createDateInput: function(className, name)
	{
		var self = this;
		var datePickerOpts = {
			buttonText: 'select',
			buttonImage: this.options.icon,
			buttonImageOnly: true,
			showOn: 'button',
			constrainInput: false,
			dateFormat: this.options.dateFormat,
			changeMonth: true,
			changeYear: true
		};

		var result = $('<input type="text">');
		result
			.addClass(className)
			.datepicker(datePickerOpts)
			.change(function() { self._updateInternalValue(); })
			.keyup(function() { self._updateInternalValue(); });
		if (name)
			result.attr('name', name);
		return result;
	},

	_calcDateDiff: function(diff, from)
	{
		var m = diff.match(/^(\-?)(\d+)([dwmy]?)$/);
		if (!m) return null;

		var dt = new Date();
		if (from instanceof Date) dt = from;
		if (m[3] == 'd' || m[3] == 'w' || !m[3])
		{
			var days = m[3] == 'w' ? m[2] * 7 : m[2];
			if (m[1]) days = -days;
			dt.setTime(dt.getTime() + 86400000 * days);
			return dt;
		}
		else
		{
			var months = m[3] == 'y' ? m[2] * 12 : m[2];
			if (m[1]) months = -months;
			var year = dt.getFullYear();
			var month = dt.getMonth() + parseInt(months);
			var date = dt.getDate();
			// round date in such a way that '1 month before 2011/Mar/30' is
			// 2011/Feb/28
			var lastDayOfTargetMonth = new Date(year, month + 1, 0).getDate();
			if (date > lastDayOfTargetMonth) date = lastDayOfTargetMonth;
			return new Date(year, month, date);
		}
	},

	_format: function(date)
	{
		return $.datepicker.formatDate(this.options.dateFormat, date);
	},

	_setOption: function(key, value)
	{
		$.Widget.prototype._setOption.apply(this, arguments);
		switch (key)
		{
			case 'fromDate':
				this._commitFromDate();
				break;
			case 'toDate':
				this._commitToDate();
				break;
			case 'kind':
				this._commitKind();
				break;
		}
	}
});<|endoftext|>


<commit_before>angular.module('ui-notification',[]);

angular.module('ui-notification').value('uiNotificationTemplates','angular-ui-notification.html');

angular.module('ui-notification').factory('Notification', function(
	$timeout, uiNotificationTemplates, $http, $compile, $templateCache, $rootScope, $injector, $sce) {

	var startTop = 10;
	var startRight = 10;
	var verticalSpacing = 10;
	var horizontalSpacing = 10;
	var type = '';
	var delay = 5000;

	var messageElements = [];

	var notify = function(args, t){

		if (typeof args !== 'object'){
			args = {message:args};
		}

		args.template = args.template ? args.template : uiNotificationTemplates;
		args.delay = !angular.isUndefined(args.delay) ? args.delay : delay;
		args.type = t ? t : '';

		$http.get(args.template,{cache: $templateCache}).success(function(template) {

			var scope = $rootScope.$new();
			scope.message = $sce.trustAsHtml(args.message);
			scope.title = $sce.trustAsHtml(args.title);
			scope.t = args.type.substr(0,1);
			scope.delay = args.delay;

			if (typeof args.scope === 'object'){
				for (var key in args.scope){
					scope[key] = args.scope[key];
				}
			}

			var reposite = function() {
				var j = 0;
				var k = 0;
				var lastTop = startTop;
				var lastRight = startRight;
				for(var i = messageElements.length - 1; i >= 0; i --) {
					var element = messageElements[i];
					var elHeight = parseInt(element[0].offsetHeight);
					var elWidth = parseInt(element[0].offsetWidth);
					if ((top + elHeight) > window.innerHeight) {
						lastTop = startTop;
						k ++;
						j = 0;
					}
					var top = lastTop + (j === 0 ? 0 : verticalSpacing);
					var right = startRight + (k * (horizontalSpacing + elWidth));

					element.css('top', top + 'px');
					element.css('right', right + 'px');

					lastTop = top + elHeight;
					j ++;
				}
			};

			var templateElement = $compile(template)(scope);
			templateElement.addClass(args.type);
			templateElement.bind('webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd click', function(e){
				e = e.originalEvent || e;
				if (e.type === 'click' || (e.propertyName === 'opacity' && e.elapsedTime >= 1)){
					templateElement.remove();
					messageElements.splice(messageElements.indexOf(templateElement), 1);
					reposite();
				}
			});
			$timeout(function() {
				templateElement.addClass('killed');
			}, args.delay);

			angular.element(document.getElementsByTagName('body')).append(templateElement);
			messageElements.push(templateElement);

			$timeout(reposite);

		}).error(function(data){
			throw new Error('Template ('+args.template+') could not be loaded. ' + data);
		});

	};

	notify.config = function(args){
		startTop = args.top ? args.top : startTop;
		verticalSpacing = args.verticalSpacing ? args.verticalSpacing : verticalSpacing;
	};
	notify.primary = function() {
		this(args, '');
	};
	notify.error = function(args) {
		this(args, 'error');
	};
	notify.success = function(args) {
		this(args, 'success');
	};
	notify.info = function(args) {
		this(args, 'info');
	};
	notify.warning = function(args) {
		this(args, 'warning');
	};

	return notify;
});
<commit_msg>add clear all notify support<commit_after>angular.module('ui-notification',[]);

angular.module('ui-notification').value('uiNotificationTemplates','angular-ui-notification.html');

angular.module('ui-notification').factory('Notification', function(
	$timeout, uiNotificationTemplates, $http, $compile, $templateCache, $rootScope, $injector, $sce) {

	var startTop = 10;
	var startRight = 10;
	var verticalSpacing = 10;
	var horizontalSpacing = 10;
	var type = '';
	var delay = 5000;

	var messageElements = [];

	var notify = function(args, t){

		if (typeof args !== 'object'){
			args = {message:args};
		}

		args.template = args.template ? args.template : uiNotificationTemplates;
		args.delay = !angular.isUndefined(args.delay) ? args.delay : delay;
		args.type = t ? t : '';

		$http.get(args.template,{cache: $templateCache}).success(function(template) {

			var scope = $rootScope.$new();
			scope.message = $sce.trustAsHtml(args.message);
			scope.title = $sce.trustAsHtml(args.title);
			scope.t = args.type.substr(0,1);
			scope.delay = args.delay;

			if (typeof args.scope === 'object'){
				for (var key in args.scope){
					scope[key] = args.scope[key];
				}
			}

			var reposite = function() {
				var j = 0;
				var k = 0;
				var lastTop = startTop;
				var lastRight = startRight;
				for(var i = messageElements.length - 1; i >= 0; i --) {
					var element = messageElements[i];
					var elHeight = parseInt(element[0].offsetHeight);
					var elWidth = parseInt(element[0].offsetWidth);
					if ((top + elHeight) > window.innerHeight) {
						lastTop = startTop;
						k ++;
						j = 0;
					}
					var top = lastTop + (j === 0 ? 0 : verticalSpacing);
					var right = startRight + (k * (horizontalSpacing + elWidth));

					element.css('top', top + 'px');
					element.css('right', right + 'px');

					lastTop = top + elHeight;
					j ++;
				}
			};

			var templateElement = $compile(template)(scope);
			templateElement.addClass(args.type);
			templateElement.bind('webkitTransitionEnd oTransitionEnd otransitionend transitionend msTransitionEnd click', function(e){
				e = e.originalEvent || e;
				if (e.type === 'click' || (e.propertyName === 'opacity' && e.elapsedTime >= 1)){
					templateElement.remove();
					messageElements.splice(messageElements.indexOf(templateElement), 1);
					reposite();
				}
			});
			$timeout(function() {
				templateElement.addClass('killed');
			}, args.delay);

			angular.element(document.getElementsByTagName('body')).append(templateElement);
			messageElements.push(templateElement);

			$timeout(reposite);

		}).error(function(data){
			throw new Error('Template ('+args.template+') could not be loaded. ' + data);
		});

	};

	notify.config = function(args){
		startTop = args.top ? args.top : startTop;
		verticalSpacing = args.verticalSpacing ? args.verticalSpacing : verticalSpacing;
	};
	notify.primary = function() {
		this(args, '');
	};
	notify.error = function(args) {
		this(args, 'error');
	};
	notify.success = function(args) {
		this(args, 'success');
	};
	notify.info = function(args) {
		this(args, 'info');
	};
	notify.warning = function(args) {
		this(args, 'warning');
	};

	notify.clearAll = function() {
		var notifys = angular.element(document.getElementsByClassName('ui-notification'));

		if (notifys) {
			angular.forEach(notifys, function(notify) {
				notify.remove();
			});
		}
	};

	return notify;
});
<|endoftext|>


<commit_before>const assert = require('assert');

const MovingMedian = (arr) => {
  const N = arr.indexOf(0, 1);
  const r = [arr[0]];
  for (let i = 1; i < arr.length; i += 1) {
    r.push(getMedian(arr.slice((i + 1 - N > 0) ? i + 1 - N : 0, i + 1)));
  }
  return r.join(',');
};

const getMedian = (arr) => {
  arr.sort((a, b) => a - b); // ascending sort

  if (arr.length % 2 === 0) {
    return (arr[arr.length / 2] + arr[(arr.length / 2) - 1]) / 2;
  }
  return arr[(arr.length - 1) / 2];
};

const a1 = '5, 2, 4, 6'; // input
const r1 = '2,3,4'; // output
const t1 = MovingMedian(a1);
assert(r1, t1);

const a2 = '3, 0, 0, -2, 0, 2, 0, -2'; // input
const r2 = '0,0,0,0,0,0,0'; // output
const t2 = MovingMedian(a2);
assert(r2, t2);

// console.log(r2);
<commit_msg>add comment on solution<commit_after>// Read the array of numbers stored in arr which contains a sliding
// window size, N, as the first element in the array and the rest
// will be a list of numbers.
//
// Return the Moving Median for each element based on the element and its
// N-1 predecessors, where N is the sliding window size. The final output
// should be a string with the moving median corresponding to each entry
// in the original array separated by commas.

const assert = require('assert');

const MovingMedian = (arr) => {
  const N = arr.indexOf(0, 1);
  const r = [arr[0]];
  for (let i = 1; i < arr.length; i += 1) {
    r.push(getMedian(arr.slice((i + 1 - N > 0) ? i + 1 - N : 0, i + 1)));
  }
  return r.join(',');
};

const getMedian = (arr) => {
  arr.sort((a, b) => a - b); // ascending sort

  if (arr.length % 2 === 0) {
    return (arr[arr.length / 2] + arr[(arr.length / 2) - 1]) / 2;
  }
  return arr[(arr.length - 1) / 2];
};

const a1 = '5, 2, 4, 6'; // input
const r1 = '2,3,4'; // output
const t1 = MovingMedian(a1);
assert(r1, t1);

const a2 = '3, 0, 0, -2, 0, 2, 0, -2'; // input
const r2 = '0,0,0,0,0,0,0'; // output
const t2 = MovingMedian(a2);
assert(r2, t2);

// console.log(r2);
<|endoftext|>


<commit_before>/**
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

goog.provide('org.apache.flex.core.DataBindingBase');

/**
 * @constructor
 */
org.apache.flex.core.DataBindingBase = function() {
};

/**
 * Metadata
 *
 * @type {Object.<string, Array.<Object>>}
 */
org.apache.flex.core.DataBindingBase.prototype.FLEXJS_CLASS_INFO =
    { names: [{ name: 'DataBindingBase',
                qName: 'org.apache.flex.core.DataBindingBase'}] };

/**
 * @expose
 * @param {Object} obj The object.
 * @param {string} propName The name of the property.
 * @return {boolean} True if property exists.
 */
org.apache.flex.core.DataBindingBase.prototype.hasProperty =
    function(obj, propName) {
  if (typeof obj['get_' + propName] === 'function') {
    return true;
  }
  return (propName in obj);
};

/**
 * @expose
 * @param {Object} obj The object.
 * @param {string} propName The name of the property.
 * @return {Object} value The value of the property.
 */
org.apache.flex.core.DataBindingBase.prototype.getProperty =
    function(obj, propName) {
  if (typeof obj['get_' + propName] === 'function') {
    return obj['get_' + propName]();
  }
  return obj[propName];
};

/**
 * @expose
 * @param {Object} obj The object.
 * @param {string} propName The name of the property.
 * @param {Object} value The value of the property.
 */
org.apache.flex.core.DataBindingBase.prototype.setProperty =
function(obj, propName, value) {
  if (typeof obj['set_' + propName] === 'function') {
    obj['set_' + propName](value);
  } else {
    obj[propName] = value;
  }
};

<commit_msg>handle 'this' in databinding expressions'<commit_after>/**
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

goog.provide('org.apache.flex.core.DataBindingBase');

/**
 * @constructor
 */
org.apache.flex.core.DataBindingBase = function() {
};

/**
 * Metadata
 *
 * @type {Object.<string, Array.<Object>>}
 */
org.apache.flex.core.DataBindingBase.prototype.FLEXJS_CLASS_INFO =
    { names: [{ name: 'DataBindingBase',
                qName: 'org.apache.flex.core.DataBindingBase'}] };

/**
 * @expose
 * @param {Object} obj The object.
 * @param {string} propName The name of the property.
 * @return {boolean} True if property exists.
 */
org.apache.flex.core.DataBindingBase.prototype.hasProperty =
    function(obj, propName) {
  if (typeof obj['get_' + propName] === 'function') {
    return true;
  }
  return (propName in obj);
};

/**
 * @expose
 * @param {Object} obj The object.
 * @param {string} propName The name of the property.
 * @return {Object} value The value of the property.
 */
org.apache.flex.core.DataBindingBase.prototype.getProperty =
    function(obj, propName) {
  if (propName == 'this')
    return obj;

  if (typeof obj['get_' + propName] === 'function') {
    return obj['get_' + propName]();
  }
  return obj[propName];
};

/**
 * @expose
 * @param {Object} obj The object.
 * @param {string} propName The name of the property.
 * @param {Object} value The value of the property.
 */
org.apache.flex.core.DataBindingBase.prototype.setProperty =
function(obj, propName, value) {
  if (typeof obj['set_' + propName] === 'function') {
    obj['set_' + propName](value);
  } else {
    obj[propName] = value;
  }
};

<|endoftext|>


<commit_before>var Backbone = require('backbone'),
    $ = require('jquery');

var AdminView = Backbone.View.extend({
  el: $("#linksf"),
  template: require('templates/admin'),
  render: function() {
    console.log('template is', this.template());
    console.log('element is', $(this.el).html());
    console.log('rendering admin!');
    $(this.el).html(this.template());
    return this;
  }
});

module.exports = AdminView;
<commit_msg>remove logging<commit_after>var Backbone = require('backbone'),
    $ = require('jquery');

var AdminView = Backbone.View.extend({
  el: $("#linksf"),
  template: require('templates/admin'),
  render: function() {
    $(this.el).html(this.template());
    return this;
  }
});

module.exports = AdminView;
<|endoftext|>


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

    angular.module("mfl.gis.interceptor", [])

    .factory("mfl.gis.interceptor.headers", [function () {
        var cache_headers = {};

        var request_fxn = function(config) {
            var headers = cache_headers[config.url];
            if (_.isUndefined(headers)) {
                console.log("cache miss : ", config.url);
                return config;
            }
            console.log("cache hit : ", config.url);
            if (headers.etag_header) {
                config.headers["If-None-Match"] = headers.etag_header;
            }
            if (headers.last_modified_header) {
                config.headers["If-Modified-Since"] = headers.last_modified_header;
            }
            return config;
        };

        var response_fxn = function(response) {
            var etag = response.headers("ETag");
            var last_modified = response.headers("Last-Modified");
            var headers = {};
            if (etag) {
                headers.etag_header = etag;
            }
            if (last_modified) {
                headers.last_modified_header = last_modified;
            }
            cache_headers[response.config.url] = headers;
            return response;
        };

        return {
            "request" : request_fxn,
            "response": response_fxn
        };
    }]);

})(angular);
<commit_msg>Remove console.log statements in interceptors<commit_after>(function (angular) {
    "use strict";

    angular.module("mfl.gis.interceptor", [])

    .factory("mfl.gis.interceptor.headers", [function () {
        var cache_headers = {};

        var request_fxn = function(config) {
            var headers = cache_headers[config.url];
            if (_.isUndefined(headers)) {
                return config;
            }

            if (headers.etag_header) {
                config.headers["If-None-Match"] = headers.etag_header;
            }
            if (headers.last_modified_header) {
                config.headers["If-Modified-Since"] = headers.last_modified_header;
            }
            return config;
        };

        var response_fxn = function(response) {
            var etag = response.headers("ETag");
            var last_modified = response.headers("Last-Modified");
            var headers = {};
            if (etag) {
                headers.etag_header = etag;
            }
            if (last_modified) {
                headers.last_modified_header = last_modified;
            }
            cache_headers[response.config.url] = headers;
            return response;
        };

        return {
            "request" : request_fxn,
            "response": response_fxn
        };
    }]);

})(angular);
<|endoftext|>