<commit_before>import $ from 'jquery';
import _ from 'underscore';
import Backbone from 'backbone';
import BaseView from 'picnic/core/views/Base';

/**
 * A generic template view to render an underscore.js template string. The
 * rendered template can be accessed by the property "content" (jQuery object)
 * on each instance of this class.
 *
 * To render a certain template, simply overwrite the "template" getter inside
 * the inheriting class and return an underscore template string.
 *
 * By default, an instance of this view passes the serialized model and
 * collection into the template context.
 *
 * @class Template-View
 * @example
 *		import TemplateView from 'picnic/core/commands/Initialize';
 *		import Template from 'app/modules/example/views/Example.html!text'
 *
 *		class View extends TemplateView {
 *
 *			get template() {
 *				return Template;
 *			}
 *
 * 		}
 *
 *		export default View;
 *
 * @example
 *		import TemplateView from 'picnic/core/commands/Initialize';
 *		import Template from 'app/modules/example/views/Example.html!text'
 *
 *		class View extends TemplateView {
 *
 *			constructor(options) {
 *				super(options);
 *
 *				// Re-render content on model change. Pay attention to remove
 *				// possible eventlisteners from previous content!
 *				this.model.on('change', () => {
 *					this.render();
 *				});
 *			}
 *
 *			get template() {
 *				return Template;
 *			}
 *
 * 		}
 *
 *		export default View;
 */
class View extends BaseView {

	constructor(options) {
		super(options);

		if (!this.template) {
			throw new Error('Define a template by overwrite the "get template()" property of the TemplateView.');
		}
	}

	/**
	 * This is the getter for the required underscore.js template string. This
	 * getter needs to be overwritten when inheriting from this class.
	 *
	 * @return {string} is the underscore.js template string.
	 */
	get template() {
		return this.options.template;
	}

	/**
	 * This is the getter which retuns the context data for the template. By
	 * default it will return an object, with the serialized model and
	 * collection data, when passed to the constructor of this instance.
	 *
	 * Whether model or collection may be undefined, each property will be null
	 * in the returned object.
	 *
	 * @return {object} is the template context.
	 */
	get data() {
		var data = {
			model: this.model instanceof Backbone.Model ? this.model.toJSON() : this.model || null,
			collection: this.collection instanceof Backbone.Collection ? this.collection.toJSON() : this.collection || null
		};

		return data;
	}

	/**
	 * This getter returns the target where to add the rendered content. By
	 * default it will return the this.$el value of a backbone view. The return
	 * value must be a DOM- or jQuery-element.
	 *
	 * @return {DOMElement|jQuery} is the target where to add the rendered content.
	 */
	get target() {
		return this.$el;
	}

	/**
	 * This returns the rendering strategy how to add the created content to a
	 * certain `target`. It supports the following values which map to the
	 * identically named jQuery functions:
	 *
	 * * "appendTo" (default) – TemplateView.STRATEGY_APPEND
	 * * "insertBefore" – TemplateView.STRATEGY_BEFORE
	 * * "insertAfter" – TemplateView.STRATEGY_AFTER
	 *
	 * All jQuery insertion strategies will be used in relation to the `.target`
	 * element
	 *
	 * @return {string} is the jQuery function how to add the rendered content.
	 */
	get strategy() {
		return this.options.strategy || View.STRATEGY_APPEND;
	}

	/**
	 * This renders the content of this view.
	 *
	 * @return {view} is the instance of this view.
	 */
	render() {
		var
			template = _.template(this.template),
			data = this.data,
			strategy = this.strategy,
			target = $(this.target),
			previous
		;

		// This block allows a re-rendering of the view instance's content
		// at the same DOM position like the previous content was rendered...
		if (this.content) {
			strategy = View.STRATEGY_AFTER;
			target = this.content.off();
			previous = target;
		}

		this.content = $(template(data))[strategy](target);

		// When there was a previous content, remove them from the DOM...
		if (previous) {
			previous.remove();
		}

		return this;
	}

	/**
	 * Destroys this view.
	 */
	destroy() {
		this.content.off().remove();
		super.destroy();
	}

}

View.STRATEGY_APPEND = 'appendTo';
View.STRATEGY_BEFORE = 'insertBefore';
View.STRATEGY_AFTER = 'insertAfter';

export default View;
<commit_msg>Update template view documentation<commit_after>import $ from 'jquery';
import _ from 'underscore';
import Backbone from 'backbone';
import BaseView from 'picnic/core/views/Base';

/**
 * A generic template view to render an underscore.js template string. The
 * rendered template can be accessed by the property "content" (jQuery object)
 * on each instance of this class.
 *
 * To render a certain template, simply overwrite the "template" getter inside
 * the inheriting class and return an underscore template string.
 *
 * By default, an instance of this view passes the serialized model and
 * collection into the template context.
 *
 * @class Template-View
 * @example
 *		import Backbone from 'backbone';
 *		import TemplateView from 'picnic/core/views/Template';
 *		import Template from 'app/modules/example/views/Example.html!text'
 *
 *		var model = new Backbone.Model({id: 1});
 *
 *		new TemplateView({
 *			el: document.body,
 *			context: app.context,
 *			template: Template,
 *			model: model
 *		}).render();
 *
 * @example
 *		import TemplateView from 'picnic/core/views/Template';
 *		import Template from 'app/modules/example/views/Example.html!text'
 *
 *		class View extends TemplateView {
 *
 *			get template() {
 *				return Template;
 *			}
 *
 * 		}
 *
 *		export default View;
 *
 * @example
 *		import TemplateView from 'picnic/core/views/Template';
 *		import Template from 'app/modules/example/views/Example.html!text'
 *
 *		class View extends TemplateView {
 *
 *			constructor(options) {
 *				super(options);
 *
 *				// Re-render content on model change. Pay attention to remove
 *				// possible eventlisteners from previous content!
 *				this.model.on('change', () => {
 *					this.render();
 *				});
 *			}
 *
 *			get template() {
 *				return Template;
 *			}
 *
 * 		}
 *
 *		export default View;
 */
class View extends BaseView {

	/**
	 * Creates an instance of this view.
	 *
	 * @constructor
	 * @param {object} options The settings for the view.
	 * @param {context} options.context The reference to the
	 *		backbone.geppetto context.
	 * @param {DOMElement|$Element} options.el the element reference for a
	 *		backbone.view.
	 * @param {string} options.template is the underscore.js template string.
	 * @param {string} options.strategy allows to change the default rendering
	 *		strategy. For more details take a look at the `.strategy` getter of
	 *		this class.
	 */
	constructor(options) {
		super(options);

		if (!this.template) {
			throw new Error('Define a template by overwrite the "get template()" property of the TemplateView.');
		}
	}

	/**
	 * This is the getter for the required underscore.js template string. This
	 * getter needs to be overwritten when inheriting from this class.
	 *
	 * @return {string} is the underscore.js template string.
	 */
	get template() {
		return this.options.template;
	}

	/**
	 * This is the getter which retuns the context data for the template. By
	 * default it will return an object, with the serialized model and
	 * collection data, when passed to the constructor of this instance.
	 *
	 * Whether model or collection may be undefined, each property will be null
	 * in the returned object.
	 *
	 * @return {object} is the template context.
	 */
	get data() {
		var data = {
			model: this.model instanceof Backbone.Model ? this.model.toJSON() : this.model || null,
			collection: this.collection instanceof Backbone.Collection ? this.collection.toJSON() : this.collection || null
		};

		return data;
	}

	/**
	 * This getter returns the target where to add the rendered content. By
	 * default it will return the this.$el value of a backbone view. The return
	 * value must be a DOM- or jQuery-element.
	 *
	 * @return {DOMElement|$Element} is the target where to add the rendered content.
	 */
	get target() {
		return this.$el;
	}

	/**
	 * This returns the rendering strategy how to add the created content to a
	 * certain `target`. It supports the following values which map to the
	 * identically named jQuery functions:
	 *
	 * * "appendTo" (default) – TemplateView.STRATEGY_APPEND
	 * * "insertBefore" – TemplateView.STRATEGY_BEFORE
	 * * "insertAfter" – TemplateView.STRATEGY_AFTER
	 *
	 * All jQuery insertion strategies will be used in relation to the `.target`
	 * element
	 *
	 * @return {string} is the jQuery function how to add the rendered content.
	 */
	get strategy() {
		return this.options.strategy || View.STRATEGY_APPEND;
	}

	/**
	 * This renders the content of this view.
	 *
	 * @return {view} is the instance of this view.
	 */
	render() {
		var
			template = _.template(this.template),
			data = this.data,
			strategy = this.strategy,
			target = $(this.target),
			previous
		;

		// This block allows a re-rendering of the view instance's content
		// at the same DOM position like the previous content was rendered...
		if (this.content) {
			strategy = View.STRATEGY_AFTER;
			target = this.content.off();
			previous = target;
		}

		this.content = $(template(data))[strategy](target);

		// When there was a previous content, remove them from the DOM...
		if (previous) {
			previous.remove();
		}

		return this;
	}

	/**
	 * Destroys this view.
	 */
	destroy() {
		this.content.off().remove();
		super.destroy();
	}

}

View.STRATEGY_APPEND = 'appendTo';
View.STRATEGY_BEFORE = 'insertBefore';
View.STRATEGY_AFTER = 'insertAfter';

export default View;
<|endoftext|>


<commit_before>/**
 * jQRangeSlider
 * A javascript slider selector that supports dates
 *
 * Copyright (C) Guillaume Gautreau 2012
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 */

 (function($, undefined){
	"use strict";

	$.widget("ui.rangeSliderHandle", $.ui.rangeSliderDraggable, {
		currentMove: null,
		margin: 0,
		parentElement: null,

		options: {
			isLeft: true,
			bounds: {min:0, max:100},
			range: false,
			value: 0,
			step: false
		},

		_value: 0,
		_left: 0,

		_create: function(){
			$.ui.rangeSliderDraggable.prototype._create.apply(this);

			this.element
				.css("position", "absolute")
				.css("top", 0)
				.addClass("ui-rangeSlider-handle")
				.toggleClass("ui-rangeSlider-leftHandle", this.options.isLeft)
				.toggleClass("ui-rangeSlider-rightHandle", !this.options.isLeft);

			this._value = this.options.value;
		},

		_setOption: function(key, value){
			if (key === "isLeft" && (value === true || value === false) && value !== this.options.isLeft){
				this.options.isLeft = value;

				this.element
					.toggleClass("ui-rangeSlider-leftHandle", this.options.isLeft)
					.toggleClass("ui-rangeSlider-rightHandle", !this.options.isLeft);

				this._position(this._value);

				this.element.trigger("switch", this.options.isLeft);
			} else if (key === "step" && this._checkStep(value)){
				this.options.step = value;
				this.update();
			} else if (key === "bounds"){
				this.options.bounds = value;
				this.update();
			}else if (key === "range" && this._checkRange(value)){
				this.options.range = value;
				this.update();
			}

			$.ui.rangeSliderDraggable.prototype._setOption.apply(this, [key, value]);
		},

		_checkRange: function(range){
			return range === false || (!this._isValidValue(range.min) && !this._isValidValue(range.max));
		},

		_isValidValue: function(value){
			return typeof value !== "undefined" && value !== false && parseFloat(value) === value;
		},

		_checkStep: function(step){
			return (step === false || parseFloat(step) === step);
		},

		_initElement: function(){
			$.ui.rangeSliderDraggable.prototype._initElement.apply(this);

			if (this.cache.parent.width === 0 || this.cache.parent.width === null){
				setTimeout($.proxy(this._initElement, this), 500);
			}else{
				this._position(this._value);
				this._triggerMouseEvent("initialize");
			}
		},

		_bounds: function(){
			return this.options.bounds;
		},

		/*
		 * From draggable
		 */

		_cache: function(){
			$.ui.rangeSliderDraggable.prototype._cache.apply(this);

			this._cacheParent();
		},

		_cacheParent: function(){
			var parent = this.element.parent();

			this.cache.parent = {
				element: parent,
				offset: parent.offset(),
				padding: {
					left: this._parsePixels(parent, "paddingLeft")
				},
				width: parent.width()
			}
		},

		_position: function(value){
			var left = this._getPositionForValue(value);

			this._applyPosition(left);
		},

		_constraintPosition: function(position){
			var value = this._getValueForPosition(position);

			return this._getPositionForValue(value);
		},

		_applyPosition: function(left){
			$.ui.rangeSliderDraggable.prototype._applyPosition.apply(this, [left]);

			this._left = left;
			this._setValue(this._getValueForPosition(left));
			this._triggerMouseEvent("moving");
		},

		_prepareEventData: function(){
			var data = $.ui.rangeSliderDraggable.prototype._prepareEventData.apply(this);

			data.value = this._value;

			return data;
		},

		/*
		 * Value
		 */
		_setValue: function(value){
			if (value !== this._value){
				this._value = value;
			}
		},

		_constraintValue: function(value){
			value = Math.min(value, this._bounds().max);
			value = Math.max(value, this._bounds().min);

			value = this._round(value);

			if (this.options.range !== false){
				var min = this.options.range.min || false,
					max = this.options.range.max || false;

				if (min !== false){
					value = Math.max(value, this._round(min));
				}

				if (max !== false){
					value = Math.min(value, this._round(max));
				}
			}

			return value;
		},

		_round: function(value){
			if (this.options.step !== false && this.options.step > 0){
				return Math.round(value / this.options.step) * this.options.step;
			}

			return value;
		},

		_getPositionForValue: function(value){
			if (this.cache.parent.offset === null){
				return 0;
			}

			value = this._constraintValue(value);

			var ratio = (value - this.options.bounds.min) / (this.options.bounds.max - this.options.bounds.min),
				availableWidth = this.cache.parent.width - this.cache.width.outer,
				parentPosition = this.cache.parent.offset.left;

			return ratio * availableWidth + parentPosition;
		},

		_getValueForPosition: function(position){
			var raw = this._getRawValueForPositionAndBounds(position, this.options.bounds.min, this.options.bounds.max);

			return this._constraintValue(raw);
		},

		_getRawValueForPositionAndBounds: function(position, min, max){
			var parentPosition =  this.cache.parent.offset === null ? 0 : this.cache.parent.offset.left,
					availableWidth = this.cache.parent.width - this.cache.width.outer,
					ratio = (position - parentPosition) / availableWidth;

			return	ratio * (max - min) + min;
		},

		/*
		 * Public
		 */

		value: function(value){
			if (typeof value !== "undefined"){
				this._cache();

				value = this._constraintValue(value);

				this._position(value);
			}

			return this._value;
		},

		update: function(){
			this._cache();
			var value = this._constraintValue(this._value),
				position = this._getPositionForValue(value);

			if (value !== this._value){
				this._triggerMouseEvent("updating");
				this._position(value);
				this._triggerMouseEvent("update");
			}else if (position !== this.cache.offset.left){
				this._triggerMouseEvent("updating");
				this._position(value);
				this._triggerMouseEvent("update");
			}
		},

		position: function(position){
			if (typeof position !== "undefined"){
				this._cache();

				position = this._constraintPosition(position);
				this._applyPosition(position);
			}

			return this._left;
		},

		add: function(value, step){
			return value + step;
		},

		substract: function(value, step){
			return value - step;
		},

		stepsBetween: function(val1, val2){
			if (this.options.step === false){
				return val2 - val1;
			}

			return (val2 - val1) / this.options.step;
		},

		multiplyStep: function(step, factor){
			return step * factor;
		},

		moveRight: function(quantity){
			var previous;

			if (this.options.step === false){
				previous = this._left;
				this.position(this._left + quantity);

				return this._left - previous;
			}

			previous = this._value;
			this.value(this.add(previous, this.multiplyStep(this.options.step, quantity)));

			return this.stepsBetween(previous, this._value);
		},

		moveLeft: function(quantity){
			return -this.moveRight(-quantity);
		},

		stepRatio: function(){
			if (this.options.step === false){
				return 1;
			}else{
				var steps = (this.options.bounds.max - this.options.bounds.min) / this.options.step;
				return this.cache.parent.width / steps;
			}
		}
	});
 }(jQuery));
<commit_msg>Bug introduced in previous revisions when fixing JSHints<commit_after>/**
 * jQRangeSlider
 * A javascript slider selector that supports dates
 *
 * Copyright (C) Guillaume Gautreau 2012
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 */

 (function($, undefined){
	"use strict";

	$.widget("ui.rangeSliderHandle", $.ui.rangeSliderDraggable, {
		currentMove: null,
		margin: 0,
		parentElement: null,

		options: {
			isLeft: true,
			bounds: {min:0, max:100},
			range: false,
			value: 0,
			step: false
		},

		_value: 0,
		_left: 0,

		_create: function(){
			$.ui.rangeSliderDraggable.prototype._create.apply(this);

			this.element
				.css("position", "absolute")
				.css("top", 0)
				.addClass("ui-rangeSlider-handle")
				.toggleClass("ui-rangeSlider-leftHandle", this.options.isLeft)
				.toggleClass("ui-rangeSlider-rightHandle", !this.options.isLeft);

			this._value = this.options.value;
		},

		_setOption: function(key, value){
			if (key === "isLeft" && (value === true || value === false) && value !== this.options.isLeft){
				this.options.isLeft = value;

				this.element
					.toggleClass("ui-rangeSlider-leftHandle", this.options.isLeft)
					.toggleClass("ui-rangeSlider-rightHandle", !this.options.isLeft);

				this._position(this._value);

				this.element.trigger("switch", this.options.isLeft);
			} else if (key === "step" && this._checkStep(value)){
				this.options.step = value;
				this.update();
			} else if (key === "bounds"){
				this.options.bounds = value;
				this.update();
			}else if (key === "range" && this._checkRange(value)){
				this.options.range = value;
				this.update();
			}

			$.ui.rangeSliderDraggable.prototype._setOption.apply(this, [key, value]);
		},

		_checkRange: function(range){
			return range === false || (!this._isValidValue(range.min) && !this._isValidValue(range.max));
		},

		_isValidValue: function(value){
			return typeof value !== "undefined" && value !== false && parseFloat(value) !== value;
		},

		_checkStep: function(step){
			return (step === false || parseFloat(step) === step);
		},

		_initElement: function(){
			$.ui.rangeSliderDraggable.prototype._initElement.apply(this);

			if (this.cache.parent.width === 0 || this.cache.parent.width === null){
				setTimeout($.proxy(this._initElement, this), 500);
			}else{
				this._position(this._value);
				this._triggerMouseEvent("initialize");
			}
		},

		_bounds: function(){
			return this.options.bounds;
		},

		/*
		 * From draggable
		 */

		_cache: function(){
			$.ui.rangeSliderDraggable.prototype._cache.apply(this);

			this._cacheParent();
		},

		_cacheParent: function(){
			var parent = this.element.parent();

			this.cache.parent = {
				element: parent,
				offset: parent.offset(),
				padding: {
					left: this._parsePixels(parent, "paddingLeft")
				},
				width: parent.width()
			}
		},

		_position: function(value){
			var left = this._getPositionForValue(value);

			this._applyPosition(left);
		},

		_constraintPosition: function(position){
			var value = this._getValueForPosition(position);

			return this._getPositionForValue(value);
		},

		_applyPosition: function(left){
			$.ui.rangeSliderDraggable.prototype._applyPosition.apply(this, [left]);

			this._left = left;
			this._setValue(this._getValueForPosition(left));
			this._triggerMouseEvent("moving");
		},

		_prepareEventData: function(){
			var data = $.ui.rangeSliderDraggable.prototype._prepareEventData.apply(this);

			data.value = this._value;

			return data;
		},

		/*
		 * Value
		 */
		_setValue: function(value){
			if (value !== this._value){
				this._value = value;
			}
		},

		_constraintValue: function(value){
			value = Math.min(value, this._bounds().max);
			value = Math.max(value, this._bounds().min);

			value = this._round(value);

			if (this.options.range !== false){
				var min = this.options.range.min || false,
					max = this.options.range.max || false;

				if (min !== false){
					value = Math.max(value, this._round(min));
				}

				if (max !== false){
					value = Math.min(value, this._round(max));
				}
			}

			return value;
		},

		_round: function(value){
			if (this.options.step !== false && this.options.step > 0){
				return Math.round(value / this.options.step) * this.options.step;
			}

			return value;
		},

		_getPositionForValue: function(value){
			if (this.cache.parent.offset === null){
				return 0;
			}

			value = this._constraintValue(value);

			var ratio = (value - this.options.bounds.min) / (this.options.bounds.max - this.options.bounds.min),
				availableWidth = this.cache.parent.width - this.cache.width.outer,
				parentPosition = this.cache.parent.offset.left;

			return ratio * availableWidth + parentPosition;
		},

		_getValueForPosition: function(position){
			var raw = this._getRawValueForPositionAndBounds(position, this.options.bounds.min, this.options.bounds.max);

			return this._constraintValue(raw);
		},

		_getRawValueForPositionAndBounds: function(position, min, max){
			var parentPosition =  this.cache.parent.offset === null ? 0 : this.cache.parent.offset.left,
					availableWidth = this.cache.parent.width - this.cache.width.outer,
					ratio = (position - parentPosition) / availableWidth;

			return	ratio * (max - min) + min;
		},

		/*
		 * Public
		 */

		value: function(value){
			if (typeof value !== "undefined"){
				this._cache();

				value = this._constraintValue(value);

				this._position(value);
			}

			return this._value;
		},

		update: function(){
			this._cache();
			var value = this._constraintValue(this._value),
				position = this._getPositionForValue(value);

			if (value !== this._value){
				this._triggerMouseEvent("updating");
				this._position(value);
				this._triggerMouseEvent("update");
			}else if (position !== this.cache.offset.left){
				this._triggerMouseEvent("updating");
				this._position(value);
				this._triggerMouseEvent("update");
			}
		},

		position: function(position){
			if (typeof position !== "undefined"){
				this._cache();

				position = this._constraintPosition(position);
				this._applyPosition(position);
			}

			return this._left;
		},

		add: function(value, step){
			return value + step;
		},

		substract: function(value, step){
			return value - step;
		},

		stepsBetween: function(val1, val2){
			if (this.options.step === false){
				return val2 - val1;
			}

			return (val2 - val1) / this.options.step;
		},

		multiplyStep: function(step, factor){
			return step * factor;
		},

		moveRight: function(quantity){
			var previous;

			if (this.options.step === false){
				previous = this._left;
				this.position(this._left + quantity);

				return this._left - previous;
			}

			previous = this._value;
			this.value(this.add(previous, this.multiplyStep(this.options.step, quantity)));

			return this.stepsBetween(previous, this._value);
		},

		moveLeft: function(quantity){
			return -this.moveRight(-quantity);
		},

		stepRatio: function(){
			if (this.options.step === false){
				return 1;
			}else{
				var steps = (this.options.bounds.max - this.options.bounds.min) / this.options.step;
				return this.cache.parent.width / steps;
			}
		}
	});
 }(jQuery));
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Route.extend({
  controllerName: 'cabin',

  model: function (params) {
    return this.store.createRecord('cabin');
  },

  setupController: function (controller, model) {
    controller.set('model', model);
  },

  renderTemplate: function () {
    this.render('cabins/edit');

    this.render('cabins/toolbar', {
      into: 'application',
      outlet: 'toolbar'
    });
  }
});
<commit_msg>Updated incorrect template name which broke new cabin route<commit_after>import Ember from 'ember';

export default Ember.Route.extend({
  controllerName: 'cabin',

  model: function (params) {
    return this.store.createRecord('cabin');
  },

  setupController: function (controller, model) {
    controller.set('model', model);
  },

  renderTemplate: function () {
    this.render('cabins/edit');

    this.render('cabins/header-right', {
      into: 'application',
      outlet: 'header-right'
    });
  }
});
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */
var app = {
    // Application Constructor
        initialize: function() {
            this.bindEvents();
        },
        // Bind Event Listeners
        //
        // Bind any events that are required on startup. Common events are:
        // 'load', 'deviceready', 'offline', and 'online'.
        bindEvents: function() {
            document.addEventListener('deviceready', this.onDeviceReady, false);
        },
        onDeviceReady: function() {
            navigator.accelerometer.getCurrentAccleration(app.onSuccess, app.onError);
            alert("accelerometer called");
        },
        onSuccess: function(acceleration) {//success fully got the acceleration
            alert('Accelaration X ' + acceleration.x + '\n' +
                    'Accelaration Y ' + acceleration.y + '\n' +
                    'Accelaration Z ' + acceleration.z + '\n' +
                    'TimeStamp  ' + acceleration.timestamp + '\n');
        },
        onError: function() {// Failed to get the acceleration
            alert('Accelerometer Error');
        }

};
<commit_msg>only the testing file<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */
var app = {
    // Application Constructor
        initialize: function() {
            this.bindEvents();
        },
        // Bind Event Listeners
        //
        // Bind any events that are required on startup. Common events are:
        // 'load', 'deviceready', 'offline', and 'online'.
        bindEvents: function() {
            document.addEventListener('deviceready', this.onDeviceReady, false);
        },
        onDeviceReady: function() {
            navigator.accelerometer.getCurrentAcceleration(this.onSuccess, this.onError);
            alert("accelerometer called");
        },
        onSuccess: function(acceleration) {//success fully got the acceleration
            alert('Accelaration X ' + acceleration.x + '\n' +
                    'Accelaration Y ' + acceleration.y + '\n' +
                    'Accelaration Z ' + acceleration.z + '\n' +
                    'TimeStamp  ' + acceleration.timestamp + '\n');
        },
        onError: function() {// Failed to get the acceleration
            alert('Accelerometer Error');
        }

};
<|endoftext|>


<commit_before>'use strict';

var config = require('./config/config.js')();
var ESOptions = require('./es-options.js');

var seneca = require('seneca')();

seneca.log.info('using config', JSON.stringify(config, null, 4));

seneca.options(config);

seneca.use('postgresql-store', config["postgresql-store"]);
seneca.use('elasticsearch', _.defaults(config["elasticsearch"], ESOptions));
seneca.use(require('./es.js'));
seneca.use(require('./agreements.js'));
seneca.use(require('./users.js'));
seneca.use('user');

seneca.listen();
<commit_msg>added missing lodash<commit_after>'use strict';
var _ =require('lodash');

var config = require('./config/config.js')();
var ESOptions = require('./es-options.js');

var seneca = require('seneca')();

seneca.log.info('using config', JSON.stringify(config, null, 4));

seneca.options(config);

seneca.use('postgresql-store', config["postgresql-store"]);
seneca.use('elasticsearch', _.defaults(config["elasticsearch"], ESOptions));
seneca.use(require('./es.js'));
seneca.use(require('./agreements.js'));
seneca.use(require('./users.js'));
seneca.use('user');

seneca.listen();
<|endoftext|>


<commit_before>var globals = require('lib/globals');
var scheduleTableView = '';

exports.scheduleWindow = function() {
  var instance = Ti.UI.createWindow({
    title: 'Schedule',
    backgroundColor: '#eeeeee'
  });
  instance.orientationModes = [Ti.UI.PORTRAIT];

  // Android Specific Code
  if (globals.osname === 'android') {
    instance.backgroundColor = "#111111";
    instance.activity.onCreateOptionsMenu = function(e) {
      var menu = e.menu;
      var menuItem = menu.add({title:"Refresh"});
      menuItem.addEventListener("click", function(e) {
        Ti.App.fireEvent('events.update');
      });
    };
  }

  // iPhone Specific Code
  if (globals.osname === 'iphone' || globals.osname === 'ipad') {
    var refresh = Ti.UI.createButton({
      systemButton:Ti.UI.iPhone.SystemButton.REFRESH
    });
    refresh.addEventListener('click', function(e) {
      Ti.App.fireEvent('events.update', {prune: true});
    });
    instance.rightNavButton = refresh;
  }

  var scheduleData = getEventData();
  scheduleTableView = Ti.UI.createTableView({
    data:scheduleData,
    separatorColor: '#eeeeee',
    backgroundColor: '#eeeeee'
  });
  scheduleTableView.addEventListener('click', function(x) {
    //Ti.API.info("x = "+x.row.hasChild);
    if (x.row.hasChild) {
      Ti.App.fireEvent('schedule.click', {nid: x.row.nid});
    }
  });
  instance.add(scheduleTableView);

  instance.addEventListener('open', function(e) {
    instance.addEventListener('focus', function(f) {
      Ti.App.fireEvent('events.update');
    });
  });

  return instance;
};

Ti.App.addEventListener('schedule.updateTableView', function(x) {
  var scheduleData = getEventData();
  scheduleTableView.setData(scheduleData);
});

// Will return an array for use in a TableView
function getEventData() {
  var events = globals.dbGetEvents();
  var x;
  var data = [];
  var header = '';
  var currentDay = '';
  var currentSection = '';
  var row = '';
  var time, room, title, topView, bottomView, timeLabel, roomLabel, titleLabel;
  for (x in events) {
    //Ti.API.info(x);
    currentDay = events[x].day;
    time = globals.secondsToTime(events[x].datefrom) + "-" +
           globals.secondsToTime(events[x].dateto);
    room = events[x].room;
    title = globals.html_decode(events[x].title);
    row = Ti.UI.createTableViewRow({
      height: 50,
      backgroundColor: '#eeeeee',
      layout: 'absolute'
    });
    if (events[x].eventtype == 'Workshop') {
      row.hasChild = true;
    }
    timeLabel = Ti.UI.createLabel({
      text: time,
      color: '#273a51',
      top: 5,
      left: 25,
      font: {fontWeight: 'bold'},
      height: 'auto',
      width: 'auto'
    });
    roomLabel = Ti.UI.createLabel({
      text: room,
      color: '#20607c',
      top: 5,
      width: 'auto',
      height: 'auto',
      right: 25,
      font: {fontWeight: 'bold'}
    });
    titleLabel = Ti.UI.createLabel({
      text: title,
      color: '#515151',
      top: 25,
      left: 25,
      width: "80%",
      height: 'auto',
      font: {fontFamily: 'Times New Roman', fontSize: 18}
    });
    row.add(Ti.UI.createView({
      top: 0,
      left: 25,
      height: 1,
      backgroundColor: '#e0e0e0',
      width: (row.hasChild) ? "90%" : "85%"
    }));
    row.add(timeLabel);
    row.add(roomLabel);
    row.add(titleLabel);
    if (title.length > 30) {
      row.setHeight(70);
    }
    row.nid = events[x].nid;

    if (header == currentDay) {
      currentSection.add(row);
    } else {
      if (currentSection != '') {
        data.push(currentSection);
      }
      var timestamp = globals.strtotime(currentDay) + 25212;
      var formattedDay = globals.date('l, F j', timestamp);
      var headerView = Ti.UI.createView({
        backgroundColor: '#eeeeee',
        height: 30,
        width: 'auto'
      });
      var headerLabel = Ti.UI.createLabel({
        text: formattedDay,
        color: '#20607c',
        font: {fontSize: 20, fontWeight: 'bold'},
        left: 25
      });
      headerView.add(headerLabel);
      var footerView = Ti.UI.createView({
        height: 16,
        backgroundColor: '#eeeeee'
      });
      if (globals.osname === "android") {
        currentSection = Ti.UI.createTableViewSection({
          headerTitle: formattedDay,
          footerView: footerView
        });
      } else {
        currentSection = Ti.UI.createTableViewSection({
          headerView: headerView,
          footerView: footerView
        });
      }
      currentSection.add(row);
    }
    header = currentDay;
  }
  // Push the last section into the data array
  data.push(currentSection);
  return data;
}

exports.getMainScheduleData = function() {
  return getEventData();
};
<commit_msg>Removed android specific code.<commit_after>var globals = require('lib/globals');
var scheduleTableView = '';

exports.scheduleWindow = function() {
  var instance = Ti.UI.createWindow({
    title: 'Schedule',
    backgroundColor: '#eeeeee'
  });
  instance.orientationModes = [Ti.UI.PORTRAIT];

  var refresh = Ti.UI.createButton({
    systemButton:Ti.UI.iPhone.SystemButton.REFRESH
  });
  refresh.addEventListener('click', function(e) {
    Ti.App.fireEvent('events.update', {prune: true});
  });
  instance.rightNavButton = refresh;

  var scheduleData = getEventData();
  scheduleTableView = Ti.UI.createTableView({
    data:scheduleData,
    separatorColor: '#eeeeee',
    backgroundColor: '#eeeeee'
  });
  scheduleTableView.addEventListener('click', function(x) {
    if (x.row.hasChild) {
      Ti.App.fireEvent('schedule.click', {nid: x.row.nid});
    }
  });
  instance.add(scheduleTableView);

  instance.addEventListener('open', function(e) {
    instance.addEventListener('focus', function(f) {
      Ti.App.fireEvent('events.update');
    });
  });

  return instance;
};

Ti.App.addEventListener('schedule.updateTableView', function(x) {
  var scheduleData = getEventData();
  scheduleTableView.setData(scheduleData);
});

// Will return an array for use in a TableView
function getEventData() {
  var events = globals.dbGetEvents();
  var x;
  var data = [];
  var header = '';
  var currentDay = '';
  var currentSection = '';
  var row = '';
  var time, room, title, topView, bottomView, timeLabel, roomLabel, titleLabel;
  for (x in events) {
    //Ti.API.info(x);
    currentDay = events[x].day;
    time = globals.secondsToTime(events[x].datefrom) + "-" +
           globals.secondsToTime(events[x].dateto);
    room = events[x].room;
    title = globals.html_decode(events[x].title);
    row = Ti.UI.createTableViewRow({
      height: 50,
      backgroundColor: '#eeeeee',
      layout: 'absolute'
    });
    if (events[x].eventtype == 'Workshop') {
      row.hasChild = true;
    }
    timeLabel = Ti.UI.createLabel({
      text: time,
      color: '#273a51',
      top: 5,
      left: 25,
      font: {fontWeight: 'bold'},
      height: 'auto',
      width: 'auto'
    });
    roomLabel = Ti.UI.createLabel({
      text: room,
      color: '#20607c',
      top: 5,
      width: 'auto',
      height: 'auto',
      right: 25,
      font: {fontWeight: 'bold'}
    });
    titleLabel = Ti.UI.createLabel({
      text: title,
      color: '#515151',
      top: 25,
      left: 25,
      width: "80%",
      height: 'auto',
      font: {fontFamily: 'Times New Roman', fontSize: 18}
    });
    row.add(Ti.UI.createView({
      top: 0,
      left: 25,
      height: 1,
      backgroundColor: '#e0e0e0',
      width: (row.hasChild) ? "90%" : "85%"
    }));
    row.add(timeLabel);
    row.add(roomLabel);
    row.add(titleLabel);
    if (title.length > 30) {
      row.setHeight(70);
    }
    row.nid = events[x].nid;

    if (header == currentDay) {
      currentSection.add(row);
    } else {
      if (currentSection != '') {
        data.push(currentSection);
      }
      var timestamp = globals.strtotime(currentDay) + 25212;
      var formattedDay = globals.date('l, F j', timestamp);
      var headerView = Ti.UI.createView({
        backgroundColor: '#eeeeee',
        height: 30,
        width: 'auto'
      });
      var headerLabel = Ti.UI.createLabel({
        text: formattedDay,
        color: '#20607c',
        font: {fontSize: 20, fontWeight: 'bold'},
        left: 25
      });
      headerView.add(headerLabel);
      var footerView = Ti.UI.createView({
        height: 16,
        backgroundColor: '#eeeeee'
      });
      currentSection = Ti.UI.createTableViewSection({
        headerView: headerView,
        footerView: footerView
      });
      currentSection.add(row);
    }
    header = currentDay;
  }
  // Push the last section into the data array
  data.push(currentSection);
  return data;
}

exports.getMainScheduleData = function() {
  return getEventData();
};
<|endoftext|>


<commit_before>var _utils = require('../utils');
var replace = _utils.replace;
var merge = _utils.merge;
var noop = _utils.noop;

/**
 * Block-Level Grammar
 */

var block = {
  newline: /^\n+/,
  code: /^((?: {4}|\t)[^\n]+\n*)+/,
  fences: noop,
  yamlHeader: noop,
  hr: /^( *[-*_]){3,} *(?:\n|$)/,
  heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n|$)/,
  nptable: noop,
  lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n|$)/,
  blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
  list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
  html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
  def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n|$)/,
  footnote: /^\[\^([^\]]+)\]: ([^\n]+)/,
  table: noop,
  paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def|math))+)\n*/,
  text: /^[^\n]+/,
  math: /^ *(\${2,}) *([\s\S]+?)\s*\1 *(?:\n|$)/,
};

block._bullet = /(?:[*+-]|\d+\.)/;
block._item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
block._item = replace(block._item, 'gm')
  (/bull/g, block._bullet)
  ();

block.list = replace(block.list)
  (/bull/g, block._bullet)
  ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
  ('def', '\\n+(?=' + block.def.source + ')')
  ('footnote', block.footnote)
  ();

block.blockquote = replace(block.blockquote)
  ('def', block.def)
  ();

block._tag = '(?!(?:'
  + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
  + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
  + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';

block.html = replace(block.html)
  ('comment', /<!--[\s\S]*?-->/)
  ('closed', /<(tag)[\s\S]+?<\/\1>/)
  ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
  (/tag/g, block._tag)
  ();

block.paragraph = replace(block.paragraph)
  ('hr', block.hr)
  ('heading', block.heading)
  ('lheading', block.lheading)
  ('blockquote', block.blockquote)
  ('tag', '<' + block._tag)
  ('def', block.def)
  ('math', block.math)
  ();

/**
 * Normal Block Grammar
 */

block.normal = merge({}, block);

/**
 * GFM Block Grammar
 */

block.gfm = merge({}, block.normal, {
  fences: /^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n|$)/,
  paragraph: /^/,
  yamlHeader: /^ *(?=```)/,
});

block.gfm.paragraph = replace(block.paragraph)
  ('(?!', '(?!'
    + block.gfm.fences.source.replace('\\1', '\\2') + '|'
    + block.list.source.replace('\\1', '\\3') + '|')
  ();

/**
 * GFM + Tables Block Grammar
 */

block.tables = merge({}, block.gfm, {
  nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
  table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
});

module.exports = block;
<commit_msg>Escape forward slash in html block regex<commit_after>var _utils = require('../utils');
var replace = _utils.replace;
var merge = _utils.merge;
var noop = _utils.noop;

/**
 * Block-Level Grammar
 */

var block = {
  newline: /^\n+/,
  code: /^((?: {4}|\t)[^\n]+\n*)+/,
  fences: noop,
  yamlHeader: noop,
  hr: /^( *[-*_]){3,} *(?:\n|$)/,
  heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n|$)/,
  nptable: noop,
  lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n|$)/,
  blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
  list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
  html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
  def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n|$)/,
  footnote: /^\[\^([^\]]+)\]: ([^\n]+)/,
  table: noop,
  paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def|math))+)\n*/,
  text: /^[^\n]+/,
  math: /^ *(\${2,}) *([\s\S]+?)\s*\1 *(?:\n|$)/,
};

block._bullet = /(?:[*+-]|\d+\.)/;
block._item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
block._item = replace(block._item, 'gm')
  (/bull/g, block._bullet)
  ();

block.list = replace(block.list)
  (/bull/g, block._bullet)
  ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
  ('def', '\\n+(?=' + block.def.source + ')')
  ('footnote', block.footnote)
  ();

block.blockquote = replace(block.blockquote)
  ('def', block.def)
  ();

block._tag = '(?!(?:'
  + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
  + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
  + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:\\/|[^\\w\\s@]*@)\\b';

block.html = replace(block.html)
  ('comment', /<!--[\s\S]*?-->/)
  ('closed', /<(tag)[\s\S]+?<\/\1>/)
  ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
  (/tag/g, block._tag)
  ();

block.paragraph = replace(block.paragraph)
  ('hr', block.hr)
  ('heading', block.heading)
  ('lheading', block.lheading)
  ('blockquote', block.blockquote)
  ('tag', '<' + block._tag)
  ('def', block.def)
  ('math', block.math)
  ();

/**
 * Normal Block Grammar
 */

block.normal = merge({}, block);

/**
 * GFM Block Grammar
 */

block.gfm = merge({}, block.normal, {
  fences: /^ *(`{3,}|~{3,}) *(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n|$)/,
  paragraph: /^/,
  yamlHeader: /^ *(?=```)/,
});

block.gfm.paragraph = replace(block.paragraph)
  ('(?!', '(?!'
    + block.gfm.fences.source.replace('\\1', '\\2') + '|'
    + block.list.source.replace('\\1', '\\3') + '|')
  ();

/**
 * GFM + Tables Block Grammar
 */

block.tables = merge({}, block.gfm, {
  nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
  table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
});

module.exports = block;
<|endoftext|>


<commit_before>'use strict'

var AbstractTransport = require('./abstract')
var dgram = require('dgram')
var merge = require('merge')
var myUtils = require('../utils')
var netstring = require('netstring-stream')
var nicAddresses = require('./addresses/nic')
var runtime = require('mm-runtime-info')
var signalingFactory = require('../signaling/in-band/factory')
var UdpSession = require('./streams/udp')
var util = require('util')
var winston = require('winston')
var winstonWrapper = require('winston-meta-wrapper')

/**
 * Udp transport
 *
 * @constructor
 * @fires UdpTransport#listening
 * @fires UdpTransport#connection
 * @fires UdpTransport#connect
 * @fires UdpTransport#error
 */
function UdpTransport (dgramOpts) {
  if (!(this instanceof UdpTransport)) {
    return new UdpTransport(dgramOpts)
  }
  AbstractTransport.call(this)
  // verify runtime compatibility
  if (!UdpTransport.isCompatibleWithRuntime()) {
    var errorMsg = 'UDP transport cannot be used on this runtime'
    this._error(errorMsg)
  }
  // logging
  this._log = winstonWrapper(winston)
  this._log.addMeta({
    module: '1tp:transports:udp'
  })
  // create and configure dgram socket
  this._opts = merge(Object.create(UdpTransport.DEFAULTS), dgramOpts)
  this._createNewDgramSocket()
  // keep track of udp sessions
  this._sessions = {}
  // accept new incoming connections
  this._acceptIncomingConnections = true
  // done
  this._log.debug('created udp transport with args ' + JSON.stringify(this._opts))
}

// Inherit from abstract transport
util.inherits(UdpTransport, AbstractTransport)

UdpTransport.DEFAULTS = {
  type: 'udp4',
  reuseAddr: false
}

UdpTransport.BIND_STATE = {
  UNBOUND: 0,
  BOUND: 1
}

UdpTransport.isCompatibleWithRuntime = function () {
  return !runtime.isBrowser()
}

UdpTransport.prototype.transportType = function () {
  return 'udp'
}

UdpTransport.prototype.connectTimeout = function () {
  return 500
}

UdpTransport.prototype.listen = function (listeningInfo, onSuccess, onFailure) {
  this._log.debug('listen to ' + JSON.stringify(listeningInfo))
  var port = 0
  var address = '0.0.0.0'
  if (listeningInfo !== undefined) {
    // verify listeningInfo
    if (listeningInfo.transportType !== this.transportType()) {
      var transportTypeError = 'incorrect listeningInfo: unexpected transportType -- ignoring request'
      this._log.error(transportTypeError)
      this._error(transportTypeError, onFailure)
      return
    }
    if (listeningInfo.transportInfo === undefined) {
      var transportInfoUndefined = 'incorrect connectionInfo: transportInfo is undefined'
      this._log.error(transportInfoUndefined)
      this._error(transportInfoUndefined, onFailure)
      return
    }
    port = listeningInfo.transportInfo.port
    address = listeningInfo.transportInfo.address
  }
  var self = this
  // prepare to process errors during bind operation
  var onBindError = function (error) {
    self._createNewDgramSocket() // otherwise chrome-dgram complains that this socket is already bound when we try again (i.e. without listeningInfo)
    self._error(error, onFailure)
  }
  // mute existing error listeners during bind operation
  this._muteSocketErrorListeners = true
  // register temp error listener
  this._socket.once('error', onBindError)
  // fire up
  this._socket.bind(port, address, function () {
    // drop error listener
    self.removeListener('error', onBindError)
    // unmute existing error listeners
    self._muteSocketErrorListeners = false
    // change bind state
    self._bindState = UdpTransport.BIND_STATE.BOUND
    // create connection info
    var myConnectionInfo = {
      transportType: self.transportType(),
      transportInfo: {
        // address will be added below
        port: self._socket.address().port
      },
      version: self.version
    }
    // if address was specified in listening info, then reuse it
    if (address !== '0.0.0.0') {
      myConnectionInfo.transportInfo.address = self._socket.address().address
      self._myConnectionInfo = myConnectionInfo
      self._log.debug('udp socket bound, connectionInfo = ' + JSON.stringify(myConnectionInfo))
      self._fireListeningEvent(myConnectionInfo, onSuccess)
    } else {
      // otherwise, retrieve local ip address
      nicAddresses.getIpAddressesP()
        .then(function (addresses) {
          var myConnectionInfos = addresses.map(function (localAddress) {
            var connectionInfo = {
              transportType: myConnectionInfo.transportType,
              transportInfo: {
                address: localAddress,
                // INVARIANT thomasdelaet: port numbers must be the same when creating separate transport info instances for different local ipAddresses
                port: myConnectionInfo.transportInfo.port
              },
              version: self.version
            }
            return connectionInfo
          })
          self._log.debug('udp socket bound, connectionInfo = ' + JSON.stringify(myConnectionInfos))
          self._fireListeningEvent(myConnectionInfos, onSuccess)
        })
        .catch(function (error) {
          self._error(error, onFailure)
        })
    }
  })
}

UdpTransport.prototype.connect = function (peerConnectionInfo, onSuccess, onFailure) {
  this._log.debug('connect to ' + JSON.stringify(peerConnectionInfo))
  // verify peerConnectionInfo
  if (peerConnectionInfo.transportType !== this.transportType()) {
    var transportTypeError = 'incorrect connectionInfo: unexpected transportType -- Ignoring request'
    this._log.error(transportTypeError)
    this._error(transportTypeError, onFailure)
    return
  }
  if (peerConnectionInfo.transportInfo === undefined) {
    var transportInfoUndefined = 'incorrect connectionInfo: transportInfo is undefined'
    this._log.error(transportInfoUndefined)
    this._error(transportInfoUndefined, onFailure)
    return
  }
  if (peerConnectionInfo.transportInfo.address === undefined || peerConnectionInfo.transportInfo.port === undefined) {
    var addressError = 'incorrect connectionInfo: address and/or port attribute is undefined'
    this._log.error(addressError)
    this._error(addressError, onFailure)
    return
  }
  // create new session and init handshake
  var session = this._createUdpSession(peerConnectionInfo.transportInfo, null)
  // and init handshake
  var self = this
  session.initHandshakeP()
    .then(function () {
      self._fireConnectEvent(session, peerConnectionInfo, onSuccess)
    })
    .catch(function (error) {
      delete self._sessions[session._sessionId]
      self._error(error, onFailure)
    })
}

UdpTransport.prototype.close = function (onSuccess, onFailure) {
  this._acceptIncomingConnections = false
  if (myUtils.isEmpty(this._sessions)) {
    onSuccess()
    return
  }
}

// UdpTransport.prototype.close = function (onSuccess, onFailure) {
//   var self = this
//   this._socket.close(function () {
//     self._fireCloseEvent(onSuccess)
//   })
// }

UdpTransport.prototype._createNewDgramSocket = function () {
  this._socket = dgram.createSocket(this._opts)
  this._bindState = UdpTransport.BIND_STATE.UNBOUND
  this._muteSocketErrorListeners = false
  this._socket.on('message', this._onIncomingBytes())
  this._socket.on('close', function () {
    self._log.debug('udp socket closed')
  // TODO
  })
  var self = this
  this._socket.on('error', function (error) {
    if (self._muteSocketErrorListeners) {
      return
    }
    self._log.error(error)
    self._error(error)
  })
}

UdpTransport.prototype._onIncomingBytes = function () {
  var self = this
  return function (bytes, rinfo) {
    self._log.debug('incoming bytes ' + JSON.stringify(bytes) + ' from ' + JSON.stringify(rinfo))
    var message = signalingFactory.parse(bytes)
    // drop requests with no version info
    if (message.version === undefined) {
      var undefinedVersionError = 'incorrect signaling message: undefined version -- ignoring request'
      self._log.error(undefinedVersionError)
      self._error(undefinedVersionError)
      return
    }
    // drop SYN requests when this transport is closed -- i.e. it doesn't accepts incoming connections
    if (message.type === signalingFactory.MESSAGE.SYN && !self._acceptIncomingConnections) {
      var notAcceptingNewConnectionsError = 'not accepting new connections -- ignoring request'
      self._log.debug(notAcceptingNewConnectionsError)
      return
    }
    // create new udp session object when SYN request and transport is not closed
    if (message.type === signalingFactory.MESSAGE.SYN && self._acceptIncomingConnections) {
      var peerAddress = {
        address: rinfo.address,
        port: rinfo.port
      }
      // create new udp session
      var session = self._createUdpSession(peerAddress, message.sessionId)
      if (!session) {
        // or obtain the existing session
        session = self._sessions[message.sessionId]
      }
      // and notify all listeners once this session is ready to use
      var peerConnectionInfo = {
        transportType: self.transportType(),
        transportInfo: peerAddress
      }
      session.once('connected', function () {
        self._fireConnectionEvent(session, self, peerConnectionInfo)
      })
    }
    // get session
    var session = self._sessions[message.sessionId]
    // drop message if session is undefined
    if (!session) {
      var sessionNotFoundError = 'could not find UDP session for session ' + message.sessionId + ' -- ignoring request'
      self._log.debug(sessionNotFoundError)
      return
    }
    // process valid message
    session.processMessage(message)
  }
}

UdpTransport.prototype._createUdpSession = function (peerAddress, sessionId) {
  var sessionAlreadyExists = (sessionId !== null && (sessionId in this._sessions))
  if (sessionAlreadyExists) {
    this._log.debug('session ' + sessionId + ' already exists')
  }
  var blockIncomingConnections = (sessionId !== null && !this._acceptIncomingConnections)
  if (blockIncomingConnections) {
    this._log.debug('blocking incoming session requests')
  }
  if (sessionAlreadyExists || blockIncomingConnections) {
    return
  }
  // create new udp session
  var session = new UdpSession(peerAddress, sessionId, this._socket)
  // store session
  this._sessions[session._sessionId] = session
  // register handlers for closing events
  var self = this
  session.once('close', function () {
    delete self._sessions[session._sessionId]
  })
  // session.once('end', function () {
  //   delete self._sessions[session._sessionId]
  // })
  // session.once('finish', function () {
  //   delete self._sessions[session._sessionId]
  // })
  // done
  this._log.debug('created new session for ' + JSON.stringify(peerAddress))
  return session
}

module.exports = UdpTransport
<commit_msg>delete session when write and read stream are ended and finished<commit_after>'use strict'

var AbstractTransport = require('./abstract')
var dgram = require('dgram')
var merge = require('merge')
var myUtils = require('../utils')
var netstring = require('netstring-stream')
var nicAddresses = require('./addresses/nic')
var runtime = require('mm-runtime-info')
var signalingFactory = require('../signaling/in-band/factory')
var UdpSession = require('./streams/udp')
var util = require('util')
var winston = require('winston')
var winstonWrapper = require('winston-meta-wrapper')

/**
 * Udp transport
 *
 * @constructor
 * @fires UdpTransport#listening
 * @fires UdpTransport#connection
 * @fires UdpTransport#connect
 * @fires UdpTransport#error
 */
function UdpTransport (dgramOpts) {
  if (!(this instanceof UdpTransport)) {
    return new UdpTransport(dgramOpts)
  }
  AbstractTransport.call(this)
  // verify runtime compatibility
  if (!UdpTransport.isCompatibleWithRuntime()) {
    var errorMsg = 'UDP transport cannot be used on this runtime'
    this._error(errorMsg)
  }
  // logging
  this._log = winstonWrapper(winston)
  this._log.addMeta({
    module: '1tp:transports:udp'
  })
  // create and configure dgram socket
  this._opts = merge(Object.create(UdpTransport.DEFAULTS), dgramOpts)
  this._createNewDgramSocket()
  // keep track of udp sessions
  this._sessions = {}
  // accept new incoming connections
  this._acceptIncomingConnections = true
  // done
  this._log.debug('created udp transport with args ' + JSON.stringify(this._opts))
}

// Inherit from abstract transport
util.inherits(UdpTransport, AbstractTransport)

UdpTransport.DEFAULTS = {
  type: 'udp4',
  reuseAddr: false
}

UdpTransport.BIND_STATE = {
  UNBOUND: 0,
  BOUND: 1
}

UdpTransport.isCompatibleWithRuntime = function () {
  return !runtime.isBrowser()
}

UdpTransport.prototype.transportType = function () {
  return 'udp'
}

UdpTransport.prototype.connectTimeout = function () {
  return 500
}

UdpTransport.prototype.listen = function (listeningInfo, onSuccess, onFailure) {
  this._log.debug('listen to ' + JSON.stringify(listeningInfo))
  var port = 0
  var address = '0.0.0.0'
  if (listeningInfo !== undefined) {
    // verify listeningInfo
    if (listeningInfo.transportType !== this.transportType()) {
      var transportTypeError = 'incorrect listeningInfo: unexpected transportType -- ignoring request'
      this._log.error(transportTypeError)
      this._error(transportTypeError, onFailure)
      return
    }
    if (listeningInfo.transportInfo === undefined) {
      var transportInfoUndefined = 'incorrect connectionInfo: transportInfo is undefined'
      this._log.error(transportInfoUndefined)
      this._error(transportInfoUndefined, onFailure)
      return
    }
    port = listeningInfo.transportInfo.port
    address = listeningInfo.transportInfo.address
  }
  var self = this
  // prepare to process errors during bind operation
  var onBindError = function (error) {
    self._createNewDgramSocket() // otherwise chrome-dgram complains that this socket is already bound when we try again (i.e. without listeningInfo)
    self._error(error, onFailure)
  }
  // mute existing error listeners during bind operation
  this._muteSocketErrorListeners = true
  // register temp error listener
  this._socket.once('error', onBindError)
  // fire up
  this._socket.bind(port, address, function () {
    // drop error listener
    self.removeListener('error', onBindError)
    // unmute existing error listeners
    self._muteSocketErrorListeners = false
    // change bind state
    self._bindState = UdpTransport.BIND_STATE.BOUND
    // create connection info
    var myConnectionInfo = {
      transportType: self.transportType(),
      transportInfo: {
        // address will be added below
        port: self._socket.address().port
      },
      version: self.version
    }
    // if address was specified in listening info, then reuse it
    if (address !== '0.0.0.0') {
      myConnectionInfo.transportInfo.address = self._socket.address().address
      self._myConnectionInfo = myConnectionInfo
      self._log.debug('udp socket bound, connectionInfo = ' + JSON.stringify(myConnectionInfo))
      self._fireListeningEvent(myConnectionInfo, onSuccess)
    } else {
      // otherwise, retrieve local ip address
      nicAddresses.getIpAddressesP()
        .then(function (addresses) {
          var myConnectionInfos = addresses.map(function (localAddress) {
            var connectionInfo = {
              transportType: myConnectionInfo.transportType,
              transportInfo: {
                address: localAddress,
                // INVARIANT thomasdelaet: port numbers must be the same when creating separate transport info instances for different local ipAddresses
                port: myConnectionInfo.transportInfo.port
              },
              version: self.version
            }
            return connectionInfo
          })
          self._log.debug('udp socket bound, connectionInfo = ' + JSON.stringify(myConnectionInfos))
          self._fireListeningEvent(myConnectionInfos, onSuccess)
        })
        .catch(function (error) {
          self._error(error, onFailure)
        })
    }
  })
}

UdpTransport.prototype.connect = function (peerConnectionInfo, onSuccess, onFailure) {
  this._log.debug('connect to ' + JSON.stringify(peerConnectionInfo))
  // verify peerConnectionInfo
  if (peerConnectionInfo.transportType !== this.transportType()) {
    var transportTypeError = 'incorrect connectionInfo: unexpected transportType -- Ignoring request'
    this._log.error(transportTypeError)
    this._error(transportTypeError, onFailure)
    return
  }
  if (peerConnectionInfo.transportInfo === undefined) {
    var transportInfoUndefined = 'incorrect connectionInfo: transportInfo is undefined'
    this._log.error(transportInfoUndefined)
    this._error(transportInfoUndefined, onFailure)
    return
  }
  if (peerConnectionInfo.transportInfo.address === undefined || peerConnectionInfo.transportInfo.port === undefined) {
    var addressError = 'incorrect connectionInfo: address and/or port attribute is undefined'
    this._log.error(addressError)
    this._error(addressError, onFailure)
    return
  }
  // create new session and init handshake
  var session = this._createUdpSession(peerConnectionInfo.transportInfo, null)
  // and init handshake
  var self = this
  session.initHandshakeP()
    .then(function () {
      self._fireConnectEvent(session, peerConnectionInfo, onSuccess)
    })
    .catch(function (error) {
      delete self._sessions[session._sessionId]
      self._error(error, onFailure)
    })
}

UdpTransport.prototype.close = function (onSuccess, onFailure) {
  this._acceptIncomingConnections = false
  if (myUtils.isEmpty(this._sessions)) {
    onSuccess()
    return
  }
}

// UdpTransport.prototype.close = function (onSuccess, onFailure) {
//   var self = this
//   this._socket.close(function () {
//     self._fireCloseEvent(onSuccess)
//   })
// }

UdpTransport.prototype._createNewDgramSocket = function () {
  this._socket = dgram.createSocket(this._opts)
  this._bindState = UdpTransport.BIND_STATE.UNBOUND
  this._muteSocketErrorListeners = false
  this._socket.on('message', this._onIncomingBytes())
  this._socket.on('close', function () {
    self._log.debug('udp socket closed')
  // TODO
  })
  var self = this
  this._socket.on('error', function (error) {
    if (self._muteSocketErrorListeners) {
      return
    }
    self._log.error(error)
    self._error(error)
  })
}

UdpTransport.prototype._onIncomingBytes = function () {
  var self = this
  return function (bytes, rinfo) {
    self._log.debug('incoming bytes ' + JSON.stringify(bytes) + ' from ' + JSON.stringify(rinfo))
    var message = signalingFactory.parse(bytes)
    // drop requests with no version info
    if (message.version === undefined) {
      var undefinedVersionError = 'incorrect signaling message: undefined version -- ignoring request'
      self._log.error(undefinedVersionError)
      self._error(undefinedVersionError)
      return
    }
    // drop SYN requests when this transport is closed -- i.e. it doesn't accepts incoming connections
    if (message.type === signalingFactory.MESSAGE.SYN && !self._acceptIncomingConnections) {
      var notAcceptingNewConnectionsError = 'not accepting new connections -- ignoring request'
      self._log.debug(notAcceptingNewConnectionsError)
      return
    }
    // create new udp session object when SYN request and transport is not closed
    if (message.type === signalingFactory.MESSAGE.SYN && self._acceptIncomingConnections) {
      var peerAddress = {
        address: rinfo.address,
        port: rinfo.port
      }
      // create new udp session
      var session = self._createUdpSession(peerAddress, message.sessionId)
      if (!session) {
        // or obtain the existing session
        session = self._sessions[message.sessionId]
      }
      // and notify all listeners once this session is ready to use
      var peerConnectionInfo = {
        transportType: self.transportType(),
        transportInfo: peerAddress
      }
      session.once('connected', function () {
        self._fireConnectionEvent(session, self, peerConnectionInfo)
      })
    }
    // get session
    var session = self._sessions[message.sessionId]
    // drop message if session is undefined
    if (!session) {
      var sessionNotFoundError = 'could not find UDP session for session ' + message.sessionId + ' -- ignoring request'
      self._log.debug(sessionNotFoundError)
      return
    }
    // process valid message
    session.processMessage(message)
  }
}

UdpTransport.prototype._createUdpSession = function (peerAddress, sessionId) {
  var sessionAlreadyExists = (sessionId !== null && (sessionId in this._sessions))
  if (sessionAlreadyExists) {
    this._log.debug('session ' + sessionId + ' already exists')
  }
  var blockIncomingConnections = (sessionId !== null && !this._acceptIncomingConnections)
  if (blockIncomingConnections) {
    this._log.debug('blocking incoming session requests')
  }
  if (sessionAlreadyExists || blockIncomingConnections) {
    return
  }
  // create new udp session
  var session = new UdpSession(peerAddress, sessionId, this._socket)
  // store session
  this._sessions[session._sessionId] = session
  // register handlers for closing events
  var self = this
  session.once('close', function () {
    delete self._sessions[session._sessionId]
  })
  session.once('end', function () {
    // delete if finished + ended
    if (self.finished) {
      delete self._sessions[session._sessionId]
    }
  })
  session.once('finish', function () {
    // delete if finished + ended
    if (self.ended) {
      delete self._sessions[session._sessionId]
    }
  })
  // done
  this._log.debug('created new session for ' + JSON.stringify(peerAddress))
  return session
}

module.exports = UdpTransport
<|endoftext|>


<commit_before>/**
 * @class Alloy
 * Top-level module for Alloy functions.
 *
 */
var 	   _ = require('alloy/underscore')._,
	Backbone = require('alloy/backbone');

exports._ = _;
exports.Backbone = Backbone;

function ucfirst(text) {
    if (!text) { return text; }
    return text[0].toUpperCase() + text.substr(1);
};

// Ti.Analytics.featureEvent('alloy.start', {
// 	guid: Ti.Platform.id,
// 	tiversion: Ti.version,
// 	osname: Ti.Platform.osname,
// 	osversion: Ti.Platform.version,
// 	locale: Ti.Platform.locale
// });

exports.M = function(name, modelDesc, migrations) {
	var config = modelDesc.config;
    var type = (config.adapter ? config.adapter.type : null) || 'localDefault';
    if (type === 'localDefault') {
    	type = OS_MOBILEWEB ? 'localStorage' : 'sql';
    }

	var adapter = require('alloy/sync/'+type);
    var extendObj = {
		defaults: config.defaults,
        sync: function(method, model, opts) {
			var config = model.config || {};
			var adapterObj = config.adapter || {};
			var type = (config.adapter ? config.adapter.type : null) || 'localDefault';
			if (type === 'localDefault') {
		    	type = OS_MOBILEWEB ? 'localStorage' : 'sql';
		    }

			require('alloy/sync/'+type).sync(model,method,opts);
		}
	};

	var extendClass = {};

	// construct the model based on the current adapter type
	if (migrations) { extendClass.migrations = migrations; }
    if (_.isFunction(adapter.beforeModelCreate)) { config = adapter.beforeModelCreate(config) || config; }
	var Model = Backbone.Model.extend(extendObj, extendClass);
	Model.prototype.config = config;
	if (_.isFunction(adapter.afterModelCreate)) { adapter.afterModelCreate(Model); }

	if (_.isFunction(modelDesc.extendModel)) {
		Model = modelDesc.extendModel(Model) || Model;
	}

	return Model;
};

exports.C = function(name, modelDesc, model) {
    var extendObj = {
		model: model,
        sync: function(method, model, opts) {
			var config = (model.config || {});
			var type = (config.adapter ? config.adapter.type : null) || 'localDefault';
			if (type === 'localDefault') {
		    	type = OS_MOBILEWEB ? 'localStorage' : 'sql';
		    }

			require('alloy/sync/'+type).sync(model,method,opts);
		}
	};

	var Collection = Backbone.Collection.extend(extendObj);
	var config = Collection.prototype.config = model.prototype.config;

	var type = (config.adapter ? config.adapter.type : null) || 'localDefault';
	var adapter = require('alloy/sync/'+type);
	if (_.isFunction(adapter.afterCollectionCreate)) { adapter.afterCollectionCreate(Collection); }

	if (_.isFunction(modelDesc.extendModel)) {
		Collection = modelDesc.extendCollection(Collection) || Collection;
	}

	return Collection;
};

exports.A = function(t, type, parent) {
	_.extend(t,Backbone.Events);

	(function() {

		// we are going to wrap addEventListener and removeEventListener
		// with on, off so we can use the Backbone events
		var al = t.addEventListener,
			rl = t.removeEventListener,
			oo = t.on,
			of = t.off,
			tg = t.trigger,
		   cbs = {},
		   ctx = _.extend({}, Backbone.Events);

		if (!al || !rl) {
			return;
		}

		t.trigger = function() {
			ctx.trigger.apply(ctx, Array.prototype.slice.apply(arguments));
		}

		t.on = function(e,cb,context) {
			var wcb = function(evt) {
				try {
					_.bind(tg,ctx,e,evt)();
				}
				catch(E) {
					Ti.API.error("Error triggering '"+e+"' event: "+E);
				}
			};

			if (!cbs[e]) {
				cbs[e] = {};
				if (OS_IOS) {
					al(e, wcb);
				} else {
					al.call(t, e, wcb);
				}
			}
			cbs[e][cb] = wcb;

			_.bind(oo,ctx,e,cb,context)();
		};

		t.off = function(e,cb,context) {
			var f = cbs[e] ? cbs[e][cb] : null;
			if (f) {
				_.bind(of,ctx,e,cb,context)();
				delete cbs[e][cb];

				if (cbs[e].length === 0) {
					delete cbs[e];
					if (OS_IOS) {
						rl(e, f);
					} else {
						rl.call(t, e, f);
					}
				}
				f = null;
			}
		};

	})();

	return t;
}

/**
 * @method getWidget
 * Factory method for instantiating a widget controller. Creates and returns an instance of the
 * named widget.
 * @param {String} id Id of widget to instantiate.
 * @param {String} name Name of the view within the widget to instantiate ('widget' by default)
 * @param {*...} [args] Arguments to pass to the widget.
 * @return {Alloy.Controller} Alloy widget controller object.
 *
 * @deprecated 0.3 Use {Alloy#createWidget} instead
 */
exports.getWidget = function(id, name, args) {
	Ti.API.warn('Alloy.getWidget() is deprecated, use Alloy.createWidget() instead.');
	return exports.createWidget(id, name, args);
}

/**
 * @method createWidget
 * Factory method for instantiating a widget controller. Creates and returns an instance of the
 * named widget.
 * @param {String} id Id of widget to instantiate.
 * @param {String} name Name of the view within the widget to instantiate ('widget' by default)
 * @param {*...} [args] Arguments to pass to the widget.
 * @return {Alloy.Controller} Alloy widget controller object.
 */
exports.createWidget = function(id, name, args) {
	return new (require('alloy/widgets/' + id + '/controllers/' + (name || 'widget')))(args);
}

/**
 * @method getController
 * Factory method for instantiating a controller. Creates and returns an instance of the
 * named controller.
 * @param {String} name Name of controller to instantiate.
 * @param {*...} [args] Arguments to pass to the controller.
 * @return {Alloy.Controller} Alloy controller object.
 *
 * @deprecated 0.3 Use {Alloy#createController} instead
 */
exports.getController = function(name, args) {
	Ti.API.warn('Alloy.getController() is deprecated, use Alloy.createController() instead.');
	return exports.createController(name, args);
}

/**
 * @method createController
 * Factory method for instantiating a controller. Creates and returns an instance of the
 * named controller.
 * @param {String} name Name of controller to instantiate.
 * @param {*...} [args] Arguments to pass to the controller.
 * @return {Alloy.Controller} Alloy controller object.
 */
exports.createController = function(name, args) {
	return new (require('alloy/controllers/' + name))(args);
}

/**
 * @method getModel
 * Factory method for instantiating a Backbone Model object. Creates and returns an instance of the
 * named model.
 *
 * See [Backbone.Model](http://backbonejs.org/#Model) in the Backbone.js documentation for
 * information on the methods and properties provided by the Model object.
 * @param {String} name Name of model to instantiate.
 * @param {*...} [args] Arguments to pass to the model.
 * @return {Backbone.Model} Backbone model object.
 *
 * @deprecated 0.3 Use {Alloy#createModel} instead
 */
exports.getModel = function(name, args) {
	Ti.API.warn('Alloy.getModel() is deprecated, use Alloy.createModel() instead.');
	return exports.createModel(name, args);
}

/**
 * @method createModel
 * Factory method for instantiating a Backbone Model object. Creates and returns an instance of the
 * named model.
 *
 * See [Backbone.Model](http://backbonejs.org/#Model) in the Backbone.js documentation for
 * information on the methods and properties provided by the Model object.
 * @param {String} name Name of model to instantiate.
 * @param {*...} [args] Arguments to pass to the model.
 * @return {Backbone.Model} Backbone model object.
 */
exports.createModel = function(name, args) {
	return new (require('alloy/models/' + ucfirst(name)).Model)(args);
}

/**
 * @method getCollection
 * Factory method for instantiating a Backbone collection of model objects. Creates and returns a
 * collection for holding the named type of model objects.
 *
 * See [Backbone.Collection](http://backbonejs.org/#Collection) in the Backbone.js
 * documentation for  information on the methods and  properties provided by the
 * Collection object.
 * @param {String} name Name of model to hold in this collection.
 * @param {*...} [args] Arguments to pass to the collection.
 * @return {Backbone.Collection} Backbone collection object.
 *
 * @deprecated 0.3 Use {Alloy#createCollection} instead
 */
exports.getCollection = function(name, args) {
	Ti.API.warn('Alloy.getCollection() is deprecated, use Alloy.createCollection() instead.');
	return exports.createCollection(name, args);
}

/**
 * @method createCollection
 * Factory method for instantiating a Backbone collection of model objects. Creates and returns a
 * collection for holding the named type of model objects.
 *
 * See [Backbone.Collection](http://backbonejs.org/#Collection) in the Backbone.js
 * documentation for  information on the methods and  properties provided by the
 * Collection object.
 * @param {String} name Name of model to hold in this collection.
 * @param {*...} [args] Arguments to pass to the collection.
 * @return {Backbone.Collection} Backbone collection object.
 */
exports.createCollection = function(name, args) {
	return new (require('alloy/models/' + ucfirst(name)).Collection)(args);
}

function isTabletFallback() {
	return !(Math.min(
		Ti.Platform.displayCaps.platformHeight,
		Ti.Platform.displayCaps.platformWidth
	) < 700);
}

/**
 * @property {Boolean} [readOnly=false] isTablet
 * `true` if the current device is a tablet.
 *
 */
exports.isTablet = (function() {
	if (OS_IOS) {
		return Ti.Platform.osname === 'ipad';
	}
	if (OS_ANDROID) {
		try {
			var psc = require('ti.physicalSizeCategory');
			return psc.physicalSizeCategory === 'large' ||
				   psc.physicalSizeCategory === 'xlarge';
		} catch(e) {
			Ti.API.warn('Could not find ti.physicalSizeCategory module, using fallback for Alloy.isTablet');
			return isTabletFallback();
		}
	}
	if (OS_MOBILEWEB) {
		return !(Math.min(
			Ti.Platform.displayCaps.platformHeight,
			Ti.Platform.displayCaps.platformWidth
		) < 400);
	}

	// Last resort. Don't worry, uglifyjs cleans up this dead code if necessary.
	return isTabletFallback();
})();

/**
 * @property {Boolean} [readOnly=false] isHandheld
 * `true` if the current device is a handheld device (not a tablet).
 *
 */
exports.isHandheld = !exports.isTablet;

if (OS_ANDROID) {
	exports.Android = {};
	exports.Android.menuItemCreateArgs = ['itemId','groupId','title','order'];
}
<commit_msg>updated doc tags for isTablet and isHandheld<commit_after>/**
 * @class Alloy
 * Top-level module for Alloy functions.
 *
 */
var 	   _ = require('alloy/underscore')._,
	Backbone = require('alloy/backbone');

exports._ = _;
exports.Backbone = Backbone;

function ucfirst(text) {
    if (!text) { return text; }
    return text[0].toUpperCase() + text.substr(1);
};

// Ti.Analytics.featureEvent('alloy.start', {
// 	guid: Ti.Platform.id,
// 	tiversion: Ti.version,
// 	osname: Ti.Platform.osname,
// 	osversion: Ti.Platform.version,
// 	locale: Ti.Platform.locale
// });

exports.M = function(name, modelDesc, migrations) {
	var config = modelDesc.config;
    var type = (config.adapter ? config.adapter.type : null) || 'localDefault';
    if (type === 'localDefault') {
    	type = OS_MOBILEWEB ? 'localStorage' : 'sql';
    }

	var adapter = require('alloy/sync/'+type);
    var extendObj = {
		defaults: config.defaults,
        sync: function(method, model, opts) {
			var config = model.config || {};
			var adapterObj = config.adapter || {};
			var type = (config.adapter ? config.adapter.type : null) || 'localDefault';
			if (type === 'localDefault') {
		    	type = OS_MOBILEWEB ? 'localStorage' : 'sql';
		    }

			require('alloy/sync/'+type).sync(model,method,opts);
		}
	};

	var extendClass = {};

	// construct the model based on the current adapter type
	if (migrations) { extendClass.migrations = migrations; }
    if (_.isFunction(adapter.beforeModelCreate)) { config = adapter.beforeModelCreate(config) || config; }
	var Model = Backbone.Model.extend(extendObj, extendClass);
	Model.prototype.config = config;
	if (_.isFunction(adapter.afterModelCreate)) { adapter.afterModelCreate(Model); }

	if (_.isFunction(modelDesc.extendModel)) {
		Model = modelDesc.extendModel(Model) || Model;
	}

	return Model;
};

exports.C = function(name, modelDesc, model) {
    var extendObj = {
		model: model,
        sync: function(method, model, opts) {
			var config = (model.config || {});
			var type = (config.adapter ? config.adapter.type : null) || 'localDefault';
			if (type === 'localDefault') {
		    	type = OS_MOBILEWEB ? 'localStorage' : 'sql';
		    }

			require('alloy/sync/'+type).sync(model,method,opts);
		}
	};

	var Collection = Backbone.Collection.extend(extendObj);
	var config = Collection.prototype.config = model.prototype.config;

	var type = (config.adapter ? config.adapter.type : null) || 'localDefault';
	var adapter = require('alloy/sync/'+type);
	if (_.isFunction(adapter.afterCollectionCreate)) { adapter.afterCollectionCreate(Collection); }

	if (_.isFunction(modelDesc.extendModel)) {
		Collection = modelDesc.extendCollection(Collection) || Collection;
	}

	return Collection;
};

exports.A = function(t, type, parent) {
	_.extend(t,Backbone.Events);

	(function() {

		// we are going to wrap addEventListener and removeEventListener
		// with on, off so we can use the Backbone events
		var al = t.addEventListener,
			rl = t.removeEventListener,
			oo = t.on,
			of = t.off,
			tg = t.trigger,
		   cbs = {},
		   ctx = _.extend({}, Backbone.Events);

		if (!al || !rl) {
			return;
		}

		t.trigger = function() {
			ctx.trigger.apply(ctx, Array.prototype.slice.apply(arguments));
		}

		t.on = function(e,cb,context) {
			var wcb = function(evt) {
				try {
					_.bind(tg,ctx,e,evt)();
				}
				catch(E) {
					Ti.API.error("Error triggering '"+e+"' event: "+E);
				}
			};

			if (!cbs[e]) {
				cbs[e] = {};
				if (OS_IOS) {
					al(e, wcb);
				} else {
					al.call(t, e, wcb);
				}
			}
			cbs[e][cb] = wcb;

			_.bind(oo,ctx,e,cb,context)();
		};

		t.off = function(e,cb,context) {
			var f = cbs[e] ? cbs[e][cb] : null;
			if (f) {
				_.bind(of,ctx,e,cb,context)();
				delete cbs[e][cb];

				if (cbs[e].length === 0) {
					delete cbs[e];
					if (OS_IOS) {
						rl(e, f);
					} else {
						rl.call(t, e, f);
					}
				}
				f = null;
			}
		};

	})();

	return t;
}

/**
 * @method getWidget
 * Factory method for instantiating a widget controller. Creates and returns an instance of the
 * named widget.
 * @param {String} id Id of widget to instantiate.
 * @param {String} name Name of the view within the widget to instantiate ('widget' by default)
 * @param {*...} [args] Arguments to pass to the widget.
 * @return {Alloy.Controller} Alloy widget controller object.
 *
 * @deprecated 0.3 Use {Alloy#createWidget} instead
 */
exports.getWidget = function(id, name, args) {
	Ti.API.warn('Alloy.getWidget() is deprecated, use Alloy.createWidget() instead.');
	return exports.createWidget(id, name, args);
}

/**
 * @method createWidget
 * Factory method for instantiating a widget controller. Creates and returns an instance of the
 * named widget.
 * @param {String} id Id of widget to instantiate.
 * @param {String} name Name of the view within the widget to instantiate ('widget' by default)
 * @param {*...} [args] Arguments to pass to the widget.
 * @return {Alloy.Controller} Alloy widget controller object.
 */
exports.createWidget = function(id, name, args) {
	return new (require('alloy/widgets/' + id + '/controllers/' + (name || 'widget')))(args);
}

/**
 * @method getController
 * Factory method for instantiating a controller. Creates and returns an instance of the
 * named controller.
 * @param {String} name Name of controller to instantiate.
 * @param {*...} [args] Arguments to pass to the controller.
 * @return {Alloy.Controller} Alloy controller object.
 *
 * @deprecated 0.3 Use {Alloy#createController} instead
 */
exports.getController = function(name, args) {
	Ti.API.warn('Alloy.getController() is deprecated, use Alloy.createController() instead.');
	return exports.createController(name, args);
}

/**
 * @method createController
 * Factory method for instantiating a controller. Creates and returns an instance of the
 * named controller.
 * @param {String} name Name of controller to instantiate.
 * @param {*...} [args] Arguments to pass to the controller.
 * @return {Alloy.Controller} Alloy controller object.
 */
exports.createController = function(name, args) {
	return new (require('alloy/controllers/' + name))(args);
}

/**
 * @method getModel
 * Factory method for instantiating a Backbone Model object. Creates and returns an instance of the
 * named model.
 *
 * See [Backbone.Model](http://backbonejs.org/#Model) in the Backbone.js documentation for
 * information on the methods and properties provided by the Model object.
 * @param {String} name Name of model to instantiate.
 * @param {*...} [args] Arguments to pass to the model.
 * @return {Backbone.Model} Backbone model object.
 *
 * @deprecated 0.3 Use {Alloy#createModel} instead
 */
exports.getModel = function(name, args) {
	Ti.API.warn('Alloy.getModel() is deprecated, use Alloy.createModel() instead.');
	return exports.createModel(name, args);
}

/**
 * @method createModel
 * Factory method for instantiating a Backbone Model object. Creates and returns an instance of the
 * named model.
 *
 * See [Backbone.Model](http://backbonejs.org/#Model) in the Backbone.js documentation for
 * information on the methods and properties provided by the Model object.
 * @param {String} name Name of model to instantiate.
 * @param {*...} [args] Arguments to pass to the model.
 * @return {Backbone.Model} Backbone model object.
 */
exports.createModel = function(name, args) {
	return new (require('alloy/models/' + ucfirst(name)).Model)(args);
}

/**
 * @method getCollection
 * Factory method for instantiating a Backbone collection of model objects. Creates and returns a
 * collection for holding the named type of model objects.
 *
 * See [Backbone.Collection](http://backbonejs.org/#Collection) in the Backbone.js
 * documentation for  information on the methods and  properties provided by the
 * Collection object.
 * @param {String} name Name of model to hold in this collection.
 * @param {*...} [args] Arguments to pass to the collection.
 * @return {Backbone.Collection} Backbone collection object.
 *
 * @deprecated 0.3 Use {Alloy#createCollection} instead
 */
exports.getCollection = function(name, args) {
	Ti.API.warn('Alloy.getCollection() is deprecated, use Alloy.createCollection() instead.');
	return exports.createCollection(name, args);
}

/**
 * @method createCollection
 * Factory method for instantiating a Backbone collection of model objects. Creates and returns a
 * collection for holding the named type of model objects.
 *
 * See [Backbone.Collection](http://backbonejs.org/#Collection) in the Backbone.js
 * documentation for  information on the methods and  properties provided by the
 * Collection object.
 * @param {String} name Name of model to hold in this collection.
 * @param {*...} [args] Arguments to pass to the collection.
 * @return {Backbone.Collection} Backbone collection object.
 */
exports.createCollection = function(name, args) {
	return new (require('alloy/models/' + ucfirst(name)).Collection)(args);
}

function isTabletFallback() {
	return !(Math.min(
		Ti.Platform.displayCaps.platformHeight,
		Ti.Platform.displayCaps.platformWidth
	) < 700);
}

/**
 * @property {Boolean} isTablet
 * `true` if the current device is a tablet.
 *
 */
exports.isTablet = (function() {
	if (OS_IOS) {
		return Ti.Platform.osname === 'ipad';
	}
	if (OS_ANDROID) {
		try {
			var psc = require('ti.physicalSizeCategory');
			return psc.physicalSizeCategory === 'large' ||
				   psc.physicalSizeCategory === 'xlarge';
		} catch(e) {
			Ti.API.warn('Could not find ti.physicalSizeCategory module, using fallback for Alloy.isTablet');
			return isTabletFallback();
		}
	}
	if (OS_MOBILEWEB) {
		return !(Math.min(
			Ti.Platform.displayCaps.platformHeight,
			Ti.Platform.displayCaps.platformWidth
		) < 400);
	}

	// Last resort. Don't worry, uglifyjs cleans up this dead code if necessary.
	return isTabletFallback();
})();

/**
 * @property {Boolean} isHandheld
 * `true` if the current device is a handheld device (not a tablet).
 *
 */
exports.isHandheld = !exports.isTablet;

if (OS_ANDROID) {
	exports.Android = {};
	exports.Android.menuItemCreateArgs = ['itemId','groupId','title','order'];
}
<|endoftext|>


<commit_before>var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
        var testElement = document.getElementById('test');
        testElement.innerHTML = 'That';
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        window.addEventListener("batterystatus", onBatteryStatus, false);

        var testElement = document.getElementById('test');
        testElment.innerHTML = "Ash";
        function onBatteryStatus(info) {
    // Handle the online event
        testElement.innerHTML = info.level;
      };

    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }

};

var addToStatus = function(message) {
console.log(message);
var newP = document.createElement("p");
var node = document.createTextNode(message);
var status = document.getElementById("status");
newP.appendChild(node);
// document.getElementById("status").appendChild(newP);
status.insertBefore(newP, status.firstChild);
}

var test = {
addNetwork: function() {

//var ssid =  document.getElementById("SSID").value;
//var pass = document.getElementById("password").value;

var wifiConfiguration = WifiWizard.formatWifiConfig(ssid, pass, 'WPA');

WifiWizard.addNetwork(wifiConfiguration, addToStatus, addToStatus);
addToStatus(wifiConfiguration.SSID + " " + wifiConfiguration.Password);
addToStatus("Adding Network...");
},

removeNetwork: function() {
var ssid =  document.getElementById("SSID").value;
addToStatus("Removing network: " + ssid);
WifiWizard.removeNetwork(ssid, addToStatus, addToStatus);
},

handleList: function(networkList) {
addToStatus(networkList.join(" "));
},

listNetworks: function() {
WifiWizard.listNetworks(test.handleList);
addToStatus("Listing networks...");
},

disconnect: function() {
var ssid =  document.getElementById("SSID").value;
addToStatus("Disconnecting: " + ssid);
WifiWizard.disconnectNetwork(ssid, addToStatus, addToStatus);
},

connect: function() {
//var ssid =  document.getElementById("SSID").value;
var ssid = 'utsav';
addToStatus("Connecting: " + ssid);
WifiWizard.connectNetwork(ssid, addToStatus, addToStatus);
},

clear: function() {
document.getElementById("status").innerHTML="";
addToStatus("WifiTest Cleared.");
}
};

addToStatus("WifiTest loaded.");
var wwIsObject = (typeof WifiWizard == "object") ? true : false ;
var wwFunctions = [];
if (wwIsObject) {
  for (var prop in WifiWizard) {
    wwFunctions.push(prop);
  }
  wwFunctions.join(", ")
  addToStatus("WifiWizard functions: " + wwFunctions.join(", "));
}
else {
  addToStatus("Variable WifiWizard not an object.");
};
<commit_msg>testing local network<commit_after>var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
        var testElement = document.getElementById('test');
        testElement.innerHTML = 'That';
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
        window.addEventListener("batterystatus", onBatteryStatus, false);

        var testElement = document.getElementById('test');
        testElment.innerHTML = "Ash";
        function onBatteryStatus(info) {
    // Handle the online event
        testElement.innerHTML = info.level;
      };

    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }

};

var addToStatus = function(message) {
console.log(message);
var newP = document.createElement("p");
var node = document.createTextNode(message);
var status = document.getElementById("status");
newP.appendChild(node);
// document.getElementById("status").appendChild(newP);
status.insertBefore(newP, status.firstChild);
}

var test = {
addNetwork: function() {

//var ssid =  document.getElementById("SSID").value;
//var pass = document.getElementById("password").value;

var wifiConfiguration = WifiWizard.formatWifiConfig(ssid, pass, 'WPA');

WifiWizard.addNetwork(wifiConfiguration, addToStatus, addToStatus);
addToStatus(wifiConfiguration.SSID + " " + wifiConfiguration.Password);
addToStatus("Adding Network...");
},

removeNetwork: function() {
var ssid =  document.getElementById("SSID").value;
addToStatus("Removing network: " + ssid);
WifiWizard.removeNetwork(ssid, addToStatus, addToStatus);
},

handleList: function(networkList) {
addToStatus(networkList.join(" "));
},

listNetworks: function() {
WifiWizard.listNetworks(test.handleList);
addToStatus("Listing networks...");
},

disconnect: function() {
var ssid =  document.getElementById("SSID").value;
addToStatus("Disconnecting: " + ssid);
WifiWizard.disconnectNetwork(ssid, addToStatus, addToStatus);
},

connect: function() {
//var ssid =  document.getElementById("SSID").value;
var ssid = 'noble';
addToStatus("Connecting: " + ssid);
WifiWizard.connectNetwork(ssid, addToStatus, addToStatus);
},

clear: function() {
document.getElementById("status").innerHTML="";
addToStatus("WifiTest Cleared.");
}
};

addToStatus("WifiTest loaded.");
var wwIsObject = (typeof WifiWizard == "object") ? true : false ;
var wwFunctions = [];
if (wwIsObject) {
  for (var prop in WifiWizard) {
    wwFunctions.push(prop);
  }
  wwFunctions.join(", ")
  addToStatus("WifiWizard functions: " + wwFunctions.join(", "));
}
else {
  addToStatus("Variable WifiWizard not an object.");
};
<|endoftext|>


<commit_before>/*global self, caches, fetch*/

var urlsToCache = [
	// '/index.html',
	'/offline.html',
	'/style.css',
	'/fonts/FiraSans-Regular.woff',
	'/fonts/FiraSans-Regular.woff2',
	'/fonts/FiraSans-Bold.woff',
	'/fonts/FiraSans-Bold.woff2',
	'/images/CoffeeCup.svg',
	'/js/stampit.min.js',
	'/js/Util.js',
	'/js/Events.js',
	'/js/View.js',
	'/js/Controller.js',
	'/js/Model.js',
	'/js/app/CardsModel.js',
	'/js/app/ToolbarView.js',
	'/js/app/cardHelper.js',
	'/js/app/CardsView.js',
	'/js/app/BigCardView.js',
	'/js/app/BigCardController.js',
	'/js/app/ToolbarController.js',
	'/js/app/CardsController.js',
	'/js/app/app.js'
];

var cacheName = 'scrumpoker-v1.0.11';

self.addEventListener('activate', function (event) {
	'use strict';
	var cacheWhitelist = [cacheName];

	event.waitUntil(
		caches.keys().then(function(cacheNames) {
			return Promise.all(
				cacheNames.map(function(cacheName) {
					if (cacheWhitelist.indexOf(cacheName) === -1) {
						return caches.delete(cacheName);
					}
				})
			);
		}).then(self.clients.claim())
	);
});
self.addEventListener('install', function (e) {
	'use strict';
	e.waitUntil(caches.open(cacheName).then(function (cache) {
		return cache.addAll(urlsToCache);
	}));
}, false);

function serveRightFromCache(event) {
	'use strict';

	return caches.open(cacheName).then(function (cache) {
		return cache.match(event.request);
	}).then(function (response) {
		if (typeof response === 'undefined') {
			return fetch(event.request);
		}

		return Promise.resolve(response);
	}).catch(function () {
		return fetch(event.request);
	});
}

function serveOnline(event, alias) {
	'use strict';

	return fetch(event.request, {cache: 'no-cache'}).catch(function() {
		return caches.open(cacheName).then(function (cache) {
			return cache.match(alias || event.request);
		});
	});
}

self.addEventListener('fetch', function (event) {
	'use strict';

	if (new URL(event.request.url).pathname === '/') {
		event.respondWith(serveOnline(event, '/offline.html'));
	} else {
		event.respondWith(serveRightFromCache(event));
	}
}, false);
<commit_msg>Update cache version<commit_after>/*global self, caches, fetch*/

var urlsToCache = [
	// '/index.html',
	'/offline.html',
	'/style.css',
	'/fonts/FiraSans-Regular.woff',
	'/fonts/FiraSans-Regular.woff2',
	'/fonts/FiraSans-Bold.woff',
	'/fonts/FiraSans-Bold.woff2',
	'/images/CoffeeCup.svg',
	'/js/stampit.min.js',
	'/js/Util.js',
	'/js/Events.js',
	'/js/View.js',
	'/js/Controller.js',
	'/js/Model.js',
	'/js/app/CardsModel.js',
	'/js/app/ToolbarView.js',
	'/js/app/cardHelper.js',
	'/js/app/CardsView.js',
	'/js/app/BigCardView.js',
	'/js/app/BigCardController.js',
	'/js/app/ToolbarController.js',
	'/js/app/CardsController.js',
	'/js/app/app.js'
];

var cacheName = 'scrumpoker-v1.0.12';

self.addEventListener('activate', function (event) {
	'use strict';
	var cacheWhitelist = [cacheName];

	event.waitUntil(
		caches.keys().then(function(cacheNames) {
			return Promise.all(
				cacheNames.map(function(cacheName) {
					if (cacheWhitelist.indexOf(cacheName) === -1) {
						return caches.delete(cacheName);
					}
				})
			);
		}).then(self.clients.claim())
	);
});
self.addEventListener('install', function (e) {
	'use strict';
	e.waitUntil(caches.open(cacheName).then(function (cache) {
		return cache.addAll(urlsToCache);
	}));
}, false);

function serveRightFromCache(event) {
	'use strict';

	return caches.open(cacheName).then(function (cache) {
		return cache.match(event.request);
	}).then(function (response) {
		if (typeof response === 'undefined') {
			return fetch(event.request);
		}

		return Promise.resolve(response);
	}).catch(function () {
		return fetch(event.request);
	});
}

function serveOnline(event, alias) {
	'use strict';

	return fetch(event.request, {cache: 'no-cache'}).catch(function() {
		return caches.open(cacheName).then(function (cache) {
			return cache.match(alias || event.request);
		});
	});
}

self.addEventListener('fetch', function (event) {
	'use strict';

	if (new URL(event.request.url).pathname === '/') {
		event.respondWith(serveOnline(event, '/offline.html'));
	} else {
		event.respondWith(serveRightFromCache(event));
	}
}, false);
<|endoftext|>