<commit_before>'use strict'

var validUrl = require('valid-url')
var hh = require('http-https')
var streamifier = require('streamifier')
var streamify = require('streamify')
var convertStream = require('./lib/convertSitemapData')

function sitemapToArray (sitemap, callback) {

  if (!sitemap) {
    return callback(new Error('Missing required input: sitemap.'), null)
  }

  var list = []
  var stream = false;

  if (validUrl.isWebUri(sitemap)) {
    stream = streamify()
    hh.get(sitemap, function (response) {
      stream.resolve(response)
    })
  } else {
    stream = streamifier.createReadStream(sitemap)
  }

  convertStream.on('data', function (data) {
    list.push(JSON.parse(data))
  })

  convertStream.on('end', function () {
    return callback(null, list)
  })

  convertStream.on('error', function (error) {
    return callback(error, null)
  })

  stream
    .pipe(convertStream)

}

module.exports = sitemapToArray

module.exports.stream = convertStream
<commit_msg>Fixes codestyle<commit_after>'use strict'

var validUrl = require('valid-url')
var hh = require('http-https')
var streamifier = require('streamifier')
var streamify = require('streamify')
var convertStream = require('./lib/convertSitemapData')

function sitemapToArray (sitemap, callback) {
  if (!sitemap) {
    return callback(new Error('Missing required input: sitemap.'), null)
  }

  var list = []
  var stream = false

  if (validUrl.isWebUri(sitemap)) {
    stream = streamify()
    hh.get(sitemap, function (response) {
      stream.resolve(response)
    })
  } else {
    stream = streamifier.createReadStream(sitemap)
  }

  convertStream.on('data', function (data) {
    list.push(JSON.parse(data))
  })

  convertStream.on('end', function () {
    return callback(null, list)
  })

  convertStream.on('error', function (error) {
    return callback(error, null)
  })

  stream
    .pipe(convertStream)
}

module.exports = sitemapToArray

module.exports.stream = convertStream
<|endoftext|>


<commit_before>'use strict';
const Beam = require('beam-client-node');
const Tetris = require('beam-interactive-node');
const Packets = require('beam-interactive-node/dist/robot/packets').default;

const auth = require('./lib/auth.js');

const State = require('./lib/state/ControlState');
const ControlsProcessor = require('./lib/ControlsProcessor');
const Config = require('./lib/Config');
const enhanceState = require('./lib/state/enhancer');
const reconnector = require('./lib/reconnector');

const args = process.argv.slice(2);
const file = args[0];
const config = new Config(file);

let state;
let widgets;
let channelID;
const beam = new Beam();
let robot = null;

if (config.widgets !== undefined && config.widgets) {
	widgets = require('./lib/widgets');
} else {
	widgets = function () {};
}
const processor = new ControlsProcessor(config);

processor.on('changed', report => {
	widgets(report);
});

/**
 * Our report handler, entry point for data from beam
 * @param  {Object} report Follows the format specified in the latest tetris.proto file
 */
function handleReport(report) {
	// Each report needs to be treated by itself and thus we can't carry any references through
	// If we do newer reports will update some state before we've processed it.
	// Due to this we're doing Immuteable style design with the report
	// Eventually I might make everything here Imuteable but for now just making
	// each report run in sequence will do
	const enhancedState = enhanceState(report, state);
	const progress = processor.process(enhancedState, state);
	if (robot !== null) {
		if (progress.tactile.length !== 0 || progress.joystick.length !== 0) {
			robot.send(new Packets.ProgressUpdate(progress));
		}
	}
	if (!report.tactile.length && report.users.active === 0) {
		processor.clearKeys(state.tactiles);
	}
}

// clear the keys on exit?? Ctrl+C doesn't appear to send this event
process.on('exit', code => {
	console.log(`Process is exiting wih code: ${code}`);
	processor.clearKeys(state);
});
process.on('SIGINT', () => {
	console.log('SIGINT');
	processor.clearKeys(state);
	process.exit();
});

function getChannelID(channelName) {
	return beam.request('GET', `channels/${channelName}`).then(res => {
		channelID = res.body.id;
		return res.body.id;
	});
}

// interactive: true, tetrisGameId: versionId, tetrisShareCode: :code
function goInteractive(versionCode, shareCode) {
	return beam.request('PUT', `channels/${channelID}`, {body: {
		interactive: true,
		tetrisGameId: versionCode,
		tetrisShareCode: shareCode
	}, json: true}).then(res => {
		if (res.statusCode !== 200) {
			if (res.body && res.body.tetrisGameId) {
				throw new Error(res.body.tetrisGameId);
			}
			throw new Error('Couldn\'t set channel to interactive with that game.');
		}
	});
}

function checkInteractive() {
	return beam.request('GET', `channels/${channelID}?fields=interactive`).then(res => {
		return res.body && res.body.interactive;
	});
}

function hasControls(type, controls) {
	return controls[type] && controls[type].length;
}

function hasSomeControls(controls) {
	return hasControls('tactiles', controls) || hasControls('joysticks', controls) || hasControls('screens', controls);
}

function validateControls(controls) {
	if (!hasSomeControls(controls)) {
		throw new Error('No controls found');
	}
	return controls;
}

function getControls(version, code) {
	return beam.request('GET', `tetris/versions/${version}?code=${code}`)
	.then(res => {
		if (!res.body.controls) {
			throw new Error('Incorrect version id or share code in your config or no control layout saved for that version.');
		}
		return res.body.controls;
	}).catch(() => {
		throw new Error('Problem retrieving controls');
	});
}

function createState(controls) {
	return new State(controls);
}

function validateConfig() {
	if (!config) {
		throw new Error('Missing config file cannot proceed, Please create a config file. Check the readme for help!');
	}
	if (!config.version || !config.code) {
		throw new Error('Missing version id and share code. These are required for now');
	}
}

function setup() {
	validateConfig();
	console.log(`Using ${config.beam.username} with Version: ${config.version} && Code: ${config.code}`);
	getChannelID(config.beam.username).then(result => {
		if (result) {
			go(result);
		}
	});
}

function onInteractiveConnect(err) {
	if (err) {
		console.log('Theres a problem connecting to tetris');
		console.log(err);
	} else {
		console.log('Connected to Tetris');
	}
}

function launchInteractive(beam, id) {
	return beam.game.join(id).then(details => {
		console.log('Authenticated, Spinning up Tetris Connection');
		const tetrisDetails = {};
		tetrisDetails.remote = details.body.address;
		tetrisDetails.key = details.body.key;
		tetrisDetails.channel = id;
		robot = new Tetris.Robot(tetrisDetails);
		robot.handshake(onInteractiveConnect);
		robot.on('report', handleReport);
		robot.on('error', code => console.log(code));
		reconnector(robot, launchInteractive.bind(this, beam, id), onInteractiveConnect);
	});
}

function go(id) {
	channelID = id;
	auth(config.beam, beam)
	.then(() => {
		return goInteractive(config.version, config.code);
	}).then(() => {
		return getControls(config.version, config.code);
	}).then(controls => {
		return validateControls(controls);
	}).then(controls => {
		state = createState(controls);
		return state;
	}).then(launchInteractive.bind(this, beam, id))
	.catch(err => {
		if (err.message !== undefined && err.message.body !== undefined) {
			console.log(err);
		} else {
			throw err;
		}
	});
}

setup();
<commit_msg>Fix slow handshakes<commit_after>'use strict';
const Beam = require('beam-client-node');
const Tetris = require('beam-interactive-node');
const Packets = require('beam-interactive-node/dist/robot/packets').default;
const Promise = require('bluebird');

const auth = require('./lib/auth.js');

const State = require('./lib/state/ControlState');
const ControlsProcessor = require('./lib/ControlsProcessor');
const Config = require('./lib/Config');
const enhanceState = require('./lib/state/enhancer');
const reconnector = require('./lib/reconnector');

const args = process.argv.slice(2);
const file = args[0];
const config = new Config(file);

let state;
let widgets;
let channelID;
const beam = new Beam();
let robot = null;

if (config.widgets !== undefined && config.widgets) {
	widgets = require('./lib/widgets');
} else {
	widgets = function () {};
}
const processor = new ControlsProcessor(config);

processor.on('changed', report => {
	widgets(report);
});

/**
 * Our report handler, entry point for data from beam
 * @param  {Object} report Follows the format specified in the latest tetris.proto file
 */
function handleReport(report) {
	// Each report needs to be treated by itself and thus we can't carry any references through
	// If we do newer reports will update some state before we've processed it.
	// Due to this we're doing Immuteable style design with the report
	// Eventually I might make everything here Imuteable but for now just making
	// each report run in sequence will do
	const enhancedState = enhanceState(report, state);
	const progress = processor.process(enhancedState, state);
	if (robot !== null) {
		if (progress.tactile.length !== 0 || progress.joystick.length !== 0) {
			robot.send(new Packets.ProgressUpdate(progress));
		}
	}
	if (!report.tactile.length && report.users.active === 0) {
		processor.clearKeys(state.tactiles);
	}
}

// clear the keys on exit?? Ctrl+C doesn't appear to send this event
process.on('exit', code => {
	console.log(`Process is exiting wih code: ${code}`);
	processor.clearKeys(state);
});
process.on('SIGINT', () => {
	console.log('SIGINT');
	processor.clearKeys(state);
	process.exit();
});

function getChannelID(channelName) {
	return beam.request('GET', `channels/${channelName}`).then(res => {
		channelID = res.body.id;
		return res.body.id;
	});
}

// interactive: true, tetrisGameId: versionId, tetrisShareCode: :code
function goInteractive(versionCode, shareCode) {
	return beam.request('PUT', `channels/${channelID}`, {body: {
		interactive: true,
		tetrisGameId: versionCode,
		tetrisShareCode: shareCode
	}, json: true}).then(res => {
		if (res.statusCode !== 200) {
			if (res.body && res.body.tetrisGameId) {
				throw new Error(res.body.tetrisGameId);
			}
			throw new Error('Couldn\'t set channel to interactive with that game.');
		}
	});
}

function checkInteractive() {
	return beam.request('GET', `channels/${channelID}?fields=interactive`).then(res => {
		return res.body && res.body.interactive;
	});
}

function hasControls(type, controls) {
	return controls[type] && controls[type].length;
}

function hasSomeControls(controls) {
	return hasControls('tactiles', controls) || hasControls('joysticks', controls) || hasControls('screens', controls);
}

function validateControls(controls) {
	if (!hasSomeControls(controls)) {
		throw new Error('No controls found');
	}
	return controls;
}

function getControls(version, code) {
	return beam.request('GET', `tetris/versions/${version}?code=${code}`)
	.then(res => {
		if (!res.body.controls) {
			throw new Error('Incorrect version id or share code in your config or no control layout saved for that version.');
		}
		return res.body.controls;
	}).catch(() => {
		throw new Error('Problem retrieving controls');
	});
}

function createState(controls) {
	return new State(controls);
}

function validateConfig() {
	if (!config) {
		throw new Error('Missing config file cannot proceed, Please create a config file. Check the readme for help!');
	}
	if (!config.version || !config.code) {
		throw new Error('Missing version id and share code. These are required for now');
	}
}

function setup() {
	validateConfig();
	console.log(`Using ${config.beam.username} with Version: ${config.version} && Code: ${config.code}`);
	getChannelID(config.beam.username).then(result => {
		if (result) {
			go(result);
		}
	});
}

function onInteractiveConnect(err) {
	if (err) {
		console.log('Theres a problem connecting to tetris');
		console.log(err);
	} else {
		console.log('Connected to Tetris');
	}
}

function performRobotHandshake(robot) {
	return new Promise((resolve, reject) => {
		robot.handshake(err => {
			if (err) {
				reject(err);
			}
			onInteractiveConnect(err);
			resolve();
		});
	});
}

function launchInteractive(beam, id) {
	return beam.game.join(id).then(details => {
		console.log('Authenticated, Spinning up Tetris Connection');
		robot = new Tetris.Robot({
			remote: details.body.address,
			key: details.body.key,
			channel: id
		});
		robot.handshake(onInteractiveConnect);
		robot.on('report', handleReport);
		robot.on('error', code => console.log(code));
		reconnector(robot, launchInteractive.bind(this, beam, id), onInteractiveConnect);
		return performRobotHandshake(robot);
	});
}

function go(id) {
	channelID = id;
	auth(config.beam, beam)
	.then(() => {
		return goInteractive(config.version, config.code);
	}).then(() => {
		return getControls(config.version, config.code);
	}).then(controls => {
		return validateControls(controls);
	}).then(controls => {
		state = createState(controls);
		return state;
	}).then(launchInteractive.bind(this, beam, id))
	.catch(err => {
		if (err.message !== undefined && err.message.body !== undefined) {
			console.log(err);
		} else {
			throw err;
		}
	});
}

setup();
<|endoftext|>


<commit_before>var _ = require("underscore"),
	path = require("path"),
	Backbone = require("backbone"),
	debug = require("debug"),
	cluster = require("cluster"),
	objectPath = require("object-path"),
	randId = require('alphanumeric-id'),
	merge = require("merge"),
	asyncWait = require("asyncwait"),
	hjson = require("hjson"),
	fs = require("fs");

var hasClusterSupport = cluster.Worker != null;

var Application =
module.exports = function(name) {
	if (!(this instanceof Application)) {
		return new Application(name);
	}

	if (typeof name === "string" && name != "") this.name = name;
	this.id = randId(12);
	this.options = _.clone(Application.defaults);
	this.configure();
}

Application.Events = Backbone.Events;
Application.extend = Backbone.Model.extend;
Application.create = function(configure) {
	if (typeof configure !== "function")
		throw new Error("Expecting function for configure.");

	return Application.extend({
		configure: configure
	});
}

// ascending state values
var state_constants = Application.states = {
	FAIL: 0,
	INIT: 1,
	READY: 2,
	RUNNING: 3,
	SHUTDOWN: 4,
	EXIT: 5
}

// attach constants directly to instances and class
_.extend(Application, state_constants);
_.extend(Application.prototype, state_constants);

// lowercase version are methods to call now or on event
_.each(state_constants, function(v, state) {
	if (!v) return;// no support for fail
	var lower = state.toLowerCase();
	Application.prototype[lower] = function(fn) {
		if (typeof fn !== "function") {
			throw new Error("Expecting a function for callback.");
		}

		if (this.state != null && this.state !== this.FAIL && this.state >= this[state]) fn.call(this);
		else this.once("state:" + lower, fn);

		return this;
	}
})

// options defaults
Application.defaults = {
	cwd: process.browser ? "/" : process.cwd(),
	env: process.env.NODE_ENV || "development",
	browser_keys: [ "version", "env", "log" ]
};

// prototype methods/properties
_.extend(Application.prototype, Backbone.Events, {
	name: "app",

	configure: function(){},

	start: function(parent) {
		var self, log, name, attemptExit, version, args;

		args = _.toArray(arguments);
		if (parent instanceof Application) args.shift();
		else parent = null;

		// make sure init didn't already get run
		if (this.state != null) return this.set.apply(this, args);

		this._initDate = new Date;
		self = this;
		name = this.name;

		// add protected properties
		Object.defineProperties(this, {
			hasClusterSupport: {
				get: function() { return this.get("threads") && hasClusterSupport; },
				configurable: false,
				enumerable: true
			},

			isMaster: {
				get: function() { return !hasClusterSupport || cluster.isMaster; },
				configurable: false,
				enumerable: true
			},

			isWorker: {
				get: function() { return hasClusterSupport && cluster.isWorker; },
				configurable: false,
				enumerable: true
			},

			isClient: {
				get: function() { return typeof window !== "undefined"; },
				configurable: false,
				enumerable: true
			},

			isServer: {
				get: function() { return typeof window === "undefined"; },
				configurable: false,
				enumerable: true
			},

			parent: {
				get: function() { return parent || null; },
				configurable: false,
				enumerable: true
			},

			isRoot: {
				get: function() { return parent == null; },
				configurable: false,
				enumerable: true
			}
		});

		// apply the parent
		if (parent != null) {
			// prevent parent from entering running state until this one is running
			parent.ready(function() {
				if (!self.state) return;
				var wait = parent.wait();
				self.once("state:fail", wait);
				self.running(wait);
			});

			// exit the app on parent shutdown
			parent.shutdown(function() {
				self.exit(parent.wait());
				self.halt();
			});
		}

		// set initial options
		this.set.apply(this, args);

		// auto-enable logging before we make loggers
		if (this.isRoot) {
			log = this.get("log")
			if (log) debug.enable(typeof log === "string" ? log : name + "*");
		} else {
			name = parent.name + ":" + name;
		}

		// set up loggers
		this.log = debug(name);
		this.log.error = debug(name + ":error");
		this.log.warn = debug(name + ":warn");
		this.log.debug = debug(name + ":debug");
		this.log.master = function() { if (self.isMaster) self.log.apply(self, arguments); }
		this.log.worker = function() { if (self.isWorker) self.log.apply(self, arguments); }

		// clustering
		if (hasClusterSupport) this.cluster = cluster;

		// on server, handle normal exits
		if (this.isServer) {
			attemptExit = function() {
				if (!self.halt()) self._fullappexit(0);
			}

			process.once("SIGINT", attemptExit);
			process.once("SIGTERM", attemptExit);

			// handle nodemon exits
			process.once("SIGUSR2", function() {
				function kill() { process.kill(process.pid, "SIGUSR2"); }
				self.once("state:exit", kill);
				if (!self.halt()) kill();
			});
		}

		// set up state
		this.state = this.INIT;
		this._onStateChange();
		this._announceState();
		if (this._handleErrors(true)) return;

		// announce our new application
		if (this.isMaster) {
			version = this.get("version");
			this.log("Starting %s application (%sbuild %s)", this.get("env"), version ? "v" + version + ", " : "", this.id);
		}
	},

	use: function(plugin) {
		var isapp = plugin instanceof Application;
		if (!isapp && !_.isFunction(plugin)) {
			throw new Error("Expecting function for plugin.");
		}

		// check if plugin is already loaded on this template
		if (this._plugins == null) this._plugins = [];
		if (~this._plugins.indexOf(plugin)) return this;
		this._plugins.push(plugin);

		var args = _.toArray(arguments).slice(1);
		this.init(function() {
			if (isapp) plugin.start.apply(plugin, [this].concat(args));
			else plugin.apply(this, args);
		});

		return this;
	},

	halt: function() {
		if (this._onhalt != null) {
			var onhalt = this._onhalt;
			delete this._onhalt;
			onhalt();
			return true;
		}

		return false;
	},

	error: function(err) {
		if (this._errors == null) this._errors = [];
		this._errors.push(err);
		this.trigger("error", err);

		if (this.state != null && this.get("log_errors") !== false) {
			var logval;
			if (typeof err === "string") logval = _.toArray(arguments);
			else if (err instanceof Error) logval = [ err.stack || err.toString() ];
			else if (err != null) logval = [ err.message || JSON.stringify(err) ];
			if (logval) this.log.error.apply(null, logval);
		}

		return this;
	},

	get: function(key) {
		var val, app = this;

		while (app != null && typeof val === "undefined") {
			val = objectPath.get(app.options, key);
			app = app.parent;
		}

		return val;
	},

	set: function() {
		_.each(arguments, function(obj) {
			if (_.isString(obj)) this.load(obj);
			if (_.isObject(obj)) this.options = merge(this.options, obj);
		}, this);

		return this;
	},

	load: function(file) {
		if (this.isClient) return this;

		// load options from a config file
		try {
			var config = fs.readFileSync(path.resolve(this.get("cwd"), file), { encoding: "utf-8" });
			if (config) this.set(hjson.parse(config));
		} catch(e) {
			if (e.code !== "ENOENT") throw e;
		}

		return this;
	},

	resolve: function() {
		var parts = _.toArray(arguments);
		parts.unshift(this.get("cwd"));
		return path.resolve.apply(path, parts);
	},

	relative: function(to) {
		return path.relative(this.get("cwd"), to);
	},

	getBrowserOptions: function() {
		var options = _.pick(this.get(), this.get("browser_keys"));
		_.extend(options, this.get("browser_options"));
		return options;
	},

	// handles changing states
	_onStateChange: function() {
		var self = this;

		if (this.state === this.FAIL ||
			this.state === this.EXIT) return;

		this.wait = asyncWait(_.once(function() {
			// don't keep running if we are in exit mode
			if (self.state === self.FAIL ||
				self.state === self.EXIT) return;

			// handle any errors since the last state change
			if (self._handleErrors(false)) return;

			// bump the state
			// on init, master goes straight to ready
			if (self.state < self.READY && self.hasClusterSupport && self.isMaster) {
				self.state = self.RUNNING;
			} else {
				self.state++;
			}

			// make the state change
			self._onStateChange();

			// handle the special cases first
			switch (self.state) {
				case self.RUNNING:
					self.log.master("Application started successfully in " + (new Date - self._initDate) + "ms.");
					self._onhalt = self.wait();
					break;

				case self.EXIT:
					self._fullappexit(0);
					break;
			}

			// annouce the change
			self._announceState();

			// the state change may have caused some errors
			self._handleErrors(true);
		}), this);
	},

	// triggers state events
	_announceState: function() {
		for (var key in state_constants) {
			if (state_constants[key] === this.state) break;
		}

		if (!key) return;

		try {
			key = key.toLowerCase();
			this.trigger("state:" + key);
			this.trigger("state", key);
		} catch(e) {
			this.error(e);
		}
	},

	// a browser compatible quit
	_fullappexit: function(code) {
		if (this.isRoot && typeof process.exit === "function") process.exit(code);
		else this.log.master("Application has exited with status %s", code);
	},

	_handleErrors: function(isAfter) {
		var inRange = (!isAfter && this.state < this.RUNNING) ||
			(isAfter && this.state <= this.RUNNING);

		if (inRange && this._errors && this._errors.length) {
			this.log("Errors preventing startup.");
			this.state = this.FAIL;
			this._announceState();
			this._fullappexit(1);
			return true;
		}

		return false;
	}
});<commit_msg>fixed exitting issues with children<commit_after>var _ = require("underscore"),
	path = require("path"),
	Backbone = require("backbone"),
	debug = require("debug"),
	cluster = require("cluster"),
	objectPath = require("object-path"),
	randId = require('alphanumeric-id'),
	merge = require("merge"),
	asyncWait = require("asyncwait"),
	hjson = require("hjson"),
	fs = require("fs");

var hasClusterSupport = cluster.Worker != null;

var Application =
module.exports = function(name) {
	if (!(this instanceof Application)) {
		return new Application(name);
	}

	if (typeof name === "string" && name != "") this.name = name;
	this.id = randId(12);
	this.options = _.clone(Application.defaults);
	this.configure();
}

Application.Events = Backbone.Events;
Application.extend = Backbone.Model.extend;
Application.create = function(configure) {
	if (typeof configure !== "function")
		throw new Error("Expecting function for configure.");

	return Application.extend({
		configure: configure
	});
}

// ascending state values
var state_constants = Application.states = {
	FAIL: 0,
	INIT: 1,
	READY: 2,
	RUNNING: 3,
	SHUTDOWN: 4,
	EXIT: 5
}

// attach constants directly to instances and class
_.extend(Application, state_constants);
_.extend(Application.prototype, state_constants);

// lowercase version are methods to call now or on event
_.each(state_constants, function(v, state) {
	if (!v) return;// no support for fail
	var lower = state.toLowerCase();
	Application.prototype[lower] = function(fn) {
		if (typeof fn !== "function") {
			throw new Error("Expecting a function for callback.");
		}

		if (this.state != null && this.state !== this.FAIL && this.state >= this[state]) fn.call(this);
		else this.once("state:" + lower, fn);

		return this;
	}
})

// options defaults
Application.defaults = {
	cwd: process.browser ? "/" : process.cwd(),
	env: process.env.NODE_ENV || "development",
	browser_keys: [ "version", "env", "log" ]
};

// prototype methods/properties
_.extend(Application.prototype, Backbone.Events, {
	name: "app",

	configure: function(){},

	start: function(parent) {
		var self, log, name, attemptExit, version, args;

		args = _.toArray(arguments);
		if (parent instanceof Application) args.shift();
		else parent = null;

		// make sure init didn't already get run
		if (this.state != null) return this.set.apply(this, args);

		this._initDate = new Date;
		self = this;
		name = this.name;

		// add protected properties
		Object.defineProperties(this, {
			hasClusterSupport: {
				get: function() { return this.get("threads") && hasClusterSupport; },
				configurable: false,
				enumerable: true
			},

			isMaster: {
				get: function() { return !hasClusterSupport || cluster.isMaster; },
				configurable: false,
				enumerable: true
			},

			isWorker: {
				get: function() { return hasClusterSupport && cluster.isWorker; },
				configurable: false,
				enumerable: true
			},

			isClient: {
				get: function() { return typeof window !== "undefined"; },
				configurable: false,
				enumerable: true
			},

			isServer: {
				get: function() { return typeof window === "undefined"; },
				configurable: false,
				enumerable: true
			},

			parent: {
				get: function() { return parent || null; },
				configurable: false,
				enumerable: true
			},

			isRoot: {
				get: function() { return parent == null; },
				configurable: false,
				enumerable: true
			}
		});

		// apply the parent
		if (parent != null) {
			// prevent parent from entering running state until this one is running
			parent.ready(function() {
				if (!self.state) return;
				var wait = parent.wait();
				self.once("state:fail", wait);
				self.running(wait);
			});

			// exit the app on parent shutdown
			parent.shutdown(function() {
				self.exit(parent.wait());
				self.halt();
			});
		}

		// set initial options
		this.set.apply(this, args);

		// auto-enable logging before we make loggers
		if (this.isRoot) {
			log = this.get("log")
			if (log) debug.enable(typeof log === "string" ? log : name + "*");
		} else {
			name = parent.name + ":" + name;
		}

		// set up loggers
		this.log = debug(name);
		this.log.error = debug(name + ":error");
		this.log.warn = debug(name + ":warn");
		this.log.debug = debug(name + ":debug");
		this.log.master = function() { if (self.isMaster) self.log.apply(self, arguments); }
		this.log.worker = function() { if (self.isWorker) self.log.apply(self, arguments); }

		// clustering
		if (hasClusterSupport) this.cluster = cluster;

		// on server root, handle normal exits
		if (this.isServer && this.isRoot) {
			attemptExit = function() {
				if (!self.halt()) self._fullappexit(0);
			}

			process.once("SIGINT", attemptExit);
			process.once("SIGTERM", attemptExit);

			// handle nodemon exits
			process.once("SIGUSR2", function() {
				function kill() { process.kill(process.pid, "SIGUSR2"); }
				if (self.halt()) self.exit(kill);
				else kill();
			});
		}

		// log about our new application
		if (this.isMaster) {
			version = this.get("version");
			this.log("Starting %s application (%sbuild %s)", this.get("env"), version ? "v" + version + ", " : "", this.id);
		}

		// set up state
		this.state = this.INIT;
		this._onStateChange();
		this._announceState();
		this._handleErrors(true);
	},

	use: function(plugin) {
		var isapp = plugin instanceof Application;
		if (!isapp && !_.isFunction(plugin)) {
			throw new Error("Expecting function for plugin.");
		}

		// check if plugin is already loaded on this template
		if (this._plugins == null) this._plugins = [];
		if (~this._plugins.indexOf(plugin)) return this;
		this._plugins.push(plugin);

		var args = _.toArray(arguments).slice(1);
		this.init(function() {
			if (isapp) plugin.start.apply(plugin, [this].concat(args));
			else plugin.apply(this, args);
		});

		return this;
	},

	halt: function() {
		if (this._onhalt != null) {
			var onhalt = this._onhalt;
			delete this._onhalt;
			onhalt();
			return true;
		}

		return false;
	},

	error: function(err) {
		if (this._errors == null) this._errors = [];
		this._errors.push(err);
		this.trigger("error", err);

		if (this.state != null && this.get("log_errors") !== false) {
			var logval;
			if (typeof err === "string") logval = _.toArray(arguments);
			else if (err instanceof Error) logval = [ err.stack || err.toString() ];
			else if (err != null) logval = [ err.message || JSON.stringify(err) ];
			if (logval) this.log.error.apply(null, logval);
		}

		return this;
	},

	get: function(key) {
		var val, app = this;

		while (app != null && typeof val === "undefined") {
			val = objectPath.get(app.options, key);
			app = app.parent;
		}

		return val;
	},

	set: function() {
		_.each(arguments, function(obj) {
			if (_.isString(obj)) this.load(obj);
			if (_.isObject(obj)) this.options = merge(this.options, obj);
		}, this);

		return this;
	},

	load: function(file) {
		if (this.isClient) return this;

		// load options from a config file
		try {
			var config = fs.readFileSync(path.resolve(this.get("cwd"), file), { encoding: "utf-8" });
			if (config) this.set(hjson.parse(config));
		} catch(e) {
			if (e.code !== "ENOENT") throw e;
		}

		return this;
	},

	resolve: function() {
		var parts = _.toArray(arguments);
		parts.unshift(this.get("cwd"));
		return path.resolve.apply(path, parts);
	},

	relative: function(to) {
		return path.relative(this.get("cwd"), to);
	},

	getBrowserOptions: function() {
		var options = _.pick(this.get(), this.get("browser_keys"));
		_.extend(options, this.get("browser_options"));
		return options;
	},

	// handles changing states
	_onStateChange: function() {
		var self = this;

		if (this.state === this.FAIL ||
			this.state === this.EXIT) return;

		this.wait = asyncWait(_.once(function() {
			// don't keep running if we are in exit mode
			if (self.state === self.FAIL ||
				self.state === self.EXIT) return;

			// handle any errors since the last state change
			if (self._handleErrors(false)) return;

			// bump the state
			// on init, master goes straight to ready
			if (self.state < self.READY && self.hasClusterSupport && self.isMaster) {
				self.state = self.RUNNING;
			} else {
				self.state++;
			}

			// make the state change
			self._onStateChange();

			// handle running state
			if (self.state === self.RUNNING) {
				self.log.master("Application started successfully in " + (new Date - self._initDate) + "ms.");
				self._onhalt = self.wait();
			}

			// annouce the change
			self._announceState();

			// the state change may have caused some errors
			self._handleErrors(true);

			// exit on exit
			if (self.state === self.EXIT) self._fullappexit(0);
		}), this);
	},

	// triggers state events
	_announceState: function() {
		for (var key in state_constants) {
			if (state_constants[key] === this.state) break;
		}

		if (!key) return;

		try {
			key = key.toLowerCase();
			this.trigger("state:" + key);
			this.trigger("state", key);
		} catch(e) {
			this.error(e);
		}
	},

	// a browser compatible quit
	_fullappexit: function(code) {
		if (this.isRoot && typeof process.exit === "function") process.exit(code);
		else this.log.master("Application has exited with status %s", code);
	},

	_handleErrors: function(isAfter) {
		var inRange = (!isAfter && this.state < this.RUNNING) ||
			(isAfter && this.state <= this.RUNNING);

		if (inRange && this._errors && this._errors.length) {
			this.log("Errors preventing startup.");
			this.state = this.FAIL;
			this._announceState();
			this._fullappexit(1);
			return true;
		}

		return false;
	}
});<|endoftext|>


<commit_before>module.exports = function thirteen(number) {
  if (number !== undefined && typeof number != "number") {
    // Can number be cast to a number?
    if (!isNaN(+number.toString())) {
      return +number.toString() * 13;
    } else if (!isNaN(+number.valueOf())) {
      return +number.valueOf() * 13;
    } else {
      return new Error("I can only deal with numbers");
    }
  } else {
    return number * 13;
  }
};
<commit_msg>Update index.js<commit_after>module.exports = function thirteen(number) {
  if (number !== undefined && typeof number !== "number") {
    // Can number be cast to a number?
    if (!isNaN(+number.toString())) {
      return +number.toString() * 13;
    } else if (!isNaN(+number.valueOf())) {
      return +number.valueOf() * 13;
    } else {
      return new Error("I can only deal with numbers");
    }
  } else {
    return number * 13;
  }
};
<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash')
const knex = require('knex')
const DatastoreTrailpack = require('trailpack-datastore')

/**
 * Knex integration for Trails. Allows knex to read its configration from the
 * trails datastore config, and auto-migrate on startup.
 */
module.exports = class KnexTrailpack extends DatastoreTrailpack {

  /**
   * Ensure that this trailpack supports the configured migration
   */
  validate () {
    if (!_.includes([ 'drop', 'create' ], this.app.config.database.models.migrate)) {
      throw new Error('Migrate must be configured to either "create" or "drop"')
    }
  }

  configure () {
    this.app.config.database.orm = 'knex'
  }

  /**
   * Initialize knex connections, and perform migrations.
   */
  initialize () {
    super.initialize()

    this.stores = _.mapValues(this.app.config.database.stores, (store, storeName) => {
      return {
        knex: knex(store),
        models: _.pickBy(this.app.models, { store: storeName })
      }
    })

    return this.migrate()
  }

  /**
   * Close all database connections
   */
  unload () {
    return Promise.all(
      _.map(this.stores, store => store.knex.destroy())
    )
  }

  constructor (app) {
    super(app, {
      config: require('./config'),
      api: require('./api'),
      pkg: require('./package')
    })
  }

  /**
   * Migrate schema according to the database configuration
   */
  migrate () {
    const SchemaMigrationService = this.app.services.SchemaMigrationService
    const database = this.app.config.database

    if (database.models.migrate == 'none') return

    return Promise.all(
      _.map(this.stores, store => {
        if (database.models.migrate == 'drop') {
          return SchemaMigrationService.drop(store.knex, this.app.models)
        }
      }))
      .then(() => {
        return Promise.all(_.map(this.stores, store => {
          return SchemaMigrationService.create(store.knex, this.app.models)
        }))
      })
  }
}

<commit_msg>[fix] update supported migrate settings<commit_after>'use strict'

const _ = require('lodash')
const knex = require('knex')
const DatastoreTrailpack = require('trailpack-datastore')

/**
 * Knex integration for Trails. Allows knex to read its configration from the
 * trails datastore config, and auto-migrate on startup.
 */
module.exports = class KnexTrailpack extends DatastoreTrailpack {

  /**
   * Ensure that this trailpack supports the configured migration
   */
  validate () {
    if (!_.includes([ 'none', 'drop', 'create' ], this.app.config.database.models.migrate)) {
      throw new Error('Migrate must be configured to either "create" or "drop"')
    }
  }

  configure () {
    this.app.config.database.orm = 'knex'
  }

  /**
   * Initialize knex connections, and perform migrations.
   */
  initialize () {
    super.initialize()

    this.stores = _.mapValues(this.app.config.database.stores, (store, storeName) => {
      return {
        knex: knex(store),
        models: _.pickBy(this.app.models, { store: storeName })
      }
    })
    this.defaultStore = this.stores[this.app.config.database.defaultStore]

    return this.migrate()
  }

  /**
   * Close all database connections
   */
  unload () {
    return Promise.all(
      _.map(this.stores, store => store.knex.destroy())
    )
  }

  constructor (app) {
    super(app, {
      config: require('./config'),
      api: require('./api'),
      pkg: require('./package')
    })
  }

  /**
   * Migrate schema according to the database configuration
   */
  migrate () {
    const SchemaMigrationService = this.app.services.SchemaMigrationService
    const database = this.app.config.database

    if (database.models.migrate == 'none') return

    return Promise.all(
      _.map(this.stores, store => {
        if (database.models.migrate == 'drop') {
          return SchemaMigrationService.drop(store.knex, this.app.models)
        }
      }))
      .then(() => {
        return Promise.all(_.map(this.stores, store => {
          return SchemaMigrationService.create(store.knex, this.app.models)
        }))
      })
  }
}

<|endoftext|>


<commit_before>var vdf = require('vdf');
var fs = require('fs');
var SteamID = require('steamid');

var protomask = 0x80000000;

var Language = require(__dirname + '/language.js');
var Protos = require(__dirname + '/protos.js');

var base_gcmessages = Protos.base_gcmessages;
var tf_gcmessages = Protos.tf_gcmessages;

module.exports = TeamFortress2;

require('util').inherits(TeamFortress2, require('events').EventEmitter);

function TeamFortress2(steam) {
	this._steam = steam;
	this.haveGCSession = false;

	var self = this;

	// "extend" the default steam.gamesPlayed function so we can catch when TF2 starts up
	var gamesPlayed = steam.gamesPlayed;
	steam.gamesPlayed = function(appids) {
		if(appids.indexOf(440) != -1 && !self.haveGCSession) {
			self._connect();
		} else if(self._helloInterval) {
			clearInterval(self._helloInterval);
			self._helloInterval = null;
		}

		gamesPlayed.call(steam, appids);
	};

	steam.on('fromGC', function(appID, type, body) {
		if(appID != 440) {
			// Not from the TF2 GC
			return;
		}

		var protobuf = !!(type & protomask);
		type &= ~protomask;

		if(self._handlers[type]) {
			self._handlers[type].call(self, body);
		} else {
			var msgName = type;
			for(var i in Language) {
				if(Language[i] == type) {
					msgName = i;
					break;
				}
			}

			self.emit('debug', "Got unhandled GC message " + msgName + (protobuf ? " (protobuf)" : ""));
		}
	});
}

TeamFortress2.prototype._connect = function() {
	var self = this;
	this._helloInterval = setInterval(function() {
		if(self.haveGCSession) {
			clearInterval(self._helloInterval);
			self._helloInterval = null;
			return;
		}

		self._send(Language.ClientHello, base_gcmessages.CMsgClientHello, {});
	}, 2000);
};

TeamFortress2.prototype._send = function(type, protobuf, body) {
	var msgName = type;
	for(var i in Language) {
		if(Language[i] == type) {
			msgName = i;
			break;
		}
	}

	this.emit('debug', "Sending GC message " + msgName);

	if(protobuf) {
		this._steam.toGC(440, type | protomask, protobuf.serialize(body));
	} else {
		this._steam.toGC(440, type, body);
	}
};

TeamFortress2.prototype.setLang = function(langFile) {
	var lang = vdf.parse(langFile);
	// The vdf parser appears to add some random characters and quotes to the root 'lang' key, so we'll just use a loop to find it
	for(var i in lang) {
		this.lang = lang[i].Tokens;
	}
};

TeamFortress2.prototype.craft = function(items, recipe) {
	var buffer = new Buffer(2 + 2 + (8 * items.length));
	buffer.writeInt16LE(recipe || -2, 0); // -2 is wildcard
	buffer.writeInt16LE(items.length, 2);
	for(var i = 0; i < items.length; i++) {
		buffer.writeUInt64LE(items[i], 4 + (i * 8));
	}

	this._send(Language.Craft, null, buffer);
};

TeamFortress2.prototype.trade = function(steamID) {
	var tradeID = Math.floor(Math.random() * 100000) + 1;
	var buffer = new Buffer(12);
	buffer.writeUInt32LE(tradeID, 0);
	buffer.writeUInt64LE(steamID, 4);
	this._send(Language.Trading_InitiateTradeRequest, null, buffer);
	return tradeID;
};

TeamFortress2.prototype.setStyle = function(item, style) {
	var buffer = new Buffer(12);
	buffer.writeUInt64LE(item, 0);
	buffer.writeUInt32LE(style, 8);
	this._send(Language.SetItemStyle, null, buffer);
};

TeamFortress2.prototype.setPosition = function(item, position) {
	var buffer = new Buffer(16);
	buffer.writeUInt64LE(item, 0);
	buffer.writeUInt64LE(position, 8);
	this._send(Language.SetSingleItemPosition, null, buffer);
};

TeamFortress2.prototype.setPositions = function(items) {
	this._send(Language.SetItemPositions, base_gcmessages.CMsgSetItemPositions, {"itemPositions": items});
};

TeamFortress2.prototype.deleteItem = function(item) {
	var buffer = new Buffer(8);
	buffer.writeUInt64LE(item);
	this._send(Language.Delete, null, buffer);
};

TeamFortress2.prototype.wrapItem = function(wrapID, itemID) {
	var buffer = new Buffer(16);
	buffer.writeUInt64LE(wrapID, 0);
	buffer.writeUInt64LE(itemID, 8);
	this._send(Language.GiftWrapItem, null, buffer);
};

TeamFortress2.prototype.deliverGift = function(gift, steamID) {
	var buffer = new Buffer(16);
	buffer.writeUInt64LE(gift, 0);
	buffer.writeUInt64LE(steamID, 8);
	this._send(Language.DeliverGift, null, buffer);
};

TeamFortress2.prototype.unwrapGift = function(gift) {
	var buffer = new Buffer(8);
	buffer.writeUInt64LE(gift);
	this._send(Language.UnwrapGiftRequest, null, buffer);
};

TeamFortress2.prototype.useItem = function(item) {
	this._send(Language.UseItemRequest, base_gcmessages.CMsgUseItem, {"itemId": item});
};

TeamFortress2.prototype.sortBackpack = function(sortType) {
	this._send(Language.SortItems, base_gcmessages.CMsgSortItems, {"sortType": sortType});
};

TeamFortress2.prototype.sendProfessorSpeks = function(steamID) {
	this._send(Language.FreeTrial_ChooseMostHelpfulFriend, tf_gcmessages.CMsgTFFreeTrialChooseMostHelpfulFriend, {"accountIdFriend": new SteamID(steamID).accountid});
};

TeamFortress2.prototype.createServerIdentity = function() {
	this._send(Language.GameServer_CreateIdentity, tf_gcmessages.CMsgGC_GameServer_CreateIdentity, {"accountId": new SteamID(this._steam.steamID).accountid});
};

TeamFortress2.prototype.getRegisteredServers = function() {
	this._send(Language.GameServer_List, tf_gcmessages.CMsgGC_GameServer_List, {"accountId": new SteamID(this._steam.steamID).accountid});
};

TeamFortress2.prototype.resetServerIdentity = function(id) {
	this._send(Language.GameServer_ResetIdentity, tf_gcmessages.CMsgGC_GameServer_ResetIdentity, {"gameServerAccountId": id});
};

TeamFortress2.prototype._handlers = {};

require('./enums.js');
require('./handlers.js');<commit_msg>Revert "Generate and return a tradeID when sending a trade request"<commit_after>var vdf = require('vdf');
var fs = require('fs');
var SteamID = require('steamid');

var protomask = 0x80000000;

var Language = require(__dirname + '/language.js');
var Protos = require(__dirname + '/protos.js');

var base_gcmessages = Protos.base_gcmessages;
var tf_gcmessages = Protos.tf_gcmessages;

module.exports = TeamFortress2;

require('util').inherits(TeamFortress2, require('events').EventEmitter);

function TeamFortress2(steam) {
	this._steam = steam;
	this.haveGCSession = false;

	var self = this;

	// "extend" the default steam.gamesPlayed function so we can catch when TF2 starts up
	var gamesPlayed = steam.gamesPlayed;
	steam.gamesPlayed = function(appids) {
		if(appids.indexOf(440) != -1 && !self.haveGCSession) {
			self._connect();
		} else if(self._helloInterval) {
			clearInterval(self._helloInterval);
			self._helloInterval = null;
		}

		gamesPlayed.call(steam, appids);
	};

	steam.on('fromGC', function(appID, type, body) {
		if(appID != 440) {
			// Not from the TF2 GC
			return;
		}

		var protobuf = !!(type & protomask);
		type &= ~protomask;

		if(self._handlers[type]) {
			self._handlers[type].call(self, body);
		} else {
			var msgName = type;
			for(var i in Language) {
				if(Language[i] == type) {
					msgName = i;
					break;
				}
			}

			self.emit('debug', "Got unhandled GC message " + msgName + (protobuf ? " (protobuf)" : ""));
		}
	});
}

TeamFortress2.prototype._connect = function() {
	var self = this;
	this._helloInterval = setInterval(function() {
		if(self.haveGCSession) {
			clearInterval(self._helloInterval);
			self._helloInterval = null;
			return;
		}

		self._send(Language.ClientHello, base_gcmessages.CMsgClientHello, {});
	}, 2000);
};

TeamFortress2.prototype._send = function(type, protobuf, body) {
	var msgName = type;
	for(var i in Language) {
		if(Language[i] == type) {
			msgName = i;
			break;
		}
	}

	this.emit('debug', "Sending GC message " + msgName);

	if(protobuf) {
		this._steam.toGC(440, type | protomask, protobuf.serialize(body));
	} else {
		this._steam.toGC(440, type, body);
	}
};

TeamFortress2.prototype.setLang = function(langFile) {
	var lang = vdf.parse(langFile);
	// The vdf parser appears to add some random characters and quotes to the root 'lang' key, so we'll just use a loop to find it
	for(var i in lang) {
		this.lang = lang[i].Tokens;
	}
};

TeamFortress2.prototype.craft = function(items, recipe) {
	var buffer = new Buffer(2 + 2 + (8 * items.length));
	buffer.writeInt16LE(recipe || -2, 0); // -2 is wildcard
	buffer.writeInt16LE(items.length, 2);
	for(var i = 0; i < items.length; i++) {
		buffer.writeUInt64LE(items[i], 4 + (i * 8));
	}

	this._send(Language.Craft, null, buffer);
};

TeamFortress2.prototype.trade = function(steamID) {
	var buffer = new Buffer(12);
	buffer.writeUInt32LE(0, 0);
	buffer.writeUInt64LE(steamID, 4);
	this._send(Language.Trading_InitiateTradeRequest, null, buffer);
};

TeamFortress2.prototype.setStyle = function(item, style) {
	var buffer = new Buffer(12);
	buffer.writeUInt64LE(item, 0);
	buffer.writeUInt32LE(style, 8);
	this._send(Language.SetItemStyle, null, buffer);
};

TeamFortress2.prototype.setPosition = function(item, position) {
	var buffer = new Buffer(16);
	buffer.writeUInt64LE(item, 0);
	buffer.writeUInt64LE(position, 8);
	this._send(Language.SetSingleItemPosition, null, buffer);
};

TeamFortress2.prototype.setPositions = function(items) {
	this._send(Language.SetItemPositions, base_gcmessages.CMsgSetItemPositions, {"itemPositions": items});
};

TeamFortress2.prototype.deleteItem = function(item) {
	var buffer = new Buffer(8);
	buffer.writeUInt64LE(item);
	this._send(Language.Delete, null, buffer);
};

TeamFortress2.prototype.wrapItem = function(wrapID, itemID) {
	var buffer = new Buffer(16);
	buffer.writeUInt64LE(wrapID, 0);
	buffer.writeUInt64LE(itemID, 8);
	this._send(Language.GiftWrapItem, null, buffer);
};

TeamFortress2.prototype.deliverGift = function(gift, steamID) {
	var buffer = new Buffer(16);
	buffer.writeUInt64LE(gift, 0);
	buffer.writeUInt64LE(steamID, 8);
	this._send(Language.DeliverGift, null, buffer);
};

TeamFortress2.prototype.unwrapGift = function(gift) {
	var buffer = new Buffer(8);
	buffer.writeUInt64LE(gift);
	this._send(Language.UnwrapGiftRequest, null, buffer);
};

TeamFortress2.prototype.useItem = function(item) {
	this._send(Language.UseItemRequest, base_gcmessages.CMsgUseItem, {"itemId": item});
};

TeamFortress2.prototype.sortBackpack = function(sortType) {
	this._send(Language.SortItems, base_gcmessages.CMsgSortItems, {"sortType": sortType});
};

TeamFortress2.prototype.sendProfessorSpeks = function(steamID) {
	this._send(Language.FreeTrial_ChooseMostHelpfulFriend, tf_gcmessages.CMsgTFFreeTrialChooseMostHelpfulFriend, {"accountIdFriend": new SteamID(steamID).accountid});
};

TeamFortress2.prototype.createServerIdentity = function() {
	this._send(Language.GameServer_CreateIdentity, tf_gcmessages.CMsgGC_GameServer_CreateIdentity, {"accountId": new SteamID(this._steam.steamID).accountid});
};

TeamFortress2.prototype.getRegisteredServers = function() {
	this._send(Language.GameServer_List, tf_gcmessages.CMsgGC_GameServer_List, {"accountId": new SteamID(this._steam.steamID).accountid});
};

TeamFortress2.prototype.resetServerIdentity = function(id) {
	this._send(Language.GameServer_ResetIdentity, tf_gcmessages.CMsgGC_GameServer_ResetIdentity, {"gameServerAccountId": id});
};

TeamFortress2.prototype._handlers = {};

require('./enums.js');
require('./handlers.js');<|endoftext|>


<commit_before>var fs = require("fs");
var twitterPkg = require("twitter");
var express = require('express');
var hexu = require("hexu");
var request = require("request");
var kov = require("kov");
var app = express();

var addData = require("./data/data.js").addData;

var config = JSON.parse(fs.readFileSync("./config.json"));

var data = JSON.parse(fs.readFileSync("./data/data.json"));

var Twitter = new twitterPkg(config);

var opts = {
  type: "sentence",
  min: 2,
  max: 5
}

var makePost = function() {
  var post = kov(data, opts);
  Twitter.post('statuses/update', {status: post},  function(error, tweet, response){
    if(error){
      console.log(hexu.red(error));
    }
    console.log(hexu.green("🐦  Tweeted: " + post));
    addData(post);
  });
}

var greeting = function() {
  Twitter.post('statuses/update', {status: "I'm alive. Hello world?"},  function(error, tweet, response){
    if(error){
      console.log(error);
    }
  });
}

// Routes
app.get("/", function(req, res) {
  res.header('Content-Type', 'application/json');
  res.end(JSON.stringify(require("./data/data.js").quotes));
  // console.log(hexu.green("GET '/'"));
});

app.get("/new", function(req, res) {
  makePost();
  console.log(hexu.green("GET '/new', making new post..."));
})

app.listen(process.env.OPENSHIFT_NODEJS_PORT || 3000, process.env.OPENSHIFT_NODEJS_IP || "localhost");
console.log(hexu.blue("======= Ice is Awake ======="))

makePost()
setInterval(makePost, 1000 * 60 * 60)
<commit_msg>stringify error<commit_after>var fs = require("fs");
var twitterPkg = require("twitter");
var express = require('express');
var hexu = require("hexu");
var request = require("request");
var kov = require("kov");
var app = express();

var addData = require("./data/data.js").addData;

var config = JSON.parse(fs.readFileSync("./config.json"));

var data = JSON.parse(fs.readFileSync("./data/data.json"));

var Twitter = new twitterPkg(config);

var opts = {
  type: "sentence",
  min: 2,
  max: 5
}

var makePost = function() {
  var post = kov(data, opts);
  Twitter.post('statuses/update', {status: post},  function(error, tweet, response){
    if(error){
      console.log(hexu.red(JSON.stringify(error)));
    }
    console.log(hexu.green("🐦  Tweeted: " + post));
    addData(post);
  });
}

var greeting = function() {
  Twitter.post('statuses/update', {status: "I'm alive. Hello world?"},  function(error, tweet, response){
    if(error){
      console.log(error);
    }
  });
}

// Routes
app.get("/", function(req, res) {
  res.header('Content-Type', 'application/json');
  res.end(JSON.stringify(require("./data/data.js").quotes));
  // console.log(hexu.green("GET '/'"));
});

app.get("/new", function(req, res) {
  makePost();
  console.log(hexu.green("GET '/new', making new post..."));
})

app.listen(process.env.OPENSHIFT_NODEJS_PORT || 3000, process.env.OPENSHIFT_NODEJS_IP || "localhost");
console.log(hexu.blue("======= Ice is Awake ======="))

makePost()
setInterval(makePost, 1000 * 60 * 60)
<|endoftext|>


<commit_before>/*
    This gulp plugin converts raw html files into mithril m() syntax.
    The original code is written by Leo Horie (https://github.com/lhorie)
    Original code on a web application can be found here: http://lhorie.github.io/mithril/tools/template-converter.html

*/

// Scripts used
var through = require('through2');
var gutil = require('gulp-util');
// Cheerio is needed for jquery
var cheerio = require('cheerio');

var PluginError = gutil.PluginError;

// Consts
const PLUGIN_NAME = 'mithrilify';

function mithrilify(obj, postRender) {

    // Creating a stream through which each file will pass
    var stream = through.obj(function(file, enc, callback) {
        //console.log(String(file.contents));

        var source = String(file.contents);
        $ = cheerio.load('

');

        var templateConverter = {};
        templateConverter.DOMFragment = function(markup) {
            if (markup.indexOf("<!doctype") > -1) return [new DOMParser().parseFromString(markup, "text/html").childNodes[1]]
            //var container = window.document.createElement("div");
            //container.insertAdjacentHTML("beforeend", markup);
            $("div").html(markup);
            //console.log($("div").children());
            return $("div").children();
        }
        templateConverter.VirtualFragment = function recurse(domFragment) {
            var virtualFragment = [];

                domFragment.each(function(){
                    if(this.type == "text"){
                        virtualFragment.push(this.data);
                    } else {
                        var attrs = this.attribs;
                        virtualFragment.push({tag: this.name.toLowerCase(), attrs: attrs, children: recurse($(this).children())});

                    }
                })

            return virtualFragment;
        }
        templateConverter.Template = function recurse() {
            if (Object.prototype.toString.call(arguments[0]) == "[object String]") {
                return new recurse(new templateConverter.VirtualFragment(new templateConverter.DOMFragment(arguments[0])));
            }

            var virtualFragment = arguments[0], level = arguments[1]
            if (!level) level = 1;

            var tab = "\n" + new Array(level + 1).join("\t");
            var virtuals = [];
            for (var i = 0, el; el = virtualFragment[i]; i++) {
                if (typeof el == "string") {
                    if (el.match(/\t| {2,}/g) && el.trim().length == 0) virtuals.indented = true;
                    else virtuals.push('"' + el.replace(/"/g, '\\"').replace(/\r/g, "\\r").replace(/\n/g, "\\n") + '"');
                }
                else {
                    var virtual = "";
                    if (el.tag != "div") virtual += el.tag;
                    if (el.attrs["class"]) {
                        virtual += "." + el.attrs["class"].replace(/\t+/g, " ").split(" ").join(".");
                        delete el.attrs["class"];
                    }
                    var attrNames = Object.keys(el.attrs).sort()
                    for (var j = 0, attrName; attrName = attrNames[j]; j++) {
                        if (attrName != "style") virtual += "[" + attrName + "='" + el.attrs[attrName].replace(/'/g, "\\'") + "']";
                    }
                    virtual = '"' + virtual + '"';

                    var style = ""
                    if (el.attrs.style) {
                        virtual += ", {style: " + ("{\"" + el.attrs.style.replace(/:/g, "\": \"").replace(/;/g, "\", \"") + "}").replace(/, "}|"}/, "}") + "}"
                    }

                    if (el.children.length > 0) {
                        virtual += ", " + recurse(el.children, level + 1);
                    }
                    virtual = "m(" + virtual + ")";
                    virtuals.push(virtual);
                }
            }
            if (!virtuals.indented) tab = "";

            var isInline = virtuals.length == 1 && virtuals[0].charAt(0) == '"';
            var template = isInline ? virtuals.join(", ") : "[" + tab + virtuals.join("," + tab) + tab.slice(0, -1) + "]";
            return new String(template);
        }

        templateConverter.controller = function(source) {
            var template =  new templateConverter.Template(source);
            return template;
        };

        var output = templateConverter.controller(source).toString();
        if(postRender){
            var config = '{ config: ctrl.'+postRender+' },'
        } else {
            var config = "";
        }
        if(!obj){
            var obj = "obj";
        }
        var viewjs =  obj + '.view =  function(ctrl){ return m("div",'+config+' ['+output+']) }';

        var outputBuffer = new Buffer(viewjs);
        if (file.isNull()) {
            // Do nothing if no contents
            throw new PluginError(PLUGIN_NAME, "The file is empty or there was no file. ");

        }
        if (file.isBuffer()) {
            file.contents = Buffer.concat([outputBuffer]);
        }

        if (file.isStream()) {
            throw new PluginError(PLUGIN_NAME, "Stream isn't supported yet. ");
        }

        this.push(file);
        return callback();

    });

    return stream;
};

module.exports = mithrilify;<commit_msg>Fixed two bugs<commit_after>/*
    This gulp plugin converts raw html files into mithril m() syntax.
    The original code is written by Leo Horie (https://github.com/lhorie)
    Original code on a web application can be found here: http://lhorie.github.io/mithril/tools/template-converter.html

*/

// Scripts used
var through = require('through2');
var gutil = require('gulp-util');
// Cheerio is needed for jquery
var cheerio = require('cheerio');

var PluginError = gutil.PluginError;

// Consts
const PLUGIN_NAME = 'mithrilify';

function mithrilify(obj, postRender) {

    // Creating a stream through which each file will pass
    var stream = through.obj(function(file, enc, callback) {

        var source = String(file.contents);
        $ = cheerio.load('

');

        var templateConverter = {};
        templateConverter.DOMFragment = function(markup) {
            if (markup.indexOf("<!doctype") > -1) return [new DOMParser().parseFromString(markup, "text/html").childNodes[1]]
            //var container = window.document.createElement("div");
            //container.insertAdjacentHTML("beforeend", markup);
            var newDiv = $("div");
            newDiv.html(markup);
            //console.log($("div").children());
            return newDiv.children();
        }
        templateConverter.VirtualFragment = function recurse(domFragment) {
            var virtualFragment = [];

                domFragment.each(function(){
                    if(this.prev){
                        if(this.prev.type == "text"){
                            virtualFragment.push(this.prev.data);
                        }
                    }
                    var attrs = this.attribs;
                    virtualFragment.push({tag: this.name.toLowerCase(), attrs: attrs, children: recurse($(this).children())});
                })

            return virtualFragment;
        }
        templateConverter.Template = function recurse() {
            if (Object.prototype.toString.call(arguments[0]) == "[object String]") {
                return new recurse(new templateConverter.VirtualFragment(new templateConverter.DOMFragment(arguments[0])));
            }

            var virtualFragment = arguments[0], level = arguments[1]
            if (!level) level = 1;

            var tab = "\n" + new Array(level + 1).join("\t");
            var virtuals = [];
            for (var i = 0, el; el = virtualFragment[i]; i++) {
                if (typeof el == "string") {
                    if (el.match(/\t| {2,}/g) && el.trim().length == 0) virtuals.indented = true;
                    else virtuals.push('"' + el.replace(/"/g, '\\"').replace(/\r/g, "\\r").replace(/\n/g, "\\n") + '"');
                }
                else {
                    var virtual = "";
                    if (el.tag != "div") virtual += el.tag;
                    if (el.attrs["class"]) {
                        virtual += "." + el.attrs["class"].replace(/\t+/g, " ").split(" ").join(".");
                        delete el.attrs["class"];
                    }
                    var attrNames = Object.keys(el.attrs).sort()
                    for (var j = 0, attrName; attrName = attrNames[j]; j++) {
                        if (attrName != "style") virtual += "[" + attrName + "='" + el.attrs[attrName].replace(/'/g, "\\'") + "']";
                    }
                    virtual = '"' + virtual + '"';

                    var style = ""
                    if (el.attrs.style) {
                        virtual += ", {style: " + ("{\"" + el.attrs.style.replace(/:/g, "\": \"").replace(/;/g, "\", \"") + "}").replace(/, "}|"}/, "}") + "}"
                    }

                    if (el.children.length > 0) {
                        virtual += ", " + recurse(el.children, level + 1);
                    }
                    virtual = "m(" + virtual + ")";
                    virtuals.push(virtual);
                }
            }
            if (!virtuals.indented) tab = "";

            var isInline = virtuals.length == 1 && virtuals[0].charAt(0) == '"';
            var template = isInline ? virtuals.join(", ") : "[" + tab + virtuals.join("," + tab) + tab.slice(0, -1) + "]";
            return new String(template);
        }

        templateConverter.controller = function(source) {
            var template =  new templateConverter.Template(source);
            return template;
        };

        var output = templateConverter.controller(source).toString();
        if(postRender){
            var config = '{ config: ctrl.'+postRender+' },'
        } else {
            var config = "";
        }
        if(!obj){
            var obj = "obj";
        }
        var viewjs =  obj + '.view =  function(ctrl){ return m("div",'+config+' ['+output+']) }';

        var outputBuffer = new Buffer(viewjs);
        if (file.isNull()) {
            // Do nothing if no contents
            throw new PluginError(PLUGIN_NAME, "The file is empty or there was no file. ");

        }
        if (file.isBuffer()) {
            file.contents = Buffer.concat([outputBuffer]);
        }

        if (file.isStream()) {
            throw new PluginError(PLUGIN_NAME, "Stream isn't supported yet. ");
        }

        this.push(file);
        return callback();

    });

    return stream;
};

module.exports = mithrilify;<|endoftext|>


<commit_before>var jsext = module.require('./base').jsext;

module.require('./events');
module.require('./collection');
module.require('./function');
module.require('./string');
module.require('./number');
module.require('./date');
module.require('./object');
module.require('./messenger');
module.require('./worker-nodejs');

module.exports = {
  events: jsext.events,
  arr: jsext.arr,
  grid: jsext.grid,
  interval: jsext.interval,
  arrayProjection: jsext.arrayProjection,
  fun: jsext.fun,
  Closure: jsext.Closure,
  string: jsext.string,
  num: jsext.num,
  date: jsext.date,
  obj: jsext.obj,
  path: jsext.path,
  properties: jsext.properties,
  message: jsext.message,
  worker: jsext.worker
}
<commit_msg>fix for messenger import<commit_after>var jsext = module.require('./base').jsext;

module.require('./events');
module.require('./collection');
module.require('./function');
module.require('./string');
module.require('./number');
module.require('./date');
module.require('./object');
module.require('./messenger');
module.require('./worker-nodejs');

module.exports = {
  events: jsext.events,
  arr: jsext.arr,
  grid: jsext.grid,
  interval: jsext.interval,
  arrayProjection: jsext.arrayProjection,
  fun: jsext.fun,
  Closure: jsext.Closure,
  string: jsext.string,
  num: jsext.num,
  date: jsext.date,
  obj: jsext.obj,
  path: jsext.path,
  properties: jsext.properties,
  messenger: jsext.messenger,
  worker: jsext.worker
}
<|endoftext|>


<commit_before>#! /usr/bin/env node
"use strict"

var path = require('path')
var sh = require('shelljs')
var config = require('yargs')
  .option('s', {
    alias: 'srcDir',
    type: 'string',
    default: 'dist',
    describe: 'The source directory that you want to publish to the gh-pages branch. This directory will become the root directory of the gh-pages branch.'
  })
  .option('p', {
    alias: 'publishDir',
    type: 'string',
    default: '.publish',
    describe: 'When publishing to GitHub pages, this directory will be created to publish from.'
  })
  .option('d', {
    alias: 'deletePublishDir',
    type: 'boolean',
    default: false,
    describe: 'If true, the publishDir will be recursively deleted when the script has finished.'
  })
  .option('u', {
    alias: 'allowUncommitted',
    type: 'boolean',
    default: false,
    describe: 'If true, the script will allow you to deploy uncommitted changes to the gh-pages branch.'
  })
  .option('o', {
    alias: 'outputLevel',
    type: 'number',
    default: 1,
    choices: [0, 1, 2, 3],
    describe: 'The verbosity of the output from 0 (no output) to 3 (verbose output).'
  })
  .usage('Usage: $0 [options]')
  .example('$0 -c -s dist', 'Publish the contents of the `dist` directory to the gh-pages branch and delete the publish directory afterwards.')
  .help('h')
  .alias('h', 'help')
  .argv

function logToConsole(msg) {
  if (config.outputLevel >= 1)
    console.log(msg)
}

sh.config.verbose = config.outputLevel >= 2
sh.config.silent = !(config.outputLevel >= 3)

var projectRoot = process.cwd()
var absoluteSourceDir = path.resolve(projectRoot, config.srcDir)
var absolutePublishDir = path.resolve(projectRoot, config.publishDir)
var remoteUrl = sh.exec('git config --get remote.origin.url').trim()

if (!config.allowUncommitted && sh.exec('git diff --exit-code && git diff --staged --exit-code').code !== 0) {
  logToConsole('You have uncommitted changes! Please commit your files and then try again.')
  deletePublishDir()
  return process.exit(1)
}

sh.mkdir('-p', absolutePublishDir)
sh.cd(absolutePublishDir)

if (sh.ls('.git').code !== 0)
  sh.exec('git clone ' + remoteUrl + ' .')

if (sh.exec('git branch -a').indexOf('gh-pages') === -1)
  sh.exec('git branch gh-pages')
sh.exec('git checkout gh-pages')

sh.exec('git rm -r .')
sh.cp('-R', path.join(absoluteSourceDir, '*'), '.')
sh.exec('git add -A .')

if (sh.exec('git diff --staged --exit-code').code === 0) {
  sh.exec('git reset --hard')
  logToConsole('Nothing to deploy - no changes detected.')
}
else {
  sh.exec('git commit -m "update gh-pages ' + new Date().toISOString() + '"')
  sh.exec('git push --set-upstream origin gh-pages')
  logToConsole('Successfully deployed to origin/gh-pages.')
}

deletePublishDir()

function deletePublishDir() {
  if (!config.deletePublishDir)
    return

  while (sh.pwd().indexOf(absolutePublishDir) >= 0)
    sh.cd('..')

  sh.rm('-rf', absolutePublishDir)
}<commit_msg>fix example<commit_after>#! /usr/bin/env node
"use strict"

var path = require('path')
var sh = require('shelljs')
var config = require('yargs')
  .option('s', {
    alias: 'srcDir',
    type: 'string',
    default: 'dist',
    describe: 'The source directory that you want to publish to the gh-pages branch. This directory will become the root directory of the gh-pages branch.'
  })
  .option('p', {
    alias: 'publishDir',
    type: 'string',
    default: '.publish',
    describe: 'When publishing to GitHub pages, this directory will be created to publish from.'
  })
  .option('d', {
    alias: 'deletePublishDir',
    type: 'boolean',
    default: false,
    describe: 'If true, the publishDir will be recursively deleted when the script has finished.'
  })
  .option('u', {
    alias: 'allowUncommitted',
    type: 'boolean',
    default: false,
    describe: 'If true, the script will allow you to deploy uncommitted changes to the gh-pages branch.'
  })
  .option('o', {
    alias: 'outputLevel',
    type: 'number',
    default: 1,
    choices: [0, 1, 2, 3],
    describe: 'The verbosity of the output from 0 (no output) to 3 (verbose output).'
  })
  .usage('Usage: $0 [options]')
  .example('$0 -d -s dist', 'Publish the contents of the `dist` directory to the gh-pages branch and delete the publish directory afterwards.')
  .help('h')
  .alias('h', 'help')
  .argv

function logToConsole(msg) {
  if (config.outputLevel >= 1)
    console.log(msg)
}

sh.config.verbose = config.outputLevel >= 2
sh.config.silent = !(config.outputLevel >= 3)

var projectRoot = process.cwd()
var absoluteSourceDir = path.resolve(projectRoot, config.srcDir)
var absolutePublishDir = path.resolve(projectRoot, config.publishDir)
var remoteUrl = sh.exec('git config --get remote.origin.url').trim()

if (!config.allowUncommitted && sh.exec('git diff --exit-code && git diff --staged --exit-code').code !== 0) {
  logToConsole('You have uncommitted changes! Please commit your files and then try again.')
  deletePublishDir()
  return process.exit(1)
}

sh.mkdir('-p', absolutePublishDir)
sh.cd(absolutePublishDir)

if (sh.ls('.git').code !== 0)
  sh.exec('git clone ' + remoteUrl + ' .')

if (sh.exec('git branch -a').indexOf('gh-pages') === -1)
  sh.exec('git branch gh-pages')
sh.exec('git checkout gh-pages')

sh.exec('git rm -r .')
sh.cp('-R', path.join(absoluteSourceDir, '*'), '.')
sh.exec('git add -A .')

if (sh.exec('git diff --staged --exit-code').code === 0) {
  sh.exec('git reset --hard')
  logToConsole('Nothing to deploy - no changes detected.')
}
else {
  sh.exec('git commit -m "update gh-pages ' + new Date().toISOString() + '"')
  sh.exec('git push --set-upstream origin gh-pages')
  logToConsole('Successfully deployed to origin/gh-pages.')
}

deletePublishDir()

function deletePublishDir() {
  if (!config.deletePublishDir)
    return

  while (sh.pwd().indexOf(absolutePublishDir) >= 0)
    sh.cd('..')

  sh.rm('-rf', absolutePublishDir)
}<|endoftext|>