<commit_before>var fs = require('fs')
var polyfills = require('./polyfills.js')
var legacy = require('./legacy-streams.js')
var clone = require('./clone.js')

var queue = []

var util = require('util')

function noop () {}

var debug = noop
if (util.debuglog)
  debug = util.debuglog('gfs4')
else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
  debug = function() {
    var m = util.format.apply(util, arguments)
    m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ')
    console.error(m)
  }

if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
  process.on('exit', function() {
    debug(queue)
    require('assert').equal(queue.length, 0)
  })
}

module.exports = patch(clone(fs))
if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
    module.exports = patch(fs)
    fs.__patched = true;
}

// Always patch fs.close/closeSync, because we want to
// retry() whenever a close happens *anywhere* in the program.
// This is essential when multiple graceful-fs instances are
// in play at the same time.
module.exports.close = (function (fs$close) { return function (fd, cb) {
  return fs$close.call(fs, fd, function (err) {
    if (!err)
      retry()

    if (typeof cb === 'function')
      cb.apply(this, arguments)
  })
}})(fs.close)

module.exports.closeSync = (function (fs$closeSync) { return function (fd) {
  // Note that graceful-fs also retries when fs.closeSync() fails.
  // Looks like a bug to me, although it's probably a harmless one.
  var rval = fs$closeSync.apply(fs, arguments)
  retry()
  return rval
}})(fs.closeSync)

// Only patch fs once, otherwise we'll run into a memory leak if
// graceful-fs is loaded multiple times, such as in test environments that
// reset the loaded modules between tests.
// We look for the string `graceful-fs` from the comment above. This
// way we are not adding any extra properties and it will detect if older
// versions of graceful-fs are installed.
if (!fs.closeSync.toString().includes('graceful-fs')) {
  fs.closeSync = module.exports.closeSync;
  fs.close = module.exports.close;
}

function patch (fs) {
  // Everything that references the open() function needs to be in here
  polyfills(fs)
  fs.gracefulify = patch
  fs.FileReadStream = ReadStream;  // Legacy name.
  fs.FileWriteStream = WriteStream;  // Legacy name.
  fs.createReadStream = createReadStream
  fs.createWriteStream = createWriteStream
  var fs$readFile = fs.readFile
  fs.readFile = readFile
  function readFile (path, options, cb) {
    if (typeof options === 'function')
      cb = options, options = null

    return go$readFile(path, options, cb)

    function go$readFile (path, options, cb) {
      return fs$readFile(path, options, function (err) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$readFile, [path, options, cb]])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
          retry()
        }
      })
    }
  }

  var fs$writeFile = fs.writeFile
  fs.writeFile = writeFile
  function writeFile (path, data, options, cb) {
    if (typeof options === 'function')
      cb = options, options = null

    return go$writeFile(path, data, options, cb)

    function go$writeFile (path, data, options, cb) {
      return fs$writeFile(path, data, options, function (err) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$writeFile, [path, data, options, cb]])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
          retry()
        }
      })
    }
  }

  var fs$appendFile = fs.appendFile
  if (fs$appendFile)
    fs.appendFile = appendFile
  function appendFile (path, data, options, cb) {
    if (typeof options === 'function')
      cb = options, options = null

    return go$appendFile(path, data, options, cb)

    function go$appendFile (path, data, options, cb) {
      return fs$appendFile(path, data, options, function (err) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$appendFile, [path, data, options, cb]])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
          retry()
        }
      })
    }
  }

  var fs$readdir = fs.readdir
  fs.readdir = readdir
  function readdir (path, options, cb) {
    var args = [path]
    if (typeof options !== 'function') {
      args.push(options)
    } else {
      cb = options
    }
    args.push(go$readdir$cb)

    return go$readdir(args)

    function go$readdir$cb (err, files) {
      if (files && files.sort)
        files.sort()

      if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
        enqueue([go$readdir, [args]])

      else {
        if (typeof cb === 'function')
          cb.apply(this, arguments)
        retry()
      }
    }
  }

  function go$readdir (args) {
    return fs$readdir.apply(fs, args)
  }

  if (process.version.substr(0, 4) === 'v0.8') {
    var legStreams = legacy(fs)
    ReadStream = legStreams.ReadStream
    WriteStream = legStreams.WriteStream
  }

  var fs$ReadStream = fs.ReadStream
  if (fs$ReadStream) {
    ReadStream.prototype = Object.create(fs$ReadStream.prototype)
    ReadStream.prototype.open = ReadStream$open
  }

  var fs$WriteStream = fs.WriteStream
  if (fs$WriteStream) {
    WriteStream.prototype = Object.create(fs$WriteStream.prototype)
    WriteStream.prototype.open = WriteStream$open
  }

  fs.ReadStream = ReadStream
  fs.WriteStream = WriteStream

  function ReadStream (path, options) {
    if (this instanceof ReadStream)
      return fs$ReadStream.apply(this, arguments), this
    else
      return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
  }

  function ReadStream$open () {
    var that = this
    open(that.path, that.flags, that.mode, function (err, fd) {
      if (err) {
        if (that.autoClose)
          that.destroy()

        that.emit('error', err)
      } else {
        that.fd = fd
        that.emit('open', fd)
        that.read()
      }
    })
  }

  function WriteStream (path, options) {
    if (this instanceof WriteStream)
      return fs$WriteStream.apply(this, arguments), this
    else
      return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
  }

  function WriteStream$open () {
    var that = this
    open(that.path, that.flags, that.mode, function (err, fd) {
      if (err) {
        that.destroy()
        that.emit('error', err)
      } else {
        that.fd = fd
        that.emit('open', fd)
      }
    })
  }

  function createReadStream (path, options) {
    return new ReadStream(path, options)
  }

  function createWriteStream (path, options) {
    return new WriteStream(path, options)
  }

  var fs$open = fs.open
  fs.open = open
  function open (path, flags, mode, cb) {
    if (typeof mode === 'function')
      cb = mode, mode = null

    return go$open(path, flags, mode, cb)

    function go$open (path, flags, mode, cb) {
      return fs$open(path, flags, mode, function (err, fd) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$open, [path, flags, mode, cb]])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
          retry()
        }
      })
    }
  }

  return fs
}

function enqueue (elem) {
  debug('ENQUEUE', elem[0].name, elem[1])
  queue.push(elem)
}

function retry () {
  var elem = queue.shift()
  if (elem) {
    debug('RETRY', elem[0].name, elem[1])
    elem[0].apply(null, elem[1])
  }
}
<commit_msg>Use regexp instead of String.includes<commit_after>var fs = require('fs')
var polyfills = require('./polyfills.js')
var legacy = require('./legacy-streams.js')
var clone = require('./clone.js')

var queue = []

var util = require('util')

function noop () {}

var debug = noop
if (util.debuglog)
  debug = util.debuglog('gfs4')
else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
  debug = function() {
    var m = util.format.apply(util, arguments)
    m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ')
    console.error(m)
  }

if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
  process.on('exit', function() {
    debug(queue)
    require('assert').equal(queue.length, 0)
  })
}

module.exports = patch(clone(fs))
if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
    module.exports = patch(fs)
    fs.__patched = true;
}

// Always patch fs.close/closeSync, because we want to
// retry() whenever a close happens *anywhere* in the program.
// This is essential when multiple graceful-fs instances are
// in play at the same time.
module.exports.close = (function (fs$close) { return function (fd, cb) {
  return fs$close.call(fs, fd, function (err) {
    if (!err)
      retry()

    if (typeof cb === 'function')
      cb.apply(this, arguments)
  })
}})(fs.close)

module.exports.closeSync = (function (fs$closeSync) { return function (fd) {
  // Note that graceful-fs also retries when fs.closeSync() fails.
  // Looks like a bug to me, although it's probably a harmless one.
  var rval = fs$closeSync.apply(fs, arguments)
  retry()
  return rval
}})(fs.closeSync)

// Only patch fs once, otherwise we'll run into a memory leak if
// graceful-fs is loaded multiple times, such as in test environments that
// reset the loaded modules between tests.
// We look for the string `graceful-fs` from the comment above. This
// way we are not adding any extra properties and it will detect if older
// versions of graceful-fs are installed.
if (!/\bgraceful-fs\b/.test(fs.closeSync.toString())) {
  fs.closeSync = module.exports.closeSync;
  fs.close = module.exports.close;
}

function patch (fs) {
  // Everything that references the open() function needs to be in here
  polyfills(fs)
  fs.gracefulify = patch
  fs.FileReadStream = ReadStream;  // Legacy name.
  fs.FileWriteStream = WriteStream;  // Legacy name.
  fs.createReadStream = createReadStream
  fs.createWriteStream = createWriteStream
  var fs$readFile = fs.readFile
  fs.readFile = readFile
  function readFile (path, options, cb) {
    if (typeof options === 'function')
      cb = options, options = null

    return go$readFile(path, options, cb)

    function go$readFile (path, options, cb) {
      return fs$readFile(path, options, function (err) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$readFile, [path, options, cb]])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
          retry()
        }
      })
    }
  }

  var fs$writeFile = fs.writeFile
  fs.writeFile = writeFile
  function writeFile (path, data, options, cb) {
    if (typeof options === 'function')
      cb = options, options = null

    return go$writeFile(path, data, options, cb)

    function go$writeFile (path, data, options, cb) {
      return fs$writeFile(path, data, options, function (err) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$writeFile, [path, data, options, cb]])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
          retry()
        }
      })
    }
  }

  var fs$appendFile = fs.appendFile
  if (fs$appendFile)
    fs.appendFile = appendFile
  function appendFile (path, data, options, cb) {
    if (typeof options === 'function')
      cb = options, options = null

    return go$appendFile(path, data, options, cb)

    function go$appendFile (path, data, options, cb) {
      return fs$appendFile(path, data, options, function (err) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$appendFile, [path, data, options, cb]])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
          retry()
        }
      })
    }
  }

  var fs$readdir = fs.readdir
  fs.readdir = readdir
  function readdir (path, options, cb) {
    var args = [path]
    if (typeof options !== 'function') {
      args.push(options)
    } else {
      cb = options
    }
    args.push(go$readdir$cb)

    return go$readdir(args)

    function go$readdir$cb (err, files) {
      if (files && files.sort)
        files.sort()

      if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
        enqueue([go$readdir, [args]])

      else {
        if (typeof cb === 'function')
          cb.apply(this, arguments)
        retry()
      }
    }
  }

  function go$readdir (args) {
    return fs$readdir.apply(fs, args)
  }

  if (process.version.substr(0, 4) === 'v0.8') {
    var legStreams = legacy(fs)
    ReadStream = legStreams.ReadStream
    WriteStream = legStreams.WriteStream
  }

  var fs$ReadStream = fs.ReadStream
  if (fs$ReadStream) {
    ReadStream.prototype = Object.create(fs$ReadStream.prototype)
    ReadStream.prototype.open = ReadStream$open
  }

  var fs$WriteStream = fs.WriteStream
  if (fs$WriteStream) {
    WriteStream.prototype = Object.create(fs$WriteStream.prototype)
    WriteStream.prototype.open = WriteStream$open
  }

  fs.ReadStream = ReadStream
  fs.WriteStream = WriteStream

  function ReadStream (path, options) {
    if (this instanceof ReadStream)
      return fs$ReadStream.apply(this, arguments), this
    else
      return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
  }

  function ReadStream$open () {
    var that = this
    open(that.path, that.flags, that.mode, function (err, fd) {
      if (err) {
        if (that.autoClose)
          that.destroy()

        that.emit('error', err)
      } else {
        that.fd = fd
        that.emit('open', fd)
        that.read()
      }
    })
  }

  function WriteStream (path, options) {
    if (this instanceof WriteStream)
      return fs$WriteStream.apply(this, arguments), this
    else
      return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
  }

  function WriteStream$open () {
    var that = this
    open(that.path, that.flags, that.mode, function (err, fd) {
      if (err) {
        that.destroy()
        that.emit('error', err)
      } else {
        that.fd = fd
        that.emit('open', fd)
      }
    })
  }

  function createReadStream (path, options) {
    return new ReadStream(path, options)
  }

  function createWriteStream (path, options) {
    return new WriteStream(path, options)
  }

  var fs$open = fs.open
  fs.open = open
  function open (path, flags, mode, cb) {
    if (typeof mode === 'function')
      cb = mode, mode = null

    return go$open(path, flags, mode, cb)

    function go$open (path, flags, mode, cb) {
      return fs$open(path, flags, mode, function (err, fd) {
        if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
          enqueue([go$open, [path, flags, mode, cb]])
        else {
          if (typeof cb === 'function')
            cb.apply(this, arguments)
          retry()
        }
      })
    }
  }

  return fs
}

function enqueue (elem) {
  debug('ENQUEUE', elem[0].name, elem[1])
  queue.push(elem)
}

function retry () {
  var elem = queue.shift()
  if (elem) {
    debug('RETRY', elem[0].name, elem[1])
    elem[0].apply(null, elem[1])
  }
}
<|endoftext|>


<commit_before>var _ = require('lodash');
var express = require('express');
var fs = require('fs');
var grappling = require('grappling-hook');
var path = require('path');
var utils = require('keystone-utils');

/**
 * Don't use process.cwd() as it breaks module encapsulation
 * Instead, let's use module.parent if it's present, or the module itself if there is no parent (probably testing keystone directly if that's the case)
 * This way, the consuming app/module can be an embedded node_module and path resolutions will still work
 * (process.cwd() breaks module encapsulation if the consuming app/module is itself a node_module)
 */
var moduleRoot = (function (_rootPath) {
	var parts = _rootPath.split(path.sep);
	parts.pop(); // get rid of /node_modules from the end of the path
	return parts.join(path.sep);
})(module.parent ? module.parent.paths[0] : module.paths[0]);

/**
 * Keystone Class
 */
var Keystone = function () {
	grappling.mixin(this).allowHooks('pre:static', 'pre:bodyparser', 'pre:session', 'pre:logger', 'pre:admin', 'pre:routes', 'pre:render', 'updates', 'signin', 'signout');
	this.lists = {};
	this.fieldTypes = {};
	this.paths = {};
	this._options = {
		'name': 'Keystone',
		'brand': 'Keystone',
		'admin path': 'keystone',
		'compress': true,
		'headless': false,
		'logger': ':method :url :status :response-time ms',
		'auto update': false,
		'model prefix': null,
		'module root': moduleRoot,
		'frame guard': 'sameorigin',
	};
	this._redirects = {};

	// expose express
	this.express = express;

	// init environment defaults
	this.set('env', process.env.NODE_ENV || 'development');

	this.set('port', process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || '3000');
	this.set('host', process.env.HOST || process.env.IP || process.env.OPENSHIFT_NODEJS_IP) || '0.0.0.0';
	this.set('listen', process.env.LISTEN);

	this.set('ssl', process.env.SSL);
	this.set('ssl port', process.env.SSL_PORT || '3001');
	this.set('ssl host', process.env.SSL_HOST || process.env.SSL_IP);
	this.set('ssl key', process.env.SSL_KEY);
	this.set('ssl cert', process.env.SSL_CERT);

	this.set('cookie secret', process.env.COOKIE_SECRET);
	this.set('cookie signin', (this.get('env') === 'development') ? true : false);

	this.set('embedly api key', process.env.EMBEDLY_API_KEY || process.env.EMBEDLY_APIKEY);
	this.set('mandrill api key', process.env.MANDRILL_API_KEY || process.env.MANDRILL_APIKEY);
	this.set('mandrill username', process.env.MANDRILL_USERNAME);
	this.set('google api key', process.env.GOOGLE_BROWSER_KEY);
	this.set('google server api key', process.env.GOOGLE_SERVER_KEY);
	this.set('ga property', process.env.GA_PROPERTY);
	this.set('ga domain', process.env.GA_DOMAIN);
	this.set('chartbeat property', process.env.CHARTBEAT_PROPERTY);
	this.set('chartbeat domain', process.env.CHARTBEAT_DOMAIN);
	this.set('allowed ip ranges', process.env.ALLOWED_IP_RANGES);

	if (process.env.S3_BUCKET && process.env.S3_KEY && process.env.S3_SECRET) {
		this.set('s3 config', { bucket: process.env.S3_BUCKET, key: process.env.S3_KEY, secret: process.env.S3_SECRET, region: process.env.S3_REGION });
	}

	if (process.env.AZURE_STORAGE_ACCOUNT && process.env.AZURE_STORAGE_ACCESS_KEY) {
		this.set('azurefile config', { account: process.env.AZURE_STORAGE_ACCOUNT, key: process.env.AZURE_STORAGE_ACCESS_KEY });
	}

	if (process.env.CLOUDINARY_URL) {
		// process.env.CLOUDINARY_URL is processed by the cloudinary package when this is set
		this.set('cloudinary config', true);
	}

	// init mongoose
	this.set('mongoose', require('mongoose'));
	this.mongoose.Promise = require('es6-promise').Promise;

	// Attach middleware packages, bound to this instance
	this.middleware = {
		api: require('./lib/middleware/api')(this),
		cors: require('./lib/middleware/cors')(this),
	};
};

_.extend(Keystone.prototype, require('./lib/core/options'));

Keystone.prototype.prefixModel = function (key) {
	var modelPrefix = this.get('model prefix');

	if (modelPrefix) {
		key = modelPrefix + '_' + key;
	}

	return require('mongoose/lib/utils').toCollectionName(key);
};

/* Attach core functionality to Keystone.prototype */
Keystone.prototype.createItems = require('./lib/core/createItems');
Keystone.prototype.createRouter = require('./lib/core/createRouter');
Keystone.prototype.getOrphanedLists = require('./lib/core/getOrphanedLists');
Keystone.prototype.importer = require('./lib/core/importer');
Keystone.prototype.init = require('./lib/core/init');
Keystone.prototype.initDatabaseConfig = require('./lib/core/initDatabaseConfig');
Keystone.prototype.initExpressApp = require('./lib/core/initExpressApp');
Keystone.prototype.initExpressSession = require('./lib/core/initExpressSession');
Keystone.prototype.initNav = require('./lib/core/initNav');
Keystone.prototype.list = require('./lib/core/list');
Keystone.prototype.openDatabaseConnection = require('./lib/core/openDatabaseConnection');
Keystone.prototype.closeDatabaseConnection = require('./lib/core/closeDatabaseConnection');
Keystone.prototype.populateRelated = require('./lib/core/populateRelated');
Keystone.prototype.redirect = require('./lib/core/redirect');
Keystone.prototype.start = require('./lib/core/start');
Keystone.prototype.wrapHTMLError = require('./lib/core/wrapHTMLError');

/* Deprecation / Change warnings for 0.4 */
Keystone.prototype.routes = function () {
	throw new Error('keystone.routes(fn) has been removed, use keystone.set(\'routes\', fn)');
};

/**
 * The exports object is an instance of Keystone.
 */
var keystone = module.exports = new Keystone();

/*
	Note: until #1777 is complete, the order of execution here with the requires
	(specifically, they happen _after_ the module.exports above) is really
	important. As soon as the circular dependencies are sorted out to get their
	keystone instance from a closure or reference on {this} we can move these
	bindings into the Keystone constructor.
*/

// Expose modules and Classes
keystone.Admin = {
	Server: require('./admin/server'),
};
keystone.Email = require('./lib/email');
keystone.Field = require('./fields/types/Type');
keystone.Field.Types = require('./lib/fieldTypes');
keystone.Keystone = Keystone;
keystone.List = require('./lib/list')(keystone);
keystone.Storage = require('./lib/storage');
keystone.View = require('./lib/view');

keystone.content = require('./lib/content');
keystone.security = {
	csrf: require('./lib/security/csrf'),
};
keystone.utils = utils;

/**
 * returns all .js modules (recursively) in the path specified, relative
 * to the module root (where the keystone project is being consumed from).
 *
 * ####Example:
 *     var models = keystone.import('models');
 */

Keystone.prototype.import = function (dirname) {

	var initialPath = path.join(this.get('module root'), dirname);

	var doImport = function (fromPath) {

		var imported = {};

		fs.readdirSync(fromPath).forEach(function (name) {

			var fsPath = path.join(fromPath, name);
			var info = fs.statSync(fsPath);

			// recur
			if (info.isDirectory()) {
				imported[name] = doImport(fsPath);
			} else {
				// only import files that we can `require`
				var ext = path.extname(name);
				var base = path.basename(name, ext);
				if (require.extensions[ext]) {
					imported[base] = require(fsPath);
				}
			}

		});

		return imported;
	};

	return doImport(initialPath);
};

/**
 * Applies Application updates
 */

Keystone.prototype.applyUpdates = function (callback) {
	var self = this;
	self.callHook('pre:updates', function (err) {
		if (err) return callback(err);
		require('./lib/updates').apply(function (err) {
			if (err) return callback(err);
			self.callHook('post:updates', callback);
		});
	});
};

/**
 * Logs a configuration error to the console
 */

Keystone.prototype.console = {};
Keystone.prototype.console.err = function (type, msg) {
	if (keystone.get('logger')) {
		var dashes = '\n------------------------------------------------\n';
		console.log(dashes + 'KeystoneJS: ' + type + ':\n\n' + msg + dashes);
	}
};

/**
 * Keystone version
 */

keystone.version = require('./package.json').version;

// Expose Modules
keystone.session = require('./lib/session');
<commit_msg>Fixes issue where host is undefined<commit_after>var _ = require('lodash');
var express = require('express');
var fs = require('fs');
var grappling = require('grappling-hook');
var path = require('path');
var utils = require('keystone-utils');

/**
 * Don't use process.cwd() as it breaks module encapsulation
 * Instead, let's use module.parent if it's present, or the module itself if there is no parent (probably testing keystone directly if that's the case)
 * This way, the consuming app/module can be an embedded node_module and path resolutions will still work
 * (process.cwd() breaks module encapsulation if the consuming app/module is itself a node_module)
 */
var moduleRoot = (function (_rootPath) {
	var parts = _rootPath.split(path.sep);
	parts.pop(); // get rid of /node_modules from the end of the path
	return parts.join(path.sep);
})(module.parent ? module.parent.paths[0] : module.paths[0]);

/**
 * Keystone Class
 */
var Keystone = function () {
	grappling.mixin(this).allowHooks('pre:static', 'pre:bodyparser', 'pre:session', 'pre:logger', 'pre:admin', 'pre:routes', 'pre:render', 'updates', 'signin', 'signout');
	this.lists = {};
	this.fieldTypes = {};
	this.paths = {};
	this._options = {
		'name': 'Keystone',
		'brand': 'Keystone',
		'admin path': 'keystone',
		'compress': true,
		'headless': false,
		'logger': ':method :url :status :response-time ms',
		'auto update': false,
		'model prefix': null,
		'module root': moduleRoot,
		'frame guard': 'sameorigin',
	};
	this._redirects = {};

	// expose express
	this.express = express;

	// init environment defaults
	this.set('env', process.env.NODE_ENV || 'development');

	this.set('port', process.env.PORT || process.env.OPENSHIFT_NODEJS_PORT || '3000');
	this.set('host', process.env.HOST || process.env.IP || process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0');
	this.set('listen', process.env.LISTEN);

	this.set('ssl', process.env.SSL);
	this.set('ssl port', process.env.SSL_PORT || '3001');
	this.set('ssl host', process.env.SSL_HOST || process.env.SSL_IP);
	this.set('ssl key', process.env.SSL_KEY);
	this.set('ssl cert', process.env.SSL_CERT);

	this.set('cookie secret', process.env.COOKIE_SECRET);
	this.set('cookie signin', (this.get('env') === 'development') ? true : false);

	this.set('embedly api key', process.env.EMBEDLY_API_KEY || process.env.EMBEDLY_APIKEY);
	this.set('mandrill api key', process.env.MANDRILL_API_KEY || process.env.MANDRILL_APIKEY);
	this.set('mandrill username', process.env.MANDRILL_USERNAME);
	this.set('google api key', process.env.GOOGLE_BROWSER_KEY);
	this.set('google server api key', process.env.GOOGLE_SERVER_KEY);
	this.set('ga property', process.env.GA_PROPERTY);
	this.set('ga domain', process.env.GA_DOMAIN);
	this.set('chartbeat property', process.env.CHARTBEAT_PROPERTY);
	this.set('chartbeat domain', process.env.CHARTBEAT_DOMAIN);
	this.set('allowed ip ranges', process.env.ALLOWED_IP_RANGES);

	if (process.env.S3_BUCKET && process.env.S3_KEY && process.env.S3_SECRET) {
		this.set('s3 config', { bucket: process.env.S3_BUCKET, key: process.env.S3_KEY, secret: process.env.S3_SECRET, region: process.env.S3_REGION });
	}

	if (process.env.AZURE_STORAGE_ACCOUNT && process.env.AZURE_STORAGE_ACCESS_KEY) {
		this.set('azurefile config', { account: process.env.AZURE_STORAGE_ACCOUNT, key: process.env.AZURE_STORAGE_ACCESS_KEY });
	}

	if (process.env.CLOUDINARY_URL) {
		// process.env.CLOUDINARY_URL is processed by the cloudinary package when this is set
		this.set('cloudinary config', true);
	}

	// init mongoose
	this.set('mongoose', require('mongoose'));
	this.mongoose.Promise = require('es6-promise').Promise;

	// Attach middleware packages, bound to this instance
	this.middleware = {
		api: require('./lib/middleware/api')(this),
		cors: require('./lib/middleware/cors')(this),
	};
};

_.extend(Keystone.prototype, require('./lib/core/options'));

Keystone.prototype.prefixModel = function (key) {
	var modelPrefix = this.get('model prefix');

	if (modelPrefix) {
		key = modelPrefix + '_' + key;
	}

	return require('mongoose/lib/utils').toCollectionName(key);
};

/* Attach core functionality to Keystone.prototype */
Keystone.prototype.createItems = require('./lib/core/createItems');
Keystone.prototype.createRouter = require('./lib/core/createRouter');
Keystone.prototype.getOrphanedLists = require('./lib/core/getOrphanedLists');
Keystone.prototype.importer = require('./lib/core/importer');
Keystone.prototype.init = require('./lib/core/init');
Keystone.prototype.initDatabaseConfig = require('./lib/core/initDatabaseConfig');
Keystone.prototype.initExpressApp = require('./lib/core/initExpressApp');
Keystone.prototype.initExpressSession = require('./lib/core/initExpressSession');
Keystone.prototype.initNav = require('./lib/core/initNav');
Keystone.prototype.list = require('./lib/core/list');
Keystone.prototype.openDatabaseConnection = require('./lib/core/openDatabaseConnection');
Keystone.prototype.closeDatabaseConnection = require('./lib/core/closeDatabaseConnection');
Keystone.prototype.populateRelated = require('./lib/core/populateRelated');
Keystone.prototype.redirect = require('./lib/core/redirect');
Keystone.prototype.start = require('./lib/core/start');
Keystone.prototype.wrapHTMLError = require('./lib/core/wrapHTMLError');

/* Deprecation / Change warnings for 0.4 */
Keystone.prototype.routes = function () {
	throw new Error('keystone.routes(fn) has been removed, use keystone.set(\'routes\', fn)');
};

/**
 * The exports object is an instance of Keystone.
 */
var keystone = module.exports = new Keystone();

/*
	Note: until #1777 is complete, the order of execution here with the requires
	(specifically, they happen _after_ the module.exports above) is really
	important. As soon as the circular dependencies are sorted out to get their
	keystone instance from a closure or reference on {this} we can move these
	bindings into the Keystone constructor.
*/

// Expose modules and Classes
keystone.Admin = {
	Server: require('./admin/server'),
};
keystone.Email = require('./lib/email');
keystone.Field = require('./fields/types/Type');
keystone.Field.Types = require('./lib/fieldTypes');
keystone.Keystone = Keystone;
keystone.List = require('./lib/list')(keystone);
keystone.Storage = require('./lib/storage');
keystone.View = require('./lib/view');

keystone.content = require('./lib/content');
keystone.security = {
	csrf: require('./lib/security/csrf'),
};
keystone.utils = utils;

/**
 * returns all .js modules (recursively) in the path specified, relative
 * to the module root (where the keystone project is being consumed from).
 *
 * ####Example:
 *     var models = keystone.import('models');
 */

Keystone.prototype.import = function (dirname) {

	var initialPath = path.join(this.get('module root'), dirname);

	var doImport = function (fromPath) {

		var imported = {};

		fs.readdirSync(fromPath).forEach(function (name) {

			var fsPath = path.join(fromPath, name);
			var info = fs.statSync(fsPath);

			// recur
			if (info.isDirectory()) {
				imported[name] = doImport(fsPath);
			} else {
				// only import files that we can `require`
				var ext = path.extname(name);
				var base = path.basename(name, ext);
				if (require.extensions[ext]) {
					imported[base] = require(fsPath);
				}
			}

		});

		return imported;
	};

	return doImport(initialPath);
};

/**
 * Applies Application updates
 */

Keystone.prototype.applyUpdates = function (callback) {
	var self = this;
	self.callHook('pre:updates', function (err) {
		if (err) return callback(err);
		require('./lib/updates').apply(function (err) {
			if (err) return callback(err);
			self.callHook('post:updates', callback);
		});
	});
};

/**
 * Logs a configuration error to the console
 */

Keystone.prototype.console = {};
Keystone.prototype.console.err = function (type, msg) {
	if (keystone.get('logger')) {
		var dashes = '\n------------------------------------------------\n';
		console.log(dashes + 'KeystoneJS: ' + type + ':\n\n' + msg + dashes);
	}
};

/**
 * Keystone version
 */

keystone.version = require('./package.json').version;

// Expose Modules
keystone.session = require('./lib/session');
<|endoftext|>


<commit_before>// ==UserScript==
// @name        GM WinterIndieFest KeyGraber
// @namespace   gameminer.ru
// @description key graber for winter indi fest
// @version     2.1
// @grant       none
// @require	http://static.gameminer.ru/static/js/jquery-1.7.1.min.js
// @include     http://event.gameminer.ru/*
// ==/UserScript==
$(document).ready(function() {
    var time = $('div.event-head-keyttl').html();
    if ($('.event-head-keys__chance').length > 0) {
        console.log('Form found! Try submit...');
        $('form').submit();
    } else {
        console.log('Not found! Time left: ' + time);
        setTimeout(function() {
            location.reload();
        }, 60000);
    }
});
<commit_msg>outdated<commit_after><|endoftext|>


<commit_before>var through = require('through')

module.exports = function BlkDatStream() {
  var buffers = []
  var buffer = new Buffer(0)
  var remaining = 0
  var needed = 0

  return through(function write(data) {
    remaining += data.length
    buffers.push(data)

    // early exit if we have a header, but not enough data
    if (needed !== 0 && remaining < needed) return

    // merge buffers
    buffer = Buffer.concat([buffer].concat(buffers), remaining)
    buffers = []

    var offset = 0

    do {
      // do we need to parse a magic header?
      if (needed === 0) {
        // do we have enough for a magic header?
        if (remaining < 8) break

        // read the magic header (magic number, block length)
        var magicInt = buffer.readUInt32LE(0)
        var blockLength = buffer.readUInt32LE(4)

        if (magicInt !== 0xd9b4bef9) {
          throw new Error('Unexpected data')
        }

        // now, block length is what is needed
        needed = blockLength
        remaining -= 8
        offset = 8

        // and loop
        continue
      }

      // read the block
      var block = buffer.slice(offset, offset + needed)

      // process block
      this.queue(block)

      // update cursor information
      buffer = buffer.slice(offset + needed)
      remaining -= needed
      needed = 0

    // do we [still] have enough data?
    } while (remaining >= needed)

    // truncate Buffer if magic header was read
    if (needed !== 0) {
      buffer = buffer.slice(offset)
      remaining = buffer.length
    }
  })
}
<commit_msg>index: remove offsets<commit_after>var through = require('through')

module.exports = function BlkDatStream() {
  var buffers = []
  var buffer = new Buffer(0)

  var blockLength
  var remaining = 0
  var needed = 0

  return through(function write(data) {
    remaining += data.length
    buffers.push(data)

    // early exit if we have a header, but not enough data
    if (needed !== 0 && remaining < needed) return

    // merge buffers
    buffer = Buffer.concat([buffer].concat(buffers), remaining)
    buffers = []

    do {
      // do we need to parse a magic header?
      if (needed === 0) {
        // do we have enough for a magic header?
        if (remaining < 8) break

        // read the magic header (magic number, block length)
        var magicInt = buffer.readUInt32LE(0)
        blockLength = buffer.readUInt32LE(4)

        if (magicInt !== 0xd9b4bef9) {
          throw new Error('Unexpected data')
        }

        // block length is what is needed further
        // but we don't truncate, so we also need the magic header
        needed = 8 + blockLength

        // and loop
        continue
      }

      // read the block
      var block = buffer.slice(8, blockLength)

      // process block
      this.queue(block)

      // update stream information
      buffer = buffer.slice(needed)
      remaining = buffer.length
      needed = 0

    // do we [still] have enough data?
    } while (remaining >= needed)
  })
}
<|endoftext|>


<commit_before>var path = Npm.require("path");
var fs = Npm.require("fs");
var glob = Npm.require("glob");

// Install bower components into the local meteor directory.
// XXX Should we find a better host?
var bowerHome = ".meteor/local/bower";

log = function (message) {
  return console.log("Bower: ", message);
};

var bowerHandler = function (compileStep, bowerTree) {

  if (! _.isObject(bowerTree))
    compileStep.error({
      message: "Bower list must be a dictionnary in " + compileStep.inputPath
    });

  var bowerDirectory = path.join(path.relative(process.cwd(),
                          path.dirname(compileStep._fullInputPath)), bowerHome);

  // Convert bowerTree object to an array format needed by `Bower.install`:
  //  bower: {
  //    "foo": "1.2.3",
  //    "bar": {
  //      source: "owner/repo"
  //      version: "2.1.2"
  //     }
  //  }
  //  =>
  //  ["foo#1.2.3", "bar=owner/repo#2.1.2"]
  var installList = _.map(bowerTree, function (definition, name) {
    if (_.isString(definition))
      definition = { version: definition };

    if (_.isEmpty(definition.version))
      compileStep.error({
        message: "You must provide a version number for package " + name
      });

    if (_.has(definition, "source"))
      name += "=" + definition.source;

    return name + "#" + definition.version;
  });

  // `localCache` use the same format than `installList`:
  // ["foo#1.2.3", "foo#2.1.2"]
  // If a value is present in `localCache` we remove it from the `installList`
  var localCache = Bower.list(null, {offline: true, directory: bowerDirectory});
  localCache = _.values(localCache.pkgMeta.dependencies);
  installList = _.filter(installList, function (pkg) {
    return localCache.indexOf(pkg) === -1;
  });

  // Installation
  var installedPackages = Bower.install(installList, {save: true},
                                                   {directory: bowerDirectory});
  _.each(installedPackages, function (val, pkgName) {
    log(pkgName + " v" + val.pkgMeta.version + " successfully installed");
  });

  // Loop over packages, look at each `.bower.json` attribute `main` and
  //  add the associated file to the Meteor bundle.
  // XXX If a package is present more than once (potentialy in different
  //  versions from different places), we should only include it once with the
  //  good version. Hopefully the `constraint-solver` package will help.
  _.each(bowerTree, function (options, pkgName) {
    var bowerInfosPath = path.join(bowerDirectory, pkgName, '.bower.json');
    var infos = loadJSONContent(compileStep, fs.readFileSync(bowerInfosPath));

    if (! _.has(infos, "main") && ! options.additionalFiles)
      return;

    if (_.isString(infos.main))
      infos.main = [infos.main];

    toInclude = [];
    if (infos.main)
      toInclude = toInclude.concat(infos.main);
    if (options.additionalFiles) {
      var pkgPath = path.join(bowerDirectory, pkgName);

      _.each(options.additionalFiles, function(pattern) {
        var matches = glob.sync(pattern, { cwd: pkgPath });

        toInclude = toInclude.concat(matches);
      });
    }

    _.each(toInclude, function (fileName) {
      var contentPath = path.join(bowerDirectory, pkgName, fileName);
      var virtualPath = path.join('packages/bower/', pkgName, fileName);
      var content = fs.readFileSync(contentPath);
      var ext = path.extname(fileName).slice(1);

      // XXX It would be cool to be able to add a ressource and let Meteor use
      //  the right source handler.
      if (ext === "js") {
        compileStep.addJavaScript({
          sourcePath: contentPath,
          path: virtualPath,
          data: content.toString('utf8'),
          bare: true
        });
      } else if (ext === "css") {
        compileStep.addStylesheet({
          sourcePath: contentPath,
          path: virtualPath,
          data: content.toString('utf8')
        });
      } else {
        compileStep.addAsset({
          sourcePath: contentPath,
          path: virtualPath,
          data: content
        });
      }
    });
  });
};

/****************/
/* JSON Loaders */
/****************/

var loadJSONContent = function (compileStep, content) {
  try {
    return JSON.parse(content);
  }
  catch (e) {
    compileStep.error({
      message: "Syntax error in " + compileStep.inputPath,
      line: e.line,
      column: e.column
    });
  }
};

var loadJSONFile = function (compileStep) {
  var content = compileStep.read().toString('utf8');
  return loadJSONContent(compileStep, content);
};

/*******************/
/* Source Handlers */
/*******************/

// XXX Hack. If this line is not present `xxx.json` handlers are not called.
//  This is a Meteor bug.
Plugin.registerSourceHandler("json", null);

// We look at the field "bower" of the `smart.json` file.
// XXX Remove when atmosphere is merged in Meteor-core
Plugin.registerSourceHandler("smart.json", function (compileStep) {
  // XXX Code copied from `packages/templating/plugin/compile-template.js:6`
  if (! compileStep.arch.match(/^browser(\.|$)/))
    return;

  var bowerTree = loadJSONFile(compileStep);
  if (! _.has(bowerTree, "bower"))
    return;

  return bowerHandler(compileStep, bowerTree.bower);
});

Plugin.registerSourceHandler("bower.json", function (compileStep) {
  // XXX Code copied from `packages/templating/plugin/compile-template.js:6`
  if (! compileStep.arch.match(/^browser(\.|$)/))
    return;

  var bowerTree = loadJSONFile(compileStep);

  // bower.json files have additional metadata beyond what we care about (dependancies)
  // but previous versions of this package assumed it was a flatter list
  // so allow both
  if (_.has(bowerTree, "dependencies"))
    bowerTree = bowerTree.dependencies;

  return bowerHandler(compileStep, bowerTree);
});
<commit_msg>Allow the additionalFiles option to be a string<commit_after>var path = Npm.require("path");
var fs = Npm.require("fs");
var glob = Npm.require("glob");

// Install bower components into the local meteor directory.
// XXX Should we find a better host?
var bowerHome = ".meteor/local/bower";

log = function (message) {
  return console.log("Bower: ", message);
};

var bowerHandler = function (compileStep, bowerTree) {

  if (! _.isObject(bowerTree))
    compileStep.error({
      message: "Bower list must be a dictionnary in " + compileStep.inputPath
    });

  var bowerDirectory = path.join(path.relative(process.cwd(),
                          path.dirname(compileStep._fullInputPath)), bowerHome);

  // Convert bowerTree object to an array format needed by `Bower.install`:
  //  bower: {
  //    "foo": "1.2.3",
  //    "bar": {
  //      source: "owner/repo"
  //      version: "2.1.2"
  //     }
  //  }
  //  =>
  //  ["foo#1.2.3", "bar=owner/repo#2.1.2"]
  var installList = _.map(bowerTree, function (definition, name) {
    if (_.isString(definition))
      definition = { version: definition };

    if (_.isEmpty(definition.version))
      compileStep.error({
        message: "You must provide a version number for package " + name
      });

    if (_.has(definition, "source"))
      name += "=" + definition.source;

    return name + "#" + definition.version;
  });

  // `localCache` use the same format than `installList`:
  // ["foo#1.2.3", "foo#2.1.2"]
  // If a value is present in `localCache` we remove it from the `installList`
  var localCache = Bower.list(null, {offline: true, directory: bowerDirectory});
  localCache = _.values(localCache.pkgMeta.dependencies);
  installList = _.filter(installList, function (pkg) {
    return localCache.indexOf(pkg) === -1;
  });

  // Installation
  var installedPackages = Bower.install(installList, {save: true},
                                                   {directory: bowerDirectory});
  _.each(installedPackages, function (val, pkgName) {
    log(pkgName + " v" + val.pkgMeta.version + " successfully installed");
  });

  // Loop over packages, look at each `.bower.json` attribute `main` and
  //  add the associated file to the Meteor bundle.
  // XXX If a package is present more than once (potentialy in different
  //  versions from different places), we should only include it once with the
  //  good version. Hopefully the `constraint-solver` package will help.
  _.each(bowerTree, function (options, pkgName) {
    var bowerInfosPath = path.join(bowerDirectory, pkgName, '.bower.json');
    var infos = loadJSONContent(compileStep, fs.readFileSync(bowerInfosPath));

    if (! _.has(infos, "main") && ! options.additionalFiles)
      return;

    if (_.isString(infos.main))
      infos.main = [infos.main];

    toInclude = [];
    if (infos.main)
      toInclude = toInclude.concat(infos.main);
    if (options.additionalFiles) {
      var pkgPath = path.join(bowerDirectory, pkgName);

      if (_.isString(options.additionalFiles))
        options.additionalFiles = [options.additionalFiles];

      var matches = _.map(options.additionalFiles, function(pattern) {
        return glob.sync(pattern, { cwd: pkgPath });
      });

      toInclude = _.uniq(toInclude.concat(_.flatten(matches)));
    }

    _.each(toInclude, function (fileName) {
      var contentPath = path.join(bowerDirectory, pkgName, fileName);
      var virtualPath = path.join('packages/bower/', pkgName, fileName);
      var content = fs.readFileSync(contentPath);
      var ext = path.extname(fileName).slice(1);

      // XXX It would be cool to be able to add a ressource and let Meteor use
      //  the right source handler.
      if (ext === "js") {
        compileStep.addJavaScript({
          sourcePath: contentPath,
          path: virtualPath,
          data: content.toString('utf8'),
          bare: true
        });
      } else if (ext === "css") {
        compileStep.addStylesheet({
          sourcePath: contentPath,
          path: virtualPath,
          data: content.toString('utf8')
        });
      } else {
        compileStep.addAsset({
          sourcePath: contentPath,
          path: virtualPath,
          data: content
        });
      }
    });
  });
};

/****************/
/* JSON Loaders */
/****************/

var loadJSONContent = function (compileStep, content) {
  try {
    return JSON.parse(content);
  }
  catch (e) {
    compileStep.error({
      message: "Syntax error in " + compileStep.inputPath,
      line: e.line,
      column: e.column
    });
  }
};

var loadJSONFile = function (compileStep) {
  var content = compileStep.read().toString('utf8');
  return loadJSONContent(compileStep, content);
};

/*******************/
/* Source Handlers */
/*******************/

// XXX Hack. If this line is not present `xxx.json` handlers are not called.
//  This is a Meteor bug.
Plugin.registerSourceHandler("json", null);

// We look at the field "bower" of the `smart.json` file.
// XXX Remove when atmosphere is merged in Meteor-core
Plugin.registerSourceHandler("smart.json", function (compileStep) {
  // XXX Code copied from `packages/templating/plugin/compile-template.js:6`
  if (! compileStep.arch.match(/^browser(\.|$)/))
    return;

  var bowerTree = loadJSONFile(compileStep);
  if (! _.has(bowerTree, "bower"))
    return;

  return bowerHandler(compileStep, bowerTree.bower);
});

Plugin.registerSourceHandler("bower.json", function (compileStep) {
  // XXX Code copied from `packages/templating/plugin/compile-template.js:6`
  if (! compileStep.arch.match(/^browser(\.|$)/))
    return;

  var bowerTree = loadJSONFile(compileStep);

  // bower.json files have additional metadata beyond what we care about (dependancies)
  // but previous versions of this package assumed it was a flatter list
  // so allow both
  if (_.has(bowerTree, "dependencies"))
    bowerTree = bowerTree.dependencies;

  return bowerHandler(compileStep, bowerTree);
});
<|endoftext|>


<commit_before>'use strict'
const _ = require('lodash')

const publicReadableAttributes = [
  'id',
  'givenName',
  'familyName',
  'timeZone',
  'active',
  'authorisedToBlog'
]
const selfReadableAttributes = [
  'id',
  'givenName',
  'familyName',
  'timeZone',
  'active',
  'authorisedToBlog',
  'emailAddress'
]
const adminReadableAttributes = [
  'id',
  'givenName',
  'familyName',
  'timeZone',
  'active',
  'authorisedToBlog',
  'emailAddress',
  'admin'
]

module.exports = (authUser, trx, queryModifier) => trx
  .from('users')
  .select()
  .modify(queryModifier)

  // Filter the users to restrict the visibility of inactive and incomplete users to admins and the user himself.
  .modify(qb => {
    if (!authUser || !authUser.admin) {
      qb.where(function () {
        if (authUser) {
          this.where('id', authUser.id)
        }
        qb.orWhere(function () {
          this
            .where('active', '=', true)
            .whereNotNull('givenName')
            .whereNotNull('familyName')
        })
      })
    }
  })

  .then(users => users.map(user => {
    let readableAttributes = publicReadableAttributes
    if (authUser) {
      if (authUser.admin) {
        readableAttributes = adminReadableAttributes
      } else if (authUser.id === user.id) {
        readableAttributes = selfReadableAttributes
      }
    }
    return _.pick(user, readableAttributes)
  }))
<commit_msg>Restricted anonymous user search to blogger users.<commit_after>'use strict'
const _ = require('lodash')

const publicReadableAttributes = [
  'id',
  'givenName',
  'familyName',
  'timeZone',
  'active',
  'authorisedToBlog'
]
const selfReadableAttributes = [
  'id',
  'givenName',
  'familyName',
  'timeZone',
  'active',
  'authorisedToBlog',
  'emailAddress'
]
const adminReadableAttributes = [
  'id',
  'givenName',
  'familyName',
  'timeZone',
  'active',
  'authorisedToBlog',
  'emailAddress',
  'admin'
]

module.exports = (authUser, trx, queryModifier) => trx
  .from('users')
  .select()
  .modify(queryModifier)

  // Filter the users to restrict the visibility of inactive and incomplete users to admins and the user himself.
  .modify(qb => {
    if (!authUser || !authUser.admin) {
      qb.where(function () {
        if (authUser) {
          // Show self even if the following filters hide self.
          this.where('id', authUser.id)
        }
        qb.orWhere(function () {
          this
            // Hide inactive.
            .where('active', '=', true)
            // Hide incomplete.
            .whereNotNull('givenName')
            .whereNotNull('familyName')
            // Hide non-bloggers.
            .where('authorisedToBlog', '=', true)
        })
      })
    }
  })

  .then(users => users.map(user => {
    let readableAttributes = publicReadableAttributes
    if (authUser) {
      if (authUser.admin) {
        readableAttributes = adminReadableAttributes
      } else if (authUser.id === user.id) {
        readableAttributes = selfReadableAttributes
      }
    }
    return _.pick(user, readableAttributes)
  }))
<|endoftext|>


<commit_before>/* jslint browser: true */
var createDivs = function ( data ) {
	var body = document.querySelector( '.counter');
	var queues = [
		[ 'best' ],
		[ 'held', 'good', 'music' ],
		[ 'pending' ],
		[ 'bad' ],
		['trash' ]
	];

	var delta = document.createElement( 'div' );
	delta.className = 'delta';
	delta.id = 'delta';
	delta.innerHTML = 'Δ0';
	body.appendChild(delta);

	for ( var i = 0; i < queues.length; i++  ) {
		for ( var j = 0; j < queues[i].length; j++ ) {
			var queue = queues[i][j];
			var div = document.createElement( 'div' );
			if ( queue === 'total' ) {
				continue;
			}

			div.className = 'queue ' + queue;
			div.id = queue;
			div.innerHTML = queue;

			body.appendChild( div );

			if ( j < queues[i].length - 1) {
				var sep = document.createElement( 'span' );
				sep.class = 'sep';
				sep.innerHTML = '&#x21c6'; //'↔';
				body.appendChild( sep );
			}

			if ( queue === 'trash' ) {
				continue;
			}
		}
		var span = document.createElement( 'span' );
		span.className = 'sep';
		if ( i === queue.length ) {
			span.innerHTML = '↓'; // downwards
		} else if ( i === queue.length - 1) {
			continue;
		} else if ( i === 0 ) {
			span.innerHTML = '↑'; // upwards
		} else {
			span.innerHTML = '&#x21f5'; //'↕'; //  updown
		}
		body.appendChild( span );
	}
};
var updateCounts = function ( data ) {
	var div;
	for ( var queue in data.counts ) {
		if ( data.counts.hasOwnProperty( queue ) ) {
			div = document.getElementById( queue );
			if ( !div ) { continue; }
			div.innerHTML = data.counts[queue] + ' ' + queue;
			var size = 0.5 * Math.sqrt(data.counts[queue]) + 'em';
			div.style.height = size;
			div.style.width = size;
			div.style['line-height'] = size;
		}
	}

	div = document.getElementById( 'delta' );
	div.innerHTML = 'Δ' + data.delta;
	if ( data.delta < 0 ) {
		div.className = 'delta negative';
	} else if ( data.delta === 0 ) {
		div.className = 'delta zero';
	} else {
		div.className = 'delta';
	}
	setTimeout(poll, 3000);
};

var getJSON = function(url, callback) {
	// http://stackoverflow.com/a/35970894
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status === 200) {
        callback(null, xhr.response);
      } else {
        callback(status);
      }
    };
    xhr.send();
};

function poll() {
	getJSON('//api.webm.website/stats.json', function ( e, r ) {
		updateCounts( r );
	} );
}

window.onload = function () {
	getJSON('//api.webm.website/stats.json', function ( e, r ) {
		createDivs( r );
		updateCounts( r );
	} );
};
<commit_msg>Fix overlooked good<commit_after>/* jslint browser: true */
var createDivs = function ( data ) {
	var body = document.querySelector( '.counter');
	var queues = [
		[ 'best' ],
		[ 'held', 'decent', 'music' ],
		[ 'pending' ],
		[ 'bad' ],
		['trash' ]
	];

	var delta = document.createElement( 'div' );
	delta.className = 'delta';
	delta.id = 'delta';
	delta.innerHTML = 'Δ0';
	body.appendChild(delta);

	for ( var i = 0; i < queues.length; i++  ) {
		for ( var j = 0; j < queues[i].length; j++ ) {
			var queue = queues[i][j];
			var div = document.createElement( 'div' );
			if ( queue === 'total' ) {
				continue;
			}

			div.className = 'queue ' + queue;
			div.id = queue;
			div.innerHTML = queue;

			body.appendChild( div );

			if ( j < queues[i].length - 1) {
				var sep = document.createElement( 'span' );
				sep.class = 'sep';
				sep.innerHTML = '&#x21c6'; //'↔';
				body.appendChild( sep );
			}

			if ( queue === 'trash' ) {
				continue;
			}
		}
		var span = document.createElement( 'span' );
		span.className = 'sep';
		if ( i === queue.length ) {
			span.innerHTML = '↓'; // downwards
		} else if ( i === queue.length - 1) {
			continue;
		} else if ( i === 0 ) {
			span.innerHTML = '↑'; // upwards
		} else {
			span.innerHTML = '&#x21f5'; //'↕'; //  updown
		}
		body.appendChild( span );
	}
};
var updateCounts = function ( data ) {
	var div;
	for ( var queue in data.counts ) {
		if ( data.counts.hasOwnProperty( queue ) ) {
			div = document.getElementById( queue );
			if ( !div ) { continue; }
			div.innerHTML = data.counts[queue] + ' ' + queue;
			var size = 0.5 * Math.sqrt(data.counts[queue]) + 'em';
			div.style.height = size;
			div.style.width = size;
			div.style['line-height'] = size;
		}
	}

	div = document.getElementById( 'delta' );
	div.innerHTML = 'Δ' + data.delta;
	if ( data.delta < 0 ) {
		div.className = 'delta negative';
	} else if ( data.delta === 0 ) {
		div.className = 'delta zero';
	} else {
		div.className = 'delta';
	}
	setTimeout(poll, 3000);
};

var getJSON = function(url, callback) {
	// http://stackoverflow.com/a/35970894
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status === 200) {
        callback(null, xhr.response);
      } else {
        callback(status);
      }
    };
    xhr.send();
};

function poll() {
	getJSON('//api.webm.website/stats.json', function ( e, r ) {
		updateCounts( r );
	} );
}

window.onload = function () {
	getJSON('//api.webm.website/stats.json', function ( e, r ) {
		createDivs( r );
		updateCounts( r );
	} );
};
<|endoftext|>


<commit_before>s.Controls = new Class({

  toString: 'Controls',

  options: {

    rotationSpeed: Math.PI/2,
    pitchSpeed: Math.PI/4,
    yawSpeed: Math.PI/4,
    thrustImpulse: 0,
    brakePower: 0.85,
    velocityFadeFactor: 16,
    rotationFadeFactor: 4

  },

  construct: function( options ) {

    // Store references to game objects
    this.HUD = options.HUD;
    this.game = options.game;
    this.player = options.player;
    this.camera = options.camera;
    this.menu = options.menu;

    // Create interpreters for controllers
    this.keyboard = new s.Keyboard( );

    // Gamepad interface
    this.gamepad = new Gamepad();

    // Oculus Rift interface
    this.oculus = this.game.oculus;

    // Mouse interface - mice options are: 'keyboard', 'none', 'oculus'
    this.mouse = new s.Mouse('keyboard', options);

    console.log('Initialized gamepad...');

    this.gamepad.bind(Gamepad.Event.CONNECTED, function(device) {
      console.log('Gamepad connected: '+device.id);
    });

    this.gamepad.bind(Gamepad.Event.DISCONNECTED, function(device) {
      console.log('Gamepad disconnected: '+device.id);
    });

    this.gamepad.bind(Gamepad.Event.UNSUPPORTED, function(device) {
      console.warn('Unsupported gamepad connected: '+device.id);
    });

    if (!this.gamepad.init()) {
      console.warn('Gamepads are not supported on this browser');
    }

    // Hook to the gameloop
    this.update = this.update.bind(this);
    this.game.hook(this.update);

    this.firing = false;

    this.lastTime = new Date( ).getTime( );

    var that = this;

    $(document).keyup(function (e) {
      if (e.which === 81) {
        if (that.menu.displayed) {
          that.menu.close();
        } else {
          that.menu.open();
        }
      } else {
        if (that.menu.displayed) {
          if (e.which === 32) {
            that.menu.selectItem();
          }
          if (e.which === 38) {
            that.menu.updateHovered('up');
          }
          if (e.which === 40) {
            that.menu.updateHovered('down');
          }
        }
      }
    });
  },

  destruct: function( ) {
    this.game.unhook( this.update );
  },

  update: function( time, delta ) {
    var mouseControls = false;

    var gamepadYaw = false;
    var hasGamepad = !!this.gamepad.gamepads.length;

    var now = new Date( ).getTime( );
    var difference = now - this.lastTime;

    var root = this.player.root;

    var pitch = 0;
    var roll = 0;
    var yaw = 0;

    var thrust = 0;
    var brakes = 0;
    var thrustScalar = this.options.thrustImpulse/s.config.ship.maxSpeed + 1;

    var centerY = this.HUD.canvas.height/2;
    var centerX = this.HUD.canvas.width/2;

    ///////////////////////
    // RADIAL SUBRETICLE //
    ///////////////////////

    var yawSpeed = this.options.yawSpeed,
      pitchSpeed = this.options.pitchSpeed,
      cursor = this.HUD.cursorVector,
      radius = this.HUD.subreticleBound.radius,
      crosshairs = {width: 30, height: 30};

    ///////////////////////
    //  OCULUS CONTROLS  //
    ///////////////////////

    if (this.oculus.detected) {
      this.mouse.mouseType = 'oculus';
      this.camera.rotation.setEulerFromQuaternion(this.oculus.quat);
      pitch = this.oculus.quat.x;
      yaw = this.oculus.quat.y;
      roll = this.oculus.quat.z;
      if (this.menu.displayed) {
        this.menu.updateHovered();
      }
    } else {
      this.mouse.mouseType = 'keyboard';
    }

    ///////////////////////
    //  MOUSE CONTROLS   //
    ///////////////////////

    var mouseUpdate = this.mouse.update({
        centerX: centerX,
        crosshairs: crosshairs,
        yaw: yaw,
        radius: radius,
        yawSpeed: yawSpeed,
        thrustScalar: thrustScalar,
        centerY: centerY,
        pitch: pitch,
        pitchSpeed: pitchSpeed
    });

    pitch = mouseUpdate.pitch || pitch;
    yaw = mouseUpdate.yaw || yaw;

    ///////////////////////
    // GAMEPAD CONTROLS  //
    ///////////////////////

    if (hasGamepad) {
      var gamepadState = this.gamepad.gamepads[0].state;

      // TODO: Handle inverted option
      pitch = gamepadState.LEFT_STICK_Y;

      if (gamepadYaw) {
        yaw = gamepadState.LEFT_STICK_X*-1;
      }
      else {
        roll = gamepadState.LEFT_STICK_X*-1 * this.options.rotationSpeed;
      }

      if (gamepadState.RB || gamepadState.X || gamepadState.FACE_1)
        this.firing = true;
      else
        this.firing = false;

      var gamepadThrust = (gamepadState.RIGHT_STICK_X*-1 + 1)/2;

      // Set thrust
      this.options.thrustImpulse = gamepadThrust * s.config.ship.maxSpeed;
    }

    ///////////////////////
    // KEYBOARD COMMANDS //
    ///////////////////////

    if (this.keyboard.pressed('left')) {
      yaw = yawSpeed / thrustScalar;

    }
    else if (this.keyboard.pressed('right')) {
      yaw = -1*yawSpeed / thrustScalar;
    }

    if (this.keyboard.pressed('up')) {
      // Pitch down
      pitch = -1*pitchSpeed / thrustScalar;
    }
    else if (this.keyboard.pressed('down')) {
      // Pitch up
      pitch = pitchSpeed / thrustScalar;
    }

    if (this.keyboard.pressed('w')) {
      thrust = 1;
    }
    else if (this.keyboard.pressed('s')) {
      brakes = 1;
    }

    if (this.keyboard.pressed('a')) {
      roll = this.options.rotationSpeed;
    }
    else if (this.keyboard.pressed('d')) {
      roll = -1*this.options.rotationSpeed;
    }

    if (this.keyboard.pressed('space') || this.firing){
      this.player.fire('turret');
    }

    if (this.keyboard.pressed('tilde')) {
      vr.resetHmdOrientation();
    }

    //////////////////////////////
    // MOTION AND PHYSICS LOGIC //
    //////////////////////////////

    var linearVelocity = root.getLinearVelocity().clone();
    var angularVelocity = root.getAngularVelocity().clone();
    var rotationMatrix = new THREE.Matrix4();
    rotationMatrix.extractRotation(root.matrix);

    // Apply rotation
    // Bleed off angular velocity towards zero
    angularVelocity = angularVelocity.clone().divideScalar(this.options.rotationFadeFactor);
    root.setAngularVelocity(angularVelocity);

    // Add to the existing angular velocity,
    var newAngularVelocity = new THREE.Vector3(pitch, yaw, roll).applyMatrix4(rotationMatrix).add(angularVelocity);
    root.setAngularVelocity(newAngularVelocity);

    // Apply thrust
    // Invert existing linear velocity
    // Fractionally apply the opposite impulse
    // Then apply forward impulse

    // If ship position is greater then x apply thrust in opposite direction
    // If ship position is not greater then x allow to apply thrust
    var playerPosition = this.player.root.position;
    var boundryLimit = 30000;

    // If the ship is beyound the boundary limit push it back into the map
    /*
    if(s.util.largerThan(playerPosition, boundryLimit)){
      var boundryPush = new THREE.Vector3(0, 0, 200*this.options.thrustImpulse).applyMatrix4(rotationMatrix);
      root.applyCentralImpulse(boundryPush);
      console.log('--Outside Boundry Limit--');
    }
    */

    if (thrust && this.options.thrustImpulse < s.config.ship.maxSpeed){
      this.options.thrustImpulse += (difference > s.config.ship.maxSpeed) ?
        s.config.ship.maxSpeed : difference;
    }

    if (brakes && this.options.thrustImpulse > 0){
      this.options.thrustImpulse -= difference;
    }

    var impulse = linearVelocity.clone().negate();
    root.applyCentralImpulse(impulse);

    var forceVector = new THREE.Vector3(0, 0, -1*this.options.thrustImpulse).applyMatrix4(rotationMatrix);
    root.applyCentralImpulse(forceVector);
    this.lastTime = now;
  }
});
<commit_msg>Oculus controls working with flight stick. It's the best.<commit_after>s.Controls = new Class({

  toString: 'Controls',

  options: {

    rotationSpeed: Math.PI/2,
    pitchSpeed: Math.PI/4,
    yawSpeed: Math.PI/4,
    thrustImpulse: 0,
    brakePower: 0.85,
    velocityFadeFactor: 16,
    rotationFadeFactor: 4

  },

  construct: function( options ) {

    // Store references to game objects
    this.HUD = options.HUD;
    this.game = options.game;
    this.player = options.player;
    this.camera = options.camera;
    this.menu = options.menu;

    // Create interpreters for controllers
    this.keyboard = new s.Keyboard( );

    // Gamepad interface
    this.gamepad = new Gamepad();

    // Oculus Rift interface
    this.oculus = this.game.oculus;

    // Mouse interface - mice options are: 'keyboard', 'none', 'oculus'
    this.mouse = new s.Mouse('keyboard', options);

    console.log('Initialized gamepad...');

    this.gamepad.bind(Gamepad.Event.CONNECTED, function(device) {
      console.log('Gamepad connected: '+device.id);
    });

    this.gamepad.bind(Gamepad.Event.DISCONNECTED, function(device) {
      console.log('Gamepad disconnected: '+device.id);
    });

    this.gamepad.bind(Gamepad.Event.UNSUPPORTED, function(device) {
      console.warn('Unsupported gamepad connected: '+device.id);
    });

    if (!this.gamepad.init()) {
      console.warn('Gamepads are not supported on this browser');
    }

    // Hook to the gameloop
    this.update = this.update.bind(this);
    this.game.hook(this.update);

    this.firing = false;

    this.lastTime = new Date( ).getTime( );

    var that = this;

    $(document).keyup(function (e) {
      if (e.which === 81) {
        if (that.menu.displayed) {
          that.menu.close();
        } else {
          that.menu.open();
        }
      } else {
        if (that.menu.displayed) {
          if (e.which === 32) {
            that.menu.selectItem();
          }
          if (e.which === 38) {
            that.menu.updateHovered('up');
          }
          if (e.which === 40) {
            that.menu.updateHovered('down');
          }
        }
      }
    });
  },

  destruct: function( ) {
    this.game.unhook( this.update );
  },

  update: function( time, delta ) {
    var mouseControls = false;

    var gamepadYaw = false;
    var hasGamepad = !!this.gamepad.gamepads.length;

    var now = new Date( ).getTime( );
    var difference = now - this.lastTime;

    var root = this.player.root;

    var pitch = 0;
    var roll = 0;
    var yaw = 0;

    var thrust = 0;
    var brakes = 0;
    var thrustScalar = this.options.thrustImpulse/s.config.ship.maxSpeed + 1;

    var centerY = this.HUD.canvas.height/2;
    var centerX = this.HUD.canvas.width/2;

    ///////////////////////
    // RADIAL SUBRETICLE //
    ///////////////////////

    var yawSpeed = this.options.yawSpeed,
      pitchSpeed = this.options.pitchSpeed,
      cursor = this.HUD.cursorVector,
      radius = this.HUD.subreticleBound.radius,
      crosshairs = {width: 30, height: 30};

    ///////////////////////
    // KEYBOARD COMMANDS //
    ///////////////////////

    if (this.keyboard.pressed('left')) {
      yaw = yawSpeed / thrustScalar;
    }
    else if (this.keyboard.pressed('right')) {
      yaw = -1*yawSpeed / thrustScalar;
    }

    if (this.keyboard.pressed('up')) {
      // Pitch down
      pitch = -1*pitchSpeed / thrustScalar;
    }
    else if (this.keyboard.pressed('down')) {
      // Pitch up
      pitch = pitchSpeed / thrustScalar;
    }

    if (this.keyboard.pressed('w')) {
      thrust = 1;
    }
    else if (this.keyboard.pressed('s')) {
      brakes = 1;
    }

    if (this.keyboard.pressed('a')) {
      roll = this.options.rotationSpeed;
    }
    else if (this.keyboard.pressed('d')) {
      roll = -1*this.options.rotationSpeed;
    }

    if (this.keyboard.pressed('space') || this.firing){
      this.player.fire('turret');
    }

    if (this.keyboard.pressed('tilde')) {
      vr.resetHmdOrientation();
    }

    ///////////////////////
    //  MOUSE CONTROLS   //
    ///////////////////////

    var mouseUpdate = this.mouse.update({
        centerX: centerX,
        crosshairs: crosshairs,
        yaw: yaw,
        radius: radius,
        yawSpeed: yawSpeed,
        thrustScalar: thrustScalar,
        centerY: centerY,
        pitch: pitch,
        pitchSpeed: pitchSpeed
    });

    pitch = mouseUpdate.pitch || pitch;
    yaw = mouseUpdate.yaw || yaw;

    ///////////////////////
    // GAMEPAD CONTROLS  //
    ///////////////////////

    if (hasGamepad) {
      var gamepadState = this.gamepad.gamepads[0].state;

      // TODO: Handle inverted option
      pitch = gamepadState.LEFT_STICK_Y;

      if (gamepadYaw) {
        yaw = gamepadState.LEFT_STICK_X*-1;
      }
      else {
        roll = gamepadState.LEFT_STICK_X*-1 * this.options.rotationSpeed;
      }

      if (gamepadState.RB || gamepadState.X || gamepadState.FACE_1)
        this.firing = true;
      else
        this.firing = false;

      var gamepadThrust = (gamepadState.RIGHT_STICK_X*-1 + 1)/2;

      // Set thrust
      this.options.thrustImpulse = gamepadThrust * s.config.ship.maxSpeed;
    }

    ///////////////////////
    //  OCULUS CONTROLS  //
    ///////////////////////

    if (this.oculus.detected) {
      this.mouse.mouseType = 'oculus';
      this.camera.rotation.setEulerFromQuaternion(this.oculus.quat);
      if (hasGamepad) {
        pitch += this.oculus.quat.x/2;
        yaw += this.oculus.quat.y/2;
        roll += this.oculus.quat.z/2;
      } else {
        pitch += this.oculus.quat.x;
        yaw += this.oculus.quat.y;
        roll += this.oculus.quat.z;
      }
      if (this.menu.displayed) {
        this.menu.updateHovered();
      }
    } else {
      this.mouse.mouseType = 'keyboard';
    }

    //////////////////////////////
    // MOTION AND PHYSICS LOGIC //
    //////////////////////////////

    var linearVelocity = root.getLinearVelocity().clone();
    var angularVelocity = root.getAngularVelocity().clone();
    var rotationMatrix = new THREE.Matrix4();
    rotationMatrix.extractRotation(root.matrix);

    // Apply rotation
    // Bleed off angular velocity towards zero
    angularVelocity = angularVelocity.clone().divideScalar(this.options.rotationFadeFactor);
    root.setAngularVelocity(angularVelocity);

    // Add to the existing angular velocity,
    var newAngularVelocity = new THREE.Vector3(pitch, yaw, roll).applyMatrix4(rotationMatrix).add(angularVelocity);
    root.setAngularVelocity(newAngularVelocity);

    // Apply thrust
    // Invert existing linear velocity
    // Fractionally apply the opposite impulse
    // Then apply forward impulse

    // If ship position is greater then x apply thrust in opposite direction
    // If ship position is not greater then x allow to apply thrust
    var playerPosition = this.player.root.position;
    var boundryLimit = 30000;

    // If the ship is beyound the boundary limit push it back into the map
    /*
    if(s.util.largerThan(playerPosition, boundryLimit)){
      var boundryPush = new THREE.Vector3(0, 0, 200*this.options.thrustImpulse).applyMatrix4(rotationMatrix);
      root.applyCentralImpulse(boundryPush);
      console.log('--Outside Boundry Limit--');
    }
    */

    if (thrust && this.options.thrustImpulse < s.config.ship.maxSpeed){
      this.options.thrustImpulse += (difference > s.config.ship.maxSpeed) ?
        s.config.ship.maxSpeed : difference;
    }

    if (brakes && this.options.thrustImpulse > 0){
      this.options.thrustImpulse -= difference;
    }

    var impulse = linearVelocity.clone().negate();
    root.applyCentralImpulse(impulse);

    var forceVector = new THREE.Vector3(0, 0, -1*this.options.thrustImpulse).applyMatrix4(rotationMatrix);
    root.applyCentralImpulse(forceVector);
    this.lastTime = now;
  }
});
<|endoftext|>


<commit_before>// Rebase require directory
requirejs.config({
	baseUrl: "lib",
	paths: {
		activity: "../js"
	}
});

// Vue main app
var app = new Vue({
	el: '#app',
	data: {
		canvas: '',
		context: '',
		analyser: '',
		processor: '',
		time_domain: true,
		timeDomainData: [],
		play: true,
		time_div: 0.0005,
		num_of_samples: 1024,
		num_of_divs: 20
	},
	methods: {
		init: function() {

			this.canvas.width = window.innerWidth;
			this.canvas.height = window.innerHeight - 55 - (document.getElementById("axisScale").clientHeight);

			window.addEventListener("resize", () => {
				this.resizeCanvas()
			})
			this.drawGrid();

			//Getting permission for microphone from user
			// if (window.cordova || window.PhoneGap) {
			// 	console.log("cordova", window.cordova)
			// 	console.log("audioinput", window.audioinput)
			// 	// Start the plugin in Web Audio mode
			// 	audioinput.start({
			// 		streamToWebAudio: true
			// 	});
			// }
			// else{
			// 	navigator.mediaDevices.getUserMedia({ audio: true })
			// 		.then((stream) => {
			// 			if (this.time_domain) {
			// 				this.setTimeDomain(stream)
			// 			}
			// 		})
			// 		.catch((err) => alert('Please allow microphone access'))
			// }
		},
		resizeCanvas: function() {
			this.canvas.width = window.innerWidth;
			this.canvas.height = window.innerHeight - 55 - (document.getElementById("axisScale").clientHeight);
		},
		setTimeDomain: function(stream) {
			document.getElementById("domainName").innerText = 'Time'
			document.getElementById("scaleValue").innerText = this.time_div*1000;

			// Create and init a Web Audio Analyser node
			if (window.cordova || window.PhoneGap) {
				this.context = audioinput.getAudioContext();
				this.source = audioinput;
				console.log(this.context)
			}
			else {
				this.context = new AudioContext();
				this.source = this.context.createMediaStreamSource(stream);
			}
			this.analyser = this.context.createAnalyser();
			this.analyser.smoothingTimeConstant = 0;
			this.analyser.fftSize = 1024;

			this.processor = this.context.createScriptProcessor(this.analyser.fftSize, 1, 1);
			this.timeDomainData = new Float32Array(this.analyser.fftSize);
			this.source.connect(this.analyser);
			this.analyser.connect(this.processor);
			this.processor.connect(this.context.destination);
			this.processor.addEventListener('audioprocess', (e) => {
				if(!this.play) return;
				this.analyser.getFloatTimeDomainData(this.timeDomainData)

				console.log(this.timeDomainData)

				this.num_of_divs = this.canvas.width/50; // 50 is width of one div
				var total_time_duration = this.time_div*this.num_of_divs;

				// Formula: num_of_samples = sampling_frequency*total_time_duration
				this.num_of_samples = Math.ceil(total_time_duration*48000); //48000 is sampling frequency
				this.drawWaveform()
			})
		},
		drawWaveform: function() {
			var canvasCtx = this.canvas.getContext("2d");
			this.drawGrid();
			canvasCtx.lineWidth = 3;
			canvasCtx.strokeStyle = 'red';

			canvasCtx.beginPath();

			var sliceWidth = this.canvas.width*1.0/this.num_of_samples;
			var x = 0;
			for(var i=0;i<this.num_of_samples;i++) {
				let y = this.mapCoords(this.timeDomainData[i], -1, 1, 0, this.canvas.height);
				if(i == 0) {
					canvasCtx.moveTo(x,y);
				}
				else {
					canvasCtx.lineTo(x,y);
				}
				x += sliceWidth;
			}
			canvasCtx.lineTo(this.canvas.width, this.canvas.height/2);
			canvasCtx.stroke();
		},
		drawGrid: function() {
			var canvasCtx = this.canvas.getContext("2d");

			canvasCtx.fillStyle = 'white';
			canvasCtx.fillRect(0, 0, this.canvas.width, this.canvas.height);

			canvasCtx.fillStyle = 'black';
			for (var i = 0; i < this.canvas.width; i = i + 50) {
				canvasCtx.fillRect(i, 0, 1, this.canvas.height)
			}
			for (var i = 0; i < this.canvas.height; i = i + 50) {
				canvasCtx.fillRect(0, i, this.canvas.width, 1)
			}
		},
		mapCoords: function(value, a, b, c, d) {
			value = (value - a) / (b - a);
			return c + value * (d - c);
		},
		playOrPause: function() {
			this.play = !this.play;
			if(this.play) {
				document.getElementById("play-button").style.display = "initial";
				document.getElementById("pause-button").style.display = "none";
			}
			else {
				document.getElementById("play-button").style.display = "none";
				document.getElementById("pause-button").style.display = "initial";
			}
		},
		onDeviceReady: function() {
			console.log("Hello")
			console.log("cordova from ondevice", window.cordova)
			console.log("audioinput from ondevice", window.audioinput)
			this.init()
			audioinput.start({
				streamToWebAudio: true
			});
			this.setTimeDomain(null)
		}
	},
	mounted() {
		this.canvas = document.getElementById("mainCanvas");
		if (window.cordova || window.PhoneGap) {
			document.addEventListener('deviceready', this.onDeviceReady, false);
		}
		else {
			this.init()
			navigator.mediaDevices.getUserMedia({ audio: true })
				.then((stream) => {
					if (this.time_domain) {
						this.setTimeDomain(stream)
					}
				})
				.catch((err) => alert('Please allow microphone access'))
		}
	}
});
<commit_msg>time domain functioning for browser<commit_after>// Rebase require directory
requirejs.config({
	baseUrl: "lib",
	paths: {
		activity: "../js"
	}
});

// Vue main app
var app = new Vue({
	el: '#app',
	data: {
		canvas: '',
		context: '',
		analyser: '',
		processor: '',
		time_domain: true,
		timeDomainData: [],
		play: true,
		time_div: 0.0005,
		num_of_samples: 1024,
		num_of_divs: 20
	},
	methods: {
		init: function() {

			this.canvas.width = window.innerWidth;
			this.canvas.height = window.innerHeight - 55 - (document.getElementById("axisScale").clientHeight);

			window.addEventListener("resize", () => {
				this.resizeCanvas()
			})
			this.drawGrid();
		},
		resizeCanvas: function() {
			this.canvas.width = window.innerWidth;
			this.canvas.height = window.innerHeight - 55 - (document.getElementById("axisScale").clientHeight);
		},
		setTimeDomain: function(stream) {
			document.getElementById("domainName").innerText = 'Time'
			document.getElementById("scaleValue").innerText = this.time_div*1000;

			// Create and init a Web Audio Analyser node
			if (window.cordova || window.PhoneGap) {
				this.context = audioinput.getAudioContext();
				this.source = audioinput;
			}
			else {
				this.context = new AudioContext();
				this.source = this.context.createMediaStreamSource(stream);
			}
			this.analyser = this.context.createAnalyser();
			this.analyser.smoothingTimeConstant = 0;
			this.analyser.fftSize = 1024;

			this.processor = this.context.createScriptProcessor(this.analyser.fftSize, 1, 1);
			this.timeDomainData = new Float32Array(this.analyser.fftSize);
			this.source.connect(this.analyser);
			this.analyser.connect(this.processor);
			this.processor.connect(this.context.destination);
			this.processor.addEventListener('audioprocess', (e) => {
				if(!this.play) return;
				this.analyser.getFloatTimeDomainData(this.timeDomainData)

				this.num_of_divs = this.canvas.width/50; // 50 is width of one div
				var total_time_duration = this.time_div*this.num_of_divs;

				// Formula: num_of_samples = sampling_frequency*total_time_duration
				this.num_of_samples = Math.ceil(total_time_duration*48000); //48000 is sampling frequency
				this.drawWaveform()
			})
		},
		drawWaveform: function() {
			var canvasCtx = this.canvas.getContext("2d");
			this.drawGrid();
			canvasCtx.lineWidth = 3;
			canvasCtx.strokeStyle = 'red';

			canvasCtx.beginPath();

			var sliceWidth = this.canvas.width*1.0/this.num_of_samples;
			var x = 0;
			for(var i=0;i<this.num_of_samples;i++) {
				let y = this.mapCoords(this.timeDomainData[i], -1, 1, 0, this.canvas.height);
				if(i == 0) {
					canvasCtx.moveTo(x,y);
				}
				else {
					canvasCtx.lineTo(x,y);
				}
				x += sliceWidth;
			}
			canvasCtx.lineTo(this.canvas.width, this.canvas.height/2);
			canvasCtx.stroke();
		},
		drawGrid: function() {
			var canvasCtx = this.canvas.getContext("2d");

			canvasCtx.fillStyle = 'black';
			canvasCtx.fillRect(0, 0, this.canvas.width, this.canvas.height);

			canvasCtx.fillStyle = 'grey';
			for (var i = 0; i < this.canvas.width; i = i + 50) {
				canvasCtx.fillRect(i, 0, 1, this.canvas.height)
			}
			for (var i = 0; i < this.canvas.height; i = i + 50) {
				canvasCtx.fillRect(0, i, this.canvas.width, 1)
			}
		},
		mapCoords: function(value, a, b, c, d) {
			value = (value - a) / (b - a);
			return c + value * (d - c);
		},
		playOrPause: function() {
			this.play = !this.play;
			if(this.play) {
				document.getElementById("play-button").style.display = "initial";
				document.getElementById("pause-button").style.display = "none";
			}
			else {
				document.getElementById("play-button").style.display = "none";
				document.getElementById("pause-button").style.display = "initial";
			}
		},
		onDeviceReady: function() {
			console.log("Hello")
			console.log("cordova from ondevice", window.cordova)
			console.log("audioinput from ondevice", window.audioinput)
			this.init()
			audioinput.start({
				streamToWebAudio: true
			});
			this.setTimeDomain(null)
		}
	},
	mounted() {
		this.canvas = document.getElementById("mainCanvas");
		if (window.cordova || window.PhoneGap) {
			document.addEventListener('deviceready', this.onDeviceReady, false);
		}
		else {
			this.init()
			navigator.mediaDevices.getUserMedia({ audio: true })
				.then((stream) => {
					if (this.time_domain) {
						this.setTimeDomain(stream)
					}
				})
				.catch((err) => alert('Please allow microphone access'))
		}
	}
});
<|endoftext|>


<commit_before>import {createSelector} from 'reselect';
import moment from 'moment';
import {OrderedMap} from 'immutable';
import {formatDate} from '@ciscospark/react-component-utils';
import {FEATURE_GROUP_CALLING} from '@ciscospark/redux-module-features';

const getAvatars = (state) => state.avatar;
const getCurrentUser = (state, ownProps) => ownProps.currentUser;
const getFeatures = (state) => state.features;
const getCalls = (state) => state.media.get('calls');
const getSpaces = (state) => state.spaces;
const getSpark = (state) => state.spark;
const getTeams = (state) => state.teams;
const getUsers = (state) => state.users;
const getWidget = (state) => state.widgetRecents;

function sortByNewest(space) {
  return -moment(space.get('lastReadableActivityDate')).format('x');
}

function constructSpace(space) {
  const lastSeenActivityDate = space.get('lastSeenActivityDate');
  const lastActivityTimestamp = space.get('lastReadableActivityDate');
  const isUnread = lastSeenActivityDate ? moment(lastSeenActivityDate).isBefore(lastActivityTimestamp) : true;

  const id = space.get('id');
  const actorName = space.getIn(['latestActivity', 'actor', 'displayName']);

  return {
    id,
    type: space.get('type'),
    lastActivityTime: formatDate(lastActivityTimestamp),
    lastActivityTimestamp,
    name: 'Untitled',
    latestActivity: {
      actorName: actorName ? actorName.split(' ')[0] : '',
      actor: space.getIn(['latestActivity', 'actor']).toJS(),
      type: space.getIn(['latestActivity', 'verb']),
      object: space.getIn(['latestActivity', 'object']).toJS(),
      text: space.getIn(['latestActivity', 'object', 'displayName'])
    },
    participants: space.get('participants').toJS(),
    published: space.get('published'),
    isLocked: space.get('tags') && space.get('tags').includes('LOCKED'),
    isUnread,
    isDecrypting: space.get('isDecrypting')
  };
}

function constructOneOnOne({space, currentUser, users}) {
  const thisSpace = constructSpace(space);

  // Get the user ID of the participant that isn't current user
  const toPersonId = space.get('participants').find((p) => p !== currentUser.id);
  const toPerson = users.getIn(['byId', toPersonId]);
  if (toPerson) {
    thisSpace.toPersonId = toPersonId;
    thisSpace.toPersonEmail = toPerson.email;
    thisSpace.name = toPerson.displayName;
  }
  return thisSpace;
}

function constructGroup({space, team}) {
  const id = space.get('id');
  const thisSpace = constructSpace(space);
  thisSpace.name = space.get('displayName') || 'Untitled';
  if (team) {
    thisSpace.teamName = team.get('displayName');
    thisSpace.teamColor = team.get('teamColor');
    thisSpace.teamId = team.get('id');
    if (id === team.get('generalConversationUuid')) {
      thisSpace.name = 'General';
    }
  }
  return thisSpace;
}

const getRecentSpaces = createSelector(
  [getSpaces, getCurrentUser, getUsers, getTeams, getWidget],
  (spaces, currentUser, users, teams, widget) => {
    const visibilityCount = widget.get('visibilityCount');
    let recents = new OrderedMap();
    let count = 0;
    spaces.get('items').toOrderedMap().sortBy(sortByNewest).some((space) => {
      if (!space.get('hidden')) {
        const spaceId = space.get('id');
        const team = teams.getIn(['items', space.getIn(['team', 'id'])]);
        if (space.get('type') === 'direct') {
          recents = recents.set(spaceId, constructOneOnOne({space, users, currentUser}));
        }
        else {
          recents = recents.set(spaceId, constructGroup({space, team}));
        }
        count += 1;
      }
      if (count >= visibilityCount) {
        return true;
      }
      return false;
    });
    return recents;
  }
);

const getRecentSpacesWithAvatarUrl = createSelector(
  [getRecentSpaces, getAvatars],
  (recentSpaces, avatars) => {
    const avatarItems = avatars.get('items');
    if (avatarItems.count()) {
      return recentSpaces.map((space) => {
        const s = space;
        if (s.type === 'direct') {
          s.avatarUrl = avatarItems.get(s.toPersonId);
        }
        else {
          s.avatarUrl = avatarItems.get(s.id);
        }
        return s;
      });
    }
    return recentSpaces;
  }
);

const getIncomingCall = createSelector(
  [getCalls],
  (calls) => calls.find((call) => call.isIncoming && !call.isDismissed)
);

const getRecentsWidgetProps = createSelector(
  [
    getWidget,
    getRecentSpacesWithAvatarUrl,
    getSpark,
    getFeatures,
    getIncomingCall
  ],
  (
    widget,
    spacesList,
    spark,
    features,
    incomingCall
  ) => {
    let lastActivityDate;
    if (spacesList && spacesList.count()) {
      lastActivityDate = spacesList.last().lastActivityTimestamp;
    }
    const hasGroupCalling = features.getIn(['items', FEATURE_GROUP_CALLING]);
    return {
      widgetStatus: widget.get('status').toJS(),
      sparkState: spark.get('status'),
      sparkInstance: spark.get('spark'),
      widgetRecents: widget,
      spacesList,
      hasGroupCalling,
      lastActivityDate,
      incomingCall
    };
  }
);

export default getRecentsWidgetProps;
<commit_msg>feat(widget-recents): use isAnswered for incoming call status<commit_after>import {createSelector} from 'reselect';
import moment from 'moment';
import {OrderedMap} from 'immutable';
import {formatDate} from '@ciscospark/react-component-utils';
import {FEATURE_GROUP_CALLING} from '@ciscospark/redux-module-features';

const getAvatars = (state) => state.avatar;
const getCurrentUser = (state, ownProps) => ownProps.currentUser;
const getFeatures = (state) => state.features;
const getCalls = (state) => state.media.get('calls');
const getSpaces = (state) => state.spaces;
const getSpark = (state) => state.spark;
const getTeams = (state) => state.teams;
const getUsers = (state) => state.users;
const getWidget = (state) => state.widgetRecents;

function sortByNewest(space) {
  return -moment(space.get('lastReadableActivityDate')).format('x');
}

function constructSpace(space) {
  const lastSeenActivityDate = space.get('lastSeenActivityDate');
  const lastActivityTimestamp = space.get('lastReadableActivityDate');
  const isUnread = lastSeenActivityDate ? moment(lastSeenActivityDate).isBefore(lastActivityTimestamp) : true;

  const id = space.get('id');
  const actorName = space.getIn(['latestActivity', 'actor', 'displayName']);

  return {
    id,
    type: space.get('type'),
    lastActivityTime: formatDate(lastActivityTimestamp),
    lastActivityTimestamp,
    name: 'Untitled',
    latestActivity: {
      actorName: actorName ? actorName.split(' ')[0] : '',
      actor: space.getIn(['latestActivity', 'actor']).toJS(),
      type: space.getIn(['latestActivity', 'verb']),
      object: space.getIn(['latestActivity', 'object']).toJS(),
      text: space.getIn(['latestActivity', 'object', 'displayName'])
    },
    participants: space.get('participants').toJS(),
    published: space.get('published'),
    isLocked: space.get('tags') && space.get('tags').includes('LOCKED'),
    isUnread,
    isDecrypting: space.get('isDecrypting')
  };
}

function constructOneOnOne({space, currentUser, users}) {
  const thisSpace = constructSpace(space);

  // Get the user ID of the participant that isn't current user
  const toPersonId = space.get('participants').find((p) => p !== currentUser.id);
  const toPerson = users.getIn(['byId', toPersonId]);
  if (toPerson) {
    thisSpace.toPersonId = toPersonId;
    thisSpace.toPersonEmail = toPerson.email;
    thisSpace.name = toPerson.displayName;
  }
  return thisSpace;
}

function constructGroup({space, team}) {
  const id = space.get('id');
  const thisSpace = constructSpace(space);
  thisSpace.name = space.get('displayName') || 'Untitled';
  if (team) {
    thisSpace.teamName = team.get('displayName');
    thisSpace.teamColor = team.get('teamColor');
    thisSpace.teamId = team.get('id');
    if (id === team.get('generalConversationUuid')) {
      thisSpace.name = 'General';
    }
  }
  return thisSpace;
}

const getRecentSpaces = createSelector(
  [getSpaces, getCurrentUser, getUsers, getTeams, getWidget],
  (spaces, currentUser, users, teams, widget) => {
    const visibilityCount = widget.get('visibilityCount');
    let recents = new OrderedMap();
    let count = 0;
    spaces.get('items').toOrderedMap().sortBy(sortByNewest).some((space) => {
      if (!space.get('hidden')) {
        const spaceId = space.get('id');
        const team = teams.getIn(['items', space.getIn(['team', 'id'])]);
        if (space.get('type') === 'direct') {
          recents = recents.set(spaceId, constructOneOnOne({space, users, currentUser}));
        }
        else {
          recents = recents.set(spaceId, constructGroup({space, team}));
        }
        count += 1;
      }
      if (count >= visibilityCount) {
        return true;
      }
      return false;
    });
    return recents;
  }
);

const getRecentSpacesWithAvatarUrl = createSelector(
  [getRecentSpaces, getAvatars],
  (recentSpaces, avatars) => {
    const avatarItems = avatars.get('items');
    if (avatarItems.count()) {
      return recentSpaces.map((space) => {
        const s = space;
        if (s.type === 'direct') {
          s.avatarUrl = avatarItems.get(s.toPersonId);
        }
        else {
          s.avatarUrl = avatarItems.get(s.id);
        }
        return s;
      });
    }
    return recentSpaces;
  }
);

const getIncomingCall = createSelector(
  [getCalls],
  (calls) => calls.find((call) => call.isIncoming && !call.isDismissed && !call.isAnswered)
);

const getRecentsWidgetProps = createSelector(
  [
    getWidget,
    getRecentSpacesWithAvatarUrl,
    getSpark,
    getFeatures,
    getIncomingCall
  ],
  (
    widget,
    spacesList,
    spark,
    features,
    incomingCall
  ) => {
    let lastActivityDate;
    if (spacesList && spacesList.count()) {
      lastActivityDate = spacesList.last().lastActivityTimestamp;
    }
    const hasGroupCalling = features.getIn(['items', FEATURE_GROUP_CALLING]);
    return {
      widgetStatus: widget.get('status').toJS(),
      sparkState: spark.get('status'),
      sparkInstance: spark.get('spark'),
      widgetRecents: widget,
      spacesList,
      hasGroupCalling,
      lastActivityDate,
      incomingCall
    };
  }
);

export default getRecentsWidgetProps;
<|endoftext|>


<commit_before>/*
 *
 * This code was modified from the example found at http://bl.ocks.org/kerryrodden/7090426
 * which is covered by the Apache v2.0 License. A copy of this license is as follows:
 *    --- BEGIN ---
 *    Copyright 2013 Google Inc. All Rights Reserved.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 *  --- END ---
 * Developers: Do not remove this notification or license.
 */

"use strict";

var React = require('react');
var d3 = require('d3');
var _ = require('lodash');
var uuid = require('node-uuid');
var DashboardApi = require('../../api/dashboardApi');
var SunburstActions = require('../../actions/sunburstActions');
var SunburstStore = require('../../stores/sunburstStore');

var arc = d3.svg.arc()
            .startAngle(function(d) { return d.x; })
            .endAngle(function(d) { return d.x + d.dx; })
            .innerRadius(function(d) { return Math.sqrt(d.y); })
            .outerRadius(function(d) { return Math.sqrt(d.y + d.dy); });

var Path = React.createClass({
  propTypes: {
    height: React.PropTypes.number.isRequired,
    width: React.PropTypes.number.isRequired,
    radius: React.PropTypes.number,
    arcData: React.PropTypes.object.isRequired,
    highlightedNodes: React.PropTypes.array,
    fillOpacity: React.PropTypes.number
  },

    getDefaultProps: function () {
      return {
        arc: arc
      };
    },

    // getInitialState: function () {
    //   return {
    //     fillOpacity: 1,
    //     highlightedNodes: []
    //   };
    // },

    // componentWillMount: function () {
    //   CircleChartStore.addChangeListener(this._onChange);
    // },

    // componentWillUnmount: function () {
    //   CircleChartStore.removeChangeListener(this._onChange);
    // },

    // _onChange: function () {
    //   this.setState({ highlightedNodes: CircleChartStore.getHighlightedNodes() });
    // },

    // Given a node in a partition layout, return an array of all of its ancestor
    // nodes, highest first, but excluding the root.
    getAncestors: function (node) {
      var path = [];
      var current = node;
      while (current.parent) {
        path.unshift(current);
        current = current.parent;
      }
      return path;
    },

    resetChart: function () {
      SunburstActions.resetChart();
    },

    render: function() {
      var vm = this;
        return (
          <g className="chart"
              width={this.props.width}
              height={this.props.height}
              transform={"translate(" + this.props.width / 2 + "," + this.props.height / 2 + ")"} >
              { this.props.arcData.array.map(this.renderPaths) }
          </g>
        );
    },

    setHighlightedNodes: function (node) {
      if (node.name !== "root") {
        var nodes = this.getAncestors(node);
        // this.setState({fillOpacity: 0.3, highlightedNodes: nodes});
        SunburstActions.highlightNodes(nodes);
      }
    },

    renderPaths: function (node) {
      var vm = this;
      var props = {
        display: node.depth ? null : "none",
        d: this.props.arc(node),
        "fill-rule": "evenodd",
        name: "sampleName!",
        children: ['a', 'b', 'c'],
        size: 101,
        stroke: "#fff",
        fillOpacity: vm.props.highlightedNodes.indexOf(node) >= 0 ? 1 : vm.props.fillOpacity,
        fill: node.name !== "root" ? DashboardApi.calculateColor(node.name) : "#ffffff",
        key: uuid.v4(),
        onMouseOver: (function (selectedNode) {return function () { vm.setHighlightedNodes(selectedNode); }; })(node)
      };
      return (
        <path {...props} fill-rule="evenodd"></path>
      );
    }
});

module.exports = Path;<commit_msg>code cleanup<commit_after>/*
 *
 * This code was modified from the example found at http://bl.ocks.org/kerryrodden/7090426
 * which is covered by the Apache v2.0 License. A copy of this license is as follows:
 *    --- BEGIN ---
 *    Copyright 2013 Google Inc. All Rights Reserved.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 *  --- END ---
 * Developers: Do not remove this notification or license.
 */

"use strict";

var React = require('react');
var d3 = require('d3');
var _ = require('lodash');
var uuid = require('node-uuid');
var DashboardApi = require('../../api/dashboardApi');
var SunburstActions = require('../../actions/sunburstActions');
var SunburstStore = require('../../stores/sunburstStore');

var arc = d3.svg.arc()
            .startAngle(function(d) { return d.x; })
            .endAngle(function(d) { return d.x + d.dx; })
            .innerRadius(function(d) { return Math.sqrt(d.y); })
            .outerRadius(function(d) { return Math.sqrt(d.y + d.dy); });

var Path = React.createClass({
  propTypes: {
    height: React.PropTypes.number.isRequired,
    width: React.PropTypes.number.isRequired,
    radius: React.PropTypes.number,
    arcData: React.PropTypes.object.isRequired,
    highlightedNodes: React.PropTypes.array,
    fillOpacity: React.PropTypes.number
  },

    getDefaultProps: function () {
      return {
        arc: arc
      };
    },

    // Given a node in a partition layout, return an array of all of its ancestor
    // nodes, highest first, but excluding the root.
    getAncestors: function (node) {
      var path = [];
      var current = node;
      while (current.parent) {
        path.unshift(current);
        current = current.parent;
      }
      return path;
    },

    resetChart: function () {
      SunburstActions.resetChart();
    },

    render: function() {
      var vm = this;
        return (
          <g className="chart"
              width={this.props.width}
              height={this.props.height}
              transform={"translate(" + this.props.width / 2 + "," + this.props.height / 2 + ")"} >
              { this.props.arcData.array.map(this.renderPaths) }
          </g>
        );
    },

    setHighlightedNodes: function (node) {
      if (node.name !== "root") {
        var nodes = this.getAncestors(node);
        // this.setState({fillOpacity: 0.3, highlightedNodes: nodes});
        SunburstActions.highlightNodes(nodes);
      }
    },

    renderPaths: function (node) {
      var vm = this;
      var props = {
        display: node.depth ? null : "none",
        d: this.props.arc(node),
        "fill-rule": "evenodd",
        stroke: "#fff",
        fillOpacity: vm.props.highlightedNodes.indexOf(node) >= 0 ? 1 : vm.props.fillOpacity,
        fill: node.name !== "root" ? DashboardApi.calculateColor(node.name) : "#ffffff",
        key: uuid.v4(),
        onMouseOver: (function (selectedNode) {return function () { vm.setHighlightedNodes(selectedNode); }; })(node)
      };
      return (
        <path {...props}></path>
      );
    }
});

module.exports = Path;<|endoftext|>