<commit_before>var self = module.exports = {
	channel: (str) => { return str.charAt(0) === "#" ? str.toLowerCase() : "#" + str.toLowerCase(); },
	isBoolean: (obj) => { return obj === true || obj === false || toString.call(obj) === "[object Boolean]"; },
	isFinite: (int) => { return isFinite(int) && !isNaN(parseFloat(int)); },
	isInteger: (int) => { return !isNaN(self.toNumber(int, 0)); },
	isNull: (obj) => { return obj === null; },
	isString: (str) => { return typeof(str) === "string"; },
	isURL: (str) => { return RegExp("^(?:(?:https?|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))\\.?)(?::\\d{2,5})?(?:[/?#]\\S*)?$","i").test(str); },
	justinfan: () => { return "justinfan" + Math.floor((Math.random() * 80000) + 1000); },
	password: (str) => { return `oauth:${str.toLowerCase().replace("oauth:", "")}`; },
	promiseDelay: (time) => { return new Promise(function (resolve) { setTimeout(resolve, time); }); },
	username: (str) => { return str.charAt(0) === "#" ? str.substring(1).toLowerCase() : str.toLowerCase(); },

	addWord: (line, word) => {
	    if (line.length != 0) { line += " "; }
	    return (line += word);
	},
	inherits: (ctor, superCtor) => {
        ctor.super_ = superCtor;
        ctor.prototype = Object.create(superCtor.prototype, {
            constructor: {
                value: ctor,
                enumerable: false,
                writable: true,
                configurable: true
            }
        });
    },
	isNode: () => {
		try {
			if (module.exports = "object" === typeof process && Object.prototype.toString.call(process) === "[object process]") { return true; }
			return false;
		} catch(e) {
			return false;
		}
	},
	merge: (obj1, obj2) => {
	    for (var p in obj2) {
	        try {
	            if (obj2[p].constructor == Object) { obj1[p] = self.merge(obj1[p], obj2[p]); }
				else { obj1[p] = obj2[p]; }
	        } catch(e) { obj1[p] = obj2[p]; }
	    }
	    return obj1;
	},
	server: (cluster, secure, cb) => {
	    switch(cluster) {
	        case "event":
	        case "events":
				cb(secure ? "event-ws.tmi.twitch.tv:443": "event.tmi.twitch.tv:80");
	            break;
	        case "group":
	        case "groups":
				cb(secure ? "group-ws.tmi.twitch.tv:443": "group.tmi.twitch.tv:80");
	            break;
	        case "main":
				cb(secure ? "main-ws.tmi.twitch.tv:443": "main.tmi.twitch.tv:80");
	            break;
	        default:
				cb(secure ? "irc-ws.chat.twitch.tv:443": "irc-ws.chat.twitch.tv:80");
	            break;
	    }
	},
	splitLine: (input, length) => {
	    var lastSpace = input.substring(0, length).lastIndexOf(" ");
	    return [input.substring(0, lastSpace), input.substring(lastSpace + 1)];
	},
	toNumber: (num, precision) => {
		if (num === null) return 0;
		var factor = Math.pow(10, self.isFinite(precision) ? precision : 0);
		return Math.round(num * factor) / factor;
	},
	union: (arr1, arr2) => {
		var hash = {};
		var ret = [];
		for(var i=0; i < arr1.length; i++){
			var e = arr1[i];
			if (!hash[e]) {
				hash[e] = true;
				ret.push(e);
			}
		}
		for(var i=0; i < arr2.length; i++){
			var e = arr2[i];
			if (!hash[e]) {
				hash[e] = true;
				ret.push(e);
			}
		}
		return ret;
	}
}
<commit_msg>utils: changed indentation of some lines.<commit_after>var self = module.exports = {
	channel: (str) => { return str.charAt(0) === "#" ? str.toLowerCase() : "#" + str.toLowerCase(); },
	isBoolean: (obj) => { return obj === true || obj === false || toString.call(obj) === "[object Boolean]"; },
	isFinite: (int) => { return isFinite(int) && !isNaN(parseFloat(int)); },
	isInteger: (int) => { return !isNaN(self.toNumber(int, 0)); },
	isNull: (obj) => { return obj === null; },
	isString: (str) => { return typeof(str) === "string"; },
	isURL: (str) => { return RegExp("^(?:(?:https?|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))\\.?)(?::\\d{2,5})?(?:[/?#]\\S*)?$","i").test(str); },
	justinfan: () => { return "justinfan" + Math.floor((Math.random() * 80000) + 1000); },
	password: (str) => { return `oauth:${str.toLowerCase().replace("oauth:", "")}`; },
	promiseDelay: (time) => { return new Promise(function (resolve) { setTimeout(resolve, time); }); },
	username: (str) => { return str.charAt(0) === "#" ? str.substring(1).toLowerCase() : str.toLowerCase(); },

	addWord: (line, word) => {
		if (line.length != 0) { line += " "; }
		return (line += word);
	},
	inherits: (ctor, superCtor) => {
		ctor.super_ = superCtor;
		ctor.prototype = Object.create(superCtor.prototype, {
			constructor: {
				value: ctor,
				enumerable: false,
				writable: true,
				configurable: true
			}
		});
	},
	isNode: () => {
		try {
			if (module.exports = "object" === typeof process && Object.prototype.toString.call(process) === "[object process]") { return true; }
			return false;
		} catch(e) {
			return false;
		}
	},
	merge: (obj1, obj2) => {
		for (var p in obj2) {
			try {
				if (obj2[p].constructor == Object) { obj1[p] = self.merge(obj1[p], obj2[p]); }
				else { obj1[p] = obj2[p]; }
			} catch(e) { obj1[p] = obj2[p]; }
		}
		return obj1;
	},
	server: (cluster, secure, cb) => {
		switch(cluster) {
			case "event":
			case "events":
				cb(secure ? "event-ws.tmi.twitch.tv:443": "event.tmi.twitch.tv:80");
				break;
			case "group":
			case "groups":
				cb(secure ? "group-ws.tmi.twitch.tv:443": "group.tmi.twitch.tv:80");
				break;
			case "main":
				cb(secure ? "main-ws.tmi.twitch.tv:443": "main.tmi.twitch.tv:80");
				break;
			default:
				cb(secure ? "irc-ws.chat.twitch.tv:443": "irc-ws.chat.twitch.tv:80");
				break;
		}
	},
	splitLine: (input, length) => {
		var lastSpace = input.substring(0, length).lastIndexOf(" ");
		return [input.substring(0, lastSpace), input.substring(lastSpace + 1)];
	},
	toNumber: (num, precision) => {
		if (num === null) return 0;
		var factor = Math.pow(10, self.isFinite(precision) ? precision : 0);
		return Math.round(num * factor) / factor;
	},
	union: (arr1, arr2) => {
		var hash = {};
		var ret = [];
		for(var i=0; i < arr1.length; i++) {
			var e = arr1[i];
			if (!hash[e]) {
				hash[e] = true;
				ret.push(e);
			}
		}
		for(var i=0; i < arr2.length; i++) {
			var e = arr2[i];
			if (!hash[e]) {
				hash[e] = true;
				ret.push(e);
			}
		}
		return ret;
	}
}
<|endoftext|>


<commit_before>
(function (module) {
	'use strict';

	var _key_iterator = Symbol.iterator;

	module.exports = {
		dialog: dialog,
		notice: notice,
		info: notice('info'),
		warn: notice('warning'),
		error: notice('error'),
		chainFunction: chainFunction,
		isIterable: isIterable,
		repeat: repeat,
		some: some,
		forOf: forOf,
		makeSubProperty: makeSubProperty,
		ternary: ternary,
		makeDefaultProperty: makeDefaultProperty,
		iterable: iterable,
		deepJoin: deepJoin,
		tryCatch: tryCatch,
		tryCatchOf: tryCatchOf,
		throwError: throwError,
		createMerelyObject: createMerelyObject,
		clearChildren: clearChildren
	};

	function dialog(title) {
		return (message) =>
			setTimeout(alert.bind(null, message, title));
	}

	function notice(type) {
		return (message, detail) =>
			atom.notifications.add(type, message, {detail: detail});
	}

	function chainFunction(fna, fnb) {
		return (...arg) => new chainFunction.Return(fna(...arg), fnb(...arg));
	}

	chainFunction.array = (fnlist) => {
		var fn = () => chainFunction.NOT_AN_ELEMENT;
		for (let fne of fnlist) {
			ensure(fne);
			fn = chainFunction(fn, fne);
		}
		function ensure(fn) {
			if (typeof fn !== 'function') {
				let error = new TypeError(`An element of parameter 'fnlist' is not a function: ${typeof fn} ${tryConvert.forString(fn)}`);
				error.details = {element: fn, array: fnlist};
				throw error;
			}
		}
		return fn;
	}

	chainFunction.Return = class Return extends Array {

		constructor(a, b) {
			if (a instanceof Return) {
				a.push(b);
				return a;
			} else {
				super();
				this.push(a, b);
			}
		}

		push(...args) {
			return super.push(...this.filter((val) => val !== chainFunction.NOT_AN_ELEMENT));
		}

	}

	chainFunction.NOT_AN_ELEMENT = Symbol('NOT_AN_ELEMENT');

	function isIterable(object) {
		return typeof object === 'object' && typeof object[_key_iterator] === 'function';
	}

	function tryConvert(value, type) {
		return tryCatch(() => type(value), (error) => error);
	}

	tryConvert.forString = (value) => tryConvert(value, String);

	tryConvert.forNumber = (value) => tryConvert(value, Number);

	function repeat(action) {
		return new repeat.Return(action);
	}

	repeat.Return = class {

		constructor(action) {
			if (typeof action !== 'function') {
				throw new TypeError(`Parameter 'action' must be a function`)
			}
			this.action = action.bind(null);
		}

		until(isstop) {
			do {
				this.action();
			} while (!isstop());
		}

		times(count) {
			while (count) {
				action(count);
				--count;
			}
		}

	};

	function some(iterable, element, check) {
		for (let el of iterable) {
			if (check(element, el)) {
				return true;
			}
		}
		return false;
	}

	some.equal = (values, value) =>
		some(values, value, some.equal.check);

	some.equal.check = (a, b) => a === b;

	some.equal.typeof = (types, value) =>
		some.equal(types, typeof value);

	some.equiv = (iterable, element, get) =>
		some(iterable, element, equiv.checkOf(get));

	some.equiv.checkOf = (get) =>
		(a, b) => a === get(b);

	some.equiv.forType = (iterable, element, types) =>
		some.equiv(iterable, element, some.equiv.forType.get);

	some.equiv.forType.get = (value) => typeof value;

	function forOf(iterable, callback) {

		var isiter = isIterable(iterable);
		var isfunc = typeof callback === 'function';

		if (isiter && isfunc) {
			return forOf.for.both(iterable, callback);
		}

		if (isiter) {
			return forOf.for.iterable(iterable);
		}

		if (isfunc) {
			return forOf.for.callback(callback);
		}

		throw new TypeError(`Invalid type of arguments.`);

	}

	forOf.gen = function * (iterable, generator) {
		for (let element of iterable) {
			yield * generator(element, iterable);
		}
	}

	forOf.gen.fromCallback = function * (iterable, callback) {
		yield * forOf.gen(iterable, forOf.gen.create(callback));
	}

	forOf.gen.create = (callback) =>
		function * (element, iterable) {
			yield callback(element, iterable);
		}

	forOf.for = (iterable, callback) => {
		for (let element of iterable) {
			callback(element, iterable);
		}
	}

	forOf.for.both = (iterable, callback) =>
		forOf.for.bind(null, iterable, callback);

	forOf.for.iterable = (iterable) =>
		(callback) => forOf.for(iterable, callback);

	forOf.for.callback = (callback) =>
		(iterable) => forOf.for(iterable, callback);

	function makeSubProperty(object, pname, subpname, subval) {
		var sub = object[pname];
		if (some.typeof(['object', 'function'], sub)) {
			sub[subpname] = subval;
		} else {
			object[pname] = {[subpname]: subval};
		}
	}

	function ternary(is, iftrue, iffalse) {
		return (is() ? iftrue : iffalse)();
	}

	ternary.if = (is, act, val) =>
		ternary(is, act, () => val);

	ternary.unless = (is, act, val) =>
		ternary(is, () => val, act);

	ternary.ternary = (is, valiftrue, valiffalse) =>
		ternary(is, () => valiftrue, () => valiffalse);

	ternary.correct = (val, iswrong, getright) =>
		ternary(() => iswrong(val()), getright, val);

	ternary.correct.typeof = (val, wrongtypes, getright) =>
		ternary.correct(val, some.equal.typeof.bind(null, wrongtypes), getright);

	ternary.correct.valof = (val, wrongs, getright) =>
		ternary.correct(val, some.equal.bind(null, wrongs), getright);

	function makeDefaultProperty(object, pname, iswrong, right) {
		if (iswrong(object[pname])) {
			object[pname] = right;
		}
	}

	makeDefaultProperty.typeof = (object, pname, wrongtypes, right) =>
		makeDefaultProperty(object, pname, some.equal.typeof.bind(null, wrongtypes), right);

	makeDefaultProperty.belongs = (object, pname, wrongs, right) =>
		makeDefaultProperty(object, pname, some.equal.bind(null, wrongs), right);

	class IterableBase {

		* entries() {
			yield * this;
		}

		forEach(callback) {
			for (let element of this) {
				callback(element, this);
			}
		}

		map(callback) {
			var result = [];
			this.forEach((element) => result.push(callback(element, this)));
			return result;
		}

	}

	function iterable() {
		return new IterableBase();
	}

	iterable.class = IterableBase;

	class DeepIterable extends IterableBase {

		constructor(base, deeper) {
			super();
			this.base = base;
			this.deeper = typeof deeper === 'function' ? deeper : isIterable;
		}

		* [_key_iterator]() {
			var deeper = this.deeper;
			var base = this.base;
			if (deeper(base)) {
				for (let element of base) {
					yield * new DeepIterable(element, deeper);
				}
			} else {
				yield base;
			}
		}

	}

	iterable.deep = (...args) => new DeepIterable(...args);

	iterable.deep.class = DeepIterable;

	function deepJoin(array, separator) {
		return array.map((element) => element instanceof Array ? deepJoin(element, separator) : element).join(separator);
	}

	deepJoin.fromAny = (val, sep) => deepJoin([val], sep);

	deepJoin.many = (sep, ...val) => deepJoin(val, sep);

	function tryCatch(callback, onerror, onsuccess, ...args) {

		var result;

		try {
			result = callback(...args)
		} catch (error) {
			return typeof onerror === 'function' && onerror(error, ...args);
		}

		typeof onsuccess === 'function' && onsuccess(result, ...args);

		return result;

	}

	tryCatch.of = tryCatchOf;

	function tryCatchOf(callback, onerror, onsuccess) {

		if (typeof callback !== 'function') {
			throw new TypeError(`Parameter 'callback' must be a function.`);
		}

		return (...args) =>
			tryCatch(callback, onerror, onsuccess, ...args);

	}

	tryCatchOf.setTimeout = (callback, timeout) => {
		setTimeout((param) => tryCatch(callback, result.onerror, result.onsuccess, param), timeout);
		var result = new tryCatchOf.setTimeout.Return();
		return result;
	};

	tryCatchOf.setTimeout.Return = class {

		constructor() {
			var res = this;
			res.then = (handle) => (res.onsuccess = handle, res);
			res.catch = (handle) => (res.onerror = handle, res);
		}

		onsuccess() {}

		onerror(error) {
			throw error;
		}

	};

	function throwError(error) {
		throw error;
	}

	function createMerelyObject() {
		return new MerelyObject();
	}

	class MerelyObject {

		constructor() {
			this.object = Object.create(null);
		}

		assign(object) {
			Object.assign(this.object, object);
			return this;
		}

		defineProperty(pname, desc) {
			Object.defineProperty(this.object, pname, desc);
			return this;
		}

		makeData(pname, value, writable, enumerable, configurable) {
			this.defineProperty(pname, {
				value: value,
				writable: writable,
				enumerable: enumerable,
				configurable: configurable
			});
			return this;
		}

		makeAccessor(pname, get, set, enumerable, configurable) {
			this.defineProperty({
				get: get,
				set: set,
				enumerable: enumerable,
				configurable: configurable
			});
			return this;
		}

		newFrozen() {
			return Object.freeze(this.createChild());
		}

		createChild() {
			return Object.create(this.object);
		}

		createClass() {
			base.prototype = this.createChild();
			return class extends base {};
			function base() {}
		}

	}

	createMerelyObject.MerelyObject = MerelyObject;

	function clearChildren(element) {
		for ( ; ; ) {
			let child = element.lastChild;
			if (child) {
				child.remove();
			} else {
				break;
			}
		}
	}

})(module);
<commit_msg>add compareSequence<commit_after>
(function (module) {
	'use strict';

	var _key_iterator = Symbol.iterator;

	module.exports = {
		dialog: dialog,
		notice: notice,
		info: notice('info'),
		warn: notice('warning'),
		error: notice('error'),
		chainFunction: chainFunction,
		isIterable: isIterable,
		repeat: repeat,
		some: some,
		forOf: forOf,
		compareSequence: compareSequence,
		makeSubProperty: makeSubProperty,
		ternary: ternary,
		makeDefaultProperty: makeDefaultProperty,
		iterable: iterable,
		deepJoin: deepJoin,
		tryCatch: tryCatch,
		tryCatchOf: tryCatchOf,
		throwError: throwError,
		createMerelyObject: createMerelyObject,
		clearChildren: clearChildren
	};

	function dialog(title) {
		return (message) =>
			setTimeout(alert.bind(null, message, title));
	}

	function notice(type) {
		return (message, detail) =>
			atom.notifications.add(type, message, {detail: detail});
	}

	function chainFunction(fna, fnb) {
		return (...arg) => new chainFunction.Return(fna(...arg), fnb(...arg));
	}

	chainFunction.array = (fnlist) => {
		var fn = () => chainFunction.NOT_AN_ELEMENT;
		for (let fne of fnlist) {
			ensure(fne);
			fn = chainFunction(fn, fne);
		}
		function ensure(fn) {
			if (typeof fn !== 'function') {
				let error = new TypeError(`An element of parameter 'fnlist' is not a function: ${typeof fn} ${tryConvert.forString(fn)}`);
				error.details = {element: fn, array: fnlist};
				throw error;
			}
		}
		return fn;
	}

	chainFunction.Return = class Return extends Array {

		constructor(a, b) {
			if (a instanceof Return) {
				a.push(b);
				return a;
			} else {
				super();
				this.push(a, b);
			}
		}

		push(...args) {
			return super.push(...this.filter((val) => val !== chainFunction.NOT_AN_ELEMENT));
		}

	}

	chainFunction.NOT_AN_ELEMENT = Symbol('NOT_AN_ELEMENT');

	function isIterable(object) {
		return typeof object === 'object' && typeof object[_key_iterator] === 'function';
	}

	function tryConvert(value, type) {
		return tryCatch(() => type(value), (error) => error);
	}

	tryConvert.forString = (value) => tryConvert(value, String);

	tryConvert.forNumber = (value) => tryConvert(value, Number);

	function repeat(action) {
		return new repeat.Return(action);
	}

	repeat.Return = class {

		constructor(action) {
			if (typeof action !== 'function') {
				throw new TypeError(`Parameter 'action' must be a function`)
			}
			this.action = action.bind(null);
		}

		until(isstop) {
			do {
				this.action();
			} while (!isstop());
		}

		times(count) {
			while (count) {
				action(count);
				--count;
			}
		}

	};

	function some(iterable, element, check) {
		for (let el of iterable) {
			if (check(element, el)) {
				return true;
			}
		}
		return false;
	}

	some.equal = (values, value) =>
		some(values, value, some.equal.check);

	some.equal.check = (a, b) => a === b;

	some.equal.typeof = (types, value) =>
		some.equal(types, typeof value);

	some.equiv = (iterable, element, get) =>
		some(iterable, element, equiv.checkOf(get));

	some.equiv.checkOf = (get) =>
		(a, b) => a === get(b);

	some.equiv.forType = (iterable, element, types) =>
		some.equiv(iterable, element, some.equiv.forType.get);

	some.equiv.forType.get = (value) => typeof value;

	function forOf(iterable, callback) {

		var isiter = isIterable(iterable);
		var isfunc = typeof callback === 'function';

		if (isiter && isfunc) {
			return forOf.for.both(iterable, callback);
		}

		if (isiter) {
			return forOf.for.iterable(iterable);
		}

		if (isfunc) {
			return forOf.for.callback(callback);
		}

		throw new TypeError(`Invalid type of arguments.`);

	}

	forOf.gen = function * (iterable, generator) {
		for (let element of iterable) {
			yield * generator(element, iterable);
		}
	}

	forOf.gen.fromCallback = function * (iterable, callback) {
		yield * forOf.gen(iterable, forOf.gen.create(callback));
	}

	forOf.gen.create = (callback) =>
		function * (element, iterable) {
			yield callback(element, iterable);
		}

	forOf.for = (iterable, callback) => {
		for (let element of iterable) {
			callback(element, iterable);
		}
	}

	forOf.for.both = (iterable, callback) =>
		forOf.for.bind(null, iterable, callback);

	forOf.for.iterable = (iterable) =>
		(callback) => forOf.for(iterable, callback);

	forOf.for.callback = (callback) =>
		(iterable) => forOf.for(iterable, callback);

	function compareSequence(a, b) {
		if (a.size !== b.size) {
			return false;
		}
		for (let element of a) {
			if (!b.has(element)) {
				return false;
			}
		}
		return true;
	}

	compareSequence.iterable = (a, b) =>
		compareSequence(new Set(a), new Set(b));

	function makeSubProperty(object, pname, subpname, subval) {
		var sub = object[pname];
		if (some.typeof(['object', 'function'], sub)) {
			sub[subpname] = subval;
		} else {
			object[pname] = {[subpname]: subval};
		}
	}

	function ternary(is, iftrue, iffalse) {
		return (is() ? iftrue : iffalse)();
	}

	ternary.if = (is, act, val) =>
		ternary(is, act, () => val);

	ternary.unless = (is, act, val) =>
		ternary(is, () => val, act);

	ternary.ternary = (is, valiftrue, valiffalse) =>
		ternary(is, () => valiftrue, () => valiffalse);

	ternary.correct = (val, iswrong, getright) =>
		ternary(() => iswrong(val()), getright, val);

	ternary.correct.typeof = (val, wrongtypes, getright) =>
		ternary.correct(val, some.equal.typeof.bind(null, wrongtypes), getright);

	ternary.correct.valof = (val, wrongs, getright) =>
		ternary.correct(val, some.equal.bind(null, wrongs), getright);

	function makeDefaultProperty(object, pname, iswrong, right) {
		if (iswrong(object[pname])) {
			object[pname] = right;
		}
	}

	makeDefaultProperty.typeof = (object, pname, wrongtypes, right) =>
		makeDefaultProperty(object, pname, some.equal.typeof.bind(null, wrongtypes), right);

	makeDefaultProperty.belongs = (object, pname, wrongs, right) =>
		makeDefaultProperty(object, pname, some.equal.bind(null, wrongs), right);

	class IterableBase {

		* entries() {
			yield * this;
		}

		forEach(callback) {
			for (let element of this) {
				callback(element, this);
			}
		}

		map(callback) {
			var result = [];
			this.forEach((element) => result.push(callback(element, this)));
			return result;
		}

	}

	function iterable() {
		return new IterableBase();
	}

	iterable.class = IterableBase;

	class DeepIterable extends IterableBase {

		constructor(base, deeper) {
			super();
			this.base = base;
			this.deeper = typeof deeper === 'function' ? deeper : isIterable;
		}

		* [_key_iterator]() {
			var deeper = this.deeper;
			var base = this.base;
			if (deeper(base)) {
				for (let element of base) {
					yield * new DeepIterable(element, deeper);
				}
			} else {
				yield base;
			}
		}

	}

	iterable.deep = (...args) => new DeepIterable(...args);

	iterable.deep.class = DeepIterable;

	function deepJoin(array, separator) {
		return array.map((element) => element instanceof Array ? deepJoin(element, separator) : element).join(separator);
	}

	deepJoin.fromAny = (val, sep) => deepJoin([val], sep);

	deepJoin.many = (sep, ...val) => deepJoin(val, sep);

	function tryCatch(callback, onerror, onsuccess, ...args) {

		var result;

		try {
			result = callback(...args)
		} catch (error) {
			return typeof onerror === 'function' && onerror(error, ...args);
		}

		typeof onsuccess === 'function' && onsuccess(result, ...args);

		return result;

	}

	tryCatch.of = tryCatchOf;

	function tryCatchOf(callback, onerror, onsuccess) {

		if (typeof callback !== 'function') {
			throw new TypeError(`Parameter 'callback' must be a function.`);
		}

		return (...args) =>
			tryCatch(callback, onerror, onsuccess, ...args);

	}

	tryCatchOf.setTimeout = (callback, timeout) => {
		setTimeout((param) => tryCatch(callback, result.onerror, result.onsuccess, param), timeout);
		var result = new tryCatchOf.setTimeout.Return();
		return result;
	};

	tryCatchOf.setTimeout.Return = class {

		constructor() {
			var res = this;
			res.then = (handle) => (res.onsuccess = handle, res);
			res.catch = (handle) => (res.onerror = handle, res);
		}

		onsuccess() {}

		onerror(error) {
			throw error;
		}

	};

	function throwError(error) {
		throw error;
	}

	function createMerelyObject() {
		return new MerelyObject();
	}

	class MerelyObject {

		constructor() {
			this.object = Object.create(null);
		}

		assign(object) {
			Object.assign(this.object, object);
			return this;
		}

		defineProperty(pname, desc) {
			Object.defineProperty(this.object, pname, desc);
			return this;
		}

		makeData(pname, value, writable, enumerable, configurable) {
			this.defineProperty(pname, {
				value: value,
				writable: writable,
				enumerable: enumerable,
				configurable: configurable
			});
			return this;
		}

		makeAccessor(pname, get, set, enumerable, configurable) {
			this.defineProperty({
				get: get,
				set: set,
				enumerable: enumerable,
				configurable: configurable
			});
			return this;
		}

		newFrozen() {
			return Object.freeze(this.createChild());
		}

		createChild() {
			return Object.create(this.object);
		}

		createClass() {
			base.prototype = this.createChild();
			return class extends base {};
			function base() {}
		}

	}

	createMerelyObject.MerelyObject = MerelyObject;

	function clearChildren(element) {
		for ( ; ; ) {
			let child = element.lastChild;
			if (child) {
				child.remove();
			} else {
				break;
			}
		}
	}

})(module);
<|endoftext|>


<commit_before>"use strict";
var Game = function(canvas, sprites, audio) {
	this.fps = 60;
	var canvas = canvas;
	this.ctx = canvas.getContext("2d");
	this.sprites = sprites;
	this.audio = audio;
	this.backgroundSound = "casanova";

	var worldOptions = {
		width : canvas.width,
		height : canvas.height
	};

	this.world = new World(this.ctx, worldOptions, this.sprites);

	this.world.addPlayer(new Player(this.world, Bullet, this.audio));

	var game = this;

	this.audio[this.backgroundSound].loop();
	this.audio[this.backgroundSound].setVolume(20);
	this.audio[this.backgroundSound].play();

	var gameloop = setInterval(function() {
		collider(game);
		update(game, CatEnemy, Bullet, audio);
		draw(game.world);
	}, 1000 / this.fps);
}
<commit_msg>Update Game.js<commit_after>"use strict";
var Game = function(canvas, sprites, audio) {
	this.fps = 60;
	var canvas = canvas;
	this.ctx = canvas.getContext("2d");
	this.sprites = sprites;
	this.audio = audio;
	this.backgroundSound = "casanova";

	var worldOptions = {
		width : canvas.width,
		height : canvas.height
	};

	this.world = new World(this.ctx, worldOptions, this.sprites);

	this.world.addPlayer(new Player(this.world, Bullet, this.audio));

	var game = this;

	this.audio[this.backgroundSound].loop();
	this.audio[this.backgroundSound].setVolume(20);
	buzz.all.setVolume(20);
	this.audio[this.backgroundSound].play();

	var gameloop = setInterval(function() {
		collider(game);
		update(game, CatEnemy, Bullet, audio);
		draw(game.world);
	}, 1000 / this.fps);
}
<|endoftext|>


<commit_before>module.exports = {
  arraysAreEqual : function(a, b) {
    for(var i = 0; i < a.length; i++){
      if(a[i] !== b[i]) return false;
    }
    return true;
  }
};<commit_msg>Add newline<commit_after>module.exports = {
  arraysAreEqual : function(a, b) {
    for(var i = 0; i < a.length; i++){
      if(a[i] !== b[i]) return false;
    }
    return true;
  }
};
<|endoftext|>


<commit_before>/*!*/
// Copyright 2012 Splunk, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

(function() {
    "use strict";

    var root = exports || this;

    /**
     * Provides various utility functions, which are mostly modeled after
     * [Underscore.js](http://documentcloud.github.com/underscore/).
     *
     * @module splunkjs.Utils
     */

    /**
     * Binds a function to a specific object.
     *
     * @example
     *
     *      var obj = {a: 1, b: function() { console.log(a); }};
     *      var bound = splunkjs.Utils.bind(obj, obj.b);
     *      bound(); // prints 1
     *
     * @param {Object} me The object to bind to.
     * @param {Function} fn The function to bind.
     * @return {Function} The bound function.
     *
     * @function splunkjs.Utils
     */
    root.bind = function(me, fn) {
        return function() {
            return fn.apply(me, arguments);
        };
    };

    /**
     * Strips a string of all leading and trailing whitespace characters.
     *
     * @example
     *
     *      var a = " aaa ";
     *      var b = splunkjs.Utils.trim(a); //== "aaa"
     *
     * @param {String} str The string to trim.
     * @return {String} The trimmed string.
     *
     * @function splunkjs.Utils
     */
    root.trim = function(str) {
        str = str || "";

        if (String.prototype.trim) {
            return String.prototype.trim.call(str);
        }
        else {
            return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        }
    };

    /**
     * Searches an array for a specific object and returns its location.
     *
     * @example
     *
     *      var a = ["a", "b', "c"];
     *      console.log(splunkjs.Utils.indexOf(a, "b")) //== 1
     *      console.log(splunkjs.Utils.indexOf(a, "d")) //== -1
     *
     * @param {Array} arr The array to search in.
     * @param {Anything} search The object to search for.
     * @return {Number} The index of the object (`search`), or `-1` if the object wasn't found.
     *
     * @function splunkjs.Utils
     */
    root.indexOf = function(arr, search) {
        for(var i=0; i<arr.length; i++) {
            if (arr[i] === search) {
                return i;
            }
        }
        return -1;
    };

    /**
     * Indicates whether an array contains a specific object.
     *
     * @example
     *
     *      var a = {a: 3};
     *      var b = [{}, {c: 1}, {b: 1}, a];
     *      var contained = splunkjs.Utils.contains(b, a); // true
     *
     * @param {Array} arr The array to search in.
     * @param {Anything} obj The object to search for.
     * @return {Boolean} `true` if the array contains the object, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.contains = function(arr, obj) {
        arr = arr || [];
        return (root.indexOf(arr, obj) >= 0);
    };

    /**
     * Indicates whether a string starts with a specific prefix.
     *
     * @example
     *
     *      var starts = splunkjs.Utils.startsWith("splunk-foo", "splunk-");
     *
     * @param {String} original The string to search in.
     * @param {String} prefix The prefix to search for.
     * @return {Boolean} `true` if the string starts with the prefix, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.startsWith = function(original, prefix) {
        var matches = original.match("^" + prefix);
        return matches && matches.length > 0 && matches[0] === prefix;
    };

    /**
     * Indicates whether a string ends with a specific suffix.
     *
     * @example
     *
     *      var ends = splunkjs.Utils.endsWith("foo-splunk", "-splunk");
     *
     * @param {String} original The string to search in.
     * @param {String} suffix The suffix to search for.
     * @return {Boolean} `true` if the string ends with the suffix, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.endsWith = function(original, suffix) {
        var matches = original.match(suffix + "$");
        return matches && matches.length > 0 && matches[0] === suffix;
    };

    var toString = Object.prototype.toString;

    /**
     * Converts an iterable to an array.
     *
     * @example
     *
     *      function() {
     *          console.log(arguments instanceof Array); // false
     *          var arr = console.log(splunkjs.Utils.toArray(arguments) instanceof Array); // true
     *      }
     *
     * @param {Arguments} iterable The iterable to convert.
     * @return {Array} The converted array.
     *
     * @function splunkjs.Utils
     */
    root.toArray = function(iterable) {
        return Array.prototype.slice.call(iterable);
    };

    /**
     * Indicates whether an argument is an array.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.isArray(arguments)); // false
     *          console.log(splunkjs.Utils.isArray([1,2,3])); // true
     *      }
     *
     * @param {Anything} obj The argument to evaluate.
     * @return {Boolean} `true` if the argument is an array, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.isArray = Array.isArray || function(obj) {
        return toString.call(obj) === '[object Array]';
    };

    /**
     * Indicates whether an argument is a function.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.isFunction([1,2,3]); // false
     *          console.log(splunkjs.Utils.isFunction(function() {})); // true
     *      }
     *
     * @param {Anything} obj The argument to evaluate.
     * @return {Boolean} `true` if the argument is a function, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.isFunction = function(obj) {
        return !!(obj && obj.constructor && obj.call && obj.apply);
    };

    /**
     * Indicates whether an argument is a number.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.isNumber(1); // true
     *          console.log(splunkjs.Utils.isNumber(function() {})); // false
     *      }
     *
     * @param {Anything} obj The argument to evaluate.
     * @return {Boolean} `true` if the argument is a number, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.isNumber = function(obj) {
        return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed));
    };

    /**
     * Indicates whether an argument is a string.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.isString("abc"); // true
     *          console.log(splunkjs.Utils.isString(function() {})); // false
     *      }
     *
     * @param {Anything} obj The argument to evaluate.
     * @return {Boolean} `true` if the argument is a string, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.isString = function(obj) {
        return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
    };

    /**
     * Indicates whether an argument is an object.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.isObject({abc: "abc"}); // true
     *          console.log(splunkjs.Utils.isObject("abc"); // false
     *      }
     *
     * @param {Anything} obj The argument to evaluate.
     * @return {Boolean} `true` if the argument is an object, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.isObject = function(obj) {
        /*jslint newcap:false */
        return obj === Object(obj);
    };

    /**
     * Indicates whether an argument is empty.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.isEmpty({})); // true
     *          console.log(splunkjs.Utils.isEmpty({a: 1})); // false
     *      }
     *
     * @param {Anything} obj The argument to evaluate.
     * @return {Boolean} `true` if the argument is empty, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.isEmpty = function(obj) {
        if (root.isArray(obj) || root.isString(obj)) {
            return obj.length === 0;
        }

        for (var key in obj) {
            if (this.hasOwnProperty.call(obj, key)) {
                return false;
            }
        }

        return true;
    };

    /**
     * Applies an iterator function to each element in an object.
     *
     * @example
     *
     *      splunkjs.Utils.forEach([1,2,3], function(el) { console.log(el); }); // 1,2,3
     *
     * @param {Object|Array} obj An object or array.
     * @param {Function} iterator The function to apply to each element: `(element, list, index)`.
     * @param {Object} context A context to apply to the function (optional).
     *
     * @function splunkjs.Utils
     */
    root.forEach = function(obj, iterator, context) {
        if (obj === null) {
            return;
        }
        if (Array.prototype.forEach && obj.forEach === Array.prototype.forEach) {
            obj.forEach(iterator, context);
        }
        else if (obj.length === +obj.length) {
            for (var i = 0, l = obj.length; i < l; i++) {
                if (i in obj && iterator.call(context, obj[i], i, obj) === {}) {
                    return;
                }
            }
        }
        else {
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    if (iterator.call(context, obj[key], key, obj) === {}) {
                        return;
                    }
                }
            }
        }
    };

    /**
     * Extends a given object with all the properties from other source objects.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.extend({foo: "bar"}, {a: 2})); // {foo: "bar", a: 2}
     *      }
     *
     * @param {Object} obj The object to extend.
     * @param {Object...} sources The source objects from which to take properties.
     * @return {Object} The extended object.
     *
     * @function splunkjs.Utils
     */
    root.extend = function(obj) {
        root.forEach(Array.prototype.slice.call(arguments, 1), function(source) {
            for (var prop in source) {
                obj[prop] = source[prop];
            }
        });
        return obj;
    };

    /**
     * Creates a shallow-cloned copy of an object or array.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.clone({foo: "bar"})); // {foo: "bar"}
     *          console.log(splunkjs.Utils.clone([1,2,3])); // [1,2,3]
     *      }
     *
     * @param {Object|Array} obj The object or array to clone.
     * @return {Object|Array} The cloned object or array.
     *
     * @function splunkjs.Utils
     */
    root.clone = function(obj) {
        if (!root.isObject(obj)) {
            return obj;
        }
        return root.isArray(obj) ? obj.slice() : root.extend({}, obj);
    };

    /**
     * Extracts namespace information from a dictionary of properties. Namespace
     * information includes values for _owner_, _app_, and _sharing_.
     *
     * @param {Object} props The dictionary of properties.
     * @return {Object} Namespace information from the properties dictionary.
     *
     * @function splunkjs.Utils
     */
    root.namespaceFromProperties = function(props) {
        return {
            owner: props.acl.owner,
            app: props.acl.app,
            sharing: props.acl.sharing
        };
    };

    /**
      * Tests whether a value appears in a given object.
      *
      * @param {Anything} val The value to search for.
      * @param {Object} obj The object to search in.
      *
      * @function splunkjs.Utils
      */
    root.keyOf = function(val, obj) {
        for (var k in obj) {
            if (obj.hasOwnProperty(k) && obj[k] === val) {
                return k;
            }
        }
        return undefined;
    };

    /**
     * Finds a version in a dictionary.
     *
     * @param {String} version The version to search for.
     * @param {Object} map The dictionary to search.
     * @return {Anything} The value of the dictionary at the closest version match.
     *
     * @function splunkjs.Utils
     */
    root.getWithVersion = function(version, map) {
        map = map || {};
        var currentVersion = (version + "") || "";
        while (currentVersion !== "") {
            if (map.hasOwnProperty(currentVersion)) {
                return map[currentVersion];
            }
            else {
                currentVersion = currentVersion.slice(
                    0,
                    currentVersion.lastIndexOf(".")
                );
            }
        }

        return map["default"];
    };

    // TODO: replace this with the underscore object equals function.
    /**
     * Compare 2 objects for deep equality.
     *
     * @param {Object} an object.
     * @param {Object} another object.
     * @return {Boolean} `true` if the objects are equal, `false` if not.
     */
    root.deepEquals = function (actual, expected) {
        var a = [], b = [];
        root.forEach(actual, function (elem, key, obj) {
            a.push(key);
            a.push(elem);
        });
        root.forEach(expected, function (elem, key, obj) {
            b.push(key);
            b.push(elem);
        });

        if (a === b) {
            return true;
        }
        if (a == null || b == null) {
            return false;
        }
        if (a.length !== b.length) {
            return false;
        }

        var areEqual = true;
        a = a.sort();
        b = b.sort();
        root.forEach(actual, function (elem, i, obj) {
            if (a[i] !== b[i]) {
                areEqual =  false;
            }
        });
        return areEqual;
    };
})();<commit_msg>update comment<commit_after>/*!*/
// Copyright 2012 Splunk, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

(function() {
    "use strict";

    var root = exports || this;

    /**
     * Provides various utility functions, which are mostly modeled after
     * [Underscore.js](http://documentcloud.github.com/underscore/).
     *
     * @module splunkjs.Utils
     */

    /**
     * Binds a function to a specific object.
     *
     * @example
     *
     *      var obj = {a: 1, b: function() { console.log(a); }};
     *      var bound = splunkjs.Utils.bind(obj, obj.b);
     *      bound(); // prints 1
     *
     * @param {Object} me The object to bind to.
     * @param {Function} fn The function to bind.
     * @return {Function} The bound function.
     *
     * @function splunkjs.Utils
     */
    root.bind = function(me, fn) {
        return function() {
            return fn.apply(me, arguments);
        };
    };

    /**
     * Strips a string of all leading and trailing whitespace characters.
     *
     * @example
     *
     *      var a = " aaa ";
     *      var b = splunkjs.Utils.trim(a); //== "aaa"
     *
     * @param {String} str The string to trim.
     * @return {String} The trimmed string.
     *
     * @function splunkjs.Utils
     */
    root.trim = function(str) {
        str = str || "";

        if (String.prototype.trim) {
            return String.prototype.trim.call(str);
        }
        else {
            return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        }
    };

    /**
     * Searches an array for a specific object and returns its location.
     *
     * @example
     *
     *      var a = ["a", "b', "c"];
     *      console.log(splunkjs.Utils.indexOf(a, "b")) //== 1
     *      console.log(splunkjs.Utils.indexOf(a, "d")) //== -1
     *
     * @param {Array} arr The array to search in.
     * @param {Anything} search The object to search for.
     * @return {Number} The index of the object (`search`), or `-1` if the object wasn't found.
     *
     * @function splunkjs.Utils
     */
    root.indexOf = function(arr, search) {
        for(var i=0; i<arr.length; i++) {
            if (arr[i] === search) {
                return i;
            }
        }
        return -1;
    };

    /**
     * Indicates whether an array contains a specific object.
     *
     * @example
     *
     *      var a = {a: 3};
     *      var b = [{}, {c: 1}, {b: 1}, a];
     *      var contained = splunkjs.Utils.contains(b, a); // true
     *
     * @param {Array} arr The array to search in.
     * @param {Anything} obj The object to search for.
     * @return {Boolean} `true` if the array contains the object, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.contains = function(arr, obj) {
        arr = arr || [];
        return (root.indexOf(arr, obj) >= 0);
    };

    /**
     * Indicates whether a string starts with a specific prefix.
     *
     * @example
     *
     *      var starts = splunkjs.Utils.startsWith("splunk-foo", "splunk-");
     *
     * @param {String} original The string to search in.
     * @param {String} prefix The prefix to search for.
     * @return {Boolean} `true` if the string starts with the prefix, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.startsWith = function(original, prefix) {
        var matches = original.match("^" + prefix);
        return matches && matches.length > 0 && matches[0] === prefix;
    };

    /**
     * Indicates whether a string ends with a specific suffix.
     *
     * @example
     *
     *      var ends = splunkjs.Utils.endsWith("foo-splunk", "-splunk");
     *
     * @param {String} original The string to search in.
     * @param {String} suffix The suffix to search for.
     * @return {Boolean} `true` if the string ends with the suffix, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.endsWith = function(original, suffix) {
        var matches = original.match(suffix + "$");
        return matches && matches.length > 0 && matches[0] === suffix;
    };

    var toString = Object.prototype.toString;

    /**
     * Converts an iterable to an array.
     *
     * @example
     *
     *      function() {
     *          console.log(arguments instanceof Array); // false
     *          var arr = console.log(splunkjs.Utils.toArray(arguments) instanceof Array); // true
     *      }
     *
     * @param {Arguments} iterable The iterable to convert.
     * @return {Array} The converted array.
     *
     * @function splunkjs.Utils
     */
    root.toArray = function(iterable) {
        return Array.prototype.slice.call(iterable);
    };

    /**
     * Indicates whether an argument is an array.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.isArray(arguments)); // false
     *          console.log(splunkjs.Utils.isArray([1,2,3])); // true
     *      }
     *
     * @param {Anything} obj The argument to evaluate.
     * @return {Boolean} `true` if the argument is an array, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.isArray = Array.isArray || function(obj) {
        return toString.call(obj) === '[object Array]';
    };

    /**
     * Indicates whether an argument is a function.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.isFunction([1,2,3]); // false
     *          console.log(splunkjs.Utils.isFunction(function() {})); // true
     *      }
     *
     * @param {Anything} obj The argument to evaluate.
     * @return {Boolean} `true` if the argument is a function, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.isFunction = function(obj) {
        return !!(obj && obj.constructor && obj.call && obj.apply);
    };

    /**
     * Indicates whether an argument is a number.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.isNumber(1); // true
     *          console.log(splunkjs.Utils.isNumber(function() {})); // false
     *      }
     *
     * @param {Anything} obj The argument to evaluate.
     * @return {Boolean} `true` if the argument is a number, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.isNumber = function(obj) {
        return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed));
    };

    /**
     * Indicates whether an argument is a string.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.isString("abc"); // true
     *          console.log(splunkjs.Utils.isString(function() {})); // false
     *      }
     *
     * @param {Anything} obj The argument to evaluate.
     * @return {Boolean} `true` if the argument is a string, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.isString = function(obj) {
        return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
    };

    /**
     * Indicates whether an argument is an object.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.isObject({abc: "abc"}); // true
     *          console.log(splunkjs.Utils.isObject("abc"); // false
     *      }
     *
     * @param {Anything} obj The argument to evaluate.
     * @return {Boolean} `true` if the argument is an object, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.isObject = function(obj) {
        /*jslint newcap:false */
        return obj === Object(obj);
    };

    /**
     * Indicates whether an argument is empty.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.isEmpty({})); // true
     *          console.log(splunkjs.Utils.isEmpty({a: 1})); // false
     *      }
     *
     * @param {Anything} obj The argument to evaluate.
     * @return {Boolean} `true` if the argument is empty, `false` if not.
     *
     * @function splunkjs.Utils
     */
    root.isEmpty = function(obj) {
        if (root.isArray(obj) || root.isString(obj)) {
            return obj.length === 0;
        }

        for (var key in obj) {
            if (this.hasOwnProperty.call(obj, key)) {
                return false;
            }
        }

        return true;
    };

    /**
     * Applies an iterator function to each element in an object.
     *
     * @example
     *
     *      splunkjs.Utils.forEach([1,2,3], function(el) { console.log(el); }); // 1,2,3
     *
     * @param {Object|Array} obj An object or array.
     * @param {Function} iterator The function to apply to each element: `(element, list, index)`.
     * @param {Object} context A context to apply to the function (optional).
     *
     * @function splunkjs.Utils
     */
    root.forEach = function(obj, iterator, context) {
        if (obj === null) {
            return;
        }
        if (Array.prototype.forEach && obj.forEach === Array.prototype.forEach) {
            obj.forEach(iterator, context);
        }
        else if (obj.length === +obj.length) {
            for (var i = 0, l = obj.length; i < l; i++) {
                if (i in obj && iterator.call(context, obj[i], i, obj) === {}) {
                    return;
                }
            }
        }
        else {
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    if (iterator.call(context, obj[key], key, obj) === {}) {
                        return;
                    }
                }
            }
        }
    };

    /**
     * Extends a given object with all the properties from other source objects.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.extend({foo: "bar"}, {a: 2})); // {foo: "bar", a: 2}
     *      }
     *
     * @param {Object} obj The object to extend.
     * @param {Object...} sources The source objects from which to take properties.
     * @return {Object} The extended object.
     *
     * @function splunkjs.Utils
     */
    root.extend = function(obj) {
        root.forEach(Array.prototype.slice.call(arguments, 1), function(source) {
            for (var prop in source) {
                obj[prop] = source[prop];
            }
        });
        return obj;
    };

    /**
     * Creates a shallow-cloned copy of an object or array.
     *
     * @example
     *
     *      function() {
     *          console.log(splunkjs.Utils.clone({foo: "bar"})); // {foo: "bar"}
     *          console.log(splunkjs.Utils.clone([1,2,3])); // [1,2,3]
     *      }
     *
     * @param {Object|Array} obj The object or array to clone.
     * @return {Object|Array} The cloned object or array.
     *
     * @function splunkjs.Utils
     */
    root.clone = function(obj) {
        if (!root.isObject(obj)) {
            return obj;
        }
        return root.isArray(obj) ? obj.slice() : root.extend({}, obj);
    };

    /**
     * Extracts namespace information from a dictionary of properties. Namespace
     * information includes values for _owner_, _app_, and _sharing_.
     *
     * @param {Object} props The dictionary of properties.
     * @return {Object} Namespace information from the properties dictionary.
     *
     * @function splunkjs.Utils
     */
    root.namespaceFromProperties = function(props) {
        return {
            owner: props.acl.owner,
            app: props.acl.app,
            sharing: props.acl.sharing
        };
    };

    /**
      * Tests whether a value appears in a given object.
      *
      * @param {Anything} val The value to search for.
      * @param {Object} obj The object to search in.
      *
      * @function splunkjs.Utils
      */
    root.keyOf = function(val, obj) {
        for (var k in obj) {
            if (obj.hasOwnProperty(k) && obj[k] === val) {
                return k;
            }
        }
        return undefined;
    };

    /**
     * Finds a version in a dictionary.
     *
     * @param {String} version The version to search for.
     * @param {Object} map The dictionary to search.
     * @return {Anything} The value of the dictionary at the closest version match.
     *
     * @function splunkjs.Utils
     */
    root.getWithVersion = function(version, map) {
        map = map || {};
        var currentVersion = (version + "") || "";
        while (currentVersion !== "") {
            if (map.hasOwnProperty(currentVersion)) {
                return map[currentVersion];
            }
            else {
                currentVersion = currentVersion.slice(
                    0,
                    currentVersion.lastIndexOf(".")
                );
            }
        }

        return map["default"];
    };

    // TODO: replace this with the underscore object equals function. (DVPL-4289)
    /**
     * Compare 2 objects for deep equality.
     *
     * @param {Object} an object.
     * @param {Object} another object.
     * @return {Boolean} `true` if the objects are equal, `false` if not.
     */
    root.deepEquals = function (actual, expected) {
        var a = [], b = [];
        root.forEach(actual, function (elem, key, obj) {
            a.push(key);
            a.push(elem);
        });
        root.forEach(expected, function (elem, key, obj) {
            b.push(key);
            b.push(elem);
        });

        if (a === b) {
            return true;
        }
        if (a == null || b == null) {
            return false;
        }
        if (a.length !== b.length) {
            return false;
        }

        var areEqual = true;
        a = a.sort();
        b = b.sort();
        root.forEach(actual, function (elem, i, obj) {
            if (a[i] !== b[i]) {
                areEqual =  false;
            }
        });
        return areEqual;
    };
})();<|endoftext|>


<commit_before>var controllerDir;

// Get js-controller directory to load libs
function getControllerDir(isInstall) {
    var fs = require('fs');
    // Find the js-controller location
    var controllerDir = __dirname.replace(/\\/g, '/');
    controllerDir = controllerDir.split('/');
    if (controllerDir[controllerDir.length - 3] == 'adapter') {
        controllerDir.splice(controllerDir.length - 3, 3);
        controllerDir = controllerDir.join('/');
    } else if (controllerDir[controllerDir.length - 3] == 'node_modules') {
        controllerDir.splice(controllerDir.length - 3, 3);
        controllerDir = controllerDir.join('/');
        if (fs.existsSync(controllerDir + '/node_modules/iobroker.js-controller')) {
            controllerDir += '/node_modules/iobroker.js-controller';
        } else if (fs.existsSync(controllerDir + '/node_modules/ioBroker.js-controller')) {
            controllerDir += '/node_modules/ioBroker.js-controller';
        } else if (!fs.existsSync(controllerDir + '/controller.js')) {
            if (!isInstall) {
                console.log('Cannot find js-controller');
                process.exit(10);
            } else {
                process.exit();
            }
        }
    } else {
        if (!isInstall) {
            console.log('Cannot find js-controller');
            process.exit(10);
        } else {
            process.exit();
        }
    }
    return controllerDir;
}

// Read controller configuration file
function getConfig() {
    return JSON.parse(fs.readFileSync(controllerDir + '/conf/iobroker.json'));
}
controllerDir = getControllerDir(typeof process != 'undefined' && process.argv && process.argv.indexOf('--install') != -1);

exports.controllerDir = controllerDir;
exports.getConfig =     getConfig;
exports.adapter =       require(controllerDir + '/lib/adapter.js');
<commit_msg>update util.js<commit_after>var controllerDir;
var appName;

function getAppName() {
    var parts = __dirname.replace(/\\/g, '/').split('/');
    return parts[parts.length - 2].split('.')[0];
}

// Get js-controller directory to load libs
function getControllerDir(isInstall) {
    var fs = require('fs');
    // Find the js-controller location
    var controllerDir = __dirname.replace(/\\/g, '/');
    controllerDir = controllerDir.split('/');
    if (controllerDir[controllerDir.length - 3] === 'adapter') {
        controllerDir.splice(controllerDir.length - 3, 3);
        controllerDir = controllerDir.join('/');
    } else if (controllerDir[controllerDir.length - 3] === 'node_modules') {
        controllerDir.splice(controllerDir.length - 3, 3);
        controllerDir = controllerDir.join('/');
        if (fs.existsSync(controllerDir + '/node_modules/' + appName + '.js-controller')) {
            controllerDir += '/node_modules/' + appName + '.js-controller';
        } else if (fs.existsSync(controllerDir + '/node_modules/' + appName.toLowerCase() + '.js-controller')) {
            controllerDir += '/node_modules/' + appName.toLowerCase() + '.js-controller';
        } else if (!fs.existsSync(controllerDir + '/controller.js')) {
            if (!isInstall) {
                console.log('Cannot find js-controller');
                process.exit(10);
            } else {
                process.exit();
            }
        }
    } else {
        if (!isInstall) {
            console.log('Cannot find js-controller');
            process.exit(10);
        } else {
            process.exit();
        }
    }
    return controllerDir;
}

// Read controller configuration file
function getConfig() {
    var fs = require('fs');
    if (fs.existsSync(controllerDir + '/conf/' + appName + '.json')) {
        return JSON.parse(fs.readFileSync(controllerDir + '/conf/' + appName + '.json'));
    } else if (fs.existsSync(controllerDir + '/conf/' + appName.toLowerCase() + '.json')) {
        return JSON.parse(fs.readFileSync(controllerDir + '/conf/' + appName.toLowerCase() + '.json'));
    } else {
        throw new Error('Cannot find ' + controllerDir + '/conf/' + appName + '.json');
    }
}
appName       = getAppName();
controllerDir = getControllerDir(typeof process !== 'undefined' && process.argv && process.argv.indexOf('--install') !== -1);

exports.controllerDir = controllerDir;
exports.getConfig =     getConfig;
exports.adapter =       require(controllerDir + '/lib/adapter.js');
exports.appName =       appName;<|endoftext|>


<commit_before>/*
* Copyright 2017 the Isard-vdi project authors:
*      Josep Maria Viñolas Auquer
*      Alberto Larraz Dalmases
* License: AGPLv3
*/
table={}
$(document).ready(function() {

    table['domains']=$('#domains_tbl').DataTable({
			"ajax": {
				"url": "/admin/updates/domains",
				"dataSrc": ""
			},
			"language": {
				"loadingRecords": 'Loading...',
                "emptyTable": "No updates available"
			},
			"rowId": "id",
			"deferRender": true,
			"columns": [
				{"data": "icon"},
				{ "data": "name"},
				//~ { "data": "description"},
				{
                "className":      'actions-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": '<button id="btn-download" class="btn btn-xs" type="button"  data-placement="top" ></button>'
				},
                ],
			 "order": [[1, 'asc']],
			 "columnDefs": [ {
							"targets": 0,
							"render": function ( data, type, full, meta ) {
                                return 'New'
							  //~ return renderIcon(full);
							}}]

    } );

    $('#domains_tbl').find(' tbody').on( 'click', 'button', function () {
        var data = int_table.row( $(this).parents('tr') ).data();
        console.log($(this).attr('id'),data);
        //~ switch($(this).attr('id')){
            //~ case 'btn-play':
                //~ break;
    });

    table['media']=$('#media_tbl').DataTable({
			"ajax": {
				"url": "/admin/updates/media",
				"dataSrc": ""
			},
			"language": {
				"loadingRecords": 'Loading...',
                "emptyTable": "No updates available"
			},
			"rowId": "id",
			"deferRender": true,
			"columns": [
				{"data": "icon"},
				{ "data": "name"},
				//~ { "data": "description"},
				{
                "className":      'actions-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": '<button id="btn-download" class="btn btn-xs" type="button"  data-placement="top" ></button>'
				},
                ],
			 "order": [[1, 'asc']],
			 "columnDefs": [ {
							"targets": 0,
							"render": function ( data, type, full, meta ) {
							  return renderIcon(full);
							}}]
    } );

    $('#media_tbl').find(' tbody').on( 'click', 'button', function () {
        var data = int_table.row( $(this).parents('tr') ).data();
        console.log($(this).attr('id'),data);
        //~ switch($(this).attr('id')){
            //~ case 'btn-play':
                //~ break;
    });

    table['builders']=$('#builders_tbl').DataTable({
			"ajax": {
				"url": "/admin/updates/builders",
				"dataSrc": ""
			},
			"language": {
				"loadingRecords": 'Loading...',
                "emptyTable": "No updates available"
			},
			"rowId": "id",
			"deferRender": true,
			"columns": [
				{"data": "icon"},
				{ "data": "name"},
				//~ { "data": "description"},
				{
                "className":      'actions-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": '<button id="btn-download" class="btn btn-xs" type="button"  data-placement="top" ></button>'
				},
                ],
			 "order": [[1, 'asc']],
			 "columnDefs": [ {
							"targets": 0,
							"render": function ( data, type, full, meta ) {
							  return renderIcon(full);
							}}]
    } );

    $('#builders_tbl').find(' tbody').on( 'click', 'button', function () {
        var data = int_table.row( $(this).parents('tr') ).data();
        console.log($(this).attr('id'),data);
        //~ switch($(this).attr('id')){
            //~ case 'btn-play':
                //~ break;
    });

    table['virt_builder']=$('#virt_builder_tbl').DataTable({
			"ajax": {
				"url": "/admin/updates/virt_builder",
				"dataSrc": ""
			},
			"language": {
				"loadingRecords": 'Loading...',
                "emptyTable": "No updates available"
			},
			"rowId": "id",
			"deferRender": true,
			"columns": [
				{"data": "icon"},
				{ "data": "name"},
				//~ { "data": "description"},
				{
                "className":      'actions-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": '<button id="btn-download" class="btn btn-xs" type="button"  data-placement="top" ></button>'
				},
                ],
			 "order": [[1, 'asc']],
			 "columnDefs": [ {
							"targets": 0,
							"render": function ( data, type, full, meta ) {
							  return renderIcon(full);
							}}]
    } );

    $('#virt_builder_tbl').find(' tbody').on( 'click', 'button', function () {
        var data = int_table.row( $(this).parents('tr') ).data();
        console.log($(this).attr('id'),data);
        //~ switch($(this).attr('id')){
            //~ case 'btn-play':
                //~ break;
    });

    table['virt_install']=$('#virt_install_tbl').DataTable({
			"ajax": {
				"url": "/admin/updates/virt_install",
				"dataSrc": ""
			},
			"language": {
				"loadingRecords": 'Loading...',
                "emptyTable": "No updates available"
			},
			"rowId": "id",
			"deferRender": true,
			"columns": [
				{"data": "icon"},
				{ "data": "name"},
				//~ { "data": "description"},
				{
                "className":      'actions-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": '<button id="btn-download" class="btn btn-xs" type="button"  data-placement="top" ></button>'
				},
                ],
			 "order": [[1, 'asc']],
			 "columnDefs": [ {
							"targets": 0,
							"render": function ( data, type, full, meta ) {
							  return renderIcon(full);
							}}]
    } );

    $('#virt_install_tbl').find(' tbody').on( 'click', 'button', function () {
        var data = int_table.row( $(this).parents('tr') ).data();
        console.log($(this).attr('id'),data);
        //~ switch($(this).attr('id')){
            //~ case 'btn-play':
                //~ break;
    });

    $('.update').on( 'click', function () {
      id=$(this).attr('id')
      api.ajax('/admin/updates/update/'+id,'POST',{}).done(function(data) {
          console.log(id)
          table[id].ajax.reload();
          //~ if(id == 'virt_install'){virt_install_table.ajax.reload();}
      });
      // invalidate table

    })

});

function renderIcon(data){
		return ''+icon(data.icon)+''
}

function icon(name){
    if(name.startsWith("fa-")){return "";}
    if(name.startsWith("fl-")){return "";}
       if(name=='windows' || name=='linux'){
           return "";
        }else{
            return "";
		}
}
<commit_msg>checks new dowmains<commit_after>/*
* Copyright 2017 the Isard-vdi project authors:
*      Josep Maria Viñolas Auquer
*      Alberto Larraz Dalmases
* License: AGPLv3
*/
table={}
$(document).ready(function() {

    table['domains']=$('#domains_tbl').DataTable({
			"ajax": {
				"url": "/admin/updates/domains",
				"dataSrc": ""
			},
			"language": {
				"loadingRecords": 'Loading...',
                "emptyTable": "No updates available"
			},
			"rowId": "id",
			"deferRender": true,
			"columns": [
				{"data": "icon"},
				{ "data": "name"},
				//~ { "data": "description"},
				{
                "className":      'actions-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": '<button id="btn-download" class="btn btn-xs" type="button"  data-placement="top" ></button>'
				},
                ],
			 "order": [[1, 'asc']],
			 "columnDefs": [ {
							"targets": 0,
							"render": function ( data, type, full, meta ) {
                                if(datata['new']){
                                    return 'New';
                                }else{
                                    return renderIcon(full);
                                }
							}}]

    } );

    $('#domains_tbl').find(' tbody').on( 'click', 'button', function () {
        var data = int_table.row( $(this).parents('tr') ).data();
        console.log($(this).attr('id'),data);
        //~ switch($(this).attr('id')){
            //~ case 'btn-play':
                //~ break;
    });

    table['media']=$('#media_tbl').DataTable({
			"ajax": {
				"url": "/admin/updates/media",
				"dataSrc": ""
			},
			"language": {
				"loadingRecords": 'Loading...',
                "emptyTable": "No updates available"
			},
			"rowId": "id",
			"deferRender": true,
			"columns": [
				{"data": "icon"},
				{ "data": "name"},
				//~ { "data": "description"},
				{
                "className":      'actions-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": '<button id="btn-download" class="btn btn-xs" type="button"  data-placement="top" ></button>'
				},
                ],
			 "order": [[1, 'asc']],
			 "columnDefs": [ {
							"targets": 0,
							"render": function ( data, type, full, meta ) {
							  return renderIcon(full);
							}}]
    } );

    $('#media_tbl').find(' tbody').on( 'click', 'button', function () {
        var data = int_table.row( $(this).parents('tr') ).data();
        console.log($(this).attr('id'),data);
        //~ switch($(this).attr('id')){
            //~ case 'btn-play':
                //~ break;
    });

    table['builders']=$('#builders_tbl').DataTable({
			"ajax": {
				"url": "/admin/updates/builders",
				"dataSrc": ""
			},
			"language": {
				"loadingRecords": 'Loading...',
                "emptyTable": "No updates available"
			},
			"rowId": "id",
			"deferRender": true,
			"columns": [
				{"data": "icon"},
				{ "data": "name"},
				//~ { "data": "description"},
				{
                "className":      'actions-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": '<button id="btn-download" class="btn btn-xs" type="button"  data-placement="top" ></button>'
				},
                ],
			 "order": [[1, 'asc']],
			 "columnDefs": [ {
							"targets": 0,
							"render": function ( data, type, full, meta ) {
							  return renderIcon(full);
							}}]
    } );

    $('#builders_tbl').find(' tbody').on( 'click', 'button', function () {
        var data = int_table.row( $(this).parents('tr') ).data();
        console.log($(this).attr('id'),data);
        //~ switch($(this).attr('id')){
            //~ case 'btn-play':
                //~ break;
    });

    table['virt_builder']=$('#virt_builder_tbl').DataTable({
			"ajax": {
				"url": "/admin/updates/virt_builder",
				"dataSrc": ""
			},
			"language": {
				"loadingRecords": 'Loading...',
                "emptyTable": "No updates available"
			},
			"rowId": "id",
			"deferRender": true,
			"columns": [
				{"data": "icon"},
				{ "data": "name"},
				//~ { "data": "description"},
				{
                "className":      'actions-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": '<button id="btn-download" class="btn btn-xs" type="button"  data-placement="top" ></button>'
				},
                ],
			 "order": [[1, 'asc']],
			 "columnDefs": [ {
							"targets": 0,
							"render": function ( data, type, full, meta ) {
							  return renderIcon(full);
							}}]
    } );

    $('#virt_builder_tbl').find(' tbody').on( 'click', 'button', function () {
        var data = int_table.row( $(this).parents('tr') ).data();
        console.log($(this).attr('id'),data);
        //~ switch($(this).attr('id')){
            //~ case 'btn-play':
                //~ break;
    });

    table['virt_install']=$('#virt_install_tbl').DataTable({
			"ajax": {
				"url": "/admin/updates/virt_install",
				"dataSrc": ""
			},
			"language": {
				"loadingRecords": 'Loading...',
                "emptyTable": "No updates available"
			},
			"rowId": "id",
			"deferRender": true,
			"columns": [
				{"data": "icon"},
				{ "data": "name"},
				//~ { "data": "description"},
				{
                "className":      'actions-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": '<button id="btn-download" class="btn btn-xs" type="button"  data-placement="top" ></button>'
				},
                ],
			 "order": [[1, 'asc']],
			 "columnDefs": [ {
							"targets": 0,
							"render": function ( data, type, full, meta ) {
							  return renderIcon(full);
							}}]
    } );

    $('#virt_install_tbl').find(' tbody').on( 'click', 'button', function () {
        var data = int_table.row( $(this).parents('tr') ).data();
        console.log($(this).attr('id'),data);
        //~ switch($(this).attr('id')){
            //~ case 'btn-play':
                //~ break;
    });

    $('.update').on( 'click', function () {
      id=$(this).attr('id')
      api.ajax('/admin/updates/update/'+id,'POST',{}).done(function(data) {
          console.log(id)
          table[id].ajax.reload();
          //~ if(id == 'virt_install'){virt_install_table.ajax.reload();}
      });
      // invalidate table

    })

});

function renderIcon(data){
		return ''+icon(data.icon)+''
}

function icon(name){
    if(name.startsWith("fa-")){return "";}
    if(name.startsWith("fl-")){return "";}
       if(name=='windows' || name=='linux'){
           return "";
        }else{
            return "";
		}
}
<|endoftext|>


<commit_before>const requestFormatter = (req) => (res) => {
  if (req.query.q) {
    res.query = req.query.q;
    if (res.query.slice(-1) != "?") {
      res.query = res.query + "?";
    }
  }
  return {...res};
};

const dilate = (req) => (s) => (res) => {
  if (req.query.big && req.query.big == 1) {
    res.response =
      res.response.substr(0, 3) +
      s +
      res.response.substr(3, res.response.length - 1);
  }
  return {...res};
};

const getPort = envPort => envPort || 3000;

module.exports = { requestFormatter, dilate, getPort };
<commit_msg>Refactor utils' dilate to return new response<commit_after>const requestFormatter = req => res => {
  if (req.query.q) {
    res.query = req.query.q;
    if (res.query.slice(-1) != "?") {
      res.query = res.query + "?";
    }
  }
  return { ...res };
};

const dilate = req => s => res => {
  const { response } = res;

  return req.query.big == 1
    ? {
        ...res,
        response: `${response.substr(0, 3)}${s}${response.substr(
          3,
          response.length - 1
        )}`
      }
    : { ...res };
};

const getPort = envPort => envPort || 3000;

module.exports = { requestFormatter, dilate, getPort };
<|endoftext|>


<commit_before>function buildPrompt(movies) {
  var promptData = {
      searchResults: movies,
      yesAction  : 'addMovie',
      yesResponse: 'Added ' + movies[0].original_title + ' (' + movies[0].year + ')' + ' to your list of movies to download.'
  };

  if (movies.length > 1) {
    promptData.noAction = 'suggestNextMovie';
    promptData.noResponse = 'Ok, did you mean ' + movies[1].original_title + ' (' + movies[1].year + ')' + '?';
  }
  else {
    promptData.noAction = 'endSession';
    promptData.noResponse = 'Ok. I\'m out of suggestions. Sorry about that.';
  }

  return promptData;
}

function sendSearchResponse(movies, resp) {
  if(!movies || !movies.length) {
    return resp.say('No movie found for ' + movieName).send();
  }

  resp
    .say(['Add', movies[0].original_title, '(' + movies[0].year + ')', 'to your list?'].join(' '))
    .session('promptData', buildPrompt(movies))
    .shouldEndSession(false)
    .send();
}

function formatSearchResults(movies)
{
  try{

    if (movies != undefined)
    {

    var newMovies = [];

  for (var i = 0; i < movies.length; i++)
  { newMovies.push({
    original_title: movies[i].original_title,
    inLibrary: movies[i].in_library,
    year: movies[i].year,
    titles: movies[i].titles,
    imdb: movies[i].imdb });
  }
function formatSearchResults(movies) {

    if (movies != undefined) {

      var newMovies = [];

      for (var i = 0; i < movies.length; i++) {

        newMovies.push({
          original_title: movies[i].original_title,
          inLibrary: isInLibrary(movies[i].in_library),
          year: movies[i].year,
          titles: movies[i].titles,
          imdb: movies[i].imdb
        });

      }

    }

    return newMovies;
}

module.exports = {
  buildPrompt: buildPrompt,
  sendSearchResponse: sendSearchResponse,
  formatSearchResults: formatSearchResults
};

<commit_msg>More formatting fixes<commit_after>function buildPrompt(movies) {
  var promptData = {
      searchResults: movies,
      yesAction  : 'addMovie',
      yesResponse: 'Added ' + movies[0].original_title + ' (' + movies[0].year + ')' + ' to your list of movies to download.'
  };

  if (movies.length > 1) {
    promptData.noAction = 'suggestNextMovie';
    promptData.noResponse = 'Ok, did you mean ' + movies[1].original_title + ' (' + movies[1].year + ')' + '?';
  }
  else {
    promptData.noAction = 'endSession';
    promptData.noResponse = 'Ok. I\'m out of suggestions. Sorry about that.';
  }

  return promptData;
}

function sendSearchResponse(movies, resp) {
  if(!movies || !movies.length) {
    return resp.say('No movie found for ' + movieName).send();
  }

  resp
    .say(['Add', movies[0].original_title, '(' + movies[0].year + ')', 'to your list?'].join(' '))
    .session('promptData', buildPrompt(movies))
    .shouldEndSession(false)
    .send();
}

function formatSearchResults(movies) {

    if (movies != undefined) {

      var newMovies = [];

      for (var i = 0; i < movies.length; i++) {

        newMovies.push({
          original_title: movies[i].original_title,
          inLibrary: isInLibrary(movies[i].in_library),
          year: movies[i].year,
          titles: movies[i].titles,
          imdb: movies[i].imdb
        });

      }

    }

    return newMovies;
}

module.exports = {
  buildPrompt: buildPrompt,
  sendSearchResponse: sendSearchResponse,
  formatSearchResults: formatSearchResults
};

<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Charity = require('../../models/charity')(mongoose);
var aqp = require('api-query-params');
var {filteredObject, isAncestorProperty} = require('../helpers/index');

var latestVersion = 'v0.2.0';

function customiseProjection (projection) {

  var custom = projection || {};

  var privateFields = [];
  var compulsoryFields = ['charityNumber', 'subNumber', 'registered', 'name'];

  // Remove exclusions since projection cannot have a mix of inclusion and exclusion:
  var custom = filteredObject(custom, (key, value) => value===1);

  // Remove projection if it or its (grand-)parent is in privateFields:
  var custom = filteredObject(custom, (key, value) => !privateFields.some(isAncestorProperty(key)));

  // Do not return ID
  custom._id = 0;
  // Always return compulsoryFields
  for (var i=0; i<compulsoryFields.length; i++) {
    custom[compulsoryFields[i]] = 1;
  }

  return custom;
}

function addSearchQuery (query, searchTerm) {
  if (!searchTerm) {
    return;
  }

  // Perform AND text-search on charity name:
  var quotedWords = '"' + searchTerm.split('"').join('').split(' ').join('" "') + '"';
  query.filter["$text"] = { "$search" : quotedWords };
  // Project text-match score:
  query.projection.score = { "$meta" : "textScore" };
  // If no sorting specified, sort by score:
  if (!query.sort) {
    query.sort = {
      score : { "$meta" : "textScore" }
    };
  }
}

function addDefaultSort (query) {
  if (!query.sort) {
    query.sort = {
      charityNumber : 1,
      subNumber: 1
    };
  }
}

function validateLimit(query, defaultLimit, maxLimit) {
  if (query.limit > maxLimit) {
    query.limit = maxLimit;
  } else {
    query.limit = query.limit > 0 ? query.limit : defaultLimit;
  }
}

function validateSkip(query) {
  query.skip = query.skip > -1 ? query.skip : 0;
}

module.exports.getCharities = function (req, res) {

  if (req.params.version!==latestVersion) {
    return res.status(400).send({
      message: `You requested version ${req.params.version} but only the latest version ${latestVersion} is supported`
    });
  }

  var query = aqp.default(req.query, {
    // whitelist only allows filters on these fields (not including their children)
    whitelist: ['charityNumber', 'subNumber', 'registered', 'mainCharity.income']
  });
  // Note: the following accepted query parameters are not processed by aqp: ['search', 'countResults']

  query.projection = customiseProjection(query.projection);

  addSearchQuery(query, req.query.search);

  addDefaultSort(query);

  validateLimit(query, defaultLimit=10, maxLimit=50);

  validateSkip(query);

  return Promise.resolve(
    req.query.hasOwnProperty('countResults')
  )
  .then((countResults) => {
    if (!countResults) {
      return null;
    }
    return Charity
    .count(query.filter)
    .exec(function (err, count) {
      if (err) {
        return res.status(400).send({message: err});
      }
      return count;
    });
  })
  .then((count) => {
    return Charity
    .find(query.filter)
    .select(query.projection)
    .sort(query.sort)
    .skip(query.skip)
    .limit(query.limit)
    .exec(function (err, charities) {
      if (err) {
        return res.status(400).send({message: err});
      }
      return res.send({
        version : latestVersion,
        totalMatches : count,
        query : {
          filter : query.filter,
          projection : query.projection,
          sort : query.sort,
          skip : query.skip,
          limit : query.limit
        },
        charities : charities
      });
    });
  });

}
<commit_msg>refactor validating of query projection<commit_after>var mongoose = require('mongoose');
var Charity = require('../../models/charity')(mongoose);
var aqp = require('api-query-params');
var {filteredObject, isAncestorProperty} = require('../helpers/index');

var latestVersion = 'v0.2.0';

function validateProjection (query) {

  query.projection = query.projection || {};

  var privateFields = [];
  var compulsoryFields = ['charityNumber', 'subNumber', 'registered', 'name'];

  // Remove exclusions since projection cannot have a mix of inclusion and exclusion:
  query.projection = filteredObject(query.projection, (key, value) => value===1);

  // Remove projection if it or its (grand-)parent is in privateFields:
  query.projection = filteredObject(query.projection, (key, value) => !privateFields.some(isAncestorProperty(key)));

  // Do not return ID
  query.projection._id = 0;

  // Always return compulsoryFields
  for (var i=0; i<compulsoryFields.length; i++) {
    query.projection[compulsoryFields[i]] = 1;
  }

}

function addSearchQuery (query, searchTerm) {

  if (!searchTerm) {
    return;
  }

  // Perform AND text-search on charity name:
  var quotedWords = '"' + searchTerm.split('"').join('').split(' ').join('" "') + '"';
  query.filter["$text"] = { "$search" : quotedWords };

  // Project text-match score:
  query.projection.score = { "$meta" : "textScore" };

  // If no sorting specified, sort by score:
  if (!query.sort) {
    query.sort = {
      score : { "$meta" : "textScore" }
    };
  }

}

function addDefaultSort (query) {
  if (!query.sort) {
    query.sort = {
      charityNumber : 1,
      subNumber: 1
    };
  }
}

function validateLimit(query, defaultLimit, maxLimit) {
  if (query.limit > maxLimit) {
    query.limit = maxLimit;
  } else {
    query.limit = query.limit > 0 ? query.limit : defaultLimit;
  }
}

function validateSkip(query) {
  query.skip = query.skip > -1 ? query.skip : 0;
}

module.exports.getCharities = function (req, res) {

  if (req.params.version!==latestVersion) {
    return res.status(400).send({
      message: `You requested version ${req.params.version} but only the latest version ${latestVersion} is supported`
    });
  }

  var query = aqp.default(req.query, {
    // whitelist only allows filters on these fields (not including their children)
    whitelist: ['charityNumber', 'subNumber', 'registered', 'mainCharity.income']
  });
  // Note: the following accepted query parameters are not processed by aqp: ['search', 'countResults']

  validateProjection(query);

  addSearchQuery(query, req.query.search);

  addDefaultSort(query);

  validateLimit(query, defaultLimit=10, maxLimit=50);

  validateSkip(query);

  return Promise.resolve(
    req.query.hasOwnProperty('countResults')
  )
  .then((countResults) => {
    if (!countResults) {
      return null;
    }
    return Charity
    .count(query.filter)
    .exec(function (err, count) {
      if (err) {
        return res.status(400).send({message: err});
      }
      return count;
    });
  })
  .then((count) => {
    return Charity
    .find(query.filter)
    .select(query.projection)
    .sort(query.sort)
    .skip(query.skip)
    .limit(query.limit)
    .exec(function (err, charities) {
      if (err) {
        return res.status(400).send({message: err});
      }
      return res.send({
        version : latestVersion,
        totalMatches : count,
        query : {
          filter : query.filter,
          projection : query.projection,
          sort : query.sort,
          skip : query.skip,
          limit : query.limit
        },
        charities : charities
      });
    });
  });

}
<|endoftext|>


<commit_before>// var dbconn = require('../data/dbconnection.js');
// var ObjectId = require('mongodb').ObjectId;
// var hotelData = require('../data/hotel-data.json');
var mongoose = require('mongoose');
var Hotel = mongoose.model('Hotel');

var runGeoQuery = function(req, res){
  var lng = parseFloat(req.query.lng);
  var lat = parseFloat(req.query.lat);

  // a geoJSON point
  var point = {
    type: "Point",
    coordinates: [lng, lat]
  };

  var geoOptions = {
    spherical: true,
    maxDistance: 99000,
    num: 5
  }

  Hotel
    .geoNear(point, geoOptions, function(err, results, stats){
        console.log("this is geo results: ", results);
        console.log("this is geo stats: ", stats);
        res
          .status(200)
          .json(results);
    });
};

module.exports.hotelsGetAll = function(req,res){

  var start = 0, count = 3; // which hotel to start at and how many to show
  if(req.query && req.query.lat && req.query.lng){
    runGeoQuery(req,res);
    return;
  }

  (req.query.start) ? start = parseInt(req.query.start, 10) : start = 0 ;
  (req.query.count) ? count = parseInt(req.query.count, 10) : count = 5 ;

  Hotel
    .find()
    .skip(start)
    .limit(count)
    .exec(function(err, hotels){
      console.log("Found this many hotels: ", hotels.length);
      res.json(hotels);
    });
  // var db = dbconn.get();
  // var collection = db.collection('hotelCollection');
  // collection
  //   .find()
  //   .skip(start)
  //   .limit(count)
  //   .toArray(function(err, docs){
  //     console.log('found these hotels: ', docs);
  //     res
  //       .status(200)
  //       .json(docs);
  //   });
};

module.exports.hotelsGetOne = function(req,res){
  // var db = dbconn.get();
  // var collection = db.collection('hotelCollection');
  var hotelId = req.params.hotelId; // I named this route in index.js
  console.log("getting one hotel with ID of ", hotelId );

  Hotel
    .findById(hotelId)
    .exec(function(err, doc){
      res
        .status(200)
        .json(doc);
    });
    // .findOne( { _id : ObjectId(hotelId) } , function(err, doc){
    //   res
    //     .status(200)
    //     .json(doc);
    // });
};

// ON lecture 23 09/20/17
module.exports.hotelsAddOne = function(req,res){
  var db = dbconn.get();
  var collection = db.collection('hotelCollection');
  var newHotel;
  console.log('posting new hotel');

  if(req.body && req.body.name && req.body.stars){
    newHotel = req.body;
    newHotel.stars = parseInt(req.body.stars, 10);

    console.log("this is new hotel line 51ish: ", newHotel );
    collection.insertOne(newHotel, function(err, response){
      console.log("response line 53: ",response);
      console.log("response.ops line 54: ", response.ops);

      res
        .status(201)
        .json(response.ops);
    });
  }//if
  else{
    console.log("Data is missing from body");
    res.status(400)
       .json( {message: "required data is missing from body"});
  }

};
<commit_msg>handled errors for hotels all and hotels one, can't see error for hotelsGetOne<commit_after>// var dbconn = require('../data/dbconnection.js');
// var ObjectId = require('mongodb').ObjectId;
// var hotelData = require('../data/hotel-data.json');
var mongoose = require('mongoose');
var Hotel = mongoose.model('Hotel');

var runGeoQuery = function(req, res){
  var lng = parseFloat(req.query.lng);
  var lat = parseFloat(req.query.lat);

  // a geoJSON point
  var point = {
    type: "Point",
    coordinates: [lng, lat]
  };

  var geoOptions = {
    spherical: true,
    maxDistance: 99000,
    num: 5
  }

  Hotel
    .geoNear(point, geoOptions, function(err, results, stats){
        console.log("this is geo results: ", results);
        console.log("this is geo stats: ", stats);
        res
          .status(200)
          .json(results);
    });
};

module.exports.hotelsGetAll = function(req,res){

  var start = 0, count = 3, maxCount = 10; // which hotel to start at and how many to show

  if(req.query && req.query.lat && req.query.lng){
    runGeoQuery(req,res);
    return;
  }

  (req.query.start) ? start = parseInt(req.query.start, 10) : start = 0 ;
  (req.query.count) ? count = parseInt(req.query.count, 10) : count = 5 ;

  if(isNaN(start) || isNaN(count) ){
    res
      .status(400)
      .json( {"message": "start and/or count must be numbers"} );
      return;
  }

  if(count > maxCount){
    res
      .status(400)
      .json({"message": "count limit of " + maxCount + " exceeded"});
      return;
  }

  Hotel
    .find()
    .skip(start)
    .limit(count)
    .exec(function(err, hotels){
      if(err){
        console.log("Error finding hotels, hotels controller: ");
        res
          .status(500)
          .json(err);
      }else{
        console.log("Found this many hotels: ", hotels.length);
        res.json(hotels);
      }
    });//exec
  // var db = dbconn.get();
  // var collection = db.collection('hotelCollection');
  // collection
  //   .find()
  //   .skip(start)
  //   .limit(count)
  //   .toArray(function(err, docs){
  //     console.log('found these hotels: ', docs);
  //     res
  //       .status(200)
  //       .json(docs);
  //   });
};

module.exports.hotelsGetOne = function(req,res){
  var hotelId = req.params.hotelId; // I named this route in index.js
  console.log("getting one hotel with ID of ", hotelId );

  Hotel
    .findById(hotelId)
    .exec(function(err, doc){
      var response = {status: 200, message: doc};
      if(err){
        console.log("Error finding hotel, hotels controller");
        response.status = 500;
        response.message = err;
      }else if(!doc){
        response.status = 404;
        response.message = {"message": "Hotel Id not found, hotels controller"};
      }

      // status and message set above
      // there seems to be a bug seeing the response on error and !doc
      res.status(response.status).json(response.message);

    });
};

// ON lecture 23 09/20/17
module.exports.hotelsAddOne = function(req,res){
  var db = dbconn.get();
  var collection = db.collection('hotelCollection');
  var newHotel;
  console.log('posting new hotel');

  if(req.body && req.body.name && req.body.stars){
    newHotel = req.body;
    newHotel.stars = parseInt(req.body.stars, 10);

    console.log("this is new hotel line 51ish: ", newHotel );
    collection.insertOne(newHotel, function(err, response){
      console.log("response line 53: ",response);
      console.log("response.ops line 54: ", response.ops);

      res
        .status(201)
        .json(response.ops);
    });
  }//if
  else{
    console.log("Data is missing from body");
    res.status(400)
       .json( {message: "required data is missing from body"});
  }

};
<|endoftext|>


<commit_before>"use strict";

var redis = require('redis');
var Promise = require('bluebird');
var _ = require('lodash');

Promise.promisifyAll(redis);

/**
	Instantiates a Redis Redbird backend.

	opts: {
		prefix: '',
		port: 6739,
		host: 'localhost',
		opts: {}
	}
*/
function RedisBackend(opts)
{
	if(!(this instanceof RedisBackend)){
		return new RedisBackend(opts);
	}

	opts = opts || {};

	this.redis = redis.createClient(opts);
	this.publish = redis.createClient(opts);

	this.prefix = opts.prefix + '';

	this.baseKey = baseKey(this.prefix);
}

/**
	Returns a Promise that resolves to an array with all the
	registered services and removes the expired ones.
*/
RedisBackend.prototype.getServices = function(){
	var _this = this;
	var redis = this.redis;
	var baseKey = this.baseKey;

	//
	// Get all members in the service set.
	//
	return redis.smembersAsync(baseKey + 'ids').then(function(serviceIds){
		return Promise.all(_.map(serviceIds, function(id){
			return _this.getService(id);
		}));
	}).then(function(services){
		// Clean expired services
		return _.compact(services);
	});
}

RedisBackend.prototype.getService = function(id){
	var redis = this.redis;
	//
	// Get service hash
	//
	return redis.hgetallAsync(this.baseKey + id).then(function(service){
		if(service){
			return service;
		}else{
			//
			// Service has expired, we must delete it from the service set.
			//
			return redis.sremAsync(id);
		}
	});
}

RedisBackend.prototype.register = function(service){
	var redis = this.redis;
	var publish = this.publish;
	var baseKey = this.baseKey;

	//
	// Get unique service ID.
	//
	return redis.incrAsync(baseKey + 'counter').then(function(id){
		// Store it
		redis.hset(baseKey + id, service).then(function(){
			return id;
		})
	}).then(function(id){
		//
		// // Publish a meesage so that the proxy can react faster to a new registration.
		//
		return publish.publishAsync(baseKey + 'registered', id).then(function(){
			return id;
		})
	});
}

RedisBackend.prototype.ping = function(id){
	return this.redis.pexpireAsync(id, 5000);
}

function baseKey(prefix){
	return 'redbird-' + prefix + '-services-';
}

module.exports = RedisBackend;

<commit_msg>corrected redis initialisation<commit_after>"use strict";

var redis = require('redis');
var Promise = require('bluebird');
var _ = require('lodash');

Promise.promisifyAll(redis);

/**
	Instantiates a Redis Redbird backend.

	opts: {
		prefix: '',
		port: 6739,
		host: 'localhost',
		opts: {}
	}
*/
function RedisBackend(port, hostname, opts)
{
	if(!(this instanceof RedisBackend)){
		return new RedisBackend(opts);
	}

	opts = opts || {};
	port = port || 6379;
	hostname = hostname || 'localhost';

	this.redis = redis.createClient(port, hostname, opts);
	this.publish = redis.createClient(port, hostname, opts);

	this.prefix = opts.prefix + '';

	this.baseKey = baseKey(this.prefix);
}

/**
	Returns a Promise that resolves to an array with all the
	registered services and removes the expired ones.
*/
RedisBackend.prototype.getServices = function(){
	var _this = this;
	var redis = this.redis;
	var baseKey = this.baseKey;

	//
	// Get all members in the service set.
	//
	return redis.smembersAsync(baseKey + 'ids').then(function(serviceIds){
		return Promise.all(_.map(serviceIds, function(id){
			return _this.getService(id);
		}));
	}).then(function(services){
		// Clean expired services
		return _.compact(services);
	});
}

RedisBackend.prototype.getService = function(id){
	var redis = this.redis;
	//
	// Get service hash
	//
	return redis.hgetallAsync(this.baseKey + id).then(function(service){
		if(service){
			return service;
		}else{
			//
			// Service has expired, we must delete it from the service set.
			//
			return redis.sremAsync(id);
		}
	});
}

RedisBackend.prototype.register = function(service){
	var redis = this.redis;
	var publish = this.publish;
	var baseKey = this.baseKey;

	//
	// Get unique service ID.
	//
	return redis.incrAsync(baseKey + 'counter').then(function(id){
		// Store it
		redis.hset(baseKey + id, service).then(function(){
			return id;
		})
	}).then(function(id){
		//
		// // Publish a meesage so that the proxy can react faster to a new registration.
		//
		return publish.publishAsync(baseKey + 'registered', id).then(function(){
			return id;
		})
	});
}

RedisBackend.prototype.ping = function(id){
	return this.redis.pexpireAsync(id, 5000);
}

function baseKey(prefix){
	return 'redbird-' + prefix + '-services-';
}

module.exports = RedisBackend;

<|endoftext|>