<commit_before>"use strict"

////////////////////////////////////////////////////////////////////////////////////////////////////
function Form(name, parent, data) {
    this.name          = name;
    this.page          = parent;
    this.data          = data;
    this.parent        = parent;
    this.dataSource    = null;
    this.changed       = false;
    this.dataSources   = {};
    this.fields        = {};
    this.controls      = {};
    this.eventHandlers = {};
    // event
    this.eventChanged  = new QForms.Event(this);
    this.eventUpdated  = new QForms.Event(this);
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.init = function() {
    // dataSources
    for (var dsName in this.data.dataSources) {
        this.dataSources[dsName] = new DataSource(dsName,this,this.data.dataSources[dsName]);
        this.dataSources[dsName].init();
    }
    // fields
    for (var name in this.data.fields) {
        var field = this.data.fields[name];
        this.fields[name] = eval("new {class}(name,this,field)".replace("{class}",field.class));
        this.fields[name].init();
    }
    // controls
    for (var name in this.data.controls) {
        var data = this.data.controls[name];
        this.controls[name] = eval("new {class}(data,this)".replace("{class}",data.class));
        this.controls[name].init();
    }
    // eventHandlers
    for (var name in this.data.eventHandlers) {
        this.eventHandlers[name] = new EventHandler(this,this.data.eventHandlers[name]);
        this.eventHandlers[name].init();
    }
    this.dataSource = this.dataSources["default"];
    this.dataSource.eventChanged.subscribe(this,"onDataSourceChanged");
    this.dataSource.eventUpdated.subscribe(this,"onDataSourceUpdated");
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.deinit = function() {
    this.dataSource.eventChanged.unsubscribe(this,"onDataSourceChanged");
    this.dataSource.eventUpdated.unsubscribe(this,"onDataSourceUpdated");
    for (var dsName in this.dataSources) {
        this.dataSources[dsName].deinit();
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.defaultValuesToRow = function(row) {
    for (var name in this.fields) {
        var field = this.fields[name];
        if (field.data.column !== undefined) {
            row[field.data.column] = field.getDefaultValue();
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.onDataSourceChanged = function(eventArgs) {
    var dataSource = eventArgs.object;
    if (dataSource.name === "default") {
        this.changed = true;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.onDataSourceUpdated = function(eventArgs) {
    var dataSource = eventArgs.object;
    if (dataSource.name === "default") {
        this.changed = false;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.update = function() {
    var self = this;
    // during new row creation, set row key to page if is not opened yet
    this.dataSources["default"].update(function(newKey) {
        if (!self.page.deinited) self.page.setKey(newKey);
    });
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.refill = function() {
    this.dataSources["default"].refill(this.page.params);
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.executeAction = function(action,args) {
    action.exec(args,{"form":this});
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.handleEvent = function(event,args) {
    //console.log(event);
    if (this.eventHandlers && this.eventHandlers[event]) {
        this.eventHandlers[event].handleEvent(args);
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.getExpValue = function(exp) {
    //console.log(exp);
    var value = exp;
    if (value === "CurrentDate()") {
        value = QForms.currentDate();
    } else if (value === "CurrentTime()") {
        value = QForms.currentTime();
    } else if (value.substr(0,1) === "@") {
        var name = value.substr(1,value.length-1);
        var arr = name.split(".");
        if (arr[0] === "this") arr[0] = this.page.name;
        if (arr[1] === "this") arr[1] = this.name;
        name = arr.join(".");
        if (this.page.params[name] !== undefined) {
            value = this.page.params[name];
        }
    }
    return value;
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.openPage = function(params) {
    this.page.openPage(params);
}<commit_msg>empty default value is null<commit_after>"use strict"

////////////////////////////////////////////////////////////////////////////////////////////////////
function Form(name, parent, data) {
    this.name          = name;
    this.page          = parent;
    this.data          = data;
    this.parent        = parent;
    this.dataSource    = null;
    this.changed       = false;
    this.dataSources   = {};
    this.fields        = {};
    this.controls      = {};
    this.eventHandlers = {};
    // event
    this.eventChanged  = new QForms.Event(this);
    this.eventUpdated  = new QForms.Event(this);
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.init = function() {
    // dataSources
    for (var dsName in this.data.dataSources) {
        this.dataSources[dsName] = new DataSource(dsName,this,this.data.dataSources[dsName]);
        this.dataSources[dsName].init();
    }
    // fields
    for (var name in this.data.fields) {
        var field = this.data.fields[name];
        this.fields[name] = eval("new {class}(name,this,field)".replace("{class}",field.class));
        this.fields[name].init();
    }
    // controls
    for (var name in this.data.controls) {
        var data = this.data.controls[name];
        this.controls[name] = eval("new {class}(data,this)".replace("{class}",data.class));
        this.controls[name].init();
    }
    // eventHandlers
    for (var name in this.data.eventHandlers) {
        this.eventHandlers[name] = new EventHandler(this,this.data.eventHandlers[name]);
        this.eventHandlers[name].init();
    }
    this.dataSource = this.dataSources["default"];
    this.dataSource.eventChanged.subscribe(this,"onDataSourceChanged");
    this.dataSource.eventUpdated.subscribe(this,"onDataSourceUpdated");
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.deinit = function() {
    this.dataSource.eventChanged.unsubscribe(this,"onDataSourceChanged");
    this.dataSource.eventUpdated.unsubscribe(this,"onDataSourceUpdated");
    for (var dsName in this.dataSources) {
        this.dataSources[dsName].deinit();
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.defaultValuesToRow = function(row) {
    for (var name in this.fields) {
        var field = this.fields[name];
        if (field.data.column !== undefined) {
            row[field.data.column] = field.getDefaultValue();
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.onDataSourceChanged = function(eventArgs) {
    var dataSource = eventArgs.object;
    if (dataSource.name === "default") {
        this.changed = true;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.onDataSourceUpdated = function(eventArgs) {
    var dataSource = eventArgs.object;
    if (dataSource.name === "default") {
        this.changed = false;
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.update = function() {
    var self = this;
    // during new row creation, set row key to page if is not opened yet
    this.dataSources["default"].update(function(newKey) {
        if (!self.page.deinited) self.page.setKey(newKey);
    });
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.refill = function() {
    this.dataSources["default"].refill(this.page.params);
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.executeAction = function(action,args) {
    action.exec(args,{"form":this});
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.handleEvent = function(event,args) {
    //console.log(event);
    if (this.eventHandlers && this.eventHandlers[event]) {
        this.eventHandlers[event].handleEvent(args);
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.getExpValue = function(exp) {
    //console.log(exp);
    var value = exp;
    if (value === "CurrentDate()") {
        value = QForms.currentDate();
    } else if (value === "CurrentTime()") {
        value = QForms.currentTime();
    } else if (value.substr(0,1) === "@") {
        var name = value.substr(1,value.length-1);
        var arr = name.split(".");
        if (arr[0] === "this") arr[0] = this.page.name;
        if (arr[1] === "this") arr[1] = this.name;
        name = arr.join(".");
        if (this.page.params[name] !== undefined) {
            value = this.page.params[name];
        }
    } else if (value === '') {
        value = null;
    }
    return value;
};

////////////////////////////////////////////////////////////////////////////////////////////////////
Form.prototype.openPage = function(params) {
    this.page.openPage(params);
}<|endoftext|>


<commit_before>/* Hyperaudio core
 *
 */

var hyperaudio = (function() {

	// jQuery 2.0.3 (c) 2013 http://jquery.com/

	var
		// [[Class]] -> type pairs
		class2type = {},
		core_toString = class2type.toString,
		core_hasOwn = class2type.hasOwnProperty;

	function hyperaudio() {
		// Nada
	}

	hyperaudio.extend = function() {
		var options, name, src, copy, copyIsArray, clone,
			target = arguments[0] || {},
			i = 1,
			length = arguments.length,
			deep = false;

		// Handle a deep copy situation
		if ( typeof target === "boolean" ) {
			deep = target;
			target = arguments[1] || {};
			// skip the boolean and the target
			i = 2;
		}

		// Handle case when target is a string or something (possible in deep copy)
		if ( typeof target !== "object" && !hyperaudio.isFunction(target) ) {
			target = {};
		}

		// extend hyperaudio itself if only one argument is passed
		if ( length === i ) {
			target = this;
			--i;
		}

		for ( ; i < length; i++ ) {
			// Only deal with non-null/undefined values
			if ( (options = arguments[ i ]) != null ) {
				// Extend the base object
				for ( name in options ) {
					src = target[ name ];
					copy = options[ name ];

					// Prevent never-ending loop
					if ( target === copy ) {
						continue;
					}

					// Recurse if we're merging plain objects or arrays
					if ( deep && copy && ( hyperaudio.isPlainObject(copy) || (copyIsArray = hyperaudio.isArray(copy)) ) ) {
						if ( copyIsArray ) {
							copyIsArray = false;
							clone = src && hyperaudio.isArray(src) ? src : [];

						} else {
							clone = src && hyperaudio.isPlainObject(src) ? src : {};
						}

						// Never move original objects, clone them
						target[ name ] = hyperaudio.extend( deep, clone, copy );

					// Don't bring in undefined values
					} else if ( copy !== undefined ) {
						target[ name ] = copy;
					}
				}
			}
		}

		// Return the modified object
		return target;
	};

	hyperaudio.extend({

		// See test/unit/core.js for details concerning isFunction.
		// Since version 1.3, DOM methods and functions like alert
		// aren't supported. They return false on IE (#2968).
		isFunction: function( obj ) {
			return hyperaudio.type(obj) === "function";
		},

		isArray: Array.isArray,

		isWindow: function( obj ) {
			return obj != null && obj === obj.window;
		},

		type: function( obj ) {
			if ( obj == null ) {
				return String( obj );
			}
			// Support: Safari <= 5.1 (functionish RegExp)
			return typeof obj === "object" || typeof obj === "function" ?
				class2type[ core_toString.call(obj) ] || "object" :
				typeof obj;
		},

		isPlainObject: function( obj ) {
			// Not plain objects:
			// - Any object or value whose internal [[Class]] property is not "[object Object]"
			// - DOM nodes
			// - window
			if ( hyperaudio.type( obj ) !== "object" || obj.nodeType || hyperaudio.isWindow( obj ) ) {
				return false;
			}

			// Support: Firefox <20
			// The try/catch suppresses exceptions thrown when attempting to access
			// the "constructor" property of certain host objects, ie. |window.location|
			// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
			try {
				if ( obj.constructor &&
						!core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
					return false;
				}
			} catch ( e ) {
				return false;
			}

			// If the function hasn't returned already, we're confident that
			// |obj| is a plain object, created by {} or constructed with new Object
			return true;
		}
	});

	function isArraylike( obj ) {
		var length = obj.length,
			type = hyperaudio.type( obj );

		if ( hyperaudio.isWindow( obj ) ) {
			return false;
		}

		if ( obj.nodeType === 1 && length ) {
			return true;
		}

		return type === "array" || type !== "function" &&
			( length === 0 ||
			typeof length === "number" && length > 0 && ( length - 1 ) in obj );
	}
	// [End jQuery code]

	// [Adapted from] jQuery 2.0.3 (c) 2013 http://jquery.com/
	// - each() : removed args parameter (was for use internal to jQuery)

	hyperaudio.extend({
		each: function( obj, callback ) {
			var value,
				i = 0,
				length = obj.length,
				isArray = isArraylike( obj );

			if ( isArray ) {
				for ( ; i < length; i++ ) {
					value = callback.call( obj[ i ], i, obj[ i ] );

					if ( value === false ) {
						break;
					}
				}
			} else {
				for ( i in obj ) {
					value = callback.call( obj[ i ], i, obj[ i ] );

					if ( value === false ) {
						break;
					}
				}
			}

			return obj;
		}
	});
	// [End jQuery code]

	hyperaudio.extend({
		event: {
			ready: 'ha:ready',
			load: 'ha:load',
			save: 'ha:save',
			change: 'ha:change',
			// login: 'ha:login', // No DOM element relating to a login. It is handled by the api.signin when the stage fails to authenticate.
			unauthenticated: 'ha:unauthenticated',
			userplay: 'ha:userplay',
			userpause: 'ha:userpause',
			usercurrenttime: 'ha:usercurrenttime',
			userplayword: 'ha:userplayword',
			error: 'ha:error'
		},
		_commonMethods: {
			options: {
				DEBUG: false,
				entity: 'core'
			},
			_trigger: function(eventType, eventData) {
				var eventObject = hyperaudio.extend(true, {options: this.options}, eventData),
					event = new CustomEvent(eventType, {
						detail: eventObject,
						bubbles: true,
						cancelable: true
					});
				hyperaudio.gaEvent({
					type: this.options.entity + ' : ' + eventType,
					action: eventObject.msg ? eventObject.msg : ''
				});
				this.target.dispatchEvent(event);
			},
			_error: function(msg) {
				var data = {msg: this.options.entity + ' Error : ' + msg};
				this._trigger(hyperaudio.event.error, data);
			},
			_debug: function() {
				var self = this;
				hyperaudio.each(hyperaudio.event, function(eventName, eventType) {
					self.target.addEventListener(eventType, function(event) {
						console.log(self.options.entity + ' ' + eventType + ' event : %o', event);
					}, false);
				});
			}
		},
		register: function(name, module) {
			if(typeof name === 'string') {
				if(typeof module === 'function') {
					module.prototype = hyperaudio.extend({}, this._commonMethods, module.prototype);
					this[name] = function(options) {
						return new module(options);
					};
				} else if(typeof module === 'object') {
					module = hyperaudio.extend({}, this._commonMethods, module);
					this[name] = module;
				}
			}
		},
		utility: function(name, utility) {
			if(typeof name === 'string') {
				this[name] = utility;
			}
		},

		// http://stackoverflow.com/questions/1403888/get-url-parameter-with-javascript-or-jquery
		getURLParameter: function(name) {
			// return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
			// Now looks at top window (frame).
			return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(window.top.location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
		},

		gaEvent: function(detail) {
			// detail: {origin, type, action}

			if(typeof detail !== 'object') {
				if(typeof detail === 'string') {
					detail = {
						type: 'message',
						action: detail
					};
				} else {
					detail = {};
				}
			}

			detail.origin = detail.origin ? detail.origin : 'Hyperaudio Lib';
			detail.type = detail.type ? detail.type : 'no type';
			detail.action = detail.action ? detail.action : 'no action';

			var event = new CustomEvent("ga", {
				detail: detail,
				bubbles: true,
				cancelable: true
			});
			document.dispatchEvent(event);
		},

		hasClass: function(e, c) {
			if ( !e ) return false;

			var re = new RegExp("(^|\\s)" + c + "(\\s|$)");
			return re.test(e.className);
		},
		addClass: function(e, c) {
			if ( this.hasClass(e, c) ) {
				return;
			}

			e.className += ' ' + c;
		},
		removeClass: function (e, c) {
			if ( !this.hasClass(e, c) ) {
				return;
			}

			var re = new RegExp("(^|\\s)" + c + "(\\s|$)", 'g');
			e.className = e.className.replace(re, ' ').replace(/\s{2,}/g, ' ');
		},
		toggleClass: function (e, c) {
			if ( this.hasClass(e, c) ) {
				this.removeClass(e, c);
			} else {
				this.addClass(e, c);
			}
		}

	});

	return hyperaudio;
}());<commit_msg>Refactored the GA type and action use. Type is now the module.<commit_after>/* Hyperaudio core
 *
 */

var hyperaudio = (function() {

	// jQuery 2.0.3 (c) 2013 http://jquery.com/

	var
		// [[Class]] -> type pairs
		class2type = {},
		core_toString = class2type.toString,
		core_hasOwn = class2type.hasOwnProperty;

	function hyperaudio() {
		// Nada
	}

	hyperaudio.extend = function() {
		var options, name, src, copy, copyIsArray, clone,
			target = arguments[0] || {},
			i = 1,
			length = arguments.length,
			deep = false;

		// Handle a deep copy situation
		if ( typeof target === "boolean" ) {
			deep = target;
			target = arguments[1] || {};
			// skip the boolean and the target
			i = 2;
		}

		// Handle case when target is a string or something (possible in deep copy)
		if ( typeof target !== "object" && !hyperaudio.isFunction(target) ) {
			target = {};
		}

		// extend hyperaudio itself if only one argument is passed
		if ( length === i ) {
			target = this;
			--i;
		}

		for ( ; i < length; i++ ) {
			// Only deal with non-null/undefined values
			if ( (options = arguments[ i ]) != null ) {
				// Extend the base object
				for ( name in options ) {
					src = target[ name ];
					copy = options[ name ];

					// Prevent never-ending loop
					if ( target === copy ) {
						continue;
					}

					// Recurse if we're merging plain objects or arrays
					if ( deep && copy && ( hyperaudio.isPlainObject(copy) || (copyIsArray = hyperaudio.isArray(copy)) ) ) {
						if ( copyIsArray ) {
							copyIsArray = false;
							clone = src && hyperaudio.isArray(src) ? src : [];

						} else {
							clone = src && hyperaudio.isPlainObject(src) ? src : {};
						}

						// Never move original objects, clone them
						target[ name ] = hyperaudio.extend( deep, clone, copy );

					// Don't bring in undefined values
					} else if ( copy !== undefined ) {
						target[ name ] = copy;
					}
				}
			}
		}

		// Return the modified object
		return target;
	};

	hyperaudio.extend({

		// See test/unit/core.js for details concerning isFunction.
		// Since version 1.3, DOM methods and functions like alert
		// aren't supported. They return false on IE (#2968).
		isFunction: function( obj ) {
			return hyperaudio.type(obj) === "function";
		},

		isArray: Array.isArray,

		isWindow: function( obj ) {
			return obj != null && obj === obj.window;
		},

		type: function( obj ) {
			if ( obj == null ) {
				return String( obj );
			}
			// Support: Safari <= 5.1 (functionish RegExp)
			return typeof obj === "object" || typeof obj === "function" ?
				class2type[ core_toString.call(obj) ] || "object" :
				typeof obj;
		},

		isPlainObject: function( obj ) {
			// Not plain objects:
			// - Any object or value whose internal [[Class]] property is not "[object Object]"
			// - DOM nodes
			// - window
			if ( hyperaudio.type( obj ) !== "object" || obj.nodeType || hyperaudio.isWindow( obj ) ) {
				return false;
			}

			// Support: Firefox <20
			// The try/catch suppresses exceptions thrown when attempting to access
			// the "constructor" property of certain host objects, ie. |window.location|
			// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
			try {
				if ( obj.constructor &&
						!core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
					return false;
				}
			} catch ( e ) {
				return false;
			}

			// If the function hasn't returned already, we're confident that
			// |obj| is a plain object, created by {} or constructed with new Object
			return true;
		}
	});

	function isArraylike( obj ) {
		var length = obj.length,
			type = hyperaudio.type( obj );

		if ( hyperaudio.isWindow( obj ) ) {
			return false;
		}

		if ( obj.nodeType === 1 && length ) {
			return true;
		}

		return type === "array" || type !== "function" &&
			( length === 0 ||
			typeof length === "number" && length > 0 && ( length - 1 ) in obj );
	}
	// [End jQuery code]

	// [Adapted from] jQuery 2.0.3 (c) 2013 http://jquery.com/
	// - each() : removed args parameter (was for use internal to jQuery)

	hyperaudio.extend({
		each: function( obj, callback ) {
			var value,
				i = 0,
				length = obj.length,
				isArray = isArraylike( obj );

			if ( isArray ) {
				for ( ; i < length; i++ ) {
					value = callback.call( obj[ i ], i, obj[ i ] );

					if ( value === false ) {
						break;
					}
				}
			} else {
				for ( i in obj ) {
					value = callback.call( obj[ i ], i, obj[ i ] );

					if ( value === false ) {
						break;
					}
				}
			}

			return obj;
		}
	});
	// [End jQuery code]

	hyperaudio.extend({
		event: {
			ready: 'ha:ready',
			load: 'ha:load',
			save: 'ha:save',
			change: 'ha:change',
			// login: 'ha:login', // No DOM element relating to a login. It is handled by the api.signin when the stage fails to authenticate.
			unauthenticated: 'ha:unauthenticated',
			userplay: 'ha:userplay',
			userpause: 'ha:userpause',
			usercurrenttime: 'ha:usercurrenttime',
			userplayword: 'ha:userplayword',
			error: 'ha:error'
		},
		_commonMethods: {
			options: {
				DEBUG: false,
				entity: 'core'
			},
			_trigger: function(eventType, eventData) {
				var eventObject = hyperaudio.extend(true, {options: this.options}, eventData),
					event = new CustomEvent(eventType, {
						detail: eventObject,
						bubbles: true,
						cancelable: true
					});
				hyperaudio.gaEvent({
					type: this.options.entity,
					action: eventType + ' event: ' + (eventObject.msg ? eventObject.msg : '')
				});
				this.target.dispatchEvent(event);
			},
			_error: function(msg) {
				var data = {msg: this.options.entity + ' Error : ' + msg};
				this._trigger(hyperaudio.event.error, data);
			},
			_debug: function() {
				var self = this;
				hyperaudio.each(hyperaudio.event, function(eventName, eventType) {
					self.target.addEventListener(eventType, function(event) {
						console.log(self.options.entity + ' ' + eventType + ' event : %o', event);
					}, false);
				});
			}
		},
		register: function(name, module) {
			if(typeof name === 'string') {
				if(typeof module === 'function') {
					module.prototype = hyperaudio.extend({}, this._commonMethods, module.prototype);
					this[name] = function(options) {
						return new module(options);
					};
				} else if(typeof module === 'object') {
					module = hyperaudio.extend({}, this._commonMethods, module);
					this[name] = module;
				}
			}
		},
		utility: function(name, utility) {
			if(typeof name === 'string') {
				this[name] = utility;
			}
		},

		// http://stackoverflow.com/questions/1403888/get-url-parameter-with-javascript-or-jquery
		getURLParameter: function(name) {
			// return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
			// Now looks at top window (frame).
			return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(window.top.location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
		},

		gaEvent: function(detail) {
			// detail: {origin, type, action}

			if(typeof detail !== 'object') {
				if(typeof detail === 'string') {
					detail = {
						type: 'message',
						action: detail
					};
				} else {
					detail = {};
				}
			}

			detail.origin = detail.origin ? detail.origin : 'Hyperaudio Lib';
			detail.type = detail.type ? detail.type : 'no type';
			detail.action = detail.action ? detail.action : 'no action';

			var event = new CustomEvent("ga", {
				detail: detail,
				bubbles: true,
				cancelable: true
			});
			document.dispatchEvent(event);
		},

		hasClass: function(e, c) {
			if ( !e ) return false;

			var re = new RegExp("(^|\\s)" + c + "(\\s|$)");
			return re.test(e.className);
		},
		addClass: function(e, c) {
			if ( this.hasClass(e, c) ) {
				return;
			}

			e.className += ' ' + c;
		},
		removeClass: function (e, c) {
			if ( !this.hasClass(e, c) ) {
				return;
			}

			var re = new RegExp("(^|\\s)" + c + "(\\s|$)", 'g');
			e.className = e.className.replace(re, ' ').replace(/\s{2,}/g, ' ');
		},
		toggleClass: function (e, c) {
			if ( this.hasClass(e, c) ) {
				this.removeClass(e, c);
			} else {
				this.addClass(e, c);
			}
		}

	});

	return hyperaudio;
}());<|endoftext|>


<commit_before>/* Hyperaudio core
 *
 */

var hyperaudio = (function() {

	// jQuery 2.0.3 (c) 2013 http://jquery.com/

	var
		// [[Class]] -> type pairs
		class2type = {},
		core_toString = class2type.toString,
		core_hasOwn = class2type.hasOwnProperty;

	function hyperaudio() {
		// Nada
	}

	hyperaudio.extend = function() {
		var options, name, src, copy, copyIsArray, clone,
			target = arguments[0] || {},
			i = 1,
			length = arguments.length,
			deep = false;

		// Handle a deep copy situation
		if ( typeof target === "boolean" ) {
			deep = target;
			target = arguments[1] || {};
			// skip the boolean and the target
			i = 2;
		}

		// Handle case when target is a string or something (possible in deep copy)
		if ( typeof target !== "object" && !hyperaudio.isFunction(target) ) {
			target = {};
		}

		// extend hyperaudio itself if only one argument is passed
		if ( length === i ) {
			target = this;
			--i;
		}

		for ( ; i < length; i++ ) {
			// Only deal with non-null/undefined values
			if ( (options = arguments[ i ]) != null ) {
				// Extend the base object
				for ( name in options ) {
					src = target[ name ];
					copy = options[ name ];

					// Prevent never-ending loop
					if ( target === copy ) {
						continue;
					}

					// Recurse if we're merging plain objects or arrays
					if ( deep && copy && ( hyperaudio.isPlainObject(copy) || (copyIsArray = hyperaudio.isArray(copy)) ) ) {
						if ( copyIsArray ) {
							copyIsArray = false;
							clone = src && hyperaudio.isArray(src) ? src : [];

						} else {
							clone = src && hyperaudio.isPlainObject(src) ? src : {};
						}

						// Never move original objects, clone them
						target[ name ] = hyperaudio.extend( deep, clone, copy );

					// Don't bring in undefined values
					} else if ( copy !== undefined ) {
						target[ name ] = copy;
					}
				}
			}
		}

		// Return the modified object
		return target;
	};

	hyperaudio.extend({

		// See test/unit/core.js for details concerning isFunction.
		// Since version 1.3, DOM methods and functions like alert
		// aren't supported. They return false on IE (#2968).
		isFunction: function( obj ) {
			return hyperaudio.type(obj) === "function";
		},

		isArray: Array.isArray,

		isWindow: function( obj ) {
			return obj != null && obj === obj.window;
		},

		type: function( obj ) {
			if ( obj == null ) {
				return String( obj );
			}
			// Support: Safari <= 5.1 (functionish RegExp)
			return typeof obj === "object" || typeof obj === "function" ?
				class2type[ core_toString.call(obj) ] || "object" :
				typeof obj;
		},

		isPlainObject: function( obj ) {
			// Not plain objects:
			// - Any object or value whose internal [[Class]] property is not "[object Object]"
			// - DOM nodes
			// - window
			if ( hyperaudio.type( obj ) !== "object" || obj.nodeType || hyperaudio.isWindow( obj ) ) {
				return false;
			}

			// Support: Firefox <20
			// The try/catch suppresses exceptions thrown when attempting to access
			// the "constructor" property of certain host objects, ie. |window.location|
			// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
			try {
				if ( obj.constructor &&
						!core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
					return false;
				}
			} catch ( e ) {
				return false;
			}

			// If the function hasn't returned already, we're confident that
			// |obj| is a plain object, created by {} or constructed with new Object
			return true;
		}
	});

	function isArraylike( obj ) {
		var length = obj.length,
			type = hyperaudio.type( obj );

		if ( hyperaudio.isWindow( obj ) ) {
			return false;
		}

		if ( obj.nodeType === 1 && length ) {
			return true;
		}

		return type === "array" || type !== "function" &&
			( length === 0 ||
			typeof length === "number" && length > 0 && ( length - 1 ) in obj );
	}
	// [End jQuery code]

	// [Adapted from] jQuery 2.0.3 (c) 2013 http://jquery.com/
	// - each() : removed args parameter (was for use internal to jQuery)

	hyperaudio.extend({
		each: function( obj, callback ) {
			var value,
				i = 0,
				length = obj.length,
				isArray = isArraylike( obj );

			if ( isArray ) {
				for ( ; i < length; i++ ) {
					value = callback.call( obj[ i ], i, obj[ i ] );

					if ( value === false ) {
						break;
					}
				}
			} else {
				for ( i in obj ) {
					value = callback.call( obj[ i ], i, obj[ i ] );

					if ( value === false ) {
						break;
					}
				}
			}

			return obj;
		}
	});
	// [End jQuery code]

	hyperaudio.extend({
		event: {
			ready: 'ha:ready',
			load: 'ha:load',
			save: 'ha:save',
			error: 'ha:error'
		},
		_commonMethods: {
			options: {
				DEBUG: true,
				entity: 'core'
			},
			_trigger: function(eventType, eventData) {
				var eventObject = hyperaudio.extend(true, {options: this.options}, eventData),
					event = new CustomEvent(eventType, {
						detail: eventObject,
						bubbles: true,
						cancelable: true
					});
				this.target.dispatchEvent(event);
			},
			_error: function(msg) {
				var data = {msg: this.options.entity + ' Error : ' + msg};
				this._trigger(hyperaudio.event.error, data);
			},
			_debug: function() {
				var self = this;
				hyperaudio.each(hyperaudio.event, function(eventName, eventType) {
					self.target.addEventListener(eventType, function(event) {
						console.log(self.options.entity + ' ' + eventType + ' event : %o', event);
					}, false);
				});
			}
		},
		register: function(name, module) {
			if(typeof name === 'string') {
				if(typeof module === 'function') {
					module.prototype = hyperaudio.extend({}, this._commonMethods, module.prototype);
					this[name] = function(options) {
						return new module(options);
					};
				} else if(typeof module === 'object') {
					module = hyperaudio.extend({}, this._commonMethods, module);
					this[name] = module;
				}
			}
		},
		utility: function(name, utility) {
			if(typeof name === 'string') {
				this[name] = utility;
			}
		},

		// TMP - This fn is WIP and left in as started making code for JSONP and then put it on hold.
		jsonp: function(url, scope, callback) {
			//
			var head = document.getElementsByTagName('head')[0];
			var script = document.createElement('script');
			script.type = 'text/javascript';

			var jsonp_i = 0; // TMP - would be in scope of core code as a static.

			// Need to make the callback run in the correct scope.
			callback[jsonp_i++] = function(json) {
				callback.call(scope, data);
			};

			script.src = url;

		},

		hasClass: function(e, c) {
			if ( !e ) return false;

			var re = new RegExp("(^|\\s)" + c + "(\\s|$)");
			return re.test(e.className);
		},
		addClass: function(e, c) {
			if ( this.hasClass(e, c) ) {
				return;
			}

			e.className += ' ' + c;
		},
		removeClass: function (e, c) {
			if ( !this.hasClass(e, c) ) {
				return;
			}

			var re = new RegExp("(^|\\s)" + c + "(\\s|$)", 'g');
			e.className = e.className.replace(re, ' ').replace(/\s{2,}/g, ' ');
		},
		toggleClass: function (e, c) {
			if ( this.hasClass(e, c) ) {
				this.removeClass(e, c);
			} else {
				this.addClass(e, c);
			}
		}

	});

	return hyperaudio;
}());<commit_msg>Deleted unused json method from core.<commit_after>/* Hyperaudio core
 *
 */

var hyperaudio = (function() {

	// jQuery 2.0.3 (c) 2013 http://jquery.com/

	var
		// [[Class]] -> type pairs
		class2type = {},
		core_toString = class2type.toString,
		core_hasOwn = class2type.hasOwnProperty;

	function hyperaudio() {
		// Nada
	}

	hyperaudio.extend = function() {
		var options, name, src, copy, copyIsArray, clone,
			target = arguments[0] || {},
			i = 1,
			length = arguments.length,
			deep = false;

		// Handle a deep copy situation
		if ( typeof target === "boolean" ) {
			deep = target;
			target = arguments[1] || {};
			// skip the boolean and the target
			i = 2;
		}

		// Handle case when target is a string or something (possible in deep copy)
		if ( typeof target !== "object" && !hyperaudio.isFunction(target) ) {
			target = {};
		}

		// extend hyperaudio itself if only one argument is passed
		if ( length === i ) {
			target = this;
			--i;
		}

		for ( ; i < length; i++ ) {
			// Only deal with non-null/undefined values
			if ( (options = arguments[ i ]) != null ) {
				// Extend the base object
				for ( name in options ) {
					src = target[ name ];
					copy = options[ name ];

					// Prevent never-ending loop
					if ( target === copy ) {
						continue;
					}

					// Recurse if we're merging plain objects or arrays
					if ( deep && copy && ( hyperaudio.isPlainObject(copy) || (copyIsArray = hyperaudio.isArray(copy)) ) ) {
						if ( copyIsArray ) {
							copyIsArray = false;
							clone = src && hyperaudio.isArray(src) ? src : [];

						} else {
							clone = src && hyperaudio.isPlainObject(src) ? src : {};
						}

						// Never move original objects, clone them
						target[ name ] = hyperaudio.extend( deep, clone, copy );

					// Don't bring in undefined values
					} else if ( copy !== undefined ) {
						target[ name ] = copy;
					}
				}
			}
		}

		// Return the modified object
		return target;
	};

	hyperaudio.extend({

		// See test/unit/core.js for details concerning isFunction.
		// Since version 1.3, DOM methods and functions like alert
		// aren't supported. They return false on IE (#2968).
		isFunction: function( obj ) {
			return hyperaudio.type(obj) === "function";
		},

		isArray: Array.isArray,

		isWindow: function( obj ) {
			return obj != null && obj === obj.window;
		},

		type: function( obj ) {
			if ( obj == null ) {
				return String( obj );
			}
			// Support: Safari <= 5.1 (functionish RegExp)
			return typeof obj === "object" || typeof obj === "function" ?
				class2type[ core_toString.call(obj) ] || "object" :
				typeof obj;
		},

		isPlainObject: function( obj ) {
			// Not plain objects:
			// - Any object or value whose internal [[Class]] property is not "[object Object]"
			// - DOM nodes
			// - window
			if ( hyperaudio.type( obj ) !== "object" || obj.nodeType || hyperaudio.isWindow( obj ) ) {
				return false;
			}

			// Support: Firefox <20
			// The try/catch suppresses exceptions thrown when attempting to access
			// the "constructor" property of certain host objects, ie. |window.location|
			// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
			try {
				if ( obj.constructor &&
						!core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
					return false;
				}
			} catch ( e ) {
				return false;
			}

			// If the function hasn't returned already, we're confident that
			// |obj| is a plain object, created by {} or constructed with new Object
			return true;
		}
	});

	function isArraylike( obj ) {
		var length = obj.length,
			type = hyperaudio.type( obj );

		if ( hyperaudio.isWindow( obj ) ) {
			return false;
		}

		if ( obj.nodeType === 1 && length ) {
			return true;
		}

		return type === "array" || type !== "function" &&
			( length === 0 ||
			typeof length === "number" && length > 0 && ( length - 1 ) in obj );
	}
	// [End jQuery code]

	// [Adapted from] jQuery 2.0.3 (c) 2013 http://jquery.com/
	// - each() : removed args parameter (was for use internal to jQuery)

	hyperaudio.extend({
		each: function( obj, callback ) {
			var value,
				i = 0,
				length = obj.length,
				isArray = isArraylike( obj );

			if ( isArray ) {
				for ( ; i < length; i++ ) {
					value = callback.call( obj[ i ], i, obj[ i ] );

					if ( value === false ) {
						break;
					}
				}
			} else {
				for ( i in obj ) {
					value = callback.call( obj[ i ], i, obj[ i ] );

					if ( value === false ) {
						break;
					}
				}
			}

			return obj;
		}
	});
	// [End jQuery code]

	hyperaudio.extend({
		event: {
			ready: 'ha:ready',
			load: 'ha:load',
			save: 'ha:save',
			error: 'ha:error'
		},
		_commonMethods: {
			options: {
				DEBUG: true,
				entity: 'core'
			},
			_trigger: function(eventType, eventData) {
				var eventObject = hyperaudio.extend(true, {options: this.options}, eventData),
					event = new CustomEvent(eventType, {
						detail: eventObject,
						bubbles: true,
						cancelable: true
					});
				this.target.dispatchEvent(event);
			},
			_error: function(msg) {
				var data = {msg: this.options.entity + ' Error : ' + msg};
				this._trigger(hyperaudio.event.error, data);
			},
			_debug: function() {
				var self = this;
				hyperaudio.each(hyperaudio.event, function(eventName, eventType) {
					self.target.addEventListener(eventType, function(event) {
						console.log(self.options.entity + ' ' + eventType + ' event : %o', event);
					}, false);
				});
			}
		},
		register: function(name, module) {
			if(typeof name === 'string') {
				if(typeof module === 'function') {
					module.prototype = hyperaudio.extend({}, this._commonMethods, module.prototype);
					this[name] = function(options) {
						return new module(options);
					};
				} else if(typeof module === 'object') {
					module = hyperaudio.extend({}, this._commonMethods, module);
					this[name] = module;
				}
			}
		},
		utility: function(name, utility) {
			if(typeof name === 'string') {
				this[name] = utility;
			}
		},

		hasClass: function(e, c) {
			if ( !e ) return false;

			var re = new RegExp("(^|\\s)" + c + "(\\s|$)");
			return re.test(e.className);
		},
		addClass: function(e, c) {
			if ( this.hasClass(e, c) ) {
				return;
			}

			e.className += ' ' + c;
		},
		removeClass: function (e, c) {
			if ( !this.hasClass(e, c) ) {
				return;
			}

			var re = new RegExp("(^|\\s)" + c + "(\\s|$)", 'g');
			e.className = e.className.replace(re, ' ').replace(/\s{2,}/g, ' ');
		},
		toggleClass: function (e, c) {
			if ( this.hasClass(e, c) ) {
				this.removeClass(e, c);
			} else {
				this.addClass(e, c);
			}
		}

	});

	return hyperaudio;
}());<|endoftext|>


<commit_before>//==========================================
//      Namespace and Vars
//==========================================

var namespace = {};

// Initialize preset variables
namespace.vars = (function() {
    var preset = {
        pi: CSNumber.real(Math.PI),
        'π': CSNumber.real(Math.PI),
        i: CSNumber.complex(0, 1),
        'true': General.bool(true),
        'false': General.bool(false),
        '#': nada,
        'nil': List.turnIntoCSList([]),
        'newline': General.string('\n'),
        'tab': General.string('\t'),
    };
    var vars = [];
    for (var name in preset)
        vars[name] = [preset[name]];
    return vars;
})();

namespace.isVariable = function(name) {
    return this.vars.hasOwnProperty(name);
};

namespace.create = function(name) {
    if (this.vars.hasOwnProperty(name))
        return this.vars[name];
    var v = [null];
    this.vars[name] = v;
    return v;
};

namespace.newvar = function(name) {
    var v = this.vars[name];
    v.push(nada); // nada not null for deeper levels
    return v;
};

namespace.removevar = function(name) {
    var stack = this.vars[name];
    if (stack.length === 0) console.error("Removing non-existing " + name);
    stack.pop();
    if (stack.length === 0) console.warn("Removing last " + name);
};

namespace.setvar = function(name, val) {
    var stack = this.vars[name];
    if (stack.length === 0) console.error("Setting non-existing variable " + name);
    if (val === undefined) {
        console.error("Setting variable " + name + " to undefined value");
        val = nada;
    }
    if (val.ctype === 'undefined') {
        stack[stack.length - 1] = val;
        return;
    }
    var erg = val;
    if (erg === null) erg = nada; // explicit setting does lift unset state
    stack[stack.length - 1] = erg;
};

namespace.undefinedWarning = {};

namespace.getvar = function(name) {

    var stack = this.vars[name];
    if (stack.length === 0) console.error("Getting non-existing variable " + name);
    var erg = stack[stack.length - 1];
    if (erg === null) {
        if (csgeo.csnames.hasOwnProperty(name)) {
            return {
                'ctype': 'geo',
                'value': csgeo.csnames[name]
            };
        } else {
            if (console && console.log && this.undefinedWarning[name] === undefined) {
                this.undefinedWarning[name] = true;
                console.log("Warning: Accessing undefined variable: " + name);
            }
        }
        return nada;
    }
    return erg;
};

namespace.dump = function(name) {
    var stack = this.vars[name];
    console.log("*** Dump " + name);

    for (var i = 0; i < stack.length; i++) {
        console.log(i + ":> " + niceprint(stack[i]));
    }
};

namespace.vstack = [];

namespace.pushVstack = function(v) {
    this.vstack.push(v);

};
namespace.popVstack = function() {
    this.vstack.pop();
};

namespace.cleanVstack = function() {
    var st = this.vstack;
    while (st.length > 0 && st[st.length - 1] !== "*") {
        this.removevar(st[st.length - 1]);
        st.pop();
    }
    if (st.length > 0) {
        st.pop();
    }
};
<commit_msg>empty stack for doubledot operator<commit_after>//==========================================
//      Namespace and Vars
//==========================================

var namespace = {};

// Initialize preset variables
namespace.vars = (function() {
    var preset = {
        pi: CSNumber.real(Math.PI),
        'π': CSNumber.real(Math.PI),
        i: CSNumber.complex(0, 1),
        'true': General.bool(true),
        'false': General.bool(false),
        '#': nada,
        'nil': List.turnIntoCSList([]),
        'newline': General.string('\n'),
        'tab': General.string('\t'),
    };
    var vars = [];
    for (var name in preset)
        vars[name] = [preset[name]];
    return vars;
})();

namespace.isVariable = function(name) {
    return this.vars.hasOwnProperty(name);
};

namespace.create = function(name) {
    if (this.vars.hasOwnProperty(name))
        return this.vars[name];
    var v = [null];
    this.vars[name] = v;
    return v;
};

namespace.newvar = function(name) {
    var v = this.vars[name];
    v.push(nada); // nada not null for deeper levels
    return v;
};

namespace.removevar = function(name) {
    var stack = this.vars[name];
    if (stack.length === 0) console.error("Removing non-existing " + name);
    stack.pop();
    if (stack.length === 0) console.warn("Removing last " + name);
};

namespace.setvar = function(name, val) {
    var stack = this.vars[name];
    if (stack.length === 0) console.error("Setting non-existing variable " + name);
    if (val === undefined) {
        console.error("Setting variable " + name + " to undefined value");
        val = nada;
    }
    if (val.ctype === 'undefined') {
        stack[stack.length - 1] = val;
        return;
    }
    var erg = val;
    if (erg === null) erg = nada; // explicit setting does lift unset state
    stack[stack.length - 1] = erg;
};

namespace.undefinedWarning = {};

namespace.getvar = function(name) {

    var stack = this.vars[name] || [];
    if (stack.length === 0) console.error("Getting non-existing variable " + name);
    var erg = stack[stack.length - 1];
    if (erg === null) {
        if (csgeo.csnames.hasOwnProperty(name)) {
            return {
                'ctype': 'geo',
                'value': csgeo.csnames[name]
            };
        } else {
            if (console && console.log && this.undefinedWarning[name] === undefined) {
                this.undefinedWarning[name] = true;
                console.log("Warning: Accessing undefined variable: " + name);
            }
        }
        return nada;
    }
    return erg;
};

namespace.dump = function(name) {
    var stack = this.vars[name];
    console.log("*** Dump " + name);

    for (var i = 0; i < stack.length; i++) {
        console.log(i + ":> " + niceprint(stack[i]));
    }
};

namespace.vstack = [];

namespace.pushVstack = function(v) {
    this.vstack.push(v);

};
namespace.popVstack = function() {
    this.vstack.pop();
};

namespace.cleanVstack = function() {
    var st = this.vstack;
    while (st.length > 0 && st[st.length - 1] !== "*") {
        this.removevar(st[st.length - 1]);
        st.pop();
    }
    if (st.length > 0) {
        st.pop();
    }
};
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from 'react'
import MenuItem from './MenuItem'

const items = [
  {id: 'monitor', iconClass: 'eye', title: 'Monitor', shortcuts: ['m', '1']},
  {id: 'tracking', iconClass: 'drawer2', title: 'Tracking', shortcuts: ['t', '2']},
  {id: 'success', iconClass: 'checkmark', title: 'Success', shortcuts: ['s', '3']},
  {id: 'audio-visual', iconClass: 'display', title: 'Audio', shortcuts: ['v', '4']},
  {id: 'backup', iconClass: 'floppy-disk', title: 'Backup', shortcuts: ['b', '5']},
  {id: 'help', iconClass: 'question', title: 'Help', shortcuts: ['h', '6']}
]

class Menu extends Component {
  constructor(props) {
    super(props)
  }

  render() {
    const footerStyle = {
      backgroundColor: this.props.versionColour
    }

    return (

Navigation

            {
              items.map((item) => {
                return <MenuItem key={item.id} id={item.id}
                                 iconClass={'icon-' + item.iconClass}
                                 title={item.title}
                                 shortcuts={item.shortcuts}/>
              })
            }

v{this.props.versionNumber}

{this.props.versionName}

{`<${this.props.commitHash}>`}

    )
  }
}

Menu.propTypes = {
  versionNumber: PropTypes.string,
  versionName: PropTypes.string,
  commitHash: PropTypes.string,
  versionColour: PropTypes.string
}

export default Menu
<commit_msg>Revert "Ste - changing text as example"<commit_after>import React, {Component, PropTypes} from 'react'
import MenuItem from './MenuItem'

const items = [
  {id: 'monitor', iconClass: 'eye', title: 'Monitor', shortcuts: ['m', '1']},
  {id: 'tracking', iconClass: 'drawer2', title: 'Tracking', shortcuts: ['t', '2']},
  {id: 'success', iconClass: 'checkmark', title: 'Success', shortcuts: ['s', '3']},
  {id: 'audio-visual', iconClass: 'display', title: 'Audio/Visual', shortcuts: ['v', '4']},
  {id: 'backup', iconClass: 'floppy-disk', title: 'Backup', shortcuts: ['b', '5']},
  {id: 'help', iconClass: 'question', title: 'Help', shortcuts: ['h', '6']}
]

class Menu extends Component {
  constructor(props) {
    super(props)
  }

  render() {
    const footerStyle = {
      backgroundColor: this.props.versionColour
    }

    return (

Navigation

            {
              items.map((item) => {
                return <MenuItem key={item.id} id={item.id}
                                 iconClass={'icon-' + item.iconClass}
                                 title={item.title}
                                 shortcuts={item.shortcuts}/>
              })
            }

v{this.props.versionNumber}

{this.props.versionName}

{`<${this.props.commitHash}>`}

    )
  }
}

Menu.propTypes = {
  versionNumber: PropTypes.string,
  versionName: PropTypes.string,
  commitHash: PropTypes.string,
  versionColour: PropTypes.string
}

export default Menu
<|endoftext|>


<commit_before>// ==========================================================================
// Plyr Polyfilled Build
// plyr.js v3.4.3
// https://github.com/sampotts/plyr
// License: The MIT License (MIT)
// ==========================================================================

import 'babel-polyfill';
import 'custom-event-polyfill';
import 'url-polyfill';
import Plyr from './plyr';

export default Plyr;
<commit_msg>Remove babel-polyfill in favour of core-js<commit_after>// ==========================================================================
// Plyr Polyfilled Build
// plyr.js v3.4.3
// https://github.com/sampotts/plyr
// License: The MIT License (MIT)
// ==========================================================================

import 'custom-event-polyfill';
import 'url-polyfill';
import Plyr from './plyr';

export default Plyr;
<|endoftext|>


<commit_before>// Modules
var http = require('http'),
    urllib = require('url'),
    RPCHandler = require('jsonrpc').RPCHandler,
    scheduler = require('./schedulerRpcWrapper'),
    handleStaticFile = require('./staticFileHandler').handle;

// Configuration
var cfg = require('config')('ControlNode', {
  port: 46212,
  address: "",
  jsonRpcPath: "/jsonrpc",
  debugRpc: false
});

// Local variables
var version = "0.1.6",
    versionString = ["ControlNode=", version, ";NodeJS=", process.version].join("");

var schedulerWrapper = new scheduler.Wrapper(cfg.mongodbAddress);

var handleHttpRequest = function(req, res) {
    if(req.method == "POST"){
        // Define whether this is JSON request.
        if (urllib.parse(req.url).pathname == cfg.jsonRpcPath) {
            new RPCHandler(req, res, schedulerWrapper, cfg.debugRpc);
        } else {
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end('Unknown path!\n');
        }
    } else if (urllib.parse(req.url).pathname === "/status") {
        res.writeHead(200, {'Content-Type': 'application/json'});
        res.end(JSON.stringify(schedulerWrapper.getStatus(), null, 4))
    } else {
        handleStaticFile('../http_server/web', '', req, res);
    }
};

// Run server.
http.createServer(handleHttpRequest).listen(cfg.port, cfg.address);
console.log([versionString, ";at http://", cfg.address, ':', cfg.port].join(''));
<commit_msg>Simple logging to control node.<commit_after>// Modules
var http = require('http'),
    urllib = require('url'),
    RPCHandler = require('jsonrpc').RPCHandler,
    scheduler = require('./schedulerRpcWrapper'),
    handleStaticFile = require('./staticFileHandler').handle,
    fs = require('fs');

// Configuration
var cfg = require('config')('ControlNode', {
  port: 46212,
  address: "",
  jsonRpcPath: "/jsonrpc",
  debugRpc: false,
  statusPath: "/status",
  webuiFilesPath: "../http_server/web",
  webuiPathRoot: ""
});

// Local variables
var version = "0.1.6",
    versionString = ["ControlNode=", version, ";NodeJS=", process.version].join(""),
    logfile = fs.createWriteStream("/var/log/kts46/ControlNode.log", {flags:"w+"});

var log = function(code, path){
    logfile.write([Date(), code, path + "\n"].join("\t"));
};

var schedulerWrapper = new scheduler.Wrapper(cfg.mongodbAddress);

var handleHttpRequest = function(req, res) {
    var path = urllib.parse(req.url).pathname;
    if(req.method == "POST"){
        // Define whether this is JSON request.
        if (path == cfg.jsonRpcPath) {
            log(200, path);
            new RPCHandler(req, res, schedulerWrapper, cfg.debugRpc);
        } else {
            log(404, path);
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end('Unknown path!\n');
        }
    } else if (path === cfg.statusPath) {
        log(200, path);
        res.writeHead(200, {'Content-Type': 'application/json'});
        res.end(JSON.stringify(schedulerWrapper.getStatus(), null, 4))
    } else {
        log(200, path);
        handleStaticFile(cfg.webuiFilesPath, cfg.webuiPathRoot, req, res);
    }
};

// Run server.
http.createServer(handleHttpRequest).listen(cfg.port, cfg.address);
console.log(["Starting ", versionString, " at http://", cfg.address, ':', cfg.port].join(''));
logfile.write([Date()])
<|endoftext|>


<commit_before>'use strict';
if (!module.parent) console.error('Please don\'t call me directly.I am just the main app\'s minion.') || process.process.exit(1);
require('nodestrum');
var Class = require('sji'),
    util = require('util'),
    cloudinary = require('cloudinary'),
    _ = require('lodash');

var Widget = exports.Widget = Class.extend({
    init: function (options) {
        this.options = options;
        this.limit = this.options.limit || 50;
        this.validators = options.validators || [];
        this.attrs = options.attrs || {};
        this.attrs.class = [];
        this.attrs.required = options.required || false;
        _.assign(options.attr, this.attrs);
        this.attrs.class.push(this.attrs.required ? 'required' : 'optional');
        this.data = options.data || {};
        this.name = '';
        this.value = null;
        this.head = [];
    },

    pre_render: function (callback) {
        callback();
    },

    render: function () {
        return this;
    },

    render_attributes: function (res) {
        var self = this;
        var longString = _(this.data).pairs()
            .forEach(function(pair) {pair[0] = 'data-' + pair[0];})
            .concat(_.pairs(this.attrs), [['name', self.name], ['id','id_' + self.name]])
            .map(function (pair) {
                pair[1] = Array.isArray(pair[1]) ? pair[1].join(' ') : pair[1];
                return util.format('%s="%s"', escapeHTMLComponent(pair[0]), escapeHTMLComponent(pair[1]));
            })
            .join(' ');

        res.write(' ' + longString + ' ');
        return this;
    }
});

exports.InputWidget = Widget.extend({
    init: function (type, options) {
        options.attrs.type = options.attrs.type || type;
        this._super(options);
    },
    render: function (res) {
        res.write('\n<input' + (this.value ? ' value="' + escapeHTMLComponent(this.value) + '"' : '') );
        this.render_attributes(res);
        res.write(' />\n');
        return this;
    }
});

exports.HiddenWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('hidden', options);
    }
});

exports.TextWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('text', options);
    }
});

exports.PasswordWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('password', options);
    }
});

exports.TextAreaWidget = Widget.extend({
    render: function (res) {
        res.write('\n<textarea ');
        this.render_attributes(res);
        res.write(' >\n');
        res.write(escapeHTMLComponent(this.value));
        res.write('\n</textarea>\n');
        return this;
    }
});

exports.RichTextAreaWidget = exports.TextAreaWidget.extend({
    init: function (options) {
        this._super(options);
        this.attrs.class.push('ckeditor');
    },
    render: function (res) {
        res.write('\n
\n');
        this._super(res);
        res.write('\n
\n');
    }
});

exports.DateWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('text', options);
        this.attrs.class.push('nf_datepicker');
    },
    render: function (res) {
        res.write('\n
\n');
        this._super(res);
        res.write('\n\n');
        res.write('\n
\n');
    }
});

exports.DateTimeWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('text', options);
        this.attrs['data-format'] = "yyyy-MM-dd hh:mm";
    },
    render: function (res) {
        var widget_id =  'datetimepicker' + this.name;
        res.write('\n
\n');
        this._super(res);
        res.write('\n\n\n\n
\n');
        var script = "$('#" + widget_id + "').datetimepicker();";
        res.write('');
    }
});

exports.TimeWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('time', options);
        this.attrs.class.push('nf_timepicker');
    },
    render: function (res) {
        res.write('\n
\n');
        this._super(res);
        res.write('\n\n');
        res.write('\n
\n');
    }
});

exports.NumberWidget = exports.InputWidget.extend({
    init: function (options) {
        options = options || {};
        options.attrs = options.attrs || {};
        if ('min' in options) {
            options.attrs.min = options.min;
        }
        if ('max' in options) {
            options.attrs.max = options.max;
        }
        options.attrs.step = options.attrs.step || options.step || 'any';
        this._super('number', options);
    }
});

exports.CheckboxWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('checkbox', options);
    },
    render: function (res) {
        var old_value = this.value;
        if (this.value) {
            this.attrs['checked'] = 'checked';
        }
        this.value = 'on';
        var ret = this._super(res);
        this.value = old_value;
        return ret;

    }
});

exports.ChoicesWidget = Widget.extend({
    init: function (options) {
        this.choices = options.choices || [];
        this._super(options);
    },

    isSelected: function (choice) {
        if (Array.isArray(this.value)) {
            return Boolean(~this.value.indexOf(choice));
        } else {
            return choice == this.value;
        }
    },

    prepareValues: function () {
        if (!this.names) {
            this.names = new Array(this.choices.length);
            for (var i = 0; i < this.choices.length; i++) {
                if (typeof(this.choices[i]) == 'object') {
                    this.names[i] = this.choices[i][1];
                    this.choices[i] = this.choices[i][0];
                } else {
                    this.names[i] = this.choices[i];
                }
            }
        }
    },

    render: function (res) {
        this.prepareValues();
        res.write('\n<select ');
        this.render_attributes(res);
        res.write(' >\n');
        var found_selected = false;
        if (!this.attrs.required) {
            var selected = this.value ? '' : 'selected="selected" ';
            if (selected) {
                found_selected = true;
            }
            res.write('\n<option ' + selected + 'value=""> ... </option>\n');
        }
        for (var i = 0; i < this.choices.length; i++) {
            var selected2 = this.isSelected(this.choices[i]) ? 'selected="selected" ' : '';
            if (selected2) {
                found_selected = true;
            }
            res.write('\n<option ' + selected2 + 'value="' + this.choices[i] + '">' + this.names[i] + '</option>\n');
        }
        if (!found_selected && this.value) {
            res.write('\n<option selected="selected" value="' + this.value + '">Current</option>\n');
        }
        res.write('\n</select>\n');
        return this;
    }
});

exports.RefWidget = exports.ChoicesWidget.extend({
    init: function (options) {
        this.ref = options.ref;
        if (!this.ref) {
            throw new TypeError('model was not provided');
        }
        this._super(options);
        this.refForm = options.refForm || options.ref.label;
        this.attrs['data-ref'] = this.refForm;
    },
    pre_render: function (callback) {
        var self = this;
        var base = self._super;
        this.ref.find({}).limit(self.limit).exec(function (err, objects) {
            if (err) throw callback(err);
            self.choices = [];
            for (var i = 0; i < objects.length; i++) {
                var label = objects[i].name || objects[i].title || objects[i].toString;
                if (typeof(label) == 'function') {
                    label = label.call(objects[i]);
                }
                self.choices.push([objects[i].id, label]);
            }
            base.call(self, callback);
        });
    }
});

exports.ListWidget = Widget.extend({
    init: function (options) {
        this._super(options);
    },
    render: function (res, render_template, render_item) {
        res.write('\n
\n
\n');
        render_template(res);
        res.write('\n
\n
\n');
        this.value = this.value || [];
        for (var i = 0; i < this.value.length; i++) {
            res.write('\n
\n');
            render_item(res, i);
            res.write('\n
\n');
        }
        res.write('\n
\n
\n');
    }
});

exports.FileWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('file', options);
    },
    render: function (res) {
        this._super(res);
        if (this.value && this.value.path) {
            res.write('\n\n' + this.value.path + '\n<input type="checkbox" name="' + this.name + '_clear" value="Clear" />\n Clear\n');
        }
    }
});

exports.FilepickerWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('filepicker', options);
        this.attrs.class.push('_filepicker');
        //noinspection JSUnresolvedVariable
        this.attrs['data-fp-apikey'] = process.env.FILEPICKER_API_KEY;
    },

    render: function (res) {
        var raw_value = this.value || '';
        this.value = JSON.stringify(raw_value);
        this._super(res);
        if (raw_value && raw_value.url) {
            res.write(util.format('%s\n', raw_value.url, raw_value.filename));
            res.write(util.format('<input type="checkbox" name="%s_clear" value="false" /> Clear\n', this.name));
        }
    }
});

exports.PictureWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('file', options);
    },

    render: function (res) {
        if (this.value && this.value.url) {
            var thumbnail_url = cloudinary.image(
                this.value.public_id, {
                    format: 'png',
                    width: 150,
                    height: 110,
                    crop: 'fill',
                    alt: this.value.original_name,
                    title: this.value.original_name
                }
            );
            res.write(util.format('%s\n', this.value.url, thumbnail_url));
            res.write(util.format('<input type="checkbox" name="%s_clear" value="false" />\nClear\n', this.name));
        }
        res.write(util.format('<input type="hidden" name="%s" value="%s" />\n', this.name, encodeJSONHTML(this.value)));
        this._super(res);
    },
    render_attributes: function (res) {
        this.name += "_file";
        this._super(res)
    }
});

exports.MapWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('hidden', options);
        this.attrs.class.push('nf_mapview');
        this.head.push('');
    },

    render: function (res) {
        res.write('
');
        //noinspection JSUnresolvedVariable
        if (!this.options.hide_address) {
            var address = this.value ? this.value.address : '';
            this.attrs['address_field'] = 'id_' + this.name + '_address';
            res.write('\n<input type="text" name="' + this.name + '_address" id="id_' + this.name + '_address" value="' + address + '" />\n');
        }
        var old_value = this.value;
        var lat = this.value && this.value.geometry ? this.value.geometry.lat : '';
        var lng = this.value && this.value.geometry ? this.value.geometry.lng : '';
        this.value = lat + ',' + lng;
        this._super(res);
        this.value = old_value;
        res.write('\n
\n');
    }
});

exports.ComboBoxWidget = exports.ChoicesWidget.extend({
    init: function (options) {
        this._super(options);
        this.attrs.class.push('nf_comb');
    }
});

exports.AutocompleteWidget = exports.TextWidget.extend({
    init: function (options) {
        if (!options.url) throw new Error('must specify url');
        if (!options.ref) throw new TypeError('model was not provided');

        this._super(options);
        this.attrs.class.push('nf_ref');
        this.attrs['data-ref'] = options.refForm || options.ref.label;

        this.data = this.data || {};
        this.data.url = this.data.url || options.url;
        this.data.data = this.data.data || options.data;

        this.ref = options.ref;
    },

    pre_render: function (callback) {
        var self = this;
        var _super = this._super.bind(self);
        var id = this.value;
        self.data['name'] = id || '';
        if (!id) return _super(callback);
        var query = Array.isArray(id) ? this.ref.find().where('_id').in(id) : this.ref.findById(id);
        return query.exec(function (err, doc) {
            if (err) return callback(err);
            if (doc) {
                self.doc = doc;
            }
            return _super(callback);
        });
    },

    render: function (res) {
        var self = this;
        var name = self.value;
        if (self.doc) {
            if (Array.isArray(self.doc)) {
                var elem = self.doc.filter(function (d) {return d.id == self.value;})[0];
                name = (elem || '').toString()
            } else {
                name = self.doc.toString();
            }
        }
        self.data.name = name || '';
        self._super(res);
    }
});
<commit_msg>handle HTML5 attributes differently<commit_after>'use strict';
if (!module.parent) console.error('Please don\'t call me directly.I am just the main app\'s minion.') || process.process.exit(1);
require('nodestrum');
var Class = require('sji'),
    util = require('util'),
    cloudinary = require('cloudinary'),
    _ = require('lodash');

var Widget = exports.Widget = Class.extend({
    init: function (options) {
        this.options = options;
        this.limit = this.options.limit || 50;
        this.validators = options.validators || [];
        this.attrs = options.attrs || {};
        this.attrs.class = [];
        this.attrs.required = options.required;
        _.assign(options.attr, this.attrs);
        this.attrs.class.push(this.attrs.required ? 'required' : 'optional');
        this.data = options.data || {};
        this.name = '';
        this.value = null;
        this.head = [];
    },

    pre_render: function (callback) {
        callback();
    },

    render: function () {
        return this;
    },

    render_attributes: function (res) {
        var self = this;
        var longString = _(this.data).pairs()
            .forEach(function(pair) {pair[0] = 'data-' + pair[0];})
            .concat(_.pairs(this.attrs), [['name', self.name], ['id','id_' + self.name]])
            .map(function (pair) {
                var name = pair[0];
                var value = pair[1];
                if (name in {required:1, selected:1, hidden:1} && !value) return '';
                value = Object.isArray(value) ? value.join(' ') : value;
                return util.format('%s="%s"', escapeHTMLComponent(name), escapeHTMLComponent(value));
            })
            .join(' ');

        res.write(' ' + longString + ' ');
        return this;
    }
});

exports.InputWidget = Widget.extend({
    init: function (type, options) {
        options.attrs.type = options.attrs.type || type;
        this._super(options);
    },
    render: function (res) {
        res.write('\n<input' + (this.value ? ' value="' + escapeHTMLComponent(this.value) + '"' : '') );
        this.render_attributes(res);
        res.write(' />\n');
        return this;
    }
});

exports.HiddenWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('hidden', options);
    }
});

exports.TextWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('text', options);
    }
});

exports.PasswordWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('password', options);
    }
});

exports.TextAreaWidget = Widget.extend({
    render: function (res) {
        res.write('\n<textarea ');
        this.render_attributes(res);
        res.write(' >\n');
        res.write(escapeHTMLComponent(this.value));
        res.write('\n</textarea>\n');
        return this;
    }
});

exports.RichTextAreaWidget = exports.TextAreaWidget.extend({
    init: function (options) {
        this._super(options);
        this.attrs.class.push('ckeditor');
    },
    render: function (res) {
        res.write('\n
\n');
        this._super(res);
        res.write('\n
\n');
    }
});

exports.DateWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('text', options);
        this.attrs.class.push('nf_datepicker');
    },
    render: function (res) {
        res.write('\n
\n');
        this._super(res);
        res.write('\n\n');
        res.write('\n
\n');
    }
});

exports.DateTimeWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('text', options);
        this.attrs['data-format'] = "yyyy-MM-dd hh:mm";
    },
    render: function (res) {
        var widget_id =  'datetimepicker' + this.name;
        res.write('\n
\n');
        this._super(res);
        res.write('\n\n\n\n
\n');
        var script = "$('#" + widget_id + "').datetimepicker();";
        res.write('');
    }
});

exports.TimeWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('time', options);
        this.attrs.class.push('nf_timepicker');
    },
    render: function (res) {
        res.write('\n
\n');
        this._super(res);
        res.write('\n\n');
        res.write('\n
\n');
    }
});

exports.NumberWidget = exports.InputWidget.extend({
    init: function (options) {
        options = options || {};
        options.attrs = options.attrs || {};
        if ('min' in options) {
            options.attrs.min = options.min;
        }
        if ('max' in options) {
            options.attrs.max = options.max;
        }
        options.attrs.step = options.attrs.step || options.step || 'any';
        this._super('number', options);
    }
});

exports.CheckboxWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('checkbox', options);
    },
    render: function (res) {
        var old_value = this.value;
        if (this.value) {
            this.attrs['checked'] = 'checked';
        }
        this.value = 'on';
        var ret = this._super(res);
        this.value = old_value;
        return ret;

    }
});

exports.ChoicesWidget = Widget.extend({
    init: function (options) {
        this.choices = options.choices || [];
        this._super(options);
    },

    isSelected: function (choice) {
        if (Array.isArray(this.value)) {
            return Boolean(~this.value.indexOf(choice));
        } else {
            return choice == this.value;
        }
    },

    prepareValues: function () {
        if (!this.names) {
            this.names = new Array(this.choices.length);
            for (var i = 0; i < this.choices.length; i++) {
                if (typeof(this.choices[i]) == 'object') {
                    this.names[i] = this.choices[i][1];
                    this.choices[i] = this.choices[i][0];
                } else {
                    this.names[i] = this.choices[i];
                }
            }
        }
    },

    render: function (res) {
        this.prepareValues();
        res.write('\n<select ');
        this.render_attributes(res);
        res.write(' >\n');
        var found_selected = false;
        if (!this.attrs.required) {
            var selected = this.value ? '' : 'selected="selected" ';
            if (selected) {
                found_selected = true;
            }
            res.write('\n<option ' + selected + 'value=""> ... </option>\n');
        }
        for (var i = 0; i < this.choices.length; i++) {
            var selected2 = this.isSelected(this.choices[i]) ? 'selected="selected" ' : '';
            if (selected2) {
                found_selected = true;
            }
            res.write('\n<option ' + selected2 + 'value="' + this.choices[i] + '">' + this.names[i] + '</option>\n');
        }
        if (!found_selected && this.value) {
            res.write('\n<option selected="selected" value="' + this.value + '">Current</option>\n');
        }
        res.write('\n</select>\n');
        return this;
    }
});

exports.RefWidget = exports.ChoicesWidget.extend({
    init: function (options) {
        this.ref = options.ref;
        if (!this.ref) {
            throw new TypeError('model was not provided');
        }
        this._super(options);
        this.refForm = options.refForm || options.ref.label;
        this.attrs['data-ref'] = this.refForm;
    },
    pre_render: function (callback) {
        var self = this;
        var base = self._super;
        this.ref.find({}).limit(self.limit).exec(function (err, objects) {
            if (err) throw callback(err);
            self.choices = [];
            for (var i = 0; i < objects.length; i++) {
                var label = objects[i].name || objects[i].title || objects[i].toString;
                if (typeof(label) == 'function') {
                    label = label.call(objects[i]);
                }
                self.choices.push([objects[i].id, label]);
            }
            base.call(self, callback);
        });
    }
});

exports.ListWidget = Widget.extend({
    init: function (options) {
        this._super(options);
    },
    render: function (res, render_template, render_item) {
        res.write('\n
\n
\n');
        render_template(res);
        res.write('\n
\n
\n');
        this.value = this.value || [];
        for (var i = 0; i < this.value.length; i++) {
            res.write('\n
\n');
            render_item(res, i);
            res.write('\n
\n');
        }
        res.write('\n
\n
\n');
    }
});

exports.FileWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('file', options);
    },
    render: function (res) {
        this._super(res);
        if (this.value && this.value.path) {
            res.write('\n\n' + this.value.path + '\n<input type="checkbox" name="' + this.name + '_clear" value="Clear" />\n Clear\n');
        }
    }
});

exports.FilepickerWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('filepicker', options);
        this.attrs.class.push('_filepicker');
        //noinspection JSUnresolvedVariable
        this.attrs['data-fp-apikey'] = process.env.FILEPICKER_API_KEY;
    },

    render: function (res) {
        var raw_value = this.value || '';
        this.value = JSON.stringify(raw_value);
        this._super(res);
        if (raw_value && raw_value.url) {
            res.write(util.format('%s\n', raw_value.url, raw_value.filename));
            res.write(util.format('<input type="checkbox" name="%s_clear" value="false" /> Clear\n', this.name));
        }
    }
});

exports.PictureWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('file', options);
    },

    render: function (res) {
        if (this.value && this.value.url) {
            var thumbnail_url = cloudinary.image(
                this.value.public_id, {
                    format: 'png',
                    width: 150,
                    height: 110,
                    crop: 'fill',
                    alt: this.value.original_name,
                    title: this.value.original_name
                }
            );
            res.write(util.format('%s\n', this.value.url, thumbnail_url));
            res.write(util.format('<input type="checkbox" name="%s_clear" value="false" />\nClear\n', this.name));
        }
        res.write(util.format('<input type="hidden" name="%s" value="%s" />\n', this.name, encodeJSONHTML(this.value)));
        this._super(res);
    },
    render_attributes: function (res) {
        this.name += "_file";
        this._super(res)
    }
});

exports.MapWidget = exports.InputWidget.extend({
    init: function (options) {
        this._super('hidden', options);
        this.attrs.class.push('nf_mapview');
        this.head.push('');
    },

    render: function (res) {
        res.write('
');
        //noinspection JSUnresolvedVariable
        if (!this.options.hide_address) {
            var address = this.value ? this.value.address : '';
            this.attrs['address_field'] = 'id_' + this.name + '_address';
            res.write('\n<input type="text" name="' + this.name + '_address" id="id_' + this.name + '_address" value="' + address + '" />\n');
        }
        var old_value = this.value;
        var lat = this.value && this.value.geometry ? this.value.geometry.lat : '';
        var lng = this.value && this.value.geometry ? this.value.geometry.lng : '';
        this.value = lat + ',' + lng;
        this._super(res);
        this.value = old_value;
        res.write('\n
\n');
    }
});

exports.ComboBoxWidget = exports.ChoicesWidget.extend({
    init: function (options) {
        this._super(options);
        this.attrs.class.push('nf_comb');
    }
});

exports.AutocompleteWidget = exports.TextWidget.extend({
    init: function (options) {
        if (!options.url) throw new Error('must specify url');
        if (!options.ref) throw new TypeError('model was not provided');

        this._super(options);
        this.attrs.class.push('nf_ref');
        this.attrs['data-ref'] = options.refForm || options.ref.label;

        this.data = this.data || {};
        this.data.url = this.data.url || options.url;
        this.data.data = this.data.data || options.data;

        this.ref = options.ref;
    },

    pre_render: function (callback) {
        var self = this;
        var _super = this._super.bind(self);
        var id = this.value;
        self.data['name'] = id || '';
        if (!id) return _super(callback);
        var query = Array.isArray(id) ? this.ref.find().where('_id').in(id) : this.ref.findById(id);
        return query.exec(function (err, doc) {
            if (err) return callback(err);
            if (doc) {
                self.doc = doc;
            }
            return _super(callback);
        });
    },

    render: function (res) {
        var self = this;
        var name = self.value;
        if (self.doc) {
            if (Array.isArray(self.doc)) {
                var elem = self.doc.filter(function (d) {return d.id == self.value;})[0];
                name = (elem || '').toString()
            } else {
                name = self.doc.toString();
            }
        }
        self.data.name = name || '';
        self._super(res);
    }
});
<|endoftext|>


<commit_before>export const GraphStatsServices = [

'$http', '$rootScope',

class GraphStatsServices {
  constructor($http, $rootScope){
    this.$http = $http;
    this.$rootScope = $rootScope;
  }

  setCurrentData(recentGames, allstats){

    //Set data for graphs
    let recentPercentComplete = [];
    let totalWords = [];

    for(let x = 0; x<recentGames.length; x++){
      recentPercentComplete.push(recentGames[x].percentCompleted);
    }

    for(let x = 0; x<allstats.length; x++){
      totalWords.push(allstats[x].totalWordsCompleted);
    }

    return this.graphData(recentPercentComplete), this.totalWordsGraph(totalWords);
  }

  graphData(recentPercentComplete){

    var margin = {top: 30, right: 20, bottom: 30, left: 50},
    width = 600 - margin.left - margin.right,
    height = 270 - margin.top - margin.bottom;

    // Set the ranges
    var x = d3.scaleLinear().range([0, width]);
    var y = d3.scaleLinear().range([height, 0]);

    if(recentPercentComplete){
      // var p = d3.select(".totalGamesPlayed").selectAll("p")

      // Define the axes
      var xAxis = d3.axisBottom().scale(x)
        .ticks(5);

      var yAxis = d3.axisLeft().scale(y)
        .ticks(5);

      // Define the line
      var valueline = d3.line()
        .x(function(d, i) {return  x(i)})
        .y(function(d) { return y(d); });

      // Adds the svg canvas
      var svg = d3.select(".totalGamesPlayed")
        .append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
        .append("g")
          .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

     // Scale the range of the data
     x.domain(d3.extent(recentPercentComplete, function(d, i) { return i; }));
     y.domain([0, d3.max(recentPercentComplete, function(d) { return d; })]);

     // Add the valueline path.
     svg.append("path")
      .attr("class", "line")
      .attr("d", valueline(recentPercentComplete))
      .style('stroke-width', '3')
      .style('stroke', '#feedba')

     // Add the X Axis
     svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

     // Add the Y Axis
      var gy = svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);

      gy.selectAll('g').filter((d) => {
        return d;
      })
        .classed('minor', true)

      gy.selectAll('text')
        .attr('x',-20)
        .attr('y', 0)
        .style('fill', '#cc33ff')

      gy.selectAll('path')
        .style('stroke', '#cc33ff')
        .style('stroke-width', '2')

    }

  }

  totalWordsGraph(totalWords){
    console.log('totalWords: ', totalWords);

    var svg = d3.select(".totalWords"),
  margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 40
  },
  width = +svg.attr("width") - margin.left - margin.right,
  height = +svg.attr("height") - margin.top - margin.bottom;

// Set the ranges
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
  y = d3.scaleLinear().rangeRound([height, 0]);

var g = svg.append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

if (totalWords) {

  x.domain(totalWords.map(function(d, i) {

    console.log('i.freq: ', i);
    return i;
  }));
  y.domain([0, d3.max(totalWords, function(d) {

    console.log('d.totalWords: ', d);
    return d;
  })]);

  g.append("g")
    .attr("class", "axis axis--x")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

  g.append("g")
    .attr("class", "axis axis--y")
    .call(d3.axisLeft(y).ticks(20))
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 7)
    .attr("dy","0.71em")
    .attr("text-anchor", "end")
    .text("Frequency");

  g.selectAll(".bar")
    .data(totalWords)
    .enter().append("rect")
    .attr("class", "bar")
    .attr("x", function(d, i) {
      //54
      console.log('i: ', i);
      console.log('x(i): ', x(i));
      return x(i);
    })
    .attr("y", function(d) {

      console.log('d: ', d);
      console.log('y(d): ', y(d));
      return y(d);
    })
    .attr("width", x.bandwidth())
    .attr("height", function(d) {

      console.log('heigh - y(d): ', height + y(d));
      return height - y(d);
    });
}
  }
}];

<commit_msg>removes unwanted code from graph_state_service<commit_after>export const GraphStatsServices = [

'$http', '$rootScope',

class GraphStatsServices {
  constructor($http, $rootScope){
    this.$http = $http;
    this.$rootScope = $rootScope;
  }

  setCurrentData(recentGames, allstats){

    //Set data for graphs
    let recentPercentComplete = [];
    let totalWords = [];

    for(let x = 0; x<recentGames.length; x++){
      recentPercentComplete.push(recentGames[x].percentCompleted);
    }

    for(let x = 0; x<allstats.length; x++){
      totalWords.push(allstats[x].totalWordsCompleted);
    }

    return this.graphData(recentPercentComplete), this.totalWordsGraph(totalWords);
  }

  graphData(recentPercentComplete){

    var margin = {top: 30, right: 20, bottom: 30, left: 50},
    width = 600 - margin.left - margin.right,
    height = 270 - margin.top - margin.bottom;

    // Set the ranges
    var x = d3.scaleLinear().range([0, width]);
    var y = d3.scaleLinear().range([height, 0]);

    if(recentPercentComplete){
      // var p = d3.select(".totalGamesPlayed").selectAll("p")

      // Define the axes
      var xAxis = d3.axisBottom().scale(x)
        .ticks(5);

      var yAxis = d3.axisLeft().scale(y)
        .ticks(5);

      // Define the line
      var valueline = d3.line()
        .x(function(d, i) {return  x(i)})
        .y(function(d) { return y(d); });

      // Adds the svg canvas
      var svg = d3.select(".totalGamesPlayed")
        .append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
        .append("g")
          .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

     // Scale the range of the data
     x.domain(d3.extent(recentPercentComplete, function(d, i) { return i; }));
     y.domain([0, d3.max(recentPercentComplete, function(d) { return d; })]);

     // Add the valueline path.
     svg.append("path")
      .attr("class", "line")
      .attr("d", valueline(recentPercentComplete))
      .style('stroke-width', '3')
      .style('stroke', '#feedba')

     // Add the X Axis
     svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

     // Add the Y Axis
      svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);

    }

  }

  totalWordsGraph(totalWords){
    console.log('totalWords: ', totalWords);

    var svg = d3.select(".totalWords"),
  margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 40
  },
  width = +svg.attr("width") - margin.left - margin.right,
  height = +svg.attr("height") - margin.top - margin.bottom;

// Set the ranges
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
  y = d3.scaleLinear().rangeRound([height, 0]);

var g = svg.append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

if (totalWords) {

  x.domain(totalWords.map(function(d, i) {

    console.log('i.freq: ', i);
    return i;
  }));
  y.domain([0, d3.max(totalWords, function(d) {

    console.log('d.totalWords: ', d);
    return d;
  })]);

  g.append("g")
    .attr("class", "axis axis--x")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x));

  g.append("g")
    .attr("class", "axis axis--y")
    .call(d3.axisLeft(y).ticks(20))
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 7)
    .attr("dy","0.71em")
    .attr("text-anchor", "end")
    .text("Frequency");

  g.selectAll(".bar")
    .data(totalWords)
    .enter().append("rect")
    .attr("class", "bar")
    .attr("x", function(d, i) {
      //54
      console.log('i: ', i);
      console.log('x(i): ', x(i));
      return x(i);
    })
    .attr("y", function(d) {

      console.log('d: ', d);
      console.log('y(d): ', y(d));
      return y(d);
    })
    .attr("width", x.bandwidth())
    .attr("height", function(d) {

      console.log('heigh - y(d): ', height + y(d));
      return height - y(d);
    });
}
  }
}];

<|endoftext|>