<commit_before>'use strict'

var ref = require('../../util/get/reference')
var Event = require('../../event')

exports.inject = require('./retrieve')

exports.define = {
  subscribe (path, type, val, key, fire, event) {
    let id = this.uid
    if (key) {
      id += '.' + key
    }
    let pathType = typeof path
    if (path === true) {
      path = [] // make faster
    } else if (pathType === 'string') {
      id += path
      path = path.split('.')
    } else if (pathType === 'number') {
      id += path
      path = [path]
    } else {
      id += path.join('.')
    }
    let index = 0
    let length = path.length
    // unsubs will not work now
    this.on('remove', function () {
      unsubscribe(this, path, index, length, id)
    }, id)
    return subscribe(this, path, index, length, type, val, id, fire, this, event)
  },

  // test and make better -- the uid is crap now
  unsubscribe (path, key) {
    let id = this.uid
    if (key) {
      id += '.' + key
    }
    // make shared shit
    let pathType = typeof path
    if (path === true) {
      path = [] // make faster
    } else if (pathType === 'string') {
      id += path
      path = path.split('.')
    } else if (pathType === 'number') {
      id += path
      path = [path]
    } else {
      id += path.join('.')
    }

    let index = 0
    let length = path.length
    return unsubscribe(this, path, index, length, id)
  }
}

// subscriptions have to take care of references
// we have to add walking over the refs here
function subscribe (obs, path, index, length, type, val, id, fire, origin, event) {
  if (index === length) {
    obs.on('remove', function () {
      // null
      subscribe(origin, path, 0, length, type, val, id, false, origin, event)
    }, id)
    obs.on(type, val, id)
    if (fire) {
      // **TODO** SUPER DIRTY
      // need to have some godamn arguments

      // console.log('WTF WTF', obs, event)

      if (event === void 0) {
        var trigger = true
        event = new Event('data') // wrong
      }
      // var data = obs._input
      // if (typeof val === 'function') {

      //   // console.log('do it bitch')

      //   val.call(obs, data, event)
      // } else {
      //   // console.log('do it bitch', data)
      //   // ref and value
      //   val[0].call(obs, data, event, val[1])
      // }

      if (typeof val === 'function') {
        val.call(obs, obs._input, event)
      } else {
        // console.log('do it bitch', data)
        // var data =  // if property if data haha lulllzzzz
        // ref and value
        val[0].call(obs, type === 'data' ? obs._input : void 0, event, val[1])
      }

      if (trigger) {
        event.trigger()
      }
      // console.log('AM I FUCKING IT UP!', event)
      // obs.emit(type, void 0, event)
    }
    return obs
  } else {
    let key = path[index]
    let property = obs[key]
    let result

    if (property && property._input !== null) {
      result = subscribe(property, path, index + 1, length, type, val, id, fire, origin, event)
    } else {
      let listenerType = key === 'parent' ? key : 'property'
      let listener = function (data, event) {
        let property = obs[key]
        if (property) {
          obs.off(listenerType, id)
          subscribe(property, path, index + 1, length, type, val, id, true, origin, event)
        }
      }
      obs.on(listenerType, listener, id)
    }

    // if sub is not fulfilled look in the reference
    if (!result) {
      let reference = ref(obs)
      if (reference) {
        subscribe(reference, path, index, length, type, val, id, fire, origin, event)
      }
    }
  }
}

function unsubscribe (obs, path, index, length, id) {
  // console.log('REMOVE!')
  obs.off(void 0, id)
  let key = path[index]
  let property = obs[key]
  if (property) {
    unsubscribe(property, path, index + 1, length, id)
  }
  let reference = ref(obs)
  if (reference) {
    unsubscribe(obs, path, index, length, id)
  }
}
<commit_msg>subscribe debugs<commit_after>'use strict'

var ref = require('../../util/get/reference')
var Event = require('../../event')

exports.inject = require('./retrieve')

exports.define = {
  subscribe (path, type, val, key, fire, event) {
    let id = this.uid
    if (key) {
      id += '.' + key
    }
    let pathType = typeof path
    if (path === true) {
      path = [] // make faster
    } else if (pathType === 'string') {
      id += path
      path = path.split('.')
    } else if (pathType === 'number') {
      id += path
      path = [path]
    } else {
      id += path.join('.')
    }
    let index = 0
    let length = path.length
    // unsubs will not work now

    this.on('remove', function () {
      unsubscribe(this, path, index, length, id)
    }, id)
    return subscribe(this, path, index, length, type, val, id, fire, this, event)
  },

  // test and make better -- the uid is crap now
  unsubscribe (path, key) {
    let id = this.uid
    if (key) {
      id += '.' + key
    }
    // make shared shit
    let pathType = typeof path
    if (path === true) {
      path = [] // make faster
    } else if (pathType === 'string') {
      id += path
      path = path.split('.')
    } else if (pathType === 'number') {
      id += path
      path = [path]
    } else {
      id += path.join('.')
    }

    let index = 0
    let length = path.length
    return unsubscribe(this, path, index, length, id)
  }
}

// subscriptions have to take care of references
// we have to add walking over the refs here
function subscribe (obs, path, index, length, type, val, id, fire, origin, event) {
  if (index === length) {
    obs.on('remove', function () {
      // null
      subscribe(origin, path, 0, length, type, val, id, false, origin, event)
    }, id)
    obs.on(type, val, id)
    if (fire) {
      // **TODO** SUPER DIRTY
      // need to have some godamn arguments

      // console.log('WTF WTF', obs, event)

      if (event === void 0) {
        var trigger = true
        event = new Event('data') // wrong
      }
      // var data = obs._input
      // if (typeof val === 'function') {

      //   // console.log('do it bitch')

      //   val.call(obs, data, event)
      // } else {
      //   // console.log('do it bitch', data)
      //   // ref and value
      //   val[0].call(obs, data, event, val[1])
      // }

      if (typeof val === 'function') {
        val.call(obs, obs._input, event)
      } else {
        // console.log('do it bitch', data)
        // var data =  // if property if data haha lulllzzzz
        // ref and value
        val[0].call(obs, type === 'data' ? obs._input : void 0, event, val[1])
      }

      if (trigger) {
        event.trigger()
      }
      // console.log('AM I FUCKING IT UP!', event)
      // obs.emit(type, void 0, event)
    }
    return obs
  } else {
    let key = path[index]
    let property = obs[key]
    let result

    if (property && property._input !== null) {
      result = subscribe(property, path, index + 1, length, type, val, id, fire, origin, event)
    } else {
      let listenerType = key === 'parent' ? key : 'property'
      let listener = function (data, event) {
        // console.error('fire prop!')
        let property = obs[key]
        if (property) {
          obs.off(listenerType, id)
          subscribe(property, path, index + 1, length, type, val, id, true, origin, event)
        }
      }
      obs.on(listenerType, listener, id)
    }

    // if sub is not fulfilled look in the reference
    if (!result) {
      let reference = ref(obs)
      if (reference) {
        subscribe(reference, path, index, length, type, val, id, fire, origin, event)
      }
    }
  }
}

function unsubscribe (obs, path, index, length, id) {
  obs.off(void 0, id)
  let key = path[index]
  let property = obs[key]
  if (property) {
    unsubscribe(property, path, index + 1, length, id)
  }
  let reference = ref(obs)
  if (reference) {
    unsubscribe(obs, path, index, length, id)
  }
}
<|endoftext|>


<commit_before>var _ = require('lodash');
var async = require('async');

module.exports = function(models, cb) {
  var self = this;
  var transactionCnx = {};
  models = _.isArray(models) ? models : [models];
  models.forEach(function(model) {
    _.keys(model.adapter.dictionary).forEach(function(fct) {
      var cnx = model.adapter.dictionary[fct];

      if(!transactionCnx[cnx]) {
        transactionCnx[cnx] = {collections: {}, adapter: model.offshore.connections[cnx]._adapter, context: model.offshore};
      }
      if(!transactionCnx[cnx].collections[model.identity]) {
        transactionCnx[cnx].collections[model.identity] = [];
      }
      transactionCnx[cnx].collections[model.identity].push(fct);
    });
  });

  var transactionDeferred = new TransactionDeferred(transactionCnx);
  var transactionDictionary = {};
  async.eachSeries(_.keys(transactionCnx), function(cnx, cb) {
    transactionCnx[cnx].adapter.registerTransaction(cnx, _.keys(transactionCnx[cnx].collections), function(err, id) {
      if(err) {
        return cb(err);
      }
      transactionDictionary[cnx] = id;
      transactionCnx[cnx].id = id;
      cb();
    });
  }, function(err) {
    if(err) {
      return transactionDeferred.rollback(err);
    }
    var transaction = {};
    _.keys(transactionCnx).forEach(function(cnx) {
      var connection = transactionCnx[cnx];
      _.keys(connection.collections).forEach(function(col) {
        transaction[col] = connection.context.collections[col]._loadQuery({transaction:  transactionDictionary});
      });
    });
    cb(transaction, function(err, result) {
      if(err) {
        return transactionDeferred.rollback(err);
      }
      transactionDeferred.commit(result);

    });
  });
  return transactionDeferred;
};

var TransactionDeferred = function(connections) {
  this._connections = connections;
  this._commit = null;
  this._rollback = null;
  this._execCallback = null;
};

TransactionDeferred.prototype.commit = function(result) {
  var self = this;
  if(self._rollback) {
    throw new Error('Cannot commit when transaction has been rollbacked');
  }
  if(self._commit) {
    throw new Error('Transaction already commited');
  }
  this._commit = result;

  async.eachSeries(_.keys(self._connections), function(cnx, next) {
    self._connections[cnx].adapter.commit(self._connections[cnx].id, _.keys(self._connections[cnx].collections), next);
  }, function() {
    if(self._execCallback) {
      self._execCallback(null, self._commit);
    }
  });
};

TransactionDeferred.prototype.rollback = function(err) {
  var self = this;
  if(self._commit) {
    throw new Error('Cannot rollback when transaction has been commited');
  }
  if(self._rollback) {
    throw new Error('Transaction already rollbacked');
  }
  this._rollback = err;
  async.eachSeries(_.keys(self._connections), function(cnx, next) {
    self._connections[cnx].adapter.rollback(self._connections[cnx].id, _.keys(self._connections[cnx].collections), next);
  }, function() {
    if(self._execCallback) {
      self._execCallback(self._rollback);
    }
  });
};

TransactionDeferred.prototype.exec = function(cb) {
  this._execCallback = cb;
};
<commit_msg>Add some error messages to transactions<commit_after>var _ = require('lodash');
var async = require('async');

module.exports = function(models, cb) {
  var self = this;
  var transactionCnx = {};
  models = _.isArray(models) ? models : [models];
  var errs = [];
  models.forEach(function(model) {
    if(!_.isObject(model) || !_.isObject(model.adapter) || !model.adapter.dictionary) {
      return errs.push('Invalid model : ' + model);
    }
    _.keys(model.adapter.dictionary).forEach(function(fct) {
      var cnx = model.adapter.dictionary[fct];

      if(!model.offshore.connections[cnx]._adapter.registerTransaction) {
        return errs.push(new Error('Adapter ' + model.offshore.connections[cnx]._adapter.identity + ' has no transactable interface'));
      }

      if(!transactionCnx[cnx]) {
        transactionCnx[cnx] = {collections: {}, adapter: model.offshore.connections[cnx]._adapter, context: model.offshore};
      }
      if(!transactionCnx[cnx].collections[model.identity]) {
        transactionCnx[cnx].collections[model.identity] = [];
      }
      transactionCnx[cnx].collections[model.identity].push(fct);
    });
  });

  if(errs.length) {
    return cb(errs[0]);
  }
  var transactionDeferred = new TransactionDeferred(transactionCnx);
  var transactionDictionary = {};
  async.eachSeries(_.keys(transactionCnx), function(cnx, cb) {
    transactionCnx[cnx].adapter.registerTransaction(cnx, _.keys(transactionCnx[cnx].collections), function(err, id) {
      if(err) {
        return cb(err);
      }
      transactionDictionary[cnx] = id;
      transactionCnx[cnx].id = id;
      cb();
    });
  }, function(err) {
    if(err) {
      return transactionDeferred.rollback(err);
    }
    var transaction = {};
    _.keys(transactionCnx).forEach(function(cnx) {
      var connection = transactionCnx[cnx];
      _.keys(connection.collections).forEach(function(col) {
        transaction[col] = connection.context.collections[col]._loadQuery({transaction:  transactionDictionary});
      });
    });
    cb(transaction, function(err, result) {
      if(err) {
        return transactionDeferred.rollback(err);
      }
      transactionDeferred.commit(result);

    });
  });
  return transactionDeferred;
};

var TransactionDeferred = function(connections) {
  this._connections = connections;
  this._commit = null;
  this._rollback = null;
  this._execCallback = null;
};

TransactionDeferred.prototype.commit = function(result) {
  var self = this;
  if(self._rollback) {
    throw new Error('Cannot commit when transaction has been rollbacked');
  }
  if(self._commit) {
    throw new Error('Transaction already commited');
  }
  this._commit = result;

  async.eachSeries(_.keys(self._connections), function(cnx, next) {
    self._connections[cnx].adapter.commit(self._connections[cnx].id, _.keys(self._connections[cnx].collections), next);
  }, function() {
    if(self._execCallback) {
      self._execCallback(null, self._commit);
    }
  });
};

TransactionDeferred.prototype.rollback = function(err) {
  var self = this;
  if(self._commit) {
    throw new Error('Cannot rollback when transaction has been commited');
  }
  if(self._rollback) {
    throw new Error('Transaction already rollbacked');
  }
  this._rollback = err;
  async.eachSeries(_.keys(self._connections), function(cnx, next) {
    self._connections[cnx].adapter.rollback(self._connections[cnx].id, _.keys(self._connections[cnx].collections), next);
  }, function() {
    if(self._execCallback) {
      self._execCallback(self._rollback);
    }
  });
};

TransactionDeferred.prototype.exec = function(cb) {
  this._execCallback = cb;
};
<|endoftext|>


<commit_before>//set main entry point path
global.BOT_DIR = require('path').resolve(__dirname, '..');
global.LIBS_DIR = require('path').resolve(BOT_DIR, 'libs');
global.MODULES_DIR = require('path').resolve(BOT_DIR, 'modules');

var logger = require(LIBS_DIR + '/logger');

function Bot() {
	//events
	var dispatcher = new(require('events').EventEmitter)();
	dispatcher.setMaxListeners(0); //remove listener limit
	//add empty config
	var config = new(require(LIBS_DIR + '/config').Config)();
	//add MM
	var moduleManager = new(require(LIBS_DIR + '/moduleManager').ModuleManager)(dispatcher, config);

	//load module on new listener
	dispatcher.on('newListener', function(event, listener) {
		var i, name;
		if(((i = event.indexOf('/')) + 1) && (name = event.substr(0, i))) {
			if(moduleManager.exists(name)) {
				moduleManager.load(name);
			}
		}
	});

	//bot config
	this.config = config;
	//bot MM
	this.modules = moduleManager;
	//dispatcher
	this.dispatcher = dispatcher;

	//list of core modules
	this.core_modules = {
		'irc': true
	};

	//bind to exit event of main process
	var bot = this;
	process.on('exit', function() {
		bot.emit('halt', bot);
		bot.unloadModules();
	});
}

Bot.prototype.addListener = function() {
	this.dispatcher.addListener.apply(this.dispatcher, arguments);
	return this;
};

Bot.prototype.on = function() {
	this.dispatcher.on.apply(this.dispatcher, arguments);
	return this;
};

Bot.prototype.off = Bot.prototype.removeListener = function() {
	this.dispatcher.removeListener.apply(this.dispatcher, arguments);
	return this;
};

Bot.prototype.once = function() {
	this.dispatcher.once.apply(this.dispatcher, arguments);
	return this;
};

Bot.prototype.emit = function() {
	this.dispatcher.emit.apply(this.dispatcher, arguments);
	return this;
};

Bot.prototype.loadConfig = function loadConfig(config, callback) {
	var bot = this;

	var error = null;
	if(typeof config === 'function' && typeof callback === 'undefined') {
		callback = config;
		config = undefined;
	}

	if(typeof config === 'string') {
		try {
			bot.config.extend(require(BOT_DIR + '/' + config));
			logger.info('Config loaded!');
		} catch(e) {
			logger.error('Cannot load config!');
			error = new Error('Cannot load config!');
		}
	} else if(config instanceof Object) {
		bot.config.extend(config);
	} else {
		try {
			bot.config.extend(require(BOT_DIR + '/config.json'));
		} catch(e) {
			logger.error('Cannot load config!');
			error = new Error('Cannot load config!');
		}
	}

	//make sure we have important values
	if(typeof bot.config.bot === 'undefined') {
		bot.config.bot = {
			'name': 'IRC-PONY',
			'modules': 'modules.json'
		};
	} else {
		if(typeof bot.config.bot.name === 'undefined') {
			bot.config.bot.name = 'IRC-PONY';
		}
		if(typeof bot.config.bot.modules === 'undefined') {
			bot.config.bot.modules = 'modules.json';
		}
	}

	if(callback) callback(error, bot.config);
	else if(error) throw error;

	logger.info('Config loaded!');
	return bot;
};

Bot.prototype.loadModules = function loadModules(modules, callback) {
	var bot = this;

	if(typeof modules === 'function' && typeof callback === 'undefined') {
		callback = modules;
		modules = {};
	}

	if(typeof bot.config.bot === 'undefined') { //we need atleast empty bot config
		bot.config.bot = {
			'modules': 'modules.json'
		};
	}

	var error = null;
	if(typeof modules === 'string') {
		bot.config.bot.modules = modules;
		modules = {};
	} else if(typeof modules === 'object' && modules instanceof Array) {
		var tmp = modules.slice(0);
		modules = {};
		for(var i = 0; i < tmp.length; i++) {
			modules[tmp[i]] = true;
		}

	} else if(typeof modules !== 'object' && typeof bot.config.bot.modules === 'string') {
		modules = {};
	} else if(typeof modules !== 'object') {
		logger.error('Modules was nor Object nor Array nor String! Trying to load default \'modules.json\'.');
		error = new Error('Modules was nor Object nor Array nor String! Trying to load default \'modules.json\'.');

		modules = {};
	}

	//first load core modules
	Object.keys(bot.core_modules).forEach(function(name) {
		if(bot.core_modules[name] === true) {
			bot.modules.load(name);
		}
	});

	//then custom modules
	if(Object.keys(modules).length <= 0) {
		try {
			modules = require(BOT_DIR + '/' + bot.config.bot.modules);
		} catch(e) {
			modules = {};
			logger.error('Cannot load modules file \'' + bot.config.bot.modules + '\'!');
			error = new Error('Cannot load modules file \'' + bot.config.bot.modules + '\'!');
		}
	}

	var keys = Object.keys(modules);
	if(keys.length > 0) {
		keys.forEach(function(name) {
			if(modules[name] === true) {
				bot.modules.load(name);
			}
		});
	}

	if(callback) callback(error, bot.modules);
	else if(error) throw error;

	logger.info('Modules loaded!');
	return bot;
};

Bot.prototype.unloadModules = function() {
	var bot = this;
	bot.modules.getModules().forEach(function(m) {
		bot.modules.unload(m.name);
	});
	logger.info('Modules unloaded!');
};

Bot.prototype.load = function load(names, callback) {
	var bot = this;

	if(!(names instanceof Array)) {
		names = [names];
	}

	var recallback = callback ?
	function(err, module, mm) {
		callback(err, module, mm, bot);
	} : undefined;

	names.forEach(function(name) {
		bot.modules.load(name, recallback);
	});

	return bot;
};

Bot.prototype.unload = function unload(names, callback) {
	var bot = this;

	if(!(names instanceof Array)) {
		names = [names];
	}

	var recallback = callback ?
	function(err, mm) {
		callback(err, mm, bot);
	} : undefined;

	names.forEach(function(name) {
		bot.modules.unload(name, recallback);
	});

	return bot;
};

Bot.prototype.run = function run() {
	this.emit('init', this);
	return this;
};

Bot.prototype.end = function end() {
	//halt event is emitted on process 'exit'
	process.nextTick(function() {
		process.exit(0);
	});
};

module.exports.Bot = Bot;
module.exports.create = function() {
	return new Bot();
};<commit_msg>some signal handling<commit_after>//set main entry point path
global.BOT_DIR = require('path').resolve(__dirname, '..');
global.LIBS_DIR = require('path').resolve(BOT_DIR, 'libs');
global.MODULES_DIR = require('path').resolve(BOT_DIR, 'modules');

var logger = require(LIBS_DIR + '/logger');

function Bot() {
	//events
	var dispatcher = new(require('events').EventEmitter)();
	dispatcher.setMaxListeners(0); //remove listener limit
	//add empty config
	var config = new(require(LIBS_DIR + '/config').Config)();
	//add MM
	var moduleManager = new(require(LIBS_DIR + '/moduleManager').ModuleManager)(dispatcher, config);

	//load module on new listener
	dispatcher.on('newListener', function(event, listener) {
		var i, name;
		if(((i = event.indexOf('/')) + 1) && (name = event.substr(0, i))) {
			if(moduleManager.exists(name)) {
				moduleManager.load(name);
			}
		}
	});

	//bot config
	this.config = config;
	//bot MM
	this.modules = moduleManager;
	//dispatcher
	this.dispatcher = dispatcher;

	//list of core modules
	this.core_modules = {
		'irc': true
	};

	//bind to exit event of main process
	var bot = this;
	process.on('exit', function() {
		bot.emit('halt', bot);
		bot.unloadModules();
	});

	//shutdown on ctrl+c gracefully
	process.on('SIGINT', function() {
		process.exit(0);
	});

	// This will override SIGTSTP and prevent the program from going to the background.
	process.on('SIGTSTP', function() {});
}

Bot.prototype.addListener = function() {
	this.dispatcher.addListener.apply(this.dispatcher, arguments);
	return this;
};

Bot.prototype.on = function() {
	this.dispatcher.on.apply(this.dispatcher, arguments);
	return this;
};

Bot.prototype.off = Bot.prototype.removeListener = function() {
	this.dispatcher.removeListener.apply(this.dispatcher, arguments);
	return this;
};

Bot.prototype.once = function() {
	this.dispatcher.once.apply(this.dispatcher, arguments);
	return this;
};

Bot.prototype.emit = function() {
	this.dispatcher.emit.apply(this.dispatcher, arguments);
	return this;
};

Bot.prototype.loadConfig = function loadConfig(config, callback) {
	var bot = this;

	var error = null;
	if(typeof config === 'function' && typeof callback === 'undefined') {
		callback = config;
		config = undefined;
	}

	if(typeof config === 'string') {
		try {
			bot.config.extend(require(BOT_DIR + '/' + config));
			logger.info('Config loaded!');
		} catch(e) {
			logger.error('Cannot load config!');
			error = new Error('Cannot load config!');
		}
	} else if(config instanceof Object) {
		bot.config.extend(config);
	} else {
		try {
			bot.config.extend(require(BOT_DIR + '/config.json'));
		} catch(e) {
			logger.error('Cannot load config!');
			error = new Error('Cannot load config!');
		}
	}

	//make sure we have important values
	if(typeof bot.config.bot === 'undefined') {
		bot.config.bot = {
			'name': 'IRC-PONY',
			'modules': 'modules.json'
		};
	} else {
		if(typeof bot.config.bot.name === 'undefined') {
			bot.config.bot.name = 'IRC-PONY';
		}
		if(typeof bot.config.bot.modules === 'undefined') {
			bot.config.bot.modules = 'modules.json';
		}
	}

	if(callback) callback(error, bot.config);
	else if(error) throw error;

	logger.info('Config loaded!');
	return bot;
};

Bot.prototype.loadModules = function loadModules(modules, callback) {
	var bot = this;

	if(typeof modules === 'function' && typeof callback === 'undefined') {
		callback = modules;
		modules = {};
	}

	if(typeof bot.config.bot === 'undefined') { //we need atleast empty bot config
		bot.config.bot = {
			'modules': 'modules.json'
		};
	}

	var error = null;
	if(typeof modules === 'string') {
		bot.config.bot.modules = modules;
		modules = {};
	} else if(typeof modules === 'object' && modules instanceof Array) {
		var tmp = modules.slice(0);
		modules = {};
		for(var i = 0; i < tmp.length; i++) {
			modules[tmp[i]] = true;
		}

	} else if(typeof modules !== 'object' && typeof bot.config.bot.modules === 'string') {
		modules = {};
	} else if(typeof modules !== 'object') {
		logger.error('Modules was nor Object nor Array nor String! Trying to load default \'modules.json\'.');
		error = new Error('Modules was nor Object nor Array nor String! Trying to load default \'modules.json\'.');

		modules = {};
	}

	//first load core modules
	Object.keys(bot.core_modules).forEach(function(name) {
		if(bot.core_modules[name] === true) {
			bot.modules.load(name);
		}
	});

	//then custom modules
	if(Object.keys(modules).length <= 0) {
		try {
			modules = require(BOT_DIR + '/' + bot.config.bot.modules);
		} catch(e) {
			modules = {};
			logger.error('Cannot load modules file \'' + bot.config.bot.modules + '\'!');
			error = new Error('Cannot load modules file \'' + bot.config.bot.modules + '\'!');
		}
	}

	var keys = Object.keys(modules);
	if(keys.length > 0) {
		keys.forEach(function(name) {
			if(modules[name] === true) {
				bot.modules.load(name);
			}
		});
	}

	if(callback) callback(error, bot.modules);
	else if(error) throw error;

	logger.info('Modules loaded!');
	return bot;
};

Bot.prototype.unloadModules = function() {
	var bot = this;
	bot.modules.getModules().forEach(function(m) {
		bot.modules.unload(m.name);
	});
	logger.info('Modules unloaded!');
};

Bot.prototype.load = function load(names, callback) {
	var bot = this;

	if(!(names instanceof Array)) {
		names = [names];
	}

	var recallback = callback ?
	function(err, module, mm) {
		callback(err, module, mm, bot);
	} : undefined;

	names.forEach(function(name) {
		bot.modules.load(name, recallback);
	});

	return bot;
};

Bot.prototype.unload = function unload(names, callback) {
	var bot = this;

	if(!(names instanceof Array)) {
		names = [names];
	}

	var recallback = callback ?
	function(err, mm) {
		callback(err, mm, bot);
	} : undefined;

	names.forEach(function(name) {
		bot.modules.unload(name, recallback);
	});

	return bot;
};

Bot.prototype.run = function run() {
	this.emit('init', this);
	return this;
};

Bot.prototype.end = function end() {
	//halt event is emitted on process 'exit'
	process.nextTick(function() {
		process.exit(0);
	});
};

module.exports.Bot = Bot;
module.exports.create = function() {
	return new Bot();
};<|endoftext|>


<commit_before>// Attachments parser plugin
// - add attachments as `<attach>` tag to AST
// - collect attach refs
// - remove attach refs from tail
// - render `<attach>` tag to link with image or to link
//
'use strict';

var _ = require('lodash');
var $ = require('../cheequery');

module.exports = function (N, mTypes) {

  return function (parser) {

    ///////////////////////////////////////////////////////////////////////////
    // Add attachments as `attach` tag to AST

    var defaultImageRender = parser.md.renderer.rules.image;

    parser.md.renderer.rules.image = function (tokens, idx, options, env, self) {
      var match = _.find(N.router.matchAll(tokens[idx].src), function (match) {
        return match.meta.methods.get === 'users.media';
      });

      // It is not URL of media, continue
      if (!match) {
        return defaultImageRender(tokens, idx, options, env, self);
      }

      return '<attach data-nd-media-id="' + match.params.media_id + '" data-nd-src="' + tokens[idx].src + '"></attach>';
    };

    ///////////////////////////////////////////////////////////////////////////
    // Calculate attach tail

    parser.bus.on('transform', function calc_tail(data) {
      // Get refs from `attach` tag
      var refs = _.uniq(data.ast.find('attach').map(function () {
        return $(this).data('nd-media-id');
      }));

      var tail = _.uniq(data.params.attachments, function (attach) {
        return attach.media_id;
      });

      tail = tail.filter(function (attach) {
        return refs.indexOf(attach.media_id) === -1;
      });

      data.result.tail = tail;
    });

    ///////////////////////////////////////////////////////////////////////////
    // Render `attach` tag to link with image or to link

    parser.bus.on('render', function render_attachments(data) {
      var escapeHtml = parser.md.utils.escapeHtml;

      var binTpl = _.template('<a href="<%= href %>"><%= text %>');
      var imgTpl = _.template('<a href="<%= href %>"><img src="<%= src %>">');

      var $attach, attachData, mediaId;

      data.ast.find('attach').each(function () {
        $attach = $(this);
        mediaId = $attach.data('nd-media-id');

        // Find attachment info (`file_name`, 'type') by `media_id`
        attachData = _.find(data.params.attachments, function (attach) {
          return attach.media_id === mediaId;
        });

        // If attachment is image replace `attach` tag to link and image
        if (attachData.type === mTypes.IMAGE) {
          $attach.replaceWith(imgTpl({
            href: $attach.data('nd-src'),
            src: N.router.linkTo('core.gridfs', { bucket: mediaId + '_sm' })
          }));
          return;
        }

        // If attachment is binary replace `attach` tag to link
        if (attachData.type === mTypes.BINARY) {
          $attach.replaceWith(binTpl({
            href: $attach.data('nd-src'),
            text: escapeHtml(attachData.file_name)
          }));
          return;
        }

        // Remove if invalid attachment type
        $attach.remove();
      });
    });
  };
};
<commit_msg>editor: added missing check (undefined)<commit_after>// Attachments parser plugin
// - add attachments as `<attach>` tag to AST
// - collect attach refs
// - remove attach refs from tail
// - render `<attach>` tag to link with image or to link
//
'use strict';

var _ = require('lodash');
var $ = require('../cheequery');

module.exports = function (N, mTypes) {

  return function (parser) {

    ///////////////////////////////////////////////////////////////////////////
    // Add attachments as `attach` tag to AST

    var defaultImageRender = parser.md.renderer.rules.image;

    parser.md.renderer.rules.image = function (tokens, idx, options, env, self) {
      var match = _.find(N.router.matchAll(tokens[idx].src), function (match) {
        return match.meta.methods.get === 'users.media';
      });

      // It is not URL of media, continue
      if (!match) {
        return defaultImageRender(tokens, idx, options, env, self);
      }

      return '<attach data-nd-media-id="' + match.params.media_id + '" data-nd-src="' + tokens[idx].src + '"></attach>';
    };

    ///////////////////////////////////////////////////////////////////////////
    // Calculate attach tail

    parser.bus.on('transform', function calc_tail(data) {
      // Get refs from `attach` tag
      var refs = _.uniq(data.ast.find('attach').map(function () {
        return $(this).data('nd-media-id');
      }));

      var tail = _.uniq(data.params.attachments, function (attach) {
        return attach.media_id;
      });

      tail = tail.filter(function (attach) {
        return refs.indexOf(attach.media_id) === -1;
      });

      data.result.tail = tail;
    });

    ///////////////////////////////////////////////////////////////////////////
    // Render `attach` tag to link with image or to link

    parser.bus.on('render', function render_attachments(data) {
      var escapeHtml = parser.md.utils.escapeHtml;

      var binTpl = _.template('<a href="<%= href %>"><%= text %>');
      var imgTpl = _.template('<a href="<%= href %>"><img src="<%= src %>">');

      var $attach, attachData, mediaId;

      data.ast.find('attach').each(function () {
        $attach = $(this);
        mediaId = $attach.data('nd-media-id');

        // Find attachment info (`file_name`, 'type') by `media_id`
        attachData = _.find(data.params.attachments, function (attach) {
          return attach.media_id === mediaId;
        });

        // If attachment is image replace `attach` tag to link and image
        if (attachData && attachData.type === mTypes.IMAGE) {
          $attach.replaceWith(imgTpl({
            href: $attach.data('nd-src'),
            src: N.router.linkTo('core.gridfs', { bucket: mediaId + '_sm' })
          }));
          return;
        }

        // If attachment is binary replace `attach` tag to link
        if (attachData && attachData.type === mTypes.BINARY) {
          $attach.replaceWith(binTpl({
            href: $attach.data('nd-src'),
            text: escapeHtml(attachData.file_name)
          }));
          return;
        }

        // Remove if invalid attachment type
        $attach.remove();
      });
    });
  };
};
<|endoftext|>


<commit_before>var path = require('path');
var fs = require('fs');
var cfg = require('config');

var isWindows = require('os').platform().match(/win/i);

exports.getACPath = function() {
    return cfg.get('AC.installpath');
};

exports.getServerExecutable = function() {
    return path.join(this.getACPath(), isWindows ? 'acServer.exe' : 'acServer');
};

exports.getServersPath = function() {
    return path.join(this.getACPath(), 'servers');
};

exports.getPresetsPath = function() {
    return path.join(this.getACPath(), 'presets');
};

exports.getTracksPath = function() {
    return path.join(this.getACPath(), 'content', 'tracks');
};

exports.getCarsPath = function() {
    return path.join(this.getACPath(), 'content', 'cars');
};

exports.getPresetNames = function (filter) {
    var presetRegExp = new RegExp(filter, 'i');
    var presetsMatched = [];
    var presetsPath = this.getPresetsPath();
    fs.readdirSync(presetsPath).every(
        function checkItem(dirItem) {
            if (dirItem.match(presetRegExp)) {
                if (fs.lstatSync(path.join(presetsPath, dirItem)).isDirectory()) {
                    presetsMatched.push(dirItem);
                }
            }

            return true;
        }
    );
    return presetsMatched;
};

exports.getPresetName = function (presetPrefix) {
    var presetsMatched = this.getPresetNames(presetPrefix);
    if (presetsMatched.length === 0) {
        return false;
    }
    return presetsMatched[0];
};

require('fs-extra').ensureDirSync(exports.getServersPath());

if(!fs.existsSync(exports.getServerExecutable())) {
    console.error('AC server binary "' + exports.getServerExecutable() + '" not found, aborting ...');
    console.error(' Please execute acCtrl from within the AC Dedicated Server Directory');
    process.exit(1);
}
<commit_msg>add getPreset method<commit_after>var path = require('path');
var fs = require('fs');
var cfg = require('config');

var isWindows = require('os').platform().match(/win/i);

exports.getACPath = function() {
    return cfg.get('AC.installpath');
};

exports.getServerExecutable = function() {
    return path.join(this.getACPath(), isWindows ? 'acServer.exe' : 'acServer');
};

exports.getServersPath = function() {
    return path.join(this.getACPath(), 'servers');
};

exports.getPresetsPath = function() {
    return path.join(this.getACPath(), 'presets');
};

exports.getTracksPath = function() {
    return path.join(this.getACPath(), 'content', 'tracks');
};

exports.getCarsPath = function() {
    return path.join(this.getACPath(), 'content', 'cars');
};

exports.getPresetNames = function (filter) {
    var presetRegExp = new RegExp(filter, 'i');
    var presetsMatched = [];
    var presetsPath = this.getPresetsPath();
    fs.readdirSync(presetsPath).every(
        function checkItem(dirItem) {
            if (dirItem.match(presetRegExp)) {
                if (fs.lstatSync(path.join(presetsPath, dirItem)).isDirectory()) {
                    presetsMatched.push(dirItem);
                }
            }

            return true;
        }
    );
    return presetsMatched;
};

exports.getPreset = function (presetName) {
    return require('./preset')(presetName);
};

require('fs-extra').ensureDirSync(exports.getServersPath());

if(!fs.existsSync(exports.getServerExecutable())) {
    console.error('AC server binary "' + exports.getServerExecutable() + '" not found, aborting ...');
    console.error(' Please execute acCtrl from within the AC Dedicated Server Directory');
    process.exit(1);
}
<|endoftext|>


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

.controller('AccountCtrl', function($scope) {
})

.directive('noScroll', function($document) {

  return {
    restrict: 'A',
    link: function($scope, $element, $attr) {

      $document.on('touchmove', function(e) {
        e.preventDefault();
      });
    }
  }
})

.controller('DashCtrl', function($scope, $http, $localstorage,TDCardDelegate) {
  var cardTypes;

  $scope.cardDestroyed = function(index) {
    $scope.cards.splice(index, 1);
    // $scope.addCard();
    console.log('destroyed');
  };

  $scope.addCard = function() {

    var newCard = cardTypes.splice(Math.floor(Math.random() * cardTypes.length),1)[0];
    //newCard.id = Math.random();
    console.log('new card is', newCard);
    $scope.cards.push(angular.extend({}, newCard));
  }

  $scope.startExplore = function() {
    console.log($localstorage.getObject('temp'));

    if(Object.keys($localstorage.getObject('temp')).length ===0){
      console.log('making a http request');
      $http.get("https://mealmatch2.herokuapp.com/test/explore").success(function(data, status, headers, config) {
        console.log('success', data);
        cardTypes = data;
        $scope.cards = Array.prototype.slice.call(cardTypes, 1,4);
        $localstorage.setObject('temp', data);
      })
      .error(function(data, status, headers, config) {
      console.log('fail', data);
      });
    } else{ //currently pulling from local storage data to avoid overusing api

      //make a copy of local storage so that local storage remains persistant
      cardTypes = Array.prototype.slice.call($localstorage.getObject('temp'));
      //load 3 cards for view
      $scope.cards = Array.prototype.splice.call(cardTypes, 1,4);
    }
  };

  $scope.startExplore();
})

.controller('CardCtrl', function($scope, TDCardDelegate) {
  $scope.cardSwipedLeft = function(index) {
    console.log('LEFT SWIPE');
    $scope.addCard();
  };
  $scope.cardSwipedRight = function(index) {
    console.log('RIGHT SWIPE');
    $scope.addCard();
  };
})

.filter('largerimages', function () {
  console.log('this ran');
    return function (item) {
      return item.replace('s90', 's450');
    }
  });
<commit_msg>add card on destroy instead of swipe left/right<commit_after>angular.module('starter.controllers', [])

.controller('AccountCtrl', function($scope) {
})

.directive('noScroll', function($document) {

  return {
    restrict: 'A',
    link: function($scope, $element, $attr) {

      $document.on('touchmove', function(e) {
        e.preventDefault();
      });
    }
  }
})

.controller('DashCtrl', function($scope, $http, $localstorage,TDCardDelegate,$timeout) {
  var cardTypes;

  $scope.cardDestroyed = function(index) {
    $scope.cards.splice(index, 1);
    console.log('destroyed');
    $timeout($scope.addCard,0);
  };

  $scope.addCard = function() {

    var newCard = cardTypes.splice(Math.floor(Math.random() * cardTypes.length),1)[0];
    newCard.id = Math.random();
    console.log('new card is', newCard);
    $scope.cards.push(angular.extend({}, newCard));
  }

  $scope.startExplore = function() {
    console.log($localstorage.getObject('temp'));

    if(Object.keys($localstorage.getObject('temp')).length ===0){
      console.log('making a http request');
      $http.get("https://mealmatch2.herokuapp.com/test/explore").success(function(data, status, headers, config) {
        console.log('success', data);
        cardTypes = data;
        $scope.cards = Array.prototype.slice.call(cardTypes, 1,1);
        $localstorage.setObject('temp', data);
      })
      .error(function(data, status, headers, config) {
      console.log('fail', data);
      });
    } else{ //currently pulling from local storage data to avoid overusing api

      //make a copy of local storage so that local storage remains persistant
      cardTypes = Array.prototype.slice.call($localstorage.getObject('temp'));
      //load 3 cards for view
      $scope.cards = Array.prototype.splice.call(cardTypes, 1,1);
    }
  };

  $scope.startExplore();
})

.controller('CardCtrl', function($scope, TDCardDelegate) {
  $scope.cardSwipedLeft = function(index) {
    console.log('LEFT SWIPE');
    // $scope.addCard();
  };
  $scope.cardSwipedRight = function(index) {
    console.log('RIGHT SWIPE');
    // $scope.addCard();
  };
})

.filter('largerimages', function () {
  console.log('this ran');
    return function (item) {
      return item.replace('s90', 's450');
    }
  });
<|endoftext|>


<commit_before>/* ************************************************************************

   qooxdoo - the new era of web development

   http://qooxdoo.org

   Copyright:
     2017 Zenesis Ltd

   License:
     MIT: https://opensource.org/licenses/MIT
     See the LICENSE file in the project's top-level directory for details.

   Authors:
     * John Spackman (john.spackman@zenesis.com, @johnspackman)

************************************************************************ */

require("qooxdoo");
const path = require("upath");
const process = require("process");
const express = require("express");

require("app-module-path").addPath(process.cwd() + "/node_modules");

require("./Compile");

/**
 * Handles compilation of the project by qxcompiler
 */
qx.Class.define("qx.tool.cli.commands.Serve", {
  extend: qx.tool.cli.commands.Compile,

  statics: {

    getYargsCommand: function() {
      return {
        command   : "serve [configFile]",
        describe  : "runs a webserver to run the current application with continuous compilation, using compile.json",
        builder   : {
          "target": {
            "default": "source",
            describe: "Set the target type: source or build or class name",
            requiresArg: true,
            type: "string"
          },
          "output-path": {
            describe: "Base path for output",
            nargs: 1,
            requiresArg: true,
            type: "string"
          },
          "locale": {
            describe: "Compile for a given locale",
            nargs: 1,
            requiresArg: true,
            type: "string",
            array: true
          },
          "write-all-translations": {
            describe: "enables output of all translations, not just those that are explicitly referenced",
            type: "boolean"
          },
          "set": {
            describe: "sets an environment value",
            nargs: 1,
            requiresArg: true,
            type: "string",
            array: true
          },
          "machine-readable": {
            describe: "output compiler messages in machine-readable format",
            type: "boolean"
          },
          "verbose": {
            alias: "v",
            describe: "enables additional progress output to console",
            type: "boolean"
          },
          "minify": {
            describe: "disables minification (for build targets only)",
            choices: ["off", "minify", "mangle", "beautify"],
            default: "mangle"
          },
          "save-unminified": {
            describe: "Saves a copy of the unminified version of output files (build target only)",
            type: "boolean",
            default: false
          },
          "erase": {
            describe: "Enabled automatic deletion of the output directory when compiler version changes",
            type: "boolean",
            default: true
          },
          "typescript": {
            describe: "Outputs typescript definitions in qooxdoo.d.ts",
            type: "boolean"
          },
          "add-created-at": {
            describe: "Adds code to populate object's $$createdAt",
            type: "boolean"
          },
          "clean": {
            describe: "Deletes the target dir before compile",
            type: "boolean"
          },
          "listen-port": {
            describe: "The port for the web browser to listen on",
            type: "number",
            default: 8080
          },
          "write-library-info": {
            describe: "Write library information to the script, for reflection",
            type: "boolean",
            default: true
          }
        },
        handler   : function(argv) {
          return new qx.tool.cli.commands.Serve(argv)
            .process()
            .catch(e => {
              console.error(e.stack || e.message);
              process.exit(1);
            });
        }
      };
    }
  },

  members: {
    /*
     * @Override
     */
    process: async function() {
      this.argv.watch = true;
      this.argv["machine-readable"] = false;
      this.argv["feedback"] = false;
      return this.base(arguments).then(() => this.runWebServer());
    },

    /**
     *
     * @returns
     */
    runWebServer: function() {
      var maker = this._getMaker();
      var config = this._getConfig();
      var target = maker.getTarget();
      var apps = maker.getApplications();

      const app = express();
      if ((apps.length === 1) && apps[0].getWriteIndexHtmlToRoot()) {
        app.use("/", express.static(target.getOutputDir()));
      } else {
        app.use("/", express.static(path.join(__dirname, "../../../../../tool/cli/serve/build")));
        app.use("/build/", express.static(target.getOutputDir()));
        var obj = {
          target: {
            type: target.getType(),
            outputDir: "/build/"
          },
          apps: apps.map(app => ({
            name: app.getName(),
            type: app.getType(),
            title: app.getTitle() || app.getName(),
            outputPath: target.getProjectDir(app) + "/"
          }))
        };
        app.get("/serve.api/apps.json", (req, res) => {
          res.set("Content-Type", "application/json");
          res.send(JSON.stringify(obj, null, 2));
        });
      }
      this.addListenerOnce("made", e =>
        app.listen(config.serve.listenPort, () => qx.tool.compiler.Console.print("qx.tool.cli.serve.webStarted", "http://localhost:" + config.serve.listenPort)));
    },

    /*
     * @Override
     */
    _mergeArguments: function(parsedArgs, config, contribConfig) {
      this.base(arguments, parsedArgs, config, contribConfig);
      if (!config.serve) {
        config.serve = {};
      }
      config.serve.listenPort = config.serve.listenPort||this.argv.listenPort;
      return config;
    }
  },

  defer: function(statics) {
    qx.tool.compiler.Console.addMessageIds({
      "qx.tool.cli.serve.webStarted": "Web server started, please browse to %1"
    });
  }
});

<commit_msg>Fix missing serve property (#292)<commit_after>/* ************************************************************************

   qooxdoo - the new era of web development

   http://qooxdoo.org

   Copyright:
     2017 Zenesis Ltd

   License:
     MIT: https://opensource.org/licenses/MIT
     See the LICENSE file in the project's top-level directory for details.

   Authors:
     * John Spackman (john.spackman@zenesis.com, @johnspackman)

************************************************************************ */

require("qooxdoo");
const path = require("upath");
const process = require("process");
const express = require("express");

require("app-module-path").addPath(process.cwd() + "/node_modules");

require("./Compile");

/**
 * Handles compilation of the project by qxcompiler
 */
qx.Class.define("qx.tool.cli.commands.Serve", {
  extend: qx.tool.cli.commands.Compile,

  statics: {

    getYargsCommand: function() {
      return {
        command   : "serve [configFile]",
        describe  : "runs a webserver to run the current application with continuous compilation, using compile.json",
        builder   : {
          "target": {
            "default": "source",
            describe: "Set the target type: source or build or class name",
            requiresArg: true,
            type: "string"
          },
          "output-path": {
            describe: "Base path for output",
            nargs: 1,
            requiresArg: true,
            type: "string"
          },
          "locale": {
            describe: "Compile for a given locale",
            nargs: 1,
            requiresArg: true,
            type: "string",
            array: true
          },
          "write-all-translations": {
            describe: "enables output of all translations, not just those that are explicitly referenced",
            type: "boolean"
          },
          "set": {
            describe: "sets an environment value",
            nargs: 1,
            requiresArg: true,
            type: "string",
            array: true
          },
          "machine-readable": {
            describe: "output compiler messages in machine-readable format",
            type: "boolean"
          },
          "verbose": {
            alias: "v",
            describe: "enables additional progress output to console",
            type: "boolean"
          },
          "minify": {
            describe: "disables minification (for build targets only)",
            choices: ["off", "minify", "mangle", "beautify"],
            default: "mangle"
          },
          "save-unminified": {
            describe: "Saves a copy of the unminified version of output files (build target only)",
            type: "boolean",
            default: false
          },
          "erase": {
            describe: "Enabled automatic deletion of the output directory when compiler version changes",
            type: "boolean",
            default: true
          },
          "typescript": {
            describe: "Outputs typescript definitions in qooxdoo.d.ts",
            type: "boolean"
          },
          "add-created-at": {
            describe: "Adds code to populate object's $$createdAt",
            type: "boolean"
          },
          "clean": {
            describe: "Deletes the target dir before compile",
            type: "boolean"
          },
          "listen-port": {
            describe: "The port for the web browser to listen on",
            type: "number",
            default: 8080
          },
          "write-library-info": {
            describe: "Write library information to the script, for reflection",
            type: "boolean",
            default: true
          }
        },
        handler   : function(argv) {
          return new qx.tool.cli.commands.Serve(argv)
            .process()
            .catch(e => {
              console.error(e.stack || e.message);
              process.exit(1);
            });
        }
      };
    }
  },

  members: {
    /*
     * @Override
     */
    process: async function() {
      this.argv.watch = true;
      this.argv["machine-readable"] = false;
      this.argv["feedback"] = false;
      return this.base(arguments).then(() => this.runWebServer());
    },

    /**
     *
     * @returns
     */
    runWebServer: function() {
      var maker = this._getMaker();
      var config = this._getConfig();
      var target = maker.getTarget();
      var apps = maker.getApplications();

      const app = express();
      if ((apps.length === 1) && apps[0].getWriteIndexHtmlToRoot()) {
        app.use("/", express.static(target.getOutputDir()));
      } else {
        app.use("/", express.static(path.join(__dirname, "../../../../../tool/cli/serve/build")));
        app.use("/build/", express.static(target.getOutputDir()));
        var obj = {
          target: {
            type: target.getType(),
            outputDir: "/build/"
          },
          apps: apps.map(app => ({
            name: app.getName(),
            type: app.getType(),
            title: app.getTitle() || app.getName(),
            outputPath: target.getProjectDir(app) + "/"
          }))
        };
        app.get("/serve.api/apps.json", (req, res) => {
          res.set("Content-Type", "application/json");
          res.send(JSON.stringify(obj, null, 2));
        });
      }
      this.addListenerOnce("made", e =>
        app.listen(config.serve.listenPort, () => qx.tool.compiler.Console.print("qx.tool.cli.serve.webStarted", "http://localhost:" + config.serve.listenPort)));
    },

    /*
     * @Override
     */
    _mergeArguments: function(parsedArgs, config, contribConfig) {
      if (!config.serve) {
        config.serve = {};
      }
      this.base(arguments, parsedArgs, config, contribConfig);
      config.serve.listenPort = config.serve.listenPort||this.argv.listenPort;
      return config;
    }
  },

  defer: function(statics) {
    qx.tool.compiler.Console.addMessageIds({
      "qx.tool.cli.serve.webStarted": "Web server started, please browse to %1"
    });
  }
});

<|endoftext|>


<commit_before>/**
 * Created by michael on 22/08/15.
 */
define(function() {
    'use strict';

    function Item(store) {

        return store.defineResource({
            name: 'Item',
            relations: {
                hasOne: {
                    RobotPart: {
                        localField: 'robotpart',
                        localKey: 'robot_id'
                    }
                }
            }
        });

    };

    return Item;

});<commit_msg>falscher localKey in der Item -> RobotPart Beziehung<commit_after>/**
 * Created by michael on 22/08/15.
 */
define(function() {
    'use strict';

    function Item(store) {

        return store.defineResource({
            name: 'Item',
            relations: {
                hasOne: {
                    RobotPart: {
                        localField: 'robotpart',
                        localKey: 'robotpart_id'
                    }
                }
            }
        });

    };

    return Item;

});<|endoftext|>


<commit_before>// Demo of Pararr.js
// Run with:
//  >node demo.js
// Output:
//  >Parallel map returned: 1,2,6,24,120,720,5040,40320,362880,3628800
//  >Parallel map returned: 1,2,3,5,7

var p = require('./lib/pararr'),

	arr = [1,2,3,4,5,6,7,8,9,10],

	// Imperformant factorial funciton
	fac = function(a) {
		return (function facI(a) {
			if (a === 1) {
				return a;

			}
			return a * facI(a - 1);
		})(a);
	},

	// Imperformant primality check
	isPrime = function(a) {
		var i;
		if (a <= 2) {
			return true;
		}
		for (i = Math.ceil(Math.sqrt(a)) ; i > 1; i--) {
			if (a % i === 0) {
				return false;
			}
		}
		return true;
	};

// Parallel map
p.map(arr, fac, function(err, res) {
	console.log('Parallel map returned: ' + res);

	// Parallel filter
	p.filter(arr, isPrime, function(err, res) {
		console.log('Parallel filter returned: ' + res);

		p.destroy(); //Cleanup
	});
});

<commit_msg>Fixed comments<commit_after>// Demo of Pararr.js
// Run with:
//  >node demo.js
// Output:
//  >Parallel map returned: 1,2,6,24,120,720,5040,40320,362880,3628800
//  >Parallel map returned: 1,2,3,5,7

var p = require('./lib/pararr'),

	arr = [1,2,3,4,5,6,7,8,9,10],

	// Inperformant factorial funciton
	fac = function(a) {
		return (function facI(a) {
			if (a === 1) {
				return a;

			}
			return a * facI(a - 1);
		})(a);
	},

	// Inperformant primality check
	isPrime = function(a) {
		var i;
		if (a <= 2) {
			return true;
		}
		for (i = Math.ceil(Math.sqrt(a)) ; i > 1; i--) {
			if (a % i === 0) {
				return false;
			}
		}
		return true;
	};

// Parallel map
p.map(arr, fac, function(err, res) {
	console.log('Parallel map returned: ' + res);

	// Parallel filter
	p.filter(arr, isPrime, function(err, res) {
		console.log('Parallel filter returned: ' + res);

		p.destroy(); //Cleanup
	});
});

<|endoftext|>


<commit_before>import * as I from 'immutable';
import * as F from '../arithmetic/float';
import _M from '../arithmetic/matrix';
import _V from '../arithmetic/vector';

const M = _M(F, 0, 1);
const V = _V(F, 0);

const faceNormal = function faceNormal(vs) {
  vs = I.List(vs);

  const es = vs.pop().zip(vs.shift()).push([vs.last(), vs.first()]);
  const normal = es
    .map(e => V.crossProduct(e[0], e[1]))
    .reduce(V.plus);

  return V.normalized(normal);
};

const faceNormals = (pos, faces) =>
  faces.map(idcs => faceNormal(idcs.map(i => pos.get(i))));

const vertexNormals = function vertexNormals(pos, faces, faceNormals) {
  const normals = pos.map(v => V.scaled(0, v)).asMutable();

  faces.forEach((f, i) => {
    const n = faceNormals.get(i);
    f.forEach(k => { normals.update(k, v => V.plus(v, n)); });
  });

  return normals.map(V.normalized);
};

const pos = I.fromJS([[0,0,0], [0,0,1], [0,1,0], [0,1,1],
                      [1,0,0], [1,0,1], [1,1,0], [1,1,1]]).map(V.make);

const faces = I.fromJS([[0,1,3,2],[5,4,6,7],
                        [1,0,4,5],[2,3,7,6],
                        [0,2,6,4],[3,1,5,7]]);

const normals = faceNormals(pos, faces);

console.log(normals);

console.log(vertexNormals(pos, faces, normals));
<commit_msg>start implementation of subdivision surface<commit_after>import * as I from 'immutable';
import * as F from '../arithmetic/float';
import _M from '../arithmetic/matrix';
import _V from '../arithmetic/vector';

const M = _M(F, 0, 1);
const V = _V(F, 0);

const pairs = as => as.pop().zip(as.shift()).push([as.last(), as.first()]);

const corners = pos => idcs => idcs.map(i => pos.get(i));

const centroid = pos => V.scaled(1/pos.size, pos.reduce(V.plus));

const faceNormal = vs => V.normalized(
  pairs(I.List(vs))
    .map(e => V.crossProduct(e[0], e[1]))
    .reduce(V.plus)
);

const faceNormals = (pos, faces) => faces.map(corners(pos)).map(faceNormal);

const vertexNormals = function vertexNormals(pos, faces, faceNormals) {
  const normals = pos.map(v => V.scaled(0, v)).asMutable();

  faces.forEach((f, i) => {
    const n = faceNormals.get(i);
    f.forEach(k => { normals.update(k, v => V.plus(v, n)); });
  });

  return normals.map(V.normalized);
};

const subD = function subD({ pos, faces, isFixed }) {
  const n        = pos.size;
  const m        = faces.size;
  const rPos     = pos.asMutable();
  const rIsFixed = isFixed.asMutable();

  faces.map(corners(pos)).map(centroid).forEach(v => rPos.push(v));
  I.Repeat(false, faces.size).forEach(x => rIsFixed.push(x));

  const rFaces    = I.List().asMutable();
  const edgeIndex = I.Map().asMutable();

  faces.forEach((vs, f) => {
    const k = vs.size;
    const edgePointIndices = [];

    pairs(vs).forEach(([v, w]) => {
      let e = edgeIndex.get(I.List([w, v]));
      if (e == null) {
        e = rPos.size;
        rPos.push(V.scaled(0.5, V.plus(pos.get(v), pos.get(w))));
        rIsFixed.push(isFixed.get(v) && isFixed.get(w));
      }
      edgeIndex.set(I.List([v, w]), e);
      edgePointIndices.push(e);
    });

    I.Range(0, k)
      .map(j => I.List([
        n + f,
        edgePointIndices[(j + k - 1) % k],
        vs.get(j),
        edgePointIndices[j]
      ]))
      .forEach(f => rFaces.push(f));
  });

  return {
    pos    : rPos.asImmutable(),
    faces  : rFaces.asImmutable(),
    isFixed: rIsFixed.asImmutable()
  };
};

const pos = I.fromJS([[0,0,0], [0,0,1], [0,1,0], [0,1,1],
                      [1,0,0], [1,0,1], [1,1,0], [1,1,1]]).map(V.make);

const faces = I.fromJS([[0,1,3,2],[5,4,6,7],
                        [1,0,4,5],[2,3,7,6],
                        [0,2,6,4],[3,1,5,7]]);

const normals = faceNormals(pos, faces);

console.log(normals);

console.log(vertexNormals(pos, faces, normals));

console.log(subD({
  pos,
  faces,
  isFixed: I.List(I.Repeat(true, 8))
}));
<|endoftext|>


<commit_before>/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice, this
    list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

if(!GLMAT_EPSILON) {
    var GLMAT_EPSILON = 0.000001;
}

if(!GLMAT_ARRAY_TYPE) {
    var GLMAT_ARRAY_TYPE = (typeof Float32Array !== 'undefined') ? Float32Array : Array;
}

if(!GLMAT_RANDOM) {
    var GLMAT_RANDOM = Math.random;
}

/**
 * @class Common utilities
 * @name glMatrix
 */
var glMatrix = {};

/**
 * Sets the type of array used when creating new vectors and matricies
 *
 * @param {Type} type Array type, such as Float32Array or Array
 */
glMatrix.setMatrixArrayType = function(type) {
    GLMAT_ARRAY_TYPE = type;
}

if(typeof(exports) !== 'undefined') {
    exports.glMatrix = glMatrix;
}

/**
* Convert Degree To Radian
*
* @param {Number} Angle in Degrees
*/
glMatrix.toRadian = function(a){
     return a * (Math.PI / 180);
}
<commit_msg>Move degree out of toRadian<commit_after>/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice, this
    list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

if(!GLMAT_EPSILON) {
    var GLMAT_EPSILON = 0.000001;
}

if(!GLMAT_ARRAY_TYPE) {
    var GLMAT_ARRAY_TYPE = (typeof Float32Array !== 'undefined') ? Float32Array : Array;
}

if(!GLMAT_RANDOM) {
    var GLMAT_RANDOM = Math.random;
}

/**
 * @class Common utilities
 * @name glMatrix
 */
var glMatrix = {};

/**
 * Sets the type of array used when creating new vectors and matricies
 *
 * @param {Type} type Array type, such as Float32Array or Array
 */
glMatrix.setMatrixArrayType = function(type) {
    GLMAT_ARRAY_TYPE = type;
}

if(typeof(exports) !== 'undefined') {
    exports.glMatrix = glMatrix;
}

var degree = Math.PI / 180;

/**
* Convert Degree To Radian
*
* @param {Number} Angle in Degrees
*/
glMatrix.toRadian = function(a){
     return a * degree;
}
<|endoftext|>


<commit_before>var config = require('./config.js')
if (!config.couch) {
  throw new Error('must set an exports.couch url in config.js')
}
if (!config.couch.match(/\/$/)) config.couch += '/'

if (config.auth) {
  var auth = new Buffer(config.auth).toString('base64')
}

var file = process.argv[2]
if (!file) throw new Error('usage: node upload.js <logfile>')

var WORKERS = +process.env.WORKERS || 48

var request = require('request')
var LogParse = require('couchdb-log-parse')
var fs = require('fs')
var zlib = require('zlib')

var parser = new LogParse()

var downloads = {}
var k
var counts = []

console.error('Parsing log file... ' + file);
var st = fs.createReadStream(file)
if (file.match(/\.gz$/)) st = st.pipe(zlib.Gunzip())

st.pipe(parser)
  .on('message', function (msg) {
    if (msg.type !== 'http' ||
        msg.statusCode !== 200 ||
        msg.method !== 'GET' ||
        !msg.url.match('tgz')) return
    var pkg = msg.url.split('/')[2]

    k = k || msg.date.getTime()
    var day = msg.date.toISOString().split('T')[0]
    downloads[day] = downloads[day] || {}
    var d = downloads[day]

    d[pkg] = d[pkg] || 0
    d[pkg] ++
  })
  .on('end', function () {
    console.error('tallying up counts...')
    Object.keys(downloads).forEach(function (d) {
      var day = downloads[d]
      Object.keys(day).forEach(function (pkg) {
        var count = day[pkg]
        counts.push({ _id: pkg + '_' + k + '_' + d,
                      pkg: pkg,
                      count: count,
                      day: d })
      })
    })
    uploadCounts()
  })

function uploadCounts () {
  if (!counts) throw new Error('must tally up first')

  console.error('uploading count data...')
  var i = 0;
  for (var i = 0; i < WORKERS; i ++) work(i)
}

function work (id) {
  var c = counts.pop()
  if (!c) return console.log('done worker '+id);
  var r = { uri: config.couch + c._id,
            body: c,
            method: 'PUT',
            json: true }
  if (auth) r.headers = { authorization: 'Basic ' + auth }
  console.error(counts.length, c._id, c.count)
  request(r, function (er, res, body) {
    if (er || (res && res.statusCode >= 400)) {
      console.error(c._id, res && res.statusCode || er)
    }
    work(id)
  })
}
<commit_msg>no longer upload to /downloads database<commit_after>// This is no longer relevant, since npm-lylog actually gets the downloads.
// There will rarely be a tgz in these logs, and when there is, it is almost
// certainly a duplicate.
return
var config = require('./config.js')
if (!config.couch) {
  throw new Error('must set an exports.couch url in config.js')
}
if (!config.couch.match(/\/$/)) config.couch += '/'

if (config.auth) {
  var auth = new Buffer(config.auth).toString('base64')
}

var file = process.argv[2]
if (!file) throw new Error('usage: node upload.js <logfile>')

var WORKERS = +process.env.WORKERS || 48

var request = require('request')
var LogParse = require('couchdb-log-parse')
var fs = require('fs')
var zlib = require('zlib')

var parser = new LogParse()

var downloads = {}
var k
var counts = []

console.error('Parsing log file... ' + file);
var st = fs.createReadStream(file)
if (file.match(/\.gz$/)) st = st.pipe(zlib.Gunzip())

st.pipe(parser)
  .on('message', function (msg) {
    if (msg.type !== 'http' ||
        msg.statusCode !== 200 ||
        msg.method !== 'GET' ||
        !msg.url.match('tgz')) return
    var pkg = msg.url.split('/')[2]

    k = k || msg.date.getTime()
    var day = msg.date.toISOString().split('T')[0]
    downloads[day] = downloads[day] || {}
    var d = downloads[day]

    d[pkg] = d[pkg] || 0
    d[pkg] ++
  })
  .on('end', function () {
    console.error('tallying up counts...')
    Object.keys(downloads).forEach(function (d) {
      var day = downloads[d]
      Object.keys(day).forEach(function (pkg) {
        var count = day[pkg]
        counts.push({ _id: pkg + '_' + k + '_' + d,
                      pkg: pkg,
                      count: count,
                      day: d })
      })
    })
    uploadCounts()
  })

function uploadCounts () {
  if (!counts) throw new Error('must tally up first')

  console.error('uploading count data...')
  var i = 0;
  for (var i = 0; i < WORKERS; i ++) work(i)
}

function work (id) {
  var c = counts.pop()
  if (!c) return console.log('done worker '+id);
  var r = { uri: config.couch + c._id,
            body: c,
            method: 'PUT',
            json: true }
  if (auth) r.headers = { authorization: 'Basic ' + auth }
  console.error(counts.length, c._id, c.count)
  request(r, function (er, res, body) {
    if (er || (res && res.statusCode >= 400)) {
      console.error(c._id, res && res.statusCode || er)
    }
    work(id)
  })
}
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const fs = require('fs');
const path = require('path');

const OSX_EXT = '.dmg';
const OSX_PATCH_EXT = '-mac.zip';
const WIN_EXT = '.exe';
const WIN64_EXT = '-x64.exe';
const WIN_NU_EXT = '-full.nupkg';
const WIN64_NU_EXT = 'x64-full.nupkg';
const WIN_NU_DELTA_EXT = '-delta.nupkg';
const WIN64_NU_DELTA_EXT = 'x64-delta.nupkg';

let NUCLEUS_PATH_GLOBAL;
let COUNT = 0;

const last = (string, num) => {
  return string.substr(string.length - num);
};

const upload = (github, id, assetPath, name, suppressError) => {
  if (!fs.existsSync(path.resolve(NUCLEUS_PATH_GLOBAL + assetPath))) {
    return;
  }
  COUNT++;
  console.log('Starting upload - ' + name); // eslint-disable-line
  github.releases.uploadAsset({
    owner: 'Nucleus-Player',
    repo: 'Nucleus-Player-Releases',
    id,
    name,
    filePath: path.resolve(NUCLEUS_PATH_GLOBAL + assetPath),
  }, (err) => {
    if (err && !suppressError) {
      console.log('Something went wrong...'); // eslint-disable-line
      console.error(err); // eslint-disable-line
    } else if (err) {
      console.log('!!! Upload Suppressed - ' + name); // eslint-disable-line
    } else {
      console.log('Upload Successfull - ' + name); // eslint-disable-line
    }
    COUNT--;
    if (COUNT === 0) {
      require('request').get('http://ut.samuel.ninja:6069/api/force');
    }
  });
};

module.exports = (NUCLEUS_PATH, RELEASE_TYPE, github, targetRelease) => {
  let needOSX = RELEASE_TYPE === 'darwin';
  let needOSXPatch = RELEASE_TYPE === 'darwin';
  let needWin = RELEASE_TYPE !== 'darwin';
  let needWin64 = RELEASE_TYPE !== 'darwin';
  let needWinNu = RELEASE_TYPE !== 'darwin';
  let needWin64Nu = RELEASE_TYPE !== 'darwin';
  let needWinNuDelta = RELEASE_TYPE !== 'darwin';
  let needWin64NuDelta = RELEASE_TYPE !== 'darwin';

  NUCLEUS_PATH_GLOBAL = NUCLEUS_PATH;

  _.forEach(targetRelease.assets || [], (asset) => {
    if (last(asset.name, OSX_EXT.length) === OSX_EXT) {
      needOSX = false;
    } else if (last(asset.name, OSX_PATCH_EXT.length) === OSX_PATCH_EXT) {
      needOSXPatch = false;
    } else if (last(asset.name, WIN64_EXT.length) === WIN64_EXT) {
      needWin64 = false;
    } else if (last(asset.name, WIN_EXT.length) === WIN_EXT) {
      needWin = false;
    } else if (last(asset.name, WIN64_NU_EXT.length) === WIN64_NU_EXT) {
      needWin64Nu = false;
    } else if (last(asset.name, WIN_NU_EXT.length) === WIN_NU_EXT) {
      needWinNu = false;
    } else if (last(asset.name, WIN64_NU_DELTA_EXT.length) === WIN64_NU_DELTA_EXT) {
      needWin64NuDelta = false;
    } else if (last(asset.name, WIN_NU_DELTA_EXT.length) === WIN_NU_DELTA_EXT) {
      needWinNuDelta = false;
    }
  });

  const packageJSON = require(path.resolve(NUCLEUS_PATH + '/package.json'));

  if (needWin) {
    upload(github, targetRelease.id,
      '/dist/build/installer32/Nucleus PlayerSetup.exe', 'Nucleus Player Setup.win.exe');
  }
  if (needWin64) {
    upload(github, targetRelease.id,
      '/dist/build/installer64/Nucleus PlayerSetup.exe', 'Nucleus Player Setup.win-x64.exe');
  }
  if (needWinNu) {
    upload(github, targetRelease.id,
      '/dist/build/installer32/NucleusPlayer-' + packageJSON.version + '-full.nupkg',
      'NucleusPlayer-' + packageJSON.version + '-full.nupkg');
  }
  if (needWin64Nu) {
    upload(github, targetRelease.id,
      '/dist/build/installer64/NucleusPlayer-' + packageJSON.version + '-full.nupkg',
      'NucleusPlayer-' + packageJSON.version + '-x64-full.nupkg');
  }
  if (needWinNuDelta) {
    upload(github, targetRelease.id,
      '/dist/build/installer32/NucleusPlayer-' + packageJSON.version + '-delta.nupkg',
      'NucleusPlayer-' + packageJSON.version + '-delta.nupkg', true);
  }
  if (needWin64NuDelta) {
    upload(github, targetRelease.id,
      '/dist/build/installer64/NucleusPlayer-' + packageJSON.version + '-delta.nupkg',
      'NucleusPlayer-' + packageJSON.version + '-x64-delta.nupkg', true);
  }
  if (needWinNuDelta) {
    upload(github, targetRelease.id,
      '/dist/build/installer32/RELEASES',
      'RELEASES', true);
  }
  if (needWin64NuDelta) {
    upload(github, targetRelease.id,
      '/dist/build/installer64/RELEASES',
      'RELEASES-x64', true);
  }
  // if (needWinNu) {
  //   pathToAsset = NUCLEUS_PATH + '/dist/built/win/Nuceleus Player Setup.exe';
  //   upload(github, targetRelease.id, pathToAsset, 'Nucleus Player Setup.exe');
  // }
};
<commit_msg>Added mac release asset<commit_after>'use strict';

const _ = require('lodash');
const fs = require('fs');
const path = require('path');

const OSX_EXT = '.dmg';
const OSX_PATCH_EXT = '-mac.zip';
const WIN_EXT = '.exe';
const WIN64_EXT = '-x64.exe';
const WIN_NU_EXT = '-full.nupkg';
const WIN64_NU_EXT = 'x64-full.nupkg';
const WIN_NU_DELTA_EXT = '-delta.nupkg';
const WIN64_NU_DELTA_EXT = 'x64-delta.nupkg';

let NUCLEUS_PATH_GLOBAL;
let COUNT = 0;

const last = (string, num) => {
  return string.substr(string.length - num);
};

const upload = (github, id, assetPath, name, suppressError) => {
  if (!fs.existsSync(path.resolve(NUCLEUS_PATH_GLOBAL + assetPath))) {
    return;
  }
  COUNT++;
  console.log('Starting upload - ' + name); // eslint-disable-line
  github.releases.uploadAsset({
    owner: 'Nucleus-Player',
    repo: 'Nucleus-Player-Releases',
    id,
    name,
    filePath: path.resolve(NUCLEUS_PATH_GLOBAL + assetPath),
  }, (err) => {
    if (err && !suppressError) {
      console.log('Something went wrong...'); // eslint-disable-line
      console.error(err); // eslint-disable-line
    } else if (err) {
      console.log('!!! Upload Suppressed - ' + name); // eslint-disable-line
    } else {
      console.log('Upload Successfull - ' + name); // eslint-disable-line
    }
    COUNT--;
    if (COUNT === 0) {
      require('request').get('http://ut.samuel.ninja:6069/api/force');
    }
  });
};

module.exports = (NUCLEUS_PATH, RELEASE_TYPE, github, targetRelease) => {
  let needOSX = RELEASE_TYPE === 'darwin';
  let needOSXPatch = RELEASE_TYPE === 'darwin';
  let needWin = RELEASE_TYPE !== 'darwin';
  let needWin64 = RELEASE_TYPE !== 'darwin';
  let needWinNu = RELEASE_TYPE !== 'darwin';
  let needWin64Nu = RELEASE_TYPE !== 'darwin';
  let needWinNuDelta = RELEASE_TYPE !== 'darwin';
  let needWin64NuDelta = RELEASE_TYPE !== 'darwin';

  NUCLEUS_PATH_GLOBAL = NUCLEUS_PATH;

  _.forEach(targetRelease.assets || [], (asset) => {
    if (last(asset.name, OSX_EXT.length) === OSX_EXT) {
      needOSX = false;
    } else if (last(asset.name, OSX_PATCH_EXT.length) === OSX_PATCH_EXT) {
      needOSXPatch = false;
    } else if (last(asset.name, WIN64_EXT.length) === WIN64_EXT) {
      needWin64 = false;
    } else if (last(asset.name, WIN_EXT.length) === WIN_EXT) {
      needWin = false;
    } else if (last(asset.name, WIN64_NU_EXT.length) === WIN64_NU_EXT) {
      needWin64Nu = false;
    } else if (last(asset.name, WIN_NU_EXT.length) === WIN_NU_EXT) {
      needWinNu = false;
    } else if (last(asset.name, WIN64_NU_DELTA_EXT.length) === WIN64_NU_DELTA_EXT) {
      needWin64NuDelta = false;
    } else if (last(asset.name, WIN_NU_DELTA_EXT.length) === WIN_NU_DELTA_EXT) {
      needWinNuDelta = false;
    }
  });

  const packageJSON = require(path.resolve(NUCLEUS_PATH + '/package.json'));

  if (needOSX) {
    upload(github, targetRelease.id,
      '/dist/Nucleus Player-darwin-x64/Nucleus Player.app', 'Nucleus Player.app');
  }
  if (needWin) {
    upload(github, targetRelease.id,
      '/dist/build/installer32/Nucleus PlayerSetup.exe', 'Nucleus Player Setup.win.exe');
  }
  if (needWin64) {
    upload(github, targetRelease.id,
      '/dist/build/installer64/Nucleus PlayerSetup.exe', 'Nucleus Player Setup.win-x64.exe');
  }
  if (needWinNu) {
    upload(github, targetRelease.id,
      '/dist/build/installer32/NucleusPlayer-' + packageJSON.version + '-full.nupkg',
      'NucleusPlayer-' + packageJSON.version + '-full.nupkg');
  }
  if (needWin64Nu) {
    upload(github, targetRelease.id,
      '/dist/build/installer64/NucleusPlayer-' + packageJSON.version + '-full.nupkg',
      'NucleusPlayer-' + packageJSON.version + '-x64-full.nupkg');
  }
  if (needWinNuDelta) {
    upload(github, targetRelease.id,
      '/dist/build/installer32/NucleusPlayer-' + packageJSON.version + '-delta.nupkg',
      'NucleusPlayer-' + packageJSON.version + '-delta.nupkg', true);
  }
  if (needWin64NuDelta) {
    upload(github, targetRelease.id,
      '/dist/build/installer64/NucleusPlayer-' + packageJSON.version + '-delta.nupkg',
      'NucleusPlayer-' + packageJSON.version + '-x64-delta.nupkg', true);
  }
  if (needWinNuDelta) {
    upload(github, targetRelease.id,
      '/dist/build/installer32/RELEASES',
      'RELEASES', true);
  }
  if (needWin64NuDelta) {
    upload(github, targetRelease.id,
      '/dist/build/installer64/RELEASES',
      'RELEASES-x64', true);
  }
  // if (needWinNu) {
  //   pathToAsset = NUCLEUS_PATH + '/dist/built/win/Nuceleus Player Setup.exe';
  //   upload(github, targetRelease.id, pathToAsset, 'Nucleus Player Setup.exe');
  // }
};
<|endoftext|>


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

  var LaceyModule, validate_app_name, validate_module_name, validate_module_type, validate_duplicated_module;

  LaceyApp = function (app_name) {
    validate_app_name(app_name);

    this.modules = {};
    this.name = app_name;

    return this;
  };

  LaceyApp.prototype.register_module = function (module_name, module) {
    validate_module_name.call(this, module_name);
    validate_module_type.call(this, module);
    validate_duplicated_module.call(this, module_name);

    this.modules[module_name] = module;

    this[module_name] = new LaceyModule(module_name, module);
  };

  // private

  LaceyModule = function (module_name, module) {
    this.instance = null;
    this.module = module;
    this.module_name = module_name;
  };

  LaceyModule.prototype.get_instance = function () {
    if (this.instance === null) {
      this.instance = new this.module();
    }

    return this.instance;
  };

  LaceyModule.prototype.initialize = function () {
    if (this.instance === null) {
      var module = this.get_instance();

      if (typeof module.initialize === 'function') {
        module.initialize();
      }
    }

    return this.instance;
  };

  validate_app_name = function (app_name) {
    if (typeof app_name !== 'string' || app_name === '') {
      throw 'InvalidNameError - you must give a valid name to your lacey app';
    }
  };

  validate_module_name = function (module_name) {
    if (typeof module_name !== 'string' || module_name === '') {
      throw 'InvalidModuleNameError - you must give a valid name to your module';
    }
  };

  validate_module_type = function (module) {
    if (typeof module !== 'function') {
      throw 'InvalidModuleError - your module must be a function';
    }
  };

  validate_duplicated_module = function (module_name) {
    if (this.modules[module_name] !== undefined) {
      throw 'DuplicateModuleError - your module has already been registered';
    }
  };
}());
<commit_msg>LaceyModule - inheritance<commit_after>(function () {
  'use strict';

  var LaceyApp,
    LaceyModule,
    modules,
    validate_app_name,
    validate_module_name,
    validate_module_type,
    validate_duplicated_module;

  LaceyApp = function (app_name) {
    validate_app_name.call(this, app_name);

    modules = this.modules = {};
    this.name = app_name;

    return this;
  };

  LaceyApp.prototype.register_module = function (module_name, parent_module, Module) {
    if (typeof parent_module === 'function') {
      Module = parent_module;
      parent_module = null;
    }

    validate_module_name.call(this, module_name);
    validate_module_type.call(this, Module);
    validate_duplicated_module.call(this, module_name);

    this[module_name] = new LaceyModule(module_name, parent_module, Module);
    this.modules[module_name] = Module;

    return this[module_name];
  };

  LaceyModule = function (module_name, parent_module, Module) {
    var instance = null;

    this.module_name = module_name;

    this.get_instance = function () {
      if (instance === null) {
        if (parent_module !== null) {
          Module.prototype = new modules[parent_module]();
          Module.prototype.constructor = Module;
        }

        instance = new Module();
      }

      return instance;
    };
  };

  LaceyModule.prototype.initialize = function () {
    if (this.instance === null) {
      var module = this.get_instance();

      if (typeof module.initialize === 'function') {
        module.initialize();
      }
    }

    return this.instance;
  };

  validate_app_name = function (app_name) {
    if (typeof app_name !== 'string' || app_name === '') {
      throw 'InvalidNameError - you must give a valid name to your lacey app';
    }

    return true;
  };

  validate_module_name = function (module_name) {
    if (typeof module_name !== 'string' || module_name === '') {
      throw 'InvalidModuleNameError - you must give a valid name to your module';
    }

    return true;
  };

  validate_module_type = function (Module) {
    if (typeof Module !== 'function') {
      throw 'InvalidModuleError - your module must be a function';
    }

    return true;
  };

  validate_duplicated_module = function (module_name) {
    if (this.modules[module_name] !== undefined) {
      throw 'DuplicateModuleError - your module has already been registered';
    }

    return true;
  };

  window.LaceyApp = LaceyApp;
}());
<|endoftext|>


<commit_before>/**
* @license in-viewport v0.3.0 | github.com/vvo/in-viewport#license
*/

(function(win, doc){
  var instances = [];

  win['inViewport'] = inViewport;

  function inViewport(elt, params, cb) {
    var opts = {
      container: doc.body,
      offset: 0
    };

    if (params === undefined || typeof params === 'function') {
      cb = params;
      params = {};
    }

    var container = opts.container = params['container'] || opts.container;
    var offset = opts.offset = params['offset'] || opts.offset;

    for (var i = 0; i < instances.length; i++) {
      if (instances[i].container === container) {
        return instances[i].inViewport(elt, offset, cb);
      }
    }

    return instances[
      instances.push(createInViewport(container)) - 1
    ].inViewport(elt, offset, cb)
  }

  function addEvent( el, type, fn ) {
    if (el.attachEvent) {
      el.attachEvent( 'on' + type, fn );
    } else {
      el.addEventListener( type, fn, false );
    }
  }

  function debounce(func, wait, immediate) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(context, args);
    }
  }

  // https://github.com/jquery/sizzle/blob/3136f48b90e3edc84cbaaa6f6f7734ef03775a07/sizzle.js#L708
  var contains = document.documentElement.compareDocumentPosition ?
    function( a, b ) {
      return !!(a.compareDocumentPosition( b ) & 16);
    } :
    document.documentElement.contains ?
    function( a, b ) {
      return a !== b && ( a.contains ? a.contains( b ) : false );
    } :
    function( a, b ) {
      while ( (b = b.parentNode) ) {
        if ( b === a ) {
          return true;
        }
      }
      return false;
    };

  function createInViewport(container) {
    var watches = [];
    var scrollContainer = container === doc.body ? win : container;
    var debouncedCheck = debounce(checkElements, 15);

    addEvent(scrollContainer, 'scroll', debouncedCheck);

    if (scrollContainer === win) {
      addEvent(win, 'resize', debouncedCheck);
    }

    function inViewport(elt, offset, cb) {
      if (!contains(doc.documentElement, elt) ||
          !contains(doc.documentElement, container)) {
          if (cb) {
            return setTimeout(addWatch(elt, offset, cb), 0);
          } else {
            console.log('coucou')
            return false;
          }
      }

      var eltRect = elt.getBoundingClientRect();
      var containerRect = container.getBoundingClientRect();

      var pos = {
        left: eltRect.left,
        top: eltRect.top
      };

      var viewport = {
        width: offset,
        height: offset
      };

      if (container === doc.body) {
        viewport.width += doc.documentElement.clientWidth;
        viewport.height += doc.documentElement.clientHeight;
      } else {
        pos.left -= containerRect.left;
        pos.top -= containerRect.top;
        viewport.width += container.clientWidth;
        viewport.height += container.clientHeight;
      }

      var visible =
        pos.left >= -offset &&
        pos.left <= viewport.width &&
        pos.top >= -offset &&
        pos.top <= viewport.height;

      if (visible) {
        if (cb) {
          cb(elt);
        } else {
          return true;
        }
      } else {
        if (cb) {
          setTimeout(addWatch(elt, offset, cb), 0);
        } else {
          return false;
        }
      }
    }

    function addWatch(elt, offset, cb) {
      return function() {
        watches.push(function() {
          inViewport(elt, offset, cb, true);
        });
      }
    }

    function checkElements() {
      var cb;
      while(cb = watches.shift()) {
        cb();
      }
    }

    return {
      container: container,
      inViewport: inViewport
    }
  }

})(window, document);<commit_msg>remove console.log<commit_after>/**
* @license in-viewport v0.3.0 | github.com/vvo/in-viewport#license
*/

(function(win, doc){
  var instances = [];

  win['inViewport'] = inViewport;

  function inViewport(elt, params, cb) {
    var opts = {
      container: doc.body,
      offset: 0
    };

    if (params === undefined || typeof params === 'function') {
      cb = params;
      params = {};
    }

    var container = opts.container = params['container'] || opts.container;
    var offset = opts.offset = params['offset'] || opts.offset;

    for (var i = 0; i < instances.length; i++) {
      if (instances[i].container === container) {
        return instances[i].inViewport(elt, offset, cb);
      }
    }

    return instances[
      instances.push(createInViewport(container)) - 1
    ].inViewport(elt, offset, cb)
  }

  function addEvent( el, type, fn ) {
    if (el.attachEvent) {
      el.attachEvent( 'on' + type, fn );
    } else {
      el.addEventListener( type, fn, false );
    }
  }

  function debounce(func, wait, immediate) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(context, args);
    }
  }

  // https://github.com/jquery/sizzle/blob/3136f48b90e3edc84cbaaa6f6f7734ef03775a07/sizzle.js#L708
  var contains = document.documentElement.compareDocumentPosition ?
    function( a, b ) {
      return !!(a.compareDocumentPosition( b ) & 16);
    } :
    document.documentElement.contains ?
    function( a, b ) {
      return a !== b && ( a.contains ? a.contains( b ) : false );
    } :
    function( a, b ) {
      while ( (b = b.parentNode) ) {
        if ( b === a ) {
          return true;
        }
      }
      return false;
    };

  function createInViewport(container) {
    var watches = [];
    var scrollContainer = container === doc.body ? win : container;
    var debouncedCheck = debounce(checkElements, 15);

    addEvent(scrollContainer, 'scroll', debouncedCheck);

    if (scrollContainer === win) {
      addEvent(win, 'resize', debouncedCheck);
    }

    function inViewport(elt, offset, cb) {
      if (!contains(doc.documentElement, elt) ||
          !contains(doc.documentElement, container)) {
          if (cb) {
            return setTimeout(addWatch(elt, offset, cb), 0);
          } else {
            return false;
          }
      }

      var eltRect = elt.getBoundingClientRect();
      var containerRect = container.getBoundingClientRect();

      var pos = {
        left: eltRect.left,
        top: eltRect.top
      };

      var viewport = {
        width: offset,
        height: offset
      };

      if (container === doc.body) {
        viewport.width += doc.documentElement.clientWidth;
        viewport.height += doc.documentElement.clientHeight;
      } else {
        pos.left -= containerRect.left;
        pos.top -= containerRect.top;
        viewport.width += container.clientWidth;
        viewport.height += container.clientHeight;
      }

      var visible =
        pos.left >= -offset &&
        pos.left <= viewport.width &&
        pos.top >= -offset &&
        pos.top <= viewport.height;

      if (visible) {
        if (cb) {
          cb(elt);
        } else {
          return true;
        }
      } else {
        if (cb) {
          setTimeout(addWatch(elt, offset, cb), 0);
        } else {
          return false;
        }
      }
    }

    function addWatch(elt, offset, cb) {
      return function() {
        watches.push(function() {
          inViewport(elt, offset, cb, true);
        });
      }
    }

    function checkElements() {
      var cb;
      while(cb = watches.shift()) {
        cb();
      }
    }

    return {
      container: container,
      inViewport: inViewport
    }
  }

})(window, document);<|endoftext|>