<commit_before>(function (stylecow) {
	var Collection = function () {};

	Collection.prototype = Object.create(Array.prototype, {
		children: {
			value: function (match) {
				var result = new Collection;

				for (var i = 0, t = this.length; i < t; ++i) {
					if (this[i].is(match)) {
						result.push(this[i]);
					}
				};

				return result;
			}
		},

		firstChild: {
			value: function (match) {
				for (var i = 0, t = this.length; i < t; ++i) {
					if (this[i].is(match)) {
						return this[i];
					}
				};
			}
		},

		hasChild: {
			value: function (match) {
				return this.some(function (child) {
					return child.is(match);
				});
			}
		},

		search: {
			value: function (match, result) {
				result = result || new Collection;

				for (var i = 0, t = this.length; i < t; i++) {
					if (this[i].is(match)) {
						result.push(this[i]);
					} else {
						this[i].search(match, result);
					}
				}

				return result;
			}
		},

		searchFirst: {
			value: function (match) {
				for (var i = 0, t = this.length; i < t; i++) {
					if (this[i].is(match)) {
						return this[i];
					}

					var found = this[i].searchFirst(match);

					if (found) {
						return found;
					}
				}
			}
		},

		has: {
			value: function (match) {
				for (var i = 0, t = this.length; i < t; i++) {
					if (this[i].is(match) || this[i].has(match)) {
						return true;
					}
				}

				return false;
			}
		}
	});

	stylecow.Base = Object.create(Collection.prototype, {
		executeTasks: {
			value: function (tasks, vendor) {
				if (vendor) {
					if (this.vendor && this.vendor !== vendor) {
						return this.remove();
					}
				} else {
					vendor = this.vendor;
				}

				executeTasks(tasks[this.type + 'Before'], this);

				var k = 0;

				while (this[k]) {
					var child = this[k];

					if (child.executed) {
						++k;
						continue;
					}

					child.executeTasks(tasks, vendor);

					k = 0;
				}

				executeTasks(tasks[this.type], this);

				this.executed = true;
			}
		},

		clone: {
			value: function () {
				var clone = new stylecow[this.type](this.name);

				this.forEach(function (child) {
					clone.push(child.clone());
				});

				clone._data = this._data;

				return clone;
			}
		},

		cloneBefore: {
			value: function () {
				return this.before(this.clone());
			}
		},

		cloneAfter: {
			value: function () {
				return this.after(this.clone());
			}
		},

		is: {
			value: function (match) {
				if (match.type && !equals(this.type, match.type)) {
					return false;
				}

				if (match.name && !equals(this.name, match.name)) {
					return false;
				}

				if (match.value && !equals(this.value, match.value)) {
					return false;
				}

				if (match.vendor && !equals(this.vendor, match.vendor)) {
					return false;
				}

				if (match.string && !equals(this.toString(), match.string)) {
					return false;
				}

				return true;
			}
		},

		parent: {
			value: function (match) {
				if (this._parent) {
					if (!match || this._parent.is(match)) {
						return this._parent;
					}

					return this._parent.parent(match);
				}
			}
		},

		empty: {
			value: function () {
				this.splice(0);

				return this;
			}
		},

		setContent: {
			value: function (content) {
				this.splice(0);

				if (content instanceof Array) {
					content.forEach(function (child) {
						stylecow.parse(child, this);
					}, this);
				} else {
					stylecow.parse(content, this);
				}

				return this;
			}
		},

		getContent: {
			value: function () {
				return this.map(function (child) {
					return child.toString();
				});
			}
		},

		getData: {
			value: function (key) {
				if (('_data' in this) && (key in this._data)) {
					return this._data[key];
				}

				if (this._parent) {
					return this._parent.getData(key);
				}
			}
		},

		setData: {
			value: function (key, value) {
				if (!('_data' in this)) {
					this._data = {};
				}

				this._data[key] = value;

				return this;
			}
		},

		index: {
			value: function () {
				if (this._parent) {
					return this._parent.indexOf(this);
				}

				return -1;
			}
		},

		push: {
			value: function () {
				prepareChildren(this, arguments, 0);

				return Array.prototype.push.apply(this, arguments);
			}
		},

		unshift: {
			value: function () {
				prepareChildren(this, arguments, 0);

				return Array.prototype.unshift.apply(this, arguments);
			}
		},

		splice: {
			value: function () {
				if (arguments.length > 2) {
					prepareChildren(this, arguments, 2);
				}

				return Array.prototype.splice.apply(this, arguments);
			}
		},

		next: {
			value: function () {
				var index = this.index();

				if (index !== -1) {
					return this._parent[index + 1];
				}
			}
		},

		prev: {
			value: function () {
				var index = this.index();

				if (index > 0) {
					return this._parent[index - 1];
				}
			}
		},

		add: {
			value: function (child, index) {
				if (typeof child === 'string') {
					var root = new stylecow[this.type];
					stylecow.parse(child, root);

					if (root._parent) {
						root = root._parent;
					}

					if (index === undefined) {
						this.push.apply(this, root);
					} else {
						this.splice.apply(this, [index, 0].concat(root.slice(0)));
					}

					return root[0];
				}

				if (index === undefined || index > this.length) {
					this.push(child);
				} else {
					this.splice(index, 0, child);
				}

				return child;
			}
		},

		before: {
			value: function (child) {
				var index = this.index();

				if (index !== -1) {
					return this._parent.add(child, index);
				}
			}
		},

		after: {
			value: function (child) {
				var index = this.index();

				if (index !== -1) {
					if (index === this.length) {
						return this._parent.add(child);
					}

					return this._parent.add(child, index + 1);
				}
			}
		},

		replaceWith: {
			value: function (child) {
				var index = this.index();

				if (index !== -1) {
					var parent = this._parent;
					this.remove();

					return parent.add(child, index);
				}
			}
		},

		remove: {
			value: function () {
				if (this._parent) {
					var index = this.index();

					if (index !== -1) {
						this._parent.splice(index, 1);
						this._parent = null;
					}
				}

				this.forEach(function (child) {
					child._parent = null;
					child.remove();
				});

				this.splice(0);

				return this;
			}
		},

		toCode: {
			value: function () {
				return this.toString();
			}
		}
	});

	function prepareChildren (parent, children, from) {
		for (var i = children.length - 1; i >= from; i--) {
			if (children[i]._parent) {
				var index = children[i].index();

				if (index !== -1) {
					children[i]._parent.splice(index, 1);
				}
			}

			children[i]._parent = parent;
		};
	}

	function equals (value, needle) {
		if (needle === true) {
			return value ? true : false;
		}

		if (typeof needle === 'string') {
			return (needle === value);
		}

		if (needle instanceof Array) {
			return (needle.indexOf(value) !== -1);
		}

		if (needle instanceof RegExp) {
			return needle.test(value);
		}

		return true;
	}

	function executeTasks (tasks, element) {
		if (!tasks) {
			return;
		}

		var i, name = element.name;

		if (tasks.hasOwnProperty('*')) {
			for (i = tasks['*'].length - 1; i >= 0; i--) {
				tasks['*'][i](element);
			};
		}

		if (tasks.hasOwnProperty(name)) {
			for (i = tasks[name].length - 1; i >= 0; i--) {
				tasks[name][i](element);
			};
		}
	}

})(require('../index'));
<commit_msg>fixed bug<commit_after>(function (stylecow) {
	var Collection = function () {};

	Collection.prototype = Object.create(Array.prototype, {
		children: {
			value: function (match) {
				var result = new Collection;

				for (var i = 0, t = this.length; i < t; ++i) {
					if (this[i].is(match)) {
						result.push(this[i]);
					}
				};

				return result;
			}
		},

		firstChild: {
			value: function (match) {
				for (var i = 0, t = this.length; i < t; ++i) {
					if (this[i].is(match)) {
						return this[i];
					}
				};
			}
		},

		hasChild: {
			value: function (match) {
				return this.some(function (child) {
					return child.is(match);
				});
			}
		},

		search: {
			value: function (match, result) {
				result = result || new Collection;

				for (var i = 0, t = this.length; i < t; i++) {
					if (this[i].is(match)) {
						result.push(this[i]);
					} else {
						this[i].search(match, result);
					}
				}

				return result;
			}
		},

		searchFirst: {
			value: function (match) {
				for (var i = 0, t = this.length; i < t; i++) {
					if (this[i].is(match)) {
						return this[i];
					}

					var found = this[i].searchFirst(match);

					if (found) {
						return found;
					}
				}
			}
		},

		has: {
			value: function (match) {
				for (var i = 0, t = this.length; i < t; i++) {
					if (this[i].is(match) || this[i].has(match)) {
						return true;
					}
				}

				return false;
			}
		}
	});

	stylecow.Base = Object.create(Collection.prototype, {
		executeTasks: {
			value: function (tasks, vendor) {
				if (vendor) {
					if (this.vendor && this.vendor !== vendor) {
						return this.remove();
					}
				} else {
					vendor = this.vendor;
				}

				executeTasks(tasks[this.type + 'Before'], this);

				var k = 0;

				while (this[k]) {
					var child = this[k];

					if (child.executed) {
						++k;
						continue;
					}

					child.executeTasks(tasks, vendor);

					k = 0;
				}

				executeTasks(tasks[this.type], this);

				this.executed = true;
			}
		},

		clone: {
			value: function () {
				var clone = new stylecow[this.type](this.name);

				this.forEach(function (child) {
					clone.push(child.clone());
				});

				clone._data = this._data;

				return clone;
			}
		},

		cloneBefore: {
			value: function () {
				return this.before(this.clone());
			}
		},

		cloneAfter: {
			value: function () {
				return this.after(this.clone());
			}
		},

		is: {
			value: function (match) {
				if (!match) {
					return true;
				}

				if (match.type && !equals(this.type, match.type)) {
					return false;
				}

				if (match.name && !equals(this.name, match.name)) {
					return false;
				}

				if (match.value && !equals(this.value, match.value)) {
					return false;
				}

				if (match.vendor && !equals(this.vendor, match.vendor)) {
					return false;
				}

				if (match.string && !equals(this.toString(), match.string)) {
					return false;
				}

				return true;
			}
		},

		parent: {
			value: function (match) {
				if (this._parent) {
					if (!match || this._parent.is(match)) {
						return this._parent;
					}

					return this._parent.parent(match);
				}
			}
		},

		empty: {
			value: function () {
				this.splice(0);

				return this;
			}
		},

		setContent: {
			value: function (content) {
				this.splice(0);

				if (content instanceof Array) {
					content.forEach(function (child) {
						stylecow.parse(child, this);
					}, this);
				} else {
					stylecow.parse(content, this);
				}

				return this;
			}
		},

		getContent: {
			value: function () {
				return this.map(function (child) {
					return child.toString();
				});
			}
		},

		getData: {
			value: function (key) {
				if (('_data' in this) && (key in this._data)) {
					return this._data[key];
				}

				if (this._parent) {
					return this._parent.getData(key);
				}
			}
		},

		setData: {
			value: function (key, value) {
				if (!('_data' in this)) {
					this._data = {};
				}

				this._data[key] = value;

				return this;
			}
		},

		index: {
			value: function () {
				if (this._parent) {
					return this._parent.indexOf(this);
				}

				return -1;
			}
		},

		push: {
			value: function () {
				prepareChildren(this, arguments, 0);

				return Array.prototype.push.apply(this, arguments);
			}
		},

		unshift: {
			value: function () {
				prepareChildren(this, arguments, 0);

				return Array.prototype.unshift.apply(this, arguments);
			}
		},

		splice: {
			value: function () {
				if (arguments.length > 2) {
					prepareChildren(this, arguments, 2);
				}

				return Array.prototype.splice.apply(this, arguments);
			}
		},

		next: {
			value: function () {
				var index = this.index();

				if (index !== -1) {
					return this._parent[index + 1];
				}
			}
		},

		prev: {
			value: function () {
				var index = this.index();

				if (index > 0) {
					return this._parent[index - 1];
				}
			}
		},

		add: {
			value: function (child, index) {
				if (typeof child === 'string') {
					var root = new stylecow[this.type];
					stylecow.parse(child, root);

					if (root._parent) {
						root = root._parent;
					}

					if (index === undefined) {
						this.push.apply(this, root);
					} else {
						this.splice.apply(this, [index, 0].concat(root.slice(0)));
					}

					return root[0];
				}

				if (index === undefined || index > this.length) {
					this.push(child);
				} else {
					this.splice(index, 0, child);
				}

				return child;
			}
		},

		before: {
			value: function (child) {
				var index = this.index();

				if (index !== -1) {
					return this._parent.add(child, index);
				}
			}
		},

		after: {
			value: function (child) {
				var index = this.index();

				if (index !== -1) {
					if (index === this.length) {
						return this._parent.add(child);
					}

					return this._parent.add(child, index + 1);
				}
			}
		},

		replaceWith: {
			value: function (child) {
				var index = this.index();

				if (index !== -1) {
					var parent = this._parent;
					this.remove();

					return parent.add(child, index);
				}
			}
		},

		remove: {
			value: function () {
				if (this._parent) {
					var index = this.index();

					if (index !== -1) {
						this._parent.splice(index, 1);
						this._parent = null;
					}
				}

				this.forEach(function (child) {
					child._parent = null;
					child.remove();
				});

				this.splice(0);

				return this;
			}
		},

		toCode: {
			value: function () {
				return this.toString();
			}
		}
	});

	function prepareChildren (parent, children, from) {
		for (var i = children.length - 1; i >= from; i--) {
			if (children[i]._parent) {
				var index = children[i].index();

				if (index !== -1) {
					children[i]._parent.splice(index, 1);
				}
			}

			children[i]._parent = parent;
		};
	}

	function equals (value, needle) {
		if (needle === true) {
			return value ? true : false;
		}

		if (typeof needle === 'string') {
			return (needle === value);
		}

		if (needle instanceof Array) {
			return (needle.indexOf(value) !== -1);
		}

		if (needle instanceof RegExp) {
			return needle.test(value);
		}

		return true;
	}

	function executeTasks (tasks, element) {
		if (!tasks) {
			return;
		}

		var i, name = element.name;

		if (tasks.hasOwnProperty('*')) {
			for (i = tasks['*'].length - 1; i >= 0; i--) {
				tasks['*'][i](element);
			};
		}

		if (tasks.hasOwnProperty(name)) {
			for (i = tasks[name].length - 1; i >= 0; i--) {
				tasks[name][i](element);
			};
		}
	}

})(require('../index'));
<|endoftext|>


<commit_before>const { EventEmitter } = require('events');
const mongodb = require('mongodb');

const Collection = require('./collection');

module.exports = class Database extends EventEmitter {
  constructor(connectionString, options) {
    super();

    if (typeof connectionString == 'string') {
        // Fix short cut connection URLs consisting only of a db name or db + host
        if (connectionString.indexOf('/') < 0) {
          connectionString = 'localhost/' + connectionString
        }

        if (connectionString.indexOf('mongodb://') < 0) {
          connectionString = 'mongodb://' + connectionString
        }
    }

    this.connectionString = connectionString;
    this.options = options;

    // Define the property to not confuse the proxy
    this.connection = null;
  }

  createCollection(name, opts) {
    const cmd = Object.assign({ create: name }, opts);

    return this.runCommand(cmd);
  }

  getCollectionInfos() {
    return this.connect()
      .then(connection => connection.listCollections().toArray())
      .then(collectionInfos => collectionInfos.filter(ci => !ci.name.startsWith('system.')))
  }

  listCollections() {
    return this.getCollectionInfos();
  }

  getCollectionNames() {
    return this.listCollections().then(collections => collections.map((collection) => collection.name));
  }

  runCommand(opts) {
    if (typeof opts === 'string') {
      opts = {
        [opts]: 1 };
    }

    return this
      .connect()
      .then(connection => connection.command(opts));
  }

  stats(scale) {
    return this.runCommand({ dbStats: 1, scale: scale });
  }

  createUser(usr) {
    const cmd = Object.assign({ createUser: usr.user }, usr);
    delete cmd.user;

    return this.runCommand(cmd);
  }

  dropUser(username) {
    return this.runCommand({ dropUser: username });
  }

  dropAllUsers() {
    return this.runCommand({ dropAllUsersFromDatabase: 1 });
  }

  dropDatabase() {
    return this.runCommand('dropDatabase');
  }

  getLastErrorObj() {
    return this.runCommand('getLastError');
  }

  getLastError() {
    return this
      .runCommand('getLastError')
      .then(res => res.err);
  }

  connect() {
    if (this.connection) {
      return Promise.resolve(this.connection);
    }

    if (typeof this.connectionString == 'string') {
      return mongodb.MongoClient
        .connect(this.connectionString, this.options)
        .then(connection => {
          this.connection = connection;
          this.emit('connect');

          return connection;
        })
        .catch(e => {
          this.emit('error', e);

          throw e;
        });
    } else if (typeof this.connectionString._getConnection === 'function') { // mongojs
      return new Promise((resolve, reject) => {
        this.connectionString._getConnection((err, connection) => {
          if (err) { return reject(err); }

          this.connection = connection;
          this.emit('connect');

          resolve(connection);
        });
      });
    }
  }

  close(force) {
    return this
      .connect()
      .then(connection => connection.close(force));
  }

  collection(collection) {
    return new Collection(this, collection);
  }
}<commit_msg>fix: always create a non undefined options field<commit_after>const { EventEmitter } = require('events');
const mongodb = require('mongodb');

const Collection = require('./collection');

module.exports = class Database extends EventEmitter {
  constructor(connectionString, options) {
    super();

    if (typeof connectionString == 'string') {
        // Fix short cut connection URLs consisting only of a db name or db + host
        if (connectionString.indexOf('/') < 0) {
          connectionString = 'localhost/' + connectionString
        }

        if (connectionString.indexOf('mongodb://') < 0) {
          connectionString = 'mongodb://' + connectionString
        }
    }

    this.connectionString = connectionString;
    this.options = options || {};

    // Define the property to not confuse the proxy
    this.connection = null;
  }

  createCollection(name, opts) {
    const cmd = Object.assign({ create: name }, opts);

    return this.runCommand(cmd);
  }

  getCollectionInfos() {
    return this.connect()
      .then(connection => connection.listCollections().toArray())
      .then(collectionInfos => collectionInfos.filter(ci => !ci.name.startsWith('system.')))
  }

  listCollections() {
    return this.getCollectionInfos();
  }

  getCollectionNames() {
    return this.listCollections().then(collections => collections.map((collection) => collection.name));
  }

  runCommand(opts) {
    if (typeof opts === 'string') {
      opts = {
        [opts]: 1 };
    }

    return this
      .connect()
      .then(connection => connection.command(opts));
  }

  stats(scale) {
    return this.runCommand({ dbStats: 1, scale: scale });
  }

  createUser(usr) {
    const cmd = Object.assign({ createUser: usr.user }, usr);
    delete cmd.user;

    return this.runCommand(cmd);
  }

  dropUser(username) {
    return this.runCommand({ dropUser: username });
  }

  dropAllUsers() {
    return this.runCommand({ dropAllUsersFromDatabase: 1 });
  }

  dropDatabase() {
    return this.runCommand('dropDatabase');
  }

  getLastErrorObj() {
    return this.runCommand('getLastError');
  }

  getLastError() {
    return this
      .runCommand('getLastError')
      .then(res => res.err);
  }

  connect() {
    if (this.connection) {
      return Promise.resolve(this.connection);
    }

    if (typeof this.connectionString == 'string') {
      return mongodb.MongoClient
        .connect(this.connectionString, this.options)
        .then(connection => {
          this.connection = connection;
          this.emit('connect');

          return connection;
        })
        .catch(e => {
          this.emit('error', e);

          throw e;
        });
    } else if (typeof this.connectionString._getConnection === 'function') { // mongojs
      return new Promise((resolve, reject) => {
        this.connectionString._getConnection((err, connection) => {
          if (err) { return reject(err); }

          this.connection = connection;
          this.emit('connect');

          resolve(connection);
        });
      });
    }
  }

  close(force) {
    return this
      .connect()
      .then(connection => connection.close(force));
  }

  collection(collection) {
    return new Collection(this, collection);
  }
}<|endoftext|>


<commit_before>/**
 * @overview Database Lib
 * @module database
 * @author Dominik Sigmund
 * @version 0.1
 * @description Positions Images on Layouts
 * @memberof resilienz
 * @requires module:mysql
 */

function Database (config) {
  var self = {}
  self.config = config
  self.mysql = require('mysql')
  self.connection = self.mysql.createConnection(self.config)
  self.connection.connect()
  self.getUsers = getUsers
  self.getUser = getUser
  self.addUser = addUser
  self.actionFinalize = actionFinalize
  self.getActions = getActions
  self.getLanguages = getLanguages
  self.getTranslations = getTranslations
  self.getLayoutInfo = getLayoutInfo
  self.close = close
  return self
}

function getUsers (callback) {
  var self = this
  self.connection.query('SELECT vorname, nachname, email, language, location FROM userList', function (error, results, fields) {
    if (error) {
      callback(error)
    } else {
      callback(null, results)
    }
  })
}
function getUser (email, callback) {
  var self = this
  self.connection.query('SELECT id, email, language, action_id, admin FROM userList WHERE email="' + email + '" LIMIT 1', function (error, results, fields) {
    if (error) {
      callback(error)
    } else {
      callback(null, results[0])
    }
  })
}
function addUser (data, callback) {
  var self = this
  // TODO: add to database (actions and user)
  /*self.connection.query('SELECT id, email, language, action_id, admin FROM userList WHERE email="' + email + '" LIMIT 1', function (error, results, fields) {
    if (error) {
      callback(error)
    } else {
      callback(null, results[0])
    }
  })*/
}
function actionFinalize (id, callback) {
  var self = this
  self.connection.query('UPDATE actions SET finalized=1 WHERE id=' + id, function (error, results, fields) {
    if (error) {
      callback(error)
    } else {
      callback(null, results)
    }
  })
}

function getActions (callback) {
  var self = this
  self.connection.query('SELECT email, language, location, start_time, end_time, finalized FROM actionList', function (error, results, fields) {
    if (error) {
      callback(error)
    } else {
      callback(null, results)
    }
  })
}
function getLanguages (callback) {
  var self = this
  self.connection.query('SELECT lang_key AS key, name FROM languages', function (error, results, fields) {
    if (error) {
      callback(error)
    } else {
      callback(null, results)
    }
  })
}
function getTranslations (callback) {
  var self = this
  self.connection.query('SELECT language_key, string_key, translation FROM resilienz.language_translations ORDER BY language_key ASC, string_key ASC', function (error, results, fields) {
    if (error) {
      callback(error)
    } else {
      var translations = {}
      for (var i = 0; i < results.length; i++) {
        if (!translations[results[i][0]]) {
          translations[results[i][0]] = {}
        }
        translations[results[i][0]][results[i][1]] = results[i][2]
      }
      console.log(translations)
      callback(null, translations)
    }
  })
}

function getLayoutInfo (actionid, page, callback) { // return array of information.{width, height, x, y, imagefile, layoutfile}
  var self = this
  self.connection.query('SELECT 1', function (error, results, fields) { // TODO Write SQL Query for getLayoutInfo
    if (error) {
      callback(error)
    } else {
      var arr = []
      for (var i = 0; i < results.length; i++) {
        var info = {}
        info.width = results[i][0]
      // TODO add rest of cols to array. if no image, doesnt matter
        arr.push(info)
      }
      callback(null, arr)
    }
  })
}
function close (callback) {
  this.connection.destroy()
  callback()
}
module.exports = Database
<commit_msg>fixed db error<commit_after>/**
 * @overview Database Lib
 * @module database
 * @author Dominik Sigmund
 * @version 0.1
 * @description Positions Images on Layouts
 * @memberof resilienz
 * @requires module:mysql
 */

function Database (config) {
  var self = {}
  self.config = config
  self.mysql = require('mysql')
  self.connection = self.mysql.createConnection(self.config)
  self.connection.connect()
  self.getUsers = getUsers
  self.getUser = getUser
  self.addUser = addUser
  self.actionFinalize = actionFinalize
  self.getActions = getActions
  self.getLanguages = getLanguages
  self.getTranslations = getTranslations
  self.getLayoutInfo = getLayoutInfo
  self.close = close
  return self
}

function getUsers (callback) {
  var self = this
  self.connection.query('SELECT vorname, nachname, email, language, location FROM userList', function (error, results, fields) {
    if (error) {
      callback(error)
    } else {
      callback(null, results)
    }
  })
}
function getUser (email, callback) {
  var self = this
  self.connection.query('SELECT id, email, language, action_id, admin FROM userList WHERE email="' + email + '" LIMIT 1', function (error, results, fields) {
    if (error) {
      callback(error)
    } else {
      callback(null, results[0])
    }
  })
}
function addUser (data, callback) {
  var self = this
  // TODO: add to database (actions and user)
  /*self.connection.query('SELECT id, email, language, action_id, admin FROM userList WHERE email="' + email + '" LIMIT 1', function (error, results, fields) {
    if (error) {
      callback(error)
    } else {
      callback(null, results[0])
    }
  })*/
}
function actionFinalize (id, callback) {
  var self = this
  self.connection.query('UPDATE actions SET finalized=1 WHERE id=' + id, function (error, results, fields) {
    if (error) {
      callback(error)
    } else {
      callback(null, results)
    }
  })
}

function getActions (callback) {
  var self = this
  self.connection.query('SELECT email, language, location, start_time, end_time, finalized FROM actionList', function (error, results, fields) {
    if (error) {
      callback(error)
    } else {
      callback(null, results)
    }
  })
}
function getLanguages (callback) {
  var self = this
  self.connection.query('SELECT lang_key AS key, name FROM languages', function (error, results, fields) {
    if (error) {
      callback(error)
    } else {
      callback(null, results)
    }
  })
}
function getTranslations (callback) {
  var self = this
  self.connection.query('SELECT language_key, string_key, translation FROM resilienz.language_translations ORDER BY language_key ASC, string_key ASC', function (error, results, fields) {
    if (error) {
      callback(error)
    } else {
      var translations = {}
      for (var i = 0; i < results.length; i++) {
        if (!translations[results[i]['language_key']]) {
          translations[results[i]['language_key']] = {}
        }
        translations[results[i]['language_key']][results[i]['string_key']] = results[i]['translation']
      }
      callback(null, translations)
    }
  })
}

function getLayoutInfo (actionid, page, callback) { // return array of information.{width, height, x, y, imagefile, layoutfile}
  var self = this
  self.connection.query('SELECT 1', function (error, results, fields) { // TODO Write SQL Query for getLayoutInfo
    if (error) {
      callback(error)
    } else {
      var arr = []
      for (var i = 0; i < results.length; i++) {
        var info = {}
        info.width = results[i][0]
      // TODO add rest of cols to array. if no image, doesnt matter
        arr.push(info)
      }
      callback(null, arr)
    }
  })
}
function close (callback) {
  this.connection.destroy()
  callback()
}
module.exports = Database
<|endoftext|>


<commit_before>'use strict';
var request = require('request')
    ;

// Private
var b = 2;
function sum(x, y) {
    return x + y;
}

// Public
module.exports = {
    // compile CSDL
    compile: function(csdl, cb){

        var encCsdl = 'csdl='+encodeURIComponent(csdl);
        var options = {
            method: 'POST',
            body: encCsdl,
            uri: 'http://api.datasift.com/v1/compile',
            headers: {
                'Authorization': 'un:api',
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        };

        // handle response
        function callback(error, response, body) {

            /*
            if (!error && response.statusCode === 200) {
                cb(false, body);
            } else {
                cb(false, response.body);
            }*/

            if(error){
                cb(false, error, body);
            } else {
                cb(false, response, body);
            }
        }

        request.post(options, callback);
    }
};<commit_msg>DS test template.<commit_after>'use strict';
var request = require('request')
    config = require('./test/config.json')
    ;

// Private
var un = config.ds_username;
var key = config.ds_api_key;

// Public
module.exports = {
    // compile CSDL
    compile: function(csdl, cb){

        var encCsdl = 'csdl='+encodeURIComponent(csdl);
        var options = {
            method: 'POST',
            body: encCsdl,
            uri: 'http://api.datasift.com/v1/compile',
            headers: {
                'Authorization': un+':'+key,
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        };

        // handle response
        function callback(error, response, body) {

            /*
            if (!error && response.statusCode === 200) {
                cb(false, body);
            } else {
                cb(false, response.body);
            }*/

            if(error){
                cb(false, error, body);
            } else {
                cb(false, response, body);
            }
        }

        request.post(options, callback);
    }
};<|endoftext|>


<commit_before>const mysql = require('mysql');
var async = require('async');

var insertAssoc = function(dbConnection, assoc, idFilm, idAssoc, relevancePosition, cb) {
    assoc = assoc.charAt(0).toUpperCase() + assoc.slice(1).toLowerCase();

    const query = 'INSERT INTO assocFilm' + assoc + ' VALUES(' +
            idFilm + ', ' +
            idAssoc +', ' +
            relevancePosition +
            ')' +
            ' ON DUPLICATE KEY UPDATE' +
            ' idFilm = VALUES(idFilm),' +
            ' id' + assoc + ' = VALUES(id' + assoc + '),' +
            ' relevancePosition = ' + relevancePosition
        ;

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var importAssoc = function (dbConnection, assoc, film, cb) {
    if ((!film[assoc] || !film[assoc].length)) {
        cb();
        return;
    }

    if (film[assoc]) {
        var itemsProcessed = 0;

        film[assoc].forEach(function(assocElement, index, array) {
            const queryInsert = 'INSERT INTO ' + assoc + ' VALUES(' +
                    '0,' +
                    mysql.escape(assocElement) +
                    ')'
                ;

            dbConnection.query(queryInsert, function (err, resultInsert) {
                var relevancePosition = index;

                if (err) {
                    if (err.code == 'ER_DUP_ENTRY') {
                        const querySelect = 'SELECT id' + assoc + ' FROM ' + assoc + ' WHERE name = ' + mysql.escape(assocElement);
                        dbConnection.query(querySelect, function (err, resultSelect) {
                            if (err || resultSelect == undefined) {
                                global.log.error(querySelect);
                                global.log.error(resultSelect);
                                throw err;
                            }

                            insertAssoc(dbConnection, assoc, film.id, resultSelect[0]['id' + assoc], relevancePosition, function() {
                                itemsProcessed++;

                                if(itemsProcessed === array.length) {
                                    cb();
                                }
                            });
                        });
                    } else {
                        global.log.error(queryInsert);
                        throw err;
                    }
                } else {
                    insertAssoc(dbConnection, assoc, film.id, resultInsert.insertId, relevancePosition, function() {
                        itemsProcessed++;

                        if(itemsProcessed === array.length) {
                            cb();
                        }
                    });
                }
            });
        });
    }
};

var importFilm = function (dbConnection, film, cb) {
    const queryNewFilm = 'INSERT INTO film VALUES(' +
            film.id + ',' +
            mysql.escape(film.title) + ',' +
            mysql.escape(film.originalTitle) + ',' +
            film.year + ',' +
            film.duration + ',' +
            mysql.escape(film.country) + ',' +
            mysql.escape(film.producer) + ',' +
            'NULL,' +
            mysql.escape(film.synopsis) + ',' +
            mysql.escape(JSON.stringify(film.proReviews)) + ',' +
            film.rating + ',' +
            film.numRatings + ', ' +
            0 + ', ' +
            'UNIX_TIMESTAMP()' +
            ')' +
            ' ON DUPLICATE KEY UPDATE' +
            ' title = VALUES(title),' +
            ' originalTitle = VALUES(originalTitle),' +
            ' year = VALUES(year),' +
            ' duration = VALUES(duration),' +
            ' country = VALUES(country),' +
            ' producer = VALUES(producer),' +
            ' awards = VALUES(awards),' +
            ' synopsis = VALUES(synopsis),' +
            ' proReviews = VALUES(proReviews),' +
            ' rating = VALUES(rating),' +
            ' numRatings = VALUES(numRatings),' +
            ' numFrames = VALUES(numFrames),' +
            ' dateUpdated = UNIX_TIMESTAMP()'
        ;

    global.log.info('***** Importing film to DB: ' + film.id);

    dbConnection.query(queryNewFilm, function (err) {
        if (err) {
            global.log.error(queryNewFilm);
            throw err;
        }

        var assoc = ['director', 'actor', 'screenplayer', 'musician', 'cinematographer', 'genre', 'topic'];
        var assocProcessed = 0;

        assoc.forEach(function(assocName) {
            importAssoc(dbConnection, assocName, film, function() {
                assocProcessed++;

                if(assocProcessed == assoc.length) {
                    cb();
                }
            });
        });
    });
};

var importUserFilmReview = function (dbConnection, filmId, review, cb) {
    const query = 'INSERT INTO userReview  VALUES(' +
      review.userId + ',' +
      filmId + ',' +
      mysql.escape(review.username) + ', ' +
      review.rating + ',' +
      mysql.escape(review.title) + ', ' +
      mysql.escape(review.reviewText) + ', ' +
      mysql.escape(review.spoiler) + ', ' +
      review.position + ',' +
      review.datePublished.getTime() / 1000 +
      ')' +
      ' ON DUPLICATE KEY UPDATE' +
      ' username = ' + mysql.escape(review.username) + ', ' +
      ' rating = ' + review.rating + ', ' +
      ' title = ' + mysql.escape(review.title) + ', ' +
      ' review = ' + mysql.escape(review.reviewText) + ', ' +
      ' spoiler = ' + mysql.escape(review.spoiler) + ', ' +
      ' position = ' + review.position
    ;

    global.log.info('***** Inserting into userReview: ' + filmId + '|' + review.userId);

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            console.log('ERROR in query: ');
            console.log(query);
            throw err;
        }

        cb();
    });
};

var updateFilmNumFrames = function (dbConnection, filmId, numFrames, cb) {
    const query = 'UPDATE film SET numFrames = ' + numFrames + ' WHERE idFilm = ' + filmId;

    dbConnection.query(query, function (err, result) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb(result);
    });
};

var filmExistsInDb = function (dbConnection, filmId, cb) {
    const queryFilmExists = 'SELECT idFilm FROM film WHERE idFilm = ' + filmId;

    dbConnection.query(queryFilmExists, function (err, result) {
        if (err) {
            global.log.error(queryFilmExists);
            throw err;
        }

        cb(result.length ? true : false);
    });
};

var insertFailedCrawlFilm = function (dbConnection, filmId, cb) {
    const query = 'INSERT INTO failedCrawlFilm VALUES(' +
            filmId +
            ')' +
            ' ON DUPLICATE KEY UPDATE' +
            ' idFilm = VALUES(idFilm)'
        ;

    global.log.info('***** Inserting into failedCrawlFilm: ' + filmId);

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var getFailedCrawlFilm = function (dbConnection, cb) {
    const query = 'SELECT idFilm FROM failedCrawlFilm';

    dbConnection.query(query, function (err, result) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb(result);
    });
};

var deleteFailedCrawlFilm = function (dbConnection, idFilm, cb) {
    const query = 'DELETE FROM failedCrawlFilm WHERE idFilm = ' + idFilm;

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var insertFilmInTheatres = function (dbConnection, film, cb) {
    const query = 'INSERT INTO filmInTheatres VALUES(' +
        film.id + ',' +
        mysql.escape(film.releaseDate) +
        ')'
    ;

    global.log.info('***** Inserting into filmInTheatres: ' + film.id + '|' + film.releaseDate);

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var clearFilmInTheatres = function (dbConnection, cb) {
    const query = 'TRUNCATE filmInTheatres';

    global.log.info('***** Truncating filmInTheatres');

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var insertFilmPopular = function (dbConnection, film, cb) {
    const query = 'INSERT INTO filmPopular VALUES(' +
        film.id + ',' +
        mysql.escape(film.position) +
        ')'
    ;

    global.log.info('***** Inserting into filmPopular: ' + film.id + '|' + film.position);

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var clearFilmPopular = function (dbConnection, cb) {
    const query = 'TRUNCATE filmPopular';

    global.log.info('***** Truncating filmPopular');

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var getUser = function (dbConnection, userId, cb) {
    const query = 'SELECT * FROM user WHERE idUser = ' + userId;

    dbConnection.query(query, function (err, result) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb(result);
    });
};

var insertUser = function (dbConnection, user, cb) {
    const query = 'INSERT INTO user (`idUser`, `name`, `dateAdded`) VALUES(' +
      user.id + ',' +
      mysql.escape(user.name) + ', ' +
      'UNIX_TIMESTAMP()' +
      ')' +
      ' ON DUPLICATE KEY UPDATE' +
      ' idUser = VALUES(idUser), ' +
      ' name = ' + mysql.escape(user.name) + ', ' +
      ' dateUpdated = UNIX_TIMESTAMP()'
    ;

    global.log.info('***** Inserting into user: ' + user.id + '|' + user.name);

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var insertUserFriendship = function (dbConnection, userIdSource, userIdTarget, cb) {
    const query = 'INSERT INTO userFriendship VALUES(' +
      userIdSource + ',' +
      userIdTarget +
      ')' +
      ' ON DUPLICATE KEY UPDATE' +
      ' idUserSource = VALUES(idUserSource)'
    ;

    global.log.info('***** Inserting into userFriendship: ' + userIdSource + '|' + userIdTarget);

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var userRatingExists = function (dbConnection, userId, filmId, rating, cb) {
    const query = 'SELECT idUserRating FROM userRating ' +
      ' WHERE idUser = ' + userId +
      ' AND idFilm = ' + filmId +
      ' AND rating = ' + rating;

    dbConnection.query(query, function (err, result) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        let ratingExists = false;
        if (result.length) {
            ratingExists = !!result[0].idUserRating;
        }

        cb(ratingExists);
    });
};

var insertUserRating = function (dbConnection, userId, film, cb) {
    userRatingExists(dbConnection, userId, film.id, film.rating, function(ratingExists) {
        if (ratingExists) {
            // global.log.info('***** Rating already exists: ' + userId + '|' + film.id + '|' + film.rating);
            cb();
            return;
        }

        /**
         * If we get here, it means either the rating is new (then we insert),
         * or user has updated the rating to some of the films (then we update on duplicate user/film)
         */
        const query = 'INSERT INTO userRating VALUES(0, ' +
          userId + ',' +
          film.id + ',' +
          film.rating + ',' +
          film.ratingDate.getTime() / 1000 + ',' +
          film.position +
          ')' +
          ' ON DUPLICATE KEY UPDATE' +
          ' rating = ' + film.rating + ',' +
          ' dateRated = ' + film.ratingDate.getTime() / 1000  + ',' +
          ' position = ' + film.position
        ;

        global.log.info('***** Inserting into userRating: ' + userId + '|' + film.id);

        dbConnection.query(query, function (err) {
            if (err) {
                global.log.error(query);
                throw err;
            }

            cb();
        });
    });
};

var getLastFriendIdUserRating = function (dbConnection, userId, cb) {
    const query = 'SELECT ur.idUserRating FROM userRating ur ' +
      ' JOIN userFriendship uf ON uf.idUserTarget = ur.idUser' +
      ' WHERE uf.idUserSource = ' + userId +
      ' ORDER BY idUserRating DESC' +
      ' LIMIT 1';

    dbConnection.query(query, function (err, result) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        let idUserRating = null;
        if (result.length) {
            idUserRating = result[0].idUserRating;
        }

        cb(idUserRating);
    });
};

var setUserLastRatingNotification = function (dbConnection, userId, cb) {
    getLastFriendIdUserRating(dbConnection, userId, function(idUserRating) {
        if (!idUserRating) {
            cb();
            return;
        }

        const query = 'INSERT INTO userLastRatingNotificated VALUES(' +
          userId + ',' +
          idUserRating +
          ')' +
          ' ON DUPLICATE KEY UPDATE' +
          ' idUserRating = ' + idUserRating
        ;

        global.log.info('***** Inserting into userLastRatingNotification: ' + userId + '|' + idUserRating);

        dbConnection.query(query, function (err) {
            if (err) {
                global.log.error(query);
                throw err;
            }

            cb();
        });
    });
};

var getUserFriends = function (dbConnection, cb) {
    const query = 'SELECT idUserTarget AS idUser FROM userFriendship GROUP BY idUserTarget';

    dbConnection.query(query, function (err, result) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb(result);
    });
};

var getUserFriendsFilms = function (dbConnection, cb) {
    const query = 'SELECT idFilm FROM userRating ' +
      'WHERE dateRated > UNIX_TIMESTAMP() - 259200 GROUP BY idFilm';// (last 3 days)

    dbConnection.query(query, function (err, results) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        if (!results.length) {
            cb([]);
            return;
        }

        cb(results.map(result => result.idFilm));
    });
};

module.exports = {
    filmExistsInDb: filmExistsInDb,
    importFilm: importFilm,
    importUserFilmReview: importUserFilmReview,
    updateFilmNumFrames: updateFilmNumFrames,
    insertFailedCrawlFilm: insertFailedCrawlFilm,
    getFailedCrawlFilm: getFailedCrawlFilm,
    deleteFailedCrawlFilm: deleteFailedCrawlFilm,
    clearFilmInTheatres: clearFilmInTheatres,
    insertFilmInTheatres: insertFilmInTheatres,
    clearFilmPopular: clearFilmPopular,
    insertFilmPopular: insertFilmPopular,
    getUser: getUser,
    insertUser: insertUser,
    insertUserFriendship: insertUserFriendship,
    userRatingExists: userRatingExists,
    insertUserRating: insertUserRating,
    getLastFriendIdUserRating: getLastFriendIdUserRating,
    setUserLastRatingNotification: setUserLastRatingNotification,
    getUserFriends: getUserFriends,
    getUserFriendsFilms: getUserFriendsFilms,
};
<commit_msg>Check rating exists<commit_after>const mysql = require('mysql');
var async = require('async');

var insertAssoc = function(dbConnection, assoc, idFilm, idAssoc, relevancePosition, cb) {
    assoc = assoc.charAt(0).toUpperCase() + assoc.slice(1).toLowerCase();

    const query = 'INSERT INTO assocFilm' + assoc + ' VALUES(' +
            idFilm + ', ' +
            idAssoc +', ' +
            relevancePosition +
            ')' +
            ' ON DUPLICATE KEY UPDATE' +
            ' idFilm = VALUES(idFilm),' +
            ' id' + assoc + ' = VALUES(id' + assoc + '),' +
            ' relevancePosition = ' + relevancePosition
        ;

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var importAssoc = function (dbConnection, assoc, film, cb) {
    if ((!film[assoc] || !film[assoc].length)) {
        cb();
        return;
    }

    if (film[assoc]) {
        var itemsProcessed = 0;

        film[assoc].forEach(function(assocElement, index, array) {
            const queryInsert = 'INSERT INTO ' + assoc + ' VALUES(' +
                    '0,' +
                    mysql.escape(assocElement) +
                    ')'
                ;

            dbConnection.query(queryInsert, function (err, resultInsert) {
                var relevancePosition = index;

                if (err) {
                    if (err.code == 'ER_DUP_ENTRY') {
                        const querySelect = 'SELECT id' + assoc + ' FROM ' + assoc + ' WHERE name = ' + mysql.escape(assocElement);
                        dbConnection.query(querySelect, function (err, resultSelect) {
                            if (err || resultSelect == undefined) {
                                global.log.error(querySelect);
                                global.log.error(resultSelect);
                                throw err;
                            }

                            insertAssoc(dbConnection, assoc, film.id, resultSelect[0]['id' + assoc], relevancePosition, function() {
                                itemsProcessed++;

                                if(itemsProcessed === array.length) {
                                    cb();
                                }
                            });
                        });
                    } else {
                        global.log.error(queryInsert);
                        throw err;
                    }
                } else {
                    insertAssoc(dbConnection, assoc, film.id, resultInsert.insertId, relevancePosition, function() {
                        itemsProcessed++;

                        if(itemsProcessed === array.length) {
                            cb();
                        }
                    });
                }
            });
        });
    }
};

var importFilm = function (dbConnection, film, cb) {
    const queryNewFilm = 'INSERT INTO film VALUES(' +
            film.id + ',' +
            mysql.escape(film.title) + ',' +
            mysql.escape(film.originalTitle) + ',' +
            film.year + ',' +
            film.duration + ',' +
            mysql.escape(film.country) + ',' +
            mysql.escape(film.producer) + ',' +
            'NULL,' +
            mysql.escape(film.synopsis) + ',' +
            mysql.escape(JSON.stringify(film.proReviews)) + ',' +
            film.rating + ',' +
            film.numRatings + ', ' +
            0 + ', ' +
            'UNIX_TIMESTAMP()' +
            ')' +
            ' ON DUPLICATE KEY UPDATE' +
            ' title = VALUES(title),' +
            ' originalTitle = VALUES(originalTitle),' +
            ' year = VALUES(year),' +
            ' duration = VALUES(duration),' +
            ' country = VALUES(country),' +
            ' producer = VALUES(producer),' +
            ' awards = VALUES(awards),' +
            ' synopsis = VALUES(synopsis),' +
            ' proReviews = VALUES(proReviews),' +
            ' rating = VALUES(rating),' +
            ' numRatings = VALUES(numRatings),' +
            ' numFrames = VALUES(numFrames),' +
            ' dateUpdated = UNIX_TIMESTAMP()'
        ;

    global.log.info('***** Importing film to DB: ' + film.id);

    dbConnection.query(queryNewFilm, function (err) {
        if (err) {
            global.log.error(queryNewFilm);
            throw err;
        }

        var assoc = ['director', 'actor', 'screenplayer', 'musician', 'cinematographer', 'genre', 'topic'];
        var assocProcessed = 0;

        assoc.forEach(function(assocName) {
            importAssoc(dbConnection, assocName, film, function() {
                assocProcessed++;

                if(assocProcessed == assoc.length) {
                    cb();
                }
            });
        });
    });
};

var importUserFilmReview = function (dbConnection, filmId, review, cb) {
    const query = 'INSERT INTO userReview  VALUES(' +
      review.userId + ',' +
      filmId + ',' +
      mysql.escape(review.username) + ', ' +
      review.rating + ',' +
      mysql.escape(review.title) + ', ' +
      mysql.escape(review.reviewText) + ', ' +
      mysql.escape(review.spoiler) + ', ' +
      review.position + ',' +
      review.datePublished.getTime() / 1000 +
      ')' +
      ' ON DUPLICATE KEY UPDATE' +
      ' username = ' + mysql.escape(review.username) + ', ' +
      ' rating = ' + review.rating + ', ' +
      ' title = ' + mysql.escape(review.title) + ', ' +
      ' review = ' + mysql.escape(review.reviewText) + ', ' +
      ' spoiler = ' + mysql.escape(review.spoiler) + ', ' +
      ' position = ' + review.position
    ;

    global.log.info('***** Inserting into userReview: ' + filmId + '|' + review.userId);

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            console.log('ERROR in query: ');
            console.log(query);
            throw err;
        }

        cb();
    });
};

var updateFilmNumFrames = function (dbConnection, filmId, numFrames, cb) {
    const query = 'UPDATE film SET numFrames = ' + numFrames + ' WHERE idFilm = ' + filmId;

    dbConnection.query(query, function (err, result) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb(result);
    });
};

var filmExistsInDb = function (dbConnection, filmId, cb) {
    const queryFilmExists = 'SELECT idFilm FROM film WHERE idFilm = ' + filmId;

    dbConnection.query(queryFilmExists, function (err, result) {
        if (err) {
            global.log.error(queryFilmExists);
            throw err;
        }

        cb(result.length ? true : false);
    });
};

var insertFailedCrawlFilm = function (dbConnection, filmId, cb) {
    const query = 'INSERT INTO failedCrawlFilm VALUES(' +
            filmId +
            ')' +
            ' ON DUPLICATE KEY UPDATE' +
            ' idFilm = VALUES(idFilm)'
        ;

    global.log.info('***** Inserting into failedCrawlFilm: ' + filmId);

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var getFailedCrawlFilm = function (dbConnection, cb) {
    const query = 'SELECT idFilm FROM failedCrawlFilm';

    dbConnection.query(query, function (err, result) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb(result);
    });
};

var deleteFailedCrawlFilm = function (dbConnection, idFilm, cb) {
    const query = 'DELETE FROM failedCrawlFilm WHERE idFilm = ' + idFilm;

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var insertFilmInTheatres = function (dbConnection, film, cb) {
    const query = 'INSERT INTO filmInTheatres VALUES(' +
        film.id + ',' +
        mysql.escape(film.releaseDate) +
        ')'
    ;

    global.log.info('***** Inserting into filmInTheatres: ' + film.id + '|' + film.releaseDate);

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var clearFilmInTheatres = function (dbConnection, cb) {
    const query = 'TRUNCATE filmInTheatres';

    global.log.info('***** Truncating filmInTheatres');

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var insertFilmPopular = function (dbConnection, film, cb) {
    const query = 'INSERT INTO filmPopular VALUES(' +
        film.id + ',' +
        mysql.escape(film.position) +
        ')'
    ;

    global.log.info('***** Inserting into filmPopular: ' + film.id + '|' + film.position);

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var clearFilmPopular = function (dbConnection, cb) {
    const query = 'TRUNCATE filmPopular';

    global.log.info('***** Truncating filmPopular');

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var getUser = function (dbConnection, userId, cb) {
    const query = 'SELECT * FROM user WHERE idUser = ' + userId;

    dbConnection.query(query, function (err, result) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb(result);
    });
};

var insertUser = function (dbConnection, user, cb) {
    const query = 'INSERT INTO user (`idUser`, `name`, `dateAdded`) VALUES(' +
      user.id + ',' +
      mysql.escape(user.name) + ', ' +
      'UNIX_TIMESTAMP()' +
      ')' +
      ' ON DUPLICATE KEY UPDATE' +
      ' idUser = VALUES(idUser), ' +
      ' name = ' + mysql.escape(user.name) + ', ' +
      ' dateUpdated = UNIX_TIMESTAMP()'
    ;

    global.log.info('***** Inserting into user: ' + user.id + '|' + user.name);

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var insertUserFriendship = function (dbConnection, userIdSource, userIdTarget, cb) {
    const query = 'INSERT INTO userFriendship VALUES(' +
      userIdSource + ',' +
      userIdTarget +
      ')' +
      ' ON DUPLICATE KEY UPDATE' +
      ' idUserSource = VALUES(idUserSource)'
    ;

    global.log.info('***** Inserting into userFriendship: ' + userIdSource + '|' + userIdTarget);

    dbConnection.query(query, function (err) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb();
    });
};

var userRatingExists = function (dbConnection, userId, filmId, rating, cb) {
    const query = 'SELECT idUserRating FROM userRating ' +
      ' WHERE idUser = ' + userId +
      ' AND idFilm = ' + filmId +
      ' AND rating = ' + rating;

    dbConnection.query(query, function (err, result) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        let ratingExists = false;
        if (result.length) {
            ratingExists = !!result[0].idUserRating;
        }

        cb(ratingExists);
    });
};

var insertUserRating = function (dbConnection, userId, film, cb) {
    if (!film.rating) {
        cb();
        return;
    }

    userRatingExists(dbConnection, userId, film.id, film.rating, function(ratingExists) {
        if (ratingExists) {
            // global.log.info('***** Rating already exists: ' + userId + '|' + film.id + '|' + film.rating);
            cb();
            return;
        }

        /**
         * If we get here, it means either the rating is new (then we insert),
         * or user has updated the rating to some of the films (then we update on duplicate user/film)
         */
        const query = 'INSERT INTO userRating VALUES(0, ' +
          userId + ',' +
          film.id + ',' +
          film.rating + ',' +
          film.ratingDate.getTime() / 1000 + ',' +
          film.position +
          ')' +
          ' ON DUPLICATE KEY UPDATE' +
          ' rating = ' + film.rating + ',' +
          ' dateRated = ' + film.ratingDate.getTime() / 1000  + ',' +
          ' position = ' + film.position
        ;

        global.log.info('***** Inserting into userRating: ' + userId + '|' + film.id);

        dbConnection.query(query, function (err) {
            if (err) {
                global.log.error(query);
                throw err;
            }

            cb();
        });
    });
};

var getLastFriendIdUserRating = function (dbConnection, userId, cb) {
    const query = 'SELECT ur.idUserRating FROM userRating ur ' +
      ' JOIN userFriendship uf ON uf.idUserTarget = ur.idUser' +
      ' WHERE uf.idUserSource = ' + userId +
      ' ORDER BY idUserRating DESC' +
      ' LIMIT 1';

    dbConnection.query(query, function (err, result) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        let idUserRating = null;
        if (result.length) {
            idUserRating = result[0].idUserRating;
        }

        cb(idUserRating);
    });
};

var setUserLastRatingNotification = function (dbConnection, userId, cb) {
    getLastFriendIdUserRating(dbConnection, userId, function(idUserRating) {
        if (!idUserRating) {
            cb();
            return;
        }

        const query = 'INSERT INTO userLastRatingNotificated VALUES(' +
          userId + ',' +
          idUserRating +
          ')' +
          ' ON DUPLICATE KEY UPDATE' +
          ' idUserRating = ' + idUserRating
        ;

        global.log.info('***** Inserting into userLastRatingNotification: ' + userId + '|' + idUserRating);

        dbConnection.query(query, function (err) {
            if (err) {
                global.log.error(query);
                throw err;
            }

            cb();
        });
    });
};

var getUserFriends = function (dbConnection, cb) {
    const query = 'SELECT idUserTarget AS idUser FROM userFriendship GROUP BY idUserTarget';

    dbConnection.query(query, function (err, result) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        cb(result);
    });
};

var getUserFriendsFilms = function (dbConnection, cb) {
    const query = 'SELECT idFilm FROM userRating ' +
      'WHERE dateRated > UNIX_TIMESTAMP() - 259200 GROUP BY idFilm';// (last 3 days)

    dbConnection.query(query, function (err, results) {
        if (err) {
            global.log.error(query);
            throw err;
        }

        if (!results.length) {
            cb([]);
            return;
        }

        cb(results.map(result => result.idFilm));
    });
};

module.exports = {
    filmExistsInDb: filmExistsInDb,
    importFilm: importFilm,
    importUserFilmReview: importUserFilmReview,
    updateFilmNumFrames: updateFilmNumFrames,
    insertFailedCrawlFilm: insertFailedCrawlFilm,
    getFailedCrawlFilm: getFailedCrawlFilm,
    deleteFailedCrawlFilm: deleteFailedCrawlFilm,
    clearFilmInTheatres: clearFilmInTheatres,
    insertFilmInTheatres: insertFilmInTheatres,
    clearFilmPopular: clearFilmPopular,
    insertFilmPopular: insertFilmPopular,
    getUser: getUser,
    insertUser: insertUser,
    insertUserFriendship: insertUserFriendship,
    userRatingExists: userRatingExists,
    insertUserRating: insertUserRating,
    getLastFriendIdUserRating: getLastFriendIdUserRating,
    setUserLastRatingNotification: setUserLastRatingNotification,
    getUserFriends: getUserFriends,
    getUserFriendsFilms: getUserFriendsFilms,
};
<|endoftext|>


<commit_before>const f7BuildConfig = require('./build-config')

module.exports = {
  build: f7BuildConfig,

  mode: 'hash',
  css: true,
  f7Icons: true,
  mdIcons: true,

  routes: {},

  app: {
    theme: 'auto',
    id: 'app'
  },

  main: {
    main: true,
    pushState: true
  }
}
<commit_msg>refine defaults.js<commit_after>const f7BuildConfig = require('./build-config')

module.exports = {
  app: {
    theme: 'auto'
  },

  main: {
    main: true,
    pushState: true
  },

  build: {
    ...f7BuildConfig,
    invertNav: true,
    noLongTap: true
  },

  css: true,
  customCSS: true,
  f7Icons: true,
  mdIcons: true,

  mode: 'hash',
  routes: {}
}
<|endoftext|>


<commit_before>var events = require("events"),
	util = require("util"),
	kinect = require("kinect");

function depthcam( opts ){

	if(typeof opts !== "undefined"){
		if(opts.kinect){
			this.context = kinect( opts.kinect );
		}else{
			this.context = kinect();
		}
	}else{
		this.context = kinect();
	}

}

util.inherits( depthcam, events.EventEmitter );

var flag = true;

depthcam.prototype.start = function(){

	var self = this;

	this.context.resume();

	this.context.start('depth');

	this.context.on('depth', function(buf) {
		// each depth pixel in buf has 2 bytes, 640 x 480, 11 bit resolution

		if(flag === true){
			console.log('depth triggered');

			console.dir(buf.toString('base64'));
			fs.writeFile('test.png', buf);
			flag = false;
		}

		var filename = 'testfilename.png';//should be the png made from the buffer

		//var image = buf.toString('base64');

		self.emit("depth", filename);
	});

};

module.exports = depthcam;<commit_msg>update<commit_after>var events = require("events"),
	util = require("util"),
	kinect = require("kinect");

function depthcam( opts ){

	if(typeof opts !== "undefined"){
		if(opts.kinect){
			this.context = kinect( opts.kinect );
		}else{
			this.context = kinect();
		}
	}else{
		this.context = kinect();
	}

}

util.inherits( depthcam, events.EventEmitter );

var flag = true;

depthcam.prototype.start = function(){

	var self = this;

	this.context.resume();

	this.context.start('depth');

	this.context.on('depth', function(buf) {
		// each depth pixel in buf has 2 bytes, 640 x 480, 11 bit resolution

		console.log('depth triggered');

		console.dir(buf.toString('base64'));

		var filename = 'testfilename.png';//should be the png made from the buffer

		//var image = buf.toString('base64');

		self.emit("depth", filename);
	});

};

module.exports = depthcam;<|endoftext|>


<commit_before>// dispatch.js
//
// Dispatches messages between workers
//
// Copyright 2012, StatusNet 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.

var cluster = require("cluster"),
    _ = require("underscore");

var Dispatch = {
    log: null,
    start: function(log) {
        var dsp = this;
        dsp.log = log.child({component: "dispatch"});
        _.each(cluster.workers, function(worker, id) {
            worker.on('message', function(msg) {
                switch (msg.cmd) {
                case "follow":
                    dsp.addFollower(msg.url, id);
                    break;
                case "unfollow":
                    dsp.removeFollower(msg.url, id);
                    break;
                case "update":
                    dsp.updateFollowers(msg.url, msg.activity);
                    break;
                default:
                    break;
                }
            });
        });
        dsp.log.info("Dispatch setup complete.");
    },
    followers: {},
    addFollower: function(url, id) {
        var dsp = this;
        if (!_.has(dsp.followers, url)) {
            dsp.followers[url] = [];
        }
        if (!_.contains(dsp.followers[url], id)) {
            dsp.log.info({url: url, id: id}, "Adding follower");
            dsp.followers[url].push(id);
        }
    },
    removeFollower: function(url, id) {
        var dsp = this,
            idx;
        if (_.has(dsp.followers, url)) {
            idx = dsp.followers[url].indexOf(id);
            if (idx !== -1) {
                dsp.log.info({url: url, id: id}, "Removing follower");
                dsp.followers[url].splice(idx, 1);
            }
        }
    },
    updateFollowers: function(url, activity) {
        var dsp = this;
        if (_.has(dsp.followers, url)) {
            _.each(dsp.followers[url], function(id) {
                var worker = cluster.workers[id];
                // XXX: clear out old subscriptions
                if (worker) {
                    dsp.log.info({url: url, activity: activity.id, id: id}, "Dispatching to worker.");
                    worker.send({cmd: "update", url: url, activity: activity});
                }
            });
        }
    }
};

module.exports = Dispatch;<commit_msg>Make log argument optional<commit_after>// dispatch.js
//
// Dispatches messages between workers
//
// Copyright 2012, StatusNet 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.

var cluster = require("cluster"),
    _ = require("underscore");

var Dispatch = {
    log: null,
    start: function(log) {
        var dsp = this;
        if (log) {
            dsp.log = log.child({component: "dispatch"});
        }
        _.each(cluster.workers, function(worker, id) {
            worker.on('message', function(msg) {
                switch (msg.cmd) {
                case "follow":
                    dsp.addFollower(msg.url, id);
                    break;
                case "unfollow":
                    dsp.removeFollower(msg.url, id);
                    break;
                case "update":
                    dsp.updateFollowers(msg.url, msg.activity);
                    break;
                default:
                    break;
                }
            });
        });
        if (dsp.log) dsp.log.info("Dispatch setup complete.");
    },
    followers: {},
    addFollower: function(url, id) {
        var dsp = this;
        if (!_.has(dsp.followers, url)) {
            dsp.followers[url] = [];
        }
        if (!_.contains(dsp.followers[url], id)) {
            if (dsp.log) dsp.log.info({url: url, id: id}, "Adding follower");
            dsp.followers[url].push(id);
        }
    },
    removeFollower: function(url, id) {
        var dsp = this,
            idx;
        if (_.has(dsp.followers, url)) {
            idx = dsp.followers[url].indexOf(id);
            if (idx !== -1) {
                if (dsp.log) dsp.log.info({url: url, id: id}, "Removing follower");
                dsp.followers[url].splice(idx, 1);
            }
        }
    },
    updateFollowers: function(url, activity) {
        var dsp = this;
        if (_.has(dsp.followers, url)) {
            _.each(dsp.followers[url], function(id) {
                var worker = cluster.workers[id];
                // XXX: clear out old subscriptions
                if (worker) {
                    if (dsp.log) dsp.log.info({url: url, activity: activity.id, id: id}, "Dispatching to worker.");
                    worker.send({cmd: "update", url: url, activity: activity});
                }
            });
        }
    }
};

module.exports = Dispatch;<|endoftext|>


<commit_before>'use strict';

var log            =  require('npmlog')
  , mutiny         =  require('mutiny')
  , pruneHtml      =  require('prune-html')
  , transformify   =  require('transformify')
  , jsdocGithubify =  require('jsdoc-githubify')

var stream = require('stream')
  , util = require('util');

var Writable = stream.Writable || require('readable-stream').Writable;

util.inherits(MutinyWritable, Writable);

function MutinyWritable (opts) {
  if (!(this instanceof MutinyWritable)) return new MutinyWritable(opts);

  opts = opts || {};

  Writable.call(this, opts);
  this.apidocs = '';
}

MutinyWritable.prototype._write = function (chunk, encoding, cb) {
  this.apidocs += chunk;
  cb();
}

var go = module.exports =

/**
 * Generates github readme compatible `*.API.md` files from `*.html` jsdoc files
 *
 * @name docmeify
 * @private
 * @function
 * @param {String} htmldir
 * @param {Function(Error, String)} cb called back with entire API section that was converted
 */
function docmeify(htmldir, cb) {
  var outstream = new MutinyWritable()
    , pruneTransform = transformify(pruneHtml.bind(null, [ 'h1', 'h2', 'h3', 'header' ]));

  function onend() {
    cb(null, outstream.apidocs);
  }

  log.verbose('docme', 'githubifying the jsdoc generated pages');

  mutiny(
      { getOutStream: function (file) { return outstream }, transform: [ jsdocGithubify, pruneTransform ] }
    , { root: htmldir, fileFilter: '*.html' }
  )
  .on('error', cb)
  .on('data', function (d) { log.verbose('docme', 'Processed:\n', d); })
  .on('end', onend)
};
<commit_msg>one stream per file to fix write after end bug<commit_after>'use strict';

var log            =  require('npmlog')
  , mutiny         =  require('mutiny')
  , pruneHtml      =  require('prune-html')
  , transformify   =  require('transformify')
  , jsdocGithubify =  require('jsdoc-githubify')

var stream = require('stream')
  , util = require('util');

var Writable = stream.Writable || require('readable-stream').Writable;

util.inherits(MutinyWritable, Writable);

function MutinyWritable (opts) {
  if (!(this instanceof MutinyWritable)) return new MutinyWritable(opts);

  opts = opts || {};

  Writable.call(this, opts);
  this.apidoc = '';
}

MutinyWritable.prototype._write = function (chunk, encoding, cb) {
  this.apidoc += chunk;
  cb();
}

var go = module.exports =

/**
 * Generates github readme compatible `*.API.md` files from `*.html` jsdoc files
 *
 * @name docmeify
 * @private
 * @function
 * @param {String} htmldir
 * @param {Function(Error, String)} cb called back with entire API section that was converted
 */
function docmeify(htmldir, cb) {
  var outstreams =  []
    , pruneTransform = transformify(pruneHtml.bind(null, [ 'h1', 'h2', 'h3', 'header' ]));

  function getOutStream() {
    var s = new MutinyWritable();
    outstreams.push(s);
    return s;
  }

  function onend() {
    var apidocs = outstreams.map(function (x) { return x.apidoc }).join('');
    cb(null, apidocs);
  }

  log.verbose('docme', 'githubifying the jsdoc generated pages');

  mutiny(
      { getOutStream: getOutStream, transform: [ jsdocGithubify, pruneTransform ] }
    , { root: htmldir, fileFilter: '*.html' }
  )
  .on('error', cb)
  .on('data', function (d) { log.verbose('docme', 'Processed:\n', d); })
  .on('end', onend)
};
<|endoftext|>


<commit_before>'use strict';

let _ = require('lodash');
let CastError = require('./error');
let debug = require('debug')('monogram:casting:document');
let handleCast = require('./common').handleCast;
let join = require('./common').join;
let realPathToSchemaPath = require('./common').realPathToSchemaPath;

module.exports = castDocument;

function castDocument(obj, schema, path, skipCast) {
  return visitObject(obj, schema, path || '', skipCast);
}

function visitArray(obj, key, path, schema, skipCast) {
  debug('visitArray', obj, key, path, schema);
  let error = new CastError();
  let realPath = join(path, key, true);
  let curPath = realPathToSchemaPath(realPath);
  let newPath = join(curPath, '$');
  if (!schema._paths[newPath] || !schema._paths[newPath].$type) {
    debug('skipping', newPath);
    return;
  }

  let arr = obj[key];
  if (!Array.isArray(arr)) {
    arr = obj[key] = [arr];
  }

  debug('newPath', newPath, schema._paths[newPath].$type);
  arr.forEach(function(value, index) {
    if (schema._paths[newPath].$type === Array) {
      let err = visitArray(arr, index, realPath, schema, skipCast);
      if (err) {
        error.merge(err);
      }
      return;
    } else if (schema._paths[newPath].$type === Object) {
      let err = visitObject(value, schema, join(realPath, index, true),
        skipCast);
      if (err) {
        error.merge(err);
      }
      return;
    }

    if (!skipCast) {
      try {
        handleCast(arr, index, schema._paths[newPath].$type);
      } catch(err) {
        error.markError(join(realPath, index, true), err);
      }
    }
  });

  if (error.hasError) {
    return error;
  }
}

function visitObject(obj, schema, path, skipCast) {
  debug('visitObject', obj, schema, path);
  let error = new CastError();
  if (typeof obj !== 'object' || Array.isArray(obj)) {
    let err = new Error('Could not cast ' + require('util').inspect(obj) +
      ' to Object');
    error.markError(path, err);
    return error;
  }

  let fakePath = realPathToSchemaPath(path);

  _.each(obj, function(value, key) {
    let newPath = join(path, key);
    if (!schema._paths[newPath]) {
      delete obj[key];
      return;
    }
    if (!schema._paths[newPath].$type) {
      // If type not specified, no type casting
      return;
    }

    if (schema._paths[newPath].$type === Array) {
      let err = visitArray(obj, key, path, schema, skipCast);
      if (err) {
        debug('merge', err.errors);
        error.merge(err);
      }
      return;
    } else if (schema._paths[newPath].$type === Object) {
      if (value == null) {
        delete obj[key];
        return;
      }
      let err = visitObject(value, schema, newPath, skipCast);
      if (err) {
        debug('merge', err.errors);
        error.merge(err);
      }
      return;
    }

    if (!skipCast) {
      try {
        handleCast(obj, key, schema._paths[newPath].$type);
      } catch(err) {
        error.markError(join(path, key, true), err);
      }
    }
  });

  if (error.hasError) {
    return error;
  }
}
<commit_msg>refactor visitObject to return a value and error<commit_after>'use strict';

let _ = require('lodash');
let CastError = require('./error');
let debug = require('debug')('monogram:casting:document');
let handleCast = require('./common').handleCast;
let join = require('./common').join;
let realPathToSchemaPath = require('./common').realPathToSchemaPath;

module.exports = castDocument;

function castDocument(obj, schema, path, skipCast) {
  return visitObject(obj, schema, path || '', skipCast).error;
}

function visitArray(obj, key, path, schema, skipCast) {
  debug('visitArray', obj, key, path, schema);
  let error = new CastError();
  let realPath = join(path, key, true);
  let curPath = realPathToSchemaPath(realPath);
  let newPath = join(curPath, '$');
  if (!schema._paths[newPath] || !schema._paths[newPath].$type) {
    debug('skipping', newPath);
    return;
  }

  let arr = obj[key];
  if (!Array.isArray(arr)) {
    arr = obj[key] = [arr];
  }

  debug('newPath', newPath, schema._paths[newPath].$type);
  arr.forEach(function(value, index) {
    if (schema._paths[newPath].$type === Array) {
      let err = visitArray(arr, index, realPath, schema, skipCast);
      if (err) {
        error.merge(err);
      }
      return;
    } else if (schema._paths[newPath].$type === Object) {
      let err = visitObject(value, schema, join(realPath, index, true),
        skipCast).error;
      if (err) {
        error.merge(err);
      }
      return;
    }

    if (!skipCast) {
      try {
        handleCast(arr, index, schema._paths[newPath].$type);
      } catch(err) {
        error.markError(join(realPath, index, true), err);
      }
    }
  });

  if (error.hasError) {
    return error;
  }
}

function visitObject(obj, schema, path, skipCast) {
  debug('visitObject', obj, schema, path);
  let error = new CastError();
  if (typeof obj !== 'object' || Array.isArray(obj)) {
    let err = new Error('Could not cast ' + require('util').inspect(obj) +
      ' to Object');
    error.markError(path, err);
    return {
      value: null,
      error: error
    };
  }

  let fakePath = realPathToSchemaPath(path);

  _.each(obj, function(value, key) {
    let newPath = join(path, key);
    if (!schema._paths[newPath]) {
      delete obj[key];
      return;
    }
    if (!schema._paths[newPath].$type) {
      // If type not specified, no type casting
      return;
    }

    if (schema._paths[newPath].$type === Array) {
      let err = visitArray(obj, key, path, schema, skipCast);
      if (err) {
        debug('merge', err.errors);
        error.merge(err);
      }
      return;
    } else if (schema._paths[newPath].$type === Object) {
      if (value == null) {
        delete obj[key];
        return;
      }
      let res = visitObject(value, schema, newPath, skipCast);
      if (res.error) {
        debug('merge', res.error.errors);
        error.merge(res.error);
      }
      obj[key] = res.value;
      return;
    }

    if (!skipCast) {
      try {
        handleCast(obj, key, schema._paths[newPath].$type);
      } catch(err) {
        error.markError(join(path, key, true), err);
      }
    }
  });

  return {
    value: obj,
    error: (error.hasError ? error : null)
  };
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 * @format
 */

const NativeModules = require('../BatchedBridge/NativeModules');
const Platform = require('../Utilities/Platform');
const UIManagerProperties = require('./UIManagerProperties');

const defineLazyObjectProperty = require('../Utilities/defineLazyObjectProperty');

import NativeUIManager from './NativeUIManager';

const viewManagerConfigs = {};

const triedLoadingConfig = new Set();

let NativeUIManagerConstants = {};
let isNativeUIManagerConstantsSet = false;
function getConstants(): Object {
  if (!isNativeUIManagerConstantsSet) {
    NativeUIManagerConstants = NativeUIManager.getConstants();
    isNativeUIManagerConstantsSet = true;
  }
  return NativeUIManagerConstants;
}

function getViewManagerConfig(viewManagerName: string): any {
  if (
    viewManagerConfigs[viewManagerName] === undefined &&
    NativeUIManager.getConstantsForViewManager
  ) {
    try {
      viewManagerConfigs[
        viewManagerName
      ] = NativeUIManager.getConstantsForViewManager(viewManagerName);

      if (viewManagerConfigs[viewManagerName] === undefined) {
        console.warn(
          'Error: Unable to find getConstantsForViewManager for viewManager: ' +
            viewManagerName +
            '.',
        );
      }
    } catch (e) {
      console.error(
        "NativeUIManager.getConstantsForViewManager('" +
          viewManagerName +
          "') threw an exception.",
        e,
      );
      viewManagerConfigs[viewManagerName] = null;
    }
  }

  const config = viewManagerConfigs[viewManagerName];
  if (config) {
    return config;
  }

  // If we're in the Chrome Debugger, let's not even try calling the sync
  // method.
  if (!global.nativeCallSyncHook) {
    return config;
  }

  if (
    NativeUIManager.lazilyLoadView &&
    !triedLoadingConfig.has(viewManagerName)
  ) {
    const result = NativeUIManager.lazilyLoadView(viewManagerName);
    triedLoadingConfig.add(viewManagerName);
    if (result != null && result.viewConfig != null) {
      getConstants()[viewManagerName] = result.viewConfig;
      lazifyViewManagerConfig(viewManagerName);
    } else {
      console.warn(
        'Error: Unable to find viewManagerConfigs for viewManager: ' +
          viewManagerName +
          ' using lazyLoadView.',
      );
    }
  }

  return viewManagerConfigs[viewManagerName];
}

/* $FlowFixMe(>=0.123.0 site=react_native_fb) This comment suppresses an error
 * found when Flow v0.123.0 was deployed. To see the error, delete this comment
 * and run Flow. */
const UIManagerJS = {
  ...NativeUIManager,
  createView(
    reactTag: ?number,
    viewName: string,
    rootTag: number,
    props: Object,
  ): void {
    if (Platform.OS === 'ios' && viewManagerConfigs[viewName] === undefined) {
      // This is necessary to force the initialization of native viewManager
      // classes in iOS when using static ViewConfigs
      getViewManagerConfig(viewName);
    }

    NativeUIManager.createView(reactTag, viewName, rootTag, props);
  },
  getConstants(): Object {
    return getConstants();
  },
  getViewManagerConfig(viewManagerName: string): any {
    return getViewManagerConfig(viewManagerName);
  },
  hasViewManagerConfig(viewManagerName: string): boolean {
    return getViewManagerConfig(viewManagerName) != null;
  },
};

// TODO (T45220498): Remove this.
// 3rd party libs may be calling `NativeModules.UIManager.getViewManagerConfig()`
// instead of `UIManager.getViewManagerConfig()` off UIManager.js.
// This is a workaround for now.
// $FlowFixMe
NativeUIManager.getViewManagerConfig = UIManagerJS.getViewManagerConfig;

function lazifyViewManagerConfig(viewName) {
  const viewConfig = getConstants()[viewName];
  viewManagerConfigs[viewName] = viewConfig;
  if (viewConfig.Manager) {
    defineLazyObjectProperty(viewConfig, 'Constants', {
      get: () => {
        const viewManager = NativeModules[viewConfig.Manager];
        const constants = {};
        viewManager &&
          Object.keys(viewManager).forEach(key => {
            const value = viewManager[key];
            if (typeof value !== 'function') {
              constants[key] = value;
            }
          });
        return constants;
      },
    });
    defineLazyObjectProperty(viewConfig, 'Commands', {
      get: () => {
        const viewManager = NativeModules[viewConfig.Manager];
        const commands = {};
        let index = 0;
        viewManager &&
          Object.keys(viewManager).forEach(key => {
            const value = viewManager[key];
            if (typeof value === 'function') {
              commands[key] = index++;
            }
          });
        return commands;
      },
    });
  }
}

/**
 * Copies the ViewManager constants and commands into UIManager. This is
 * only needed for iOS, which puts the constants in the ViewManager
 * namespace instead of UIManager, unlike Android.
 */
if (Platform.OS === 'ios') {
  Object.keys(getConstants()).forEach(viewName => {
    lazifyViewManagerConfig(viewName);
  });
} else if (getConstants().ViewManagerNames) {
  NativeUIManager.getConstants().ViewManagerNames.forEach(viewManagerName => {
    defineLazyObjectProperty(NativeUIManager, viewManagerName, {
      get: () => NativeUIManager.getConstantsForViewManager(viewManagerName),
    });
  });
}

if (!global.nativeCallSyncHook) {
  Object.keys(getConstants()).forEach(viewManagerName => {
    if (!UIManagerProperties.includes(viewManagerName)) {
      if (!viewManagerConfigs[viewManagerName]) {
        viewManagerConfigs[viewManagerName] = getConstants()[viewManagerName];
      }
      defineLazyObjectProperty(NativeUIManager, viewManagerName, {
        get: () => {
          console.warn(
            `Accessing view manager configs directly off UIManager via UIManager['${viewManagerName}'] ` +
              `is no longer supported. Use UIManager.getViewManagerConfig('${viewManagerName}') instead.`,
          );

          return UIManagerJS.getViewManagerConfig(viewManagerName);
        },
      });
    }
  });
}

module.exports = UIManagerJS;
<commit_msg>Remove log in PaperUIManager<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow
 * @format
 */

const NativeModules = require('../BatchedBridge/NativeModules');
const Platform = require('../Utilities/Platform');
const UIManagerProperties = require('./UIManagerProperties');

const defineLazyObjectProperty = require('../Utilities/defineLazyObjectProperty');

import NativeUIManager from './NativeUIManager';

const viewManagerConfigs = {};

const triedLoadingConfig = new Set();

let NativeUIManagerConstants = {};
let isNativeUIManagerConstantsSet = false;
function getConstants(): Object {
  if (!isNativeUIManagerConstantsSet) {
    NativeUIManagerConstants = NativeUIManager.getConstants();
    isNativeUIManagerConstantsSet = true;
  }
  return NativeUIManagerConstants;
}

function getViewManagerConfig(viewManagerName: string): any {
  if (
    viewManagerConfigs[viewManagerName] === undefined &&
    NativeUIManager.getConstantsForViewManager
  ) {
    try {
      viewManagerConfigs[
        viewManagerName
      ] = NativeUIManager.getConstantsForViewManager(viewManagerName);
    } catch (e) {
      console.error(
        "NativeUIManager.getConstantsForViewManager('" +
          viewManagerName +
          "') threw an exception.",
        e,
      );
      viewManagerConfigs[viewManagerName] = null;
    }
  }

  const config = viewManagerConfigs[viewManagerName];
  if (config) {
    return config;
  }

  // If we're in the Chrome Debugger, let's not even try calling the sync
  // method.
  if (!global.nativeCallSyncHook) {
    return config;
  }

  if (
    NativeUIManager.lazilyLoadView &&
    !triedLoadingConfig.has(viewManagerName)
  ) {
    const result = NativeUIManager.lazilyLoadView(viewManagerName);
    triedLoadingConfig.add(viewManagerName);
    if (result != null && result.viewConfig != null) {
      getConstants()[viewManagerName] = result.viewConfig;
      lazifyViewManagerConfig(viewManagerName);
    }
  }

  return viewManagerConfigs[viewManagerName];
}

/* $FlowFixMe(>=0.123.0 site=react_native_fb) This comment suppresses an error
 * found when Flow v0.123.0 was deployed. To see the error, delete this comment
 * and run Flow. */
const UIManagerJS = {
  ...NativeUIManager,
  createView(
    reactTag: ?number,
    viewName: string,
    rootTag: number,
    props: Object,
  ): void {
    if (Platform.OS === 'ios' && viewManagerConfigs[viewName] === undefined) {
      // This is necessary to force the initialization of native viewManager
      // classes in iOS when using static ViewConfigs
      getViewManagerConfig(viewName);
    }

    NativeUIManager.createView(reactTag, viewName, rootTag, props);
  },
  getConstants(): Object {
    return getConstants();
  },
  getViewManagerConfig(viewManagerName: string): any {
    return getViewManagerConfig(viewManagerName);
  },
  hasViewManagerConfig(viewManagerName: string): boolean {
    return getViewManagerConfig(viewManagerName) != null;
  },
};

// TODO (T45220498): Remove this.
// 3rd party libs may be calling `NativeModules.UIManager.getViewManagerConfig()`
// instead of `UIManager.getViewManagerConfig()` off UIManager.js.
// This is a workaround for now.
// $FlowFixMe
NativeUIManager.getViewManagerConfig = UIManagerJS.getViewManagerConfig;

function lazifyViewManagerConfig(viewName) {
  const viewConfig = getConstants()[viewName];
  viewManagerConfigs[viewName] = viewConfig;
  if (viewConfig.Manager) {
    defineLazyObjectProperty(viewConfig, 'Constants', {
      get: () => {
        const viewManager = NativeModules[viewConfig.Manager];
        const constants = {};
        viewManager &&
          Object.keys(viewManager).forEach(key => {
            const value = viewManager[key];
            if (typeof value !== 'function') {
              constants[key] = value;
            }
          });
        return constants;
      },
    });
    defineLazyObjectProperty(viewConfig, 'Commands', {
      get: () => {
        const viewManager = NativeModules[viewConfig.Manager];
        const commands = {};
        let index = 0;
        viewManager &&
          Object.keys(viewManager).forEach(key => {
            const value = viewManager[key];
            if (typeof value === 'function') {
              commands[key] = index++;
            }
          });
        return commands;
      },
    });
  }
}

/**
 * Copies the ViewManager constants and commands into UIManager. This is
 * only needed for iOS, which puts the constants in the ViewManager
 * namespace instead of UIManager, unlike Android.
 */
if (Platform.OS === 'ios') {
  Object.keys(getConstants()).forEach(viewName => {
    lazifyViewManagerConfig(viewName);
  });
} else if (getConstants().ViewManagerNames) {
  NativeUIManager.getConstants().ViewManagerNames.forEach(viewManagerName => {
    defineLazyObjectProperty(NativeUIManager, viewManagerName, {
      get: () => NativeUIManager.getConstantsForViewManager(viewManagerName),
    });
  });
}

if (!global.nativeCallSyncHook) {
  Object.keys(getConstants()).forEach(viewManagerName => {
    if (!UIManagerProperties.includes(viewManagerName)) {
      if (!viewManagerConfigs[viewManagerName]) {
        viewManagerConfigs[viewManagerName] = getConstants()[viewManagerName];
      }
      defineLazyObjectProperty(NativeUIManager, viewManagerName, {
        get: () => {
          console.warn(
            `Accessing view manager configs directly off UIManager via UIManager['${viewManagerName}'] ` +
              `is no longer supported. Use UIManager.getViewManagerConfig('${viewManagerName}') instead.`,
          );

          return UIManagerJS.getViewManagerConfig(viewManagerName);
        },
      });
    }
  });
}

module.exports = UIManagerJS;
<|endoftext|>


<commit_before>/**
 * Model of variable
 * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com)
 * @lastmodifiedDate 2015-07-27
 */
var Namespace = require('./namespace'),
    internal = Namespace();

/**
 * Create a model of variable
 * @param {String} name Name of the variable
 * @constructor
 * @throws {Object} when Var constructed with invalid value
 */
function Var(name) {
    'use strict';
    Var.validate(name);
    internal(this)._name = name;

    /* start-test-block */
    this._testonly_ = internal(this);
    /* end-test-block */
}

/* start-static-methods */
/**
 * Check an object is Var or not
 * @param {Object} obj
 * @returns {Boolean}
 */
Var.isVar = function (obj) {
    'use strict';
    return obj instanceof Var;
};

/**
 * Check the name is a valid identifier
 * @param {String} name
 * @returns {Boolean}
 */
Var.isValidName = function (name) {
    'use strict';
    var identifierFormat = /^[_a-zA-Z]{1}[_a-zA-Z0-9]*$/i;
    return (typeof name === 'string' && identifierFormat.test(name));
};

/**
 * Validate the values for a Var is valid
 * @param {String} name Name of checked variable
 * @param {String} msg Custom error message
 * @throws {Object} When a values of the Var is invalid
 */
Var.validate = function (name, msg) {
    'use strict';
    if (!Var.isValidName(name)) {
        throw new Error(msg || 'Invalid value for a Var');
    }
};

/**
 * Validate an object is a Var or not
 * @param {Object} obj An object to be validated
 * @param {String} msg Custom error message
 * @throws {Object} When the object is not a Var
 */
Var.validateType = function (obj, msg) {
    'use strict';
    if (!Var.isVar(obj)) {
        throw new Error(msg || 'Not a Var');
    }
};
/* end-static-methods */

/* start-public-methods */
/**
 * Represent the object as string
 * @returns {String} The variable's identity
 */
Var.prototype.toString = function () {
    'use strict';
    return internal(this)._name;
};

/**
 * Convert the variable to JSON
 * @returns {Object} JSON formatted object
 */
Var.prototype.toJSON = function () {
	'use strict';
	return {
		"name": internal(this)._name
	};
};
/* end-public-methods */

/* start-public-data-members */
Object.defineProperty(Var.prototype, 'name', {
    get: function () {
        'use strict';
        return internal(this)._name;
    },
	enumerable: true
});
/* end-public-data-members */

module.exports = Var;<commit_msg>Remove the use of single repetition<commit_after>/**
 * Model of variable
 * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com)
 * @lastmodifiedDate 2015-07-27
 */
var Namespace = require('./namespace'),
    internal = Namespace();

/**
 * Create a model of variable
 * @param {String} name Name of the variable
 * @constructor
 * @throws {Object} when Var constructed with invalid value
 */
function Var(name) {
    'use strict';
    Var.validate(name);
    internal(this)._name = name;

    /* start-test-block */
    this._testonly_ = internal(this);
    /* end-test-block */
}

/* start-static-methods */
/**
 * Check an object is Var or not
 * @param {Object} obj
 * @returns {Boolean}
 */
Var.isVar = function (obj) {
    'use strict';
    return obj instanceof Var;
};

/**
 * Check the name is a valid identifier
 * @param {String} name
 * @returns {Boolean}
 */
Var.isValidName = function (name) {
    'use strict';
    var identifierFormat = /^[_a-zA-Z][_a-zA-Z0-9]*$/i;
    return (typeof name === 'string' && identifierFormat.test(name));
};

/**
 * Validate the values for a Var is valid
 * @param {String} name Name of checked variable
 * @param {String} msg Custom error message
 * @throws {Object} When a values of the Var is invalid
 */
Var.validate = function (name, msg) {
    'use strict';
    if (!Var.isValidName(name)) {
        throw new Error(msg || 'Invalid value for a Var');
    }
};

/**
 * Validate an object is a Var or not
 * @param {Object} obj An object to be validated
 * @param {String} msg Custom error message
 * @throws {Object} When the object is not a Var
 */
Var.validateType = function (obj, msg) {
    'use strict';
    if (!Var.isVar(obj)) {
        throw new Error(msg || 'Not a Var');
    }
};
/* end-static-methods */

/* start-public-methods */
/**
 * Represent the object as string
 * @returns {String} The variable's identity
 */
Var.prototype.toString = function () {
    'use strict';
    return internal(this)._name;
};

/**
 * Convert the variable to JSON
 * @returns {Object} JSON formatted object
 */
Var.prototype.toJSON = function () {
	'use strict';
	return {
		"name": internal(this)._name
	};
};
/* end-public-methods */

/* start-public-data-members */
Object.defineProperty(Var.prototype, 'name', {
    get: function () {
        'use strict';
        return internal(this)._name;
    },
	enumerable: true
});
/* end-public-data-members */

module.exports = Var;<|endoftext|>