<commit_before>(function(root, factory) {
	if (typeof define === 'function' && define.amd) {
		define(['lodash','bluebird'], factory);
	} else if (typeof module === 'object' && module.exports) {
		module.exports = factory(require('lodash'),require('bluebird'));
	} else {
		root.bigt = factory(root._,root.Promise);
	}
}(this, function(_,Promise) {

	var ls = {};
	ls.get = function getFromStorage(prefix, key) {
		var res;
		try {
			res = localStorage.getItem(prefix + key);
			if (!res)
				res = undefined;
			else {
				res = JSON.parse(res);

			}
		} catch (e) {

			o.error('could not get %s from local o.storage', key);
			res = undefined;
		}
		return res;
	}

	ls.set = function setStorage(prefix,key, data) {

		try {
			localStorage.setItem(prefix + key, _.isString(data) ? data : JSON.stringify(data));
		} catch (e) {
			o.error('could not set %s from local o.storage', key);
			o.error(e);

		} finally {
			return data;
		}
	}

	ls.remove = function setStorage(prefix,key) {

		try {
			localStorage.removeItem(prefix + key);
		} catch (e) {
			o.error('could not remove %s from local o.storage', key);
			o.error(e);

		} finally {
			return;
		}
	}

	var u = {};

	u.defaultRequest = {
		forceString: true,
		escapeInterpolation:false,
		defaultValue:undefined,
	};

	u.defaultOptions = {
		namespaceDelimiter:':',
		keyDelimiter:'.',
		error:console.error,
		prefix:'ttt_',
		noEscapePrefix:'HTML',
		replacer:/\{\{(.*?)\}\}/g,
		recursor:/\$t\((.*?)\)/g,
		entityRegex:/[&<>"'\/]/g,
		entityMap:{
			"&": "&",
			"<": "<",
			">": ">",
			'"': '"',
			"'": ''',
			"/": '/'
		},
		sanitizeOptions:function(o){
			o = o || {};
			return _.defaults({},o,{
				forceString:o.returnObjectTrees,
				escapeParameters:o.escapeInterpolation,
			})
		}
	}

	u.init = u.initialize = function init(options) {

		this.options = options = _.defaults(options || {}, this.defaultOptions);
		this.caches={};
		this.quickCache={};
		this.remoteHashes ={};
		this.languagePromises={};

		if (options.noEscapePrefix)
			options.noEscapePrefixRegex = options.noEscapePrefixRegex || new RegExp('^' + options.noEscapePrefix);

		if (options.storage=='localStorage') {
			options.storage = ls;
		}
		if (options.storage) {
			_.each(['get','set','remove'],function(k){
				options.storage[k] = _.partial(options.storage[k],options.prefix);
			})
		}

		var lng = options.lng;
		if (!_.includes(options.languages = options.languages || ['en'], lng)) {
			lng = 'en';
		}
		this.language = options.lng = lng;

		return this;
	}

	u.ready = function(){
		return this.reload(this.language);
	}
	u.fetch = function(){

		var fetch = this.options.fetch;
		return fetch.apply(this,arguments);
	}

	u.lng = u.getLng = u.getLanguage = function getLanguage() {
		return this.language;
	}

	u.getResourceBundle = u.getNamespace = function getNamespace(lng, ns) {

		return _.get(this.caches, [lng, ns]);
	}

	u.addResource = u.addNamespace = function addNamespace(lng, ns, k, v) {
		var o = this.options;
		_.set(this.caches, [lng, ns].concat(k.split(o.keyDelimiter)), v);
		return o.storage ? o.storage.set(lng + '_' + ns, _.get(this.caches, [lng, ns])):v;
	}

	u.bind = function(lng){
		return _.bind(this.translate,this,lng)
	}

	u.setLanguage = u.setLng = function(lng){
		return this.load(lng).then(function(data){
			this.language = this.options.lng = lng;
			this.t = this.bind(this.language);
			return data;
		})
	}

	u.load = function load(lng) {

		lng = lng || this.language;

		var o = this.options,
			self = this;

		if (lng in this.languagePromises) {

			return this.languagePromises[lng];
		}

		if (!_.includes(o.languages, lng)) {

			return new Promise(function(resolve,reject){

				reject(new Error('You cant change the language to ' + lng + ', we dont have it'));
			})
		}

		if (!o.hashPath || !o.storage) {

			return this.reload(lng);
		}

		var params = {
			lng: lng,
			ns: 'hashes'
		};

		if (this.remoteHashes[lng]) {

			o.storage.set('localizationHash_' + lng, this.remoteHashes[lng]);
			this.reload(lng, cb);
		}

		var hashUrl = o.hashPath.replace(o.replacer, function(m, k) {
			return params[k];
		});

		return this.languagePromises[lng] = new Promise(function(resolve,reject){

			self.fetch(hashUrl).then(function(remoteHash){
				self.remoteHashes[lng] = remoteHash;

				var localHash = o.storage.get('localizationHash_' + lng) || {};
				if (!self.options.namespaces) {
					self.options.namespaces = Object.keys(remoteHash);
				}
				_.each(localHash, function(h, ns) {

					if (h !== remoteHash[ns]) {

						o.storage.remove(lng + '_' + ns);
					}

				})

				o.storage.set('localizationHash_' + lng, remoteHash);

				return self.reload(lng).then(resolve,reject);
			}).catch(function(err){
				o.error(err)
				o.error('error getting i18n from o.storage. flushing hash');
				self.localHash = {};
				o.storage.set('localizationHash_' + lng, '{}');
				reject(err);
			})
		});
	}

	u.reload = function reload(lng) {

		var o = this.options,
			self = this;

		var cache = this.caches[lng] = this.caches[lng] || {};

		var fetches = [];

		var promises = _.reduce(o.namespaces, function(memo, ns, index, allNs) {
			memo[ns] = new Promise(function(resolve,reject){

				var data = cache[ns] || (o.storage && o.storage.get(lng + '_' + ns));

				//if there is an __error in the data, we will try to reload it.
				if (data && !data.__error) {

					resolve(data);
					return memo;
				}

				var params = {
					lng: lng,
					ns: ns
				};

				var fetch;
				fetches.push(fetch = self.fetch(o.path.replace(o.replacer, function(m, k) {
						return params[k];
				})).then(function(data){
					delete data.__error;
					return o.storage ? o.storage.set(lng + '_' + ns, data):data;
				}).then(resolve).catch(function(){
					resolve({
						'__error': true
					})
				}));
			});
			return memo;
		}, {});

		var self = this;
		var promiseKeys = Object.keys(promises);

		return Promise.all(_.values(promises)).then(function(results){

			_.each(results, function(res, i) {

				cache[promiseKeys[i]] = res;
			});

			return cache;
		})

	}
	u.returnDefault = function returnDefault(options, k) {
		options = options || {};
		var defaultValue = options.defaultValue,
			v;
		if (defaultValue === undefined) {
			if (!options.forceString)
				v = {} //probably should be null
			else
				v = k;
		} else {
			v = _.isFunction(defaultValue) ? defaultValue.call(this, k) : defaultValue;
		}
		return (options.forceString) ? (v + '') : v;
	}

	u.translate = function translate(lng,k, options) {

		if (this.options.sanitizeOptions)
			options = this.options.sanitizeOptions(options);

		if (options && options.lng)
			lng = options.lng;

		if (!this.caches[lng]) {

			if (this.options.fallbackLanguage) {
				this.options.error(new Error('Called translate before language has loaded, using fallbackLanguage: ' + this.options.fallbackLanguage))
				this.caches[lng] = this.caches[this.options.fallbackLanguage]
			} else {
				this.options.error(new Error('Called translate before language has loaded, returning default'));
				return this.returnDefault(options,k);
			}
			//will attempt to load the language requested for next usage.
			this.reload(lng).catch(function(e){
				o.error(e)
			});
		}
		var originalOptions = _.clone(options);
		var o = options = _.defaults(options ? _.clone(options) : {}, this.defaultRequest, this.options)
		var esc = o.escapeInterpolation;

		if (!k)
			return this.returnDefault(options, k);

		var cache = this.caches[lng];
		var a = k.split(o.namespaceDelimiter);
		var defaultNamespace = this.options.defaultNamespace;

		var ns, namespace,key;

		if (a.length == 1)
			ns = defaultNamespace;
		else
			ns = a.shift();

		namespace = cache[ns];
		key = a[0].split(o.keyDelimiter);
		var v = _.get(namespace, key);

		if (v === undefined) {
			if (defaultNamespace && ns != defaultNamespace) {
				v = _.get(cache[defaultNamespace], key);
				if (v === undefined) {

					return this.returnDefault(options, k);
				}
			} else
				return this.returnDefault(options, k);
		}

		if (!_.isString(v)) {

			v = o.forceString ? (v + '') : v;
		}
		if (!_.isString(v))
			return v;

		var params = _.omit(originalOptions,Object.keys(this.defaultRequest))

		if (!_.isEmpty(params)) {
			v = v.replace(o.replacer, function(m, k) {

				if (!k) {

					return m
				}
				if (esc && o.noEscapePrefix && o.noEscapePrefixRegex.test(k)) {
					var noEscape = true;
					k = k.substring(0, k.length - o.noEscapePrefix.length);
				}
				var res = _.get(params, k);

				if (res === undefined) {

					res = m;
				}
				res += ''

				if (esc && !noEscape) {
					res = res.replace(o.entityRegex, function(s) {
						return o.entityMap[s];
					})
				}
				return res;
			});
		}
		var innerOptions = _.clone(originalOptions || {});
		//dont resupply defaultValue to inner queries
		delete innerOptions.defaultValue;

		//force return string for inner queries
		innerOptions.forceString = true;

		var self = this;

		v = v.replace(o.recursor, function(m, k) {

			if (!k)
				return ''

			return self.translate(lng,k, innerOptions) + '';
		});

		return v;

	}

	var c = function() {

	};
	_.extend(c.prototype, u);
	return c;
}));
<commit_msg>bigt fixes<commit_after>(function(root, factory) {
	if (typeof define === 'function' && define.amd) {
		define(['lodash','bluebird'], factory);
	} else if (typeof module === 'object' && module.exports) {
		module.exports = factory(require('lodash'),require('bluebird'));
	} else {
		root.bigt = factory(root._,root.Promise);
	}
}(this, function(_,Promise) {

	var ls = {};
	ls.get = function getFromStorage(prefix, key) {
		var res;
		try {
			res = localStorage.getItem(prefix + key);
			if (!res)
				res = undefined;
			else {
				res = JSON.parse(res);

			}
		} catch (e) {

			o.error('could not get %s from local o.storage', key);
			res = undefined;
		}
		return res;
	}

	ls.set = function setStorage(prefix,key, data) {

		try {
			localStorage.setItem(prefix + key, _.isString(data) ? data : JSON.stringify(data));
		} catch (e) {
			o.error('could not set %s from local o.storage', key);
			o.error(e);

		} finally {
			return data;
		}
	}

	ls.remove = function setStorage(prefix,key) {

		try {
			localStorage.removeItem(prefix + key);
		} catch (e) {
			o.error('could not remove %s from local o.storage', key);
			o.error(e);

		} finally {
			return;
		}
	}

	var u = {};

	u.defaultRequest = {
		forceString: true,
		escapeInterpolation:false,
		defaultValue:undefined,
	};

	u.defaultOptions = {
		namespaceDelimiter:':',
		keyDelimiter:'.',
		error:console.error,
		prefix:'ttt_',
		noEscapePrefix:'HTML',
		replacer:/\{\{(.*?)\}\}/g,
		recursor:/\$t\((.*?)\)/g,
		entityRegex:/[&<>"'\/]/g,
		entityMap:{
			"&": "&",
			"<": "<",
			">": ">",
			'"': '"',
			"'": ''',
			"/": '/'
		},
		sanitizeOptions:function(o){
			o = o || {};
			return _.defaults({},o,{
				forceString:o.returnObjectTrees,
				escapeParameters:o.escapeInterpolation,
			})
		}
	}

	u.init = u.initialize = function init(options) {

		this.options = options = _.defaults(options || {}, this.defaultOptions);
		this.caches={};
		this.quickCache={};
		this.remoteHashes ={};
		this.languagePromises={};

		if (options.noEscapePrefix)
			options.noEscapePrefixRegex = options.noEscapePrefixRegex || new RegExp('^' + options.noEscapePrefix);

		if (options.storage=='localStorage') {
			options.storage = ls;
		}
		if (options.storage) {
			_.each(['get','set','remove'],function(k){
				options.storage[k] = _.partial(options.storage[k],options.prefix);
			})
		}

		var lng = options.lng;
		if (!_.includes(options.languages = options.languages || ['en'], lng)) {
			lng = 'en';
		}
		this.language = options.lng = lng;

		return this;
	}

	u.ready = function(){
		return this.setLanguage(this.language);
	}
	u.fetch = function(url){

		var fetch = this.options.fetch;
		return fetch.call(this,url,Promise.resolve);
	}

	u.lng = u.getLng = u.getLanguage = function getLanguage() {
		return this.language;
	}

	u.getResourceBundle = u.getNamespace = function getNamespace(lng, ns) {

		return _.get(this.caches, [lng, ns]);
	}

	u.addResource = u.addNamespace = function addNamespace(lng, ns, k, v) {
		var o = this.options;
		_.set(this.caches, [lng, ns].concat(k.split(o.keyDelimiter)), v);
		return o.storage ? o.storage.set(lng + '_' + ns, _.get(this.caches, [lng, ns])):v;
	}

	u.bind = function(lng){
		return _.bind(this.translate,this,lng)
	}

	u.setLanguage = u.setLng = function(lng){
		return this.load(lng).bind(this).then(function(data){
			this.language = this.options.lng = lng;
			this.t = this.bind(this.language);
			return data;
		})
	}

	u.load = function load(lng) {

		lng = lng || this.language;

		var o = this.options,
			self = this;

		if (lng in this.languagePromises) {

			return this.languagePromises[lng];
		}

		if (!_.includes(o.languages, lng)) {

			return new Promise(function(resolve,reject){

				reject(new Error('You cant change the language to ' + lng + ', we dont have it'));
			})
		}

		if (!o.hashPath || !o.storage) {

			return this.reload(lng);
		}

		var params = {
			lng: lng,
			ns: 'hashes'
		};

		if (this.remoteHashes[lng]) {

			o.storage.set('localizationHash_' + lng, this.remoteHashes[lng]);
			this.reload(lng, cb);
		}

		var hashUrl = o.hashPath.replace(o.replacer, function(m, k) {
			return params[k];
		});

		return this.languagePromises[lng] = new Promise(function(resolve,reject){

			self.fetch(hashUrl).then(function(remoteHash){
				self.remoteHashes[lng] = remoteHash;

				var localHash = o.storage.get('localizationHash_' + lng) || {};
				if (!self.options.namespaces) {
					self.options.namespaces = Object.keys(remoteHash);
				}
				_.each(localHash, function(h, ns) {

					if (h !== remoteHash[ns]) {

						o.storage.remove(lng + '_' + ns);
					}

				})

				o.storage.set('localizationHash_' + lng, remoteHash);

				return self.reload(lng).then(resolve,reject);
			}).catch(function(err){
				o.error(err)
				o.error('error getting i18n from o.storage. flushing hash');
				self.localHash = {};
				o.storage.set('localizationHash_' + lng, '{}');
				reject(err);
			})
		});
	}

	u.reload = function reload(lng) {

		var o = this.options,
			self = this;

		var cache = this.caches[lng] = this.caches[lng] || {};

		var fetches = [];

		var promises = _.reduce(o.namespaces, function(memo, ns, index, allNs) {
			memo[ns] = new Promise(function(resolve,reject){

				var data = cache[ns] || (o.storage && o.storage.get(lng + '_' + ns));

				//if there is an __error in the data, we will try to reload it.
				if (data && !data.__error) {

					resolve(data);
					return memo;
				}

				var params = {
					lng: lng,
					ns: ns
				};

				var fetch;
				fetches.push(fetch = self.fetch(o.path.replace(o.replacer, function(m, k) {
						return params[k];
				})).then(function(data){
					delete data.__error;
					return o.storage ? o.storage.set(lng + '_' + ns, data):data;
				}).then(resolve).catch(function(){
					resolve({
						'__error': true
					})
				}));
			});
			return memo;
		}, {});

		var self = this;
		var promiseKeys = Object.keys(promises);

		return Promise.all(_.values(promises)).then(function(results){

			_.each(results, function(res, i) {

				cache[promiseKeys[i]] = res;
			});

			return cache;
		})

	}
	u.returnDefault = function returnDefault(options, k) {
		options = options || {};
		var defaultValue = options.defaultValue,
			v;
		if (defaultValue === undefined) {
			if (!options.forceString)
				v = {} //probably should be null
			else
				v = k;
		} else {
			v = _.isFunction(defaultValue) ? defaultValue.call(this, k) : defaultValue;
		}
		return (options.forceString) ? (v + '') : v;
	}

	u.translate = function translate(lng,k, options) {

		if (this.options.sanitizeOptions)
			options = this.options.sanitizeOptions(options);

		if (options && options.lng)
			lng = options.lng;

		if (!this.caches[lng]) {

			if (this.options.fallbackLanguage) {
				this.options.error(new Error('Called translate before language has loaded, using fallbackLanguage: ' + this.options.fallbackLanguage))
				this.caches[lng] = this.caches[this.options.fallbackLanguage]
			} else {
				this.options.error(new Error('Called translate before language has loaded, returning default'));
				return this.returnDefault(options,k);
			}
			//will attempt to load the language requested for next usage.
			this.reload(lng).catch(function(e){
				o.error(e)
			});
		}
		var originalOptions = _.clone(options);
		var o = options = _.defaults(options ? _.clone(options) : {}, this.defaultRequest, this.options)
		var esc = o.escapeInterpolation;

		if (!k)
			return this.returnDefault(options, k);

		var cache = this.caches[lng];
		var a = k.split(o.namespaceDelimiter);
		var defaultNamespace = this.options.defaultNamespace;

		var ns, namespace,key;

		if (a.length == 1)
			ns = defaultNamespace;
		else
			ns = a.shift();

		namespace = cache[ns];
		key = a[0].split(o.keyDelimiter);
		var v = _.get(namespace, key);

		if (v === undefined) {
			if (defaultNamespace && ns != defaultNamespace) {
				v = _.get(cache[defaultNamespace], key);
				if (v === undefined) {

					return this.returnDefault(options, k);
				}
			} else
				return this.returnDefault(options, k);
		}

		if (!_.isString(v)) {

			v = o.forceString ? (v + '') : v;
		}
		if (!_.isString(v))
			return v;

		var params = _.omit(originalOptions,Object.keys(this.defaultRequest))

		if (!_.isEmpty(params)) {
			v = v.replace(o.replacer, function(m, k) {

				if (!k) {

					return m
				}
				if (esc && o.noEscapePrefix && o.noEscapePrefixRegex.test(k)) {
					var noEscape = true;
					k = k.substring(0, k.length - o.noEscapePrefix.length);
				}
				var res = _.get(params, k);

				if (res === undefined) {

					res = m;
				}
				res += ''

				if (esc && !noEscape) {
					res = res.replace(o.entityRegex, function(s) {
						return o.entityMap[s];
					})
				}
				return res;
			});
		}
		var innerOptions = _.clone(originalOptions || {});
		//dont resupply defaultValue to inner queries
		delete innerOptions.defaultValue;

		//force return string for inner queries
		innerOptions.forceString = true;

		var self = this;

		v = v.replace(o.recursor, function(m, k) {

			if (!k)
				return ''

			return self.translate(lng,k, innerOptions) + '';
		});

		return v;

	}

	var c = function() {

	};
	_.extend(c.prototype, u);
	return c;
}));
<|endoftext|>


<commit_before>const email_REG = /^[0-9a-zA-Z]+([.\-_]*[0-9a-zA-Z]+)*@([0-9a-zA-Z]+[-_]*[0-9a-zA-Z]+\.)+[0-9a-zA-Z]{2,6}$/
const mobile_REG = /^1[3|4|5|7|8][0-9]{9}$/

/**
 * 校验邮箱地址
 * @param {*} email
 */
function validateEmail (email) {
  if (!email) {
    Toast("请输入邮箱")
  } else if (!email_REG.test(email)) {
    Toast("邮箱格式不正确")
  } else {
    return true
  }
}

/**
 * 校验手机号码
 * @param {*} mobile
 */
function validateMobile (mobile) {
  if (!mobile) {
    Toast('请输入手机号码')
  } else if (!mobile_REG.test(mobile)) {
    Toast('手机号码格式不正确')
  } else {
    return true
  }
}

/**
 * 校验验证码
 * @param {*} code
 */
function validateVerifyCode (code) {
  if (!code) {
    Toast('请输入验证码')
  } else if (!verify_REG.test(code)) {
    Toast('请输入正确的验证码')
  } else {
    return true
  }
}

/**
 * 校验密码
 * @param {*} password
 */
function validatePassword (password, tip = '请输入密码') {
  if (!password) {
    Toast(tip)
  } else if (!password_REG.test(password)) {
    Toast('密码为6-16位数字和字母组成')
  } else {
    return true
  }
}

/**
 * 校验手机或邮箱
 * @param {*} value
 */
function validateMobileOrEmail (value) {
  if (!value) {
    Toast('请输入邮箱或手机号')
  } else {
    if (value.indexOf('@') > 0) { // 含有 @
      if (!email_REG.test(value)) {
        Toast('邮箱格式不正确')
      } else {
        return true
      }
    } else {
      if (!mobile_REG.test(value)) {
        Toast('手机号码格式不正确')
      } else {
        return true
      }
    }
  }
}

export {
  validateEmail,
  validateMobile,
  validateVerifyCode,
  validatePassword,
  validateMobileOrEmail
}<commit_msg>修改常量标示<commit_after>const EMAIL_REG = /^[0-9a-zA-Z]+([.\-_]*[0-9a-zA-Z]+)*@([0-9a-zA-Z]+[-_]*[0-9a-zA-Z]+\.)+[0-9a-zA-Z]{2,6}$/
const MOBILE_REG = /^1[3|4|5|7|8][0-9]{9}$/
const VERIFY_REG = /^\d{6}$/
const PASSWORD_REG = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/

/**
 * 校验邮箱地址
 * @param {*} email
 */
function validateEmail (email) {
  if (!email) {
    Toast("请输入邮箱")
  } else if (!EMAIL_REG.test(email)) {
    Toast("邮箱格式不正确")
  } else {
    return true
  }
}

/**
 * 校验手机号码
 * @param {*} mobile
 */
function validateMobile (mobile) {
  if (!mobile) {
    Toast('请输入手机号码')
  } else if (!MOBILE_REG.test(mobile)) {
    Toast('手机号码格式不正确')
  } else {
    return true
  }
}

/**
 * 校验验证码
 * @param {*} code
 */
function validateVerifyCode (code) {
  if (!code) {
    Toast('请输入验证码')
  } else if (!VERIFY_REG.test(code)) {
    Toast('请输入正确的验证码')
  } else {
    return true
  }
}

/**
 * 校验密码
 * @param {*} password
 */
function validatePassword (password, tip = '请输入密码') {
  if (!password) {
    Toast(tip)
  } else if (!PASSWORD_REG.test(password)) {
    Toast('密码为6-16位数字和字母组成')
  } else {
    return true
  }
}

/**
 * 校验手机或邮箱
 * @param {*} value
 */
function validateMobileOrEmail (value) {
  if (!value) {
    Toast('请输入邮箱或手机号')
  } else {
    if (value.indexOf('@') > 0) { // 含有 @
      if (!EMAIL_REG.test(value)) {
        Toast('邮箱格式不正确')
      } else {
        return true
      }
    } else {
      if (!MOBILE_REG.test(value)) {
        Toast('手机号码格式不正确')
      } else {
        return true
      }
    }
  }
}

export {
  validateEmail,
  validateMobile,
  validateVerifyCode,
  validatePassword,
  validateMobileOrEmail
}<|endoftext|>


<commit_before>// http://mqttitude.org

var geocoder    = require('geocoder')
  , googlemaps  = require('googlemaps')
  , util        = require('util')
  , devices     = require('./../../core/device')
  , steward     = require('./../../core/steward')
  , utility     = require('./../../core/utility')
  , presence    = require('./../device-presence')
  ;

var logger   = presence.logger;

var geocache = {};

var Mobile = exports.Device = function(deviceID, deviceUID, info) {
  var param, self;

  self = this;

  self.whatami = info.deviceType;
  self.deviceID = deviceID.toString();
  self.deviceUID = deviceUID;
  self.name = info.device.name;
  self.getName();

  self.info = {};
  if (!!info.params.status) {
    self.status = info.params.status;
    delete(info.params.status);
  } else self.status = 'present';
  for (param in info.params) {
    if ((info.params.hasOwnProperty(param)) && (!!info.params[param])) self.info[param] = info.params[param];
  }
  self.points = [];
  self.update(self, info.params);

  self.events = {};

  utility.broker.subscribe('actors', function(request, eventID, actor, observe, parameter) {
    if (actor !== ('device/' + self.deviceID)) return;

    if (request === 'observe') {
      return;
    }
    if (request === 'perform') return devices.perform(self, eventID, observe, parameter);
  });
};
util.inherits(Mobile, presence.Device);

Mobile.prototype.update = function(self, params, status) {
  var i, key, location, markers, param, updateP;

  updateP = false;
  if ((!!status) && (status !== self.status)) {
    self.status = status;
    updateP = true;
  }
  location = self.info.location;
  for (param in params) {
    if ((!params.hasOwnProperty(param)) || (!params[param]) || (self.info[param] === params[param])) continue;

    self.info[param] = params[param];
    updateP = true;
  }

  if ((!location) || array_cmp (self.info.location, location)) {
    key = parseFloat(self.info.location[0]).toFixed(3) + ',' + parseFloat(self.info.location[1]).toFixed(3);
    self.info.physical = geocache[key] || '';
    if (!self.info.physical) {
      location = self.info.location;
      geocoder.reverseGeocode(location[0], location[1], function(err, result) {
        if (!!err) return logger.error('device/' + self.deviceID, { event      : 'reverseGeocode'
                                                                  , location   : location
                                                                  , diagnostic : err.message });
        if (result.status !== 'OK') return logger.warning('device/' + self.deviceID, { event      : 'reverseGeocode'
                                                                                , location   : location
                                                                                , diagnostic : result.status });
        if (result.results.length < 1) return;
        geocache[key] = result.results[0].formatted_address;
        self.info.physical = result.results[0].formatted_address;
        self.changed();
      });
    }

// NB: should just report the points and let the client do the needful; but for now, we'll just cook up a static map
    if (self.points.length > 0) {
      location = self.points[self.points.length - 1].split(',');
      i = getDistanceFromLatLonInKm(self.info.location[0], self.info.location[1], location[0], location[1]);
      if (i >= 0.4) {
        self.points.push(self.info.location.slice(0, 2).join(','));
        if (self.points.length > 50) self.points.splice(0, 50);
        markers = [];
        for (i = 0; i < self.points.length; i++) markers.push({ location: self.points[i], color: 'red', shadow: 'false' });

        self.info.staticmap = googlemaps.staticMap(self.points[0], 15, '250x250', false, false, 'roadmap', markers,
           [ { feature: 'road',   element: 'all', rules: { hue: '0x16161d' } } ]
           [ { color: '0x0000ff', weight: '5',    points: self.points        } ]);
        if (self.info.staticmap.indexOf('http://') === 0) self.info.staticmap = 'https' + self.info.staticmap.slice(4);
      }
    }
    else self.points.push(self.info.location.slice(0, 2).join(','));
  }

  if (updateP) self.changed();
};

Mobile.prototype.detail = function(self, params) {/* jshint unused: false */};

var array_cmp = function(a, b) {
  var i;

  if (!a) return (!(!!b));
  if (!util.isArray(a) || !util.isArray(b) || (a.length != b.length)) return false;
  for (i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
  return true;
};

// from http://stackoverflow.com/questions/27928/how-do-i-calculate-distance-between-two-latitude-longitude-points

var getDistanceFromLatLonInKm = function (lat1, lon1, lat2, lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1);
  var a =
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ;
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
};

var deg2rad = function(deg) {
  return deg * (Math.PI/180);
};

exports.start = function() {
  steward.actors.device.presence.mobile = steward.actors.device.presence.mobile ||
      { $info     : { type: '/device/presence/mobile' } };

  steward.actors.device.presence.mobile.mqtt =
      { $info     : { type       : '/device/presence/mobile/mqtt'
                    , observe    : [ ]
                    , perform    : [ ]
                    , properties : { name      : true
                                   , status    : [ 'present', 'recent', 'absent' ]
                                   , location  : 'coordinates'
                                   , accuracy  : 'meters'
                                   , physical  : true
                                   , staticmap : 'url'
                                   }
                    }
      , $validate : { perform    : devices.validate_perform }
      };
  devices.makers['/device/presence/mobile/mqtt'] = Mobile;

  steward.actors.device.presence.mobile.mqttitude = utility.clone(steward.actors.device.presence.mobile.mqtt);
  steward.actors.device.presence.mobile.mqttitude.$info.type = '/device/presence/mobile/mqttitude';
  devices.makers['/device/presence/mobile/mqttitude'] = Mobile;
};
<commit_msg>initial "TBD" for static map<commit_after>// http://mqttitude.org

var geocoder    = require('geocoder')
  , googlemaps  = require('googlemaps')
  , util        = require('util')
  , devices     = require('./../../core/device')
  , steward     = require('./../../core/steward')
  , utility     = require('./../../core/utility')
  , presence    = require('./../device-presence')
  ;

var logger   = presence.logger;

var geocache = {};

var Mobile = exports.Device = function(deviceID, deviceUID, info) {
  var param, self;

  self = this;

  self.whatami = info.deviceType;
  self.deviceID = deviceID.toString();
  self.deviceUID = deviceUID;
  self.name = info.device.name;
  self.getName();

  self.info = {};
  if (!!info.params.status) {
    self.status = info.params.status;
    delete(info.params.status);
  } else self.status = 'present';
  for (param in info.params) {
    if ((info.params.hasOwnProperty(param)) && (!!info.params[param])) self.info[param] = info.params[param];
  }
  self.points = [];
  self.update(self, info.params);

  self.events = {};

  utility.broker.subscribe('actors', function(request, eventID, actor, observe, parameter) {
    if (actor !== ('device/' + self.deviceID)) return;

    if (request === 'observe') {
      return;
    }
    if (request === 'perform') return devices.perform(self, eventID, observe, parameter);
  });
};
util.inherits(Mobile, presence.Device);

Mobile.prototype.update = function(self, params, status) {
  var i, key, location, markers, param, updateP;

  updateP = false;
  if ((!!status) && (status !== self.status)) {
    self.status = status;
    updateP = true;
  }
  location = self.info.location;
  for (param in params) {
    if ((!params.hasOwnProperty(param)) || (!params[param]) || (self.info[param] === params[param])) continue;

    self.info[param] = params[param];
    updateP = true;
  }

  if ((!location) || array_cmp (self.info.location, location)) {
    key = parseFloat(self.info.location[0]).toFixed(3) + ',' + parseFloat(self.info.location[1]).toFixed(3);
    self.info.physical = geocache[key] || '';
    if (!self.info.physical) {
      location = self.info.location;
      geocoder.reverseGeocode(location[0], location[1], function(err, result) {
        if (!!err) return logger.error('device/' + self.deviceID, { event      : 'reverseGeocode'
                                                                  , location   : location
                                                                  , diagnostic : err.message });
        if (result.status !== 'OK') return logger.warning('device/' + self.deviceID, { event      : 'reverseGeocode'
                                                                                , location   : location
                                                                                , diagnostic : result.status });
        if (result.results.length < 1) return;
        geocache[key] = result.results[0].formatted_address;
        self.info.physical = result.results[0].formatted_address;
        self.changed();
      });
    }

// TBD: should just report the points and let the client do the needful; but for now, we'll just cook up a static map
    if (self.points.length > 0) {
      location = self.points[self.points.length - 1].split(',');
      i = getDistanceFromLatLonInKm(self.info.location[0], self.info.location[1], location[0], location[1]);
      if (i >= 0.4) {
        self.points.push(self.info.location.slice(0, 2).join(','));
        if (self.points.length > 50) self.points.splice(0, 50);
        markers = [];
        for (i = 0; i < self.points.length; i++) markers.push({ location: self.points[i], color: 'red', shadow: 'false' });

        self.info.staticmap = googlemaps.staticMap(self.points[0], '', '250x250', false, false, 'roadmap', markers,
           [ { feature: 'road',   element: 'all', rules: { hue: '0x16161d' } } ]
           [ { color: '0x0000ff', weight: '5',    points: self.points        } ]);
        if (self.info.staticmap.indexOf('http://') === 0) self.info.staticmap = 'https' + self.info.staticmap.slice(4);
      }
    }
    else self.points.push(self.info.location.slice(0, 2).join(','));
  }

  if (updateP) self.changed();
};

Mobile.prototype.detail = function(self, params) {/* jshint unused: false */};

var array_cmp = function(a, b) {
  var i;

  if (!a) return (!(!!b));
  if (!util.isArray(a) || !util.isArray(b) || (a.length != b.length)) return false;
  for (i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
  return true;
};

// from http://stackoverflow.com/questions/27928/how-do-i-calculate-distance-between-two-latitude-longitude-points

var getDistanceFromLatLonInKm = function (lat1, lon1, lat2, lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1);
  var a =
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ;
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
};

var deg2rad = function(deg) {
  return deg * (Math.PI/180);
};

exports.start = function() {
  steward.actors.device.presence.mobile = steward.actors.device.presence.mobile ||
      { $info     : { type: '/device/presence/mobile' } };

  steward.actors.device.presence.mobile.mqtt =
      { $info     : { type       : '/device/presence/mobile/mqtt'
                    , observe    : [ ]
                    , perform    : [ ]
                    , properties : { name      : true
                                   , status    : [ 'present', 'recent', 'absent' ]
                                   , location  : 'coordinates'
                                   , accuracy  : 'meters'
                                   , physical  : true
                                   , staticmap : 'url'
                                   }
                    }
      , $validate : { perform    : devices.validate_perform }
      };
  devices.makers['/device/presence/mobile/mqtt'] = Mobile;

  steward.actors.device.presence.mobile.mqttitude = utility.clone(steward.actors.device.presence.mobile.mqtt);
  steward.actors.device.presence.mobile.mqttitude.$info.type = '/device/presence/mobile/mqttitude';
  devices.makers['/device/presence/mobile/mqttitude'] = Mobile;
};
<|endoftext|>


<commit_before>var suites = [
  {
    name: "Project Part 1",
    code: "ready!set!responsiveimages!",
    tests: [
      {
        func: "testDOMelemCSS",
        params: [
          {
            selector: "article img",
            property: "max-width",
            value: "100%"
          }
        ],
        desc: "s have max-widths of 100%"
      },
      {
        func: "testDOMelemCSS",
        repeat: true,
        params: [
          {
            selector: "article",
            property: "width",
            value: "600-1200px"
          }
        ],
        desc: "
s are reasonably wide (600-1200px)" // descriptions must be unique
      },
      {
        func: "testPageSizeMinimumLocal",
        async: true,
        noRepeat: true, // not necessary. leaving this here to show that it's possible. all async tests are automatically noRepeat
        showCurrent: true, // currently only works with async tests
        params: [
          {
            maxSize: 1500000 // in bytes
          }
        ],
        desc: "Page bytes are under 1.5MB (refresh to update)"
      }
    ]
  },
  {
    name: "Project Part 2",
    code: "markupisprettyawesome",
    tests: [
      {
        func: "testDOMelemDoesntExist",
        params: [
          {
            selector: "img[src='images/smiley_face.png']"
          }
        ],
        desc: "smiley_face.png is gone"
      },
      {
        func: "testFindStringInDocument",
        params: [
          {
            stringOpts: ["☺", "☺"] // looking for one of these
          }
        ],
        desc: "Smiley face is unicode"
      },
      {
        func: "testMetaTagContent",
        params: [
          {
            attr: "charset",
            value: "utf-8"
          }
        ],
        desc: "<meta> has charset set to utf-8"
      },
      {
        func: "testDOMelemDoesntExist",
        params: [
          {
            selector: "img[src='images/flourish.png']" // looking for one of these
          }
        ],
        desc: "Flourish is gone"
      },
      {
        func: "testDOMelemAttrApproxContent",
        params: [
          {
            selector: "*",
            attrs: ["class"],
            values: ["twitter"]
          }
        ],
        desc: "A Twitter font icon is on the page"
      },
      {
        func: "testDOMelemAttrApproxContent",
        params: [
          {
            selector: "*",
            attrs: ["class"],
            values: ["digg"]
          }
        ],
        desc: "A Digg font icon is on the page"
      },
      {
        func: "testDOMelemAttrApproxContent",
        params: [
          {
            selector: "*",
            attrs: ["class"],
            values: ["facebook"]
          }
        ],
        desc: "A Facebook font icon is on the page"
      },
      {
        func: "testDOMelemAttrApproxContent",
        params: [
          {
            selector: "*",
            attrs: ["class"],
            values: ["google"]
          }
        ],
        desc: "A Google+ font icon is on the page"
      }
    ]
  },
  {
    name: "Project Part 3",
    code: "allthepictures,allthetime",
    tests: [
      {
        func: "testDOMelemCount",
        params: [
          {
            selector: "picture",
            count: 8
          }
        ],
        desc: "There are 8 <picture>s on the page"
      },
      {
        func: "testDOMelemsCounts",
        params: [
          {
            parentSelector: "picture",
            childSelector: "source",
            count: 2
          }
        ],
        desc: "There are 2 <sources>s per <picture>"
      },
      {
        func: "testDOMelemsCounts",
        params: [
          {
            parentSelector: "picture",
            childSelector: "img",
            count: 1
          }
        ],
        desc: "There is 1  per <picture>"
      },
      {
        func: "testDOMelemsChildPosition",
        params: [
          {
            parentSelector: "picture",
            childSelector: "img",
            position: -1
          }
        ],
        desc: " is last child of all <picture>s"
      },
      {
        func: "testDOMelemsAttrContent",
        params: [
          {
            selector: "img",
            attr: "alt"
          }
        ],
        desc: "Every  has an alt attribute"
      }
    ]
  }
]

var graderProperties = {
  suites: suites
}<commit_msg>added all the smileys to the project grader<commit_after>var suites = [
  {
    name: "Project Part 1",
    code: "ready!set!responsiveimages!",
    tests: [
      {
        func: "testDOMelemCSS",
        params: [
          {
            selector: "article img",
            property: "max-width",
            value: "100%"
          }
        ],
        desc: "s have max-widths of 100%"
      },
      {
        func: "testDOMelemCSS",
        repeat: true,
        params: [
          {
            selector: "article",
            property: "width",
            value: "600-1200px"
          }
        ],
        desc: "
s are reasonably wide (600-1200px)" // descriptions must be unique
      },
      {
        func: "testPageSizeMinimumLocal",
        async: true,
        noRepeat: true, // not necessary. leaving this here to show that it's possible. all async tests are automatically noRepeat
        showCurrent: true, // currently only works with async tests
        params: [
          {
            maxSize: 1500000 // in bytes
          }
        ],
        desc: "Page bytes are under 1.5MB (refresh to update)"
      }
    ]
  },
  {
    name: "Project Part 2",
    code: "markupisprettyawesome",
    tests: [
      {
        func: "testDOMelemDoesntExist",
        params: [
          {
            selector: "img[src='images/smiley_face.png']"
          }
        ],
        desc: "smiley_face.png is gone"
      },
      {
        func: "testFindStringInDocument",
        params: [
          {
            stringOpts: [ "☺", "☺",
                          "☹", "੏",
                          "☻", "☻",
                          "😀", "😀",
                          "😁", "😁",
                          "😂", "😂",
                          "😃", "😃",
                          "😄", "😄",
                          "😅", "😅",
                          "😆", "😆",
                          "😇", "😇",
                          "😈", "😈",
                          "😉", "😉",
                          "😊", "😊",
                          "😋", "😋",
                          "😌", "😌",
                          "😍", "😍",
                          "😎", "😎",
                          "😏", "😏",
                          "😐", "😐",
                          "😑", "😑",
                          "😒", "😒",
                          "😓", "😓",
                          "😔", "😔",
                          "😕", "😕",
                          "😖", "😖",
                          "😗", "😗",
                          "😘", "😘",
                          "😙", "😙",
                          "😚", "😚",
                          "😛", "😛",
                          "😜", "😜",
                          "😝", "😝",
                          "😞", "😞",
                          "😟", "😟",
                          "😠", "😠",
                          "😡", "😡",
                          "😢", "😢",
                          "😣", "😣",
                          "😤", "😤",
                          "😥", "😥",
                          "😦", "😦",
                          "😧", "😧",
                          "😨", "😨",
                          "😩", "😩",
                          "😪", "😪",
                          "😫", "😫",
                          "😬", "😬",
                          "😭", "😭",
                          "😮", "😮",
                          "😯", "😯",
                          "😰", "😰",
                          "😱", "😱",
                          "😲", "😲",
                          "😳", "😳",
                          "😴", "😴",
                          "😵", "😵",
                          "😶", "😶",
                          "😷", "😷",
                          "😸", "😸",
                          "😹", "😹",
                          "😺", "😺",
                          "😻", "😻",
                          "😼", "😼",
                          "😽", "😽",
                          "😾", "😾",
                          "😿", "😿",
                          "🙀", "🙀"
                        ]
          }
        ],
        desc: "Smiley face is unicode"
      },
      {
        func: "testMetaTagContent",
        params: [
          {
            attr: "charset",
            value: "utf-8"
          }
        ],
        desc: "<meta> has charset set to utf-8"
      },
      {
        func: "testDOMelemDoesntExist",
        params: [
          {
            selector: "img[src='images/flourish.png']" // looking for one of these
          }
        ],
        desc: "Flourish is gone"
      },
      {
        func: "testDOMelemAttrApproxContent",
        params: [
          {
            selector: "*",
            attrs: ["class"],
            values: ["twitter"]
          }
        ],
        desc: "A Twitter font icon is on the page"
      },
      {
        func: "testDOMelemAttrApproxContent",
        params: [
          {
            selector: "*",
            attrs: ["class"],
            values: ["digg"]
          }
        ],
        desc: "A Digg font icon is on the page"
      },
      {
        func: "testDOMelemAttrApproxContent",
        params: [
          {
            selector: "*",
            attrs: ["class"],
            values: ["facebook"]
          }
        ],
        desc: "A Facebook font icon is on the page"
      },
      {
        func: "testDOMelemAttrApproxContent",
        params: [
          {
            selector: "*",
            attrs: ["class"],
            values: ["google"]
          }
        ],
        desc: "A Google+ font icon is on the page"
      }
    ]
  },
  {
    name: "Project Part 3",
    code: "allthepictures,allthetime",
    tests: [
      {
        func: "testDOMelemCount",
        params: [
          {
            selector: "picture",
            count: 8
          }
        ],
        desc: "There are 8 <picture>s on the page"
      },
      {
        func: "testDOMelemsCounts",
        params: [
          {
            parentSelector: "picture",
            childSelector: "source",
            count: 2
          }
        ],
        desc: "There are 2 <sources>s per <picture>"
      },
      {
        func: "testDOMelemsCounts",
        params: [
          {
            parentSelector: "picture",
            childSelector: "img",
            count: 1
          }
        ],
        desc: "There is 1  per <picture>"
      },
      {
        func: "testDOMelemsChildPosition",
        params: [
          {
            parentSelector: "picture",
            childSelector: "img",
            position: -1
          }
        ],
        desc: " is last child of all <picture>s"
      },
      {
        func: "testDOMelemsAttrContent",
        params: [
          {
            selector: "img",
            attr: "alt"
          }
        ],
        desc: "Every  has an alt attribute"
      }
    ]
  }
]

var graderProperties = {
  suites: suites
}<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var igvxhr = (function (igvxhr) {

    // Compression types
    const NONE = 0;
    const GZIP = 1;
    const BGZF = 2;

    igvxhr.load = function (url, options) {

        if (!options) options = {};

        if (!options.oauthToken) {
            return applyOauthToken();
        }

        var token = _.isFunction(options.oauthToken) ? options.oauthToken() : options.oauthToken;

        if (token.then && _.isFunction(token.then)) {
            return token.then(applyOauthToken);
        }

        return applyOauthToken(token);

        ////////////

        function applyOauthToken(token) {
            if (token) {
                options.token = token;
            }

            return getLoadPromise(url, options);
        }

        function getLoadPromise(url, options) {
            return new Promise(function (fullfill, reject) {

                var xhr = new XMLHttpRequest(),
                    sendData = options.sendData || options.body,
                    method = options.method || (sendData ? "POST" : "GET"),
                    range = options.range,
                    responseType = options.responseType,
                    contentType = options.contentType,
                    mimeType = options.mimeType,
                    headers = options.headers || {},
                    isSafari = navigator.vendor.indexOf("Apple") == 0 && /\sSafari\//.test(navigator.userAgent),
                    withCredentials = options.withCredentials,
                    header_keys, key, value, i;

                // Support for GCS paths.
                url = url.startsWith("gs://") ? igv.Google.translateGoogleCloudURL(url) : url;

                if (options.token) {
                    headers["Authorization"] = 'Bearer ' + options.token;
                }

                if (igv.Google.isGoogleURL(url)) {

                    url = igv.Google.addApiKey(url);

                    // Add google headers (e.g. oAuth)
                    headers = headers || {};
                    igv.Google.addGoogleHeaders(headers);

                }

                if (range) {
                    // Hack to prevent caching for byte-ranges. Attempt to fix net:err-cache errors in Chrome
                    url += url.includes("?") ? "&" : "?";
                    url += "someRandomSeed=" + Math.random().toString(36);
                }

                xhr.open(method, url);

                if (range) {
                    var rangeEnd = range.size ? range.start + range.size - 1 : "";
                    xhr.setRequestHeader("Range", "bytes=" + range.start + "-" + rangeEnd);
                    //      xhr.setRequestHeader("Cache-Control", "no-cache");    <= This can cause CORS issues, disabled for now
                }
                if (contentType) {
                    xhr.setRequestHeader("Content-Type", contentType);
                }
                if (mimeType) {
                    xhr.overrideMimeType(mimeType);
                }
                if (responseType) {
                    xhr.responseType = responseType;
                }
                if (headers) {
                    header_keys = Object.keys(headers);
                    for (i = 0; i < header_keys.length; i++) {
                        key = header_keys[i];
                        value = headers[key];
                        // console.log("Adding to header: " + key + "=" + value);
                        xhr.setRequestHeader(key, value);
                    }
                }

                // NOTE: using withCredentials with servers that return "*" for access-allowed-origin will fail
                if (withCredentials === true) {
                    xhr.withCredentials = true;
                }

                xhr.onload = function (event) {
                    // when the url points to a local file, the status is 0 but that is no error
                    if (xhr.status == 0 || (xhr.status >= 200 && xhr.status <= 300)) {

                        if (range && xhr.status != 206) {
                            handleError("ERROR: range-byte header was ignored for url: " + url);
                        }
                        else {
                            fullfill(xhr.response);
                        }
                    }
                    else {

                        //
                        if (xhr.status === 416) {
                            //  Tried to read off the end of the file.   This shouldn't happen, but if it does return an
                            handleError("Unsatisfiable range");
                        }
                        else {// TODO -- better error handling
                            handleError(xhr.status);
                        }

                    }

                };

                xhr.onerror = function (event) {

                    if (isCrossDomain(url) && url && !options.crossDomainRetried && igv.browser.crossDomainProxy &&
                        url != igv.browser.crossDomainProxy) {

                        options.sendData = "url=" + url;
                        options.crossDomainRetried = true;

                        igvxhr.load(igv.browser.crossDomainProxy, options).then(fullfill);
                    }
                    else {
                        handleError("Error accessing resource: " + url + " Status: " + xhr.status);
                    }
                }

                xhr.ontimeout = function (event) {
                    handleError("Timed out");
                };

                xhr.onabort = function (event) {
                    console.log("Aborted");
                    reject(new igv.AbortLoad());
                };

                try {
                    xhr.send(sendData);
                } catch (e) {
                    console.log(e);
                }

                function handleError(message) {
                    if (reject) {
                        reject(new Error(message));
                    }
                    else {
                        throw new Error(message);
                    }
                }
            });
        }
    };

    igvxhr.loadArrayBuffer = function (url, options) {

        if (url instanceof File) {
            return loadFileSlice(url, options);
        } else {
            if (options === undefined) options = {};
            options.responseType = "arraybuffer";
            return igvxhr.load(url, options);
        }

    };

    igvxhr.loadJson = function (url, options) {

        var method = options.method || (options.sendData ? "POST" : "GET");

        if (method == "POST") options.contentType = "application/json";

        return new Promise(function (fullfill, reject) {

            igvxhr.load(url, options).then(
                function (result) {
                    if (result) {
                        fullfill(JSON.parse(result));
                    }
                    else {
                        fullfill(result);
                    }
                }).catch(reject);
        })
    };

    igvxhr.loadString = function (path, options) {
        if (path instanceof File) {
            return loadFileHelper(path, options);
        } else {
            return loadURLHelper(path, options);
        }
    };

    igvxhr.arrayBufferToString = function (arraybuffer, compression) {

        var plain, inflate;

        if (compression === GZIP) {
            inflate = new Zlib.Gunzip(new Uint8Array(arraybuffer));
            plain = inflate.decompress();
        }
        else if (compression === BGZF) {
            plain = new Uint8Array(igv.unbgzf(arraybuffer));
        }
        else {
            plain = new Uint8Array(arraybuffer);
        }

        var result = "";
        for (var i = 0, len = plain.length; i < len; i++) {
            result = result + String.fromCharCode(plain[i]);
        }
        return result;
    };

    function arrayBufferToBits(arraybuffer, compression) {

        var plain,
            inflate;

        if (compression === GZIP) {
            inflate = new Zlib.Gunzip(new Uint8Array(arraybuffer));
            plain = inflate.decompress();
        } else if (compression === BGZF) {
            plain = new Uint8Array(igv.unbgzf(arraybuffer));
        } else {
            plain = new Uint8Array(arraybuffer);
        }

        return plain;
    }

    function loadFileSlice (localfile, options) {

        return new Promise(function (fullfill, reject) {

            var fileReader,
                blob,
                rangeEnd;

            fileReader = new FileReader();

            fileReader.onload = function (e) {

                var compression,
                    result;

                if (options.bgz) {
                    compression = BGZF;
                } else if (localfile.name.endsWith(".gz")) {
                    compression = GZIP;
                } else {
                    compression = NONE;
                }

                // result = igvxhr.arrayBufferToString(fileReader.result, compression);
                // console.log('loadFileSlice byte length ' + fileReader.result.byteLength);

                fullfill( fileReader.result );

            };

            fileReader.onerror = function (e) {
                console.log("reject uploading local file " + localfile.name);
                reject(null, fileReader);
            };

            rangeEnd = options.range.start + options.range.size - 1;
            blob = localfile.slice(options.range.start, rangeEnd + 1);

            fileReader.readAsArrayBuffer(blob);

        });

    }

    function loadFileHelper (localfile, options) {

        return new Promise(function (fullfill, reject) {

            var fileReader = new FileReader();

            fileReader.onload = function (e) {

                var compression,
                    result;

                if (options.bgz) {
                    compression = BGZF;
                } else if (localfile.name.endsWith(".gz")) {
                    compression = GZIP;
                } else {
                    compression = NONE;
                }

                result = igvxhr.arrayBufferToString(fileReader.result, compression);

                fullfill(result);

            };

            fileReader.onerror = function (e) {
                console.log("reject uploading local file " + localfile.name);
                reject(null, fileReader);
            };

            fileReader.readAsArrayBuffer(localfile);

        });

    }

    function loadURLHelper(url, options) {

        var compression,
            fn,
            idx;

        if (options === undefined) options = {};

        // Strip parameters from path
        // TODO -- handle local files with ?
        idx = url.indexOf("?");
        fn = idx > 0 ? url.substring(0, idx) : url;

        if (options.bgz) {
            compression = BGZF;
        } else if (fn.endsWith(".gz")) {
            compression = GZIP;
        } else {
            compression = NONE;
        }

        if (compression === NONE) {
            options.mimeType = 'text/plain; charset=x-user-defined';
            return igvxhr.load(url, options);
        } else {
            options.responseType = "arraybuffer";

            return new Promise(function (fullfill, reject) {

                igvxhr
                    .load(url, options)
                    .then(
                        function (data) {
                            var result = igvxhr.arrayBufferToString(data, compression);
                            fullfill(result);
                        })
                    .catch(reject)
            })
        }

    }

    function isCrossDomain(url) {

        var origin = window.location.origin;

        return !url.startsWith(origin);

    }

    igv.AbortLoad = function () {

    };

    return igvxhr;

})
(igvxhr || {});

<commit_msg>reject xhr.send errors<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var igvxhr = (function (igvxhr) {

    // Compression types
    const NONE = 0;
    const GZIP = 1;
    const BGZF = 2;

    igvxhr.load = function (url, options) {

        if (!options) options = {};

        if (!options.oauthToken) {
            return applyOauthToken();
        }

        var token = _.isFunction(options.oauthToken) ? options.oauthToken() : options.oauthToken;

        if (token.then && _.isFunction(token.then)) {
            return token.then(applyOauthToken);
        }

        return applyOauthToken(token);

        ////////////

        function applyOauthToken(token) {
            if (token) {
                options.token = token;
            }

            return getLoadPromise(url, options);
        }

        function getLoadPromise(url, options) {
            return new Promise(function (fullfill, reject) {

                var xhr = new XMLHttpRequest(),
                    sendData = options.sendData || options.body,
                    method = options.method || (sendData ? "POST" : "GET"),
                    range = options.range,
                    responseType = options.responseType,
                    contentType = options.contentType,
                    mimeType = options.mimeType,
                    headers = options.headers || {},
                    isSafari = navigator.vendor.indexOf("Apple") == 0 && /\sSafari\//.test(navigator.userAgent),
                    withCredentials = options.withCredentials,
                    header_keys, key, value, i;

                // Support for GCS paths.
                url = url.startsWith("gs://") ? igv.Google.translateGoogleCloudURL(url) : url;

                if (options.token) {
                    headers["Authorization"] = 'Bearer ' + options.token;
                }

                if (igv.Google.isGoogleURL(url)) {

                    url = igv.Google.addApiKey(url);

                    // Add google headers (e.g. oAuth)
                    headers = headers || {};
                    igv.Google.addGoogleHeaders(headers);

                }

                if (range) {
                    // Hack to prevent caching for byte-ranges. Attempt to fix net:err-cache errors in Chrome
                    url += url.includes("?") ? "&" : "?";
                    url += "someRandomSeed=" + Math.random().toString(36);
                }

                xhr.open(method, url);

                if (range) {
                    var rangeEnd = range.size ? range.start + range.size - 1 : "";
                    xhr.setRequestHeader("Range", "bytes=" + range.start + "-" + rangeEnd);
                    //      xhr.setRequestHeader("Cache-Control", "no-cache");    <= This can cause CORS issues, disabled for now
                }
                if (contentType) {
                    xhr.setRequestHeader("Content-Type", contentType);
                }
                if (mimeType) {
                    xhr.overrideMimeType(mimeType);
                }
                if (responseType) {
                    xhr.responseType = responseType;
                }
                if (headers) {
                    header_keys = Object.keys(headers);
                    for (i = 0; i < header_keys.length; i++) {
                        key = header_keys[i];
                        value = headers[key];
                        // console.log("Adding to header: " + key + "=" + value);
                        xhr.setRequestHeader(key, value);
                    }
                }

                // NOTE: using withCredentials with servers that return "*" for access-allowed-origin will fail
                if (withCredentials === true) {
                    xhr.withCredentials = true;
                }

                xhr.onload = function (event) {
                    // when the url points to a local file, the status is 0 but that is no error
                    if (xhr.status == 0 || (xhr.status >= 200 && xhr.status <= 300)) {

                        if (range && xhr.status != 206) {
                            handleError("ERROR: range-byte header was ignored for url: " + url);
                        }
                        else {
                            fullfill(xhr.response);
                        }
                    }
                    else {

                        //
                        if (xhr.status === 416) {
                            //  Tried to read off the end of the file.   This shouldn't happen, but if it does return an
                            handleError("Unsatisfiable range");
                        }
                        else {// TODO -- better error handling
                            handleError(xhr.status);
                        }

                    }

                };

                xhr.onerror = function (event) {

                    if (isCrossDomain(url) && url && !options.crossDomainRetried && igv.browser.crossDomainProxy &&
                        url != igv.browser.crossDomainProxy) {

                        options.sendData = "url=" + url;
                        options.crossDomainRetried = true;

                        igvxhr.load(igv.browser.crossDomainProxy, options).then(fullfill);
                    }
                    else {
                        handleError("Error accessing resource: " + url + " Status: " + xhr.status);
                    }
                }

                xhr.ontimeout = function (event) {
                    handleError("Timed out");
                };

                xhr.onabort = function (event) {
                    console.log("Aborted");
                    reject(new igv.AbortLoad());
                };

                try {
                    xhr.send(sendData);
                } catch (e) {
                    reject(e);
                }

                function handleError(message) {
                    if (reject) {
                        reject(new Error(message));
                    }
                    else {
                        throw new Error(message);
                    }
                }
            });
        }
    };

    igvxhr.loadArrayBuffer = function (url, options) {

        if (url instanceof File) {
            return loadFileSlice(url, options);
        } else {
            if (options === undefined) options = {};
            options.responseType = "arraybuffer";
            return igvxhr.load(url, options);
        }

    };

    igvxhr.loadJson = function (url, options) {

        var method = options.method || (options.sendData ? "POST" : "GET");

        if (method == "POST") options.contentType = "application/json";

        return new Promise(function (fullfill, reject) {

            igvxhr.load(url, options).then(
                function (result) {
                    if (result) {
                        fullfill(JSON.parse(result));
                    }
                    else {
                        fullfill(result);
                    }
                }).catch(reject);
        })
    };

    igvxhr.loadString = function (path, options) {
        if (path instanceof File) {
            return loadFileHelper(path, options);
        } else {
            return loadURLHelper(path, options);
        }
    };

    igvxhr.arrayBufferToString = function (arraybuffer, compression) {

        var plain, inflate;

        if (compression === GZIP) {
            inflate = new Zlib.Gunzip(new Uint8Array(arraybuffer));
            plain = inflate.decompress();
        }
        else if (compression === BGZF) {
            plain = new Uint8Array(igv.unbgzf(arraybuffer));
        }
        else {
            plain = new Uint8Array(arraybuffer);
        }

        var result = "";
        for (var i = 0, len = plain.length; i < len; i++) {
            result = result + String.fromCharCode(plain[i]);
        }
        return result;
    };

    function arrayBufferToBits(arraybuffer, compression) {

        var plain,
            inflate;

        if (compression === GZIP) {
            inflate = new Zlib.Gunzip(new Uint8Array(arraybuffer));
            plain = inflate.decompress();
        } else if (compression === BGZF) {
            plain = new Uint8Array(igv.unbgzf(arraybuffer));
        } else {
            plain = new Uint8Array(arraybuffer);
        }

        return plain;
    }

    function loadFileSlice (localfile, options) {

        return new Promise(function (fullfill, reject) {

            var fileReader,
                blob,
                rangeEnd;

            fileReader = new FileReader();

            fileReader.onload = function (e) {

                var compression,
                    result;

                if (options.bgz) {
                    compression = BGZF;
                } else if (localfile.name.endsWith(".gz")) {
                    compression = GZIP;
                } else {
                    compression = NONE;
                }

                // result = igvxhr.arrayBufferToString(fileReader.result, compression);
                // console.log('loadFileSlice byte length ' + fileReader.result.byteLength);

                fullfill( fileReader.result );

            };

            fileReader.onerror = function (e) {
                console.log("reject uploading local file " + localfile.name);
                reject(null, fileReader);
            };

            rangeEnd = options.range.start + options.range.size - 1;
            blob = localfile.slice(options.range.start, rangeEnd + 1);

            fileReader.readAsArrayBuffer(blob);

        });

    }

    function loadFileHelper (localfile, options) {

        return new Promise(function (fullfill, reject) {

            var fileReader = new FileReader();

            fileReader.onload = function (e) {

                var compression,
                    result;

                if (options.bgz) {
                    compression = BGZF;
                } else if (localfile.name.endsWith(".gz")) {
                    compression = GZIP;
                } else {
                    compression = NONE;
                }

                result = igvxhr.arrayBufferToString(fileReader.result, compression);

                fullfill(result);

            };

            fileReader.onerror = function (e) {
                console.log("reject uploading local file " + localfile.name);
                reject(null, fileReader);
            };

            fileReader.readAsArrayBuffer(localfile);

        });

    }

    function loadURLHelper(url, options) {

        var compression,
            fn,
            idx;

        if (options === undefined) options = {};

        // Strip parameters from path
        // TODO -- handle local files with ?
        idx = url.indexOf("?");
        fn = idx > 0 ? url.substring(0, idx) : url;

        if (options.bgz) {
            compression = BGZF;
        } else if (fn.endsWith(".gz")) {
            compression = GZIP;
        } else {
            compression = NONE;
        }

        if (compression === NONE) {
            options.mimeType = 'text/plain; charset=x-user-defined';
            return igvxhr.load(url, options);
        } else {
            options.responseType = "arraybuffer";

            return new Promise(function (fullfill, reject) {

                igvxhr
                    .load(url, options)
                    .then(
                        function (data) {
                            var result = igvxhr.arrayBufferToString(data, compression);
                            fullfill(result);
                        })
                    .catch(reject)
            })
        }

    }

    function isCrossDomain(url) {

        var origin = window.location.origin;

        return !url.startsWith(origin);

    }

    igv.AbortLoad = function () {

    };

    return igvxhr;

})
(igvxhr || {});

<|endoftext|>


<commit_before>$(document).ready(function(){
	$("form").submit(function(e){
        e.preventDefault();
    });
    $('.collapsible').collapsible({
      accordion : false // A setting that changes the collapsible behavior to expandable instead of the default accordion style
    });
	 $('select').material_select();

  });
  window.onload = function() {

	$(".drag-target").addClass('hide');

}
    $(".button-collapse").sideNav();
		$(document).ready(function(){
    // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
    $('.modal-trigger').leanModal();
  });

    $(document).ready(function(){
      $('.slider').slider({full_width: true});
    });

	$(document).on('click',".barra",function (){
		var lcarga2=$(this).attr("type");
		$($(this).attr("str")).removeClass('hide').siblings().addClass('hide');
		$("#slide-out").sideNav('hide');
		cargar(lcarga2,1);
		//$(".drag-target").removeClass('hide');
	});

	//login
	$(document).on('click',"#login",function (){
	direcion=$(this).attr("href")
	if($('#login_e').hasClass("valid")){
		var login_e=$('#login_e').val();
		var login_p=$('#login_p').val();
		$.ajax({
					type: 'POST',
					url: 'http://148.0.16.126:5123/reservaciones/consultas.php',
					data: 'tipo=login&email='+login_e+"&paswd="+login_p,
					success:
					function guepa(result){
						if(result==0){
							alert("error");
						}else{
							info=result.split("*");
							$("#nombre_user").append(info[1]);
							cambio(direcion);
							cargar("events",info[0]);
						}
					}
		});
		}else{
			$('#login_e').addClass("invalid");
		}
	});
	//registro
	$(document).on('click',"#registro_p",function (){
	var x=1;
	$('#form_resgistre').find(':input.validate').each(function(){
	if($(this).hasClass("valid")){}else{$(this).addClass("invalid");x=0;}
	});
	if(x==1){
		$.ajax({
					type: 'POST',
					url: 'http://148.0.16.126:5123/reservaciones/updates.php',
					data: $('#form_resgistre').serialize()+'&tipo=registro',
					success:
					function guepa(result){
						if(result==0){
							alert("error");
						}else{
							cambio('#login_page');
						}
					}
		});
	}

	});

	$(document).on("click",".cambio",function(){
		cambio($(this).attr("href"));
	});
	function cambio(direcion){
	$(".page").addClass('hide');
	$(direcion).removeClass('hide');
	if(direcion=="#page_content"){
	$(".drag-target").removeClass('hide');
	}
	};

//cargar contenido
	function cargar(lcarga,id){
			$.ajax({
					type: 'POST',
					url: 'http://148.0.16.126:5123/reservaciones/consultas.php',
					data: 'tipo='+lcarga+'&id='+id,
					success:
					function guepa(result){
						$('#'+lcarga+'_cards').html(result);
						$('.modal-trigger').leanModal();
						$('select').material_select();

					}
				});}
//reserva

$(document).on('click',".reserva",function (){
		data=$(this).attr("info");
			$.ajax({
					type: 'POST',
					url: 'http://148.0.16.126:5123/reservaciones/updates.php',
					data: 'tipo=reserva&info='+data,
					success:
					function guepa(result){
							cargar("reserva",1);
							$('.collapsible').collapsible({
      accordion : false // A setting that changes the collapsible behavior to expandable instead of the default accordion style
    });
					}
				});

});
$(document).on('click',".confirm",function (){
		var close=$(this).attr("str");
		$(close).trigger("click");

});
<commit_msg>Update index2.js<commit_after>$(document).ready(function(){
	$("form").submit(function(e){
        e.preventDefault();
    });
    $('.collapsible').collapsible({
      accordion : false // A setting that changes the collapsible behavior to expandable instead of the default accordion style
    });
	 $('select').material_select();

  });
  window.onload = function() {

	$(".drag-target").addClass('hide');

}
    $(".button-collapse").sideNav();
		$(document).ready(function(){
    // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
    $('.modal-trigger').leanModal();
  });

    $(document).ready(function(){
      $('.slider').slider({full_width: true});
    });

	$(document).on('click',".barra",function (){
		var lcarga2=$(this).attr("type");
		$($(this).attr("str")).removeClass('hide').siblings().addClass('hide');
		$("#slide-out").sideNav('hide');
		cargar(lcarga2,1);
		//$(".drag-target").removeClass('hide');
	});

	//login
	$(document).on('click',"#login",function (){
	direcion=$(this).attr("href")
	if($('#login_e').hasClass("valid")){
		var login_e=$('#login_e').val();
		var login_p=$('#login_p').val();
		$.ajax({
					type: 'POST',
					url: 'http://148.0.33.109:5123/reservaciones/consultas.php',
					data: 'tipo=login&email='+login_e+"&paswd="+login_p,
					success:
					function guepa(result){
						if(result==0){
							alert("error");
						}else{
							info=result.split("*");
							$("#nombre_user").append(info[1]);
							cambio(direcion);
							cargar("events",info[0]);
						}
					}
		});
		}else{
			$('#login_e').addClass("invalid");
		}
	});
	//registro
	$(document).on('click',"#registro_p",function (){
	var x=1;
	$('#form_resgistre').find(':input.validate').each(function(){
	if($(this).hasClass("valid")){}else{$(this).addClass("invalid");x=0;}
	});
	if(x==1){
		$.ajax({
					type: 'POST',
					url: 'http://148.0.33.109:5123/reservaciones/updates.php',
					data: $('#form_resgistre').serialize()+'&tipo=registro',
					success:
					function guepa(result){
						if(result==0){
							alert("error");
						}else{
							cambio('#login_page');
						}
					}
		});
	}

	});

	$(document).on("click",".cambio",function(){
		cambio($(this).attr("href"));
	});
	function cambio(direcion){
	$(".page").addClass('hide');
	$(direcion).removeClass('hide');
	if(direcion=="#page_content"){
	$(".drag-target").removeClass('hide');
	}
	};

//cargar contenido
	function cargar(lcarga,id){
			$.ajax({
					type: 'POST',
					url: 'http://148.0.33.109:5123/reservaciones/consultas.php',
					data: 'tipo='+lcarga+'&id='+id,
					success:
					function guepa(result){
						$('#'+lcarga+'_cards').html(result);
						$('.modal-trigger').leanModal();
						$('select').material_select();

					}
				});}
//reserva

$(document).on('click',".reserva",function (){
		data=$(this).attr("info");
			$.ajax({
					type: 'POST',
					url: 'http://148.0.33.109:5123/reservaciones/updates.php',
					data: 'tipo=reserva&info='+data,
					success:
					function guepa(result){
							cargar("reserva",1);
							$('.collapsible').collapsible({
      accordion : false // A setting that changes the collapsible behavior to expandable instead of the default accordion style
    });
					}
				});

});
$(document).on('click',".confirm",function (){
		var close=$(this).attr("str");
		$(close).trigger("click");

});
<|endoftext|>


<commit_before>var me = {

    url: '/v1/people/~:(id,first-name,last-name,headline,picture-url,email-address,public-profile-url,positions)?format=json',
    params: {},
    fields: {
        id: 'id',
        name: function(me) {
            return me.firstName + ' ' + me.lastName;
        },
        firstname: 'firstName',
        lastname: 'lastName',
        alias: 'screen_name',
        bio: 'headline',
        avatar: 'pictureUrl',
        email: 'emailAddress',
        url: 'publicProfileUrl'
    }
};

module.exports = me;
<commit_msg>Change me.js to use people v2 endpoint<commit_after>var me = {

    url: '/v2/people/~:(id,first-name,last-name,headline,picture-url,email-address,public-profile-url,positions)?format=json',
    params: {},
    fields: {
        id: 'id',
        name: function(me) {
            return me.firstName + ' ' + me.lastName;
        },
        firstname: 'firstName',
        lastname: 'lastName',
        alias: 'screen_name',
        bio: 'headline',
        avatar: 'pictureUrl',
        email: 'emailAddress',
        url: 'publicProfileUrl'
    }
};

module.exports = me;
<|endoftext|>


<commit_before>goog.provide('ol.format.JSONFeature');

goog.require('goog.asserts');
goog.require('goog.json');
goog.require('ol.BrowserFeature');
goog.require('ol.format.Feature');
goog.require('ol.format.FormatType');

/**
 * @classdesc
 * Abstract base class; normally only used for creating subclasses and not
 * instantiated in apps.
 * Base class for JSON feature formats.
 *
 * @constructor
 * @extends {ol.format.Feature}
 */
ol.format.JSONFeature = function() {
  goog.base(this);
};
goog.inherits(ol.format.JSONFeature, ol.format.Feature);

/**
 * @param {Document|Node|Object|string} source Source.
 * @private
 * @return {Object} Object.
 */
ol.format.JSONFeature.prototype.getObject_ = function(source) {
  if (goog.isObject(source)) {
    return source;
  } else if (goog.isString(source)) {
    var object;
    if (ol.BrowserFeature.HAS_JSON_PARSE) {
      object = /** @type {Object} */ (JSON.parse(source));
    } else {
      object = goog.json.parse(source);
    }
    return goog.isDef(object) ? object : null;
  } else {
    goog.asserts.fail();
    return null;
  }
};

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.getType = function() {
  return ol.format.FormatType.JSON;
};

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.readFeature = function(source, opt_options) {
  return this.readFeatureFromObject(this.getObject_(source), opt_options);
};

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.readFeatures = function(source, opt_options) {
  return this.readFeaturesFromObject(this.getObject_(source), opt_options);
};

/**
 * @param {Object} object Object.
 * @param {olx.format.ReadOptions=} opt_options Read options.
 * @protected
 * @return {ol.Feature} Feature.
 */
ol.format.JSONFeature.prototype.readFeatureFromObject = goog.abstractMethod;

/**
 * @param {Object} object Object.
 * @param {olx.format.ReadOptions=} opt_options Read options.
 * @protected
 * @return {Array.<ol.Feature>} Features.
 */
ol.format.JSONFeature.prototype.readFeaturesFromObject = goog.abstractMethod;

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.readGeometry = function(source, opt_options) {
  return this.readGeometryFromObject(this.getObject_(source), opt_options);
};

/**
 * @param {Object} object Object.
 * @param {olx.format.ReadOptions=} opt_options Read options.
 * @protected
 * @return {ol.geom.Geometry} Geometry.
 */
ol.format.JSONFeature.prototype.readGeometryFromObject = goog.abstractMethod;

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.readProjection = function(source) {
  return this.readProjectionFromObject(this.getObject_(source));
};

/**
 * @param {Object} object Object.
 * @protected
 * @return {ol.proj.Projection} Projection.
 */
ol.format.JSONFeature.prototype.readProjectionFromObject = goog.abstractMethod;

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.writeFeature = function(feature, opt_options) {
  return this.writeFeatureObject(feature, opt_options);
};

/**
 * @param {ol.Feature} feature Feature.
 * @param {olx.format.WriteOptions=} opt_options Write options.
 * @protected
 * @return {Object} Object.
 */
ol.format.JSONFeature.prototype.writeFeatureObject = goog.abstractMethod;

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.writeFeatures = function(
    features, opt_options) {
  return this.writeFeaturesObject(features, opt_options);
};

/**
 * @param {Array.<ol.Feature>} features Features.
 * @param {olx.format.WriteOptions=} opt_options Write options.
 * @protected
 * @return {Object} Object.
 */
ol.format.JSONFeature.prototype.writeFeaturesObject = goog.abstractMethod;

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.writeGeometry = function(
    geometry, opt_options) {
  return this.writeGeometryObject(geometry, opt_options);
};

/**
 * @param {ol.geom.Geometry} geometry Geometry.
 * @param {olx.format.WriteOptions=} opt_options Write options.
 * @protected
 * @return {Object} Object.
 */
ol.format.JSONFeature.prototype.writeGeometryObject = goog.abstractMethod;
<commit_msg>Get projection from data if dataProjection is not specified<commit_after>goog.provide('ol.format.JSONFeature');

goog.require('goog.asserts');
goog.require('goog.json');
goog.require('ol.BrowserFeature');
goog.require('ol.format.Feature');
goog.require('ol.format.FormatType');

/**
 * @classdesc
 * Abstract base class; normally only used for creating subclasses and not
 * instantiated in apps.
 * Base class for JSON feature formats.
 *
 * @constructor
 * @extends {ol.format.Feature}
 */
ol.format.JSONFeature = function() {
  goog.base(this);
};
goog.inherits(ol.format.JSONFeature, ol.format.Feature);

/**
 * @param {Document|Node|Object|string} source Source.
 * @private
 * @return {Object} Object.
 */
ol.format.JSONFeature.prototype.getObject_ = function(source) {
  if (goog.isObject(source)) {
    return source;
  } else if (goog.isString(source)) {
    var object;
    if (ol.BrowserFeature.HAS_JSON_PARSE) {
      object = /** @type {Object} */ (JSON.parse(source));
    } else {
      object = goog.json.parse(source);
    }
    return goog.isDef(object) ? object : null;
  } else {
    goog.asserts.fail();
    return null;
  }
};

/**
 * Adds the data projection to the read options.
 * @param {Object} obj Data object.
 * @param {olx.format.ReadOptions=} opt_options Options.
 * @return {olx.format.ReadOptions|undefined} Options.
 * @private
 */
ol.format.JSONFeature.prototype.getReadOptions_ = function(obj, opt_options) {
  var options;
  if (goog.isDef(opt_options)) {
    options = {
      dataProjection: goog.isDef(opt_options.dataProjection) ?
          opt_options.dataProjection : this.readProjectionFromObject(obj),
      featureProjection: opt_options.featureProjection
    };
  }
  return options;
};

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.getType = function() {
  return ol.format.FormatType.JSON;
};

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.readFeature = function(source, opt_options) {
  var obj = this.getObject_(source);
  return this.readFeatureFromObject(
      obj, this.getReadOptions_(obj, opt_options));
};

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.readFeatures = function(source, opt_options) {
  var obj = this.getObject_(source);
  return this.readFeaturesFromObject(
      obj, this.getReadOptions_(obj, opt_options));
};

/**
 * @param {Object} object Object.
 * @param {olx.format.ReadOptions=} opt_options Read options.
 * @protected
 * @return {ol.Feature} Feature.
 */
ol.format.JSONFeature.prototype.readFeatureFromObject = goog.abstractMethod;

/**
 * @param {Object} object Object.
 * @param {olx.format.ReadOptions=} opt_options Read options.
 * @protected
 * @return {Array.<ol.Feature>} Features.
 */
ol.format.JSONFeature.prototype.readFeaturesFromObject = goog.abstractMethod;

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.readGeometry = function(source, opt_options) {
  var obj = this.getObject_(source);
  return this.readGeometryFromObject(
      obj, this.getReadOptions_(obj, opt_options));
};

/**
 * @param {Object} object Object.
 * @param {olx.format.ReadOptions=} opt_options Read options.
 * @protected
 * @return {ol.geom.Geometry} Geometry.
 */
ol.format.JSONFeature.prototype.readGeometryFromObject = goog.abstractMethod;

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.readProjection = function(source) {
  return this.readProjectionFromObject(this.getObject_(source));
};

/**
 * @param {Object} object Object.
 * @protected
 * @return {ol.proj.Projection} Projection.
 */
ol.format.JSONFeature.prototype.readProjectionFromObject = goog.abstractMethod;

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.writeFeature = function(feature, opt_options) {
  return this.writeFeatureObject(feature, opt_options);
};

/**
 * @param {ol.Feature} feature Feature.
 * @param {olx.format.WriteOptions=} opt_options Write options.
 * @protected
 * @return {Object} Object.
 */
ol.format.JSONFeature.prototype.writeFeatureObject = goog.abstractMethod;

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.writeFeatures = function(
    features, opt_options) {
  return this.writeFeaturesObject(features, opt_options);
};

/**
 * @param {Array.<ol.Feature>} features Features.
 * @param {olx.format.WriteOptions=} opt_options Write options.
 * @protected
 * @return {Object} Object.
 */
ol.format.JSONFeature.prototype.writeFeaturesObject = goog.abstractMethod;

/**
 * @inheritDoc
 */
ol.format.JSONFeature.prototype.writeGeometry = function(
    geometry, opt_options) {
  return this.writeGeometryObject(geometry, opt_options);
};

/**
 * @param {ol.geom.Geometry} geometry Geometry.
 * @param {olx.format.WriteOptions=} opt_options Write options.
 * @protected
 * @return {Object} Object.
 */
ol.format.JSONFeature.prototype.writeGeometryObject = goog.abstractMethod;
<|endoftext|>


<commit_before>angular.module('broccoli')
    .service('InstanceService', function(Restangular){
      this.getInstances= function (template) {
      	if(!template){
          return Restangular.all("instances").getList();
      	}
        else{
          return Restangular.all("instances")
          .getList({ "templateId" : template.id });
          }
        }

        this.submitStatus=  function (instance, status) {
          return Restangular.all("instances")
            .customPOST({ "status": status }, instance.id, {}, {})
          }

        this.deleteInstance = function (template, instance) {
          instance.remove();
        }

        this.createInstance = function(template , paramsToValue) {
          return Restangular.all("instances")
          .post({
              templateId: template.id,
              parameters: paramsToValue
            })
        };

        this.editInstance = function(postData, newInstance) {
          return Restangular.all("instances")
          .customPOST(postData, newInstance.id, {}, {});
          };
        });
<commit_msg>#139 add some missing semicolons<commit_after>angular.module('broccoli')
    .service('InstanceService', function(Restangular){
      this.getInstances= function (template) {
      	if(!template){
          return Restangular.all("instances").getList();
      	}
        else{
          return Restangular.all("instances")
          .getList({ "templateId" : template.id });
          }
        };

        this.submitStatus=  function (instance, status) {
          return Restangular.all("instances")
            .customPOST({ "status": status }, instance.id, {}, {})
          };

        this.deleteInstance = function (template, instance) {
          instance.remove();
        };

        this.createInstance = function(template , paramsToValue) {
          return Restangular.all("instances")
          .post({
              templateId: template.id,
              parameters: paramsToValue
            })
        };

        this.editInstance = function(postData, newInstance) {
          return Restangular.all("instances")
          .customPOST(postData, newInstance.id, {}, {});
          };
        });
<|endoftext|>