<commit_before>'use strict'

const
  fs = require('fs'), stream = require('stream'), path = require('path')
,
  util = require('util'),
  debug = util.debuglog('logerr')
,
  timezoneOffset = (new Date()).getTimezoneOffset() * 60000
,
  separator = ':'
;

class Log {
  constructor ({ path = '', namespace = '' }) {
    const filePath = opts.path.resolve(module.parent, path)

    debug(`Creating log at ${filePath} with namespace ${namespace}.`)

    Object.assign(this, {
      debug: namespace ? require('util').debuglog(namespace) : null
    })

    this.init(filePath)
  }
  init (filePath) {
    fs.open(filePath, 'a', (err, fd) => {
      if (err) throw err

      debug(`Log successfully created with file-descriptor ${fd}.`)

      Object.assign(this, {
        fd
      })
    })
  }
  log (...args) {
    this.common(2, 'L', 'log', ...args)
    fs.write
  }
  info (...args) {
    this.common(3, 'I', 'info', ...args)
  }
  warn (...args) {
    this.common(1, 'W', 'warn', ...args)
  }
  error (...args) {
    this.common(0, 'E', 'error', ...args)
  }
  trace (...args) {
    this.common(0, 't', 'trace', ...args)
  }
  common (level, prefix, method, ...args) {
    args.unshift(prefix, new Date(Date.now() - timezoneOffset).toISOString())

    this.write(args)
  }
  write (args) {
    fs.write(this.fd, 'utf8', args.join(separator), (err) => {
      if (err) throw err
    })
  }
}

class DebugLog extends Log {
  constructor (...args) {
    super(...args)
  }
  write (args) {
    console.log(...args)
  }
}

class SparseLog extends Log {
  constructor (...args) {
    super(...args)
  }
  write () {}
}

// let logl, root

// class Log {
//   constructor (out, err, options = {}) {
//     debug(`logerr instance being constructed with out:::${out} and err:::${err}`)
//     // options specific to this log
//     if (typeof err !== 'string' && !( err instanceof stream.Writable )) {
//       options = err
//       err = undefined
//     }
//     if (!options.namespace || typeof options.namespace !== 'string') {
//       throw new Error(`log for ${out} missing a valid <String> namespace for util.debuglog`)
//     }
//     Object.assign(this, {
//       outLog: fs.createWriteStream(out, { flags: 'a', autoClose: false }),
//       errLog: err && fs.createWriteStream(err, { flags: 'a', autoClose: false }),
//       debuglog: require('util').debuglog(options.namespace)
//     })
//   }
//   common (level, prefix, method, ...args) {
//     this.debuglog(...args)

//     debug(`is the global logLevel (${logl}) >= the level of this log type? (${method}:::${level})`)
//     if (logl >= level) return
//     args.unshift(prefix, new Date(Date.now() - timezoneOffset).toISOString())

//     super[method](...args)
//   }
//   log (...args) {
//     this.common(2, 'L', 'log', ...args)
//     fs.write
//   }
//   info (...args) {
//     this.common(3, 'I', 'info', ...args)
//   }
//   error (...args) {
//     this.common(0, 'E', 'error', ...args)
//   }
//   warn (...args) {
//     this.common(1, 'W', 'warn', ...args)
//   }
//   trace (...args) {
//     this.common(0, 't', 'trace', ...args)
//   }
// }

// Log.prototype.log.newline = () => { console.log(this) }

// module.exports = ({ logLevel = 0, logsPath = process.cwd() }) => {
//   logl = logLevel
//   root = logsPath
//   debug(`logerr run with logLevel ${logl} and with logsPath ${root}`)
//   // change module.exports for future requires
//   module.exports = Log
//   // return Log for the first require
//   return Log
// }
<commit_msg>Revert "syntax error"<commit_after>'use strict'

const
  fs = require('fs'), stream = require('stream'), path = require('path')
,
  util = require('util'),
  debug = util.debuglog('logerr')
,
  timezoneOffset = (new Date()).getTimezoneOffset() * 60000
,
  separator = ':'
;

class Log {
  constructor ({ path = '', namespace = '' }) {
    const filePath = opts.path.resolve(module.parent, path)

    debug(`Creating log at ${filePath} with namespace ${namespace}.`)

    Object.assign(this, {
      debug: namespace ? require('util').debuglog(namespace) : null
    })

    this.init(filePath)
  }
  init (filePath) {
    fs.open(filePath, 'a', (err, fd) => {
      if (err) throw err

      debug(`Log successfully created with file-descriptor ${fd}.`)

      Object.assign(this, {
        fd
      })
    })
  }
  log (...args) {
    this.common(2, 'L', 'log', ...args)
    fs.write
  }
  info (...args) {
    this.common(3, 'I', 'info', ...args)
  }
  warn (...args) {
    this.common(1, 'W', 'warn', ...args)
  }
  error (...args) {
    this.common(0, 'E', 'error', ...args)
  }
  trace (...args) {
    this.common(0, 't', 'trace', ...args)
  }
  common (level, prefix, method, ...args) {
    args.unshift(prefix, new Date(Date.now() - timezoneOffset).toISOString())

    this.write(args)
  }
  write (args) {
    fs.write(this.fd, 'utf8', args.join(separator), (err) => {
      if (err) throw err
    })
  }
}

class DebugLog extends Log {
  constructor (...args) {
    super(...args)
  }
  write (args) {
    console.log(...args)
  }
}

class SparseLog extends Log {
  constructor (...args) {
    super(...args)
  }
  write ()
}

// let logl, root

// class Log {
//   constructor (out, err, options = {}) {
//     debug(`logerr instance being constructed with out:::${out} and err:::${err}`)
//     // options specific to this log
//     if (typeof err !== 'string' && !( err instanceof stream.Writable )) {
//       options = err
//       err = undefined
//     }
//     if (!options.namespace || typeof options.namespace !== 'string') {
//       throw new Error(`log for ${out} missing a valid <String> namespace for util.debuglog`)
//     }
//     Object.assign(this, {
//       outLog: fs.createWriteStream(out, { flags: 'a', autoClose: false }),
//       errLog: err && fs.createWriteStream(err, { flags: 'a', autoClose: false }),
//       debuglog: require('util').debuglog(options.namespace)
//     })
//   }
//   common (level, prefix, method, ...args) {
//     this.debuglog(...args)

//     debug(`is the global logLevel (${logl}) >= the level of this log type? (${method}:::${level})`)
//     if (logl >= level) return
//     args.unshift(prefix, new Date(Date.now() - timezoneOffset).toISOString())

//     super[method](...args)
//   }
//   log (...args) {
//     this.common(2, 'L', 'log', ...args)
//     fs.write
//   }
//   info (...args) {
//     this.common(3, 'I', 'info', ...args)
//   }
//   error (...args) {
//     this.common(0, 'E', 'error', ...args)
//   }
//   warn (...args) {
//     this.common(1, 'W', 'warn', ...args)
//   }
//   trace (...args) {
//     this.common(0, 't', 'trace', ...args)
//   }
// }

// Log.prototype.log.newline = () => { console.log(this) }

// module.exports = ({ logLevel = 0, logsPath = process.cwd() }) => {
//   logl = logLevel
//   root = logsPath
//   debug(`logerr run with logLevel ${logl} and with logsPath ${root}`)
//   // change module.exports for future requires
//   module.exports = Log
//   // return Log for the first require
//   return Log
// }
<|endoftext|>


<commit_before>var raw = require('raw-body');
var xml2js = require('xml2js');
var _ = require('underscore');
var http = require('http');
var parser = new xml2js.Parser();
var dftCfg = {
	host: '127.0.0.1',
	port: 7070,
	path: '/http-bind/',
	method: 'POST',
	listen: '/JHB/'
};

function getBody(req) {
	req = req.req || req;
	var type = (req.headers['content-type'] || '').split(';')[0];
	if (type.indexOf('text/xml') !== -1 || type.indexOf('application/xml') !== -1) {
		return function(done) {
			raw(req, function(err, str) {
				if (err) return done(err);
				try {
					done(null, str.toString());
				} catch (err) {
					err.status = 400;
					err.body = str;
					done(err);
				}
			});
		};
	} else {
		return function(done) {
			var err = new Error('Unsupported or missing content-type');
			err.status = 415;
			done(err);
		};
	}
}

function boshRequest(ret, config) {
	var cache = "";
	return function(done) {
		var boshReq = http.request(config, function(boshRes) {
			boshRes.on('data', function(data) {
				data = data.toString();
				cache += data;
				parser.parseString(cache, function(err, result) {
					if (!err) {
						done(null, cache);
					}
				});
			});
		});
		boshReq.end(ret);
	};
}

module.exports = function(cfg) {
	var config = _.extend({}, dftCfg, cfg);
	return function * (next) {
		var self = this;
		if (self.path === config.listen) {
			var ret = yield getBody(this);
			this.body = yield boshRequest(ret, config);
			this.type = "text/xml";
			this.charset = "utf-8";
			yield next;
		} else {
			yield next;
		}
	};
};<commit_msg>修正了有错误自动退出的bug<commit_after>var raw = require('raw-body');
var xml2js = require('xml2js');
var _ = require('underscore');
var http = require('http');
var parser = new xml2js.Parser();
var dftCfg = {
	host: '127.0.0.1',
	port: 7070,
	path: '/http-bind/',
	method: 'POST',
	listen: '/JHB/'
};

function getBody(req) {
	req = req.req || req;
	var type = (req.headers['content-type'] || '').split(';')[0];
	if (type.indexOf('text/xml') !== -1 || type.indexOf('application/xml') !== -1) {
		return function(done) {
			raw(req, function(err, str) {
				if (err) return done(err);
				try {
					done(null, str.toString());
				} catch (err) {
					err.status = 400;
					err.body = str;
					done(err);
				}
			});
		};
	} else {
		return function(done) {
			var err = new Error('Unsupported or missing content-type');
			err.status = 415;
			done(err);
		};
	}
}

function boshRequest(ret, config) {
	var cache = "";
	return function(done) {
		var boshReq = http.request(config, function(boshRes) {
			boshRes.on('data', function(data) {
				cache += data.toString();
			});
			boshRes.on('end', function() {
				parser.parseString(cache, function(err, result) {
					if (!err) {
						done(null, cache);
					}
					done(err);
				});
			});
		});
		boshReq.on('error', function(e) {
			done(e);
		});
		boshReq.end(ret);
	};
}

module.exports = function(cfg) {
	var config = _.extend({}, dftCfg, cfg);
	return function * (next) {
		var self = this;
		if (self.path === config.listen) {
			var ret = yield getBody(this);
			this.body = yield boshRequest(ret, config);
			this.type = "text/xml";
			this.charset = "utf-8";
			yield next;
		} else {
			yield next;
		}
	};
};<|endoftext|>


<commit_before>// export install function
export default function (Vue) {
  const _init = Vue.prototype._init
  Vue.prototype._init = function (options) {
    options = options || {}
    const componentOptions = this.constructor.options
    // store injection
    const store = options.store || componentOptions.store
    if (store) {
      this.$store = store
    } else if (options.parent && options.parent.$store) {
      this.$store = options.parent.$store
    }
    // vuex option handling
    const vuex = options.vuex || componentOptions.vuex
    if (vuex) {
      const { state, actions } = vuex
      // state
      if (state) {
        options.computed = options.computed || {}
        Object.keys(state).forEach(key => {
          options.computed[key] = function vuexBoundGetter () {
            return state[key](this.$store.state)
          }
        })
      }
      // actions
      if (actions) {
        options.methods = options.methods || {}
        Object.keys(actions).forEach(key => {
          options.methods[key] = function vuexBoundAction (...args) {
            return actions[key](this.$store, ...args)
          }
        })
      }
    }
    _init.call(this, options)
  }
}
<commit_msg>call getters and methods on instance<commit_after>// export install function
export default function (Vue) {
  const _init = Vue.prototype._init
  Vue.prototype._init = function (options) {
    options = options || {}
    const componentOptions = this.constructor.options
    // store injection
    const store = options.store || componentOptions.store
    if (store) {
      this.$store = store
    } else if (options.parent && options.parent.$store) {
      this.$store = options.parent.$store
    }
    // vuex option handling
    const vuex = options.vuex || componentOptions.vuex
    if (vuex) {
      const { state, actions } = vuex
      // state
      if (state) {
        options.computed = options.computed || {}
        Object.keys(state).forEach(key => {
          options.computed[key] = function vuexBoundGetter () {
            return state[key].call(this, this.$store.state)
          }
        })
      }
      // actions
      if (actions) {
        options.methods = options.methods || {}
        Object.keys(actions).forEach(key => {
          options.methods[key] = function vuexBoundAction (...args) {
            return actions[key].call(this, this.$store, ...args)
          }
        })
      }
    }
    _init.call(this, options)
  }
}
<|endoftext|>


<commit_before>const { pbkdf2 } = require("./derivation.js");
const { decryptCBC, decryptGCM, encryptCBC, encryptGCM, generateIV, generateSalt } = require("./encryption.js");
const { ALGO_DEFAULT } = require("./shared.js");

const DERIVED_KEY_ITERATIONS = 250000;
const METHODS = ["cbc", "gcm"];
const SALT_LENGTH = 12;

function getDefaultOptions() {
    return {
        decryption_cbc: decryptCBC,
        decryption_gcm: decryptGCM,
        derivationRounds: DERIVED_KEY_ITERATIONS,
        deriveKey: pbkdf2,
        encryption_cbc: encryptCBC,
        encryption_gcm: encryptGCM,
        generateIV,
        generateSalt,
        method: ALGO_DEFAULT,
        saltLength: SALT_LENGTH
    };
}

function validateEncryptionMethod(method) {
    if (METHODS.indexOf(method) === -1) {
        throw new Error(`Invalid encryption/decryption method: ${method}`);
    }
}

class Configuration {
    constructor() {
        this._options = getDefaultOptions();
    }

    get options() {
        return Object.assign({}, this._options);
    }

    overrideDecryption(method, func) {
        validateEncryptionMethod(method);
        this._options[`decryption_${method}`] = func || getDefaultOptions()[`decryption_${method}`];
        return this;
    }

    overrideEncryption(method, func) {
        validateEncryptionMethod(method);
        this._options[`encryption_${method}`] = func || getDefaultOptions()[`encryption_${method}`];
        return this;
    }

    overrideIVGeneration(func) {
        this._options.generateIV = func || getDefaultOptions().generateIV;
        return this;
    }

    overrideKeyDerivation(func) {
        this._options.deriveKey = func || getDefaultOptions().deriveKey;
        return this;
    }

    overrideSaltGeneration(func) {
        this._options.generateSalt = func || getDefaultOptions().generateSalt;
        return this;
    }

    reset() {
        this._options = getDefaultOptions();
        return this;
    }

    setDerivationRounds(rounds) {
        if (typeof rounds === "number") {
            this._options.derivationRounds = rounds;
        }
        return this;
    }

    use(method) {
        validateEncryptionMethod(method);
        this._options.method = method;
        return this;
    }
}

Configuration.getDefaultOptions = getDefaultOptions;

module.exports = Configuration;
<commit_msg>Add more docs<commit_after>const { pbkdf2 } = require("./derivation.js");
const { decryptCBC, decryptGCM, encryptCBC, encryptGCM, generateIV, generateSalt } = require("./encryption.js");
const { ALGO_DEFAULT } = require("./shared.js");

const DERIVED_KEY_ITERATIONS = 250000;
const METHODS = ["cbc", "gcm"];
const SALT_LENGTH = 12;

/**
 * @typedef {Object} ConfigurationOptions
 * @property {Function} decryption_cbc - The CBC decryption method
 * @property {Function} decryption_gcm - The GCM decryption method
 * @property {Number} derivationRounds - The number of key derivation iterations
 * @property {Function} deriveKey - The key derivation function (default: PBKDF2)
 * @property {Function} encryption_cbc - The CBC encryption method
 * @property {Function} encryption_gcm - The GCM encryption method
 * @property {Function} generateIV - The IV generation method
 * @property {Function} generateSalt - The salt generation method
 * @property {String} method - The encryption method (cbc/gcm)
 * @property {Number} saltLength - The length of the salt
 */

/**
 * Get the default options
 * @static
 * @returns {ConfigurationOptions} Default configuration options
 * @memberof Configuration
 */
function getDefaultOptions() {
    return {
        decryption_cbc: decryptCBC,
        decryption_gcm: decryptGCM,
        derivationRounds: DERIVED_KEY_ITERATIONS,
        deriveKey: pbkdf2,
        encryption_cbc: encryptCBC,
        encryption_gcm: encryptGCM,
        generateIV,
        generateSalt,
        method: ALGO_DEFAULT,
        saltLength: SALT_LENGTH
    };
}

/**
 * Validate an encryption method specification
 * @param {String} method The method to validate
 * @throws {Error} Throws if the method is not valid
 * @private
 */
function validateEncryptionMethod(method) {
    if (METHODS.indexOf(method) === -1) {
        throw new Error(`Invalid encryption/decryption method: ${method}`);
    }
}

class Configuration {
    constructor() {
        this._options = getDefaultOptions();
    }

    get options() {
        return Object.assign({}, this._options);
    }

    overrideDecryption(method, func) {
        validateEncryptionMethod(method);
        this._options[`decryption_${method}`] = func || getDefaultOptions()[`decryption_${method}`];
        return this;
    }

    overrideEncryption(method, func) {
        validateEncryptionMethod(method);
        this._options[`encryption_${method}`] = func || getDefaultOptions()[`encryption_${method}`];
        return this;
    }

    overrideIVGeneration(func) {
        this._options.generateIV = func || getDefaultOptions().generateIV;
        return this;
    }

    overrideKeyDerivation(func) {
        this._options.deriveKey = func || getDefaultOptions().deriveKey;
        return this;
    }

    overrideSaltGeneration(func) {
        this._options.generateSalt = func || getDefaultOptions().generateSalt;
        return this;
    }

    reset() {
        this._options = getDefaultOptions();
        return this;
    }

    setDerivationRounds(rounds) {
        if (typeof rounds === "number") {
            this._options.derivationRounds = rounds;
        }
        return this;
    }

    use(method) {
        validateEncryptionMethod(method);
        this._options.method = method;
        return this;
    }
}

Configuration.getDefaultOptions = getDefaultOptions;

module.exports = Configuration;
<|endoftext|>


<commit_before>'use strict'
var iop = require('iop')

function convert(a) {
	a = lowerNot(true, a)
	a = eliminateQuantifiers(a)
}

function eliminateQuantifiers(a, bound) {
	switch (a.op) {
	case 'var':
		var val = iop.get(bound, a)
		if (val)
			return val
		return a
	}
	var args = a.args.map(x => eliminateQuantifiers(x, bound))
	return {
		args,
		op: a.op,
	}
}

function lowerNot(sign, a) {
	switch (a.op) {
	case '!':
		var args = a.args.map(x => lowerNot(sign, x))
		return {
			args,
			op: sign ? '!' : '?',
			vars: a.vars,
		}
	case '!=':
		return lowerNot(!sign, {
			args: a.args,
			op: '=',
		})
	case '&':
		var args = a.args.map(x => lowerNot(sign, x))
		return {
			args,
			op: sign ? '&' : '|',
		}
	case '<=>':
		var args = [
			lowerNot(sign, a.args[0]),
			lowerNot(true, a.args[1]),
		]
		return {
			args,
			op: '<=>',
		}
	case '<~>':
		return lowerNot(!sign, {
			args: a.args,
			op: '<=>',
		})
	case '=>':
		var args = [
			{
				args: [a.args[0]],
				op: '~',
			},
			a.args[1],
		]
		return lowerNot(sign, {
			args,
			op: '|',
		})
	case '?':
		var args = a.args.map(x => lowerNot(sign, x))
		return {
			args,
			op: sign ? '?' : '!',
			vars: a.vars,
		}
	case '|':
		var args = a.args.map(x => lowerNot(sign, x))
		return {
			args,
			op: sign ? '|' : '&',
		}
	case '~':
		return lowerNot(!sign, a.args[0])
	case '~&':
		return lowerNot(!sign, {
			args: a.args,
			op: '&',
		})
	case '~|':
		return lowerNot(!sign, {
			args: a.args,
			op: '|',
		})
	}
	if (sign)
		return a
	return {
		args: [a],
		op: '~',
	}
}

exports.convert = convert
<commit_msg>quant<commit_after>'use strict'
var iop = require('iop')

function convert(a) {
	a = lowerNot(true, a)
	a = eliminateQuantifiers(a)
}

function eliminateQuantifiers(a, bound) {
	switch (a.op) {
	case '!':
		var vars = a.vars.map(
			x =>  {
				var y = {
					op: 'var',
				}
				bound = iop.put(bound, x, y)
				return y
			})
		var args = a.args.map(x => eliminateQuantifiers(x, bound))
		return {
			args,
			op: a.op,
			vars,
		}
	case '?':
		var vars = a.vars.map(
			x =>  {
				var skolem = {
					args: vals(bound).filter(a => a.op === 'var'),
					fun: {
						op: 'fun',
					},
					op: 'call',
				}
				bound = iop.put(bound, x, skolem)
				return y
			})
		var args = a.args.map(x => eliminateQuantifiers(x, bound))
		return {
			args,
			op: a.op,
			vars,
		}
	case 'var':
		var val = iop.get(bound, a)
		if (val)
			return val
		return a
	}
	var args = a.args.map(x => eliminateQuantifiers(x, bound))
	return {
		args,
		op: a.op,
	}
}

function lowerNot(sign, a) {
	switch (a.op) {
	case '!':
		var args = a.args.map(x => lowerNot(sign, x))
		return {
			args,
			op: sign ? '!' : '?',
			vars: a.vars,
		}
	case '!=':
		return lowerNot(!sign, {
			args: a.args,
			op: '=',
		})
	case '&':
		var args = a.args.map(x => lowerNot(sign, x))
		return {
			args,
			op: sign ? '&' : '|',
		}
	case '<=>':
		var args = [
			lowerNot(sign, a.args[0]),
			lowerNot(true, a.args[1]),
		]
		return {
			args,
			op: '<=>',
		}
	case '<~>':
		return lowerNot(!sign, {
			args: a.args,
			op: '<=>',
		})
	case '=>':
		var args = [
			{
				args: [a.args[0]],
				op: '~',
			},
			a.args[1],
		]
		return lowerNot(sign, {
			args,
			op: '|',
		})
	case '?':
		var args = a.args.map(x => lowerNot(sign, x))
		return {
			args,
			op: sign ? '?' : '!',
			vars: a.vars,
		}
	case '|':
		var args = a.args.map(x => lowerNot(sign, x))
		return {
			args,
			op: sign ? '|' : '&',
		}
	case '~':
		return lowerNot(!sign, a.args[0])
	case '~&':
		return lowerNot(!sign, {
			args: a.args,
			op: '&',
		})
	case '~|':
		return lowerNot(!sign, {
			args: a.args,
			op: '|',
		})
	}
	if (sign)
		return a
	return {
		args: [a],
		op: '~',
	}
}

function vals(m) {
	for (var r = []; m; m = m.outer)
		r.push(m.val)
	return r
}

exports.convert = convert
<|endoftext|>


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

'use strict';

var path = require('path');
var util = require('generator-util');
var Assemble = require('assemble-core');
var settings = require('./lib/settings');
var plugins = require('./lib/plugins');
var config = require('./lib/config');
var utils = require('./lib/utils');

/**
 * Create an instance of `Generate` with the given `options`
 *
 * ```js
 * var Generate = require('generate');
 * var generate = new Generate();
 * ```
 * @param {Object} `options` Settings to initialize with.
 * @api public
 */

function Generate(options) {
  if (!(this instanceof Generate)) {
    return new Generate(options);
  }
  this.options = utils.extend({}, this.options, options);
  Assemble.call(this, options);
  this.is('Generate');
  this.initGenerate();
}

/**
 * Extend `Assemble`
 */

Assemble.extend(Generate);

/**
 * Initialize verb defaults
 */

Generate.prototype.initGenerate = function(opts) {
  this.name = 'generate';
  this.data({runner: require('./package')});

  this.define('util', utils);
  this.define('lazyCreate', function(name, opts) {
    if (!this[name]) this.create(name, opts);
  });

  this.initPlugins(this.options);
  var plugin = this.plugin;

  this.define('plugin', function(name) {
    var pipeline = this.options.pipeline;
    if (arguments.length === 1 && pipeline) {
      var idx = pipeline.indexOf(name);
      if (idx !== -1) {
        pipeline.splice(idx, 1);
      }
    }
    return plugin.apply(this, arguments);
  });
};

/**
 * Generate prototype methods
 */

Generate.prototype.initPlugins = function() {
  this.use(plugins.generators());
  this.use(plugins.pipeline());
  this.use(plugins.loader());
  this.use(plugins.runner());
  this.use(plugins.runtimes());
  this.use(plugins.rename({replace: true}));
  this.use(plugins.ask());
  this.use(settings());
  this.use(config());

  this.create('templates');
  util.create(this);
  util.dest(this);
  util.src(this);
};

/**
 * Expose `Generate`
 */

module.exports = Generate;
<commit_msg>init code<commit_after>/*!
 * generate <https://github.com/jonschlinkert/generate>
 *
 * Copyright (c) 2015-2016, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var path = require('path');
var util = require('generator-util');
var Assemble = require('assemble-core');
var plugins = require('./lib/plugins');
var utils = require('./lib/utils');

/**
 * Create an instance of `Generate` with the given `options`
 *
 * ```js
 * var Generate = require('generate');
 * var generate = new Generate();
 * ```
 * @param {Object} `options` Settings to initialize with.
 * @api public
 */

function Generate(options) {
  if (!(this instanceof Generate)) {
    return new Generate(options);
  }
  this.options = utils.extend({prefix: 'generate'}, this.options, options);
  Assemble.call(this, options);
  this.initGenerate();
}

/**
 * Extend `Assemble`
 */

Assemble.extend(Generate);

/**
 * Initialize generate defaults
 */

Generate.prototype.initGenerate = function(opts) {
  this.is('generate');
  this.name = 'generate';
  this.data({runner: require('./package')});

  this.define('util', utils);
  this.define('lazyCreate', function(name, opts) {
    if (!this[name]) {
      this.create(name, opts);
    } else {
      this[name].option(opts);
    }
    return this[name];
  });

  this.initPlugins(this.options);
  var plugin = this.plugin;

  this.define('plugin', function(name) {
    var pipeline = this.options.pipeline || [];
    if (arguments.length === 1 && pipeline.length) {
      var idx = pipeline.indexOf(name);
      if (idx !== -1) {
        pipeline.splice(idx, 1);
      }
    } else if (!~pipeline.indexOf(name)) {
      pipeline.push(name);
    }
    plugin.apply(this, arguments);
    return this;
  });
};

/**
 * Generate prototype methods
 */

Generate.prototype.initPlugins = function(opts) {
  this.use(plugins.generators());
  this.use(plugins.pipeline());
  this.use(plugins.runner());
  this.use(plugins.loader());

  if (opts.cli === true || process.env.GENERATE_CLI) {
    this.create('templates');

    this.use(plugins.runtimes(opts));
    this.use(plugins.rename({replace: true}));
    this.use(plugins.ask());

    // modify create, dest and src methods to automatically
    // use cwd from generators unless overridden by the user
    util.create(this);
    util.dest(this);
    util.src(this);
  }
};

/**
 * Expose static `is*` methods from Templates
 */

Assemble._.plugin.is(Generate);

/**
 * Expose `Generate`
 */

module.exports = Generate;
<|endoftext|>


<commit_before>/*
 * Smoke Test
 * =============================================================================
 */

!function(document, batchGl) {
  'use strict';

  // Stub out context.
  var context = { gl: {} };

  /*
   * Pipeline Class Definitions
   * ---------------------------------------------------------------------------
   */

  var LoggingLeaf = batchGl.Leaf.extend({
    init: function(parent, name) {
      this.name = name;
    },
    buffer: function() {
      console.log('Buffering ' + this.name);
    },
    flush: function() {
      console.log('Flushing ' + this.name);
    }
  });

  var Program = batchGl.Step.extend(),
      AttributeSet = batchGl.Step.extend(),
      Texture = batchGl.Step.extend();

  /*
   * Pipeline Setup
   * ---------------------------------------------------------------------------
   */

  var root = new batchGl.Root(context),
        program = new Program(root),
          attribA = new AttributeSet(program),
            textureA = new Texture(attribA),
              leafA = new LoggingLeaf(textureA, 'A'),
            textureB = new Texture(attribA),
              leafB = new LoggingLeaf(textureB, 'B'),
          attribB = new AttributeSet(program),
            textureC = new Texture(attribB),
              leafC = new LoggingLeaf(textureC, 'C'),
              leafD = new LoggingLeaf(textureC, 'D');

  /*
   * Vertices
   * ---------------------------------------------------------------------------
   */

  var vA = new batchGl.VertexSet(leafA),
      vA2 = new batchGl.VertexSet(leafA),
      vB = new batchGl.VertexSet(leafB),
      vC = new batchGl.VertexSet(leafC),
      vC2 = new batchGl.VertexSet(leafC),
      vC3 = new batchGl.VertexSet(leafC),
      vD = new batchGl.VertexSet(leafD);

  /*
   * Rendering
   * ---------------------------------------------------------------------------
   */

  vA.buffer();
  vB.buffer();
  vC2.buffer();
  vC3.buffer();
  vA2.buffer();
  vD.buffer();
  vC.buffer();

  root.render();

}(document, batchGl);
<commit_msg>Move some vertex buffer calls around for testing.<commit_after>/*
 * Smoke Test
 * =============================================================================
 */

!function(document, batchGl) {
  'use strict';

  // Stub out context.
  var context = { gl: {} };

  /*
   * Pipeline Class Definitions
   * ---------------------------------------------------------------------------
   */

  var LoggingLeaf = batchGl.Leaf.extend({
    init: function(parent, name) {
      this.name = name;
    },
    buffer: function() {
      console.log('Buffering ' + this.name);
    },
    flush: function() {
      console.log('Flushing ' + this.name);
    }
  });

  var Program = batchGl.Step.extend(),
      AttributeSet = batchGl.Step.extend(),
      Texture = batchGl.Step.extend();

  /*
   * Pipeline Setup
   * ---------------------------------------------------------------------------
   */

  var root = new batchGl.Root(context),
        program = new Program(root),
          attribA = new AttributeSet(program),
            textureA = new Texture(attribA),
              leafA = new LoggingLeaf(textureA, 'A'),
            textureB = new Texture(attribA),
              leafB = new LoggingLeaf(textureB, 'B'),
          attribB = new AttributeSet(program),
            textureC = new Texture(attribB),
              leafC = new LoggingLeaf(textureC, 'C'),
              leafD = new LoggingLeaf(textureC, 'D');

  /*
   * Vertices
   * ---------------------------------------------------------------------------
   */

  var vA = new batchGl.VertexSet(leafA),
      vA2 = new batchGl.VertexSet(leafA),
      vB = new batchGl.VertexSet(leafB),
      vC = new batchGl.VertexSet(leafC),
      vC2 = new batchGl.VertexSet(leafC),
      vC3 = new batchGl.VertexSet(leafC),
      vD = new batchGl.VertexSet(leafD);

  /*
   * Rendering
   * ---------------------------------------------------------------------------
   */

  vA.buffer();
  vD.buffer();
  vB.buffer();
  vC2.buffer();
  vC3.buffer();
  vA2.buffer();
  vC.buffer();

  root.render();

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


<commit_before>'use strict';

var postcss = require('postcss');
var fs = require('fs');
var path = require('path');

/**
 * Throw a warning if a critical selector is used more than once.
 *
 * @param {array} Array of critical CSS rules.
 * @param {selector} Selector to check for.
 * @return {string} Console warning.
 */
function selectorReuseWarning(rules, selector) {
  return rules.reduce((init, rule) => {
    if (rule.selector === selector) {
      console.warn(`Warning: Selector ${selector} is used more than once.`);
    }
    return rules;
  }, []);
}

/**
 * Identify critical CSS selectors
 *
 * @param {obj} PostCSS CSS object.
 * @return {object} Object containing critical rules, organized by output destination
 */
function getCriticalRules(css) {
  let critical = {};

  css.walkDecls('critical-selector', decl => {
    let dest = getDest(decl.parent);

    if ('undefined' === typeof critical[dest]) {
      critical[dest] = [];
    }

    if (decl.value === 'scope') {
      let childRules = getChildRules(css, decl.parent);

      selectorReuseWarning(critical[dest], decl.parent.selector);
      critical[dest].push(decl.parent);

      if (childRules !== null && childRules.length) {
        childRules.forEach(rule => {
          critical[dest].push(rule);
        });
      }
    } else if (decl.value === 'this') {
      selectorReuseWarning(critical[dest], decl.parent.selector);
      critical[dest].push(decl.parent);
    } else {
      const container = decl.parent;

      container.selector = decl.value.replace(/['"]*/g, '');
      selectorReuseWarning(critical[dest], container.selector);
      critical[dest].push(container);
    }

    decl.remove();
  });

  return critical;
}

/**
 * Identify critical CSS selectors
 *
 * @param {obj} PostCSS CSS object.
 * @return {object} Object containing critical rules, organized by output destination
 */
function getChildRules(css, parent) {
  let ruleList = [];
  let selectorRegExp = new RegExp('^' + parent.selector);
  let childRegExp = new RegExp('^' + parent.selector + ' .*');

  css.walkRules(selectorRegExp, rule => {
    let childMatch = null;

    if (rule.selector !== parent.selector) {
      childMatch = rule.selector.match(childRegExp);

      if (childMatch !== null) {
        ruleList.push(rule);
      }
    }
  });

  return ruleList;
}

/**
 * Identify critical CSS destinations.
 *
 * @param {object} PostCSS rule.
 * @return {array} string corresponding to output destination.
 */
function getDest(selector) {
  let dest = 'critical'

  selector.walkDecls('critical-dest', decl => {
    dest = decl.value.replace(/['"]*/g, '');
    decl.remove();
  });

  return dest;
}

/**
 * Primary plugin function.
 *
 * @param {object} array of options.
 * @return {function} function for PostCSS plugin.
 */
function buildCritical(options) {
  options = Object.assign({
    outputPath: process.cwd()
  }, options || {})

  return (css, result) => {
    let criticalOutput = getCriticalRules(css);

    for (let dest in criticalOutput) {
      let criticalCSS = postcss.parse('');
      let critical = '';
      let rules = [];
      let destfilename = dest == 'critical.css' ? dest : dest + '-critical.css';

      rules = criticalOutput[dest].reduce((init, rule) => {
        rule.walkDecls('critical', (decl) => {
          decl.remove();
        });
        criticalCSS.append(rule);
        return criticalOutput[dest];
      }, {});

      critical = postcss().process(criticalCSS).css;

      fs.writeFile(path.join(options.outputPath, destfilename), critical);
    }
  }
}

module.exports = postcss.plugin('postcss-critical', buildCritical);
<commit_msg>Fix documentation<commit_after>'use strict';

var postcss = require('postcss');
var fs = require('fs');
var path = require('path');

/**
 * Throw a warning if a critical selector is used more than once.
 *
 * @param {array} Array of critical CSS rules.
 * @param {selector} Selector to check for.
 * @return {string} Console warning.
 */
function selectorReuseWarning(rules, selector) {
  return rules.reduce((init, rule) => {
    if (rule.selector === selector) {
      console.warn(`Warning: Selector ${selector} is used more than once.`);
    }
    return rules;
  }, []);
}

/**
 * Identify critical CSS selectors
 *
 * @param {obj} PostCSS CSS object.
 * @return {object} Object containing critical rules, organized by output destination
 */
function getCriticalRules(css) {
  let critical = {};

  css.walkDecls('critical-selector', decl => {
    let dest = getDest(decl.parent);

    if ('undefined' === typeof critical[dest]) {
      critical[dest] = [];
    }

    if (decl.value === 'scope') {
      let childRules = getChildRules(css, decl.parent);

      selectorReuseWarning(critical[dest], decl.parent.selector);
      critical[dest].push(decl.parent);

      if (childRules !== null && childRules.length) {
        childRules.forEach(rule => {
          critical[dest].push(rule);
        });
      }
    } else if (decl.value === 'this') {
      selectorReuseWarning(critical[dest], decl.parent.selector);
      critical[dest].push(decl.parent);
    } else {
      const container = decl.parent;

      container.selector = decl.value.replace(/['"]*/g, '');
      selectorReuseWarning(critical[dest], container.selector);
      critical[dest].push(container);
    }

    decl.remove();
  });

  return critical;
}

/**
 * Get rules for selectors nested within parent node
 *
 * @param {obj} PostCSS CSS object
 * @return {object} Parent rule for which children should be included
 */
function getChildRules(css, parent) {
  let ruleList = [];
  let selectorRegExp = new RegExp('^' + parent.selector);
  let childRegExp = new RegExp('^' + parent.selector + ' .*');

  css.walkRules(selectorRegExp, rule => {
    let childMatch = null;

    if (rule.selector !== parent.selector) {
      childMatch = rule.selector.match(childRegExp);

      if (childMatch !== null) {
        ruleList.push(rule);
      }
    }
  });

  return ruleList;
}

/**
 * Identify critical CSS destinations.
 *
 * @param {object} PostCSS rule.
 * @return {array} string corresponding to output destination.
 */
function getDest(selector) {
  let dest = 'critical'

  selector.walkDecls('critical-dest', decl => {
    dest = decl.value.replace(/['"]*/g, '');
    decl.remove();
  });

  return dest;
}

/**
 * Primary plugin function.
 *
 * @param {object} array of options.
 * @return {function} function for PostCSS plugin.
 */
function buildCritical(options) {
  options = Object.assign({
    outputPath: process.cwd()
  }, options || {})

  return (css, result) => {
    let criticalOutput = getCriticalRules(css);

    for (let dest in criticalOutput) {
      let criticalCSS = postcss.parse('');
      let critical = '';
      let rules = [];
      let destfilename = dest == 'critical.css' ? dest : dest + '-critical.css';

      rules = criticalOutput[dest].reduce((init, rule) => {
        rule.walkDecls('critical', (decl) => {
          decl.remove();
        });
        criticalCSS.append(rule);
        return criticalOutput[dest];
      }, {});

      critical = postcss().process(criticalCSS).css;

      fs.writeFile(path.join(options.outputPath, destfilename), critical);
    }
  }
}

module.exports = postcss.plugin('postcss-critical', buildCritical);
<|endoftext|>


<commit_before>var dgram = require('dgram');
var crypto = require('crypto');
var net = require('net');
var events = require('events');
var bncode = require('bncode');

var RANDOM_BYTES = crypto.randomBytes(20*1024);

var DEFAULT_NODES = [{
	host: 'router.bittorrent.com',
	port: 6881
},{
	host: 'router.utorrent.com',
	port: 6881
},{
	host: 'dht.transmissionbt.com',
	port: 6881
}];

var parseNodeInfo = function(compact) {
	var nodes = [];

	for (var i = 0; i < compact.length; i += 26) {
		nodes.push({
			id: compact.slice(i, i+20),
			host: compact[20+i]+'.'+compact[i+21]+'.'+compact[i+22]+'.'+compact[i+23],
			port: compact.readUInt16BE(i+24)
		});
	};

	return nodes;
};

var parsePeerInfo = function(list) {
	return list.map(function(peer) {
		return {
			host: peer[0]+'.'+peer[1]+'.'+peer[2]+'.'+peer[3],
			port: peer.readUInt16BE(4)
		};
	});
};

var randomOffset = 0;

var Swarm = function(infoHash, options, onconnection) {
	if (!(this instanceof Swarm)) return new Swarm(infoHash, options, onconnection);

	events.EventEmitter.call(this);

	if (typeof options === 'function') {
		onconnection = options;
		options = {};
	}

	options = options || {};

	this.infoHash = typeof infoHash === 'string' ? new Buffer(infoHash, 'hex') : infoHash;
	this.maxSize = options.maxSize || 30;
	this.maxNodes = options.maxNodes || 2500;

	this.connections = [];

	this._nextPeers = [];
	this._nextNodes = [];
	this._discoveredPeers = {};
	this._discoveredNodes = {};
	this._nodeId = RANDOM_BYTES.slice(randomOffset, randomOffset+20);
	this._reconnects = {};

	randomOffset = (randomOffset + 20) % RANDOM_BYTES.length;

	this._dht = dgram.createSocket('udp4');
	this._t = 0;
	this._sent = {};
	this._bootstrap = options.nodes || DEFAULT_NODES;

	if (onconnection) this.on('connection', onconnection);
};

Swarm.prototype.__proto__ = events.EventEmitter.prototype;

Swarm.prototype.__defineGetter__('nodesFound', function() {
	return Object.keys(this._discoveredNodes).length;
});

Swarm.prototype.__defineGetter__('peersFound', function() {
	return Object.keys(this._discoveredPeers).length;
});

Swarm.prototype.__defineGetter__('queued', function() {
	return this._nextPeers.length;
});

Swarm.prototype.reconnect = function(peer) {
	if (typeof peer === 'string') return this.reconnect({host:peer.split(':')[0], port:parseInt(peer.split(':')[1],10)});
	this._nextPeers.push(peer);
	this._connectPeers();
};

Swarm.prototype.addPeer = function(peer) {
	var id = peer.host+':'+peer.port;

	if (this._discoveredPeers[id]) return this._findPeers();
	this._discoveredPeers[id] = true;
	this._nextPeers.push(peer);
	this._connectPeers();
};

Swarm.prototype.addNode = function(node) {
	var id = node.id || node.host+':'+node.port;

	if (Object.keys(this._discoveredNodes).length >= this.maxNodes) return this._findPeers();
	if (this._discoveredNodes[id]) return this._findPeers();

	this._discoveredNodes[id] = {time:Date.now(), node:node};
	this._nextNodes.push(node);
	this._findPeers();
};

Swarm.prototype.listen = function() {
	var self = this;
	var addPeer = this.addPeer.bind(this);
	var addNode = this.addNode.bind(this);

	this._dht.on('error', function(err) {
		// do nothing...
	});

	this._dht.on('message', function(message) {
		try {
			message = bncode.decode(message);
		} catch (err) {
			return;
		}

		var r = message.y.toString() === 'r' && message.r;
		if (!r) return;

		delete self._sent[message.t.toString()];

		var values = r && r.values && parsePeerInfo(r.values);
		if (values) values.forEach(addPeer);

		var nodes = r && r.nodes && parseNodeInfo(r.nodes);
		if (nodes) nodes.forEach(addNode);
	});

	var gc = function() {
		var now = Date.now();

		Object.keys(self._sent).forEach(function(t) {
			var sent = self._sent[t];

			if (now - sent.time < self.tries * 2500) return;
			if (sent.tries >= 5) return delete self._sent[t];

			sent.tries++;
			self._dht.send(sent.message, 0, sent.message.length, sent.node.port, sent.node.host);
		});
	};

	var reset = function() {
		var nodes = self._discoveredNodes;
		var now = Date.now();

		Object.keys(nodes).some(function(id) {
			if (now - nodes[id].time < 90000) return true;
			var node = nodes[id].node;
			delete nodes[id];
			self.addNode(node);
		});
	};

	setInterval(gc, 2000);
	setInterval(reset, 10000);
	this._bootstrap.forEach(addNode);
	return this;
};

Swarm.prototype._connectPeers = function() {
	this._findPeers(); // find more peers!

	if (this.connections.length >= this.maxSize || !this._nextPeers.length) return;

	var self = this;
	var peer = this._nextPeers.pop();
	var socket = net.connect(peer.port, peer.host, {allowHalfOpen:false});
	var id = peer.host+':'+peer.port;

	var onend = function() {
		var index = self.connections.indexOf(socket);
		if (index > -1) self.connections.splice(index, 1);
		self._connectPeers();
	};

	var timeout = setTimeout(socket.destroy.bind(socket), 4000);

	socket.on('error', onend);
	socket.on('end', onend);
	socket.on('close', onend);

	self.connections.push(socket);

	socket.once('connect', function() {
		clearTimeout(timeout);
		self.emit('connection', socket, id, peer);
	});
};

Swarm.prototype._findPeers = function() {
	if (this._nextPeers.length > 2*this.maxSize || !this._nextNodes.length) return;
	if (Object.keys(this._sent).length > Math.max(this.maxSize - this._nextPeers.length, 5)) return;

	var node = this._nextNodes.pop();
	var t = ''+(this._t++);
	var message = bncode.encode({t:t, y:'q', q:'get_peers', a:{id:this._nodeId, info_hash:this.infoHash}});

	this._dht.send(message, 0, message.length, node.port, node.host);
	this._sent[t] = {node:node, message:message, time:Date.now(), tries:1};
};

module.exports = Swarm;<commit_msg>swarm will continue to try and reconnect good peers<commit_after>// TODO: refactor this completely!

var dgram = require('dgram');
var crypto = require('crypto');
var net = require('net');
var events = require('events');
var bncode = require('bncode');

var RANDOM_BYTES = crypto.randomBytes(20*1024);

var DEFAULT_NODES = [{
	host: 'router.bittorrent.com',
	port: 6881
},{
	host: 'router.utorrent.com',
	port: 6881
},{
	host: 'dht.transmissionbt.com',
	port: 6881
}];

var parseNodeInfo = function(compact) {
	var nodes = [];

	for (var i = 0; i < compact.length; i += 26) {
		nodes.push({
			id: compact.slice(i, i+20),
			host: compact[20+i]+'.'+compact[i+21]+'.'+compact[i+22]+'.'+compact[i+23],
			port: compact.readUInt16BE(i+24)
		});
	};

	return nodes;
};

var parsePeerInfo = function(list) {
	return list.map(function(peer) {
		return {
			host: peer[0]+'.'+peer[1]+'.'+peer[2]+'.'+peer[3],
			port: peer.readUInt16BE(4)
		};
	});
};

var randomOffset = 0;

var Swarm = function(infoHash, options, onconnection) {
	if (!(this instanceof Swarm)) return new Swarm(infoHash, options, onconnection);

	events.EventEmitter.call(this);

	if (typeof options === 'function') {
		onconnection = options;
		options = {};
	}

	options = options || {};

	this.infoHash = typeof infoHash === 'string' ? new Buffer(infoHash, 'hex') : infoHash;
	this.maxSize = options.maxSize || 30;
	this.maxNodes = options.maxNodes || 2500;

	this.connections = [];

	this._nextPeers = [];
	this._nextNodes = [];
	this._discoveredPeers = {};
	this._discoveredNodes = {};
	this._nodeId = RANDOM_BYTES.slice(randomOffset, randomOffset+20);
	this._reconnects = {};
	this._reconnecting = {};

	randomOffset = (randomOffset + 20) % RANDOM_BYTES.length;

	this._dht = dgram.createSocket('udp4');
	this._t = 0;
	this._sent = {};
	this._bootstrap = options.nodes || DEFAULT_NODES;

	if (onconnection) this.on('connection', onconnection);
};

Swarm.prototype.__proto__ = events.EventEmitter.prototype;

Swarm.prototype.__defineGetter__('nodesFound', function() {
	return Object.keys(this._discoveredNodes).length;
});

Swarm.prototype.__defineGetter__('peersFound', function() {
	return Object.keys(this._discoveredPeers).length;
});

Swarm.prototype.__defineGetter__('queued', function() {
	return this._nextPeers.length;
});

Swarm.prototype.reconnect = function(peer) {
	if (typeof peer === 'string') return this.reconnect({host:peer.split(':')[0], port:parseInt(peer.split(':')[1],10)});
	var id = peer.host+':'+peer.port;
	this._reconnects[id] = 0;
	this._reconnect(id, peer);
};

Swarm.prototype.addPeer = function(peer) {
	var id = peer.host+':'+peer.port;

	if (this._discoveredPeers[id]) return this._findPeers();
	this._discoveredPeers[id] = true;
	this._nextPeers.push(peer);
	this._connectPeers();
};

Swarm.prototype.addNode = function(node) {
	var id = node.id || node.host+':'+node.port;

	if (Object.keys(this._discoveredNodes).length >= this.maxNodes) return this._findPeers();
	if (this._discoveredNodes[id]) return this._findPeers();

	this._discoveredNodes[id] = {time:Date.now(), node:node};
	this._nextNodes.push(node);
	this._findPeers();
};

Swarm.prototype.listen = function() {
	var self = this;
	var addPeer = this.addPeer.bind(this);
	var addNode = this.addNode.bind(this);

	this._dht.on('error', function(err) {
		// do nothing...
	});

	this._dht.on('message', function(message) {
		try {
			message = bncode.decode(message);
		} catch (err) {
			return;
		}

		var r = message.y.toString() === 'r' && message.r;
		if (!r) return;

		delete self._sent[message.t.toString()];

		var values = r && r.values && parsePeerInfo(r.values);
		if (values) values.forEach(addPeer);

		var nodes = r && r.nodes && parseNodeInfo(r.nodes);
		if (nodes) nodes.forEach(addNode);
	});

	var gc = function() {
		var now = Date.now();

		Object.keys(self._sent).forEach(function(t) {
			var sent = self._sent[t];

			if (now - sent.time < self.tries * 2500) return;
			if (sent.tries >= 5) return delete self._sent[t];

			sent.tries++;
			self._dht.send(sent.message, 0, sent.message.length, sent.node.port, sent.node.host);
		});
	};

	var reset = function() {
		var nodes = self._discoveredNodes;
		var now = Date.now();

		Object.keys(nodes).some(function(id) {
			if (now - nodes[id].time < 90000) return true;
			var node = nodes[id].node;
			delete nodes[id];
			self.addNode(node);
		});
	};

	setInterval(gc, 2000);
	setInterval(reset, 10000);
	this._bootstrap.forEach(addNode);
	return this;
};

Swarm.prototype._connectPeers = function() {
	this._findPeers(); // find more peers!

	if (this.connections.length >= this.maxSize || !this._nextPeers.length) return;

	var self = this;
	var peer = this._nextPeers.pop();
	var socket = net.connect(peer.port, peer.host, {allowHalfOpen:false});
	var id = peer.host+':'+peer.port;

	var onend = function() {
		var index = self.connections.indexOf(socket);
		if (index > -1) self.connections.splice(index, 1);
		if (index > -1 && self._reconnects[id]) self._reconnect(id, peer);
		self._connectPeers();
	};

	var timeout = setTimeout(socket.destroy.bind(socket), 4000);

	socket.on('error', onend);
	socket.on('end', onend);
	socket.on('close', onend);

	self.connections.push(socket);

	socket.once('connect', function() {
		clearTimeout(timeout);
		self.emit('connection', socket, id, peer);
	});
};

Swarm.prototype._findPeers = function() {
	if (this._nextPeers.length > 2*this.maxSize || !this._nextNodes.length) return;
	if (Object.keys(this._sent).length > Math.max(this.maxSize - this._nextPeers.length, 5)) return;

	var node = this._nextNodes.pop();
	var t = ''+(this._t++);
	var message = bncode.encode({t:t, y:'q', q:'get_peers', a:{id:this._nodeId, info_hash:this.infoHash}});

	this._dht.send(message, 0, message.length, node.port, node.host);
	this._sent[t] = {node:node, message:message, time:Date.now(), tries:1};
};

Swarm.prototype._reconnect = function(id, peer) {
	if (this._reconnecting[id]) return;

	var self = this;
	var reconnect = function() {
		self._reconnecting[id] = null;
		self._nextPeers.push(peer);
		self._connectPeers();
	};

	this._reconnects[id] = (this._reconnects[id] || 0) + 1;
	this._reconnecting[id] = setTimeout(reconnect, this._reconnects[id] * 5000);
};

module.exports = Swarm;<|endoftext|>


<commit_before>/*jshint node: true */
'use strict';
var fs = require('fs');
var path = require('path');
var mergeTrees = require('broccoli-merge-trees');
var Funnel = require('broccoli-funnel');

module.exports = {
  name: 'ember-data-factory-guy',

  treeForApp: function(appTree) {
    var trees = [appTree];

    if (this.includeFactoryGuyFiles) {
      try {
        if (fs.statSync('tests/factories').isDirectory()) {
          var factoriesTree = new Funnel('tests/factories', {
            destDir: 'tests/factories'
          });
          trees.push(factoriesTree);
        }
      } catch (err) {
        // do nothing;
      }
    }

    return mergeTrees(trees);
  },

  included: function(app) {
    this._super.included(app);
    this.app = app;

    this.setupFactoryGuyInclude(app);

    if (this.includeFactoryGuyFiles) {
      app.import(path.join(app.bowerDirectory, 'jquery-mockjax', 'dist', 'jquery.mockjax.js'));
    }
  },

  setupFactoryGuyInclude: function(app) {
    let defaultEnabled = /test|development/.test(app.env);
    let defaultSettings = { enabled: defaultEnabled, useScenarios: false };
    let userSettings = app.project.config(app.env).factoryGuy || {};
    let settings = Object.assign(defaultSettings, userSettings);
    if (settings.useScenarios) { settings.enabled = true; }

    this.includeFactoryGuyFiles = settings.enabled;
    // Have to be carefull not to exclude factory guy from addon tree
    // in development or test env
    let trees = /test|development/.test(app.env) ? 'app' : 'app|addon';
    this.treeExcludeRegex = new RegExp(trees);
  },

  treeFor: function(name) {
    // Not sure why this is necessary, but this stops the factory guy files
    // from being added to app tree. Would have thought that this would have
    // happened in treeForApp above, but not the case
    if (!this.includeFactoryGuyFiles && this.treeExcludeRegex && this.treeExcludeRegex.test(name)) {
      return;
    }
    return this._super.treeFor.apply(this, arguments);
  }
};
<commit_msg>No need to include mockjax from bower anymore.<commit_after>/*jshint node: true */
'use strict';
var fs = require('fs');
var path = require('path');
var mergeTrees = require('broccoli-merge-trees');
var Funnel = require('broccoli-funnel');

module.exports = {
  name: 'ember-data-factory-guy',

  treeForApp: function(appTree) {
    var trees = [appTree];

    if (this.includeFactoryGuyFiles) {
      try {
        if (fs.statSync('tests/factories').isDirectory()) {
          var factoriesTree = new Funnel('tests/factories', {
            destDir: 'tests/factories'
          });
          trees.push(factoriesTree);
        }
      } catch (err) {
        // do nothing;
      }
    }

    return mergeTrees(trees);
  },

  included: function(app) {
    this._super.included(app);
    this.app = app;

    this.setupFactoryGuyInclude(app);
  },

  setupFactoryGuyInclude: function(app) {
    let defaultEnabled = /test|development/.test(app.env);
    let defaultSettings = { enabled: defaultEnabled, useScenarios: false };
    let userSettings = app.project.config(app.env).factoryGuy || {};
    let settings = Object.assign(defaultSettings, userSettings);
    if (settings.useScenarios) { settings.enabled = true; }

    this.includeFactoryGuyFiles = settings.enabled;
    // Have to be carefull not to exclude factory guy from addon tree
    // in development or test env
    let trees = /test|development/.test(app.env) ? 'app' : 'app|addon';
    this.treeExcludeRegex = new RegExp(trees);
  },

  treeFor: function(name) {
    // Not sure why this is necessary, but this stops the factory guy files
    // from being added to app tree. Would have thought that this would have
    // happened in treeForApp above, but not the case
    if (!this.includeFactoryGuyFiles && this.treeExcludeRegex && this.treeExcludeRegex.test(name)) {
      return;
    }
    return this._super.treeFor.apply(this, arguments);
  }
};
<|endoftext|>


<commit_before>angular.module('npact')
  .constant('npactConstants', {
    graphSpecDefaults: {
      // TODO: determine me dynamically
      leftPadding: 120,

      axisLabelFontsize: 11,
      axisFontcolor: "#444",
      axisTitleFontsize: 20,
      borderColor: "#444",
      rightPadding: 25,
      height: 200,
      profileTicks: 5,

      // header labels and arrows
      headerY: 5,
      headerLabelPadding: 10,
      headerLabelFontcolor: "#444",
      headerLabelFontsize: 11,
      headerArrowHeight: 12,
      headerArrowWidth: 6,
      headerArrowFontsize: 9,
      axisTitle: '% GC'

    },
    lineColors : {
      r: "red",
      g: "blue",
      b: "green"
    },
    colorBlindLineColors : {
      r: "rgb(213, 94, 0)",
      g: "rgb(204, 121, 167)",
      b: "rgb(0, 114, 178)"
    },
    // how much vertical space to leave for different kinds of headers
    headerSizes:{'extracts': 30, 'hits': 20}
  })

  .factory('GraphDealer', function($log, Utils, $q, $rootScope, GraphingCalculator, npactConstants, ExtractParser, HitsParser) {
    // the `GraphDealer` hands out graph data and processes events
    var hasProfileData = false,
        _onProfileData = $q.defer(),
        onProfileData = _onProfileData.promise,
        _onWidth = $q.defer(),
        onWidth = _onWidth.promise,
        pendingRedraws = 0,
        opts = {
          basesPerGraph: 10000,
          colorBlindFriendly: false,
          page: 0,
          offset: 0,
          graphsPerPage: 5,
          startBase: 0,
          endBase: 0,
          get length(){ return this.endBase - this.startBase; },
          profile: null,
          extracts: {},
          hits: {},
          graphSpecs: [],
          get maxPages (){
            return Math.ceil(this.length / this.basesPerGraph*this.graphsPerPage);
          },
          get hasPreviousPage(){ return this.page > 0; },
          get hasNextPage(){ return this.page < this.maxPages; }
        };

    // once we have data, load it and rebuild the graphs
    onProfileData.then(loadProfileData).then(rebuildGraphs);

    // public interface
    return {
      opts:opts,
      setProfile:function(profile){
        $log.log('setProfile', profile.length);
        _onProfileData.resolve(profile);
        return onProfileData;
      },

      addExtract:function(exopts){
        return addHeader(opts.extracts, ExtractParser, exopts.name, exopts.data);
      },
      addHits: function(exopts) {
        return addHeader(opts.hits, HitsParser, exopts.name, exopts.data);
      },

      setColors:function(colorBlindFriendly){
        $log.log('setColors', arguments);
        opts.colorBlindFriendly = colorBlindFriendly;
        // TODO: lighter change here; see if we can update colors
        // in-place without a full rebuild
        rebuildGraphs();
      },
      setZoom:function(basesPerGraph){
        $log.log('setZoom', arguments);
        opts.basesPerGraph = basesPerGraph;
        rebuildGraphs();
      },
      zoomTo: zoomTo,
      panTo: panTo,
      nextPage: function(){
        $log.log('nextPage', arguments);
        opts.page++;
        rebuildGraphs();
      },
      previousPage: function(){
        $log.log('previousPage', arguments);
        opts.page--;
        rebuildGraphs();
      },
      setWidth: function(w){
        $log.log('setting graph width to', w);
        // let folks know it's ready
        _onWidth.resolve(w);

        // TODO: handle changing this after the fact
      }
    };
    function addHeader(collection, parser, name, data) {
        $log.log('addHeader', name);

        return parser.parseAsync(data)
          .then(function(data){
            $log.log('parsed ', name, hasProfileData);
            // save it for later
            collection[name] = data;
            // if we've got profile data already, rebuild
            if(hasProfileData){
              // TODO: maybe a simpler way to add extracts to existing
              // graphs?
              rebuildGraphs();
            }
            // if we're still waiting on profile data, then when it hits
            // this extract will be processed.
          }, function(){
            $log.log('failed to parse', name, arguments);
          });

    }

    function zoomTo(startBase, zoomPct, zoomingOut){
      // TODO: make this a options object
      var res = GraphingCalculator.zoom(startBase, zoomPct, opts.basesPerGraph, opts.offset, zoomingOut);
      opts.offset = res.offset;
      opts.basesPerGraph = res.basesPerGraph;
      rebuildGraphs();
    }

    /**
     * pan all the graphs
     *
     * @param {Number} oldStartBase - the start of the pan, in gene space
     * @param {Number} newStartBase - the end of the pan, in gene space
     */
    function panTo(oldStartBase, newStartBase){
      var offset = Math.floor(newStartBase - oldStartBase);
      opts.offset += offset;
      $log.log('panTo', opts.offset);
      rebuildGraphs();
    }

    function makeGraphSpec(startBase, width){
      var endBase = startBase + opts.basesPerGraph,
          spec = angular.extend({
            startBase: startBase,
            endBase: endBase,
            extracts: {},
            hits: {},
            profile: [],
            headers: [],
            width: width,
            colors: opts.colorBlindFriendly
              ? npactConstants.colorBlindLineColors
              : npactConstants.lineColors,

            // how much space should be taken by the line graph alone
            get profileHeight(){
              // TODO: reduce duplication between here and GraphingCalculator
              return this.height - this.headerY - this.axisLabelFontsize
                - 2*this.profileTicks;
            },
            get range() {return [this.startBase, this.endBase];}
          }, npactConstants.graphSpecDefaults);

      return spec;
    }

    function makeGraphSpecs(width){
      var base = opts.page * opts.basesPerGraph * opts.graphsPerPage
            + opts.offset;
      return _.range(0, opts.graphsPerPage)
        .map(function(n){
          return makeGraphSpec(base + n*opts.basesPerGraph, width);
        });
    }

    function loadProfileData(profile){
      hasProfileData = true;
      opts.profile = profile;
      var start = profile[0],
          end = _.last(profile);

      opts.startBase = start.coordinate;
      opts.endBase = end.coordinate;

      // find a sensible zoom level
      var basesPerGraph = opts.length / opts.graphsPerPage;
      // if we're really short, reset out bases per graph
      if (basesPerGraph < opts.basesPerGraph) {
        opts.basesPerGraph = Utils.orderOfMagnitude(basesPerGraph);
      }
      return profile; // enable chaining
    }

    /**
     * distribute profile data to the graph specs
     *
     * @param {Array} graphSpecs - list of graph specifications
     * @returns {Promise} list of modified graph specifications
     */
    function attachProfileData(graphSpecs){
      // assumes the profile is ordered by coordinate from low to high
      // eg `[{coordinate: 0}, {coordinate: 10}]`

      // reset the profiles
      graphSpecs.forEach(function(gs){ gs.profile = []; });

      // want to grab data a little out of range so we can scroll a
      // little bit
      var margin = Utils.orderOfMagnitude(opts.basesPerGraph, -1);
      // TODO: reduce duplication between here and
      // `GraphingCalculator.stops`
      return onProfileData.then(function(profile){

        graphSpecs.forEach(function(gs){
          var startIdx = sortedIdx(gs.startBase - margin) - 1,
              endIdx = sortedIdx(gs.endBase + margin) + 1;

          // shallow copy of the relevant data, guarding against
          // out-of-bounds indexes
          gs.profile = profile.slice(Math.max(startIdx,0),
                                     Math.min(endIdx, profile.length - 1));
        });

        return graphSpecs;

        // search for the index in our profile where we would insert `c`
        // and have it still be sorted
        function sortedIdx(c){
          return _.sortedIndex(profile, {'coordinate': c}, 'coordinate');
        }
      });
    }

    function attachAllData(graphSpecs, key) {
      var promises = [];
      // iterate over the named extracts
      _.forOwn(opts[key], function(data, name){
        promises.push(attachData(graphSpecs, name, key));
      });
      return $q.all(promises).then(function(){ return graphSpecs;});
    }

    function attachData(graphSpecs, name, key) {
      var headerHeight = npactConstants.headerSizes[key];

      graphSpecs.forEach(function(gs){
        gs[key][name] = [];
        gs.headers.push({
          text: name,
          lineType:key,
          y: gs.headerY,
          height: headerHeight
        });
        // increment where the next header will start
        gs.headerY += headerHeight;
      });

      // TODO: use _.sortedIndex to binary search and array.slice to
      // make shallow copies onto the graph specs
      return Utils.forEachAsync(opts[key][name], function(dataPoint){
        graphSpecs.forEach(function(gs){
          // extract starts in this range?
          var startsInRange = dataPoint.start >= gs.startBase &&
                dataPoint.start <= gs.endBase,
              // extract ends in this range?
              endsInRange = dataPoint.end >= gs.startBase &&
                dataPoint.end <= gs.endBase;
          if(startsInRange || endsInRange){
            gs[key][name].push(dataPoint);
          }
        });
      })
      // promise resolves as the graphspecs
        .then(function(){ return graphSpecs;});
    }

    function redrawRequest(){
      pendingRedraws++;
      return function(graphSpecs){
        pendingRedraws--;
        if(pendingRedraws == 0){
          return redraw(graphSpecs);
        }else{
          $log.log('skipping redraw, still have pending work');
        }

        return graphSpecs;
      };
    }

    /**
     * tell the world to redraw everything
     */
    function redraw(graphSpecs){
      $rootScope.graphSpecs = graphSpecs;
      graphSpecs.forEach(function(spec){
        spec.chart = GraphingCalculator.chart(spec);
        spec.xaxis = GraphingCalculator.xaxis(spec);
      });

      opts.visible = {
        startBase : _(graphSpecs).pluck('startBase').min().value(),
        endBase : _(graphSpecs).pluck('endBase').max().value()
      };
      return graphSpecs;
    }

    function rebuildGraphs(){
      var t1 = new Date();
      return onWidth.then(makeGraphSpecs)
        .then(attachProfileData)
        .then(_.partialRight(attachAllData, 'extracts'))
        .then(_.partialRight(attachAllData, 'hits'))
        .then(function(graphSpecs){
          return opts.graphSpecs = graphSpecs;
        })
        .then(redrawRequest())
        .then(function(graphSpecs){
          $log.log('rebuild:', new Date() - t1, 'ms');
          return graphSpecs;
        }).catch(function(){
          $log.log('failed to rebuild, resetting state', arguments);
          pendingRedraws = 0;
        });
    }
  });
<commit_msg>jshint fixes<commit_after>angular.module('npact')
  .constant('npactConstants', {
    graphSpecDefaults: {
      // TODO: determine me dynamically
      leftPadding: 120,

      axisLabelFontsize: 11,
      axisFontcolor: '#444',
      axisTitleFontsize: 20,
      borderColor: '#444',
      rightPadding: 25,
      height: 200,
      profileTicks: 5,

      // header labels and arrows
      headerY: 5,
      headerLabelPadding: 10,
      headerLabelFontcolor: '#444',
      headerLabelFontsize: 11,
      headerArrowHeight: 12,
      headerArrowWidth: 6,
      headerArrowFontsize: 9,
      axisTitle: '% GC'

    },
    lineColors : {
      r: 'red',
      g: 'blue',
      b: 'green'
    },
    colorBlindLineColors : {
      r: 'rgb(213, 94, 0)',
      g: 'rgb(204, 121, 167)',
      b: 'rgb(0, 114, 178)'
    },
    // how much vertical space to leave for different kinds of headers
    headerSizes:{'extracts': 30, 'hits': 20}
  })

  .factory('GraphDealer', function($log, Utils, $q, $rootScope, GraphingCalculator, npactConstants, ExtractParser, HitsParser) {
    'use strict';
    // the `GraphDealer` hands out graph data and processes events
    var hasProfileData = false,
        _onProfileData = $q.defer(),
        onProfileData = _onProfileData.promise,
        _onWidth = $q.defer(),
        onWidth = _onWidth.promise,
        pendingRedraws = 0,
        opts = {
          basesPerGraph: 10000,
          colorBlindFriendly: false,
          page: 0,
          offset: 0,
          graphsPerPage: 5,
          startBase: 0,
          endBase: 0,
          get length(){ return this.endBase - this.startBase; },
          profile: null,
          extracts: {},
          hits: {},
          graphSpecs: [],
          get maxPages (){
            return Math.ceil(this.length / this.basesPerGraph*this.graphsPerPage);
          },
          get hasPreviousPage(){ return this.page > 0; },
          get hasNextPage(){ return this.page < this.maxPages; }
        };

    // once we have data, load it and rebuild the graphs
    onProfileData.then(loadProfileData).then(rebuildGraphs);

    // public interface
    return {
      opts:opts,
      setProfile:function(profile){
        $log.log('setProfile', profile.length);
        _onProfileData.resolve(profile);
        return onProfileData;
      },

      addExtract:function(exopts){
        return addHeader(opts.extracts, ExtractParser, exopts.name, exopts.data);
      },
      addHits: function(exopts) {
        return addHeader(opts.hits, HitsParser, exopts.name, exopts.data);
      },

      setColors:function(colorBlindFriendly){
        $log.log('setColors', arguments);
        opts.colorBlindFriendly = colorBlindFriendly;
        // TODO: lighter change here; see if we can update colors
        // in-place without a full rebuild
        rebuildGraphs();
      },
      setZoom:function(basesPerGraph){
        $log.log('setZoom', arguments);
        opts.basesPerGraph = basesPerGraph;
        rebuildGraphs();
      },
      zoomTo: zoomTo,
      panTo: panTo,
      nextPage: function(){
        $log.log('nextPage', arguments);
        opts.page++;
        rebuildGraphs();
      },
      previousPage: function(){
        $log.log('previousPage', arguments);
        opts.page--;
        rebuildGraphs();
      },
      setWidth: function(w){
        $log.log('setting graph width to', w);
        // let folks know it's ready
        _onWidth.resolve(w);

        // TODO: handle changing this after the fact
      }
    };
    function addHeader(collection, parser, name, data) {
        $log.log('addHeader', name);

        return parser.parseAsync(data)
          .then(function(data){
            $log.log('parsed ', name, hasProfileData);
            // save it for later
            collection[name] = data;
            // if we've got profile data already, rebuild
            if(hasProfileData){
              // TODO: maybe a simpler way to add extracts to existing
              // graphs?
              rebuildGraphs();
            }
            // if we're still waiting on profile data, then when it hits
            // this extract will be processed.
          }, function(){
            $log.log('failed to parse', name, arguments);
          });

    }

    function zoomTo(startBase, zoomPct, zoomingOut){
      // TODO: make this a options object
      var res = GraphingCalculator.zoom(startBase, zoomPct, opts.basesPerGraph, opts.offset, zoomingOut);
      opts.offset = res.offset;
      opts.basesPerGraph = res.basesPerGraph;
      rebuildGraphs();
    }

    /**
     * pan all the graphs
     *
     * @param {Number} oldStartBase - the start of the pan, in gene space
     * @param {Number} newStartBase - the end of the pan, in gene space
     */
    function panTo(oldStartBase, newStartBase){
      var offset = Math.floor(newStartBase - oldStartBase);
      opts.offset += offset;
      $log.log('panTo', opts.offset);
      rebuildGraphs();
    }

    function makeGraphSpec(startBase, width){
      var endBase = startBase + opts.basesPerGraph,
          spec = angular.extend({
            startBase: startBase,
            endBase: endBase,
            extracts: {},
            hits: {},
            profile: [],
            headers: [],
            width: width,
            colors: opts.colorBlindFriendly ? npactConstants.colorBlindLineColors
              : npactConstants.lineColors,

            // how much space should be taken by the line graph alone
            get profileHeight(){
              // TODO: reduce duplication between here and GraphingCalculator
              return this.height - this.headerY - this.axisLabelFontsize -
                2*this.profileTicks;
            },
            get range() {return [this.startBase, this.endBase];}
          }, npactConstants.graphSpecDefaults);

      return spec;
    }

    function makeGraphSpecs(width){
      var base = opts.page * opts.basesPerGraph * opts.graphsPerPage +
            opts.offset;
      return _.range(0, opts.graphsPerPage)
        .map(function(n){
          return makeGraphSpec(base + n*opts.basesPerGraph, width);
        });
    }

    function loadProfileData(profile){
      hasProfileData = true;
      opts.profile = profile;
      var start = profile[0],
          end = _.last(profile);

      opts.startBase = start.coordinate;
      opts.endBase = end.coordinate;

      // find a sensible zoom level
      var basesPerGraph = opts.length / opts.graphsPerPage;
      // if we're really short, reset out bases per graph
      if (basesPerGraph < opts.basesPerGraph) {
        opts.basesPerGraph = Utils.orderOfMagnitude(basesPerGraph);
      }
      return profile; // enable chaining
    }

    /**
     * distribute profile data to the graph specs
     *
     * @param {Array} graphSpecs - list of graph specifications
     * @returns {Promise} list of modified graph specifications
     */
    function attachProfileData(graphSpecs){
      // assumes the profile is ordered by coordinate from low to high
      // eg `[{coordinate: 0}, {coordinate: 10}]`

      // reset the profiles
      graphSpecs.forEach(function(gs){ gs.profile = []; });

      // want to grab data a little out of range so we can scroll a
      // little bit
      var margin = Utils.orderOfMagnitude(opts.basesPerGraph, -1);
      // TODO: reduce duplication between here and
      // `GraphingCalculator.stops`
      return onProfileData.then(function(profile){

        graphSpecs.forEach(function(gs){
          var startIdx = sortedIdx(gs.startBase - margin) - 1,
              endIdx = sortedIdx(gs.endBase + margin) + 1;

          // shallow copy of the relevant data, guarding against
          // out-of-bounds indexes
          gs.profile = profile.slice(Math.max(startIdx,0),
                                     Math.min(endIdx, profile.length - 1));
        });

        return graphSpecs;

        // search for the index in our profile where we would insert `c`
        // and have it still be sorted
        function sortedIdx(c){
          return _.sortedIndex(profile, {'coordinate': c}, 'coordinate');
        }
      });
    }

    function attachAllData(graphSpecs, key) {
      var promises = [];
      // iterate over the named extracts
      _.forOwn(opts[key], function(data, name){
        promises.push(attachData(graphSpecs, name, key));
      });
      return $q.all(promises).then(function(){ return graphSpecs;});
    }

    function attachData(graphSpecs, name, key) {
      var headerHeight = npactConstants.headerSizes[key];

      graphSpecs.forEach(function(gs){
        gs[key][name] = [];
        gs.headers.push({
          text: name,
          lineType:key,
          y: gs.headerY,
          height: headerHeight
        });
        // increment where the next header will start
        gs.headerY += headerHeight;
      });

      // TODO: use _.sortedIndex to binary search and array.slice to
      // make shallow copies onto the graph specs
      return Utils.forEachAsync(opts[key][name], function(dataPoint){
        graphSpecs.forEach(function(gs){
          // extract starts in this range?
          var startsInRange = dataPoint.start >= gs.startBase &&
                dataPoint.start <= gs.endBase,
              // extract ends in this range?
              endsInRange = dataPoint.end >= gs.startBase &&
                dataPoint.end <= gs.endBase;
          if(startsInRange || endsInRange){
            gs[key][name].push(dataPoint);
          }
        });
      })
      // promise resolves as the graphspecs
        .then(function(){ return graphSpecs;});
    }

    function redrawRequest(){
      pendingRedraws++;
      return function(graphSpecs){
        pendingRedraws--;
        if(pendingRedraws === 0){
          return redraw(graphSpecs);
        }else{
          $log.log('skipping redraw, still have pending work');
        }

        return graphSpecs;
      };
    }

    /**
     * tell the world to redraw everything
     */
    function redraw(graphSpecs){
      $rootScope.graphSpecs = graphSpecs;
      graphSpecs.forEach(function(spec){
        spec.chart = GraphingCalculator.chart(spec);
        spec.xaxis = GraphingCalculator.xaxis(spec);
      });

      opts.visible = {
        startBase : _(graphSpecs).pluck('startBase').min().value(),
        endBase : _(graphSpecs).pluck('endBase').max().value()
      };
      return graphSpecs;
    }

    function rebuildGraphs(){
      var t1 = new Date();
      return onWidth.then(makeGraphSpecs)
        .then(attachProfileData)
        .then(_.partialRight(attachAllData, 'extracts'))
        .then(_.partialRight(attachAllData, 'hits'))
        .then(function(graphSpecs){
          return (opts.graphSpecs = graphSpecs);
        })
        .then(redrawRequest())
        .then(function(graphSpecs){
          $log.log('rebuild:', new Date() - t1, 'ms');
          return graphSpecs;
        }).catch(function(){
          $log.log('failed to rebuild, resetting state', arguments);
          pendingRedraws = 0;
        });
    }
  });
<|endoftext|>


<commit_before>'use strict';

var inherit = require('inherit'),
    q = require('q'),
    childProcess = require('child_process'),
    util = require('util'),
    EventEmitter = require('events').EventEmitter,
    debug = require('debug')('ssh-tun'),
    ActivityWatcher = require('./activity-watcher');

var DEFAULTS = {
    MAX_RETRIES: 5,
    CONNECT_TIMEOUT: 10000,
    SSH_PORT: 22
};

var Tunnel = inherit(EventEmitter, {
    /**
     * Constuctor
     * @param {object} opts tunnel options
     * @param {string} opts.host remote host address
     * @param {object} opts.ports remote host ports range
     * @param {number} opts.localport local port number
     * @param {string} [opts.user] remote host user
     * @param {string} [opts.sshPort=22] host port to create tunnel
     * @param {number} [opts.maxRetries=5] max attempts to create tunnel
     * @param {number} [opts.connectTimeout=10000] ssh connect timeout
     * @param {boolean} [opts.strictHostKeyChecking=true] verify host authenticity
     * @param {string} [opts.identity] private key for public key authentication
     * @param {boolean} [opts.compression] use compression
     * @param {number} [opts.inactivityTimeout] inactivity timeout (including keep-alive pings)
     */
    __constructor: function (opts) {
        EventEmitter.call(this);

        this.host = opts.host;
        this.port = this._generateRandomPort(opts.ports);
        this._sshPort = opts.sshPort || DEFAULTS.SSH_PORT;
        this.user = opts.user;
        this.proxyHost = util.format('%s:%d', this.host, this.port);
        this.proxyUrl = this.proxyHost; // deprecated, use proxyHost
        this.connected = false;
        this._localPort = opts.localport;
        this._connectTimeout = opts.connectTimeout || DEFAULTS.CONNECT_TIMEOUT;
        this._tunnel = null;
        this._tunnelDeferred = q.defer();
        this._closeDeferred = q.defer();
        this._strictHostKeyChecking = opts.strictHostKeyChecking === undefined ? true : opts.strictHostKeyChecking;
        this._compression = opts.compression;
        this._identity = opts.identity;

        this._activityWatcher = opts.inactivityTimeout > 0 ?
            new ActivityWatcher(opts.inactivityTimeout, this.close.bind(this)) : null;
    },

    /**
     * Tries to open ssh connection to remote server
     * @returns {Promise}
     */
    open: function () {
        var _this = this;

        console.info('INFO: creating tunnel to %s', this.proxyHost);

        var cmd = this._buildSSHArgs();
        debug('running ssh: ssh', cmd.join(' '));

        this._tunnel = childProcess.spawn('ssh', cmd);

        var cleanup = function () {
            _this._tunnel.stderr.removeAllListeners('data');
        };

        var onData = function (data) {
            if (_this._activityWatcher) {
                debug('data:', data.toString());
                _this._activityWatcher.update();
            }

            if (/success/.test(data)) {
                if (!_this._activityWatcher) {
                    cleanup();
                }

                return _this._resolveTunnel();
            }

            if (!_this.connected && /failed/.test(data)) {
                return _this._rejectTunnel();
            }
        };

        this._tunnel.stderr.on('data', onData);

        this._tunnel.on('exit', function (code, signal) {
            _this.emit('exit', code, signal);
        });

        this._tunnel.on('close', function (code, signal) {
            _this.emit('close', code, signal);
            return _this._closeTunnel(code);
        });

        this._tunnel.on('error', function () {
            return _this._rejectTunnel();
        });

        return _this._tunnelDeferred.promise.timeout(this._connectTimeout);
    },

    /**
     * Closes connection. If no connection established does nothing
     * @returns {Promise}
     */
    close: function () {
        if (!this._tunnel) {
            return q();
        }

        var _this = this;

        this._tunnel.kill('SIGTERM');

        return this._closeDeferred.promise.timeout(3000).fail(function () {
            _this._tunnel.kill('SIGKILL');
            return _this._closeTunnel(-1);
        });
    },

    _resolveTunnel: function () {
        console.info('INFO: Tunnel created to %s', this.proxyHost);

        if (this._activityWatcher) {
            debug('start activity watcher');
            this._activityWatcher.start();
        }

        this.connected = true;
        this._tunnelDeferred.resolve();
    },

    _rejectTunnel: function () {
        var message = util.format('ERROR: failed to create tunnel to %s.', this.proxyHost),
            error = new Error(message);

        console.info(message);
        this._tunnelDeferred.reject(error);
    },

    _closeTunnel: function (exitCode) {
        console.info('INFO: Tunnel to %s closed. Exit code: %d', this.proxyHost, exitCode);

        this.connected = false;
        this._closeDeferred.resolve();
    },

    _buildSSHArgs: function () {
        return [
            util.format('-R %d:localhost:%d', this.port, this._localPort),
            '-N',
            '-v',
            this._strictHostKeyChecking === false ? '-o StrictHostKeyChecking=no' : '',
            this._compression !== undefined ?
                util.format('-o Compression=%s', this._compression ? 'yes' : 'no')
                : '',
            this._identity ? util.format('-i %s', this._identity) : '',
            util.format('-p %d', this._sshPort),
            (this.user ? this.user + '@' : '') + this.host
        ].filter(Boolean);
    },

    _generateRandomPort: function (ports) {
        var min = ports.min,
            max = ports.max;

        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
});

/**
 * Tries to open tunnel several times
 * @param {object} opts opts which will be passed to created tunnel
 * @param {number} retries amount of retries to open tunnel
 * @returns {Promise}
 */
Tunnel.openWithRetries = function (opts, retries) {
    retries = retries || DEFAULTS.MAX_RETRIES;

    function retry_(retriesLeft) {
        if (!retriesLeft) {
            return q.reject(util.format('ERROR: failed to create tunnel after %d attempts', retries));
        }

        var tunnel = new Tunnel(opts);

        return tunnel.open()
            .then(function () {
                return q.resolve(tunnel);
            })
            .fail(function () {
                return tunnel.close()
                    .then(retry_.bind(null, retriesLeft - 1));
            });
    }

    return retry_(retries);
};

module.exports = Tunnel;
<commit_msg>feat: conditional debug<commit_after>'use strict';

var inherit = require('inherit'),
    q = require('q'),
    childProcess = require('child_process'),
    util = require('util'),
    EventEmitter = require('events').EventEmitter,
    debug = require('debug')('ssh-tun'),
    ActivityWatcher = require('./activity-watcher');

var DEFAULTS = {
    MAX_RETRIES: 5,
    CONNECT_TIMEOUT: 10000,
    SSH_PORT: 22
};

var Tunnel = inherit(EventEmitter, {
    /**
     * Constuctor
     * @param {object} opts tunnel options
     * @param {string} opts.host remote host address
     * @param {object} opts.ports remote host ports range
     * @param {number} opts.localport local port number
     * @param {string} [opts.user] remote host user
     * @param {string} [opts.sshPort=22] host port to create tunnel
     * @param {number} [opts.maxRetries=5] max attempts to create tunnel
     * @param {number} [opts.connectTimeout=10000] ssh connect timeout
     * @param {boolean} [opts.strictHostKeyChecking=true] verify host authenticity
     * @param {string} [opts.identity] private key for public key authentication
     * @param {boolean} [opts.compression] use compression
     * @param {number} [opts.inactivityTimeout] inactivity timeout (including keep-alive pings)
     */
    __constructor: function (opts) {
        EventEmitter.call(this);

        this.host = opts.host;
        this.port = this._generateRandomPort(opts.ports);
        this._sshPort = opts.sshPort || DEFAULTS.SSH_PORT;
        this.user = opts.user;
        this.proxyHost = util.format('%s:%d', this.host, this.port);
        this.proxyUrl = this.proxyHost; // deprecated, use proxyHost
        this.connected = false;
        this._localPort = opts.localport;
        this._connectTimeout = opts.connectTimeout || DEFAULTS.CONNECT_TIMEOUT;
        this._tunnel = null;
        this._tunnelDeferred = q.defer();
        this._closeDeferred = q.defer();
        this._strictHostKeyChecking = opts.strictHostKeyChecking === undefined ? true : opts.strictHostKeyChecking;
        this._compression = opts.compression;
        this._identity = opts.identity;

        this._activityWatcher = opts.inactivityTimeout > 0 ?
            new ActivityWatcher(opts.inactivityTimeout, this.close.bind(this)) : null;
    },

    /**
     * Tries to open ssh connection to remote server
     * @returns {Promise}
     */
    open: function () {
        var _this = this;

        console.info('INFO: creating tunnel to %s', this.proxyHost);

        var cmd = this._buildSSHArgs();
        debug('running ssh: ssh', cmd.join(' '));

        this._tunnel = childProcess.spawn('ssh', cmd);
        this._tunnel.stderr.on('data', this._onData.bind(this));

        this._tunnel.on('exit', function (code, signal) {
            _this.emit('exit', code, signal);
        });

        this._tunnel.on('close', function (code, signal) {
            _this.emit('close', code, signal);
            return _this._closeTunnel(code);
        });

        this._tunnel.on('error', function () {
            return _this._rejectTunnel();
        });

        return _this._tunnelDeferred.promise.timeout(this._connectTimeout);
    },

    /**
     * Closes connection. If no connection established does nothing
     * @returns {Promise}
     */
    close: function () {
        if (!this._tunnel) {
            return q();
        }

        var _this = this;

        this._tunnel.kill('SIGTERM');

        return this._closeDeferred.promise.timeout(3000).fail(function () {
            _this._tunnel.kill('SIGKILL');
            return _this._closeTunnel(-1);
        });
    },

    _onData: function (data) {
        if (debug.enabled) {
            debug('data:', data.toString());
        }

        if (this._activityWatcher) {
            this._activityWatcher.update();
        }

        if (/success/.test(data)) {
            if (!this._activityWatcher) {
                this._tunnel.stderr.removeAllListeners('data');
            }

            return this._resolveTunnel();
        }

        if (!this.connected && /failed/.test(data)) {
            return this._rejectTunnel();
        }
    },

    _resolveTunnel: function () {
        console.info('INFO: Tunnel created to %s', this.proxyHost);

        if (this._activityWatcher) {
            debug('start activity watcher');
            this._activityWatcher.start();
        }

        this.connected = true;
        this._tunnelDeferred.resolve();
    },

    _rejectTunnel: function () {
        var message = util.format('ERROR: failed to create tunnel to %s.', this.proxyHost),
            error = new Error(message);

        console.info(message);
        this._tunnelDeferred.reject(error);
    },

    _closeTunnel: function (exitCode) {
        console.info('INFO: Tunnel to %s closed. Exit code: %d', this.proxyHost, exitCode);

        this.connected = false;
        this._closeDeferred.resolve();
    },

    _buildSSHArgs: function () {
        return [
            util.format('-R %d:localhost:%d', this.port, this._localPort),
            '-N',
            '-v',
            this._strictHostKeyChecking === false ? '-o StrictHostKeyChecking=no' : '',
            this._compression !== undefined ?
                util.format('-o Compression=%s', this._compression ? 'yes' : 'no')
                : '',
            this._identity ? util.format('-i %s', this._identity) : '',
            util.format('-p %d', this._sshPort),
            (this.user ? this.user + '@' : '') + this.host
        ].filter(Boolean);
    },

    _generateRandomPort: function (ports) {
        var min = ports.min,
            max = ports.max;

        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
});

/**
 * Tries to open tunnel several times
 * @param {object} opts opts which will be passed to created tunnel
 * @param {number} retries amount of retries to open tunnel
 * @returns {Promise}
 */
Tunnel.openWithRetries = function (opts, retries) {
    retries = retries || DEFAULTS.MAX_RETRIES;

    function retry_(retriesLeft) {
        if (!retriesLeft) {
            return q.reject(util.format('ERROR: failed to create tunnel after %d attempts', retries));
        }

        var tunnel = new Tunnel(opts);

        return tunnel.open()
            .then(function () {
                return q.resolve(tunnel);
            })
            .fail(function () {
                return tunnel.close()
                    .then(retry_.bind(null, retriesLeft - 1));
            });
    }

    return retry_(retries);
};

module.exports = Tunnel;
<|endoftext|>


<commit_before>import React, { Component } from 'react';

import ToolBar      from './src/components/toolbar'
import Alert        from './src/components/alert'
import Buttons      from './src/components/button'
import Dropdowns    from './src/components/dropdown'
import Switch       from './src/components/switch'
import Modal        from './src/components/modal'

// XXX: backward compat
let ActionBar = ToolBar

export {ActionBar, ToolBar, Alert, Buttons, Dropdowns, Modal, Switch}
<commit_msg>export Navbar<commit_after>import React, { Component } from 'react';

import Navbar       from './src/components/navbar'
import Alert        from './src/components/alert'
import Buttons      from './src/components/button'
import Dropdowns    from './src/components/dropdown'
import Switch       from './src/components/switch'
import Modal        from './src/components/modal'

// XXX: backward compat
let ActionBar = Navbar

export {ActionBar, Navbar, Alert, Buttons, Dropdowns, Modal, Switch}
<|endoftext|>


<commit_before>'use strict'

var visit = require('unist-util-visit')

module.exports = getDefinitionFactory

var own = {}.hasOwnProperty

/* Get a definition in `node` by `identifier`. */
function getDefinitionFactory(node, options) {
  return getterFactory(gather(node, options))
}

/* Gather all definitions in `node` */
function gather(node, options) {
  var cache = {}

  if (!node || !node.type) {
    throw new Error('mdast-util-definitions expected node')
  }

  visit(node, 'definition', options && options.commonmark ? commonmark : normal)

  return cache

  function commonmark(definition) {
    var id = normalise(definition.identifier)
    if (!own.call(cache, id)) {
      cache[id] = definition
    }
  }

  function normal(definition) {
    cache[normalise(definition.identifier)] = definition
  }
}

/* Factory to get a node from the given definition-cache. */
function getterFactory(cache) {
  return getter

  /* Get a node from the bound definition-cache. */
  function getter(identifier) {
    var id = identifier && normalise(identifier)
    return id && own.call(cache, id) ? cache[id] : null
  }
}

function normalise(identifier) {
  return identifier.toUpperCase()
}
<commit_msg>Refactor comments<commit_after>'use strict'

var visit = require('unist-util-visit')

module.exports = getDefinitionFactory

var own = {}.hasOwnProperty

// Get a definition in `node` by `identifier`.
function getDefinitionFactory(node, options) {
  return getterFactory(gather(node, options))
}

// Gather all definitions in `node`
function gather(node, options) {
  var cache = {}

  if (!node || !node.type) {
    throw new Error('mdast-util-definitions expected node')
  }

  visit(node, 'definition', options && options.commonmark ? commonmark : normal)

  return cache

  function commonmark(definition) {
    var id = normalise(definition.identifier)
    if (!own.call(cache, id)) {
      cache[id] = definition
    }
  }

  function normal(definition) {
    cache[normalise(definition.identifier)] = definition
  }
}

// Factory to get a node from the given definition-cache.
function getterFactory(cache) {
  return getter

  // Get a node from the bound definition-cache.
  function getter(identifier) {
    var id = identifier && normalise(identifier)
    return id && own.call(cache, id) ? cache[id] : null
  }
}

function normalise(identifier) {
  return identifier.toUpperCase()
}
<|endoftext|>


<commit_before>var LimitsUI = (function(){
    "use strict";

    function fillLimitsTable(limits){
        var open_positions = addComma(limits['open_positions']);
        var account_balance = addComma(limits['account_balance']);
        var daily_turnover = addComma(limits['daily_turnover']);
        var payout = addComma(limits['payout']);

        document.getElementById('item').textContent = Content.localize().textItem;

        var currency = TUser.get().currency;
        if (currency === "") {
            var login = TUser.get().loginid;

            if (/^CR.*$/.test(login)) {
                currency = "USD";
            } else if (/^MF.*$/.test(login) || /^MLT.*$/.test(login)){
                currency = "EUR";
            } else if (/^MX.*$/.test(login)) {
                currency = "GBP";
            }
        }

        document.getElementById('limit').textContent = Content.localize().textLimit + " (" + currency + ")";

        $('#max-open-position').prepend(Content.localize().textMaxOpenPosition);
        document.getElementById('max-open-position-tooltip').setAttribute('title', Content.localize().textMaxOpenPositionTooltip);
        document.getElementById('open-positions').textContent = open_positions;

        $('#max-acc-balance').prepend(Content.localize().textMaxAccBalance);
        document.getElementById('max-acc-balance-tooltip').setAttribute('title', Content.localize().textMaxAccBalanceTooltip);
        document.getElementById('account-balance').textContent = account_balance;

        $('#max-daily-turnover').prepend(Content.localize().textMaxDailyTurnover);
        document.getElementById('max-daily-turnover-tooltip').setAttribute('title', Content.localize().textMaxDailyTurnoverTooltip);
        document.getElementById('daily-turnover').textContent = daily_turnover;

        $('#max-aggregate').prepend(Content.localize().textMaxAggregate);
        document.getElementById('max-aggregate-tooltip').setAttribute('title', Content.localize().textMaxAggregateTooltip);
        document.getElementById('payout').textContent = payout;
    }

    function clearTableContent(){
        Table.clearTableBody(tableID);
        $("#limits-title>tfoot").hide();
    }

    function addComma(num){
        if (num % 1 !== 0) {
            num = num.toFixed(2);
        }
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    return {
        clearTableContent: clearTableContent,
        fillLimitsTable: fillLimitsTable,
        addComma: addComma
    };
}());
<commit_msg>remove currency if not set<commit_after>var LimitsUI = (function(){
    "use strict";

    function fillLimitsTable(limits){
        var open_positions = addComma(limits['open_positions']);
        var account_balance = addComma(limits['account_balance']);
        var daily_turnover = addComma(limits['daily_turnover']);
        var payout = addComma(limits['payout']);

        document.getElementById('item').textContent = Content.localize().textItem;

        var currency = TUser.get().currency;
        var limit = document.getElementById('limit');
        if (currency === "") {
            limit.textContent = Content.localize().textLimit;
        } else {
            limit.textContent = Content.localize().textLimit + " (" + currency + ")";
        }
        $('#max-open-position').prepend(Content.localize().textMaxOpenPosition);
        document.getElementById('max-open-position-tooltip').setAttribute('title', Content.localize().textMaxOpenPositionTooltip);
        document.getElementById('open-positions').textContent = open_positions;

        $('#max-acc-balance').prepend(Content.localize().textMaxAccBalance);
        document.getElementById('max-acc-balance-tooltip').setAttribute('title', Content.localize().textMaxAccBalanceTooltip);
        document.getElementById('account-balance').textContent = account_balance;

        $('#max-daily-turnover').prepend(Content.localize().textMaxDailyTurnover);
        document.getElementById('max-daily-turnover-tooltip').setAttribute('title', Content.localize().textMaxDailyTurnoverTooltip);
        document.getElementById('daily-turnover').textContent = daily_turnover;

        $('#max-aggregate').prepend(Content.localize().textMaxAggregate);
        document.getElementById('max-aggregate-tooltip').setAttribute('title', Content.localize().textMaxAggregateTooltip);
        document.getElementById('payout').textContent = payout;
    }

    function clearTableContent(){
        Table.clearTableBody(tableID);
        $("#limits-title>tfoot").hide();
    }

    function addComma(num){
        if (num % 1 !== 0) {
            num = num.toFixed(2);
        }
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    return {
        clearTableContent: clearTableContent,
        fillLimitsTable: fillLimitsTable,
        addComma: addComma
    };
}());
<|endoftext|>