<commit_before>'use strict';

var through = require('through-gulp');
var StringDecoder = require('string_decoder').StringDecoder;
var decoder = new StringDecoder('utf8');
var superviewjs = require("superviews.js");

var path = require('path');
var gutil = require('gulp-util');
var File = gutil.File;
var PluginError = gutil.PluginError;

// file can be a vinyl file object or a string
// when a string it will construct a new one
module.exports = function(file, opt) {
	opt = opt || {};
	// to preserve existing |undefined| behaviour and to introduce |newLine: ""| for binaries
	if (typeof opt.newLine !== 'string') {
		opt.newLine = gutil.linefeed;
	}
	return through(function(file, encoding,callback) {
		if (file.isNull()) {}
		if (file.isBuffer()) {
			var templateFile = new Buffer(decoder.write(file.contents));
			templateFile = superviewjs(decoder.write(templateFile));
			file.contents = new Buffer(templateFile);
		}
		if (file.isStream()) {}
		this.push(file);
		callback();
		}, function(callback) {
		callback();
	});
};
<commit_msg>fixed when there a new line or tab in html template<commit_after>'use strict';

var through = require('through-gulp');
var StringDecoder = require('string_decoder').StringDecoder;
var decoder = new StringDecoder('utf8');
var superviewjs = require("superviews.js");

var path = require('path');
var gutil = require('gulp-util');
var File = gutil.File;
var PluginError = gutil.PluginError;

// file can be a vinyl file object or a string
// when a string it will construct a new one
module.exports = function(file, opt) {
	opt = opt || {};
	// to preserve existing |undefined| behaviour and to introduce |newLine: ""| for binaries
	if (typeof opt.newLine !== 'string') {
		opt.newLine = gutil.linefeed;
	}
	return through(function(file, encoding,callback) {
		if (file.isNull()) {}
		if (file.isBuffer()) {
			var templateFile = new Buffer(decoder.write(file.contents));
			templateFile = superviewjs(decoder.write(templateFile).replace(/[\n\t\r]/g," "));
			file.contents = new Buffer(templateFile);
		}
		if (file.isStream()) {}
		this.push(file);
		callback();
		}, function(callback) {
		callback();
	});
};
<|endoftext|>


<commit_before>/*!
GPII Universal Personalization Framework GPII Windows Index

Copyright 2014 Lucendo Development Ltd.

Licensed under the New BSD license. You may not use this file except in
compliance with this License.

The research leading to these results has received funding from the European Union's
Seventh Framework Programme (FP7/2007-2013) under grant agreement no. 289016.

You may obtain a copy of the License at
https://github.com/gpii/universal/LICENSE.txt
*/

"use strict";

var fluid = require("gpii-universal");

fluid.module.register("gpii-windows", __dirname, require);

fluid.contextAware.makeChecks({
    "gpii.contexts.windows": {
        value: true
    }
});

require("./gpii/node_modules/WindowsUtilities/WindowsUtilities.js");
require("./gpii/node_modules/processHandling/processHandling.js");
require("./gpii/node_modules/displaySettingsHandler");
require("./gpii/node_modules/registrySettingsHandler");
require("./gpii/node_modules/registryResolver");
require("./gpii/node_modules/spiSettingsHandler");
require("./gpii/node_modules/registeredAT/registeredAT.js");
require("./gpii/node_modules/windowsMetrics");
require("./gpii/node_modules/processReporter");
require("./gpii/node_modules/windowMessages");
require("./gpii/node_modules/userListeners");

module.exports = fluid;
<commit_msg>Making GPII crash<commit_after>/*!
GPII Universal Personalization Framework GPII Windows Index

Copyright 2014 Lucendo Development Ltd.

Licensed under the New BSD license. You may not use this file except in
compliance with this License.

The research leading to these results has received funding from the European Union's
Seventh Framework Programme (FP7/2007-2013) under grant agreement no. 289016.

You may obtain a copy of the License at
https://github.com/gpii/universal/LICENSE.txt
*/

"use strict";

var fluid = require("gpii-universal");

fluid.module.register("gpii-windows", __dirname, require);

fluid.contextAware.makeChecks({
    "gpii.contexts.windows": {
        value: true
    }
});

require("./gpii/node_modules/WindowsUtilities/WindowsUtilities.js");

// Not for production:
var gpii = fluid.registerNamespace("gpii");
console.log("Crashing");
//  Crash by invoking a null callback.
gpii.windows.user32.EnumWindows(Buffer.alloc(0) ,0);
console.log("Crash failed");

require("./gpii/node_modules/processHandling/processHandling.js");
require("./gpii/node_modules/displaySettingsHandler");
require("./gpii/node_modules/registrySettingsHandler");
require("./gpii/node_modules/registryResolver");
require("./gpii/node_modules/spiSettingsHandler");
require("./gpii/node_modules/registeredAT/registeredAT.js");
require("./gpii/node_modules/windowsMetrics");
require("./gpii/node_modules/processReporter");
require("./gpii/node_modules/windowMessages");
require("./gpii/node_modules/userListeners");

module.exports = fluid;
<|endoftext|>


<commit_before>/**
 * Convert SGF files to a JS object
 * @param {string} sgf A valid SGF file.
 * @see http://www.red-bean.com/sgf/sgf4.html
 * @return {object} The SGF file represented as a JS object
 */
exports.parse = function (sgf) {
	var parse;
	var parser;
	var collection = {};

	// tracks the current sequence
	var sequence;

	// tracks the current node
	var node;

	// tracks the last PropIdent
	var lastPropIdent;

	// A map of functions to parse the different components of an SGF file
	parser = {

		beginSequence: function (sgf) {
			if (!sequence) {
				sequence = collection;
			}

			var newSequence = {
				parent: sequence
			};

			sequence.sequences = sequence.sequences || [];
			sequence.sequences.push(newSequence);
			sequence = newSequence;

			return parse(sgf.substring(1));
		},

		endSequence: function (sgf) {
			if (sequence.parent) {
				sequence = sequence.parent;
			} else {
				sequence = null;
			}
			return parse(sgf.substring(1));
		},

		node: function (sgf) {
			node = {};
			sequence.nodes = sequence.nodes || [];
			sequence.nodes.push(node);
			return parse(sgf.substring(1));
		},

		property: function (sgf) {
			var propValue;

			// Search for the first unescaped ]
			var firstPropEnd = sgf.search(/[^\\]\]/) + 1;

			if (firstPropEnd > -1) {
				var property = sgf.substring(0, firstPropEnd + 1);
				var propValueBegin = property.indexOf('[');

				var propIdent = property.substring(0, propValueBegin);

				// Point lists don't declare a PropIdent for each PropValue
				// Instead, they should use the last declared property
				// See: http://www.red-bean.com/sgf/sgf4.html#move/pos
				if (!propIdent) {
					propIdent = lastPropIdent;

					// If this is the first property in a list of multiple
					// properties, we need to wrap the PropValue in an array
					if (!Array.isArray(node[propIdent])) {
						node[propIdent] = [node[propIdent]];
					}
				}

				lastPropIdent = propIdent;

				propValue = property.substring(propValueBegin + 1, property.length - 1);

				// We have no problem parsing PropIdents of any length, but the spec
				// says they should be no longer than two characters.
				//
				// http://www.red-bean.com/sgf/sgf4.html#2.2
				if (propIdent.length > 2) {
					// TODO: What's the best way to issue a warning?
					console.warn(
						'SGF PropIdents should be no longer than two characters:', propIdent
					);
				}

				if (Array.isArray(node[propIdent])) {
					node[propIdent].push(propValue);
				} else {
					node[propIdent] = propValue;
				}

				return parse(sgf.substring(firstPropEnd + 1));
			} else {

				// TODO: Provide details about where in the SGF the error occurred.
				throw new Error('malformed sgf');
			}
		},

		// Whitespace, tabs, or anything else we don't recognize
		unrecognized: function (sgf) {

			// March ahead to the next character
			return parse(sgf.substring(1));
		}
	};

	// Processes an SGF file character by character
	parse = function (sgf) {
		var initial = sgf.substring(0, 1);
		var type;

		// Use the initial (the first character in the remaining sgf file) to
		// decide which parser function to use
		if (!initial) {
			return collection;
		} else if (initial === '(') {
			type = 'beginSequence';
		} else if (initial === ')') {
			type = 'endSequence';
		} else if (initial === ';') {
			type = 'node';
		} else if (initial.match(/[A-Z\[]/)) {
			type = 'property';
		} else {
			type = 'unrecognized';
		}

		return parser[type](sgf);
	};

	// Begin parsing the SGF file
	return parse(sgf);
};

/**
 * Generate an SGF file from a SmartGame Record JavaScript Object
 * @param {object} record A record object.
 * @return {string} The record as a string suitable for saving as an SGF file
 */
exports.generate = function (record) {
	function stringifySequences(sequences) {
		var contents = '';

		sequences.forEach(function (sequence) {
			contents += '(';

			// Parse all nodes in this sequence
			if (sequence.nodes) {
				sequence.nodes.forEach(function (node) {
					var nodeString = ';';
					for (property in node) {
						var prop = node[property];
						if (Array.isArray(prop)) {
							prop = prop.join('][');
						}
						nodeString += property + '[' + prop + ']';
					}
					contents += nodeString;
				});
			}

			// Call the function we're in recursively for any child sequences
			if (sequence.sequences) {
				contents += stringifySequences(sequence.sequences);
			}

			contents += ')';
		});

		return contents;
	}

	return stringifySequences(record.sequences);
};
<commit_msg>Change name of top-level array to gameTrees<commit_after>/**
 * Convert SGF files to a JS object
 * @param {string} sgf A valid SGF file.
 * @see http://www.red-bean.com/sgf/sgf4.html
 * @return {object} The SGF file represented as a JS object
 */
exports.parse = function (sgf) {
	var parse;
	var parser;
	var collection = {};

	// tracks the current sequence
	var sequence;

	// tracks the current node
	var node;

	// tracks the last PropIdent
	var lastPropIdent;

	// A map of functions to parse the different components of an SGF file
	parser = {

		beginSequence: function (sgf) {
			var key = 'sequences';

			// Top-level sequences are gameTrees
			if (!sequence) {
				sequence = collection;
				key = 'gameTrees';
			}

			if (sequence.gameTrees) {
				key = 'gameTrees';
			}

			var newSequence = {
				parent: sequence
			};

			sequence[key] = sequence[key] || [];
			sequence[key].push(newSequence);
			sequence = newSequence;

			return parse(sgf.substring(1));
		},

		endSequence: function (sgf) {
			if (sequence.parent) {
				sequence = sequence.parent;
			} else {
				sequence = null;
			}
			return parse(sgf.substring(1));
		},

		node: function (sgf) {
			node = {};
			sequence.nodes = sequence.nodes || [];
			sequence.nodes.push(node);
			return parse(sgf.substring(1));
		},

		property: function (sgf) {
			var propValue;

			// Search for the first unescaped ]
			var firstPropEnd = sgf.search(/[^\\]\]/) + 1;

			if (firstPropEnd > -1) {
				var property = sgf.substring(0, firstPropEnd + 1);
				var propValueBegin = property.indexOf('[');

				var propIdent = property.substring(0, propValueBegin);

				// Point lists don't declare a PropIdent for each PropValue
				// Instead, they should use the last declared property
				// See: http://www.red-bean.com/sgf/sgf4.html#move/pos
				if (!propIdent) {
					propIdent = lastPropIdent;

					// If this is the first property in a list of multiple
					// properties, we need to wrap the PropValue in an array
					if (!Array.isArray(node[propIdent])) {
						node[propIdent] = [node[propIdent]];
					}
				}

				lastPropIdent = propIdent;

				propValue = property.substring(propValueBegin + 1, property.length - 1);

				// We have no problem parsing PropIdents of any length, but the spec
				// says they should be no longer than two characters.
				//
				// http://www.red-bean.com/sgf/sgf4.html#2.2
				if (propIdent.length > 2) {
					// TODO: What's the best way to issue a warning?
					console.warn(
						'SGF PropIdents should be no longer than two characters:', propIdent
					);
				}

				if (Array.isArray(node[propIdent])) {
					node[propIdent].push(propValue);
				} else {
					node[propIdent] = propValue;
				}

				return parse(sgf.substring(firstPropEnd + 1));
			} else {

				// TODO: Provide details about where in the SGF the error occurred.
				throw new Error('malformed sgf');
			}
		},

		// Whitespace, tabs, or anything else we don't recognize
		unrecognized: function (sgf) {

			// March ahead to the next character
			return parse(sgf.substring(1));
		}
	};

	// Processes an SGF file character by character
	parse = function (sgf) {
		var initial = sgf.substring(0, 1);
		var type;

		// Use the initial (the first character in the remaining sgf file) to
		// decide which parser function to use
		if (!initial) {
			return collection;
		} else if (initial === '(') {
			type = 'beginSequence';
		} else if (initial === ')') {
			type = 'endSequence';
		} else if (initial === ';') {
			type = 'node';
		} else if (initial.match(/[A-Z\[]/)) {
			type = 'property';
		} else {
			type = 'unrecognized';
		}

		return parser[type](sgf);
	};

	// Begin parsing the SGF file
	return parse(sgf);
};

/**
 * Generate an SGF file from a SmartGame Record JavaScript Object
 * @param {object} record A record object.
 * @return {string} The record as a string suitable for saving as an SGF file
 */
exports.generate = function (record) {
	function stringifySequences(sequences) {
		var contents = '';

		sequences.forEach(function (sequence) {
			contents += '(';

			// Parse all nodes in this sequence
			if (sequence.nodes) {
				sequence.nodes.forEach(function (node) {
					var nodeString = ';';
					for (property in node) {
						var prop = node[property];
						if (Array.isArray(prop)) {
							prop = prop.join('][');
						}
						nodeString += property + '[' + prop + ']';
					}
					contents += nodeString;
				});
			}

			// Call the function we're in recursively for any child sequences
			if (sequence.sequences) {
				contents += stringifySequences(sequence.sequences);
			}

			contents += ')';
		});

		return contents;
	}

	return stringifySequences(record.gameTrees);
};
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var execSync = require('exec-sync');

var hookArgs = process.env.HOOK_ARGS ? process.env.HOOK_ARGS.split('\u263a') : [];

function run(cmd) {
  return _.compact(execSync(cmd).split('\n'));
}

var getArgs = {
  'pre-commit': function () {
    return run('git diff --cached --name-only --diff-filter=ACM');
  },
  'commit-msg': function () { return hookArgs[0]; },
  'applypatch-msg': function () { return hookArgs[0]; },
  'pre-applypatch': function () { return hookArgs[0]; },
  'post-checkout': function () { return hookArgs[0]; },
  'post-commit': function () { return hookArgs[0]; }
};

module.exports = function (gulp) {
  return {
    stream: function (name) {
      return gulp.src(this.src(name));
    },
    src: function (name, fn) {
      var args = getArgs[name]();

      if (fn && typeof fn === 'function') {
        return fn.bind(fn, args);
      }

      return args;
    }
  };

};
<commit_msg>stream indexed file contents<commit_after>'use strict';

var getHook = require('./lib/get-hook.js');

module.exports = function (gulp) {
  return {
    stream: function (name) {
      var hook = getHook(name);

      if (!hook.stream) {
        throw new Error('Hook not streamable: ' + name);
      }

      return hook.stream(gulp);
    },
    src: function (name, fn) {
      var hook = getHook(name);

      if (fn && typeof fn === 'function') {
        if (hook.extra) {
          return fn.bind(fn, hook.src, hook.extra);
        } else {
          return fn.bind(fn, hook.src);
        }
      } else if (!hook.src) {
        throw new Error('Hook has no source files, use guppy.src() as a callback: ' + name);
      }

      return hook.src;
    }
  };
};
<|endoftext|>


<commit_before>var request = require('request');
var url = require('url');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var WebSocket = require('ws');

function EurekaDongle(base) {
  this.url = base
  this.urlParts = url.parse(base);
  EventEmitter.call(this);
}

util.inherits(EurekaDongle, EventEmitter);

EurekaDongle.prototype.timer = null;

var appList = null;
EurekaDongle.prototype.collectAppList = function(fn) {

  request('https://clients3.google.com/cast/chromecast/device/config', function(e, r, b) {
    var obj = JSON.parse(b.replace(')]}', ''));
    appList = {};
    obj.applications.forEach(function(app) {
      appList[app.app_name.toLowerCase()] = app;
    });

    fn();
  });
};

EurekaDongle.prototype.start = function(name, resource, callback) {

  var req = {
    headers: {
      'Connection' : 'close',
    },
    method : 'POST',
  }

  if (name.toLowerCase() === 'youtube') {
    resource = 'v=' + resource;

    req.headers['Content-Type'] = 'application/x-www-form-urlencoded';

    req.headers['Content-Length'] = resource.length,
    req.body = resource;

    var payload = JSON.stringify({
      channel: 0,
      senderId : {
        appName : 'ChromeCast',
        senderId: 'myid' + Math.random()
      }
    });

    var that = this;

    this.emit('launching');

    (function waitForDevice() {

      request.post(that.url + '/connection/YouTube', {
        headers: {
          'Content-Type' : 'application/json',
          'Content-Length' : payload.length,
          'Host' : that.urlParts.host,
          'Origin' : 'chrome-extension://boadgeojelhgndaghljhdicfkmllpafd'
        },
        body : payload,
      }, function(e, r, b) {

        clearTimeout(that.timer);

        if (r.statusCode === 200) {
          that.timer = setTimeout(function() {
            that.prepareRampSocket(b)
          }, 2000);
        } else {
          that.timer = setTimeout(waitForDevice, 500);
        }
      });
    })();
  }

  request(this.url + '/apps/YouTube', req, callback);
};

EurekaDongle.prototype.stop = function(name, callback) {
  var appsUrl = this.url + '/apps/' + name;
  var that = this;

  request.del(appsUrl, function() {
    // We really need to ensure it's gone or a restart will cause
    // 408s
    that.timer = setTimeout(function() {
      that.emit('stopped');
      callback();
    }, 2000);
  });

  this.timer && clearTimeout(this.timer);
  this.ws && this.ws.close();
  this.currentApp = null;
};

EurekaDongle.prototype.prepareRampSocket = function(b) {
  var wsUrl = JSON.parse(b.toString()).URL;
  var that = this;

  var ws = this.ws = new WebSocket(wsUrl, {
    origin: 'chrome-extension://boadgeojelhgndaghljhdicfkmllpafd'
  });

  var first = true;
  ws.on('message', function(data, flags) {
    data = JSON.parse(data);

    if (first) {
      var status = data[1].status;

      ws.send(JSON.stringify([
        "cv", {
          "type":"activity",
          "message": {
            "type":"update_description",
            "activityId":status.content_id,
            "description":status.title,
            "iconUrl":status.image_url
          }
        }
      ]), { mask: true });

      that.getStatus();

      first = false;
    } else {
      clearTimeout(that.timer);

      if (data[1] && data[1].cmd_id && data[1].cmd_id === 1000) {
        that.emit('status', data);
      }

      that.timer = setTimeout(function() {
        that.getStatus()
      }, 500);
    }
  });
};

EurekaDongle.prototype.getStatus = function() {
  this.ws.send(JSON.stringify([
    'ramp', { cmd_id : 1000, type: 'INFO' }
  ]), { mask: true });
};

module.exports = EurekaDongle;
<commit_msg>allow a full youtube url to be passed<commit_after>var request = require('request');
var url = require('url');
var qs = require('querystring');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var WebSocket = require('ws');

function EurekaDongle(base) {
  this.url = base
  this.urlParts = url.parse(base);
  EventEmitter.call(this);
}

util.inherits(EurekaDongle, EventEmitter);

EurekaDongle.prototype.timer = null;

var appList = null;
EurekaDongle.prototype.collectAppList = function(fn) {

  request('https://clients3.google.com/cast/chromecast/device/config', function(e, r, b) {
    var obj = JSON.parse(b.replace(')]}', ''));
    appList = {};
    obj.applications.forEach(function(app) {
      appList[app.app_name.toLowerCase()] = app;
    });

    fn();
  });
};

EurekaDongle.prototype.start = function(name, resource, callback) {

  var req = {
    headers: {
      'Connection' : 'close',
    },
    method : 'POST',
  }

  if (name.toLowerCase() === 'youtube') {
    if (resource.indexOf('v=')) {
      var urlParts = url.parse(resource);

      if (urlParts.query) {
        var queryParts = qs.parse(urlParts.query);
        if (queryParts.v) {
          resource = queryParts.v;
        } else {
          return;
        }
      } else {
        return;
      }
    }

    resource = 'v=' + resource;

    req.headers['Content-Type'] = 'application/x-www-form-urlencoded';

    req.headers['Content-Length'] = resource.length,
    req.body = resource;

    var payload = JSON.stringify({
      channel: 0,
      senderId : {
        appName : 'ChromeCast',
        senderId: 'myid' + Math.random()
      }
    });

    var that = this;

    this.emit('launching');

    (function waitForDevice() {

      request.post(that.url + '/connection/YouTube', {
        headers: {
          'Content-Type' : 'application/json',
          'Content-Length' : payload.length,
          'Host' : that.urlParts.host,
          'Origin' : 'chrome-extension://boadgeojelhgndaghljhdicfkmllpafd'
        },
        body : payload,
      }, function(e, r, b) {

        clearTimeout(that.timer);

        if (r.statusCode === 200) {
          that.timer = setTimeout(function() {
            that.prepareRampSocket(b)
          }, 2000);
        } else {
          that.timer = setTimeout(waitForDevice, 500);
        }
      });
    })();
  }

  request(this.url + '/apps/YouTube', req, callback);
};

EurekaDongle.prototype.stop = function(name, callback) {
  var appsUrl = this.url + '/apps/' + name;
  var that = this;

  request.del(appsUrl, function() {
    // We really need to ensure it's gone or a restart will cause
    // 408s
    that.timer = setTimeout(function() {
      that.emit('stopped');
      callback();
    }, 2000);
  });

  this.timer && clearTimeout(this.timer);
  this.ws && this.ws.close();
  this.currentApp = null;
};

EurekaDongle.prototype.prepareRampSocket = function(b) {
  var wsUrl = JSON.parse(b.toString()).URL;
  var that = this;

  var ws = this.ws = new WebSocket(wsUrl, {
    origin: 'chrome-extension://boadgeojelhgndaghljhdicfkmllpafd'
  });

  var first = true;
  ws.on('message', function(data, flags) {
    data = JSON.parse(data);

    if (first) {
      var status = data[1].status;

      ws.send(JSON.stringify([
        "cv", {
          "type":"activity",
          "message": {
            "type":"update_description",
            "activityId":status.content_id,
            "description":status.title,
            "iconUrl":status.image_url
          }
        }
      ]), { mask: true });

      that.getStatus();

      first = false;
    } else {
      clearTimeout(that.timer);

      if (data[1] && data[1].cmd_id && data[1].cmd_id === 1000) {
        that.emit('status', data);
      }

      that.timer = setTimeout(function() {
        that.getStatus()
      }, 500);
    }
  });
};

EurekaDongle.prototype.getStatus = function() {
  this.ws.send(JSON.stringify([
    'ramp', { cmd_id : 1000, type: 'INFO' }
  ]), { mask: true });
};

module.exports = EurekaDongle;
<|endoftext|>


<commit_before>var path = require('path');
var moment = require('moment');

var Pingu = class Pingu {
  constructor(logLevel) {
    /**
      * available levels are:
      *
      * - 1
      * - 2
      * - 3
      */

    this.logLevel = logLevel;
    this.logDir = path.resolve(path.dirname(require.main.filename), 'log');
    this.logFile = 'pingu.log';
  }

  /**
    * set the log level without redefining the class
    */

  setLogLevel(level) {
    this.logLevel = level;
    console.log(`PINGU: Set log level to ${level}`);
  }

  /**
    * check the log level
    */

  checkLogLevel() {
    console.log(`PINGU: Log level is ${this.logLevel}`);
  }

  /**
    * set the log directory without redefining the class
    */

  setLogDir(dir) {
    this.logDir = path.resolve(path.dirname(require.main.filename), dir);
    console.log(`PINGU: Set log directory to ${dir}`);
  }

  /**
    * check the log directory
    */

  checkLogDir() {
    console.log(`PINGU: Log directory is ${this.logDir}`);
  }

  log(message) {
     var out = `PINGU [LOG]: ${message}`;
    console.log(out);

    if(this.logLevel <= 1) {
      /* write log */
      this.writeLog(out, 'log');
    }
  }

  warn(message) {
     var out = `PINGU [WARN]: ${message}`;
    console.warn(out);
    console.trace();

    if(this.logLevel <= 2) {
      /* write log */
      this.writeLog(out, 'warn');
    }
  }

  error(message) {
     var out = `PINGU [ERROR]: ${message}`;
    console.error(out);
    console.trace();

    if(this.logLevel <= 3) {
      /* write log */
      this.writeLog(out, 'error');
    }
  }

  /**
    * write our messages to the
    */

  writeLog(message, type) {
    if(typeof window === 'undefined') {
       var fs = require('fs');
       var logFile = path.join(this.logDir, this.logFile);

      try {

        if (!fs.existsSync(this.logDir)) {
          fs.mkdirSync(this.logDir);
        }

         var append = `[${moment().format()}] ${message}\r\n`;

        fs.appendFileSync(logFile, append);

        if(type !== 'log') {
           var stack = new Error().stack;
          fs.appendFileSync(logFile, `${stack}\r\n`);
        }
      } catch(err) {
        throw err;
      }
    }
  }
};

var pingu = new Pingu('LOG');

module.exports = pingu;
<commit_msg>Changing class for object approach<commit_after>var path = require('path');
var moment = require('moment');

var pingu = {
  logLevel: 1,
  logDir: path.resolve(path.dirname(require.main.filename), 'log'),
  logFile: 'pingu.log',

  /**
    * set the log level without redefining the class
    */

  setLogLevel: function(level) {
    this.logLevel = level;
    console.log(`PINGU: Set log level to ${level}`);
  },

  /**
    * check the log level
    */

  checkLogLevel: function() {
    console.log(`PINGU: Log level is ${this.logLevel}`);
  },

  /**
    * set the log directory without redefining the class
    */

  setLogDir: function(dir) {
    this.logDir = path.resolve(path.dirname(require.main.filename), dir);
    console.log(`PINGU: Set log directory to ${dir}`);
  },

  /**
    * check the log directory
    */

  checkLogDir: function() {
    console.log(`PINGU: Log directory is ${this.logDir}`);
  },

  log: function(message) {
     var out = `PINGU [LOG]: ${message}`;
    console.log(out);

    if(this.logLevel <= 1) {
      /* write log */
      this.writeLog(out, 'log');
    }
  },

  warn: function(message) {
     var out = `PINGU [WARN]: ${message}`;
    console.warn(out);
    console.trace();

    if(this.logLevel <= 2) {
      /* write log */
      this.writeLog(out, 'warn');
    }
  },

  error: function(message) {
     var out = `PINGU [ERROR]: ${message}`;
    console.error(out);
    console.trace();

    if(this.logLevel <= 3) {
      /* write log */
      this.writeLog(out, 'error');
    }
  },

  /**
    * write our messages to the
    */

  writeLog: function(message, type) {
    if(typeof window === 'undefined') {
       var fs = require('fs');
       var logFile = path.join(this.logDir, this.logFile);

      try {

        if (!fs.existsSync(this.logDir)) {
          fs.mkdirSync(this.logDir);
        }

         var append = `[${moment().format()}] ${message}\r\n`;

        fs.appendFileSync(logFile, append);

        if(type !== 'log') {
           var stack = new Error().stack;
          fs.appendFileSync(logFile, `${stack}\r\n`);
        }
      } catch(err) {
        throw err;
      }
    }
  }
};

module.exports = pingu;
<|endoftext|>


<commit_before>var five = require('johnny-five'),
	Edison = require('edison-io'),
	scroll = require('lcd-scrolling')
	;

var io = require('socket.io-client');

var board = new five.Board({
	io: new Edison(),
	repl: false,
});

var messages = [];

board.on('ready', function() {
	var messageLed = new five.Led(4);

  var lcd = new five.LCD({
    controller: 'JHD1313M1'
  });

	scroll.setup({
		lcd: lcd,
		firstCharPauseDuration: 2000,
		lastCharPauseDuration: 750,
		scrollingDuration: 150
	});

	lcd.on().bgColor('#cccccc').print('Starting...');

	const socket = io('ws://192.168.1.45:30809', {
		transports: ['websocket'],
		jsonp: false
	});
	socket.on('connect', function () {
		socket.emit('join', { name: 'test' });
		lcd.clear();
	});
	socket.on('message', function(data) {
		var message = data.message;
		messages.push(message);
		messageLed.on();

		lcd.clear();
		scroll.clear();
		if (message.length > 16) scroll.line(0, message);
		else lcd.print(message);
	});
	socket.connect();

	setTimeout(function() {
		messageLed.off();
	}, 500);

	board.on('warn', function(event) {
		if (event.class === 'Board' && event.message === 'Closing.') {
			lcd.bgColor('#000000').off();
			messageLed.off();
		}
	});
});
<commit_msg>Handle multiple messages and button to move to next<commit_after>var five = require('johnny-five'),
	Edison = require('edison-io'),
	scroll = require('lcd-scrolling')
	;

var io = require('socket.io-client');

var board = new five.Board({
	io: new Edison(),
	repl: false,
});

var messages = [];

board.on('ready', function() {
	var messageLed = new five.Led(4);

  var lcd = new five.LCD({
    controller: 'JHD1313M1'
  });

	var button = new five.Button(3);

	scroll.setup({
		lcd: lcd,
		firstCharPauseDuration: 2000,
		lastCharPauseDuration: 750,
		scrollingDuration: 150
	});

	lcd.on().bgColor('#cccccc').print('Starting...');

	var displayMessage = function() {
		var message = messages[0];

		lcd.clear();
		scroll.clear();
		if (message.length > 16) scroll.line(0, message);
		else lcd.print(message);
	}

	const socket = io('ws://192.168.1.45:30809', {
		transports: ['websocket'],
		jsonp: false
	});
	socket.on('connect', function () {
		socket.emit('join', { name: 'test' });
		lcd.clear();
	});
	socket.on('message', function(data) {
		var message = data.message;
		messages.push(message);
		messageLed.on();

		if (messages.length === 1) displayMessage();
	});

	button.on('release', function() {
		if (messages.length === 0) return;

		messages.pop();
		if (messages.length > 0) displayMessage();
		else {
			lcd.clear();
			scroll.clear();
			messageLed.off();
		}
	});

	socket.connect();

	board.on('warn', function(event) {
		if (event.class === 'Board' && event.message === 'Closing.') {
			lcd.bgColor('#000000').off();
			messageLed.off();
		}
	});
});
<|endoftext|>


<commit_before>/*!
 * is-number <https://github.com/jonschlinkert/is-number>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var typeOf = require('kind-of');

module.exports = function isNumber(num) {
  if (!num && num !== 0) return false;

  var type = typeOf(num);
  if (type !== 'number' && type !== 'string') {
    return false;
  }
  if (type === 'string') {
    num = num.trim();
    if (!num.length) return false;
  }

  var n = +num;
  return (n - n + 1) >= 0;
};
<commit_msg>update as per https://github.com/jonschlinkert/is-number/pull/6#issuecomment-244160575<commit_after>/*!
 * is-number <https://github.com/jonschlinkert/is-number>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var typeOf = require('kind-of');

module.exports = function isNumber(num) {
  var type = typeOf(num);

  if (type === 'string') {
    if (!num.trim()) return false;
  } else if (type !== 'number') {
    return false;
  }

  return (num - num + 1) >= 0;
};
<|endoftext|>


<commit_before>var request = require('request');
var config = require('./config');

var perform_request = function(url, resolve, reject){

  var options = {
    url: url,
    headers: {
      'Accept': 'application/json',
      'X-Mashape-Key': config.apikey
    }
  };

  return request(options, function(error, response, body) {
    if (error) {
      if(reject){
        return reject(error);
      }else{
        throw error;
      }
    }

    if (response.statusCode === 200) {
      if (resolve) {
        return resolve({
          url: options.url,
          body: JSON.parse(body),
          head: response.headers,
          scroll_url: response.headers['X-Next-Page'],
          scroll_count: response.headers['X-Count']
        });
      }
    } else {
      var error = response.statusCode + " - " + options.url;
      if(reject){
        return reject(error);
      }else{
        throw error;
      }
    }
  });
}

var get = function(url, fields, opts, resolve, reject) {
  if (opts == null) {
    opts = false;
  }
  url = config.endpoint + url + "/";
  if (opts) {
    var optUrl = [], filter, param;
    for (param in opts) {
      var paramValue = opts[param];
      if (param === "filters") {
        for (filter in paramValue) {
          var filterValue = paramValue[filter];
          var hyphen = filter.indexOf('-');
          filter = [filter.substring(0, hyphen), filter.substring(hyphen+1)]
          optUrl.push("filter[" + filter[0] + "][" + filter[1] + "]=" + filterValue);
        }
      } else if(param === "ids") {
        url += paramValue.join(',')
      } else {
        optUrl.push(param + "=" + paramValue);
      }
    }
    if(fields){ optUrl.push("fields=" + fields.join(',')); }
    url += "?" + optUrl.join('&');
  }

  return perform_request(url, resolve, reject);
};

var endpoint = function(e){
  return function(opts, fields) {
    return new Promise(function(resolve, reject){
      get(e, fields, opts, resolve, reject);
    });
  }
}

var endpoints = ["games", "companies", "people", "genres", "keywords", "platforms", "player_perspectives", "pulses", "themes", "franchises", "collections"],
endpoints_obj = {
  image: function(image_object, size = "thumb", filetype = "jpg"){
    if(image_object){
      return "https://res.cloudinary.com/igdb/image/upload/t_" + size + "/" + image_object.cloudinary_id + "." + filetype;
    }
  },
  scroll: function(url){
    return new Promise(function(resolve, reject){
      return perform_request(url, resolve, reject);
    });
  }
};

for(i = 0; i < endpoints.length; i++){
  endpoints_obj[endpoints[i]] = endpoint(endpoints[i]);
}

module.exports = endpoints_obj<commit_msg>a little code reduction<commit_after>var request = require('request');
var config = require('./config');

var perform_request = function(url, resolve, reject){

  var options = {
    url: url,
    headers: {
      'Accept': 'application/json',
      'X-Mashape-Key': config.apikey
    }
  };

  return request(options, function(error, response, body) {
    if (error) {
      if(reject){
        return reject(error);
      }else{
        throw error;
      }
    }

    if (response.statusCode == 200) {
      if (resolve) {
        return resolve({
          url: options.url,
          body: JSON.parse(body),
          head: response.headers,
          scroll_url: response.headers['X-Next-Page'],
          scroll_count: response.headers['X-Count']
        });
      }
    } else {
      var error = response.statusCode + " - " + options.url;
      if(reject){
        return reject(error);
      }else{
        throw error;
      }
    }
  });
}

var get = function(url, fields, opts, resolve, reject) {
  url = config.endpoint + url + "/";
  if (opts) {
    var optUrl = [], filter, param;
    for (param in opts) {
      var paramValue = opts[param];
      if (param == "filters") {
        for (filter in paramValue) {
          filter_split = filter.split('-')
          optUrl.push("filter[" + filter_split[0] + "][" + filter_split[1] + "]=" + paramValue[filter]);
        }
      } else if(param == "ids") {
        url += paramValue.join(',')
      } else {
        optUrl.push(param + "=" + paramValue);
      }
    }
    if(fields){ optUrl.push("fields=" + fields.join(',')); }
    url += "?" + optUrl.join('&');
  }

  return perform_request(url, resolve, reject);
};

var endpoint = function(e){
  return function(opts, fields) {
    return new Promise(function(resolve, reject){
      get(e, fields, opts, resolve, reject);
    });
  }
}

var endpoints = ["games", "companies", "people", "genres", "keywords", "platforms", "player_perspectives", "pulses", "themes", "franchises", "collections"],
endpoints_obj = {
  image: function(image_object, size = "thumb", filetype = "jpg"){
    if(image_object){
      return "https://res.cloudinary.com/igdb/image/upload/t_" + size + "/" + image_object.cloudinary_id + "." + filetype;
    }
  },
  scroll: function(url){
    return new Promise(function(resolve, reject){
      return perform_request(url, resolve, reject);
    });
  }
};

for(i = 0; i < endpoints.length; i++){
  endpoints_obj[endpoints[i]] = endpoint(endpoints[i]);
}

module.exports = endpoints_obj<|endoftext|>


<commit_before>'use strict';

var util = require('./lib/util');
var Parth = require('parth');

exports = module.exports = Manifold;

/*
  ## module.exports
*/
function Manifold(){
  if(!(this instanceof Manifold)){
    return new Manifold();
  }

  this.root = {};
  Parth.call(this);
}
util.inherits(Manifold, Parth);

/* ## manifold.set([path, props])
> set a path to regex mapping for an object

_arguments_
- `path` type string
- `props` type function or plainObject
 - when is a function it will be assigned to the `options.handle`
 - when is a plainObject, all option properties
   are passed first to a `parser` if there is one and if not,
  that property is cloned and assigned to the node props

_returns_ this

The path is taken as a regular expression
using the [parth](http://github.com/stringparser/parth) module,
which uses the usual conventions on for path to regexp parsing.
So you know... interesting things can happen.
*/

Manifold.prototype.set = function(path, opt){
  opt = opt || path;
  var o = util.type(opt || path).plainObject || {};

  o.path = util.type(o.path || path).string;
  o.handle = util.type(o.handle || opt).function;
  o.parent = util.type(o.parent).string;

  var node = this.root;
  if(o.path && !node[o.path]){
    util.super(this, 'set')(o.path);
    node = this.store[o.path];
  } else if(this.store[o.path]){
    node = this.store[o.path];
  }

  if(o.parent && o.parent !== o.path && this.store[o.parent]){
    node.parent = this.store[o.parent];
    o.parent = null;
  }

  Object.keys(o).forEach(function(key){
    var value = o[key]; if(!value){ return; }
    if(util.type(value).plainObject){
      if(!node[key]){ node[key] = {}; }
      util.merge(node[key], util.clone(value, true));
    } else {
      node[key] = util.clone(o[key], true);
    }
  }, this);

  return this;
};

/*
## manifold.get
```js
function get([string path, object options])
```
Get an object previously set matching the `path` given.

_arguments_
 - `path`, optional, type string
 - `options`, optional, type object with all extra information

_when_
 - `options.ref` is `true` the original node is returned
 - the node found has a parent property the parent properties are cloned into the returned object

_returns_ the object (cloned/by reference) `node` found
*/

var skipRE = /children|parent/;

Manifold.prototype.get = function(path, opt){
  var o = util.type(opt || path).plainObject || {};
  var stem = util.super(this, 'get')(path, o);
  var node = stem ? this.store[stem.path] : this.root;

  if(o.ref){ return node; }

  (function whilst(){
    Object.keys(node).forEach(function(key){
      if(skipRE.test(key) || o[key] !== void 0){ return ; }
      o[key] = util.clone(node[key], true);
    });

    if(node.parent && node !== node.parent){
      node = node.parent;
      whilst();
    }
  })();

  return o;
};
<commit_msg>no need to include undefined<commit_after>'use strict';

var util = require('./lib/util');
var Parth = require('parth');

exports = module.exports = Manifold;

/*
  ## module.exports
*/
function Manifold(){
  if(!(this instanceof Manifold)){
    return new Manifold();
  }

  this.root = {};
  Parth.call(this);
}
util.inherits(Manifold, Parth);

/* ## manifold.set([path, props])
> set a path to regex mapping for an object

_arguments_
- `path` type string
- `props` type function or plainObject
 - when is a function it will be assigned to the `options.handle`
 - when is a plainObject, all option properties
   are passed first to a `parser` if there is one and if not,
  that property is cloned and assigned to the node props

_returns_ this

The path is taken as a regular expression
using the [parth](http://github.com/stringparser/parth) module,
which uses the usual conventions on for path to regexp parsing.
So you know... interesting things can happen.
*/

Manifold.prototype.set = function(path, opt){
  opt = opt || path;
  var o = util.type(opt || path).plainObject || {};

  o.path = util.type(o.path || path).string;
  o.handle = util.type(o.handle || opt).function;
  o.parent = util.type(o.parent).string;

  var node = this.root;
  if(o.path && !node[o.path]){
    util.super(this, 'set')(o.path);
    node = this.store[o.path];
  } else if(this.store[o.path]){
    node = this.store[o.path];
  }

  if(o.parent && o.parent !== o.path && this.store[o.parent]){
    node.parent = this.store[o.parent];
    o.parent = null;
  }

  Object.keys(o).forEach(function(key){
    var value = o[key]; if(!value){ return; }
    if(util.type(value).plainObject){
      if(!node[key]){ node[key] = {}; }
      util.merge(node[key], util.clone(value, true));
    } else {
      node[key] = util.clone(o[key], true);
    }
  }, this);

  return this;
};

/*
## manifold.get
```js
function get([string path, object options])
```
Get an object previously set matching the `path` given.

_arguments_
 - `path`, optional, type string
 - `options`, optional, type object with all extra information

_when_
 - `options.ref` is `true` the original node is returned
 - the node found has a parent property the parent properties are cloned into the returned object

_returns_ the object (cloned/by reference) `node` found
*/

var skipRE = /children|parent/;

Manifold.prototype.get = function(path, opt){
  var o = util.type(opt || path).plainObject || {};
  var stem = util.super(this, 'get')(path, o);
  var node = stem ? this.store[stem.path] : this.root;

  if(o.ref){ return node; }

  (function whilst(){
    Object.keys(node).forEach(function(key){
      if(skipRE.test(key)){ return ; }
      o[key] = util.clone(node[key], true);
    });

    if(node.parent && node !== node.parent){
      node = node.parent;
      whilst();
    }
  })();

  return o;
};
<|endoftext|>


<commit_before>'use strict';

var TreeTraverser = require('broccoli-tree-traverser'),
  Writer = require('broccoli-writer'),
  util = require('util'),
  RSVP = require('rsvp'),
  fs = require('fs'),
  path = require('path');

/**
 * Take an input tree, and roll it up into a JSON document.
 * The resulting document will be named `srcDir.json`. it will have
 * key names associated with each of the file and directories that `srcDir` contains.
 * If the key represents the file, then the stringified file contents will be the value of the key.
 * If the key represents a directory, then the value of that key will be an `Object`, represented
 * by the same algorithm
 *
 * @param inputTree - Tree or path
 * @return {Tree2Json}
 * @constructor
 * @alias module:index
 */
function Tree2Json(inputTree) {
  if (!(this instanceof Tree2Json)) return new Tree2Json(inputTree);

  this.walker = new TreeTraverser(inputTree, this);
}

util.inherits(Tree2Json, Writer);

/**
 * Take the contents of the `buffer`, and place it in the JSON at the
 * path represented by filePath

 * @param filePath
 * @param buffer
 */
Tree2Json.prototype.loadJson = function (filePath, buffer) {
  var elem = this.json;
  var keys = filePath.split(path.sep);
  keys.forEach(function (key, i) {
    var subelem;
    if (i === keys.length - 1) {
      elem[key.split('.')[0]] = buffer.toString();
    } else {
      subelem = elem[key] || {};
      elem[key] = subelem;
      elem = subelem;
    }
  });
};

/**
 * Interface implementation required by Walker.
 *
 * Read the file, and load the results into json
 *
 * @param filePath
 * @return {RSVP.Promise}
 */
Tree2Json.prototype.visit = function (filePath) {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    fs.readFile(filePath, function (err, data) {
      if (err) {reject(err);}
      else {
        self.loadJson(filePath, data);
        resolve();
      }
    })
  });
};

/**
 * Satisfy interface required by 'Write'.
 *
 * Defer to walker to read the tree (which will let me visit each file)
 *
 * @param readTree - a function to read the tree. It should return a promise
 * @param destDir - the directory to write the results in
 * @return {RSVP.Promise}
 */
Tree2Json.prototype.write = function (readTree, destDir) {
  var self = this;
  this.json = {};

  return this.walker.read(readTree)
    .then(function () {
      return RSVP.all(Object.keys(self.json).map(function (key) {
        return new RSVP.Promise(function (resolve, reject) {
          fs.writeFile(path.join(destDir, key) + '.json', JSON.stringify(self.json), function (err) {
            if (err) {reject(err);}
            else resolve();
          });
        });
      }));
    }).then(function () {
      //release memory
      self.json = {};
    });
};

/**
 *
 * @type {Tree2Json}
 */
module.exports = Tree2Json;<commit_msg>fixed incorrect use of API<commit_after>'use strict';

var TreeTraverser = require('broccoli-tree-traverser'),
  Writer = require('broccoli-writer'),
  util = require('util'),
  RSVP = require('rsvp'),
  fs = require('fs'),
  path = require('path');

/**
 * Take an input tree, and roll it up into a JSON document.
 * The resulting document will be named `srcDir.json`. it will have
 * key names associated with each of the file and directories that `srcDir` contains.
 * If the key represents the file, then the stringified file contents will be the value of the key.
 * If the key represents a directory, then the value of that key will be an `Object`, represented
 * by the same algorithm
 *
 * @param inputTree - Tree or path
 * @return {Tree2Json}
 * @constructor
 * @alias module:index
 */
function Tree2Json(inputTree) {
  if (!(this instanceof Tree2Json)) return new Tree2Json(inputTree);

  this.walker = new TreeTraverser(inputTree, this);
}

util.inherits(Tree2Json, Writer);

/**
 * Take the contents of the `buffer`, and place it in the JSON at the
 * path represented by filePath

 * @param filePath
 * @param buffer
 */
Tree2Json.prototype.loadJson = function (filePath, buffer) {
  var elem = this.json;
  var keys = filePath.split(path.sep);
  keys.forEach(function (key, i) {
    var subelem;
    if (i === keys.length - 1) {
      elem[key.split('.')[0]] = buffer.toString();
    } else {
      subelem = elem[key] || {};
      elem[key] = subelem;
      elem = subelem;
    }
  });
};

/**
 * Interface implementation required by Walker.
 *
 * Read the file, and load the results into json
 *
 * @param filePath
 * @return {RSVP.Promise}
 */
Tree2Json.prototype.visit = function (filePath) {
  var self = this;
  return new RSVP.Promise(function (resolve, reject) {
    fs.readFile(filePath, function (err, data) {
      if (err) {reject(err);}
      else {
        self.loadJson(filePath, data);
        resolve();
      }
    })
  });
};

/**
 * Satisfy interface required by 'Write'.
 *
 * Defer to walker to read the tree (which will let me visit each file)
 *
 * @param readTree - a function to read the tree. It should return a promise
 * @param destDir - the directory to write the results in
 * @return {RSVP.Promise}
 */
Tree2Json.prototype.write = function (readTree, destDir) {
  var self = this;
  this.json = {};

  return readTree(this.walker)
    .then(function () {
      return RSVP.all(Object.keys(self.json).map(function (key) {
        return new RSVP.Promise(function (resolve, reject) {
          var filename = path.join(destDir, key) + '.json';
          fs.writeFile(filename, JSON.stringify(self.json), function (err) {
            if (err) {reject(err);}
            else resolve(filename);
          });
        });
      }));
    }).then(function (files) {
      self.json = {};
      return files;
    });
};

/**
 *
 * @type {Tree2Json}
 */
module.exports = Tree2Json;<|endoftext|>


<commit_before>var _ = require("lodash");
var DOMParser = require("xmldom").DOMParser;
var domParser = new DOMParser();

module.exports = citygmlPolygons;

var citygmlPolygons = function(xml) {
  var polygons = [];

  var xmlDOM = domParser.parseFromString(xml);
  var polygonsDOM = xmlDOM.getElementsByTagName("gml:Polygon");

  _.each(polygonsDOM, function(polygonDOM) {
    polygons.push(polygonDOM.toString());
  });

  return polygons;
};
<commit_msg>Fixed export order<commit_after>var _ = require("lodash");
var DOMParser = require("xmldom").DOMParser;
var domParser = new DOMParser();

var citygmlPolygons = function(xml) {
  var polygons = [];

  var xmlDOM = domParser.parseFromString(xml);
  var polygonsDOM = xmlDOM.getElementsByTagName("gml:Polygon");

  _.each(polygonsDOM, function(polygonDOM) {
    polygons.push(polygonDOM.toString());
  });

  return polygons;
};

module.exports = citygmlPolygons;
<|endoftext|>


<commit_before>"use strict";
var babel = require("babel-core");
var shouldIgnoreByBabel = require("./lib/babelrc-util").shouldIgnoreByBabel;
var fs = require("fs");
var minimatch = require("minimatch");
var extend = require("xtend");
var createEspowerPlugin = require("babel-plugin-espower/create");
var sourceMapSupport = require("source-map-support");
var extensions = require.extensions,
    originalLoader = extensions[".js"];
function espowerBabel(options) {
    var separator = (options.pattern.lastIndexOf('/', 0) === 0) ? '' : '/',
        pattern = options.cwd + separator + options.pattern,
        babelrc = options.babelrc || {},
        extension = options.extension || ".js";

    var sourceMaps = {};
    // https://github.com/evanw/node-source-map-support
    // `sourceMaps` is the cached map object of transform by babel
    sourceMapSupport.install({
        handleUncaughtExceptions: false,
        retrieveSourceMap: function (source) {
            var map = sourceMaps && sourceMaps[source];
            if (map) {
                return {
                    url: null,
                    map: map
                };
            } else {
                return null;
            }
        }
    });
    function useEspower(babelOptions) {
        babelOptions.plugins = babelOptions.plugins || [];
        var espowerPluginExists = babelOptions.plugins.some(function (plugin) {
            var pluginName = typeof plugin === "string" ? plugin : plugin.key;
            return pluginName === "babel-plugin-espower";
        });
        if (!espowerPluginExists) {
            babelOptions.plugins.push(createEspowerPlugin(babel, options.espowerOptions));
        }
        return babelOptions;
    }

    extensions[extension] = function (localModule, filepath) {
        var result;
        // https://babeljs.io/docs/usage/api/
        var babelOptions = extend(babelrc, {
            filename: filepath,
            sourceMap: "both",
            ast: false
        });
        // transform test files using espower's `pattern` value
        if (minimatch(filepath, pattern)) {
            result = babel.transform(fs.readFileSync(filepath, "utf-8"), useEspower(babelOptions));
            sourceMaps[filepath] = result.map;
            localModule._compile(result.code, filepath);
            return;
        }
        // transform the other files
        if (shouldIgnoreByBabel(filepath, babelOptions)) {
            originalLoader(localModule, filepath);
        } else {
            result = babel.transform(fs.readFileSync(filepath, "utf-8"), babelOptions);
            sourceMaps[filepath] = result.map;
            localModule._compile(result.code, filepath);
        }
    };
}

module.exports = espowerBabel;
<commit_msg>perf(index): reduce detection cost<commit_after>"use strict";
var babel = require("babel-core");
var shouldIgnoreByBabel = require("./lib/babelrc-util").shouldIgnoreByBabel;
var fs = require("fs");
var minimatch = require("minimatch");
var extend = require("xtend");
var createEspowerPlugin = require("babel-plugin-espower/create");
var sourceMapSupport = require("source-map-support");
var extensions = require.extensions,
    originalLoader = extensions[".js"];
function espowerBabel(options) {
    var separator = (options.pattern.lastIndexOf('/', 0) === 0) ? '' : '/';
    var pattern = options.cwd + separator + options.pattern;
    var babelrc = options.babelrc || {};
    var extension = options.extension || ".js";
    // extend babel option
    babelrc = extend(babelrc, {
        babelrc: false,
        sourceMap: "both",
        ast: false
    });
    // attach espower option
    var espoweredBabelrc = useEspower(babelrc);
    var sourceMaps = {};
    // https://github.com/evanw/node-source-map-support
    // `sourceMaps` is the cached map object of transform by babel
    sourceMapSupport.install({
        handleUncaughtExceptions: false,
        retrieveSourceMap: function (source) {
            var map = sourceMaps && sourceMaps[source];
            if (map) {
                return {
                    url: null,
                    map: map
                };
            } else {
                return null;
            }
        }
    });
    function useEspower(babelOptions) {
        babelOptions.plugins = babelOptions.plugins || [];
        var espowerPluginExists = babelOptions.plugins.some(function (plugin) {
            var pluginName = typeof plugin === "string" ? plugin : plugin.key;
            return pluginName === "babel-plugin-espower";
        });
        if (!espowerPluginExists) {
            babelOptions.plugins.push(createEspowerPlugin(babel, options.espowerOptions));
        }
        return babelOptions;
    }

    extensions[extension] = function (localModule, filepath) {
        var result;
        // https://babeljs.io/docs/usage/api/
        babelrc.filename = filepath;
        // transform the other files
        if (shouldIgnoreByBabel(filepath, babelrc)) {
            originalLoader(localModule, filepath);
            return
        }
        // transform test files using espower's `pattern` value
        if (minimatch(filepath, pattern)) {
            result = babel.transform(fs.readFileSync(filepath, "utf-8"), espoweredBabelrc);
            sourceMaps[filepath] = result.map;
            localModule._compile(result.code, filepath);
        } else {
            result = babel.transform(fs.readFileSync(filepath, "utf-8"), babelrc);
            sourceMaps[filepath] = result.map;
            localModule._compile(result.code, filepath);
        }
    };
}

module.exports = espowerBabel;
<|endoftext|>


<commit_before>process.on('uncaughtException', function(err) {
  console.log('Caught exception: ' + err);
  console.log(err.stack);
});

const express = require('express');
const raspividStream = require('raspivid-stream');

const app = express();
const wss = require('express-ws')(app);

const Blinkt = require('node-blinkt');
const leds = new Blinkt();
leds.setup();

leds.setAllPixels(255, 255, 255, 0.1);
leds.sendUpdate();
setTimeout(updateLeds, 1000);

app.get('/', (req, res) => res.sendFile(__dirname + '/index.html'));

app.ws('/video-stream', (ws, req) => {
    console.log('Client connected');
    updateLeds();

    ws.send(JSON.stringify({
      action: 'init',
      width: '960',
      height: '540'
    }));

    var videoStream = raspividStream({ rotation: 180 });

    videoStream.on('data', (data) => {
        ws.send(data, { binary: true }, (error) => { if (error) console.error(error); });
    });

    ws.on('close', () => {
        console.log('Client left');
        updateLeds();
        videoStream.removeAllListeners('data');
    });
});

function updateLeds() {
    const clientCount = wss.getWss().clients.size;
    console.log('Updating leds to show', clientCount, 'clients');

    leds.clearAll();

    for (let i = 0; i < clientCount; i++) {
        let colors = [0, 0, 0];
        colors[Math.floor(i / 8)] = 255;

        leds.setPixel(i % 8, ...colors, 0.1);
    }

    leds.sendUpdate();
}

app.use(function (err, req, res, next) {
  console.error(err);
  next(err);
})

app.listen(80, () => console.log('Server started on 80'));
<commit_msg>Set max brightness<commit_after>process.on('uncaughtException', function(err) {
  console.log('Caught exception: ' + err);
  console.log(err.stack);
});

const express = require('express');
const raspividStream = require('raspivid-stream');

const app = express();
const wss = require('express-ws')(app);

const Blinkt = require('node-blinkt');
const leds = new Blinkt();
leds.setup();

leds.setAllPixels(255, 255, 255, 1);
leds.sendUpdate();
setTimeout(updateLeds, 1000);

app.get('/', (req, res) => res.sendFile(__dirname + '/index.html'));

app.ws('/video-stream', (ws, req) => {
    console.log('Client connected');
    updateLeds();

    ws.send(JSON.stringify({
      action: 'init',
      width: '960',
      height: '540'
    }));

    var videoStream = raspividStream({ rotation: 180 });

    videoStream.on('data', (data) => {
        ws.send(data, { binary: true }, (error) => { if (error) console.error(error); });
    });

    ws.on('close', () => {
        console.log('Client left');
        updateLeds();
        videoStream.removeAllListeners('data');
    });
});

function updateLeds() {
    const clientCount = wss.getWss().clients.size;
    console.log('Updating leds to show', clientCount, 'clients');

    leds.clearAll();

    for (let i = 0; i < clientCount; i++) {
        let colors = [0, 0, 0];
        colors[Math.floor(i / 8)] = 255;

        leds.setPixel(i % 8, ...colors, 1);
    }

    leds.sendUpdate();
}

app.use(function (err, req, res, next) {
  console.error(err);
  next(err);
})

app.listen(80, () => console.log('Server started on 80'));
<|endoftext|>


<commit_before>'use strict';

module.exports = (r, stateFilePath) => {
	const st = require('./state')(stateFilePath),
		pick = (obj, fields) => fields.reduce((o, f) => obj[f] ? Object.assign(o, {[f]: obj[f]}) : o, {});

	if(typeof r !== 'function')
		throw new TypeError(`r must be a RethinkDB instance. Passed instances is a '${typeof r}'`);

	const isObject = v => typeof v === 'object' && v !== null && !Array.isArray(v);

	const existsHandler = err => {
		if(err.name in {ReqlOpFailedError: 0, RqlRuntimeError: 0} && (err.msg || err.message).includes('already exists'))
			return true;
		else
			throw err;
	};

	const createIndexes = (table, db, conn) => new Promise((resolve, reject) => Promise.all(
		table.indexes.map(index => new Promise((resolve, reject) => {
			if(!index.name && typeof index !== 'string')
				throw new TypeError(`Index entry in table (${table.name}) entry must be 'Object' (with '.name' property) or 'String'`);

			if(typeof index === 'string')
				r.db(db).table(table.name).indexCreate(index).run(conn).catch(existsHandler).then(resolve);
			else
				r.db(db).table(table.name)
				.indexCreate(index.name, index.indexFunction || pick(index, ['multi', 'geo']), index.indexFunction ? pick(index, ['multi', 'geo']) : undefined)
				.run(conn)
				.catch(existsHandler)
				.then(resolve);
		}))
	).then(resolve, reject));

	const createTables = (tables, db, conn) => new Promise((resolve, reject) => Promise.all(
		tables.map(table => new Promise((resolve, reject) => {
			if(!table.name && typeof table !== 'string')
				throw new TypeError('Table entry in table entry must be `Object` (with `.name` property) or `String`');

			st.get(db, table)
			.then(state => {
				if(state)
					return resolve(console.log(`table ${db}.${table.name || table} already exists`));

				if(typeof table === 'string')
					r.db(db).tableCreate(table).run(conn)
					.catch(existsHandler)
					.then(() =>
						st.add(db, table)
						.then(() => resolve(console.log(`created table ${db}.${table}`)))
						.catch(() => { throw new Error(`Couldn't add created table ${db}.${table} to the state file`); })
					);
				else
					r.db(db)
					.tableCreate(table.name, pick(table, ['primaryKey', 'durability', 'shards', 'replicas', 'primaryReplicaTag']))
					.run(conn)
					.catch(existsHandler)
					.then(() =>
						st.add(db, table)
						.then(() => {
							if(table.indexes && table.indexes.length)
								createIndexes(table, db, conn)
								.then(() => resolve(console.log(`created table ${db}.${table.name} with ${table.indexes.length} indexes`)))
								.catch(() => resolve(console.log(`created table ${db}.${table.name}, couldn't create ${table.indexes.length} indexes`)));
							else
								resolve(console.log(`created table ${db}.${table.name}`));
						})
					);
			})
			.catch(() => { throw new Error('Something is wrong with state data.'); });
		}))
	).then(resolve, reject));

	r.init = (connection, schema) => new Promise((resolve, reject) => {
		if(typeof connection.db !== 'string')
			throw new TypeError('Connection is not an object or doesn`t have a db property.');

		if(!Array.isArray(schema))
			throw new TypeError('Schema must be an array.');

		return r.connect(connection)
			.then(conn => r.dbCreate(conn.db).run(conn)
				.catch(existsHandler)
				.then(() => createTables(schema, connection.db, conn)
					.then(() =>
						st.save()
						.then(() => resolve(conn))
						.catch(reject)
					)
					.catch(reject)
				)
			);
	});

	return r.init;
};
<commit_msg>optional debug messages<commit_after>'use strict';

module.exports = (r, stateFilePath, options) => {
	const st = require('./state')(stateFilePath),
		pick = (obj, fields) => fields.reduce((o, f) => obj[f] ? Object.assign(o, {[f]: obj[f]}) : o, {});

	options = Object.assign({debug: true}, options);
	const debug = options.debug ? (...args) => console.log.apply(console, args) : (...args) => args;

	if(typeof r !== 'function')
		throw new TypeError(`r must be a RethinkDB instance. Passed instances is a '${typeof r}'`);

	const isObject = v => typeof v === 'object' && v !== null && !Array.isArray(v);

	const existsHandler = err => {
		if(err.name in {ReqlOpFailedError: 0, RqlRuntimeError: 0} && (err.msg || err.message).includes('already exists'))
			return true;
		else
			throw err;
	};

	const createIndexes = (table, db, conn) => new Promise((resolve, reject) => Promise.all(
		table.indexes.map(index => new Promise((resolve, reject) => {
			if(!index.name && typeof index !== 'string')
				throw new TypeError(`Index entry in table (${table.name}) entry must be 'Object' (with '.name' property) or 'String'`);

			if(typeof index === 'string')
				r.db(db).table(table.name).indexCreate(index).run(conn).catch(existsHandler).then(resolve);
			else
				r.db(db).table(table.name)
				.indexCreate(index.name, index.indexFunction || pick(index, ['multi', 'geo']), index.indexFunction ? pick(index, ['multi', 'geo']) : undefined)
				.run(conn)
				.catch(existsHandler)
				.then(resolve);
		}))
	).then(resolve, reject));

	const createTables = (tables, db, conn) => new Promise((resolve, reject) => Promise.all(
		tables.map(table => new Promise((resolve, reject) => {
			if(!table.name && typeof table !== 'string')
				throw new TypeError('Table entry in table entry must be `Object` (with `.name` property) or `String`');

			st.get(db, table)
			.then(state => {
				if(state)
					return resolve(debug(`table ${db}.${table.name || table} already exists`));

				if(typeof table === 'string')
					r.db(db).tableCreate(table).run(conn)
					.catch(existsHandler)
					.then(() =>
						st.add(db, table)
						.then(() => resolve(debug(`created table ${db}.${table}`)))
						.catch(() => { throw new Error(`Couldn't add created table ${db}.${table} to the state file`); })
					);
				else
					r.db(db)
					.tableCreate(table.name, pick(table, ['primaryKey', 'durability', 'shards', 'replicas', 'primaryReplicaTag']))
					.run(conn)
					.catch(existsHandler)
					.then(() =>
						st.add(db, table)
						.then(() => {
							if(table.indexes && table.indexes.length)
								createIndexes(table, db, conn)
								.then(() => resolve(debug(`created table ${db}.${table.name} with ${table.indexes.length} indexes`)))
								.catch(() => resolve(debug(`created table ${db}.${table.name}, couldn't create ${table.indexes.length} indexes`)));
							else
								resolve(debug(`created table ${db}.${table.name}`));
						})
					);
			})
			.catch(() => { throw new Error('Something is wrong with state data.'); });
		}))
	).then(resolve, reject));

	r.init = (connection, schema) => new Promise((resolve, reject) => {
		if(typeof connection.db !== 'string')
			throw new TypeError('Connection is not an object or doesn`t have a db property.');

		if(!Array.isArray(schema))
			throw new TypeError('Schema must be an array.');

		return r.connect(connection)
			.then(conn => r.dbCreate(conn.db).run(conn)
				.catch(existsHandler)
				.then(() => createTables(schema, connection.db, conn)
					.then(() =>
						st.save()
						.then(() => resolve(conn))
						.catch(reject)
					)
					.catch(reject)
				)
			);
	});

	return r.init;
};
<|endoftext|>


<commit_before>/* jshint esnext:true */

// Classes
class Car {
	constructor(color, type) {
		this.wheels = 4;
		this.attributes = {
			wheels: 4,
			color: color,
			type: type
		};
	}

	getAttributes() {
		console.log('This ' + this.attributes.type + ' has the following attributes: ');
		console.dir(this);
	}
}

var simpleCar = new Car('blue', 'classic coupe');
var simpleTruck = new Car('red', 'truck');

simpleCar.getAttributes();
simpleTruck.getAttributes();

// Extending Classes
class MegaCar extends Car {
	constructor(color, type) {
		super(color, type);
		this.supercharged = true;
	}
	goFaster() {
		console.log('Vroom!!!!');
	}
}

var bugatti = new MegaCar('red', 'really fast car');

bugatti.getAttributes();
bugatti.goFaster();

// Let Variables and Scope
var myVariable = 'something else';
function letTest() {
	let myVariable = 'something';
	console.log(myVariable);
}

letTest();
console.log(myVariable);

// Constants
const API_KEY = "aaas9df89js*#*h8sdfsdfkj";

// API_KEY = ":SLKDFJ:LSKDFJ";

// Static class methods

// Arrow Functions

// Destructuring
<commit_msg>Setting up conference structure with no code<commit_after>/* jshint esnext:true */

// Arrows and Lexical This

// Classes

// Extending Classes

// Let Variables and Constants

// Template Strings

// Destructuring

// Default Parameters<|endoftext|>


<commit_before>'use strict';

const extend = require('xtend/mutable');
const closest = require('dom-closest');
const classList = require('class-list');
const classListMultipleValues = require('classlist-multiple-values');

const isMacOs = /OS X/i.test(navigator.userAgent);

const TARGET_SAME_WINDOW = 1;
const TARGET_NEW_WINDOW = 2;

const TYPE_ANCHOR = 1;
const TYPE_BUTTON = 2;
const TYPE_UNFOCUSABLE = 3;

const ELEMENT_CLASS = 'kist-FauxAnchor';
const ELEMENT_SELECTOR = `.${ELEMENT_CLASS}`;

/**
 * @param  {Event}  e
 *
 * @return {Boolean}
 */
function isMetaKey ( e ) {
	return ((e.ctrlKey && !isMacOs) || e.metaKey);
}

/**
 * @param  {Event}  e
 *
 * @return {Boolean}
 */
function isLeftClick ( e ) {
	if (
		e.type === 'click' &&
		e.button === 0 &&
		e.which === 1 &&
		!isMetaKey(e)
	) {
		return true;
	}
	return false;
}

/**
 * @param  {Event}  e
 *
 * @return {Boolean}
 */
function isReturnClick ( e ) {
	if (
		e.type === 'keyup' &&
		e.which === 13 &&
		!isMetaKey(e)
	) {
		return true;
	}
	return false;
}

/**
 * @param  {Event}  e
 *
 * @return {Boolean}
 */
function isMiddleClick ( e ) {
	if (
		e.type === 'mouseup' &&
		e.button === 1 &&
		e.which === 2
	) {
		return true;
	}
	return false;
}

/**
 * @param  {Event}  e
 *
 * @return {Boolean}
 */
function isMetaLeftClick ( e ) {
	if (
		e.type === 'click' &&
		e.button === 0 &&
		e.which === 1 &&
		isMetaKey(e)
	) {
		return true;
	}
	return false;
}

/**
 * @param  {Event}  e
 *
 * @return {Boolean}
 */
function isMetaReturnClick ( e ) {
	if (
		e.type === 'keyup' &&
		e.which === 13 &&
		isMetaKey(e)
	) {
		return true;
	}
	return false;
}

/**
 * @param {Element} element
 * @param {Object} options
 */
function FauxAnchor ( element, options ) {

	this.element = element;
	this.options = extend({}, this.options, options);

	this.prepareClassList();

	this.type = this.determineType();
	this.href = this.determineHref();
	this.target = this.determineTarget();
	this.rel = this.determineRelations();

	this.setupDom();
	this.setupEvents();

}

extend(FauxAnchor.prototype, {

	options: {
		focusUnfocusable: true,
		onPrimaryAction: ( e, cb ) => {
			cb();
		},
		onSecondaryAction: ( e, cb ) => {
			cb();
		},
		elementClass: ELEMENT_CLASS
	},

	determineType: function () {
		if ( this.element instanceof HTMLAnchorElement ) {
			return TYPE_ANCHOR;
		}
		if (
			this.element instanceof HTMLButtonElement ||
			this.element instanceof HTMLInputElement
		) {
			return TYPE_BUTTON;
		}
		return TYPE_UNFOCUSABLE;
	},

	determineHref: function () {
		if ( this.type === TYPE_ANCHOR ) {
			return this.element.href;
		}
		if ( this.element.dataset && this.element.dataset.href ) {
			return this.element.dataset.href;
		}
		if ( this.element.getAttribute('data-href') !== null ) {
			return this.element.getAttribute('data-href');
		}
		throw new Error('Cannot determine href value for faux anchor.');
	},

	determineTarget: function ( e ) {

		if ( typeof e !== 'undefined' ) {

			if (
				this.type === TYPE_ANCHOR &&
				(
					isMiddleClick(e) ||
					isMetaLeftClick(e) ||
					isMetaReturnClick(e)
				)
			) {
				return TARGET_NEW_WINDOW;
			}

			if (
				this.type !== TYPE_ANCHOR &&
				(
					isMetaLeftClick(e)
				)
			) {
				return TARGET_NEW_WINDOW;
			}

		}

		let target = '';

		if ( this.type === TYPE_ANCHOR ) {
			target = this.element.target;
		} else if ( this.element.dataset && this.element.dataset.target ) {
			target = this.element.dataset.target;
		} else if ( this.element.getAttribute('data-target') !== null ) {
			target = this.element.getAttribute('data-target');
		}

		if ( target === '_blank' ) {
			return TARGET_NEW_WINDOW;
		}
		return TARGET_SAME_WINDOW;

	},

	determineRelations: function () {
		if ( this.type === TYPE_ANCHOR ) {
			return this.element.rel;
		}
		if ( this.element.dataset && this.element.dataset.rel ) {
			return this.element.dataset.rel;
		}
		if ( this.element.getAttribute('data-rel') !== null ) {
			return this.element.getAttribute('data-rel');
		}
		return '';
	},

	prepareClassList: function () {

		const cl = classList(this.element);
		const clmv = classListMultipleValues(cl);

		this.classList = {
			add: clmv.add,
			remove: clmv.remove
		};

	},

	setupDom: function () {

		this.classList.add(ELEMENT_CLASS);
		this.classList.add(this.options.elementClass);

		this.element.setAttribute('role', 'link');

		if ( this.type === TYPE_UNFOCUSABLE && this.options.focusUnfocusable ) {
			this.element.setAttribute('tabindex', 0);
		}

	},

	destroyDom: function () {

		this.classList.remove(ELEMENT_CLASS);
		this.classList.remove(this.options.elementClass);

		this.element.removeAttribute('role');

		if ( this.type === TYPE_UNFOCUSABLE && this.options.focusUnfocusable ) {
			this.element.removeAttribute('tabindex');
		}

	},

	setupEvents: function () {

		this.eventListeners = {
			click: ( e ) => {
				if ( this.shouldStopEventPropagation(e) ) {
					e.stopPropagation();
				}
				if (
					this.type === TYPE_ANCHOR &&
					this.target !== TARGET_NEW_WINDOW &&
					isLeftClick(e)
				) {
					e.preventDefault();
				}
				if (
					isLeftClick(e) ||
					isMetaLeftClick(e)
				) {
					this.triggerAction(e);
				}
			},
			mouseup: ( e ) => {
				if ( this.shouldStopEventPropagation(e) ) {
					e.stopPropagation();
				}
				if (
					isMiddleClick(e)
				) {
					if ( this.type === TYPE_ANCHOR ) {
						this.triggerAction(e);
					} else {
						// Fallback
					}
				}
			},
			keyup: ( e ) => {
				if ( this.shouldStopEventPropagation(e) ) {
					e.stopPropagation();
				}
				if (
					isReturnClick(e) ||
					isMetaReturnClick(e)
				) {
					if ( this.type === TYPE_UNFOCUSABLE ) {
						if (
							this.target !== TARGET_NEW_WINDOW &&
							isReturnClick(e)
						) {
							this.triggerAction(e);
						} else {
							// Fallback
						}
					}
				}
			}
		};

		Object.keys(this.eventListeners)
			.forEach(( ev ) => {
				this.element.addEventListener(ev, this.eventListeners[ev], false);
			});

	},

	destroyEvents: function () {

		Object.keys(this.eventListeners)
			.forEach(( ev ) => {
				this.element.removeEventListener(ev, this.eventListeners[ev], false);
			});

	},

	/**
	 * @param  {Event} e
	 *
	 * @return {Boolean}
	 */
	shouldTriggerAction: function ( e ) {

		/**
		 * Don’t trigger action when clicking on anchor
		 * inside non-anchor faux anchor instance
		 */
		if (
			this.type !== TYPE_ANCHOR &&
			closest(e.target, 'a')
		) {
			return false;
		}
		return true;

	},

	/**
	 * @param  {Event} e
	 *
	 * @return {Boolean}
	 */
	shouldStopEventPropagation: function ( e ) {

		/**
		 * Stop event propagation if instance has non-anchor element and
		 * faux anchor instance as parent(s)
		 */
		if (
			!closest(this.element.parentNode, 'a') &&
			closest(this.element.parentNode, ELEMENT_SELECTOR)
		) {
			return true;
		}
		return false;

	},

	/**
	 * @param  {Event} e
	 */
	triggerAction: function ( e ) {

		const target = this.determineTarget(e);

		if ( !this.shouldTriggerAction(e) ) {
			return;
		}

		if ( target === TARGET_NEW_WINDOW ) {
			if ( this.type !== TYPE_ANCHOR ) {
				this.simulateSecondaryAction();
			}
			this.options.onSecondaryAction(e, () => {});
		} else {
			this.options.onPrimaryAction(e, () => {
				this.simulatePrimaryAction();
			});
		}

	},

	simulatePrimaryAction: function () {
		return window.location.assign(this.href);
	},

	simulateSecondaryAction: function () {
		const w = window.open(this.href, '_blank');
		if (
			w &&
			this.rel !== '' &&
			/noopener/.test(this.rel)
		) {
			w.opener = null;
		}
		return w;
	},

	destroy: function () {
		this.destroyDom();
		this.destroyEvents();
	}

});

module.exports = ( element, options ) => {
	const instance = new FauxAnchor(element, options);
	return {
		destroy: () => {
			instance.destroy();
		}
	};
};

module.exports.defaults = FauxAnchor.prototype.options;
module.exports.FauxAnchor = FauxAnchor;
<commit_msg>Rename "defaults" export to "defaultOptions"<commit_after>'use strict';

const extend = require('xtend/mutable');
const closest = require('dom-closest');
const classList = require('class-list');
const classListMultipleValues = require('classlist-multiple-values');

const isMacOs = /OS X/i.test(navigator.userAgent);

const TARGET_SAME_WINDOW = 1;
const TARGET_NEW_WINDOW = 2;

const TYPE_ANCHOR = 1;
const TYPE_BUTTON = 2;
const TYPE_UNFOCUSABLE = 3;

const ELEMENT_CLASS = 'kist-FauxAnchor';
const ELEMENT_SELECTOR = `.${ELEMENT_CLASS}`;

/**
 * @param  {Event}  e
 *
 * @return {Boolean}
 */
function isMetaKey ( e ) {
	return ((e.ctrlKey && !isMacOs) || e.metaKey);
}

/**
 * @param  {Event}  e
 *
 * @return {Boolean}
 */
function isLeftClick ( e ) {
	if (
		e.type === 'click' &&
		e.button === 0 &&
		e.which === 1 &&
		!isMetaKey(e)
	) {
		return true;
	}
	return false;
}

/**
 * @param  {Event}  e
 *
 * @return {Boolean}
 */
function isReturnClick ( e ) {
	if (
		e.type === 'keyup' &&
		e.which === 13 &&
		!isMetaKey(e)
	) {
		return true;
	}
	return false;
}

/**
 * @param  {Event}  e
 *
 * @return {Boolean}
 */
function isMiddleClick ( e ) {
	if (
		e.type === 'mouseup' &&
		e.button === 1 &&
		e.which === 2
	) {
		return true;
	}
	return false;
}

/**
 * @param  {Event}  e
 *
 * @return {Boolean}
 */
function isMetaLeftClick ( e ) {
	if (
		e.type === 'click' &&
		e.button === 0 &&
		e.which === 1 &&
		isMetaKey(e)
	) {
		return true;
	}
	return false;
}

/**
 * @param  {Event}  e
 *
 * @return {Boolean}
 */
function isMetaReturnClick ( e ) {
	if (
		e.type === 'keyup' &&
		e.which === 13 &&
		isMetaKey(e)
	) {
		return true;
	}
	return false;
}

/**
 * @param {Element} element
 * @param {Object} options
 */
function FauxAnchor ( element, options ) {

	this.element = element;
	this.options = extend({}, this.options, options);

	this.prepareClassList();

	this.type = this.determineType();
	this.href = this.determineHref();
	this.target = this.determineTarget();
	this.rel = this.determineRelations();

	this.setupDom();
	this.setupEvents();

}

extend(FauxAnchor.prototype, {

	options: {
		focusUnfocusable: true,
		onPrimaryAction: ( e, cb ) => {
			cb();
		},
		onSecondaryAction: ( e, cb ) => {
			cb();
		},
		elementClass: ELEMENT_CLASS
	},

	determineType: function () {
		if ( this.element instanceof HTMLAnchorElement ) {
			return TYPE_ANCHOR;
		}
		if (
			this.element instanceof HTMLButtonElement ||
			this.element instanceof HTMLInputElement
		) {
			return TYPE_BUTTON;
		}
		return TYPE_UNFOCUSABLE;
	},

	determineHref: function () {
		if ( this.type === TYPE_ANCHOR ) {
			return this.element.href;
		}
		if ( this.element.dataset && this.element.dataset.href ) {
			return this.element.dataset.href;
		}
		if ( this.element.getAttribute('data-href') !== null ) {
			return this.element.getAttribute('data-href');
		}
		throw new Error('Cannot determine href value for faux anchor.');
	},

	determineTarget: function ( e ) {

		if ( typeof e !== 'undefined' ) {

			if (
				this.type === TYPE_ANCHOR &&
				(
					isMiddleClick(e) ||
					isMetaLeftClick(e) ||
					isMetaReturnClick(e)
				)
			) {
				return TARGET_NEW_WINDOW;
			}

			if (
				this.type !== TYPE_ANCHOR &&
				(
					isMetaLeftClick(e)
				)
			) {
				return TARGET_NEW_WINDOW;
			}

		}

		let target = '';

		if ( this.type === TYPE_ANCHOR ) {
			target = this.element.target;
		} else if ( this.element.dataset && this.element.dataset.target ) {
			target = this.element.dataset.target;
		} else if ( this.element.getAttribute('data-target') !== null ) {
			target = this.element.getAttribute('data-target');
		}

		if ( target === '_blank' ) {
			return TARGET_NEW_WINDOW;
		}
		return TARGET_SAME_WINDOW;

	},

	determineRelations: function () {
		if ( this.type === TYPE_ANCHOR ) {
			return this.element.rel;
		}
		if ( this.element.dataset && this.element.dataset.rel ) {
			return this.element.dataset.rel;
		}
		if ( this.element.getAttribute('data-rel') !== null ) {
			return this.element.getAttribute('data-rel');
		}
		return '';
	},

	prepareClassList: function () {

		const cl = classList(this.element);
		const clmv = classListMultipleValues(cl);

		this.classList = {
			add: clmv.add,
			remove: clmv.remove
		};

	},

	setupDom: function () {

		this.classList.add(ELEMENT_CLASS);
		this.classList.add(this.options.elementClass);

		this.element.setAttribute('role', 'link');

		if ( this.type === TYPE_UNFOCUSABLE && this.options.focusUnfocusable ) {
			this.element.setAttribute('tabindex', 0);
		}

	},

	destroyDom: function () {

		this.classList.remove(ELEMENT_CLASS);
		this.classList.remove(this.options.elementClass);

		this.element.removeAttribute('role');

		if ( this.type === TYPE_UNFOCUSABLE && this.options.focusUnfocusable ) {
			this.element.removeAttribute('tabindex');
		}

	},

	setupEvents: function () {

		this.eventListeners = {
			click: ( e ) => {
				if ( this.shouldStopEventPropagation(e) ) {
					e.stopPropagation();
				}
				if (
					this.type === TYPE_ANCHOR &&
					this.target !== TARGET_NEW_WINDOW &&
					isLeftClick(e)
				) {
					e.preventDefault();
				}
				if (
					isLeftClick(e) ||
					isMetaLeftClick(e)
				) {
					this.triggerAction(e);
				}
			},
			mouseup: ( e ) => {
				if ( this.shouldStopEventPropagation(e) ) {
					e.stopPropagation();
				}
				if (
					isMiddleClick(e)
				) {
					if ( this.type === TYPE_ANCHOR ) {
						this.triggerAction(e);
					} else {
						// Fallback
					}
				}
			},
			keyup: ( e ) => {
				if ( this.shouldStopEventPropagation(e) ) {
					e.stopPropagation();
				}
				if (
					isReturnClick(e) ||
					isMetaReturnClick(e)
				) {
					if ( this.type === TYPE_UNFOCUSABLE ) {
						if (
							this.target !== TARGET_NEW_WINDOW &&
							isReturnClick(e)
						) {
							this.triggerAction(e);
						} else {
							// Fallback
						}
					}
				}
			}
		};

		Object.keys(this.eventListeners)
			.forEach(( ev ) => {
				this.element.addEventListener(ev, this.eventListeners[ev], false);
			});

	},

	destroyEvents: function () {

		Object.keys(this.eventListeners)
			.forEach(( ev ) => {
				this.element.removeEventListener(ev, this.eventListeners[ev], false);
			});

	},

	/**
	 * @param  {Event} e
	 *
	 * @return {Boolean}
	 */
	shouldTriggerAction: function ( e ) {

		/**
		 * Don’t trigger action when clicking on anchor
		 * inside non-anchor faux anchor instance
		 */
		if (
			this.type !== TYPE_ANCHOR &&
			closest(e.target, 'a')
		) {
			return false;
		}
		return true;

	},

	/**
	 * @param  {Event} e
	 *
	 * @return {Boolean}
	 */
	shouldStopEventPropagation: function ( e ) {

		/**
		 * Stop event propagation if instance has non-anchor element and
		 * faux anchor instance as parent(s)
		 */
		if (
			!closest(this.element.parentNode, 'a') &&
			closest(this.element.parentNode, ELEMENT_SELECTOR)
		) {
			return true;
		}
		return false;

	},

	/**
	 * @param  {Event} e
	 */
	triggerAction: function ( e ) {

		const target = this.determineTarget(e);

		if ( !this.shouldTriggerAction(e) ) {
			return;
		}

		if ( target === TARGET_NEW_WINDOW ) {
			if ( this.type !== TYPE_ANCHOR ) {
				this.simulateSecondaryAction();
			}
			this.options.onSecondaryAction(e, () => {});
		} else {
			this.options.onPrimaryAction(e, () => {
				this.simulatePrimaryAction();
			});
		}

	},

	simulatePrimaryAction: function () {
		return window.location.assign(this.href);
	},

	simulateSecondaryAction: function () {
		const w = window.open(this.href, '_blank');
		if (
			w &&
			this.rel !== '' &&
			/noopener/.test(this.rel)
		) {
			w.opener = null;
		}
		return w;
	},

	destroy: function () {
		this.destroyDom();
		this.destroyEvents();
	}

});

module.exports = ( element, options ) => {
	const instance = new FauxAnchor(element, options);
	return {
		destroy: () => {
			instance.destroy();
		}
	};
};

module.exports.defaultOptions = FauxAnchor.prototype.options;
module.exports.FauxAnchor = FauxAnchor;
<|endoftext|>


<commit_before>'use strict';

var fs          = require('fs'),
    path        = require('path'),
    Promise     = require('bluebird'),
    util        = require('util'),
    gcloud      = require('gcloud'),
    errors      = require('../../core/server/errors'),
    utils       = require('../../core/server/utils'),
    baseStore   = require('../../core/server/storage/base'),
    options     = {},
    bucket;

function GStore(config) {
    options = config || {};

    var gcs = gcloud.storage({
        projectId: options.projectId,
        keyFilename: options.key
    });
    bucket = gcs.bucket(options.bucket);

}

util.inherits(GStore, baseStore);

GStore.prototype.save = function(image) {
    var _self = this;
    if (!options) return Promise.reject('google cloud storage is not configured');

    var targetDir = _self.getTargetDir(),
    googleStoragePath = 'https://' + options.bucket + '.storage.googleapis.com/',
    targetFilename;

    return this.getUniqueFileName(this, image, targetDir).then(function (filename) {
        targetFilename = filename
        var opts = {
            destination: targetDir + targetFilename
        };
        return new Promise(function(resolve, reject) {
            bucket.upload(image.path, opts, function(err, file) {
                if(err) {
                    reject(err);
                    return;
                }
                resolve(file);
                return;
            });
        })
    }).then(function(file){
        return new Promise(function(resolve, reject) {
            file.makePublic(function(err, apiResponse) {
                if(err) {
                    reject(err);
                    return;
                }
                resolve();
                return;
            });
        })
    }).then(function () {
        return googleStoragePath + targetDir + targetFilename;
    }).catch(function (e) {
        errors.logError(e);
        return Promise.reject(e);
    });

};

// middleware for serving the files
GStore.prototype.serve = function() {
    // a no-op, these are absolute URLs
    return function (req, res, next) {
      next();
    };
};

GStore.prototype.exists = function (filename) {
  return new Promise(function (resolve) {
    fs.exists(filename, function (exists) {
      resolve(exists);
    });
  });
};

module.exports = GStore;<commit_msg>fix(delete): add delete method and super call to support Ghost 0.10.0<commit_after>'use strict';

var fs          = require('fs'),
    path        = require('path'),
    Promise     = require('bluebird'),
    util        = require('util'),
    gcloud      = require('gcloud'),
    errors      = require('../../core/server/errors'),
    utils       = require('../../core/server/utils'),
    baseStore   = require('../../core/server/storage/base'),
    options     = {},
    bucket;

function GStore(config) {
    baseStore.call(this);
    options = config || {};

    var gcs = gcloud.storage({
        projectId: options.projectId,
        keyFilename: options.key
    });
    bucket = gcs.bucket(options.bucket);

}

util.inherits(GStore, baseStore);

GStore.prototype.save = function(image) {
    var _self = this;
    if (!options) return Promise.reject('google cloud storage is not configured');

    var targetDir = _self.getTargetDir(),
    googleStoragePath = 'https://' + options.bucket + '.storage.googleapis.com/',
    targetFilename;

    return this.getUniqueFileName(this, image, targetDir).then(function (filename) {
        targetFilename = filename
        var opts = {
            destination: targetDir + targetFilename
        };
        return new Promise(function(resolve, reject) {
            bucket.upload(image.path, opts, function(err, file) {
                if(err) {
                    reject(err);
                    return;
                }
                resolve(file);
                return;
            });
        })
    }).then(function(file){
        return new Promise(function(resolve, reject) {
            file.makePublic(function(err, apiResponse) {
                if(err) {
                    reject(err);
                    return;
                }
                resolve();
                return;
            });
        })
    }).then(function () {
        return googleStoragePath + targetDir + targetFilename;
    }).catch(function (e) {
        errors.logError(e);
        return Promise.reject(e);
    });

};

// middleware for serving the files
GStore.prototype.serve = function() {
    // a no-op, these are absolute URLs
    return function (req, res, next) {
      next();
    };
};

GStore.prototype.exists = function (filename) {
  return new Promise(function (resolve) {
    fs.exists(filename, function (exists) {
      resolve(exists);
    });
  });
};

GStore.prototype.delete = function(filename) {
  return new Promise(function (resolve, reject) {
    var file = this.bucket.file(filename);
    file.delete(function(err, apiResponse) {
      if (err) { return reject(err); }
      resolve(apiResponse);
    });
  });
};

module.exports = GStore;
<|endoftext|>