<commit_before>
// internal libs
import { component, view, on } from 'src/app-decorators';

// external libs
import sinon from 'sinon';

let isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
let isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

// init special innerHTML for test
String.prototype.removeGutter = function(){
	return this.replace(/[\t\n\r]/gm, '');
}

describe('@on decorator', () => {

	describe('view.helper.registerNamespaces', () => {

		it('should create namespace object´s', () => {

			on.helper.registerNamespaces({}).should.have.containEql({
				$appDecorators: { on: { events: { local: {} } } },
				$onCreated:  { on: [] },
				$onAttached: { on: [] },
				$onDetached: { on: [] },
			});

		});

	});

	describe('view.helper', () => {

		// Mock target
		let mockTarget = {
			$appDecorators: {
				on: { events: { local: { 'some-event' : () => {} } } }
			},
			$onCreated: {
				on: []
			}
		};
		let mockFunction = function(){}

		describe('registerEvent', () => {

			it('should build event object based on registered namespaces', () => {

				let result = on.helper.registerEvent(mockTarget, 'some-other-event', mockFunction);
				result.should.have.propertyByPath('$appDecorators', 'on', 'events', 'local', 'some-other-event').equal(mockFunction);

			});

		});

		describe('registerCallback', () => {

			it('should add callback based on registered namespaces', () => {

				let result = on.helper.registerCallback('created', mockTarget, mockFunction);
				result.should.have.propertyByPath('$onCreated', 'on', 0).equal(mockFunction);

			});

		});

	});

	describe('Snack.prototype.$appDecorators.on.events', () => {

		it('should contain registered events over @on', () => {

			class Snack {
				// local scope
				@on('click .a') onClick_a() {}
				@on('click .b') onClick_b() {}
				// custom scope (window)
				@on('resize', window) onResize(){}
				@on('wheel', window) onWheel(){}
			}

			let localEvents = Snack.prototype.$appDecorators.on.events.local;
			let windowEvents = Snack.prototype.$appDecorators.on.events[window];
			let prototype = Snack.prototype;

			localEvents.should.have.propertyByPath("click .a").Function();
			localEvents.should.have.propertyByPath("click .b").Function();

			localEvents.should.have.propertyByPath("click .a").eql(prototype.onClick_a);
			localEvents.should.have.propertyByPath("click .b").eql(prototype.onClick_b);

			windowEvents.should.have.propertyByPath("resize").Array();
			windowEvents.should.have.propertyByPath("resize", 0).eql(prototype.onResize);
			windowEvents.should.have.propertyByPath("resize", 1).eql(window);

			windowEvents.should.have.propertyByPath("wheel").Array();
			windowEvents.should.have.propertyByPath("wheel", 0).eql(prototype.onWheel);
			windowEvents.should.have.propertyByPath("wheel", 1).eql(window);

			Object.keys(localEvents).should.have.length(2);
			Object.keys(windowEvents).should.have.length(2);

		});

		it('should trigger correct method if clicked', () => {

			@view(`

 A

 B

			`)
			@component()
			class Milkey {
				@on('click .a') onFoo_a() {}
				@on('click .b') onBar_b() {}
			}

			// create instane
			let milkey_1 = Milkey.create({cid: 1});

			// spy for milkey_1
			let milkey_1_clickCallbacks = milkey_1.$.eventHandler.local.getHandlers('click');
			let milkey_1_a_function_spy = sinon.spy(milkey_1_clickCallbacks[0], ".a");
			let milkey_1_b_function_spy = sinon.spy(milkey_1_clickCallbacks[1], ".b");

			// can simulate click on safari
			if(isSafari) {
				return;
			}

			// test 1
			milkey_1.querySelector('.a').click();
			milkey_1_a_function_spy.callCount.should.eql(1);
			milkey_1_b_function_spy.callCount.should.eql(0);

			// test 2
			milkey_1.querySelector('.b').click();
			milkey_1_a_function_spy.callCount.should.eql(1);
			milkey_1_b_function_spy.callCount.should.eql(1);

			// test 3
			milkey_1.querySelector('.a').click();
			milkey_1.querySelector('.b').click();
			milkey_1_a_function_spy.callCount.should.eql(2);
			milkey_1_b_function_spy.callCount.should.eql(2);

			// cleanup
			milkey_1_a_function_spy.restore();
			milkey_1_b_function_spy.restore();

		});

		it('should ensure that eventhandler has right context', () => {

			@view('
 A
', { renderedFlag: false })
			@component()
			class Hanuta {
				cid = null;
				created({cid}){
					this.cid = cid;
				}
				@on('click .a') onFoo_a() {
					this.setAttribute('cid', this.cid);
				}
			}

			if(isSafari) {
				return;
			}

			//create instances
			let hanuta_1 = Hanuta.create({cid: 1});
			let hanuta_2 = Hanuta.create({cid: 2});

			// test 1
			hanuta_2.querySelector('.a').click();
			hanuta_2.outerHTML.should.be.equal('<com-hanuta cid="2">
 A
</com-hanuta>');
			hanuta_1.outerHTML.should.be.equal('<com-hanuta>
 A
</com-hanuta>');

			// test 2
			hanuta_1.querySelector('.a').click();
			hanuta_1.outerHTML.should.be.equal('<com-hanuta cid="1">
 A
</com-hanuta>');
			hanuta_2.outerHTML.should.be.equal('<com-hanuta cid="2">
 A
</com-hanuta>');

		});

		it('should ensure that @on methods connected with base methods', () => {

			@view('
 A
')
			@component()
			class Ritter {
				baseMethod(){
				}
				@on('click .a') onFoo_a() {
					this.baseMethod();
				}
			}

			if(isSafari) {
				return;
			}

			// create instane
			let ritter = Ritter.create();

			// spy for Ritter onFoo_a
			let ritter_clickCallbacks = ritter.$.eventHandler.local.getHandlers('click');
			let ritter_function_spy = sinon.spy(ritter_clickCallbacks[0], ".a");
			// spy for Ritter baseMethod
			let ritter_baseMethod_spy = sinon.spy(Ritter.prototype, "baseMethod");

			//test
			ritter.querySelector('.a').click();
			ritter_function_spy.callCount.should.eql(1);
			ritter_baseMethod_spy.callCount.should.eql(1);

			// cleanup
			ritter_function_spy.restore();
			ritter_baseMethod_spy.restore();

		});

		it('should trigger window events but is instanec of Context and Element', () => {

			@view(`<div class="foo"></div>`)
			@component()
			class Context {

				@on('resize', window) onResize(event){
					this.callFoo();
					return this;
				}
				callFoo(){
					return this;
				}
				@on('click .foo') onClick(event){
					this.callFoo();
				}

			}

			let context = Context.create();

			let prefixName = Object.prototype.toString.call(window);
			let context_resize_Callbacks = context.$.eventHandler[`${prefixName}_resize`].getHandlers('resize');
			let onResize = context_resize_Callbacks[0][null];

			document.body.appendChild(context);

			// test instanceof Context
			should(onResize() instanceof Context).be.true();
			should(context.callFoo() instanceof Context).be.true();

			// test instance Element
			should(onResize() instanceof Element).be.true();
			should(context.callFoo() instanceof Element).be.true();

			// spy for context resize
			let context_function_spy = sinon.spy(context_resize_Callbacks[0], null);
			let callFoo_function_spy = sinon.spy(Context.prototype, 'callFoo');

			// trigger resize
			let resizeEvent = new Event('resize');
			window.dispatchEvent(resizeEvent);

			// test
			context_function_spy.callCount.should.equal(1);
			callFoo_function_spy.callCount.should.equal(1);

			// test passed resize event object
			context_function_spy.args[0][0].type.should.equal('resize');
			should(context_function_spy.args[0][0] instanceof Event).be.true();
			if(!isFirefox){
				should(context_function_spy.args[0][0].currentTarget === window).be.true();
			}

			// test click event
			let context_clickCallbacks = context.$.eventHandler.local.getHandlers('click');
			let context_click_function_spy = sinon.spy(context_clickCallbacks[0], ".foo");

			context.querySelector('.foo').click();
			context_click_function_spy.callCount.should.equal(1);
			callFoo_function_spy.callCount.should.equal(2);

			// test that have different instances and are not in context of window
			let context2 = Context.create();
			should(context2.onResize() === context2.callFoo()).be.true();
			should(context.onResize() === context2.onResize()).be.false();
			should(context.callFoo() === context2.callFoo()).be.false();

			// cleanup
			context_function_spy.restore();
			callFoo_function_spy.restore();
			context_click_function_spy.restore();

		});

	});

});
<commit_msg>related to one commit before<commit_after>
// internal libs
import { component, view, on } from 'src/app-decorators';
import { isFirefox, isSafari } from 'src/helpers/browser-detect';
import { removeGutter } from 'src/helpers/string';

// external libs
import sinon from 'sinon';

describe('@on decorator', () => {

	describe('view.helper.registerNamespaces', () => {

		it('should create namespace object´s', () => {

			on.helper.registerNamespaces({}).should.have.containEql({
				$appDecorators: { on: { events: { local: {} } } },
				$onCreated:  { on: [] },
				$onAttached: { on: [] },
				$onDetached: { on: [] },
			});

		});

	});

	describe('view.helper', () => {

		// Mock target
		let mockTarget = {
			$appDecorators: {
				on: { events: { local: { 'some-event' : () => {} } } }
			},
			$onCreated: {
				on: []
			}
		};
		let mockFunction = function(){}

		describe('registerEvent', () => {

			it('should build event object based on registered namespaces', () => {

				let result = on.helper.registerEvent(mockTarget, 'some-other-event', mockFunction);
				result.should.have.propertyByPath('$appDecorators', 'on', 'events', 'local', 'some-other-event').equal(mockFunction);

			});

		});

		describe('registerCallback', () => {

			it('should add callback based on registered namespaces', () => {

				let result = on.helper.registerCallback('created', mockTarget, mockFunction);
				result.should.have.propertyByPath('$onCreated', 'on', 0).equal(mockFunction);

			});

		});

	});

	describe('Snack.prototype.$appDecorators.on.events', () => {

		it('should contain registered events over @on', () => {

			class Snack {
				// local scope
				@on('click .a') onClick_a() {}
				@on('click .b') onClick_b() {}
				// custom scope (window)
				@on('resize', window) onResize(){}
				@on('wheel', window) onWheel(){}
			}

			let localEvents = Snack.prototype.$appDecorators.on.events.local;
			let windowEvents = Snack.prototype.$appDecorators.on.events[window];
			let prototype = Snack.prototype;

			localEvents.should.have.propertyByPath("click .a").Function();
			localEvents.should.have.propertyByPath("click .b").Function();

			localEvents.should.have.propertyByPath("click .a").eql(prototype.onClick_a);
			localEvents.should.have.propertyByPath("click .b").eql(prototype.onClick_b);

			windowEvents.should.have.propertyByPath("resize").Array();
			windowEvents.should.have.propertyByPath("resize", 0).eql(prototype.onResize);
			windowEvents.should.have.propertyByPath("resize", 1).eql(window);

			windowEvents.should.have.propertyByPath("wheel").Array();
			windowEvents.should.have.propertyByPath("wheel", 0).eql(prototype.onWheel);
			windowEvents.should.have.propertyByPath("wheel", 1).eql(window);

			Object.keys(localEvents).should.have.length(2);
			Object.keys(windowEvents).should.have.length(2);

		});

		it('should trigger correct method if clicked', () => {

			@view(`

 A

 B

			`)
			@component()
			class Milkey {
				@on('click .a') onFoo_a() {}
				@on('click .b') onBar_b() {}
			}

			// create instane
			let milkey_1 = Milkey.create({cid: 1});

			// spy for milkey_1
			let milkey_1_clickCallbacks = milkey_1.$.eventHandler.local.getHandlers('click');
			let milkey_1_a_function_spy = sinon.spy(milkey_1_clickCallbacks[0], ".a");
			let milkey_1_b_function_spy = sinon.spy(milkey_1_clickCallbacks[1], ".b");

			// can simulate click on safari
			if(isSafari) {
				return;
			}

			// test 1
			milkey_1.querySelector('.a').click();
			milkey_1_a_function_spy.callCount.should.eql(1);
			milkey_1_b_function_spy.callCount.should.eql(0);

			// test 2
			milkey_1.querySelector('.b').click();
			milkey_1_a_function_spy.callCount.should.eql(1);
			milkey_1_b_function_spy.callCount.should.eql(1);

			// test 3
			milkey_1.querySelector('.a').click();
			milkey_1.querySelector('.b').click();
			milkey_1_a_function_spy.callCount.should.eql(2);
			milkey_1_b_function_spy.callCount.should.eql(2);

			// cleanup
			milkey_1_a_function_spy.restore();
			milkey_1_b_function_spy.restore();

		});

		it('should ensure that eventhandler has right context', () => {

			@view('
 A
', { renderedFlag: false })
			@component()
			class Hanuta {
				cid = null;
				created({cid}){
					this.cid = cid;
				}
				@on('click .a') onFoo_a() {
					this.setAttribute('cid', this.cid);
				}
			}

			if(isSafari) {
				return;
			}

			//create instances
			let hanuta_1 = Hanuta.create({cid: 1});
			let hanuta_2 = Hanuta.create({cid: 2});

			// test 1
			hanuta_2.querySelector('.a').click();
			hanuta_2.outerHTML.should.be.equal('<com-hanuta cid="2">
 A
</com-hanuta>');
			hanuta_1.outerHTML.should.be.equal('<com-hanuta>
 A
</com-hanuta>');

			// test 2
			hanuta_1.querySelector('.a').click();
			hanuta_1.outerHTML.should.be.equal('<com-hanuta cid="1">
 A
</com-hanuta>');
			hanuta_2.outerHTML.should.be.equal('<com-hanuta cid="2">
 A
</com-hanuta>');

		});

		it('should ensure that @on methods connected with base methods', () => {

			@view('
 A
')
			@component()
			class Ritter {
				baseMethod(){
				}
				@on('click .a') onFoo_a() {
					this.baseMethod();
				}
			}

			if(isSafari) {
				return;
			}

			// create instane
			let ritter = Ritter.create();

			// spy for Ritter onFoo_a
			let ritter_clickCallbacks = ritter.$.eventHandler.local.getHandlers('click');
			let ritter_function_spy = sinon.spy(ritter_clickCallbacks[0], ".a");
			// spy for Ritter baseMethod
			let ritter_baseMethod_spy = sinon.spy(Ritter.prototype, "baseMethod");

			//test
			ritter.querySelector('.a').click();
			ritter_function_spy.callCount.should.eql(1);
			ritter_baseMethod_spy.callCount.should.eql(1);

			// cleanup
			ritter_function_spy.restore();
			ritter_baseMethod_spy.restore();

		});

		it('should trigger window events but is instanec of Context and Element', () => {

			@view(`<div class="foo"></div>`)
			@component()
			class Context {

				@on('resize', window) onResize(event){
					this.callFoo();
					return this;
				}
				callFoo(){
					return this;
				}
				@on('click .foo') onClick(event){
					this.callFoo();
				}

			}

			let context = Context.create();

			let prefixName = Object.prototype.toString.call(window);
			let context_resize_Callbacks = context.$.eventHandler[`${prefixName}_resize`].getHandlers('resize');
			let onResize = context_resize_Callbacks[0][null];

			document.body.appendChild(context);

			// test instanceof Context
			should(onResize() instanceof Context).be.true();
			should(context.callFoo() instanceof Context).be.true();

			// test instance Element
			should(onResize() instanceof Element).be.true();
			should(context.callFoo() instanceof Element).be.true();

			// spy for context resize
			let context_function_spy = sinon.spy(context_resize_Callbacks[0], null);
			let callFoo_function_spy = sinon.spy(Context.prototype, 'callFoo');

			// trigger resize
			let resizeEvent = new Event('resize');
			window.dispatchEvent(resizeEvent);

			// test
			context_function_spy.callCount.should.equal(1);
			callFoo_function_spy.callCount.should.equal(1);

			// test passed resize event object
			context_function_spy.args[0][0].type.should.equal('resize');
			should(context_function_spy.args[0][0] instanceof Event).be.true();
			if(!isFirefox){
				should(context_function_spy.args[0][0].currentTarget === window).be.true();
			}

			// test click event
			let context_clickCallbacks = context.$.eventHandler.local.getHandlers('click');
			let context_click_function_spy = sinon.spy(context_clickCallbacks[0], ".foo");

			context.querySelector('.foo').click();
			context_click_function_spy.callCount.should.equal(1);
			callFoo_function_spy.callCount.should.equal(2);

			// test that have different instances and are not in context of window
			let context2 = Context.create();
			should(context2.onResize() === context2.callFoo()).be.true();
			should(context.onResize() === context2.onResize()).be.false();
			should(context.callFoo() === context2.callFoo()).be.false();

			// cleanup
			context_function_spy.restore();
			callFoo_function_spy.restore();
			context_click_function_spy.restore();

		});

	});

});
<|endoftext|>


<commit_before>/*
 	@license Copyright (c) 2011 Brian Cavalier
	LICENSE: see the LICENSE.txt file. If file is missing, this file is subject
	to the MIT License at: http://www.opensource.org/licenses/mit-license.php.
 */
/*
	Class: PresentationController
*/
define([], function() {

	var doc = window.document,
		html = doc.getElementsByTagName('html')[0],
		body = window.document.body,
		// Detect touch support
		supportsTouch = 'ontouchstart' in body,
		undef;

	/*
		Function: setHash
		Sets the location hash to the supplied slide number.  This will
		clobber any existing hash.

		Parameters:
			slide - The slide number to which to set the hash
	*/
	function setHash(slide) {
		window.location.hash = '#' + slide;
	}

	/*
		Function: getHash

		Returns:
		the current location hash without the leading '#'
	*/
	function getHash() {
		var h = window.location.hash;
		return h.length > 1 && h[0] === '#' ? (Math.max(0, 1*h.substring(1))) : 0;
	}

	/*
		Function: stopEvent
		Prevents the default action and stops propagation of the supplied DOM event.

		Parameters:
			e - the event to stop
	*/
	function stopEvent(e) {
		e.preventDefault();
		e.stopPropagation();
	}

	/*
		Function: addClass
		Adds the supplied class to the supplied DOM node--will not add a duplicate
		class name if the supplied class is already present.  Simple-minded, doesn't
		handle arrays, multiple class names as input, doesn't check node type, etc.

		Parameters:
			node - DOM node to which to add clss
			clss - class name to add
	*/
	function addClass(node, clss) {
		var cn = node.className,
			cns = " " + cn + " ";

		if(cn) {
			if(cn !== clss && cns.indexOf(clss) < 0) {
				node.className += " " + clss;
			}
		} else {
			node.className = clss;
		}
	}

	// Add touch support hint, a la Modernizr
	addClass(html, supportsTouch ? "touch" : "no-touch");

	/*
		Function: initTouchEvents
		Sets up touch events for navigating slides

		Parameters:
			slideView - the <SlideView> on which to handle touch events
	*/
	function initTouchEvents(slideView) {
		// TODO: Should use the slide view's container, not body.
		body.ontouchstart = function(e) {
			var x = e.targetTouches[0].pageX,
				y = e.targetTouches[0].pageY,
				moved = false;

			body.ontouchmove = function(e) {
				moved = true;
			};

			body.ontouchend = function(e) {
				var ret = true;
				try {
					if(e.changedTouches.length === 1) {
						var next;

						if(moved) {
							var dx = e.changedTouches[0].pageX - x,
								dy = e.changedTouches[0].pageY - y;

							if(Math.abs(dx) > Math.abs(dy)) {
								stopEvent(e);
								next = dx <= 0;
							}

							ret = false;

						} else {
							// stopEvent(e);
							// next = e.changedTouches[0].pageX > (window.innerWidth/2);
						}

						if(next != undef) {
							setTimeout(function() {
								slideView[next ? 'next' : 'prev']().then(success);
							}, 0);
						}

					}

					return ret;

				} finally {
					moved = false;
					body.ontouchend = null;
					body.ontouchmove = null;
				}
			};

			return ret;
		};

	}

	/*
		Function: success
		Callback to be invoked on successful <SlideView> transtions, currently just
		updates the location hash by calling <setHash>

		Parameters:
			result - result provided by <SlideView>
	*/
	function success(result) {
		setHash(result.slide);
	}

	/*
		Function: PresentationController
		Creates a new PresentationController that will control a <SlideView>

		Parameters:
			slideView - the <SlideView> to control

		Returns:
		a new PresentationController
	*/
	return function PresentationController(slideView) {
		window.onkeyup = function(e) {
			var key = (window.event) ? event.keyCode : e.keyCode,
				ret = true;
			switch(key) {
				case 37: // Left arrow
				// case 38: // Up arrow, used for keyboard scrolling
					slideView.prev().then(success);
					stopEvent(e);
					ret = false;
					break;
				case 32: // Space
				case 39: // Right arrow
				// case 40: // Down arrow, used for keyboard scrolling
					slideView.next().then(success);
					stopEvent(e);
					ret = false;
					break;
			}

			return ret;
		};

		// Goto first slide
		slideView.go(getHash()).then(function(result) {
			success(result);
			body.className = body.className.replace(/\s*presentation-loading\s*/g, " ");
		});

		if('onhashchange' in window) {
			window.onhashchange = function(e) {
				slideView.go(getHash());
			};
		}

		if(supportsTouch) {
			initTouchEvents(slideView);
		}
	};

});<commit_msg>Fix issue #1.  Only change slides when arrow keys are used with no modifier keys<commit_after>/*
 	@license Copyright (c) 2011 Brian Cavalier
	LICENSE: see the LICENSE.txt file. If file is missing, this file is subject
	to the MIT License at: http://www.opensource.org/licenses/mit-license.php.
 */
/*
	Class: PresentationController
*/
define([], function() {

	var doc = window.document,
		html = doc.getElementsByTagName('html')[0],
		body = window.document.body,
		// Detect touch support
		supportsTouch = 'ontouchstart' in body,
		undef;

	/*
		Function: setHash
		Sets the location hash to the supplied slide number.  This will
		clobber any existing hash.

		Parameters:
			slide - The slide number to which to set the hash
	*/
	function setHash(slide) {
		window.location.hash = '#' + slide;
	}

	/*
		Function: getHash

		Returns:
		the current location hash without the leading '#'
	*/
	function getHash() {
		var h = window.location.hash;
		return h.length > 1 && h[0] === '#' ? (Math.max(0, 1*h.substring(1))) : 0;
	}

	/*
		Function: stopEvent
		Prevents the default action and stops propagation of the supplied DOM event.

		Parameters:
			e - the event to stop
	*/
	function stopEvent(e) {
		e.preventDefault();
		e.stopPropagation();
	}

	/*
		Function: addClass
		Adds the supplied class to the supplied DOM node--will not add a duplicate
		class name if the supplied class is already present.  Simple-minded, doesn't
		handle arrays, multiple class names as input, doesn't check node type, etc.

		Parameters:
			node - DOM node to which to add clss
			clss - class name to add
	*/
	function addClass(node, clss) {
		var cn = node.className,
			cns = " " + cn + " ";

		if(cn) {
			if(cn !== clss && cns.indexOf(clss) < 0) {
				node.className += " " + clss;
			}
		} else {
			node.className = clss;
		}
	}

	// Add touch support hint, a la Modernizr
	addClass(html, supportsTouch ? "touch" : "no-touch");

	/*
		Function: initTouchEvents
		Sets up touch events for navigating slides

		Parameters:
			slideView - the <SlideView> on which to handle touch events
	*/
	function initTouchEvents(slideView) {
		// TODO: Should use the slide view's container, not body.
		body.ontouchstart = function(e) {
			var x = e.targetTouches[0].pageX,
				y = e.targetTouches[0].pageY,
				moved = false;

			body.ontouchmove = function(e) {
				moved = true;
			};

			body.ontouchend = function(e) {
				var ret = true;
				try {
					if(e.changedTouches.length === 1) {
						var next;

						if(moved) {
							var dx = e.changedTouches[0].pageX - x,
								dy = e.changedTouches[0].pageY - y;

							if(Math.abs(dx) > Math.abs(dy)) {
								stopEvent(e);
								next = dx <= 0;
							}

							ret = false;

						} else {
							// stopEvent(e);
							// next = e.changedTouches[0].pageX > (window.innerWidth/2);
						}

						if(next != undef) {
							setTimeout(function() {
								slideView[next ? 'next' : 'prev']().then(success);
							}, 0);
						}

					}

					return ret;

				} finally {
					moved = false;
					body.ontouchend = null;
					body.ontouchmove = null;
				}
			};

			return ret;
		};

	}

	/*
		Function: success
		Callback to be invoked on successful <SlideView> transtions, currently just
		updates the location hash by calling <setHash>

		Parameters:
			result - result provided by <SlideView>
	*/
	function success(result) {
		setHash(result.slide);
	}

	/*
		Function: PresentationController
		Creates a new PresentationController that will control a <SlideView>

		Parameters:
			slideView - the <SlideView> to control

		Returns:
		a new PresentationController
	*/
	return function PresentationController(slideView) {
		window.onkeyup = function(e) {
			var key = (window.event) ? event.keyCode : e.keyCode,
				ret = true;

			// Don't handle slide changes when modifiers are down. Only
			// plain arrow keys change slides.
			if(e.altKey||e.ctrlKey||e.metaKey||e.shiftKey) return true;

			switch(key) {
				case 37: // Left arrow
				// case 38: // Up arrow, used for keyboard scrolling
					slideView.prev().then(success);
					stopEvent(e);
					ret = false;
					break;
				case 39: // Right arrow
				// case 40: // Down arrow, used for keyboard scrolling
					slideView.next().then(success);
					stopEvent(e);
					ret = false;
					break;
			}

			return ret;
		};

		// Goto first slide
		slideView.go(getHash()).then(function(result) {
			success(result);
			body.className = body.className.replace(/\s*presentation-loading\s*/g, " ");
		});

		if('onhashchange' in window) {
			window.onhashchange = function(e) {
				slideView.go(getHash());
			};
		}

		if(supportsTouch) {
			initTouchEvents(slideView);
		}
	};

});<|endoftext|>


<commit_before>import Ember from 'ember';
import md5 from 'npm:js-md5';
import _get from 'npm:lodash/get';
import Cookie from 'npm:js-cookie';
import config from 'ember-get-config';
import keenTracking from 'npm:keen-tracking';

// Adapted from website/static/js/keen.js
export default Ember.Mixin.create({
    session: Ember.inject.service(),

    // Add this mixin to your route, and the afterModel hook will send pageviews to keen
    afterModel(model, transition) { // Using afterModel hook so node info can be sent to keen
        window.contextVars = {};
        window.contextVars.currentUser = this.userContextVars();
        window.contextVars.node = this.nodeContextVars(model); // model may not be a node, in which case, only id might be extracted
        let transitionData = {
            page: transition.targetName,
            queryParams: transition.queryParams
        };
        return this.KeenTracker().getInstance().trackPageView(transitionData);
    },
    actions: {
        //keenClick action can be used in template
        keenClick(category, label, url) {
            return this.keenTrackFrontEndEvent({ category: category, action: 'click', label: label, url: url });

        },
        //keenTrack action can be used in template
        keenTrack(category, action, label, node) {
            return this.keenTrackFrontEndEvent({ category: category, action: action, label: label }, node);
        }
    },
    KeenTracker() {
        function _nowUTC() {
            var now = new Date();
            return new Date(
                now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),
                now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()
            );
        }

        function _createOrUpdateKeenSession() {
            var expDate = new Date();
            var expiresInMinutes = 25;
            expDate.setTime(expDate.getTime() + (expiresInMinutes * 60 * 1000));
            var currentSessionId = Cookie.get('keenSessionId') || keenTracking.helpers.getUniqueId();
            Cookie.set('keenSessionId', currentSessionId, {
                expires: expDate, path: '/'
            });
        }

        function _getOrCreateKeenId() {
            if (!Cookie.get('keenUserId')) {
                Cookie.set('keenUserId', keenTracking.helpers.getUniqueId(), {
                    expires: 365, path: '/'
                });
            }
            return Cookie.get('keenUserId');
        }

        function _defaultKeenPayload() {
            _createOrUpdateKeenSession();

            var user = window.contextVars.currentUser;
            var node = window.contextVars.node;
            var pageMeta = _get(window, 'contextVars.analyticsMeta.pageMeta', {}); // Do not have this information.
            return {
                page: {
                    title: document.title,
                    url: document.URL,
                    meta: pageMeta,
                    info: {},
                },
                referrer: {
                    url: document.referrer,
                    info: {},
                },
                time: {
                    local: keenTracking.helpers.getDatetimeIndex(),
                    utc: keenTracking.helpers.getDatetimeIndex(_nowUTC()),
                },
                node: {
                    id: _get(node, 'id'),
                    title: _get(node, 'title'),
                    type: _get(node, 'category'),
                    tags: _get(node, 'tags'),
                },
                anon: {
                    id: md5(Cookie.get('keenSessionId')),
                    continent: user.anon.continent,
                    country: user.anon.country,
                },
                meta: {
                    epoch: 1, // version of pageview event schema
                },
                keen: {
                    addons: [
                        {
                            name: 'keen:url_parser',
                            input: {
                                url: 'page.url',
                            },
                            output: 'page.info',
                        },
                        {
                            name: 'keen:url_parser',
                            input: {
                                url: 'referrer.url',
                            },
                            output: 'referrer.info',
                        },
                        {
                            name: 'keen:referrer_parser',
                            input: {
                                referrer_url: 'referrer.url',
                                page_url: 'page.url',
                            },
                            output: 'referrer.info',
                        },
                    ]
                },
            };
        }  // end _defaultKeenPayload

        function _trackCustomEvent(client, collection, eventData) {
            if (client === null) {
                return;
            }
            client.recordEvent(collection, eventData);
        }

        function _trackCustomEvents(client, events) {
            if (client === null) {
                return;
            }
            client.recordEvents(events);
        }

        function KeenTracker() {
            if (instance) {
                throw new Error('Cannot instantiate another KeenTracker instance.');
            } else {
                var _this = this;

                _this._publicClient = null;
                _this._privateClient = null;

                _this.init = function _initKeentracker(params) {
                    var _this = this;

                    if (params === undefined) {
                        return _this;
                    }

                    _this._publicClient = keenTracking({
                        projectId: params.public.projectId,
                        writeKey: params.public.writeKey,
                    });
                    _this._publicClient.extendEvents(_defaultPublicKeenPayload);

                    _this._privateClient = keenTracking({
                        projectId: params.private.projectId,
                        writeKey: params.private.writeKey,
                    });
                    _this._privateClient.extendEvents(_defaultPrivateKeenPayload);

                    return _this;
                };

                var _defaultPublicKeenPayload = function() { return _defaultKeenPayload(); };
                var _defaultPrivateKeenPayload = function() {
                    var payload = _defaultKeenPayload();
                    var user = window.contextVars.currentUser;
                    payload.visitor = {
                        id: _getOrCreateKeenId(),
                        session: Cookie.get('keenSessionId'),
                        returning: Boolean(Cookie.get('keenUserId')),
                    };
                    payload.tech = {
                        browser: keenTracking.helpers.getBrowserProfile(),
                        ua: '${keen.user_agent}',
                        ip: '${keen.ip}',
                        info: {},
                    };
                    payload.user = {
                        id: user.id,
                        entry_point: user.entryPoint,
                        institutions: user.institutions,
                        locale: user.locale,
                        timezone: user.timezone,
                    };
                    payload.keen.addons.push({
                        name: 'keen:ip_to_geo',
                        input: {
                            ip: 'tech.ip',
                        },
                        output: 'geo',
                    });
                    payload.keen.addons.push({
                        name: 'keen:ua_parser',
                        input: {
                            ua_string: 'tech.ua'
                        },
                        output: 'tech.info',
                    });

                    return payload;
                };

                _this.trackPageView = function (data) {
                    var _this = this;
                    if (_get(window, 'contextVars.node.isPublic', false) &&
                        _get(window, 'contextVars.analyticsMeta.pageMeta.public', false)) {
                        _this.trackPublicEvent('pageviews', data);
                    }
                    _this.trackPrivateEvent('pageviews', data);
                };

                _this.trackPrivateEvent = function(collection, event) {
                    return _trackCustomEvent(_this._privateClient, collection, event);
                };
                _this.trackPrivateEvents = function(events) {
                    return _trackCustomEvents(_this._privateClient, events);
                };

                _this.trackPublicEvent = function(collection, event) {
                    return _trackCustomEvent(_this._publicClient, collection, event);
                };
                _this.trackPublicEvents = function(events) {
                    return _trackCustomEvents(_this._publicClient, events);
                };
            }
        }

        var instance = null;
        return {
            getInstance() {
                if (!instance) {
                    instance = new KeenTracker();
                    instance.init(config.KEEN);
                }
                return instance;
            }
        };
    },
    userContextVars() {
        // Extract user variables from session.
        const session = this.get('session');
        let user = {};
        if (session.get('isAuthenticated')) {
            let userInfo = session.get('session.authenticated');
            user = {
                id: userInfo.id,
                entry_point: userInfo.attributes.entry_point, // Don't have the entry point.
                institutions: null, // Don't really want to make an API request to fetch user institutions.
                locale: userInfo.attributes.locale,
                timezone: userInfo.attributes.timezone
            };
        }
        user.anon = {}; // Do not have this info, but most duplicated in geo.
        return user;
    },
    nodeContextVars(node) {
        // Extract node variables, if passed in.
        let nodeVars = {};
        if (node && node.id) {
            nodeVars = {
                id: node.get('id'),
                title: node.get('title'),
                type: node.get('category'),
                tags: node.get('tags'),
                isPublic: node.get('public')
            };
        }
        return nodeVars;
    },
    keenTrackEvent(collection, properties, node) {
        // Adds context vars and sends keen trackPrivateEvent method
        window.contextVars = {};
        window.contextVars.currentUser = this.userContextVars();
        window.contextVars.node = this.nodeContextVars(node);
        return this.KeenTracker().getInstance().trackPrivateEvent(collection, properties);
    },
    /**
     * For front-end event-tracking - Sends event info to keen front-end-events collection. Collection: front-end-events.
     * Properties: interaction dictionary plus supplemental info in default keen payload
     *
     * @method keenTrackFrontEndEvent
     * @param {Object} event Dictionary with category, action, label
     * @param {Object} model Relevant model - node model if exists
     */
    keenTrackFrontEndEvent(event, model) {
        return this.keenTrackEvent('front-end-events', {
            interaction: {
                category: event.category || null,
                action: event.action || null,
                label: event.label || null,
                url: event.url || null
            }
        }, model);
    }
});
<commit_msg>Nest transition data under transition.<commit_after>import Ember from 'ember';
import md5 from 'npm:js-md5';
import _get from 'npm:lodash/get';
import Cookie from 'npm:js-cookie';
import config from 'ember-get-config';
import keenTracking from 'npm:keen-tracking';

// Adapted from website/static/js/keen.js
export default Ember.Mixin.create({
    session: Ember.inject.service(),

    // Add this mixin to your route, and the afterModel hook will send pageviews to keen
    afterModel(model, transition) { // Using afterModel hook so node info can be sent to keen
        window.contextVars = {};
        window.contextVars.currentUser = this.userContextVars();
        window.contextVars.node = this.nodeContextVars(model); // model may not be a node, in which case, only id might be extracted
        let transitionData = {
            transition: {
                page: transition.targetName,
                queryParams: transition.queryParams
            }
        };
        return this.KeenTracker().getInstance().trackPageView(transitionData);
    },
    actions: {
        //keenClick action can be used in template
        keenClick(category, label, url) {
            return this.keenTrackFrontEndEvent({ category: category, action: 'click', label: label, url: url });

        },
        //keenTrack action can be used in template
        keenTrack(category, action, label, node) {
            return this.keenTrackFrontEndEvent({ category: category, action: action, label: label }, node);
        }
    },
    KeenTracker() {
        function _nowUTC() {
            var now = new Date();
            return new Date(
                now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),
                now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()
            );
        }

        function _createOrUpdateKeenSession() {
            var expDate = new Date();
            var expiresInMinutes = 25;
            expDate.setTime(expDate.getTime() + (expiresInMinutes * 60 * 1000));
            var currentSessionId = Cookie.get('keenSessionId') || keenTracking.helpers.getUniqueId();
            Cookie.set('keenSessionId', currentSessionId, {
                expires: expDate, path: '/'
            });
        }

        function _getOrCreateKeenId() {
            if (!Cookie.get('keenUserId')) {
                Cookie.set('keenUserId', keenTracking.helpers.getUniqueId(), {
                    expires: 365, path: '/'
                });
            }
            return Cookie.get('keenUserId');
        }

        function _defaultKeenPayload() {
            _createOrUpdateKeenSession();

            var user = window.contextVars.currentUser;
            var node = window.contextVars.node;
            var pageMeta = _get(window, 'contextVars.analyticsMeta.pageMeta', {}); // Do not have this information.
            return {
                page: {
                    title: document.title,
                    url: document.URL,
                    meta: pageMeta,
                    info: {},
                },
                referrer: {
                    url: document.referrer,
                    info: {},
                },
                time: {
                    local: keenTracking.helpers.getDatetimeIndex(),
                    utc: keenTracking.helpers.getDatetimeIndex(_nowUTC()),
                },
                node: {
                    id: _get(node, 'id'),
                    title: _get(node, 'title'),
                    type: _get(node, 'category'),
                    tags: _get(node, 'tags'),
                },
                anon: {
                    id: md5(Cookie.get('keenSessionId')),
                    continent: user.anon.continent,
                    country: user.anon.country,
                },
                meta: {
                    epoch: 1, // version of pageview event schema
                },
                keen: {
                    addons: [
                        {
                            name: 'keen:url_parser',
                            input: {
                                url: 'page.url',
                            },
                            output: 'page.info',
                        },
                        {
                            name: 'keen:url_parser',
                            input: {
                                url: 'referrer.url',
                            },
                            output: 'referrer.info',
                        },
                        {
                            name: 'keen:referrer_parser',
                            input: {
                                referrer_url: 'referrer.url',
                                page_url: 'page.url',
                            },
                            output: 'referrer.info',
                        },
                    ]
                },
            };
        }  // end _defaultKeenPayload

        function _trackCustomEvent(client, collection, eventData) {
            if (client === null) {
                return;
            }
            client.recordEvent(collection, eventData);
        }

        function _trackCustomEvents(client, events) {
            if (client === null) {
                return;
            }
            client.recordEvents(events);
        }

        function KeenTracker() {
            if (instance) {
                throw new Error('Cannot instantiate another KeenTracker instance.');
            } else {
                var _this = this;

                _this._publicClient = null;
                _this._privateClient = null;

                _this.init = function _initKeentracker(params) {
                    var _this = this;

                    if (params === undefined) {
                        return _this;
                    }

                    _this._publicClient = keenTracking({
                        projectId: params.public.projectId,
                        writeKey: params.public.writeKey,
                    });
                    _this._publicClient.extendEvents(_defaultPublicKeenPayload);

                    _this._privateClient = keenTracking({
                        projectId: params.private.projectId,
                        writeKey: params.private.writeKey,
                    });
                    _this._privateClient.extendEvents(_defaultPrivateKeenPayload);

                    return _this;
                };

                var _defaultPublicKeenPayload = function() { return _defaultKeenPayload(); };
                var _defaultPrivateKeenPayload = function() {
                    var payload = _defaultKeenPayload();
                    var user = window.contextVars.currentUser;
                    payload.visitor = {
                        id: _getOrCreateKeenId(),
                        session: Cookie.get('keenSessionId'),
                        returning: Boolean(Cookie.get('keenUserId')),
                    };
                    payload.tech = {
                        browser: keenTracking.helpers.getBrowserProfile(),
                        ua: '${keen.user_agent}',
                        ip: '${keen.ip}',
                        info: {},
                    };
                    payload.user = {
                        id: user.id,
                        entry_point: user.entryPoint,
                        institutions: user.institutions,
                        locale: user.locale,
                        timezone: user.timezone,
                    };
                    payload.keen.addons.push({
                        name: 'keen:ip_to_geo',
                        input: {
                            ip: 'tech.ip',
                        },
                        output: 'geo',
                    });
                    payload.keen.addons.push({
                        name: 'keen:ua_parser',
                        input: {
                            ua_string: 'tech.ua'
                        },
                        output: 'tech.info',
                    });

                    return payload;
                };

                _this.trackPageView = function (data) {
                    var _this = this;
                    if (_get(window, 'contextVars.node.isPublic', false) &&
                        _get(window, 'contextVars.analyticsMeta.pageMeta.public', false)) {
                        _this.trackPublicEvent('pageviews', data);
                    }
                    _this.trackPrivateEvent('pageviews', data);
                };

                _this.trackPrivateEvent = function(collection, event) {
                    return _trackCustomEvent(_this._privateClient, collection, event);
                };
                _this.trackPrivateEvents = function(events) {
                    return _trackCustomEvents(_this._privateClient, events);
                };

                _this.trackPublicEvent = function(collection, event) {
                    return _trackCustomEvent(_this._publicClient, collection, event);
                };
                _this.trackPublicEvents = function(events) {
                    return _trackCustomEvents(_this._publicClient, events);
                };
            }
        }

        var instance = null;
        return {
            getInstance() {
                if (!instance) {
                    instance = new KeenTracker();
                    instance.init(config.KEEN);
                }
                return instance;
            }
        };
    },
    userContextVars() {
        // Extract user variables from session.
        const session = this.get('session');
        let user = {};
        if (session.get('isAuthenticated')) {
            let userInfo = session.get('session.authenticated');
            user = {
                id: userInfo.id,
                entry_point: userInfo.attributes.entry_point, // Don't have the entry point.
                institutions: null, // Don't really want to make an API request to fetch user institutions.
                locale: userInfo.attributes.locale,
                timezone: userInfo.attributes.timezone
            };
        }
        user.anon = {}; // Do not have this info, but most duplicated in geo.
        return user;
    },
    nodeContextVars(node) {
        // Extract node variables, if passed in.
        let nodeVars = {};
        if (node && node.id) {
            nodeVars = {
                id: node.get('id'),
                title: node.get('title'),
                type: node.get('category'),
                tags: node.get('tags'),
                isPublic: node.get('public')
            };
        }
        return nodeVars;
    },
    keenTrackEvent(collection, properties, node) {
        // Adds context vars and sends keen trackPrivateEvent method
        window.contextVars = {};
        window.contextVars.currentUser = this.userContextVars();
        window.contextVars.node = this.nodeContextVars(node);
        return this.KeenTracker().getInstance().trackPrivateEvent(collection, properties);
    },
    /**
     * For front-end event-tracking - Sends event info to keen front-end-events collection. Collection: front-end-events.
     * Properties: interaction dictionary plus supplemental info in default keen payload
     *
     * @method keenTrackFrontEndEvent
     * @param {Object} event Dictionary with category, action, label
     * @param {Object} model Relevant model - node model if exists
     */
    keenTrackFrontEndEvent(event, model) {
        return this.keenTrackEvent('front-end-events', {
            interaction: {
                category: event.category || null,
                action: event.action || null,
                label: event.label || null,
                url: event.url || null
            }
        }, model);
    }
});
<|endoftext|>


<commit_before>var expect = require('chai').expect,
    directedGraph = require('../lib/directedGraph');

describe('directedGraph test', function() {

    describe('simple graph', function() {

        var diGraph = directedGraph().export();

        it('should add vertices', function() {
            diGraph.addVertex('v1');
            diGraph.addVertex('v2');
            diGraph.addVertex('v3');
            diGraph.addVertex('v4');
            diGraph.addVertex('v5');

            expect(diGraph.countVertices()).to.be.equal(5);

            expect(diGraph.hasVertex('v1')).to.be.equal(true);
            expect(diGraph.hasVertex('v2')).to.be.equal(true);
            expect(diGraph.hasVertex('v3')).to.be.equal(true);
            expect(diGraph.hasVertex('v4')).to.be.equal(true);
            expect(diGraph.hasVertex('v5')).to.be.equal(true);
        });

        it('should add and verify directions', function() {

            diGraph.addDirection('v1', 'v3', 7);
            diGraph.addDirection('v1', 'v5', 10);
            diGraph.addDirection('v2', 'v1', 9);
            diGraph.addDirection('v3', 'v4', 11);
            diGraph.addDirection('v5', 'v3', 15);
            expect(diGraph.addDirection.bind(diGraph, 'v5', 'v4')).to.throw({
                message: 'weight is not a valid number'
            });
            expect(diGraph.addDirection.bind(diGraph, 'v5', 'v4', 'j')).to.throw({
                message: 'weight is not a valid number'
            });

            expect(diGraph.getDirectionWeight('v1', 'v3')).to.be.equal(7);
            expect(diGraph.getDirectionWeight('v1', 'v5')).to.be.equal(10);
            expect(diGraph.getDirectionWeight('v2', 'v1')).to.be.equal(9);
            expect(diGraph.getDirectionWeight('v3', 'v4')).to.be.equal(11);
            expect(diGraph.getDirectionWeight('v5', 'v3')).to.be.equal(15);

        });

        it('should find the shortest path', function() {
            var v1v4 = diGraph.findShortestPath('v1', 'v4'),
                v2v3 = diGraph.findShortestPath('v2', 'v3'),
                v5v2 = diGraph.findShortestPath('v5', 'v2');

            expect(v1v4.length).to.be.equal(1);
            expect(v1v4[0]).to.be.eql(['v1', 'v3', 'v4']);

            expect(v2v3.length).to.be.equal(1);
            expect(v2v3[0]).to.be.eql(['v2', 'v1', 'v3']);

            expect(v5v2.length).to.be.equal(0);
        });

        it('should remove a direction', function() {
            diGraph.removeDirection('v2', 'v1');
            expect(diGraph.getDirectionWeight('v2', 'v1')).to.be.equal(null);
        });

        it('should get the separated vertices', function() {
            var s = diGraph.getSeparatedVertices();
            expect(s).to.be.eql(['v2']);
        });

        it('should remove a vertex', function() {
            diGraph.removeVertex('v3');

            expect(diGraph.countVertices()).to.be.equal(4);
            expect(diGraph.hasVertex('v3')).to.be.equal(false);
            expect(diGraph.getDirectionWeight('v3', 'v4')).to.be.equal(null);
            expect(diGraph.getDirectionWeight('v5', 'v3')).to.be.equal(null);
        });
    });

    describe('complex graph', function() {

        var diGraph = directedGraph();

        it('should add vertices', function() {
            diGraph.addVertex('v1');
            diGraph.addVertex('v2');
            diGraph.addVertex('v3');
            diGraph.addVertex('v4');
            diGraph.addVertex('v5');
            diGraph.addVertex('v6');
            diGraph.addVertex('v7');
            diGraph.addVertex('v8');
            diGraph.addVertex('v9');
            diGraph.addVertex('v10');
            diGraph.addVertex('v11');
            diGraph.addVertex('v12');

            expect(diGraph.countVertices()).to.be.equal(12);

            expect(diGraph.hasVertex('v1')).to.be.equal(true);
            expect(diGraph.hasVertex('v2')).to.be.equal(true);
            expect(diGraph.hasVertex('v3')).to.be.equal(true);
            expect(diGraph.hasVertex('v4')).to.be.equal(true);
            expect(diGraph.hasVertex('v5')).to.be.equal(true);
            expect(diGraph.hasVertex('v6')).to.be.equal(true);
            expect(diGraph.hasVertex('v7')).to.be.equal(true);
            expect(diGraph.hasVertex('v8')).to.be.equal(true);
            expect(diGraph.hasVertex('v9')).to.be.equal(true);
            expect(diGraph.hasVertex('v10')).to.be.equal(true);
            expect(diGraph.hasVertex('v11')).to.be.equal(true);
            expect(diGraph.hasVertex('v12')).to.be.equal(true);
        });

        it('should add and verify directions', function() {
            diGraph.addDirection('v1', 'v3', 10);
            diGraph.addDirection('v1', 'v6', 3);
            diGraph.addDirection('v1', 'v9', 12);
            diGraph.addDirection('v2', 'v12', 5);
            diGraph.addDirection('v3', 'v4', 6);
            diGraph.addDirection('v3', 'v7', 8);
            diGraph.addDirection('v3', 'v9', 4);
            diGraph.addDirection('v4', 'v2', 9);
            diGraph.addDirection('v4', 'v8', 1);
            diGraph.addDirection('v4', 'v11', 13);
            diGraph.addDirection('v5', 'v12', 11);
            diGraph.addDirection('v6', 'v5', 7);
            diGraph.addDirection('v7', 'v4', 10);
            diGraph.addDirection('v8', 'v2', 8);
            diGraph.addDirection('v9', 'v5', 13);
            diGraph.addDirection('v9', 'v6', 2);
            diGraph.addDirection('v9', 'v7', 5);
            diGraph.addDirection('v10', 'v2', 14);
            diGraph.addDirection('v10', 'v8', 6);
            diGraph.addDirection('v10', 'v11', 7);
            diGraph.addDirection('v10', 'v12', 2);
            diGraph.addDirection('v11', 'v8', 4);
            diGraph.addDirection('v12', 'v7', 3);

            expect(diGraph.getDirectionWeight('v1', 'v3')).to.be.equal(10);
            expect(diGraph.getDirectionWeight('v1', 'v6')).to.be.equal(3);
            expect(diGraph.getDirectionWeight('v1', 'v9')).to.be.equal(12);
            expect(diGraph.getDirectionWeight('v2', 'v12')).to.be.equal(5);
            expect(diGraph.getDirectionWeight('v3', 'v4')).to.be.equal(6);
            expect(diGraph.getDirectionWeight('v3', 'v7')).to.be.equal(8);
            expect(diGraph.getDirectionWeight('v3', 'v9')).to.be.equal(4);
            expect(diGraph.getDirectionWeight('v4', 'v2')).to.be.equal(9);
            expect(diGraph.getDirectionWeight('v4', 'v8')).to.be.equal(1);
            expect(diGraph.getDirectionWeight('v4', 'v11')).to.be.equal(13);
            expect(diGraph.getDirectionWeight('v5', 'v12')).to.be.equal(11);
            expect(diGraph.getDirectionWeight('v6', 'v5')).to.be.equal(7);
            expect(diGraph.getDirectionWeight('v7', 'v4')).to.be.equal(10);
            expect(diGraph.getDirectionWeight('v8', 'v2')).to.be.equal(8);
            expect(diGraph.getDirectionWeight('v9', 'v5')).to.be.equal(13);
            expect(diGraph.getDirectionWeight('v9', 'v6')).to.be.equal(2);
            expect(diGraph.getDirectionWeight('v9', 'v7')).to.be.equal(5);
            expect(diGraph.getDirectionWeight('v10', 'v2')).to.be.equal(14);
            expect(diGraph.getDirectionWeight('v10', 'v8')).to.be.equal(6);
            expect(diGraph.getDirectionWeight('v10', 'v11')).to.be.equal(7);
            expect(diGraph.getDirectionWeight('v10', 'v12')).to.be.equal(2);
            expect(diGraph.getDirectionWeight('v11', 'v8')).to.be.equal(4);
            expect(diGraph.getDirectionWeight('v12', 'v7')).to.be.equal(3);

        });

        it('should find the shortest path', function() {
            var v10v8 = diGraph.findShortestPath('v10', 'v8'),
                v1v7 = diGraph.findShortestPath('v1', 'v7'),
                v6v2 = diGraph.findShortestPath('v6', 'v2'),
                v3v12 = diGraph.findShortestPath('v3', 'v12'),
                v12v3 = diGraph.findShortestPath('v12', 'v3'),
                v1v10 = diGraph.findShortestPath('v1', 'v10'),
                v10v1 = diGraph.findShortestPath('v10', 'v1');

            expect(v10v8.length).to.be.equal(1);
            expect(v10v8[0]).to.be.eql(['v10', 'v8']);

            expect(v1v7.length).to.be.equal(1);
            expect(v1v7[0]).to.be.eql(['v1', 'v9', 'v7']);

            expect(v6v2.length).to.be.equal(2);
            expect(v6v2[0]).to.be.eql(['v6', 'v5', 'v12', 'v7', 'v4', 'v2']);
            expect(v6v2[1]).to.be.eql(['v6', 'v5', 'v12', 'v7', 'v4', 'v8', 'v2']);

            expect(v3v12.length).to.be.equal(2);
            expect(v3v12[0]).to.be.eql(['v3', 'v4', 'v2', 'v12']);
            expect(v3v12[1]).to.be.eql(['v3', 'v4', 'v8', 'v2', 'v12']);

            expect(v12v3.length).to.be.equal(0);
            expect(v1v10.length).to.be.equal(0);
            expect(v10v1.length).to.be.equal(0);
        });

        it('should remove a direction', function() {
            diGraph.removeDirection('v10', 'v2');
            diGraph.removeDirection('v10', 'v8');
            diGraph.removeDirection('v10', 'v11');
            diGraph.removeDirection('v10', 'v12');
            diGraph.removeDirection('v11', 'v8');
            diGraph.removeDirection('v4', 'v11');

            expect(diGraph.getDirectionWeight('v10', 'v2')).to.be.equal(null);
            expect(diGraph.getDirectionWeight('v10', 'v8')).to.be.equal(null);
            expect(diGraph.getDirectionWeight('v10', 'v11')).to.be.equal(null);
            expect(diGraph.getDirectionWeight('v10', 'v12')).to.be.equal(null);
            expect(diGraph.getDirectionWeight('v11', 'v8')).to.be.equal(null);
            expect(diGraph.getDirectionWeight('v4', 'v11')).to.be.equal(null);
        });

        it('should get the separated vertices', function() {
            var s = diGraph.getSeparatedVertices();
            expect(s).to.be.have.members(['v10', 'v11']);
        });

        it('should remove a vertex', function() {
            diGraph.removeVertex('v2');

            expect(diGraph.countVertices()).to.be.equal(11);
            expect(diGraph.hasVertex('v2')).to.be.equal(false);
        });

    });
});<commit_msg>update test<commit_after>var expect = require('chai').expect,
    directedGraph = require('../lib/directedGraph');

describe('directedGraph test', function() {

    describe('simple graph', function() {

        var diGraph = directedGraph().export();

        it('should add vertices', function() {
            diGraph.addVertex('v1');
            diGraph.addVertex('v2');
            diGraph.addVertex(3);
            diGraph.addVertex('v4');
            diGraph.addVertex('v5');

            expect(diGraph.countVertices()).to.be.equal(5);

            expect(diGraph.hasVertex('v1')).to.be.equal(true);
            expect(diGraph.hasVertex('v2')).to.be.equal(true);
            expect(diGraph.hasVertex(3)).to.be.equal(true);
            expect(diGraph.hasVertex('v4')).to.be.equal(true);
            expect(diGraph.hasVertex('v5')).to.be.equal(true);
        });

        it('should add and verify directions', function() {

            diGraph.addDirection('v1', '3', 7);
            diGraph.addDirection('v1', 'v5', 10);
            diGraph.addDirection('v2', 'v1', 9);
            diGraph.addDirection('3', 'v4', 11);
            diGraph.addDirection('v5', '3', 15);
            expect(diGraph.addDirection.bind(diGraph, 'v5', 'v4')).to.throw({
                message: 'weight is not a valid number'
            });
            expect(diGraph.addDirection.bind(diGraph, 'v5', 'v4', 'j')).to.throw({
                message: 'weight is not a valid number'
            });

            expect(diGraph.getDirectionWeight('v1', '3')).to.be.equal(7);
            expect(diGraph.getDirectionWeight('v1', 'v5')).to.be.equal(10);
            expect(diGraph.getDirectionWeight('v2', 'v1')).to.be.equal(9);
            expect(diGraph.getDirectionWeight('3', 'v4')).to.be.equal(11);
            expect(diGraph.getDirectionWeight('v5', '3')).to.be.equal(15);

        });

        it('should find the shortest path', function() {
            var v1v4 = diGraph.findShortestPath('v1', 'v4'),
                v2v3 = diGraph.findShortestPath('v2', '3'),
                v5v2 = diGraph.findShortestPath('v5', 'v2');

            expect(v1v4.length).to.be.equal(1);
            expect(v1v4[0]).to.be.eql(['v1', '3', 'v4']);

            expect(v2v3.length).to.be.equal(1);
            expect(v2v3[0]).to.be.eql(['v2', 'v1', '3']);

            expect(v5v2.length).to.be.equal(0);
        });

        it('should remove a direction', function() {
            diGraph.removeDirection('v2', 'v1');
            expect(diGraph.getDirectionWeight('v2', 'v1')).to.be.equal(null);
        });

        it('should get the separated vertices', function() {
            var s = diGraph.getSeparatedVertices();
            expect(s).to.be.eql(['v2']);
        });

        it('should remove a vertex', function() {
            diGraph.removeVertex('v2');
            diGraph.removeVertex('3');

            expect(diGraph.countVertices()).to.be.equal(3);
            expect(diGraph.hasVertex('3')).to.be.equal(false);
            expect(diGraph.getDirectionWeight('3', 'v4')).to.be.equal(null);
            expect(diGraph.getDirectionWeight('v5', '3')).to.be.equal(null);
        });
    });

    describe('complex graph', function() {

        var diGraph = directedGraph();

        it('should add vertices', function() {
            diGraph.addVertex('v1');
            diGraph.addVertex('v2');
            diGraph.addVertex('v3');
            diGraph.addVertex('v4');
            diGraph.addVertex('v5');
            diGraph.addVertex('v6');
            diGraph.addVertex('v7');
            diGraph.addVertex('v8');
            diGraph.addVertex('v9');
            diGraph.addVertex('v10');
            diGraph.addVertex('v11');
            diGraph.addVertex('v12');

            expect(diGraph.countVertices()).to.be.equal(12);

            expect(diGraph.hasVertex('v1')).to.be.equal(true);
            expect(diGraph.hasVertex('v2')).to.be.equal(true);
            expect(diGraph.hasVertex('v3')).to.be.equal(true);
            expect(diGraph.hasVertex('v4')).to.be.equal(true);
            expect(diGraph.hasVertex('v5')).to.be.equal(true);
            expect(diGraph.hasVertex('v6')).to.be.equal(true);
            expect(diGraph.hasVertex('v7')).to.be.equal(true);
            expect(diGraph.hasVertex('v8')).to.be.equal(true);
            expect(diGraph.hasVertex('v9')).to.be.equal(true);
            expect(diGraph.hasVertex('v10')).to.be.equal(true);
            expect(diGraph.hasVertex('v11')).to.be.equal(true);
            expect(diGraph.hasVertex('v12')).to.be.equal(true);
        });

        it('should add and verify directions', function() {
            diGraph.addDirection('v1', 'v3', 10);
            diGraph.addDirection('v1', 'v6', 3);
            diGraph.addDirection('v1', 'v9', 12);
            diGraph.addDirection('v2', 'v12', 5);
            diGraph.addDirection('v3', 'v4', 6);
            diGraph.addDirection('v3', 'v7', 8);
            diGraph.addDirection('v3', 'v9', 4);
            diGraph.addDirection('v4', 'v2', 9);
            diGraph.addDirection('v4', 'v8', 1);
            diGraph.addDirection('v4', 'v11', 13);
            diGraph.addDirection('v5', 'v12', 11);
            diGraph.addDirection('v6', 'v5', 7);
            diGraph.addDirection('v7', 'v4', 10);
            diGraph.addDirection('v8', 'v2', 8);
            diGraph.addDirection('v9', 'v5', 13);
            diGraph.addDirection('v9', 'v6', 2);
            diGraph.addDirection('v9', 'v7', 5);
            diGraph.addDirection('v10', 'v2', 14);
            diGraph.addDirection('v10', 'v8', 6);
            diGraph.addDirection('v10', 'v11', 7);
            diGraph.addDirection('v10', 'v12', 2);
            diGraph.addDirection('v11', 'v8', 4);
            diGraph.addDirection('v12', 'v7', 3);

            expect(diGraph.getDirectionWeight('v1', 'v3')).to.be.equal(10);
            expect(diGraph.getDirectionWeight('v1', 'v6')).to.be.equal(3);
            expect(diGraph.getDirectionWeight('v1', 'v9')).to.be.equal(12);
            expect(diGraph.getDirectionWeight('v2', 'v12')).to.be.equal(5);
            expect(diGraph.getDirectionWeight('v3', 'v4')).to.be.equal(6);
            expect(diGraph.getDirectionWeight('v3', 'v7')).to.be.equal(8);
            expect(diGraph.getDirectionWeight('v3', 'v9')).to.be.equal(4);
            expect(diGraph.getDirectionWeight('v4', 'v2')).to.be.equal(9);
            expect(diGraph.getDirectionWeight('v4', 'v8')).to.be.equal(1);
            expect(diGraph.getDirectionWeight('v4', 'v11')).to.be.equal(13);
            expect(diGraph.getDirectionWeight('v5', 'v12')).to.be.equal(11);
            expect(diGraph.getDirectionWeight('v6', 'v5')).to.be.equal(7);
            expect(diGraph.getDirectionWeight('v7', 'v4')).to.be.equal(10);
            expect(diGraph.getDirectionWeight('v8', 'v2')).to.be.equal(8);
            expect(diGraph.getDirectionWeight('v9', 'v5')).to.be.equal(13);
            expect(diGraph.getDirectionWeight('v9', 'v6')).to.be.equal(2);
            expect(diGraph.getDirectionWeight('v9', 'v7')).to.be.equal(5);
            expect(diGraph.getDirectionWeight('v10', 'v2')).to.be.equal(14);
            expect(diGraph.getDirectionWeight('v10', 'v8')).to.be.equal(6);
            expect(diGraph.getDirectionWeight('v10', 'v11')).to.be.equal(7);
            expect(diGraph.getDirectionWeight('v10', 'v12')).to.be.equal(2);
            expect(diGraph.getDirectionWeight('v11', 'v8')).to.be.equal(4);
            expect(diGraph.getDirectionWeight('v12', 'v7')).to.be.equal(3);

        });

        it('should find the shortest path', function() {
            var v10v8 = diGraph.findShortestPath('v10', 'v8'),
                v1v7 = diGraph.findShortestPath('v1', 'v7'),
                v6v2 = diGraph.findShortestPath('v6', 'v2'),
                v3v12 = diGraph.findShortestPath('v3', 'v12'),
                v12v3 = diGraph.findShortestPath('v12', 'v3'),
                v1v10 = diGraph.findShortestPath('v1', 'v10'),
                v10v1 = diGraph.findShortestPath('v10', 'v1');

            expect(v10v8.length).to.be.equal(1);
            expect(v10v8[0]).to.be.eql(['v10', 'v8']);

            expect(v1v7.length).to.be.equal(1);
            expect(v1v7[0]).to.be.eql(['v1', 'v9', 'v7']);

            expect(v6v2.length).to.be.equal(2);
            expect(v6v2[0]).to.be.eql(['v6', 'v5', 'v12', 'v7', 'v4', 'v2']);
            expect(v6v2[1]).to.be.eql(['v6', 'v5', 'v12', 'v7', 'v4', 'v8', 'v2']);

            expect(v3v12.length).to.be.equal(2);
            expect(v3v12[0]).to.be.eql(['v3', 'v4', 'v2', 'v12']);
            expect(v3v12[1]).to.be.eql(['v3', 'v4', 'v8', 'v2', 'v12']);

            expect(v12v3.length).to.be.equal(0);
            expect(v1v10.length).to.be.equal(0);
            expect(v10v1.length).to.be.equal(0);
        });

        it('should remove a direction', function() {
            diGraph.removeDirection('v10', 'v2');
            diGraph.removeDirection('v10', 'v8');
            diGraph.removeDirection('v10', 'v11');
            diGraph.removeDirection('v10', 'v12');
            diGraph.removeDirection('v11', 'v8');
            diGraph.removeDirection('v4', 'v11');

            expect(diGraph.getDirectionWeight('v10', 'v2')).to.be.equal(null);
            expect(diGraph.getDirectionWeight('v10', 'v8')).to.be.equal(null);
            expect(diGraph.getDirectionWeight('v10', 'v11')).to.be.equal(null);
            expect(diGraph.getDirectionWeight('v10', 'v12')).to.be.equal(null);
            expect(diGraph.getDirectionWeight('v11', 'v8')).to.be.equal(null);
            expect(diGraph.getDirectionWeight('v4', 'v11')).to.be.equal(null);
        });

        it('should get the separated vertices', function() {
            var s = diGraph.getSeparatedVertices();
            expect(s).to.be.have.members(['v10', 'v11']);
        });

        it('should remove a vertex', function() {
            diGraph.removeVertex('v2');

            expect(diGraph.countVertices()).to.be.equal(11);
            expect(diGraph.hasVertex('v2')).to.be.equal(false);
        });

    });
});<|endoftext|>


<commit_before>// How to perform preOrder traversal

//     23
//    /  \
//   16   45
//  / \   /  \
// 3 22  37  99

// Preorder traversal:
// 23 16 3 22 45 37 99

function preOrder( node ){
   if( node ){
      console.log( node.value ); // print out current node, then traverse
      preorder( node.left );
      preorder( node.right );
   }
}
<commit_msg>add note<commit_after>// How to perform preOrder traversal

// pre order: P L R

//     23
//    /  \
//   16   45
//  / \   /  \
// 3 22  37  99

// Preorder traversal:
// 23 16 3 22 45 37 99

function preOrder( node ){
   if( node ){
      console.log( node.value ); // print out current node, then traverse
      preorder( node.left );
      preorder( node.right );
   }
}
<|endoftext|>


<commit_before>$(document).ready(function(){
  $('form').on('submit', function(event){
    if (checkForm() == true) {
      event.preventDefault();
      setZipSession($('#user_zip').val());
      insertComma();
      getCandidates($(this));
    }
    else {
      if ($('#user_street_address').val().length < 1) {
        $('#user_street_address').val("Insert a street.");
      }
      if ($('#user_city').val().length < 1) {
        $('#user_city').val("Insert a city.");
      }
      if ($('#user_state').val().length < 1) {
        $('#user_state').val("Insert a state.");
      }
      if ($('#user_zip').val().length < 1) {
        $('#user_zip').val("Insert a zip code.");
      }
    }
  });
});

var checkForm = function() {
  if (($('#user_street_address').val().length > 1) && ($('#user_city').val().length > 1) && ($('#user_zip').val().length > 1) && ($('#user_state').val().length > 1)) {
    return true;
  }
  else {
    return false;
  }
}

var setZipSession = function(zip){
  var zipargs = {zip: zip}
  $.ajax({
    url: "/sessions/create_zip",
    data: zipargs,
    method: 'post'
  });
};

var insertComma = function() {
   $('#user_city').val($('#user_city').val() + ',');
}

var getCandidates = function(form) {
  formattedUrl = 'http://votesmart.org/x/search?s=' + $('#user_street_address').val() + '%20' + $('#user_city').val() + '%20' + $('#user_state').val() + '%20' + $('#user_zip').val();
  var candidatesRequest = $.ajax({
   method: 'get',
   url: formattedUrl
  });
 candidatesRequest.done(function(response){
  var candidateCreateRequest = $.ajax({
    url: "/candidates/create",
    data: response,
    method: 'post'
  });
  form.unbind('submit').submit();
 });
};<commit_msg>Fix congressional district bug (now congressional district will show)<commit_after>$(document).ready(function(){
  $('form').on('submit', function(event){
    if (checkForm() == true) {
      event.preventDefault();
      setZipSession($('#user_zip').val());
      insertComma();
      getCandidates($(this));
    }
    else {
      if ($('#user_street_address').val().length < 1) {
        $('#user_street_address').val("Insert a street.");
      }
      if ($('#user_city').val().length < 1) {
        $('#user_city').val("Insert a city.");
      }
      if ($('#user_state').val().length < 1) {
        $('#user_state').val("Insert a state.");
      }
      if ($('#user_zip').val().length < 1) {
        $('#user_zip').val("Insert a zip code.");
      }
    }
  });
});

var checkForm = function() {
  if (($('#user_street_address').val().length > 1) && ($('#user_city').val().length > 1) && ($('#user_zip').val().length > 1) && ($('#user_state').val().length > 1)) {
    return true;
  }
  else {
    return false;
  }
}

var setZipSession = function(zip){
  var zipargs = {zip: zip}
  $.ajax({
    url: "/sessions/create_zip",
    data: zipargs,
    method: 'post'
  });
};

var insertComma = function() {
   $('#user_city').val($('#user_city').val() + '');
}

var getCandidates = function(form) {
  formattedUrl = 'http://votesmart.org/x/search?s=' + $('#user_street_address').val() + '%20' + $('#user_city').val() + '%20' + $('#user_state').val() + '%20' + $('#user_zip').val();
  var candidatesRequest = $.ajax({
   method: 'get',
   url: formattedUrl
  });
 candidatesRequest.done(function(response){
  var candidateCreateRequest = $.ajax({
    url: "/candidates/create",
    data: response,
    method: 'post'
  });
  form.unbind('submit').submit();
 });
};<|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 120, sloppy: true, vars: true, white: true, plusplus: true, nonpropdel: true */
/*global require, db, ArangoCollection, ArangoDatabase, ArangoError, ArangoCursor,
         ShapedJson, RELOAD_AUTH, SYS_DEFINE_ACTION, SYS_EXECUTE_GLOBAL_CONTEXT_FUNCTION,
         DATABASEPATH, THREAD_NUMBER, AHUACATL_RUN, AHUACATL_PARSE, AHUACATL_EXPLAIN */

////////////////////////////////////////////////////////////////////////////////
/// @brief module "internal"
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2010-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 Module "internal"
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

(function () {
  var internal = require("internal");
  var console = require("console");

////////////////////////////////////////////////////////////////////////////////
/// @brief hide global variables
////////////////////////////////////////////////////////////////////////////////

  internal.db = db;
  delete db;

  internal.ArangoCollection = ArangoCollection;
  delete ArangoCollection;

  internal.ArangoDatabase = ArangoDatabase;
  delete ArangoDatabase;

  internal.ArangoError = ArangoError;
  delete ArangoError;

  internal.ArangoCursor = ArangoCursor;
  delete ArangoCursor;

  internal.ShapedJson = ShapedJson;
  delete ShapedJson;

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 private variables
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief database path
////////////////////////////////////////////////////////////////////////////////

  internal.DATABASEPATH = DATABASEPATH;
  delete DATABASEPATH;

////////////////////////////////////////////////////////////////////////////////
/// @brief internal thread number
////////////////////////////////////////////////////////////////////////////////

  internal.THREAD_NUMBER = THREAD_NUMBER;
  delete THREAD_NUMBER;

////////////////////////////////////////////////////////////////////////////////
/// @brief execute an AQL query
////////////////////////////////////////////////////////////////////////////////

  internal.AQL_QUERY = AHUACATL_RUN;
  delete AHUACATL_RUN;

////////////////////////////////////////////////////////////////////////////////
/// @brief parse an AQL query
////////////////////////////////////////////////////////////////////////////////

  internal.AQL_PARSE = AHUACATL_PARSE;
  delete AHUACATL_PARSE;

////////////////////////////////////////////////////////////////////////////////
/// @brief explain an AQL query
////////////////////////////////////////////////////////////////////////////////

  internal.AQL_EXPLAIN = AHUACATL_EXPLAIN;
  delete AHUACATL_EXPLAIN;

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief resets engine in development mode
////////////////////////////////////////////////////////////////////////////////

  internal.resetEngine = function () {
    internal.output("warning: routing engine resetted\n");
    require("org/arangodb/actions").reloadRouting();
  };

////////////////////////////////////////////////////////////////////////////////
/// @brief rebuilds the authentication cache
////////////////////////////////////////////////////////////////////////////////

  internal.reloadAuth = RELOAD_AUTH;
  delete RELOAD_AUTH;

////////////////////////////////////////////////////////////////////////////////
/// @brief defines an action
////////////////////////////////////////////////////////////////////////////////

  if (typeof SYS_DEFINE_ACTION === "undefined") {
    internal.defineAction = function() {
      console.error("SYS_DEFINE_ACTION not available");
    };

    internal.actionLoaded = function() {
    };
  }
  else {
    internal.defineAction = SYS_DEFINE_ACTION;
    delete SYS_DEFINE_ACTION;

    internal.actionLoaded = function() {
      var modules;
      var i;

      console.debug("actions loaded");

      modules = internal.db._collection("_modules");

      if (modules !== null) {
        modules = modules.byExample({ autoload: true }).toArray();

        for (i = 0;  i < modules.length;  ++i) {
          var module = modules[i];

          console.debug("autoloading module: %s", module.path);

          try {
            require(module.path);
          }
          catch (err) {
            console.error("while loading '%s': %s", module.path, String(err));
          }
        }
      }
    };
  }

////////////////////////////////////////////////////////////////////////////////
/// @brief initialize foxx applications
////////////////////////////////////////////////////////////////////////////////

  internal.initializeFoxx = function () {
    try {
      require("org/arangodb/foxx-manager").scanAppDirectory();
    }
    catch (err) {
      console.error("cannot initialize FOXX application: %s", String(err));
    }
  };

////////////////////////////////////////////////////////////////////////////////
/// @brief executes a string in all V8 contexts
////////////////////////////////////////////////////////////////////////////////

  if (typeof SYS_EXECUTE_GLOBAL_CONTEXT_FUNCTION === "undefined") {
    internal.executeGlobalContextFunction = function() {
      console.error("SYS_EXECUTE_GLOBAL_CONTEXT_FUNCTION not available");
    };
  }
  else {
    internal.executeGlobalContextFunction = SYS_EXECUTE_GLOBAL_CONTEXT_FUNCTION;
    delete SYS_EXECUTE_GLOBAL_CONTEXT_FUNCTION;
  }

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

}());

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}\\|/\\*jslint"
// End:
<commit_msg>added flushModuleCache for resetEngine<commit_after>/*jslint indent: 2, nomen: true, maxlen: 120, sloppy: true, vars: true, white: true, plusplus: true, nonpropdel: true */
/*global require, db, ArangoCollection, ArangoDatabase, ArangoError, ArangoCursor,
         ShapedJson, RELOAD_AUTH, SYS_DEFINE_ACTION, SYS_EXECUTE_GLOBAL_CONTEXT_FUNCTION,
         DATABASEPATH, THREAD_NUMBER, AHUACATL_RUN, AHUACATL_PARSE, AHUACATL_EXPLAIN */

////////////////////////////////////////////////////////////////////////////////
/// @brief module "internal"
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2010-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 Module "internal"
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

(function () {
  var internal = require("internal");
  var console = require("console");

////////////////////////////////////////////////////////////////////////////////
/// @brief hide global variables
////////////////////////////////////////////////////////////////////////////////

  internal.db = db;
  delete db;

  internal.ArangoCollection = ArangoCollection;
  delete ArangoCollection;

  internal.ArangoDatabase = ArangoDatabase;
  delete ArangoDatabase;

  internal.ArangoError = ArangoError;
  delete ArangoError;

  internal.ArangoCursor = ArangoCursor;
  delete ArangoCursor;

  internal.ShapedJson = ShapedJson;
  delete ShapedJson;

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 private variables
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief database path
////////////////////////////////////////////////////////////////////////////////

  internal.DATABASEPATH = DATABASEPATH;
  delete DATABASEPATH;

////////////////////////////////////////////////////////////////////////////////
/// @brief internal thread number
////////////////////////////////////////////////////////////////////////////////

  internal.THREAD_NUMBER = THREAD_NUMBER;
  delete THREAD_NUMBER;

////////////////////////////////////////////////////////////////////////////////
/// @brief execute an AQL query
////////////////////////////////////////////////////////////////////////////////

  internal.AQL_QUERY = AHUACATL_RUN;
  delete AHUACATL_RUN;

////////////////////////////////////////////////////////////////////////////////
/// @brief parse an AQL query
////////////////////////////////////////////////////////////////////////////////

  internal.AQL_PARSE = AHUACATL_PARSE;
  delete AHUACATL_PARSE;

////////////////////////////////////////////////////////////////////////////////
/// @brief explain an AQL query
////////////////////////////////////////////////////////////////////////////////

  internal.AQL_EXPLAIN = AHUACATL_EXPLAIN;
  delete AHUACATL_EXPLAIN;

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoShell
/// @{
////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////
/// @brief resets engine in development mode
////////////////////////////////////////////////////////////////////////////////

  internal.resetEngine = function () {
    internal.flushModuleCache();
    require("org/arangodb/actions").reloadRouting();
  };

////////////////////////////////////////////////////////////////////////////////
/// @brief rebuilds the authentication cache
////////////////////////////////////////////////////////////////////////////////

  internal.reloadAuth = RELOAD_AUTH;
  delete RELOAD_AUTH;

////////////////////////////////////////////////////////////////////////////////
/// @brief defines an action
////////////////////////////////////////////////////////////////////////////////

  if (typeof SYS_DEFINE_ACTION === "undefined") {
    internal.defineAction = function() {
      console.error("SYS_DEFINE_ACTION not available");
    };

    internal.actionLoaded = function() {
    };
  }
  else {
    internal.defineAction = SYS_DEFINE_ACTION;
    delete SYS_DEFINE_ACTION;

    internal.actionLoaded = function() {
      var modules;
      var i;

      console.debug("actions loaded");

      modules = internal.db._collection("_modules");

      if (modules !== null) {
        modules = modules.byExample({ autoload: true }).toArray();

        for (i = 0;  i < modules.length;  ++i) {
          var module = modules[i];

          console.debug("autoloading module: %s", module.path);

          try {
            require(module.path);
          }
          catch (err) {
            console.error("while loading '%s': %s", module.path, String(err));
          }
        }
      }
    };
  }

////////////////////////////////////////////////////////////////////////////////
/// @brief initialize foxx applications
////////////////////////////////////////////////////////////////////////////////

  internal.initializeFoxx = function () {
    try {
      require("org/arangodb/foxx-manager").scanAppDirectory();
    }
    catch (err) {
      console.error("cannot initialize FOXX application: %s", String(err));
    }
  };

////////////////////////////////////////////////////////////////////////////////
/// @brief executes a string in all V8 contexts
////////////////////////////////////////////////////////////////////////////////

  if (typeof SYS_EXECUTE_GLOBAL_CONTEXT_FUNCTION === "undefined") {
    internal.executeGlobalContextFunction = function() {
      console.error("SYS_EXECUTE_GLOBAL_CONTEXT_FUNCTION not available");
    };
  }
  else {
    internal.executeGlobalContextFunction = SYS_EXECUTE_GLOBAL_CONTEXT_FUNCTION;
    delete SYS_EXECUTE_GLOBAL_CONTEXT_FUNCTION;
  }

////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////

}());

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}\\|/\\*jslint"
// End:
<|endoftext|>


<commit_before>import Ember from 'ember';

const Logger = Ember.Logger;

class ErrorHandler {
  constructor(reporter) {
    this.reporter = reporter;
  }

  report(error) {
    // If you pass a POJO to TrackJS, you'll see "[object Object]"
    // in reports instead of object content. :(

    // If the error is an Error object, we pass it directly.
    if (error instanceof Error) {
      this.reporter.track(error);
      Logger.error(error.stack);

      return;
    }

    // Otherwise, we have to serialize it manually in order
    // to see something better than "[object Object]".
    let serializedError;

    try {
      // This will work for both primitives and POJOs:
      serializedError = JSON.stringify(error, null, 2);
    } catch (e) {
      // Protecting against circular reference errors
      if (e.message === "Converting circular structure to JSON") {
        // We have an object with circular references and thus
        // we can't serialize it into JSON. We have to extract
        // info from it manually.
        serializedError =
          `Object with circular references passed instead of an instance of Error.
            error.message: ${error.message}
            error.name:    ${error.name}
          `;
      } else {
        // Some other error happened in JSON.stringify, rethrowing.
        throw e;
      }
    }

    this.reporter.track(serializedError);
    Logger.error(error);
  }
}

export default ErrorHandler;
<commit_msg>Show error with message in console<commit_after>import Ember from 'ember';

const Logger = Ember.Logger;

// https://github.com/emberjs/ember.js/blob/master/packages/ember-metal/lib/error_handler.js#L4-L14
const getStack = error => {
  let stack = error.stack;
  let message = error.message;

  if (stack && !stack.includes(message)) {
    stack = `${message}\n${stack}`;
  }

  return stack;
};

class ErrorHandler {
  constructor(reporter) {
    this.reporter = reporter;
  }

  report(error) {
    // If you pass a POJO to TrackJS, you'll see "[object Object]"
    // in reports instead of object content. :(

    // If the error is an Error object, we pass it directly.
    if (error instanceof Error) {
      this.reporter.track(error);
      Logger.error(getStack(error));

      return;
    }

    // Otherwise, we have to serialize it manually in order
    // to see something better than "[object Object]".
    let serializedError;

    try {
      // This will work for both primitives and POJOs:
      serializedError = JSON.stringify(error, null, 2);
    } catch (e) {
      // Protecting against circular reference errors
      if (e.message === "Converting circular structure to JSON") {
        // We have an object with circular references and thus
        // we can't serialize it into JSON. We have to extract
        // info from it manually.
        serializedError =
          `Object with circular references passed instead of an instance of Error.
            error.message: ${error.message}
            error.name:    ${error.name}
          `;
      } else {
        // Some other error happened in JSON.stringify, rethrowing.
        throw e;
      }
    }

    this.reporter.track(serializedError);
    Logger.error(error);
  }
}

export default ErrorHandler;
<|endoftext|>


<commit_before>preOrderTraversal.js
<commit_msg>add desc<commit_after>// How to perform preOrder traversal

<|endoftext|>