<commit_before>dojo.provide("dojox.json.ref");
dojo.require("dojo.date.stamp");

dojox.json.ref = {
	// summary:
	// 		Adds advanced JSON {de}serialization capabilities to the base json library.
	// 		This enhances the capabilities of dojo.toJson and dojo.fromJson,
	// 		adding referencing support, date handling, and other extra format handling.
	// 		On parsing, references are resolved. When references are made to
	// 		ids/objects that have been loaded yet, the loader function will be set to
	// 		_loadObject to denote a lazy loading (not loaded yet) object.

	resolveJson: function(/*Object*/ root,/*Object?*/ args){
		// summary:
		// 		Indexes and resolves references in the JSON object.
		// description:
		// 		A JSON Schema object that can be used to advise the handling of the JSON (defining ids, date properties, urls, etc)
		//
		// root:
		//		The root object of the object graph to be processed
		// args:
		//		Object with additional arguments:
		//
		// The *index* parameter.
		//		This is the index object (map) to use to store an index of all the objects.
		// 		If you are using inter-message referencing, you must provide the same object for each call.
		// The *defaultId* parameter.
		//		This is the default id to use for the root object (if it doesn't define it's own id)
		//	The *idPrefix* parameter.
		//		This the prefix to use for the ids as they enter the index. This allows multiple tables
		// 		to use ids (that might otherwise collide) that enter the same global index.
		// 		idPrefix should be in the form "/Service/".  For example,
		//		if the idPrefix is "/Table/", and object is encountered {id:"4",...}, this would go in the
		//		index as "/Table/4".
		//	The *idAttribute* parameter.
		//		This indicates what property is the identity property. This defaults to "id"
		//	The *assignAbsoluteIds* parameter.
		//		This indicates that the resolveJson should assign absolute ids (__id) as the objects are being parsed.
		//
		// The *schemas* parameter
		//		This provides a map of schemas, from which prototypes can be retrieved
		// The *loader* parameter
		//		This is a function that is called added to the reference objects that can't be resolved (lazy objects)
		// return:
		//		An object, the result of the processing
		args = args || {};
		var idAttribute = args.idAttribute || 'id';
		var refAttribute = this.refAttribute;
		var prefix = args.idPrefix || '';
		var assignAbsoluteIds = args.assignAbsoluteIds;
		var index = args.index || {}; // create an index if one doesn't exist
		var timeStamps = args.timeStamps;
		var ref,reWalk=[];
		var pathResolveRegex = /^(.*\/)?(\w+:\/\/)|[^\/\.]+\/\.\.\/|^.*\/(\/)/;
		var addProp = this._addProp;
		var F = function(){};
		function walk(it, stop, defaultId, needsPrefix, schema, defaultObject){
			// this walks the new graph, resolving references and making other changes
		 	var update, val, id = idAttribute in it ? it[idAttribute] : defaultId;
		 	if(idAttribute in it || ((id !== undefined) && needsPrefix)){
		 		id = (prefix + id).replace(pathResolveRegex,'$2$3');
		 	}
		 	var target = defaultObject || it;
			if(id !== undefined){ // if there is an id available...
				if(assignAbsoluteIds){
					it.__id = id;
				}
				if(args.schemas && (!(it instanceof Array)) && // won't try on arrays to do prototypes, plus it messes with queries
		 					(val = id.match(/^(.+\/)[^\.\[]*$/))){ // if it has a direct table id (no paths)
		 			schema = args.schemas[val[1]];
				}
				// if the id already exists in the system, we should use the existing object, and just
				// update it... as long as the object is compatible
				if(index[id] && ((it instanceof Array) == (index[id] instanceof Array))){
					target = index[id];
					delete target.$ref; // remove this artifact
					delete target._loadObject;
					update = true;
				}else{
				 	var proto = schema && schema.prototype; // and if has a prototype
					if(proto){
						// if the schema defines a prototype, that needs to be the prototype of the object
						F.prototype = proto;
						target = new F();
					}
				}
				index[id] = target; // add the prefix, set _id, and index it
				if(timeStamps){
					timeStamps[id] = args.time;
				}
			}
			var properties = schema && schema.properties;
			var length = it.length;
			for(var i in it){
				if(i==length){
					break;
				}
				if(it.hasOwnProperty(i)){
					val=it[i];
					var propertyDefinition = properties && properties[i];
					if(propertyDefinition && propertyDefinition.format == 'date-time' && typeof val == 'string'){
						val = dojo.date.stamp.fromISOString(val);
					}else if((typeof val =='object') && val && !(val instanceof Date) && i != '__parent'){
						ref=val[refAttribute];
						if(!ref || !val.__parent){
							val.__parent = it;
						}
						if(ref){ // a reference was found
							// make sure it is a safe reference
							delete it[i];// remove the property so it doesn't resolve to itself in the case of id.propertyName lazy values
							var path = ref.toString().replace(/(#)([^\.\[])/,'$1.$2').match(/(^([^\[]*\/)?[^#\.\[]*)#?([\.\[].*)?/); // divide along the path
							if((ref = (path[1]=='$' || path[1]=='this' || path[1]=='') ? root : index[(prefix + path[1]).replace(pathResolveRegex,'$2$3')])){  // a $ indicates to start with the root, otherwise start with an id
								// if there is a path, we will iterate through the path references
								if(path[3]){
									path[3].replace(/(\[([^\]]+)\])|(\.?([^\.\[]+))/g,function(t,a,b,c,d){
										ref = ref && ref[b ? b.replace(/[\"\'\\]/,'') : d];
									});
								}
							}
							if(ref){
								val = ref;
							}else{
								// otherwise, no starting point was found (id not found), if stop is set, it does not exist, we have
								// unloaded reference, if stop is not set, it may be in a part of the graph not walked yet,
								// we will wait for the second loop
								if(!stop){
									var rewalking;
									if(!rewalking){
										reWalk.push(target); // we need to rewalk it to resolve references
									}
									rewalking = true; // we only want to add it once
									val = walk(val, false, val[refAttribute], true, propertyDefinition);
									// create a lazy loaded object
									val._loadObject = args.loader;
								}
							}
						}else{
							if(!stop){ // if we are in stop, that means we are in the second loop, and we only need to check this current one,
								// further walking may lead down circular loops
								val = walk(
									val,
									reWalk==it,
									id === undefined ? undefined : addProp(id, i), // the default id to use
									false,
									propertyDefinition,
									// if we have an existing object child, we want to
									// maintain it's identity, so we pass it as the default object
									target != it && typeof target[i] == 'object' && target[i]
								);
							}
						}
					}
					it[i] = val;
					if(target!=it && !target.__isDirty){// do updates if we are updating an existing object and it's not dirty
						var old = target[i];
						target[i] = val; // only update if it changed
						if(update && val !== old && // see if it is different
								!target._loadObject && // no updates if we are just lazy loading
								!(i.charAt(0) == '_' && i.charAt(1) == '_') && i != "$ref" &&
								!(val instanceof Date && old instanceof Date && val.getTime() == old.getTime()) && // make sure it isn't an identical date
								!(typeof val == 'function' && typeof old == 'function' && val.toString() == old.toString()) && // make sure it isn't an indentical function
								index.onUpdate){
							index.onUpdate(target,i,old,val); // call the listener for each update
						}
					}
				}
			}

			if(update && (idAttribute in it)){
				// this means we are updating with a full representation of the object, we need to remove deleted
				for(i in target){
					if(!target.__isDirty && target.hasOwnProperty(i) && !it.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && !(target instanceof Array && isNaN(i))){
						if(index.onUpdate && i != "_loadObject" && i != "_idAttr"){
							index.onUpdate(target,i,target[i],undefined); // call the listener for each update
						}
						delete target[i];
						while(target instanceof Array && target.length && target[target.length-1] === undefined){
							// shorten the target if necessary
							target.length--;
						}
					}
				}
			}else{
				if(index.onLoad){
					index.onLoad(target);
				}
			}
			return target;
		}
		if(root && typeof root == 'object'){
			root = walk(root,false,args.defaultId, true); // do the main walk through
			walk(reWalk,false); // re walk any parts that were not able to resolve references on the first round
		}
		return root;
	},

	fromJson: function(/*String*/ str,/*Object?*/ args){
	// summary:
	// 		evaluates the passed string-form of a JSON object.
	//
	// str:
	//		a string literal of a JSON item, for instance:
	//			'{ "foo": [ "bar", 1, { "baz": "thud" } ] }'
	// args: See resolveJson
	//
	// return:
	//		An object, the result of the evaluation
		function ref(target){ // support call styles references as well
			var refObject = {};
			refObject[this.refAttribute] = target;
			return refObject;
		}
		try{
			var root = eval('(' + str + ')'); // do the eval
		}catch(e){
			throw new SyntaxError("Invalid JSON string: " + e.message + " parsing: "+ str);
		}
		if(root){
			return this.resolveJson(root, args);
		}
		return root;
	},

	toJson: function(/*Object*/ it, /*Boolean?*/ prettyPrint, /*Object?*/ idPrefix, /*Object?*/ indexSubObjects){
		// summary:
		//		Create a JSON serialization of an object.
		//		This has support for referencing, including circular references, duplicate references, and out-of-message references
		// 		id and path-based referencing is supported as well and is based on http://www.json.com/2007/10/19/json-referencing-proposal-and-library/.
		//
		// it:
		//		an object to be serialized.
		//
		// prettyPrint:
		//		if true, we indent objects and arrays to make the output prettier.
		//		The variable dojo.toJsonIndentStr is used as the indent string
		//		-- to use something other than the default (tab),
		//		change that variable before calling dojo.toJson().
		//
		// idPrefix: The prefix that has been used for the absolute ids
		//
		// return:
		//		a String representing the serialized version of the passed object.
		var useRefs = this._useRefs;
		var addProp = this._addProp;
		var refAttribute = this.refAttribute;
		idPrefix = idPrefix || ''; // the id prefix for this context
		var paths={};
		var generated = {};
		function serialize(it,path,_indentStr){
			if(typeof it == 'object' && it){
				var value;
				if(it instanceof Date){ // properly serialize dates
					return '"' + dojo.date.stamp.toISOString(it,{zulu:true}) + '"';
				}
				var id = it.__id;
				if(id){ // we found an identifiable object, we will just serialize a reference to it... unless it is the root
					if(path != '#' && ((useRefs && !id.match(/#/)) || paths[id])){
						var ref = id;
						if(id.charAt(0)!='#'){
							if(it.__clientId == id){
								ref = "cid:" + id;
							}else if(id.substring(0, idPrefix.length) == idPrefix){ // see if the reference is in the current context
								// a reference with a prefix matching the current context, the prefix should be removed
								ref = id.substring(idPrefix.length);
							}else{
								// a reference to a different context, assume relative url based referencing
								ref = id;
							}
						}
						var refObject = {};
						refObject[refAttribute] = ref;
						return serialize(refObject,'#');
					}
					path = id;
				}else{
					it.__id = path; // we will create path ids for other objects in case they are circular
					generated[path] = it;
				}
				paths[path] = it;// save it here so they can be deleted at the end
				_indentStr = _indentStr || "";
				var nextIndent = prettyPrint ? _indentStr + dojo.toJsonIndentStr : "";
				var newLine = prettyPrint ? "\n" : "";
				var sep = prettyPrint ? " " : "";

				if(it instanceof Array){
					var res = dojo.map(it, function(obj,i){
						var val = serialize(obj, addProp(path, i), nextIndent);
						if(typeof val != "string"){
							val = "undefined";
						}
						return newLine + nextIndent + val;
					});
					return "[" + res.join("," + sep) + newLine + _indentStr + "]";
				}

				var output = [];
				for(var i in it){
					if(it.hasOwnProperty(i)){
						var keyStr;
						if(typeof i == "number"){
							keyStr = '"' + i + '"';
						}else if(typeof i == "string" && (i.charAt(0) != '_' || i.charAt(1) != '_')){
							// we don't serialize our internal properties __id and __clientId
							keyStr = dojo._escapeString(i);
						}else{
							// skip non-string or number keys
							continue;
						}
						var val = serialize(it[i],addProp(path, i),nextIndent);
						if(typeof val != "string"){
							// skip non-serializable values
							continue;
						}
						output.push(newLine + nextIndent + keyStr + ":" + sep + val);
					}
				}
				return "{" + output.join("," + sep) + newLine + _indentStr + "}";
			}else if(typeof it == "function" && dojox.json.ref.serializeFunctions){
				return it.toString();
			}

			return dojo.toJson(it); // use the default serializer for primitives
		}
		var json = serialize(it,'#','');
		if(!indexSubObjects){
			for(var i in generated)  {// cleanup the temporary path-generated ids
				delete generated[i].__id;
			}
		}
		return json;
	},
	_addProp: function(id, prop){
		return id + (id.match(/#/) ? id.length == 1 ? '' : '.' : '#') + prop;
	},
	//	refAttribute: String
	//		This indicates what property is the reference property. This acts like the idAttribute
	// 		except that this is used to indicate the current object is a reference or only partially
	// 		loaded. This defaults to "$ref".
	refAttribute: "$ref",
	_useRefs: false,
	serializeFunctions: false
}
<commit_msg>Look through super-schemas for date-time information, fixes #8960<commit_after>dojo.provide("dojox.json.ref");
dojo.require("dojo.date.stamp");

dojox.json.ref = {
	// summary:
	// 		Adds advanced JSON {de}serialization capabilities to the base json library.
	// 		This enhances the capabilities of dojo.toJson and dojo.fromJson,
	// 		adding referencing support, date handling, and other extra format handling.
	// 		On parsing, references are resolved. When references are made to
	// 		ids/objects that have been loaded yet, the loader function will be set to
	// 		_loadObject to denote a lazy loading (not loaded yet) object.

	resolveJson: function(/*Object*/ root,/*Object?*/ args){
		// summary:
		// 		Indexes and resolves references in the JSON object.
		// description:
		// 		A JSON Schema object that can be used to advise the handling of the JSON (defining ids, date properties, urls, etc)
		//
		// root:
		//		The root object of the object graph to be processed
		// args:
		//		Object with additional arguments:
		//
		// The *index* parameter.
		//		This is the index object (map) to use to store an index of all the objects.
		// 		If you are using inter-message referencing, you must provide the same object for each call.
		// The *defaultId* parameter.
		//		This is the default id to use for the root object (if it doesn't define it's own id)
		//	The *idPrefix* parameter.
		//		This the prefix to use for the ids as they enter the index. This allows multiple tables
		// 		to use ids (that might otherwise collide) that enter the same global index.
		// 		idPrefix should be in the form "/Service/".  For example,
		//		if the idPrefix is "/Table/", and object is encountered {id:"4",...}, this would go in the
		//		index as "/Table/4".
		//	The *idAttribute* parameter.
		//		This indicates what property is the identity property. This defaults to "id"
		//	The *assignAbsoluteIds* parameter.
		//		This indicates that the resolveJson should assign absolute ids (__id) as the objects are being parsed.
		//
		// The *schemas* parameter
		//		This provides a map of schemas, from which prototypes can be retrieved
		// The *loader* parameter
		//		This is a function that is called added to the reference objects that can't be resolved (lazy objects)
		// return:
		//		An object, the result of the processing
		args = args || {};
		var idAttribute = args.idAttribute || 'id';
		var refAttribute = this.refAttribute;
		var prefix = args.idPrefix || '';
		var assignAbsoluteIds = args.assignAbsoluteIds;
		var index = args.index || {}; // create an index if one doesn't exist
		var timeStamps = args.timeStamps;
		var i,ref,reWalk=[];
		var pathResolveRegex = /^(.*\/)?(\w+:\/\/)|[^\/\.]+\/\.\.\/|^.*\/(\/)/;
		var addProp = this._addProp;
		var F = function(){};
		function walk(it, stop, defaultId, needsPrefix, schema, defaultObject){
			// this walks the new graph, resolving references and making other changes
		 	var update, val, id = idAttribute in it ? it[idAttribute] : defaultId;
		 	if(idAttribute in it || ((id !== undefined) && needsPrefix)){
		 		id = (prefix + id).replace(pathResolveRegex,'$2$3');
		 	}
		 	var target = defaultObject || it;
			if(id !== undefined){ // if there is an id available...
				if(assignAbsoluteIds){
					it.__id = id;
				}
				if(args.schemas && (!(it instanceof Array)) && // won't try on arrays to do prototypes, plus it messes with queries
		 					(val = id.match(/^(.+\/)[^\.\[]*$/))){ // if it has a direct table id (no paths)
		 			schema = args.schemas[val[1]];
				}
				// if the id already exists in the system, we should use the existing object, and just
				// update it... as long as the object is compatible
				if(index[id] && ((it instanceof Array) == (index[id] instanceof Array))){
					target = index[id];
					delete target.$ref; // remove this artifact
					delete target._loadObject;
					update = true;
				}else{
				 	var proto = schema && schema.prototype; // and if has a prototype
					if(proto){
						// if the schema defines a prototype, that needs to be the prototype of the object
						F.prototype = proto;
						target = new F();
					}
				}
				index[id] = target; // add the prefix, set _id, and index it
				if(timeStamps){
					timeStamps[id] = args.time;
				}
			}
			while(schema){
				var properties = schema.properties;
				if(properties){
					for(i in it){
						var propertyDefinition = properties[i];
						if(propertyDefinition && propertyDefinition.format == 'date-time' && typeof it[i] == 'string'){
							it[i] = dojo.date.stamp.fromISOString(it[i]);
						}
					}
				}
				schema = schema["extends"];
			}
			var length = it.length;
			for(i in it){
				if(i==length){
					break;
				}
				if(it.hasOwnProperty(i)){
					val=it[i];
					if((typeof val =='object') && val && !(val instanceof Date) && i != '__parent'){
						ref=val[refAttribute];
						if(!ref || !val.__parent){
							val.__parent = it;
						}
						if(ref){ // a reference was found
							// make sure it is a safe reference
							delete it[i];// remove the property so it doesn't resolve to itself in the case of id.propertyName lazy values
							var path = ref.toString().replace(/(#)([^\.\[])/,'$1.$2').match(/(^([^\[]*\/)?[^#\.\[]*)#?([\.\[].*)?/); // divide along the path
							if((ref = (path[1]=='$' || path[1]=='this' || path[1]=='') ? root : index[(prefix + path[1]).replace(pathResolveRegex,'$2$3')])){  // a $ indicates to start with the root, otherwise start with an id
								// if there is a path, we will iterate through the path references
								if(path[3]){
									path[3].replace(/(\[([^\]]+)\])|(\.?([^\.\[]+))/g,function(t,a,b,c,d){
										ref = ref && ref[b ? b.replace(/[\"\'\\]/,'') : d];
									});
								}
							}
							if(ref){
								val = ref;
							}else{
								// otherwise, no starting point was found (id not found), if stop is set, it does not exist, we have
								// unloaded reference, if stop is not set, it may be in a part of the graph not walked yet,
								// we will wait for the second loop
								if(!stop){
									var rewalking;
									if(!rewalking){
										reWalk.push(target); // we need to rewalk it to resolve references
									}
									rewalking = true; // we only want to add it once
									val = walk(val, false, val[refAttribute], true, propertyDefinition);
									// create a lazy loaded object
									val._loadObject = args.loader;
								}
							}
						}else{
							if(!stop){ // if we are in stop, that means we are in the second loop, and we only need to check this current one,
								// further walking may lead down circular loops
								val = walk(
									val,
									reWalk==it,
									id === undefined ? undefined : addProp(id, i), // the default id to use
									false,
									propertyDefinition,
									// if we have an existing object child, we want to
									// maintain it's identity, so we pass it as the default object
									target != it && typeof target[i] == 'object' && target[i]
								);
							}
						}
					}
					it[i] = val;
					if(target!=it && !target.__isDirty){// do updates if we are updating an existing object and it's not dirty
						var old = target[i];
						target[i] = val; // only update if it changed
						if(update && val !== old && // see if it is different
								!target._loadObject && // no updates if we are just lazy loading
								!(i.charAt(0) == '_' && i.charAt(1) == '_') && i != "$ref" &&
								!(val instanceof Date && old instanceof Date && val.getTime() == old.getTime()) && // make sure it isn't an identical date
								!(typeof val == 'function' && typeof old == 'function' && val.toString() == old.toString()) && // make sure it isn't an indentical function
								index.onUpdate){
							index.onUpdate(target,i,old,val); // call the listener for each update
						}
					}
				}
			}

			if(update && (idAttribute in it)){
				// this means we are updating with a full representation of the object, we need to remove deleted
				for(i in target){
					if(!target.__isDirty && target.hasOwnProperty(i) && !it.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && !(target instanceof Array && isNaN(i))){
						if(index.onUpdate && i != "_loadObject" && i != "_idAttr"){
							index.onUpdate(target,i,target[i],undefined); // call the listener for each update
						}
						delete target[i];
						while(target instanceof Array && target.length && target[target.length-1] === undefined){
							// shorten the target if necessary
							target.length--;
						}
					}
				}
			}else{
				if(index.onLoad){
					index.onLoad(target);
				}
			}
			return target;
		}
		if(root && typeof root == 'object'){
			root = walk(root,false,args.defaultId, true); // do the main walk through
			walk(reWalk,false); // re walk any parts that were not able to resolve references on the first round
		}
		return root;
	},

	fromJson: function(/*String*/ str,/*Object?*/ args){
	// summary:
	// 		evaluates the passed string-form of a JSON object.
	//
	// str:
	//		a string literal of a JSON item, for instance:
	//			'{ "foo": [ "bar", 1, { "baz": "thud" } ] }'
	// args: See resolveJson
	//
	// return:
	//		An object, the result of the evaluation
		function ref(target){ // support call styles references as well
			var refObject = {};
			refObject[this.refAttribute] = target;
			return refObject;
		}
		try{
			var root = eval('(' + str + ')'); // do the eval
		}catch(e){
			throw new SyntaxError("Invalid JSON string: " + e.message + " parsing: "+ str);
		}
		if(root){
			return this.resolveJson(root, args);
		}
		return root;
	},

	toJson: function(/*Object*/ it, /*Boolean?*/ prettyPrint, /*Object?*/ idPrefix, /*Object?*/ indexSubObjects){
		// summary:
		//		Create a JSON serialization of an object.
		//		This has support for referencing, including circular references, duplicate references, and out-of-message references
		// 		id and path-based referencing is supported as well and is based on http://www.json.com/2007/10/19/json-referencing-proposal-and-library/.
		//
		// it:
		//		an object to be serialized.
		//
		// prettyPrint:
		//		if true, we indent objects and arrays to make the output prettier.
		//		The variable dojo.toJsonIndentStr is used as the indent string
		//		-- to use something other than the default (tab),
		//		change that variable before calling dojo.toJson().
		//
		// idPrefix: The prefix that has been used for the absolute ids
		//
		// return:
		//		a String representing the serialized version of the passed object.
		var useRefs = this._useRefs;
		var addProp = this._addProp;
		var refAttribute = this.refAttribute;
		idPrefix = idPrefix || ''; // the id prefix for this context
		var paths={};
		var generated = {};
		function serialize(it,path,_indentStr){
			if(typeof it == 'object' && it){
				var value;
				if(it instanceof Date){ // properly serialize dates
					return '"' + dojo.date.stamp.toISOString(it,{zulu:true}) + '"';
				}
				var id = it.__id;
				if(id){ // we found an identifiable object, we will just serialize a reference to it... unless it is the root
					if(path != '#' && ((useRefs && !id.match(/#/)) || paths[id])){
						var ref = id;
						if(id.charAt(0)!='#'){
							if(it.__clientId == id){
								ref = "cid:" + id;
							}else if(id.substring(0, idPrefix.length) == idPrefix){ // see if the reference is in the current context
								// a reference with a prefix matching the current context, the prefix should be removed
								ref = id.substring(idPrefix.length);
							}else{
								// a reference to a different context, assume relative url based referencing
								ref = id;
							}
						}
						var refObject = {};
						refObject[refAttribute] = ref;
						return serialize(refObject,'#');
					}
					path = id;
				}else{
					it.__id = path; // we will create path ids for other objects in case they are circular
					generated[path] = it;
				}
				paths[path] = it;// save it here so they can be deleted at the end
				_indentStr = _indentStr || "";
				var nextIndent = prettyPrint ? _indentStr + dojo.toJsonIndentStr : "";
				var newLine = prettyPrint ? "\n" : "";
				var sep = prettyPrint ? " " : "";

				if(it instanceof Array){
					var res = dojo.map(it, function(obj,i){
						var val = serialize(obj, addProp(path, i), nextIndent);
						if(typeof val != "string"){
							val = "undefined";
						}
						return newLine + nextIndent + val;
					});
					return "[" + res.join("," + sep) + newLine + _indentStr + "]";
				}

				var output = [];
				for(var i in it){
					if(it.hasOwnProperty(i)){
						var keyStr;
						if(typeof i == "number"){
							keyStr = '"' + i + '"';
						}else if(typeof i == "string" && (i.charAt(0) != '_' || i.charAt(1) != '_')){
							// we don't serialize our internal properties __id and __clientId
							keyStr = dojo._escapeString(i);
						}else{
							// skip non-string or number keys
							continue;
						}
						var val = serialize(it[i],addProp(path, i),nextIndent);
						if(typeof val != "string"){
							// skip non-serializable values
							continue;
						}
						output.push(newLine + nextIndent + keyStr + ":" + sep + val);
					}
				}
				return "{" + output.join("," + sep) + newLine + _indentStr + "}";
			}else if(typeof it == "function" && dojox.json.ref.serializeFunctions){
				return it.toString();
			}

			return dojo.toJson(it); // use the default serializer for primitives
		}
		var json = serialize(it,'#','');
		if(!indexSubObjects){
			for(var i in generated)  {// cleanup the temporary path-generated ids
				delete generated[i].__id;
			}
		}
		return json;
	},
	_addProp: function(id, prop){
		return id + (id.match(/#/) ? id.length == 1 ? '' : '.' : '#') + prop;
	},
	//	refAttribute: String
	//		This indicates what property is the reference property. This acts like the idAttribute
	// 		except that this is used to indicate the current object is a reference or only partially
	// 		loaded. This defaults to "$ref".
	refAttribute: "$ref",
	_useRefs: false,
	serializeFunctions: false
}
<|endoftext|>


<commit_before>angular.module('starter.directives', [])

.directive('cardboardGl', ['Planets', function(Planets) {
  return {
    'restrict': 'E',
    'scope': {
      'stereoEffect': '=',
      'landscapeMode': '=',
      'moveStarFighter': '='
    },
    'link': link
  };
  function link($scope, $element, $attr) {
    var scene, camera, renderer, element, container, effect, controls, ambientLight, clock;
    var StarFighter, StarFighterGhost, StarFighterPosition = {x: 2500, y: 1500, z: 0}, StarFighterEngineLight, StarFighterOrientation = [];
    init();
    function init() {
      // Main Scene
      scene = new THREE.Scene();
      camera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.001, Planets.Properties.Starfield.Size + 100);
      camera.position.set(StarFighterPosition.x, StarFighterPosition.y, StarFighterPosition.z);
      scene.add(camera);
      renderer = new THREE.WebGLRenderer({antialias: true});
      element = renderer.domElement;
      container = $element[0];
      container.appendChild(element);
      effect = new THREE.StereoEffect(renderer);
      // Controls
      controls = new THREE.OrbitControls(camera, element);
      controls.target.set(camera.position.x + 0.15, camera.position.y, camera.position.z);
      controls.noPan = true;
      controls.noZoom = true;
      function setOrientationControls(e) {
        if (!e.alpha) {
          return;
        }
        controls = new THREE.DeviceOrientationControls(camera, true);
        controls.connect();
        controls.update();
        element.addEventListener('click', fullscreen, false);
        window.removeEventListener('deviceorientation', setOrientationControls, true);
      };
      window.addEventListener('deviceorientation', setOrientationControls, true);
      // Lighting
      ambientLight = new THREE.AmbientLight(0xffffff);
      scene.add(ambientLight);
      // Loaders
      var manager = new THREE.LoadingManager();
      manager.onProgress = function(item, loaded, total){
        console.log("StarFighter - Loading: " + loaded + "/" + total);
        if(loaded == total) {
          console.log("StarFighter - Load Finished");
        }
      };
      var Loader_OBJ = new THREE.OBJLoader(manager);
      // Textures
      Planets.Loader.load(Planets.baseURL + 'galaxy_starfield.png', function(texture) {
        Planets.Starfield.Sphere.material = new THREE.MeshPhongMaterial({map: texture, side: THREE.BackSide});
        scene.add(Planets.Starfield.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'sunmap.jpg', function(texture) {
        Planets.Sun.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Sun.Sphere);
        var Sunlight = new THREE.PointLight(0x999900, 1, 16500);
        Planets.Sun.Sphere.add(Sunlight);
      });
      Planets.Loader.load(Planets.baseURL + 'mercurymap.jpg', function(texture) {
        Planets.Mercury.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Mercury.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'venusmap.jpg', function(texture) {
        Planets.Venus.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Venus.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'earthmap1k.jpg', function(texture) {
        Planets.Earth.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Earth.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'moonmap1k.jpg', function(texture) {
        Planets.EarthMoon.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.EarthMoon.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'marsmap1k.jpg', function(texture) {
        Planets.Mars.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Mars.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'jupitermap.jpg', function(texture) {
        Planets.Jupiter.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Jupiter.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'saturnmap.jpg', function(texture) {
        Planets.Saturn.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Saturn.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'saturn-rings.png', function(texture) {
        Planets.Saturn.Ring.material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: 0.6});
        Planets.Saturn.Ring.rotation.x = -45 * (Math.PI / 180);
        scene.add(Planets.Saturn.Ring);
      });
      Planets.Loader.load(Planets.baseURL + 'uranusmap.jpg', function(texture) {
        Planets.Uranus.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Uranus.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'saturn-rings.png', function(texture) {
        Planets.Uranus.Ring.material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: 0.6});
        Planets.Uranus.Ring.rotation.x = -80 * (Math.PI / 180);
        scene.add(Planets.Uranus.Ring);
      });
      Planets.Loader.load(Planets.baseURL + 'neptunemap.jpg', function(texture) {
        Planets.Neptune.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Neptune.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'plutomap1k.jpg', function(texture) {
        Planets.Pluto.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Pluto.Sphere);
      });
      scene.add(
        Planets.Mercury.Orbit,
        Planets.Venus.Orbit,
        Planets.Earth.Orbit,
        Planets.EarthMoon.Orbit,
        Planets.Mars.Orbit,
        Planets.Jupiter.Orbit,
        Planets.Saturn.Orbit,
        Planets.Uranus.Orbit,
        Planets.Neptune.Orbit,
        Planets.Pluto.Orbit
      );
      StarFighter = new THREE.Mesh();
      StarFighterGhost = new THREE.Mesh();
      Loader_OBJ.load( 'obj/StarFighter/StarFighter.obj', function (object) {
        object.traverse(function (child) {
          if (child instanceof THREE.Mesh) {
            child.material.map = THREE.ImageUtils.loadTexture('obj/StarFighter/StarFighter.png');
          }
        });
        object.rotation.y = -90 * (Math.PI / 180);
        object.rotation.z = -0 * (Math.PI / 180);
        object.position.set(0, -2, -17);
        object.scale.x = 0.01;
        object.scale.y = 0.01;
        object.scale.z = 0.01;
        StarFighterGhost = object.clone();
        object.scale.x = 0.3;
        object.scale.y = 0.3;
        object.scale.z = 0.3;
        StarFighter = object.clone();
        camera.add(
          StarFighter,
          StarFighterGhost
        );
        StarFighterEngineLight = new THREE.PointLight(0x00ccff, 1, 20);
        StarFighterEngineLight.position.set(0, 0, 0);
        camera.add(StarFighterEngineLight);
      });
      clock = new THREE.Clock();
      animate();
    };
    function animate() {
      var elapsedSeconds = clock.getElapsedTime();
      requestAnimationFrame(animate);
      update(clock.getDelta());
      render(clock.getDelta());
    };
    function update(dt) {
      resize();
      camera.updateProjectionMatrix();
      controls.update(dt);
    };
    var t = 100 * Math.random();
    function render(dt) {
      // Magic Zone Start
      t += 0.001;
      // Planets Rotation
      Planets.Sun.Sphere.rotation.y += Planets.Properties.Sun.Speed.Rotation;
      Planets.Mercury.Sphere.rotation.y += Planets.Properties.Mercury.Speed.Rotation;
      Planets.Venus.Sphere.rotation.y -= Planets.Properties.Venus.Speed.Rotation;
      Planets.Earth.Sphere.rotation.y += Planets.Properties.Earth.Speed.Rotation;
      Planets.EarthMoon.Sphere.rotation.y += Planets.Properties.EarthMoon.Speed.Rotation;
      Planets.Mars.Sphere.rotation.y += Planets.Properties.Mars.Speed.Rotation;
      Planets.Jupiter.Sphere.rotation.y += Planets.Properties.Jupiter.Speed.Rotation;
      Planets.Saturn.Sphere.rotation.y += Planets.Properties.Saturn.Speed.Rotation;
      Planets.Uranus.Sphere.rotation.y -= Planets.Properties.Uranus.Speed.Rotation;
      Planets.Neptune.Sphere.rotation.y += Planets.Properties.Neptune.Speed.Rotation;
      Planets.Pluto.Sphere.rotation.y -= Planets.Properties.Pluto.Speed.Rotation;
      // Planets Translation
      Planets.Sun.Sphere.position.x = Planets.Properties.Sun.Distance * Math.cos(t * Planets.Properties.Sun.Speed.Translation);
      Planets.Sun.Sphere.position.z = Planets.Properties.Sun.Distance * Math.sin(t * Planets.Properties.Sun.Speed.Translation);
      Planets.Mercury.Sphere.position.x = Planets.Properties.Mercury.Distance * Math.cos(t * Planets.Properties.Mercury.Speed.Translation);
      Planets.Mercury.Sphere.position.z = Planets.Properties.Mercury.Distance * Math.sin(t * Planets.Properties.Mercury.Speed.Translation);
      Planets.Venus.Sphere.position.x = Planets.Properties.Venus.Distance * Math.cos(t * Planets.Properties.Venus.Speed.Translation);
      Planets.Venus.Sphere.position.z = Planets.Properties.Venus.Distance * Math.sin(t * Planets.Properties.Venus.Speed.Translation);
      Planets.Earth.Sphere.position.x = Planets.Properties.Earth.Distance * Math.cos(t * Planets.Properties.Earth.Speed.Translation);
      Planets.Earth.Sphere.position.z = Planets.Properties.Earth.Distance * Math.sin(t * Planets.Properties.Earth.Speed.Translation);
      Planets.EarthMoon.Orbit.position.x = Planets.Earth.Sphere.position.x;
      Planets.EarthMoon.Orbit.position.z = Planets.Earth.Sphere.position.z;
      Planets.EarthMoon.Sphere.position.x = Planets.EarthMoon.Orbit.position.x + (Planets.Properties.EarthMoon.Distance * Math.cos(t * Planets.Properties.EarthMoon.Speed.Translation));
      Planets.EarthMoon.Sphere.position.z = Planets.EarthMoon.Orbit.position.z + (Planets.Properties.EarthMoon.Distance * Math.sin(t * Planets.Properties.EarthMoon.Speed.Translation));
      Planets.Mars.Sphere.position.x = Planets.Properties.Mars.Distance * Math.cos(t * Planets.Properties.Mars.Speed.Translation);
      Planets.Mars.Sphere.position.z = Planets.Properties.Mars.Distance * Math.sin(t * Planets.Properties.Mars.Speed.Translation);
      Planets.Jupiter.Sphere.position.x = Planets.Properties.Jupiter.Distance * Math.cos(t * Planets.Properties.Jupiter.Speed.Translation);
      Planets.Jupiter.Sphere.position.z = Planets.Properties.Jupiter.Distance * Math.sin(t * Planets.Properties.Jupiter.Speed.Translation);
      Planets.Saturn.Sphere.position.x = Planets.Properties.Saturn.Distance * Math.cos(t * Planets.Properties.Saturn.Speed.Translation);
      Planets.Saturn.Sphere.position.z = Planets.Properties.Saturn.Distance * Math.sin(t * Planets.Properties.Saturn.Speed.Translation);
      Planets.Saturn.Ring.position.x = Planets.Saturn.Sphere.position.x;
      Planets.Saturn.Ring.position.z = Planets.Saturn.Sphere.position.z;
      Planets.Uranus.Sphere.position.x = Planets.Properties.Uranus.Distance * Math.cos(t * Planets.Properties.Uranus.Speed.Translation);
      Planets.Uranus.Sphere.position.z = Planets.Properties.Uranus.Distance * Math.sin(t * Planets.Properties.Uranus.Speed.Translation);
      Planets.Uranus.Ring.position.x = Planets.Uranus.Sphere.position.x;
      Planets.Uranus.Ring.position.z = Planets.Uranus.Sphere.position.z;
      Planets.Neptune.Sphere.position.x = Planets.Properties.Neptune.Distance * Math.cos(t * Planets.Properties.Neptune.Speed.Translation);
      Planets.Neptune.Sphere.position.z = Planets.Properties.Neptune.Distance * Math.sin(t * Planets.Properties.Neptune.Speed.Translation);
      Planets.Pluto.Sphere.position.x = Planets.Properties.Pluto.Distance * Math.cos(t * Planets.Properties.Pluto.Speed.Translation);
      Planets.Pluto.Sphere.position.z = Planets.Properties.Pluto.Distance * Math.sin(t * Planets.Properties.Pluto.Speed.Translation);
      // StarFighter Orientation
      var cameraDirection = camera.getWorldDirection();
      var StarFighterGhostDirection = StarFighterGhost.getWorldDirection();
      if(StarFighterOrientation.length < 20) {
        StarFighterOrientation.push(StarFighterGhostDirection);
      } else {
        StarFighter.rotation.x = StarFighterOrientation[0].x;
        StarFighter.rotation.y = StarFighterOrientation[0].y;
        StarFighter.rotation.z = StarFighterOrientation[0].z;
        var NewStarFighterOrientation = [];
        for(i = 1; i < 20; i++) {
          NewStarFighterOrientation.push(StarFighterOrientation[i]);
        }
        StarFighterOrientation = NewStarFighterOrientation;
        StarFighterOrientation.push(StarFighterGhostDirection);
      }
      // Camera Movement
      if($scope.moveStarFighter == true) {
        var FighterSpeed = 1.5;
        StarFighterPosition.x += cameraDirection.x * FighterSpeed;
        StarFighterPosition.y += cameraDirection.y * FighterSpeed;
        StarFighterPosition.z += cameraDirection.z * FighterSpeed;
        camera.position.set(StarFighterPosition.x, StarFighterPosition.y, StarFighterPosition.z);
      }
      // Magic Zone End
      if($scope.stereoEffect == true) {
        effect.render(scene, camera);
      } else {
        renderer.render(scene, camera);
      }
    };
    function resize() {
      var width = container.offsetWidth;
      var height = container.offsetHeight;
      camera.aspect = width / height;
      camera.updateProjectionMatrix();
      if($scope.stereoEffect == true) {
        effect.setSize(width, height);
      } else {
        renderer.setSize(width, height);
      }
    };
    function fullscreen() {
      if (container.requestFullscreen) {
        container.requestFullscreen();
      } else if (container.msRequestFullscreen) {
        container.msRequestFullscreen();
      } else if (container.mozRequestFullScreen) {
        container.mozRequestFullScreen();
      } else if (container.webkitRequestFullscreen) {
        container.webkitRequestFullscreen();
      }
    };
  };
}])
<commit_msg>Moved camera direction to the movement zone<commit_after>angular.module('starter.directives', [])

.directive('cardboardGl', ['Planets', function(Planets) {
  return {
    'restrict': 'E',
    'scope': {
      'stereoEffect': '=',
      'landscapeMode': '=',
      'moveStarFighter': '='
    },
    'link': link
  };
  function link($scope, $element, $attr) {
    var scene, camera, renderer, element, container, effect, controls, ambientLight, clock;
    var StarFighter, StarFighterGhost, StarFighterPosition = {x: 2500, y: 1500, z: 0}, StarFighterEngineLight, StarFighterOrientation = [];
    init();
    function init() {
      // Main Scene
      scene = new THREE.Scene();
      camera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.001, Planets.Properties.Starfield.Size + 100);
      camera.position.set(StarFighterPosition.x, StarFighterPosition.y, StarFighterPosition.z);
      scene.add(camera);
      renderer = new THREE.WebGLRenderer({antialias: true});
      element = renderer.domElement;
      container = $element[0];
      container.appendChild(element);
      effect = new THREE.StereoEffect(renderer);
      // Controls
      controls = new THREE.OrbitControls(camera, element);
      controls.target.set(camera.position.x + 0.15, camera.position.y, camera.position.z);
      controls.noPan = true;
      controls.noZoom = true;
      function setOrientationControls(e) {
        if (!e.alpha) {
          return;
        }
        controls = new THREE.DeviceOrientationControls(camera, true);
        controls.connect();
        controls.update();
        element.addEventListener('click', fullscreen, false);
        window.removeEventListener('deviceorientation', setOrientationControls, true);
      };
      window.addEventListener('deviceorientation', setOrientationControls, true);
      // Lighting
      ambientLight = new THREE.AmbientLight(0xffffff);
      scene.add(ambientLight);
      // Loaders
      var manager = new THREE.LoadingManager();
      manager.onProgress = function(item, loaded, total){
        console.log("StarFighter - Loading: " + loaded + "/" + total);
        if(loaded == total) {
          console.log("StarFighter - Load Finished");
        }
      };
      var Loader_OBJ = new THREE.OBJLoader(manager);
      // Textures
      Planets.Loader.load(Planets.baseURL + 'galaxy_starfield.png', function(texture) {
        Planets.Starfield.Sphere.material = new THREE.MeshPhongMaterial({map: texture, side: THREE.BackSide});
        scene.add(Planets.Starfield.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'sunmap.jpg', function(texture) {
        Planets.Sun.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Sun.Sphere);
        var Sunlight = new THREE.PointLight(0x999900, 1, 16500);
        Planets.Sun.Sphere.add(Sunlight);
      });
      Planets.Loader.load(Planets.baseURL + 'mercurymap.jpg', function(texture) {
        Planets.Mercury.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Mercury.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'venusmap.jpg', function(texture) {
        Planets.Venus.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Venus.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'earthmap1k.jpg', function(texture) {
        Planets.Earth.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Earth.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'moonmap1k.jpg', function(texture) {
        Planets.EarthMoon.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.EarthMoon.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'marsmap1k.jpg', function(texture) {
        Planets.Mars.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Mars.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'jupitermap.jpg', function(texture) {
        Planets.Jupiter.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Jupiter.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'saturnmap.jpg', function(texture) {
        Planets.Saturn.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Saturn.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'saturn-rings.png', function(texture) {
        Planets.Saturn.Ring.material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: 0.6});
        Planets.Saturn.Ring.rotation.x = -45 * (Math.PI / 180);
        scene.add(Planets.Saturn.Ring);
      });
      Planets.Loader.load(Planets.baseURL + 'uranusmap.jpg', function(texture) {
        Planets.Uranus.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Uranus.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'saturn-rings.png', function(texture) {
        Planets.Uranus.Ring.material = new THREE.MeshBasicMaterial({map: texture, side: THREE.DoubleSide, transparent: true, opacity: 0.6});
        Planets.Uranus.Ring.rotation.x = -80 * (Math.PI / 180);
        scene.add(Planets.Uranus.Ring);
      });
      Planets.Loader.load(Planets.baseURL + 'neptunemap.jpg', function(texture) {
        Planets.Neptune.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Neptune.Sphere);
      });
      Planets.Loader.load(Planets.baseURL + 'plutomap1k.jpg', function(texture) {
        Planets.Pluto.Sphere.material = new THREE.MeshPhongMaterial({map: texture});
        scene.add(Planets.Pluto.Sphere);
      });
      scene.add(
        Planets.Mercury.Orbit,
        Planets.Venus.Orbit,
        Planets.Earth.Orbit,
        Planets.EarthMoon.Orbit,
        Planets.Mars.Orbit,
        Planets.Jupiter.Orbit,
        Planets.Saturn.Orbit,
        Planets.Uranus.Orbit,
        Planets.Neptune.Orbit,
        Planets.Pluto.Orbit
      );
      StarFighter = new THREE.Mesh();
      StarFighterGhost = new THREE.Mesh();
      Loader_OBJ.load( 'obj/StarFighter/StarFighter.obj', function (object) {
        object.traverse(function (child) {
          if (child instanceof THREE.Mesh) {
            child.material.map = THREE.ImageUtils.loadTexture('obj/StarFighter/StarFighter.png');
          }
        });
        object.rotation.y = -90 * (Math.PI / 180);
        object.rotation.z = -0 * (Math.PI / 180);
        object.position.set(0, -2, -17);
        object.scale.x = 0.01;
        object.scale.y = 0.01;
        object.scale.z = 0.01;
        StarFighterGhost = object.clone();
        object.scale.x = 0.3;
        object.scale.y = 0.3;
        object.scale.z = 0.3;
        StarFighter = object.clone();
        camera.add(
          StarFighter,
          StarFighterGhost
        );
        StarFighterEngineLight = new THREE.PointLight(0x00ccff, 1, 20);
        StarFighterEngineLight.position.set(0, 0, 0);
        camera.add(StarFighterEngineLight);
      });
      clock = new THREE.Clock();
      animate();
    };
    function animate() {
      var elapsedSeconds = clock.getElapsedTime();
      requestAnimationFrame(animate);
      update(clock.getDelta());
      render(clock.getDelta());
    };
    function update(dt) {
      resize();
      camera.updateProjectionMatrix();
      controls.update(dt);
    };
    var t = 100 * Math.random();
    function render(dt) {
      // Magic Zone Start
      t += 0.001;
      // Planets Rotation
      Planets.Sun.Sphere.rotation.y += Planets.Properties.Sun.Speed.Rotation;
      Planets.Mercury.Sphere.rotation.y += Planets.Properties.Mercury.Speed.Rotation;
      Planets.Venus.Sphere.rotation.y -= Planets.Properties.Venus.Speed.Rotation;
      Planets.Earth.Sphere.rotation.y += Planets.Properties.Earth.Speed.Rotation;
      Planets.EarthMoon.Sphere.rotation.y += Planets.Properties.EarthMoon.Speed.Rotation;
      Planets.Mars.Sphere.rotation.y += Planets.Properties.Mars.Speed.Rotation;
      Planets.Jupiter.Sphere.rotation.y += Planets.Properties.Jupiter.Speed.Rotation;
      Planets.Saturn.Sphere.rotation.y += Planets.Properties.Saturn.Speed.Rotation;
      Planets.Uranus.Sphere.rotation.y -= Planets.Properties.Uranus.Speed.Rotation;
      Planets.Neptune.Sphere.rotation.y += Planets.Properties.Neptune.Speed.Rotation;
      Planets.Pluto.Sphere.rotation.y -= Planets.Properties.Pluto.Speed.Rotation;
      // Planets Translation
      Planets.Sun.Sphere.position.x = Planets.Properties.Sun.Distance * Math.cos(t * Planets.Properties.Sun.Speed.Translation);
      Planets.Sun.Sphere.position.z = Planets.Properties.Sun.Distance * Math.sin(t * Planets.Properties.Sun.Speed.Translation);
      Planets.Mercury.Sphere.position.x = Planets.Properties.Mercury.Distance * Math.cos(t * Planets.Properties.Mercury.Speed.Translation);
      Planets.Mercury.Sphere.position.z = Planets.Properties.Mercury.Distance * Math.sin(t * Planets.Properties.Mercury.Speed.Translation);
      Planets.Venus.Sphere.position.x = Planets.Properties.Venus.Distance * Math.cos(t * Planets.Properties.Venus.Speed.Translation);
      Planets.Venus.Sphere.position.z = Planets.Properties.Venus.Distance * Math.sin(t * Planets.Properties.Venus.Speed.Translation);
      Planets.Earth.Sphere.position.x = Planets.Properties.Earth.Distance * Math.cos(t * Planets.Properties.Earth.Speed.Translation);
      Planets.Earth.Sphere.position.z = Planets.Properties.Earth.Distance * Math.sin(t * Planets.Properties.Earth.Speed.Translation);
      Planets.EarthMoon.Orbit.position.x = Planets.Earth.Sphere.position.x;
      Planets.EarthMoon.Orbit.position.z = Planets.Earth.Sphere.position.z;
      Planets.EarthMoon.Sphere.position.x = Planets.EarthMoon.Orbit.position.x + (Planets.Properties.EarthMoon.Distance * Math.cos(t * Planets.Properties.EarthMoon.Speed.Translation));
      Planets.EarthMoon.Sphere.position.z = Planets.EarthMoon.Orbit.position.z + (Planets.Properties.EarthMoon.Distance * Math.sin(t * Planets.Properties.EarthMoon.Speed.Translation));
      Planets.Mars.Sphere.position.x = Planets.Properties.Mars.Distance * Math.cos(t * Planets.Properties.Mars.Speed.Translation);
      Planets.Mars.Sphere.position.z = Planets.Properties.Mars.Distance * Math.sin(t * Planets.Properties.Mars.Speed.Translation);
      Planets.Jupiter.Sphere.position.x = Planets.Properties.Jupiter.Distance * Math.cos(t * Planets.Properties.Jupiter.Speed.Translation);
      Planets.Jupiter.Sphere.position.z = Planets.Properties.Jupiter.Distance * Math.sin(t * Planets.Properties.Jupiter.Speed.Translation);
      Planets.Saturn.Sphere.position.x = Planets.Properties.Saturn.Distance * Math.cos(t * Planets.Properties.Saturn.Speed.Translation);
      Planets.Saturn.Sphere.position.z = Planets.Properties.Saturn.Distance * Math.sin(t * Planets.Properties.Saturn.Speed.Translation);
      Planets.Saturn.Ring.position.x = Planets.Saturn.Sphere.position.x;
      Planets.Saturn.Ring.position.z = Planets.Saturn.Sphere.position.z;
      Planets.Uranus.Sphere.position.x = Planets.Properties.Uranus.Distance * Math.cos(t * Planets.Properties.Uranus.Speed.Translation);
      Planets.Uranus.Sphere.position.z = Planets.Properties.Uranus.Distance * Math.sin(t * Planets.Properties.Uranus.Speed.Translation);
      Planets.Uranus.Ring.position.x = Planets.Uranus.Sphere.position.x;
      Planets.Uranus.Ring.position.z = Planets.Uranus.Sphere.position.z;
      Planets.Neptune.Sphere.position.x = Planets.Properties.Neptune.Distance * Math.cos(t * Planets.Properties.Neptune.Speed.Translation);
      Planets.Neptune.Sphere.position.z = Planets.Properties.Neptune.Distance * Math.sin(t * Planets.Properties.Neptune.Speed.Translation);
      Planets.Pluto.Sphere.position.x = Planets.Properties.Pluto.Distance * Math.cos(t * Planets.Properties.Pluto.Speed.Translation);
      Planets.Pluto.Sphere.position.z = Planets.Properties.Pluto.Distance * Math.sin(t * Planets.Properties.Pluto.Speed.Translation);
      // StarFighter Orientation
      var StarFighterGhostDirection = StarFighterGhost.getWorldDirection();
      if(StarFighterOrientation.length < 20) {
        StarFighterOrientation.push(StarFighterGhostDirection);
      } else {
        //console.log();
        //StarFighter.localToWorld(StarFighterOrientation[0]);
        //StarFighter.rotation.x = StarFighterOrientation[0].x;
        //StarFighter.rotation.y = StarFighterOrientation[0].y;
        //StarFighter.rotation.z = StarFighterOrientation[0].z;
        var NewStarFighterOrientation = [];
        for(i = 1; i < 20; i++) {
          NewStarFighterOrientation.push(StarFighterOrientation[i]);
        }
        StarFighterOrientation = NewStarFighterOrientation;
        StarFighterOrientation.push(StarFighterGhostDirection);
      }
      // Camera Movement
      if($scope.moveStarFighter == true) {
        var cameraDirection = camera.getWorldDirection();
        var FighterSpeed = 1.5;
        StarFighterPosition.x += cameraDirection.x * FighterSpeed;
        StarFighterPosition.y += cameraDirection.y * FighterSpeed;
        StarFighterPosition.z += cameraDirection.z * FighterSpeed;
        camera.position.set(StarFighterPosition.x, StarFighterPosition.y, StarFighterPosition.z);
      }
      // Magic Zone End
      if($scope.stereoEffect == true) {
        effect.render(scene, camera);
      } else {
        renderer.render(scene, camera);
      }
    };
    function resize() {
      var width = container.offsetWidth;
      var height = container.offsetHeight;
      camera.aspect = width / height;
      camera.updateProjectionMatrix();
      if($scope.stereoEffect == true) {
        effect.setSize(width, height);
      } else {
        renderer.setSize(width, height);
      }
    };
    function fullscreen() {
      if (container.requestFullscreen) {
        container.requestFullscreen();
      } else if (container.msRequestFullscreen) {
        container.msRequestFullscreen();
      } else if (container.mozRequestFullScreen) {
        container.mozRequestFullScreen();
      } else if (container.webkitRequestFullscreen) {
        container.webkitRequestFullscreen();
      }
    };
  };
}])
<|endoftext|>


<commit_before>// the eslint "no-unused-expressions" rule is triggered by the `expect`
// assertions in the tests. So, in order to avoid problems with eslint, I'm
// disabling that rule in this file
//
/* eslint-disable no-unused-expressions */

import React from 'react';
import { shallow, render, mount } from 'enzyme';
import chai from 'chai';
import sinon from 'sinon';

import Form from '../Form';

const expect = chai.expect;

/* eslint-disable no-unused-vars */
const debug = (component) => {
    console.info('------------------------------------------------------------');
    console.info(component.debug());
    console.info('------------------------------------------------------------');
};
/* eslint-enable no-unused-vars */

/* *****************************************************************************
a Form component containing a SubmitButton
    should include a <Form.SubmitButton> as a child
    should be a button.btn.btn-default
    should have the label specified by the `label` property
    should have the default label if no `label` property specified
*/
describe('a Form component containing a SubmitButton', () => {

    it('should include a <Form.SubmitButton> as a child', () => {
        const component = shallow(
            <Form>
                <Form.SubmitButton />
            </Form>
        );

        expect(component.find(Form.SubmitButton)).to.have.length(1);
    });

    it('should be a button.btn.btn-default', () => {
        const component = render(
            <Form>
                <Form.SubmitButton />
            </Form>
        );

        expect(component.find('button')).to.have.length(1, 'button');
        expect(component.find('button.btn-default')).to.have.length(1, 'button.btn.btn-default');
    });

    it('should have the label specified by the `label` property', () => {
        const label = 'my label';

        const component = render(
            <Form>
                <Form.SubmitButton label={label} />
            </Form>
        );

        expect(component.find('button.btn-default').text()).to.equal(label);
    });

    it('should have the default label if no `label` property specified', () => {
        const component = render(
            <Form>
                <Form.SubmitButton />
            </Form>
        );

        expect(component.find('button.btn-default').text()).to.equal('Submit');
    });

});

/* *****************************************************************************
given a Form containing a required TextInput and a SubmitButton
    after initialization with a valid value, the SubmitButton should be enabled
    after initialization with several valid values, the SubmitButton should be enabled
    after initialization with multiple invalid values, the SubmitButton should be disabled
    after initialization with a mix of valid & invalid values, the SubmitButton should be disabled
    after changing from invalid to valid, the SubmitButton should be enabled
    after changing from valid to invalid, the SubmitButton should be disabled
*/
describe('given a Form containing a required TextInput and a SubmitButton', () => {

    it('after initialization with a valid value, the SubmitButton should be enabled', () => {
        const label = 'my label';

        const value = 'a valid value';

        const component = mount(
            <Form>
                <Form.TextInput required value={value} />
                <Form.SubmitButton label={label} />
            </Form>
        );

        expect(component.find('button.btn-default').props().disabled).to.equal(false);
    });

    it('after initialization with several valid values, the SubmitButton should be enabled', () => {
        const label = 'my label';

        const value = 'a valid value';

        const component = mount(
            <Form>
                <Form.TextInput required value={value} />
                <Form.TextInput required value={value} />
                <Form.TextInput required value={value} />
                <Form.TextInput required value={value} />
                <Form.TextInput required value={value} />
                <Form.SubmitButton label={label} />
            </Form>
        );

        expect(component.find('button.btn-default').props().disabled).to.equal(false);
    });

    it('after initialization with multiple invalid values, the SubmitButton should be disabled', () => {
        const label = 'my label';

        const value = '';

        const component = mount(
            <Form>
                <Form.TextInput required value={value} />
                <Form.TextInput required value={value} />
                <Form.TextInput required value={value} />
                <Form.SubmitButton label={label} />
            </Form>
        );

        expect(component.find('button.btn-default').props().disabled).to.equal(true);
    });

    it('after initialization with a mix of valid & invalid values, the SubmitButton should be disabled', () => {
        const label = 'my label';

        const invalid = '';

        const valid = 'triceratops';

        const component = mount(
            <Form>
                <Form.TextInput required value={invalid} />
                <Form.TextInput required value={invalid} />
                <Form.TextInput required value={valid} />
                <Form.SubmitButton label={label} />
            </Form>
        );

        expect(component.find('button.btn-default').props().disabled).to.equal(true);
    });

    it('after changing from invalid to valid, the SubmitButton should be enabled', () => {
        const label = 'my label';

        const initialValue = '';

        const finalValue = 'I wish I were an Oscar Meyer weiner';

        const component = mount(
            <Form>
                <Form.TextInput required value={initialValue} />
                <Form.SubmitButton label={label} />
            </Form>
        );

        expect(component.find('button.btn-default').props().disabled).to.equal(true);

        component.find('input').simulate('change', {
            target: { value: finalValue }
        });

        component.find('input').simulate('blur');

        expect(component.find('button.btn-default').props().disabled).to.equal(false);
    });

    it('after changing from valid to invalid, the SubmitButton should be disabled', () => {
        const label = 'my label';

        const initialValue = 'I wish I were an Oscar Meyer weiner';

        const finalValue = '';

        const component = mount(
            <Form>
                <Form.TextInput required value={initialValue} />
                <Form.SubmitButton label={label} />
            </Form>
        );

        expect(component.find('button.btn-default').props().disabled).to.equal(false);

        component.find('input').simulate('change', {
            target: { value: finalValue }
        });

        component.find('input').simulate('blur');

        expect(component.find('button.btn-default').props().disabled).to.equal(true);
    });

});

/* *****************************************************************************
a SubmitButton
    should call onClick when the button in a form is clicked
*/
describe('a SubmitButton', () => {

    it('should call onClick when the button in a form is clicked', () => {

        const onClick = sinon.spy();

        const label = 'my label';

        const component = mount(
            <Form>
                <Form.SubmitButton label={label} onClick={onClick} />
            </Form>
        );

        component.find('button').simulate('click');

        expect(onClick.callCount).to.equal(1);
    });
});
<commit_msg>code cleanup<commit_after>// the eslint "no-unused-expressions" rule is triggered by the `expect`
// assertions in the tests. So, in order to avoid problems with eslint, I'm
// disabling that rule in this file
//
/* eslint-disable no-unused-expressions */

import React from 'react';
import { shallow, render, mount } from 'enzyme';
import chai from 'chai';
import sinon from 'sinon';

import Form from '../Form';

const expect = chai.expect;

/* eslint-disable no-unused-vars */
const debug = (component) => {
    console.info('------------------------------------------------------------');
    console.info(component.debug());
    console.info('------------------------------------------------------------');
};
/* eslint-enable no-unused-vars */

/* *****************************************************************************
a Form component containing a SubmitButton
    should include a <Form.SubmitButton> as a child
    should be a button.btn.btn-default
    should have the label specified by the `label` property
    should have the default label if no `label` property specified
*/
describe('a Form component containing a SubmitButton', () => {

    it('should include a <Form.SubmitButton> as a child', () => {
        const component = shallow(
            <Form>
                <Form.SubmitButton />
            </Form>
        );

        expect(component.find(Form.SubmitButton)).to.have.length(1);
    });

    it('should be a button.btn.btn-default', () => {
        const component = render(
            <Form>
                <Form.SubmitButton />
            </Form>
        );

        expect(component.find('button')).to.have.length(1, 'button');
        expect(component.find('button.btn-default')).to.have.length(1, 'button.btn.btn-default');
    });

    it('should have the label specified by the `label` property', () => {
        const label = 'my label';

        const component = render(
            <Form>
                <Form.SubmitButton label={label} />
            </Form>
        );

        expect(component.find('button.btn-default').text()).to.equal(label);
    });

    it('should have the default label if no `label` property specified', () => {
        const component = render(
            <Form>
                <Form.SubmitButton />
            </Form>
        );

        expect(component.find('button.btn-default').text()).to.equal('Submit');
    });

});

/* *****************************************************************************
given a Form containing a required TextInput and a SubmitButton
    after initialization with a valid value, the SubmitButton should be enabled
    after initialization with several valid values, the SubmitButton should be enabled
    after initialization with multiple invalid values, the SubmitButton should be disabled
    after initialization with a mix of valid & invalid values, the SubmitButton should be disabled
    after changing from invalid to valid, the SubmitButton should be enabled
    after changing from valid to invalid, the SubmitButton should be disabled
*/
describe('given a Form containing a required TextInput and a SubmitButton', () => {

    it('after initialization with a valid value, the SubmitButton should be enabled', () => {
        const label = 'my label';

        const value = 'a valid value';

        const component = mount(
            <Form>
                <Form.TextInput required value={value} />
                <Form.SubmitButton label={label} />
            </Form>
        );

        expect(component.find('button.btn-default').props().disabled).to.equal(false);
    });

    it('after initialization with several valid values, the SubmitButton should be enabled', () => {
        const label = 'my label';

        const value = 'a valid value';

        const component = mount(
            <Form>
                <Form.TextInput required value={value} />
                <Form.TextInput required value={value} />
                <Form.TextInput required value={value} />
                <Form.TextInput required value={value} />
                <Form.TextInput required value={value} />
                <Form.SubmitButton label={label} />
            </Form>
        );

        expect(component.find('button.btn-default').props().disabled).to.equal(false);
    });

    it('after initialization with multiple invalid values, the SubmitButton ' +
        'should be disabled', () => {
        const label = 'my label';

        const value = '';

        const component = mount(
            <Form>
                <Form.TextInput required value={value} />
                <Form.TextInput required value={value} />
                <Form.TextInput required value={value} />
                <Form.SubmitButton label={label} />
            </Form>
        );

        expect(component.find('button.btn-default').props().disabled).to.equal(true);
    });

    it('after initialization with a mix of valid & invalid values, the ' +
        'SubmitButton should be disabled', () => {
        const label = 'my label';

        const invalid = '';

        const valid = 'triceratops';

        const component = mount(
            <Form>
                <Form.TextInput required value={invalid} />
                <Form.TextInput required value={invalid} />
                <Form.TextInput required value={valid} />
                <Form.SubmitButton label={label} />
            </Form>
        );

        expect(component.find('button.btn-default').props().disabled).to.equal(true);
    });

    it('after changing from invalid to valid, the SubmitButton should be enabled', () => {
        const label = 'my label';

        const initialValue = '';

        const finalValue = 'I wish I were an Oscar Meyer weiner';

        const component = mount(
            <Form>
                <Form.TextInput required value={initialValue} />
                <Form.SubmitButton label={label} />
            </Form>
        );

        expect(component.find('button.btn-default').props().disabled).to.equal(true);

        component.find('input').simulate('change', {
            target: { value: finalValue }
        });

        component.find('input').simulate('blur');

        expect(component.find('button.btn-default').props().disabled).to.equal(false);
    });

    it('after changing from valid to invalid, the SubmitButton should be disabled', () => {
        const label = 'my label';

        const initialValue = 'I wish I were an Oscar Meyer weiner';

        const finalValue = '';

        const component = mount(
            <Form>
                <Form.TextInput required value={initialValue} />
                <Form.SubmitButton label={label} />
            </Form>
        );

        expect(component.find('button.btn-default').props().disabled).to.equal(false);

        component.find('input').simulate('change', {
            target: { value: finalValue }
        });

        component.find('input').simulate('blur');

        expect(component.find('button.btn-default').props().disabled).to.equal(true);
    });

});

/* *****************************************************************************
a SubmitButton
    should call onClick when the button in a form is clicked
*/
describe('a SubmitButton', () => {

    it('should call onClick when the button in a form is clicked', () => {

        const onClick = sinon.spy();

        const label = 'my label';

        const component = mount(
            <Form>
                <Form.SubmitButton label={label} onClick={onClick} />
            </Form>
        );

        component.find('button').simulate('click');

        expect(onClick.callCount).to.equal(1);
    });
});
<|endoftext|>


<commit_before>champions = {
  "frontlines":
    ["Barik",
    "Fernando",
    "Makoa",
    "Ruckus"],

  "damage":
    ["Bomb King",
    "Cassie",
    "Drogoz",
    "Kinessa",
    "Sha Lin",
    "Tyra",
    "Viktor"],

  "support":
    ["Grohk",
    "Grover",
    "Mal'Damba",
    "Pip",
    "Ying"],

  "flank":
    ["Androxus",
    "Buck",
    "Evie",
    "Skye"],
};

function randomise(){

  pool = [];

  $("input").each(function() {

    if (this.checked){
      pool = pool.concat(champions[this.id]);
    };

  });

  //choose a champion from the pool
  chosen = pool[Math.floor(Math.random()*pool.length)];
  //set the text to the correct champion
  $("#answer").html(chosen);

  //setting the image
  url = "imgs/120px-Champion_" + chosen.replace(/\s+/g, '') + "_Icon.png";
  $("#profile").attr("src",url);

};

$( document ).ready(function() {
    randomise();
});
<commit_msg>torvald, baby<commit_after>champions = {
  "frontlines":
    ["Barik",
    "Fernando",
    "Makoa",
    "Ruckus",
    "Torvald"],

  "damage":
    ["Bomb King",
    "Cassie",
    "Drogoz",
    "Kinessa",
    "Sha Lin",
    "Tyra",
    "Viktor"],

  "support":
    ["Grohk",
    "Grover",
    "Mal'Damba",
    "Pip",
    "Ying"],

  "flank":
    ["Androxus",
    "Buck",
    "Evie",
    "Skye"],
};

function randomise(){

  pool = [];

  $("input").each(function() {

    if (this.checked){
      pool = pool.concat(champions[this.id]);
    };

  });

  //choose a champion from the pool
  chosen = pool[Math.floor(Math.random()*pool.length)];
  //set the text to the correct champion
  $("#answer").html(chosen);

  //setting the image
  url = "imgs/120px-Champion_" + chosen.replace(/\s+/g, '') + "_Icon.png";
  $("#profile").attr("src",url);

};

$( document ).ready(function() {
    randomise();
});
<|endoftext|>


<commit_before>'use strict';

module.exports = {
	app: {
		title: 'MEAN.JS',
		description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js',
		keywords: 'mongodb, express, angularjs, node.js, mongoose, passport'
	},
	port: process.env.PORT || 3000,
	templateEngine: 'swig',
	sessionSecret: 'MEAN',
	sessionCollection: 'sessions',
	assets: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.css',
				'public/lib/bootstrap/dist/css/bootstrap-theme.css',
			],
			js: [
				'public/lib/angular/angular.js',
				'public/lib/angular-resource/angular-resource.js',
				'public/lib/angular-animate/angular-animate.js',
				'public/lib/angular-ui-router/release/angular-ui-router.js',
				'public/lib/angular-ui-utils/ui-utils.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
				'public/lib/hammerjs/hammer.js',
				'public/lib/angular-aria/angular-aria.js',
				'public/lib/angular-material/angular-material.js'
			]
		},
		css: [
			'public/lib/angular-material/angular-material.css',
			'public/modules/**/css/*.css'
		],
		js: [
			'public/config.js',
			'public/application.js',
			'public/modules/*/*.js',
			'public/modules/*/*[!tests]*/*.js'
		],
		tests: [
			'public/lib/angular-mocks/angular-mocks.js',
			'public/modules/*/tests/*.js'
		]
	}
};<commit_msg>Changed app title, description, keywords and session secret<commit_after>'use strict';

module.exports = {
	app: {
		title: 'XMAS top 100',
		description: 'Vote for the top 100 of xmas songs!',
		keywords: 'xmas 100 vote spotify'
	},
	port: process.env.PORT || 3000,
	templateEngine: 'swig',
	sessionSecret: 'XMAS',
	sessionCollection: 'sessions',
	assets: {
		lib: {
			css: [
				'public/lib/bootstrap/dist/css/bootstrap.css',
				'public/lib/bootstrap/dist/css/bootstrap-theme.css',
			],
			js: [
				'public/lib/angular/angular.js',
				'public/lib/angular-resource/angular-resource.js',
				'public/lib/angular-animate/angular-animate.js',
				'public/lib/angular-ui-router/release/angular-ui-router.js',
				'public/lib/angular-ui-utils/ui-utils.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
				'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
				'public/lib/hammerjs/hammer.js',
				'public/lib/angular-aria/angular-aria.js',
				'public/lib/angular-material/angular-material.js'
			]
		},
		css: [
			'public/lib/angular-material/angular-material.css',
			'public/modules/**/css/*.css'
		],
		js: [
			'public/config.js',
			'public/application.js',
			'public/modules/*/*.js',
			'public/modules/*/*[!tests]*/*.js'
		],
		tests: [
			'public/lib/angular-mocks/angular-mocks.js',
			'public/modules/*/tests/*.js'
		]
	}
};
<|endoftext|>


<commit_before>'use strict'

var Path = require('path')
var request = require('request')

var Log = require(Path.join(__base, 'src/worker/log.js'))
var LogWorker = new Log({
  module: 'DatabaseClient'
})

function DatabaseClient (database, host, port, token) {
  this.db = database
  this.host = host
  this.port = port
  this.token = token
}

DatabaseClient.prototype.find = function (query, cb) {
  var self = this
  cb = cb || function () {}

  query['__database'] = self.db
  request.get({
    url: `http://${self.host}:${self.port}/api/find`,
    headers: {
      Authorization: `${self.token}`
    },
    qs: query
  }, function (err, res, body) {
    if (err || res.statusCode == 403) {
      if (res || res.statusCode == 403) {
        LogWorker.error('Unauthorized 403')
        cb(null, [])
      } else {
        cb(err, [])
      }
    } else {
      try {
        body = JSON.parse(body)
        if (body.err) {
          cb(body.err, [])
        } else {
          cb(null, body.data)
        }
      } catch(err) {
        cb(err, [])
      }
    }
  })
}

DatabaseClient.prototype.insert = function (data, cb) {
  var self = this
  cb = cb || function () {}

  data['__database'] = self.db
  request.post({
    url: `http://${self.host}:${self.port}/api/insert`,
    headers: {
      Authorization: `${self.token}`
    },
    form: data
  }, function (err, res, body) {
    if (err || res.statusCode == 403) {
      if (res || res.statusCode == 403) {
        cb('Database request unauthorized 403')
      } else {
        cb(err)
      }
    } else {
      try {
        body = JSON.parse(body)
        if (body.err) {
          cb(body.err)
        } else {
          cb(null)
        }
      } catch(err) {
        cb(err)
      }
    }
  })
}

DatabaseClient.prototype.update = function (query, data, options, cb) {
  var self = this
  cb = cb || function () {}

  request.post({
    url: `http://${self.host}:${self.port}/api/update`,
    headers: {
      Authorization: `${self.token}`
    },
    form: {
      query: query,
      data: data,
      options: options,
      __database: self.db
    }
  }, function (err, res, body) {
    if (err || res.statusCode == 403) {
      if (res || res.statusCode == 403) {
        cb('Database request unauthorized 403')
      } else {
        cb(err)
      }
    } else {
      try {
        body = JSON.parse(body)
        if (body.err) {
          cb(body.err)
        } else {
          cb(null)
        }
      } catch(err) {
        cb(err)
      }
    }
  })
}

DatabaseClient.prototype.remove = function (query, options, cb) {
  var self = this
  cb = cb || function () {}

  request.post({
    url: `http://${self.host}:${self.port}/api/remove`,
    headers: {
      Authorization: `${self.token}`
    },
    form: {
      query: query,
      options: options,
      __database: self.db
    }
  }, function (err, res, body) {
    if (err || res.statusCode == 403) {
      if (res || res.statusCode == 403) {
        cb('Database request unauthorized 403')
      } else {
        cb(err)
      }
    } else {
      try {
        body = JSON.parse(body)
        if (body.err) {
          cb(body.err)
        } else {
          cb(null)
        }
      } catch(err) {
        cb(err)
      }
    }
  })
}
module.exports = DatabaseClient
<commit_msg>better error catch<commit_after>'use strict'

var Path = require('path')
var request = require('request')

var Log = require(Path.join(__base, 'src/worker/log.js'))
var LogWorker = new Log({
  module: 'DatabaseClient'
})

function DatabaseClient (database, host, port, token) {
  this.db = database
  this.host = host
  this.port = port
  this.token = token
}

DatabaseClient.prototype.find = function (query, cb) {
  var self = this
  cb = cb || function () {}

  query['__database'] = self.db
  request.get({
    url: `http://${self.host}:${self.port}/api/find`,
    headers: {
      Authorization: `${self.token}`
    },
    qs: query
  }, function (err, res, body) {
    if (err || res.statusCode == 403) {
      if (res && res.statusCode == 403) {
        LogWorker.error('Unauthorized 403')
        cb(null, [])
      } else {
        cb(err, [])
      }
    } else {
      try {
        body = JSON.parse(body)
        if (body.err) {
          cb(body.err, [])
        } else {
          cb(null, body.data)
        }
      } catch(err) {
        cb(err, [])
      }
    }
  })
}

DatabaseClient.prototype.insert = function (data, cb) {
  var self = this
  cb = cb || function () {}

  data['__database'] = self.db
  request.post({
    url: `http://${self.host}:${self.port}/api/insert`,
    headers: {
      Authorization: `${self.token}`
    },
    form: data
  }, function (err, res, body) {
    if (err || res.statusCode == 403) {
      if (res && res.statusCode == 403) {
        cb('Database request unauthorized 403')
      } else {
        cb(err)
      }
    } else {
      try {
        body = JSON.parse(body)
        if (body.err) {
          cb(body.err)
        } else {
          cb(null)
        }
      } catch(err) {
        cb(err)
      }
    }
  })
}

DatabaseClient.prototype.update = function (query, data, options, cb) {
  var self = this
  cb = cb || function () {}

  request.post({
    url: `http://${self.host}:${self.port}/api/update`,
    headers: {
      Authorization: `${self.token}`
    },
    form: {
      query: query,
      data: data,
      options: options,
      __database: self.db
    }
  }, function (err, res, body) {
    if (err || res.statusCode == 403) {
      if (res && res.statusCode == 403) {
        cb('Database request unauthorized 403')
      } else {
        cb(err)
      }
    } else {
      try {
        body = JSON.parse(body)
        if (body.err) {
          cb(body.err)
        } else {
          cb(null)
        }
      } catch(err) {
        cb(err)
      }
    }
  })
}

DatabaseClient.prototype.remove = function (query, options, cb) {
  var self = this
  cb = cb || function () {}

  request.post({
    url: `http://${self.host}:${self.port}/api/remove`,
    headers: {
      Authorization: `${self.token}`
    },
    form: {
      query: query,
      options: options,
      __database: self.db
    }
  }, function (err, res, body) {
    if (err || res.statusCode == 403) {
      if (res && res.statusCode == 403) {
        cb('Database request unauthorized 403')
      } else {
        cb(err)
      }
    } else {
      try {
        body = JSON.parse(body)
        if (body.err) {
          cb(body.err)
        } else {
          cb(null)
        }
      } catch(err) {
        cb(err)
      }
    }
  })
}
module.exports = DatabaseClient
<|endoftext|>


<commit_before>//   Copyright (C) 2016 University of Dundee & Open Microscopy Environment.
//   All rights reserved.

//   This program is free software: you can redistribute it and/or modify
//   it under the terms of the GNU Affero General Public License as
//   published by the Free Software Foundation, either version 3 of the
//   License, or (at your option) any later version.

//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU Affero General Public License for more details.

//   You should have received a copy of the GNU Affero General Public License
//   along with this program.  If not, see <http://www.gnu.org/licenses/>.

//   Author: Aleksandra Tarkowska ,

//   Version: 1.0

//   Here we override ui.autocomplete

$(function () {

    $("label").inFieldLabels();

    var jstreeInst = $.jstree.reference('#dataTree');
    var oldData = jstreeInst.settings.core.data;

    $("#id_autocomplete").autocomplete({
        autoFocus: true,
        source: function( request, response ) {
            $.ajax({
                dataType: "json",
                type : 'GET',
                url: MAPANNOTATIONS.URLS.autocomplete,
                data: {
                    query: request.term,
                    experimenter_id: WEBCLIENT.active_user,
                    group: WEBCLIENT.active_group_id
                },
                success: function(data) {
                    $('#id_autocomplete').removeClass('ui-autocomplete-loading');
                    response( $.map( data, function(item) {
                        return item;
                    }));
                },
                error: function(data) {
                    $('#id_autocomplete').removeClass('ui-autocomplete-loading');
                }
            });
        },
        minLength: 1,
        open: function() {},
        close: function() {},
        focus: function(event,ui) {
            $( "#id_autocomplete" ).val( ui.item.label );
            return false;
        },
        select: function(event, ui) {
            jstreeInst.deselect_all();
            jstreeInst.close_all();
            OME.clearThumbnailsPanel();
            WEBCLIENT.URLS.api_experimenter = MAPANNOTATIONS.URLS.autocomplete_default
            jstreeInst.settings.core.data = function(node, callback, payload) {
                oldData.apply(jstreeInst, [node, callback, {'value': ui.item.value}]);
            };
            jstreeInst.refresh();
            return false;
        }
    }).data("ui-autocomplete")._renderItem = function( ul, item ) {
        return $( "
" )
            .append( "" + item.label + "" )
            .appendTo( ul );
    }

    $("#search_hints").tooltip({
        track: true,
        show: false,
        hide: false,
        items: '[data-content]',
        content: function() {
            return $(this).data('content');
        },
    });

});
<commit_msg>don't use focus in autocomplete<commit_after>//   Copyright (C) 2016 University of Dundee & Open Microscopy Environment.
//   All rights reserved.

//   This program is free software: you can redistribute it and/or modify
//   it under the terms of the GNU Affero General Public License as
//   published by the Free Software Foundation, either version 3 of the
//   License, or (at your option) any later version.

//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU Affero General Public License for more details.

//   You should have received a copy of the GNU Affero General Public License
//   along with this program.  If not, see <http://www.gnu.org/licenses/>.

//   Author: Aleksandra Tarkowska ,

//   Version: 1.0

//   Here we override ui.autocomplete

$(function () {

    $("label").inFieldLabels();

    var jstreeInst = $.jstree.reference('#dataTree');
    var oldData = jstreeInst.settings.core.data;

    $("#id_autocomplete").autocomplete({
        autoFocus: false,
        delay: 1,
        source: function( request, response ) {
            $.ajax({
                dataType: "json",
                type : 'GET',
                url: MAPANNOTATIONS.URLS.autocomplete,
                data: {
                    query: request.term,
                    experimenter_id: WEBCLIENT.active_user,
                    group: WEBCLIENT.active_group_id
                },
                success: function(data) {
                    $('#id_autocomplete').removeClass('ui-autocomplete-loading');
                    response( $.map( data, function(item) {
                        return item;
                    }));
                },
                error: function(data) {
                    $('#id_autocomplete').removeClass('ui-autocomplete-loading');
                }
            });
        },
        minLength: 1,
        open: function() {},
        close: function() {},
        focus: function(event,ui) {},
        select: function(event, ui) {
            // keep selected value in input
            $( "#id_autocomplete" ).val("");
            jstreeInst.deselect_all();
            jstreeInst.close_all();
            OME.clearThumbnailsPanel();
            WEBCLIENT.URLS.api_experimenter = MAPANNOTATIONS.URLS.autocomplete_default
            jstreeInst.settings.core.data = function(node, callback, payload) {
                oldData.apply(jstreeInst, [node, callback, {'value': ui.item.value}]);
            };
            jstreeInst.refresh();
            return false;
        }
    }).data("ui-autocomplete")._renderItem = function( ul, item ) {
        return $( "
" )
            .append( "" + item.label + "" )
            .appendTo( ul );
    }

    $("#search_hints").tooltip({
        track: true,
        show: false,
        hide: false,
        items: '[data-content]',
        content: function() {
            return $(this).data('content');
        },
    });

});
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var cluster = require('../')
  , http = require('http');

var server = http.createServer(function(req, res){
  console.log('%s %s', req.method, req.url);
  var body = 'Hello World';
  res.writeHead(200, { 'Content-Length': body.length });
  res.end(body);
});

// Launch the cluster:
//   $ nohup node examples/cli.js &

// Check the status:
//   $ node examples/cli.js status

// View other commands:
//   $ node examples/cli.js --help

cluster(server)
  .use(cluster.pidfiles())
  .use(cluster.logger())
  .use(cluster.cli())
  .listen(3000);
<commit_msg>debug() for cli() example<commit_after>
/**
 * Module dependencies.
 */

var cluster = require('../')
  , http = require('http');

var server = http.createServer(function(req, res){
  console.log('%s %s', req.method, req.url);
  var body = 'Hello World';
  res.writeHead(200, { 'Content-Length': body.length });
  res.end(body);
});

// Launch the cluster:
//   $ nohup node examples/cli.js &

// Check the status:
//   $ node examples/cli.js status

// View other commands:
//   $ node examples/cli.js --help

cluster(server)
  .use(cluster.pidfiles())
  .use(cluster.debug())
  .use(cluster.cli())
  .listen(3000);
<|endoftext|>