<commit_before>var PENDING = 0;
var FULFILLED = 1;
var REJECTED = 2;
// 空操作
function noop() {};
// isArray
var _isArray = undefined;
if (!Array.isArray) {
  _isArray = function (a) {
    return Object.prototype.toString.call(a) === '[object Array]';
  }
}
else {
  _isArray = Array.isArray
}
var isArray = _isArray;

/**
 * @class Promise
 * @param {[type]} resolver [function]
 */
function Promise(resolver) {
  this._state = PENDING;
  this._result = undefined;
  this._subscribers = [];
  // 初始化跑一遍resolver()
  if (noop !== resolver) {
    typeof resolver !== 'function' && needsResolver();
    this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  }
};
Promise.resolve = resolve;
Promise.reject  = reject;
Promise.all     = all;
Promise.race    = race;

Promise.prototype = {
  constructor: Promise,
  then: then,
  'catch': function _catch(onRejection) {
    return this.then(null, onRejection);
  }
};
function needsResolver() {
  throw new TypeError('You must pass a resolver function as the first argument to the promise constructor')
}
function needsNew() {
  throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")
}
/**
 * [initializePromise 初始化Promise并执行resolver回调]
 * @param  {[type]} promise  [Promise对象]
 * @param  {[type]} resolver [resolver回调]
 */
function initializePromise(promise, resolver) {
  try {
    resolver(function resolvePromise(value) {
      _resolve(promise, value);
    }, function rejectPromise(reason) {
      _reject(promise, reason);
    });
  } catch (e) {
    _reject(promise, e);
  }
}
/**
 * [_resolve resolve处理]
 * @param  {[type]} promise [Promise对象]
 * @param  {[type]} value   [回调参数]
 */
function _resolve (promise, value) {
    if (promise._state !== PENDING) {
      return;
    }
    promise._result = value;
    promise._state = FULFILLED;
}
/**
 * [_resolve reject处理]
 * @param  {[type]} promise [Promise对象]
 * @param  {[type]} value   [回调参数]
 */
function _reject(promise, reason) {
  if (promise._state !== PENDING) {
    return;
  }
  promise._result = reason;
  promise._state = REJECTED;
}
function ErrorObject () {
  this.error = null;
}
var TRY_CATCH_ERROR = new ErrorObject();
/**
 * [then 异步回调]
 * @param  {[function]} resolve [resolve回调]
 * @param  {[function]} reject  [reject回调]
 */
function then (resolve, reject) {
  var _arguments = arguments;
  var parent = this;
  var child = new this.constructor(noop);

  var _state = parent._state;
  var callback = _arguments[_state - 1];
  if (child._state !== PENDING) {
    // noop
  }else if (_state === FULFILLED) {
    _resolve(child, parent._result);
  }else if (_state === REJECTED) {
    _reject(child, parent._result);
  }
  if (typeof callback === 'function') {
    try {
      nextTick(callback, parent._result);
    } catch (e) {
      TRY_CATCH_ERROR.error = e;
      return TRY_CATCH_ERROR;
    }
  }
  return child;
}

function resolve (object) {
  var Constructor = this;
  // 如果传进来的参数是一个Promise对象，则直接返回该参数
  if (object && typeof object === 'object' && object.constructor === Constructor) {
    return object;
  }

  var promise = new Constructor(noop)
  _resolve(promise, object);
  return promise;
}

function reject (reason) {
  var Constructor = this;
  var promise = new Constructor(noop);
  _reject(promise, reason);
  return promise
}

function all (entries) {
  return new Enumerator(this, entries).promise;
}

function Enumerator (Constructor, input) {
  this._instanceConstructor = Constructor;
  this.promise = new Constructor(noop);

  if (isArray(input)) {
    this._input = input;
    this.length = input.length;

    this._result = new Array(this.length);

    if (this.length === 0) {
      _resolve(this.promise, this._result);
    } else {
      this._enumerate();
    }
  }
  else {
    _reject(this.promise, validationError())
  }
}
function validationError() {
  return new Error('Array Methods must be provided an Array');
}
Enumerator.prototype._enumerate = function () {
  var _input = this._input;
  var promise = this.promise;
  for (var i = 0, l = _input.length; i < l; i++) {
    var currentPromise = _input[i];
    if (!(currentPromise instanceof Promise) || currentPromise._state === PENDING) {
      currentPromise = resolve(currentPromise);
      promise._result[i] = currentPromise._result;
    }
    if (currentPromise._state === REJECTED) {
      promise._result = currentPromise._result;
    }
    promise._state = currentPromise._state;
  }
}

function race (entries) {
  var Constructor = this;

  if (!isArray(entries)) {
    return new Constructor(function(_, reject) {
      return reject(new TypeError('You must pass an array to race.'))
    });
  }
  else {
    return new Constructor(function (resolve, reject) {
      var length = entries.length;
      for (var i = 0; i < length; i++) {
        Constructor.resolve(entries[i]).then(resolve, reject);
      }
    });
  }
}

/**
 * [nextTick 下一进程处理]
 * @param  {Function} callback [回调函数]
 * @param  {[type]}   value    [回调参数值]
 */
function nextTick (callback, value) {
  setTimeout(callback, 0, value);
}
<commit_msg>[T] polyfill for event loop<commit_after>var PENDING = 0;
var FULFILLED = 1;
var REJECTED = 2;
// 空操作
function noop() {};
// isArray
var _isArray = undefined;
if (!Array.isArray) {
  _isArray = function (a) {
    return Object.prototype.toString.call(a) === '[object Array]';
  }
}
else {
  _isArray = Array.isArray
}
var isArray = _isArray;

/**
 * @class Promise
 * @param {[type]} resolver [function]
 */
function Promise(resolver) {
  this._state = PENDING;
  this._result = undefined;
  this._subscribers = [];
  // 初始化跑一遍resolver()
  if (noop !== resolver) {
    typeof resolver !== 'function' && needsResolver();
    this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  }
};
Promise.resolve = resolve;
Promise.reject  = reject;
Promise.all     = all;
Promise.race    = race;

Promise.prototype = {
  constructor: Promise,
  then: then,
  'catch': function _catch(onRejection) {
    return this.then(null, onRejection);
  }
};
function needsResolver() {
  throw new TypeError('You must pass a resolver function as the first argument to the promise constructor')
}
function needsNew() {
  throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")
}
/**
 * [initializePromise 初始化Promise并执行resolver回调]
 * @param  {[type]} promise  [Promise对象]
 * @param  {[type]} resolver [resolver回调]
 */
function initializePromise(promise, resolver) {
  try {
    resolver(function resolvePromise(value) {
      _resolve(promise, value);
    }, function rejectPromise(reason) {
      _reject(promise, reason);
    });
  } catch (e) {
    _reject(promise, e);
  }
}
/**
 * [_resolve resolve处理]
 * @param  {[type]} promise [Promise对象]
 * @param  {[type]} value   [回调参数]
 */
function _resolve (promise, value) {
    if (promise._state !== PENDING) {
      return;
    }
    promise._result = value;
    promise._state = FULFILLED;
}
/**
 * [_resolve reject处理]
 * @param  {[type]} promise [Promise对象]
 * @param  {[type]} value   [回调参数]
 */
function _reject(promise, reason) {
  if (promise._state !== PENDING) {
    return;
  }
  promise._result = reason;
  promise._state = REJECTED;
}
function ErrorObject () {
  this.error = null;
}
var TRY_CATCH_ERROR = new ErrorObject();
/**
 * [then 异步回调]
 * @param  {[function]} resolve [resolve回调]
 * @param  {[function]} reject  [reject回调]
 */
function then (resolve, reject) {
  var _arguments = arguments;
  var parent = this;
  var child = new this.constructor(noop);

  var _state = parent._state;
  var callback = _arguments[_state - 1];
  if (child._state !== PENDING) {
    // noop
  }else if (_state === FULFILLED) {
    _resolve(child, parent._result);
  }else if (_state === REJECTED) {
    _reject(child, parent._result);
  }
  if (typeof callback === 'function') {
    try {
      nextTick(callback, parent._result);
    } catch (e) {
      TRY_CATCH_ERROR.error = e;
      return TRY_CATCH_ERROR;
    }
  }
  return child;
}

function resolve (object) {
  var Constructor = this;
  // 如果传进来的参数是一个Promise对象，则直接返回该参数
  if (object && typeof object === 'object' && object.constructor === Constructor) {
    return object;
  }

  var promise = new Constructor(noop)
  _resolve(promise, object);
  return promise;
}

function reject (reason) {
  var Constructor = this;
  var promise = new Constructor(noop);
  _reject(promise, reason);
  return promise
}

function all (entries) {
  return new Enumerator(this, entries).promise;
}

function Enumerator (Constructor, input) {
  this._instanceConstructor = Constructor;
  this.promise = new Constructor(noop);

  if (isArray(input)) {
    this._input = input;
    this.length = input.length;

    this._result = new Array(this.length);

    if (this.length === 0) {
      _resolve(this.promise, this._result);
    } else {
      this._enumerate();
    }
  }
  else {
    _reject(this.promise, validationError())
  }
}
function validationError() {
  return new Error('Array Methods must be provided an Array');
}
Enumerator.prototype._enumerate = function () {
  var _input = this._input;
  var promise = this.promise;
  for (var i = 0, l = _input.length; i < l; i++) {
    var currentPromise = _input[i];
    if (!(currentPromise instanceof Promise) || currentPromise._state === PENDING) {
      currentPromise = resolve(currentPromise);
      promise._result[i] = currentPromise._result;
    }
    if (currentPromise._state === REJECTED) {
      promise._result = currentPromise._result;
    }
    promise._state = currentPromise._state;
  }
}

function race (entries) {
  var Constructor = this;

  if (!isArray(entries)) {
    return new Constructor(function(_, reject) {
      return reject(new TypeError('You must pass an array to race.'))
    });
  }
  else {
    return new Constructor(function (resolve, reject) {
      var length = entries.length;
      for (var i = 0; i < length; i++) {
        Constructor.resolve(entries[i]).then(resolve, reject);
      }
    });
  }
}

/**
 * [nextTick 下一进程处理]
 * @param  {Function} callback [回调函数]
 * @param  {[type]}   value    [回调参数值]
 */
function nextTick (callback, value) {
  setTimeout(callback, 0, value);
}

/**
 * var browserWindow = typeof window !== 'undefined' ? window : undefined;
 * var browserGlobal = browserWindow || {};
 * var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
 * var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
 *
 * // test for web worker but not in IE10
 * var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
 */

/**
 *
// node
function useNextTick() {
  // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  // see https://github.com/cujojs/when/issues/410 for details
  return function () {
    return process.nextTick(flush);
  };
}

// vertx
function useVertxTimer() {
  if (typeof vertxNext !== 'undefined') {
    return function () {
      vertxNext(flush);
    };
  }

  return useSetTimeout();
}

function useMutationObserver() {
  var iterations = 0;
  var observer = new BrowserMutationObserver(flush);
  var node = document.createTextNode('');
  observer.observe(node, { characterData: true });

  return function () {
    node.data = iterations = ++iterations % 2;
  };
}

// web worker
function useMessageChannel() {
  var channel = new MessageChannel();
  channel.port1.onmessage = flush;
  return function () {
    return channel.port2.postMessage(0);
  };
}

function useSetTimeout() {
  // Store setTimeout reference so es6-promise will be unaffected by
  // other code modifying setTimeout (like sinon.useFakeTimers())
  var globalSetTimeout = setTimeout;
  return function () {
    return globalSetTimeout(flush, 1);
  };
}
var len = 0;
var queue = new Array(1000);
function flush() {
  for (var i = 0; i < len; i += 2) {
    var callback = queue[i];
    var arg = queue[i + 1];

    callback(arg);

    queue[i] = undefined;
    queue[i + 1] = undefined;
  }

  len = 0;
}
 */<|endoftext|>


<commit_before>CKEDITOR.plugins.add('readmore',
    {
        icons: 'readmore',
        init : function(editor) {
            var pluginName = 'readmore';
            var mypath = this.path;
            editor.ui.addButton(
                'readmore',
                {
                    label : "Readmore",
                    command : 'readmore.cmd',
                    icon : mypath + 'images/icon.png'
                }
            );
            var cmd = editor.addCommand('readmore.cmd', {
               exec : function(editor)
               {
                 editor.insertHtml( '
' );
               }
            });

        }
    }
);

function showDialogPlugin(e){
    e.openDialog('readmore.dlg');
}<commit_msg>re #416 if there is a read more in the text the button will not add another one.<commit_after>CKEDITOR.plugins.add('readmore',
    {
        icons: 'readmore',
        init : function(editor) {
            var pluginName = 'readmore';
            var mypath = this.path;
            editor.ui.addButton(
                'readmore',
                {
                    label : "Readmore",
                    command : 'readmore.cmd',
                    icon : mypath + 'images/icon.png'
                }
            );
            var cmd = editor.addCommand('readmore.cmd', {

               exec : function(editor)
               {
                   var readmore = editor.document.$.getElementsByTagName("hr");
                   if(readmore.length == 0){
                    editor.insertHtml( '
' );
                   }
               }

            });

        }
    }
);

function showDialogPlugin(e){
    e.openDialog('readmore.dlg');
}<|endoftext|>


<commit_before>var Class = function(upper, init) {

    var toString = Object.prototype.toString
    var slice = [].slice

    function isFunction(f) {
        return toString.call(f) == '[object Function]'
    }

    function inherit(cls, upper) {
        function F(){}
        F.prototype = upper.prototype
        cls.prototype = new F()
        cls.prototype.constructor = cls
        cls.__parent__ = cls.prototype.__parent__ = upper

        // copy static members
        for (var prop in upper) {
            if (upper.hasOwnProperty(prop)) {
                cls[prop] = upper[prop]
            }
        }
    }

    if (arguments.length == 1) {
        init = upper
        upper = Object
    }

    var cls = function() {
        // __init__ as initializer
        this.__init__ && this.__init__.apply(this, arguments)
    }

    upper && inherit(cls, upper)

    var obj = {}

    isFunction(init) && init.call(obj)

    function wrap(name, func) {
        if (!isFunction(func)) {
            return func
        }
        var wrapped = function() {
            var args = slice.call(arguments)
            // set "this" as the first param
            args.unshift(this)
            return func.apply(this, args)
        }
        // remember func name, for finding
        func.__name__ = wrapped.__name__ = name
        return wrapped
    }

    // static members in __static__
    var statics = obj['__static__']
    if (statics) {
        for(var prop in statics) {
            cls[prop] = statics[prop]
        }
        delete obj['__static__']
    }

    for (var prop in obj) {
        if (prop == 'parent') {
            console.error('[pyclass error] parent is preserved word for pyclass');
            continue;
        }
        if (obj.hasOwnProperty(prop)) {
            // wrap function, add self as the first param
            cls.prototype[prop] = wrap(prop, obj[prop])
        }
    }

    // make self.parent() available
    cls.prototype.parent = function() {
        var name = arguments.callee.caller.__name__
        if (!name) {
            return console.error('[pyclass error] parent() should not be called in nested function')
        }
        this.__parent__.prototype[name].apply(this, arguments)
    }

    return cls
}

if (typeof module != 'undefined') {
    module.exports = Class
}<commit_msg>upper<commit_after>var Class = function(upper, init) {

    var toString = Object.prototype.toString
    var slice = [].slice

    function isFunction(f) {
        return toString.call(f) == '[object Function]'
    }

    function inherit(cls, upper) {
        function F(){}
        F.prototype = upper.prototype
        cls.prototype = new F()
        cls.prototype.constructor = cls
        cls.__parent__ = cls.prototype.__parent__ = upper

        // copy static members
        for (var prop in upper) {
            if (upper.hasOwnProperty(prop)) {
                cls[prop] = upper[prop]
            }
        }
    }

    if (arguments.length == 1) {
        init = upper
        upper = Object
    }

    var cls = function() {
        // __init__ as initializer
        this.__init__ && this.__init__.apply(this, arguments)
    }

    upper && inherit(cls, upper)

    var obj = {}

    isFunction(init) && init.call(obj)

    function wrap(name, func) {
        if (!isFunction(func)) {
            return func
        }
        var wrapped = function() {
            var args = slice.call(arguments)
            // set "this" as the first param
            args.unshift(this)
            return func.apply(this, args)
        }
        // remember func name, for finding
        func.__name__ = wrapped.__name__ = name
        return wrapped
    }

    // static members in __static__
    var statics = obj['__static__']
    if (statics) {
        for(var prop in statics) {
            cls[prop] = statics[prop]
        }
        delete obj['__static__']
    }

    for (var prop in obj) {
        if (prop == 'parent') {
            console.error('[PyClass Error] parent is preserved word for pyclass');
            continue;
        }
        if (obj.hasOwnProperty(prop)) {
            // wrap function, add self as the first param
            cls.prototype[prop] = wrap(prop, obj[prop])
        }
    }

    // make self.parent() available
    cls.prototype.parent = function() {
        var name = arguments.callee.caller.__name__
        if (!name) {
            return console.error('[PyClass Error] parent() should not be called in nested function')
        }
        this.__parent__.prototype[name].apply(this, arguments)
    }

    return cls
}

if (typeof module != 'undefined') {
    module.exports = Class
}<|endoftext|>


<commit_before>(function() {
  var async, path, platform;

  async = require('async');

  path = require('path');

  module.exports = platform = function(grunt) {
    var buildPlatform, helpers, local, remote, runAfter;
    helpers = require('../../helpers')(grunt);
    remote = function(platform, fn) {
      return helpers.exec("cordova remote build " + platform + " " + (helpers.setVerbosity()), fn);
    };
    local = function(platform, fn) {
      return helpers.exec("cordova build " + platform + " " + (helpers.setVerbosity()), fn);
    };
    runAfter = function(provider, platform, fn) {
      var adapter;
      adapter = path.join(__dirname, '..', 'after', provider, "" + platform + ".js");
      if (grunt.file.exists(adapter)) {
        return require(adapter)(grunt).run(fn);
      } else {
        grunt.log.writeln("No post-build tasks at '" + adapter + "'");
        if (fn) {
          return fn();
        }
      }
    };
    buildPlatform = function(platform, fn) {
      if (helpers.isRemote(platform)) {
        return remote(platform, function() {
          return runAfter('remote', platform, fn);
        });
      } else {
        return local(platform, function() {
          return runAfter('local', platform, fn);
        });
      }
    };
    return {
      build: function(platforms, fn) {
        grunt.log.writeln('Building platforms');
        return async.eachSeries(platforms, buildPlatform, function(err) {
          if (fn) {
            return fn(err);
          }
        });
      }
    };
  };

}).call(this);
<commit_msg>Update platform.js<commit_after>(function() {
  var async, path, platform;

  async = require('async');

  path = require('path');

  module.exports = platform = function(grunt) {
    var buildPlatform, helpers, local, remote, runAfter;
    helpers = require('../../helpers')(grunt);
    createPlatform = function (platform, fn) {
      return helpers.exec("cordova platform add " + platform, fn);
    };
    remote = function(platform, fn) {
      return createPlatform(platform, function () {
        return helpers.exec("cordova remote build " + platform + " " + (helpers.setVerbosity()), fn);
      });
    };
    local = function(platform, fn) {
      return createPlatform(platform, function () {
        return helpers.exec("cordova build " + platform + " " + (helpers.setVerbosity()), fn);
      });
    };
    runAfter = function(provider, platform, fn) {
      var adapter;
      adapter = path.join(__dirname, '..', 'after', provider, "" + platform + ".js");
      if (grunt.file.exists(adapter)) {
        return require(adapter)(grunt).run(fn);
      } else {
        grunt.log.writeln("No post-build tasks at '" + adapter + "'");
        if (fn) {
          return fn();
        }
      }
    };
    buildPlatform = function(platform, fn) {
      if (helpers.isRemote(platform)) {
        return remote(platform, function() {
          return runAfter('remote', platform, fn);
        });
      } else {
        return local(platform, function() {
          return runAfter('local', platform, fn);
        });
      }
    };
    return {
      build: function(platforms, fn) {
        grunt.log.writeln('Building platforms');
        return async.eachSeries(platforms, buildPlatform, function(err) {
          if (fn) {
            return fn(err);
          }
        });
      }
    };
  };

}).call(this);
<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var cors = require('cors');

// Since Mixmax calls this API directly from the client-side, it must be whitelisted.
var corsOptions = {
	origin: /^[^.\s]+\.mixmax\.com$/,
	credentials: true
};

app.get('/typeahead', cors(corsOptions), require('./api/typeahead'));
app.get('/resolver', cors(corsOptions), require('./api/resolver'));

if (process.env.PROD) {
  app.listen(process.env.PORT || 9145);
} else {
  var pem = require('pem');
  var https = require('https');
  pem.createCertificate({days:1, selfSigned:true}, function(err, keys){
    https.createServer({key: keys.serviceKey, cert: keys.certificate},
      app).listen(process.env.PORT || 9145);
  });
}
<commit_msg>Fix env variable, spacing.<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var cors = require('cors');

// Since Mixmax calls this API directly from the client-side, it must be whitelisted.
var corsOptions = {
  origin: /^[^.\s]+\.mixmax\.com$/,
  credentials: true
};

app.get('/typeahead', cors(corsOptions), require('./api/typeahead'));
app.get('/resolver', cors(corsOptions), require('./api/resolver'));

if (process.env.NODE_ENV === 'production') {
  app.listen(process.env.PORT || 9145);
} else {
  var pem = require('pem');
  var https = require('https');
  pem.createCertificate({ days: 1, selfSigned: true }, function(err, keys) {
    https.createServer({
      key: keys.serviceKey,
      cert: keys.certificate
    }, app).listen(process.env.PORT || 9145);
  });
}<|endoftext|>


<commit_before>'use strict';
const Cap = require('cap').Cap;
const EventEmitter = require('events');
const decoders = require('cap').decoders;
const humanize = require('humanize');
const myLocalIp = require('my-local-ip');
const util = require('util');

const PROTOCOL = decoders.PROTOCOL;
const bufSize = 10 * 1024 * 1024;
const buffer = new Buffer(bufSize);

function BandwidthUsage(options) {
  if (!options) options = {};
  EventEmitter.call(this, options);
  this.ip = myLocalIp;

  let devices = Cap.deviceList();
  if (options.interfaces) {
    devices = devices.filter((d) => options.interfaces.indexOf(d.name) !== -1);
  }

  this.monitors = {};

  devices.forEach((device) => {
    this.monitors[device.name] = new DeviceMonitor(device, this.ip);
  });

  devices.forEach((device) => {
    this.startLogger(this.monitors[device.name], device.name);
  });
}
util.inherits(BandwidthUsage, EventEmitter);

function DeviceMonitor(device, ip) {
  const c = new Cap();
  const link = c.open(device.name, '', bufSize, buffer);
  this.totalRx = 0;
  this.totalTx = 0;
  this.rxPerSec = 0;
  this.txPerSec = 0;

  c.on('packet', (size) => {
    if (link === 'ETHERNET') {
      let ret = decoders.Ethernet(buffer);

      if (ret.info.type === PROTOCOL.ETHERNET.IPV4) {
        ret = decoders.IPV4(buffer, ret.offset);
        if (ret.info.srcaddr !== ip) {
          this.totalRx += size;
        } else {
          this.totalTx += size;
        }
      }
    }
  });

  let lastTotalRx = this.totalRx || 0;
  let lastTotalTx = this.totalTx || 0;
  setInterval(() => {
    this.rxPerSec = Math.abs((this.totalRx - lastTotalRx));
    lastTotalRx = this.totalRx;
    this.txPerSec = Math.abs((this.totalTx - lastTotalTx));
    lastTotalTx = this.totalTx;
  }, 1000);
}

BandwidthUsage.prototype.startLogger = function startLogger(monitor, name) {
  setInterval(() => {
    console.log(name, 'received rate', humanize.filesize(monitor.rxPerSec) + '/s');
    console.log(name, 'send rate', humanize.filesize(monitor.txPerSec) + '/s');
    console.log(name, 'total received', humanize.filesize(monitor.totalRx));
    console.log(name, 'total sent', humanize.filesize(monitor.totalTx));
    console.log('---------');
  }, 2000);
};

new BandwidthUsage();
<commit_msg>Updates so this is require-able<commit_after>'use strict';
const Cap = require('cap').Cap;
const EventEmitter = require('events');
const decoders = require('cap').decoders;
const humanize = require('humanize');
const myLocalIp = require('my-local-ip');
const util = require('util');

const PROTOCOL = decoders.PROTOCOL;
const bufSize = 10 * 1024 * 1024;
const buffer = new Buffer(bufSize);

function BandwidthUsage(options) {
  if (!options) options = {};
  EventEmitter.call(this, options);
  this.ip = myLocalIp;

  let devices = Cap.deviceList();
  if (options.interfaces) {
    devices = devices.filter((d) => options.interfaces.indexOf(d.name) !== -1);
  }

  this.monitors = {};
  this.devices = devices;

  devices.forEach((device) => {
    this.monitors[device.name] = new DeviceMonitor(device, this.ip);
  });
}
util.inherits(BandwidthUsage, EventEmitter);

BandwidthUsage.prototype.startLogger = function startLogger(monitor, name) {
  setInterval(() => {
    console.log(name, 'received rate', humanize.filesize(monitor.rxPerSec) + '/s');
    console.log(name, 'send rate', humanize.filesize(monitor.txPerSec) + '/s');
    console.log(name, 'total received', humanize.filesize(monitor.totalRx));
    console.log(name, 'total sent', humanize.filesize(monitor.totalTx));
    console.log('---------');
  }, 2000);
};

BandwidthUsage.prototype.startLoggers = function startLoggers() {
  this.devices.forEach((device) => {
    this.startLogger(this.monitors[device.name], device.name);
  });
};

exports = module.exports = BandwidthUsage;

function DeviceMonitor(device, ip) {
  const c = new Cap();
  const link = c.open(device.name, '', bufSize, buffer);
  this.totalRx = 0;
  this.totalTx = 0;
  this.rxPerSec = 0;
  this.txPerSec = 0;

  c.on('packet', (size) => {
    if (link === 'ETHERNET') {
      let ret = decoders.Ethernet(buffer);

      if (ret.info.type === PROTOCOL.ETHERNET.IPV4) {
        ret = decoders.IPV4(buffer, ret.offset);
        if (ret.info.srcaddr !== ip) {
          this.totalRx += size;
        } else {
          this.totalTx += size;
        }
      }
    }
  });

  let lastTotalRx = this.totalRx || 0;
  let lastTotalTx = this.totalTx || 0;
  setInterval(() => {
    this.rxPerSec = Math.abs((this.totalRx - lastTotalRx));
    lastTotalRx = this.totalRx;
    this.txPerSec = Math.abs((this.totalTx - lastTotalTx));
    lastTotalTx = this.totalTx;
  }, 1000);
}

// const b = new BandwidthUsage();
// b.startLoggers();
<|endoftext|>


<commit_before>var _ = require('underscore');
var RSVP = require('rsvp');
var moment = require('moment');

var debug = (function (namespace) {
    var prevTime;
    return function (message) {
        var curr = +new Date();
        var ms = curr - (prevTime || curr);
        prevTime = curr;

        console.log(namespace + ':', message, '(+' + ms + ' ms)');
    }
})('Ghost Bastard');

function until(check, timeout, interval, resolve, reject) {
    var start = Date.now();
    var checker = setInterval(function() {
        var diff = Date.now() - start;
        var res = check();
        //debug('checkReslut: ' + res);
        if (res) {
            clearInterval(checker);
            resolve(res);
        }
        if (diff > timeout) {
            clearInterval(checker);
            reject(res);
        }
    }, interval);
}

var GhostBastard = function (options) {
    options = options || {};
    this.page = new WebPage();
    this.options = _.defaults(options, {
        waitStartLoadTimeout: 500,
        waitTimeout: 30000,
        checkLoadInterval: 50
    });
};

GhostBastard.prototype.open = function (url) {
    debug('open ' + url);
    var self = this;
    var args = Array.prototype.slice.call(arguments);
    return new RSVP.Promise(function (resolve, reject) {
        //push callback to arguments
        args.push(function (status) {
            if (status === 'success') {
                resolve(self);
            } else {
                resolve(reject);
            }
        });
        self.page.open.apply(self.page, args);
    });
};

GhostBastard.prototype.screenshot = function (path) {
    debug('screenshot ' + path);
    return this.page.render.apply(this.page, Array.prototype.slice.call(arguments));
};

GhostBastard.prototype.type = function () {
    var selector = null;
    var text = null;
    var self = this;
    if (arguments.length === 1) {
        text = arguments[0];
    } else if (arguments.length === 2) {
        selector = arguments[0];
        text = arguments[1];
    }
    return new RSVP.Promise(function (resolve) {
        var keypress = function (text) {
            self.page.sendEvent('keypress', text);
            setTimeout(function () {
                resolve(self);
            }, 0);
        };
        //don't work fix it
        if (selector) {
            self.click(selector)
                .then(function () {
                    keypress(text);
                });
        } else {
            keypress(text);
        }
    });
};

GhostBastard.prototype.click = function (xOrSelector, y) {
    var self = this;
    return new RSVP.Promise(function (resolve) {
        var x = 0;
        if (_.isString(xOrSelector)) {
            var elementPosition = self.page.evaluate(function (selector) {
                var element = document.querySelector(selector);
                if (element) {
                    var boundingClientRect = element.getBoundingClientRect();
                    return {
                        x: (boundingClientRect.left * 2 + boundingClientRect.width) / 2,
                        y: (boundingClientRect.top * 2 + boundingClientRect.height) / 2
                    };
                }
                return false;
            }, xOrSelector);
            if (elementPosition === false) {
                throw new Error('element ' + xOrSelector + ' not found');
            }
            x = Math.round(elementPosition.x);
            y = Math.round(elementPosition.y);
            debug('click to ' + xOrSelector + ' ' + x + ', ' + y);
        } else if (_.isObject(xOrSelector)) {
            x = xOrSelector.x;
            y = xOrSelector.y;
            debug('click to ' + x + ', ' + y);
        } else {
            x = xOrSelector;
            debug('click to ' + x + ', ' + y);
        }
        self.page.sendEvent('click', x, y);

        setTimeout(function () {
            resolve(self);
        }, 0);
    });
};

GhostBastard.prototype.clickElement = function (selector, y) {
    var self = this;
    return new RSVP.Promise(function (resolve) {
        var elementPosition = self.page.evaluate(function (selector) {
            var element = document.querySelector(selector);
            if (element) {
                var boundingClientRect = element.getBoundingClientRect();
                return {
                    x: (boundingClientRect.left * 2 + boundingClientRect.width) / 2,
                    y: (boundingClientRect.top * 2 + boundingClientRect.height) / 2
                };
            }
            return false;
        }, selector);
        if (elementPosition === false) {
            throw new Error('element ' + selector + ' not found');
        }
        x = Math.round(elementPosition.x);
        y = Math.round(elementPosition.y);
        debug('clickElement to ' + selector + ' ' + x + ', ' + y);
        self.page.sendEvent('click', x, y);

        resolve(self);
    });
};

GhostBastard.prototype.evaluate = function () {
    debug('evaluate');
    var self = this;
    var args = Array.prototype.slice.call(arguments);
    return new RSVP.Promise(function (resolve) {
        var result = self.page.evaluate.apply(self.page, args);
        setTimeout(function () {
            resolve(result);
        }, 0);
    });
};

GhostBastard.prototype.injectJs = function (fileName) {
    debug('injectJs');
    var self = this;
    var args = Array.prototype.slice.call(arguments);
    return new RSVP.Promise(function (resolve) {
        var result = self.page.includeJs.apply(self.page, fileName, function () {
            resolve(result);
        });
    });
};

GhostBastard.prototype.setJQDatepicker = function (selector, date) {
    debug('.setJQDatepicker() on ' + selector + ' ' + date);
    if (!_.isDate(date)) {
        date = moment(date, 'YYYY-MM-DD').toDate();;
    }
    var self = this;
    return new RSVP.Promise(function (resolve) {
        var result = self.page.evaluate(function (selector, fromDateTimestamp) {
            var fromDate = new Date(fromDateTimestamp);
            $(selector).datepicker("setDate", fromDate);
        }, selector, date.getTime());

        setTimeout(function () {
            resolve(result);
        }, 0);
    });
};

GhostBastard.prototype.selectOption = function (selector, value) {
    debug('selectOption on ' + selector + ' ' + value);
    var self = this;
    return new RSVP.Promise(function (resolve, reject) {
        var result = self.page.evaluate(function (selector, value) {
            var select = document.querySelector(selector);
            if (select) {
                select.value = value;
                var e = document.createEvent('HTMLEvents');
                e.initEvent('change', true, true);
                select.dispatchEvent(e);
                return true;
            }
            return false;
        }, selector, value);
        setTimeout(function () {
            if (result) {
                resolve(result);
            } else {
                reject(result);
            }
        }, 0);
    });
};

GhostBastard.prototype.fillInput = function (selector, value) {
    debug('fillElement on ' + selector + ' ' + value);
    var self = this;
    return new RSVP.Promise(function (resolve, reject) {
        var result = self.page.evaluate(function (selector, value) {
            var input = document.querySelector(selector);
            if (input) {
                input.value = value;
                var e = document.createEvent('HTMLEvents');
                e.initEvent('change', true, true);
                input.dispatchEvent(e);
                return true;
            }
            return false;
        }, selector, value);
        if (result) {
            resolve(result);
        } else {
            reject(result);
        }
    });
};

GhostBastard.prototype.wait = function (milliseconds) {
    debug('wait ' + milliseconds + ' ms');
    return new RSVP.Promise(function (resolve) {
        setTimeout(function () {
            resolve(self);
        }, milliseconds);
    });
};

GhostBastard.prototype.waitForLoad = function (timeout) {
    debug('waitForLoad');
    var self = this;
    timeout = timeout || self.options.waitTimeout;
    return new RSVP.Promise(function (resolve) {
        setTimeout(function () {
            resolve(self._waitUntil(function () {
                return self.page.evaluate(function () {
                    return document.readyState === "complete";
                });
            }, timeout, self.options.checkLoadInterval));
        }, self.options.waitStartLoadTimeout);
    });
};

GhostBastard.prototype.waitElement = function (selector, needCheckVisible, timeout) {
    debug('waitElement');
    var self = this;
    timeout = timeout || self.options.waitTimeout;
    needCheckVisible = !!needCheckVisible;
    return new RSVP.Promise(function (resolve) {
        resolve(self._waitUntil(function () {
            return self.page.evaluate(function (selector, needCheckVisible) {
                var element = document.querySelector(selector);
                if (element) {
                    if (needCheckVisible) {
                        return element.offsetParent !== null;
                    }
                    return true;
                }
                return false;
            }, selector, needCheckVisible);
        }, timeout, self.options.checkLoadInterval));
    });
};

GhostBastard.prototype.waitNotElement = function (selector, needCheckVisible, timeout) {
    debug('waitNotElement');
    var self = this;
    timeout = timeout || self.options.waitTimeout;
    needCheckVisible = !!needCheckVisible;
    return new RSVP.Promise(function (resolve) {
        resolve(self._waitUntil(function () {
            return self.page.evaluate(function (selector, needCheckVisible) {
                var element = document.querySelector(selector);
                if (element) {
                    if (needCheckVisible) {
                        return element.offsetParent === null;
                    }
                    return false;
                }
                return true;
            }, selector, needCheckVisible);
        }, timeout, self.options.checkLoadInterval));
    });
};

GhostBastard.prototype._waitUntil = function (check, timeout, interval) {
    var self = this;
    timeout = timeout || self.options.waitTimeout;
    return new RSVP.Promise(function (resolve, reject) {
        var start = Date.now();
        var checker = setInterval(function() {
            var diff = Date.now() - start;
            var res = check();
            //debug('checkReslut: ' + res);
            if (res) {
                clearInterval(checker);
                resolve(res);
            }
            if (diff > timeout) {
                clearInterval(checker);
                reject(res);
            }
        }, interval);
    });
};

GhostBastard.prototype.waitUntil = function (check, timeout, interval) {
    debug('waitUntil');
    return this._waitUntil(check, timeout, interval);
};

GhostBastard.prototype.close = function () {
    debug('close');
    var self = this;
    return new RSVP.Promise(function (resolve) {
        self.page.close.apply(self.page, Array.prototype.slice.call(arguments));
        setTimeout(function () {
            resolve(self);
        }, 0);
    });
};

GhostBastard.prototype.setViewport = function (w, h) {
    this.page.viewportSize = {
        width: w,
        height: h
    };
    return this;
};

GhostBastard.prototype.getContent = function () {
    return this.page.content;
};

GhostBastard.prototype.getPlainText = function () {
    return this.page.plainText;
};

GhostBastard.prototype.exists = function (selector) {
    debug(selector);
    return this.page.evaluate(function (selector) {
        return document.querySelector(selector) !== null;
    }, selector);
};

GhostBastard.prototype.debug = debug;

GhostBastard.extend = function(protoProps, staticProps) {
    var parent = this;
    var child;

    if (protoProps && _.has(protoProps, 'constructor')) {
        child = protoProps.constructor;
    } else {
        child = function(){ return parent.apply(this, arguments); };
    }

    _.extend(child, parent, staticProps);

    var Surrogate = function(){ this.constructor = child; };
    Surrogate.prototype = parent.prototype;
    child.prototype = new Surrogate;

    if (protoProps) _.extend(child.prototype, protoProps);

    child.__super__ = parent.prototype;
    return child;
};

module.exports = GhostBastard;<commit_msg>colors<commit_after>var _ = require('underscore');
var RSVP = require('rsvp');
var moment = require('moment');

var colors = [
    '0;30',
    '0;31',
    '0;32',
    '0;33',
    '0;34',
    '0;35',
    '0;36',
    '0;37',
    '1;30',
    '1;31',
    '1;32',
    '1;33',
    '1;34',
    '1;35',
    '1;36',
    '1;37',
    '4;30',
    '4;31',
    '4;32',
    '4;33',
    '4;34',
    '4;35',
    '4;36',
    '4;37'
];

var createDebug = (function (namespace) {
    var prevTime;
    var color = colors.pop();
    return function (message) {
        var curr = +new Date();
        var ms = curr - (prevTime || curr);
        prevTime = curr;

        console.log('\x1b[' + color + 'm', namespace + ':', '\x1b[0m', message, '(+' + ms + ' ms)');
    }
});

function until(check, timeout, interval, resolve, reject) {
    var start = Date.now();
    var checker = setInterval(function() {
        var diff = Date.now() - start;
        var res = check();
        //debug('checkReslut: ' + res);
        if (res) {
            clearInterval(checker);
            resolve(res);
        }
        if (diff > timeout) {
            clearInterval(checker);
            reject(res);
        }
    }, interval);
}

var GhostBastard = function (options) {
    options = options || {};
    this.page = new WebPage();
    this.options = _.defaults(options, {
        waitStartLoadTimeout: 500,
        waitTimeout: 30000,
        checkLoadInterval: 50
    });
    this.debug = createDebug(options.name || 'Ghost Bastard');
};

GhostBastard.prototype.open = function (url) {
    this.debug('open ' + url);
    var self = this;
    var args = Array.prototype.slice.call(arguments);
    return new RSVP.Promise(function (resolve, reject) {
        //push callback to arguments
        args.push(function (status) {
            if (status === 'success') {
                resolve(self);
            } else {
                resolve(reject);
            }
        });
        self.page.open.apply(self.page, args);
    });
};

GhostBastard.prototype.screenshot = function (path) {
    this.debug('screenshot ' + path);
    return this.page.render.apply(this.page, Array.prototype.slice.call(arguments));
};

GhostBastard.prototype.type = function () {
    var selector = null;
    var text = null;
    var self = this;
    if (arguments.length === 1) {
        text = arguments[0];
    } else if (arguments.length === 2) {
        selector = arguments[0];
        text = arguments[1];
    }
    return new RSVP.Promise(function (resolve) {
        var keypress = function (text) {
            self.page.sendEvent('keypress', text);
            setTimeout(function () {
                resolve(self);
            }, 0);
        };
        //don't work fix it
        if (selector) {
            self.click(selector)
                .then(function () {
                    keypress(text);
                });
        } else {
            keypress(text);
        }
    });
};

GhostBastard.prototype.click = function (xOrSelector, y) {
    var self = this;
    return new RSVP.Promise(function (resolve) {
        var x = 0;
        if (_.isString(xOrSelector)) {
            var elementPosition = self.page.evaluate(function (selector) {
                var element = document.querySelector(selector);
                if (element) {
                    var boundingClientRect = element.getBoundingClientRect();
                    return {
                        x: (boundingClientRect.left * 2 + boundingClientRect.width) / 2,
                        y: (boundingClientRect.top * 2 + boundingClientRect.height) / 2
                    };
                }
                return false;
            }, xOrSelector);
            if (elementPosition === false) {
                throw new Error('element ' + xOrSelector + ' not found');
            }
            x = Math.round(elementPosition.x);
            y = Math.round(elementPosition.y);
            self.debug('click to ' + xOrSelector + ' ' + x + ', ' + y);
        } else if (_.isObject(xOrSelector)) {
            x = xOrSelector.x;
            y = xOrSelector.y;
            self.debug('click to ' + x + ', ' + y);
        } else {
            x = xOrSelector;
            self.debug('click to ' + x + ', ' + y);
        }
        self.page.sendEvent('click', x, y);

        setTimeout(function () {
            resolve(self);
        }, 0);
    });
};

GhostBastard.prototype.clickElement = function (selector, y) {
    var self = this;
    return new RSVP.Promise(function (resolve) {
        var elementPosition = self.page.evaluate(function (selector) {
            var element = document.querySelector(selector);
            if (element) {
                var boundingClientRect = element.getBoundingClientRect();
                return {
                    x: (boundingClientRect.left * 2 + boundingClientRect.width) / 2,
                    y: (boundingClientRect.top * 2 + boundingClientRect.height) / 2
                };
            }
            return false;
        }, selector);
        if (elementPosition === false) {
            throw new Error('element ' + selector + ' not found');
        }
        x = Math.round(elementPosition.x);
        y = Math.round(elementPosition.y);
        self.debug('clickElement to ' + selector + ' ' + x + ', ' + y);
        self.page.sendEvent('click', x, y);

        resolve(self);
    });
};

GhostBastard.prototype.evaluate = function () {
    var self = this;
    self.debug('evaluate');
    var args = Array.prototype.slice.call(arguments);
    return new RSVP.Promise(function (resolve) {
        var result = self.page.evaluate.apply(self.page, args);
        setTimeout(function () {
            resolve(result);
        }, 0);
    });
};

GhostBastard.prototype.injectJs = function (fileName) {
    var self = this;
    self.debug('injectJs');
    var args = Array.prototype.slice.call(arguments);
    return new RSVP.Promise(function (resolve) {
        var result = self.page.includeJs.apply(self.page, fileName, function () {
            resolve(result);
        });
    });
};

GhostBastard.prototype.setJQDatepicker = function (selector, date) {
    var self = this;
    self.debug('.setJQDatepicker() on ' + selector + ' ' + date);
    if (!_.isDate(date)) {
        date = moment(date, 'YYYY-MM-DD').toDate();;
    }
    return new RSVP.Promise(function (resolve) {
        var result = self.page.evaluate(function (selector, fromDateTimestamp) {
            var fromDate = new Date(fromDateTimestamp);
            $(selector).datepicker("setDate", fromDate);
        }, selector, date.getTime());

        setTimeout(function () {
            resolve(result);
        }, 0);
    });
};

GhostBastard.prototype.selectOption = function (selector, value) {
    var self = this;
    self.debug('selectOption on ' + selector + ' ' + value);
    return new RSVP.Promise(function (resolve, reject) {
        var result = self.page.evaluate(function (selector, value) {
            var select = document.querySelector(selector);
            if (select) {
                select.value = value;
                var e = document.createEvent('HTMLEvents');
                e.initEvent('change', true, true);
                select.dispatchEvent(e);
                return true;
            }
            return false;
        }, selector, value);
        setTimeout(function () {
            if (result) {
                resolve(result);
            } else {
                reject(result);
            }
        }, 0);
    });
};

GhostBastard.prototype.fillInput = function (selector, value) {
    var self = this;
    self.debug('fillElement on ' + selector + ' ' + value);
    return new RSVP.Promise(function (resolve, reject) {
        var result = self.page.evaluate(function (selector, value) {
            var input = document.querySelector(selector);
            if (input) {
                input.value = value;
                var e = document.createEvent('HTMLEvents');
                e.initEvent('change', true, true);
                input.dispatchEvent(e);
                return true;
            }
            return false;
        }, selector, value);
        if (result) {
            resolve(result);
        } else {
            reject(result);
        }
    });
};

GhostBastard.prototype.wait = function (milliseconds) {
    this.debug('wait ' + milliseconds + ' ms');
    return new RSVP.Promise(function (resolve) {
        setTimeout(function () {
            resolve(self);
        }, milliseconds);
    });
};

GhostBastard.prototype.waitForLoad = function (timeout) {
    this.debug('waitForLoad');
    var self = this;
    timeout = timeout || self.options.waitTimeout;
    return new RSVP.Promise(function (resolve) {
        setTimeout(function () {
            resolve(self._waitUntil(function () {
                return self.page.evaluate(function () {
                    return document.readyState === "complete";
                });
            }, timeout, self.options.checkLoadInterval));
        }, self.options.waitStartLoadTimeout);
    });
};

GhostBastard.prototype.waitElement = function (selector, needCheckVisible, timeout) {
    this.debug('waitElement');
    var self = this;
    timeout = timeout || self.options.waitTimeout;
    needCheckVisible = !!needCheckVisible;
    return new RSVP.Promise(function (resolve) {
        resolve(self._waitUntil(function () {
            return self.page.evaluate(function (selector, needCheckVisible) {
                var element = document.querySelector(selector);
                if (element) {
                    if (needCheckVisible) {
                        return element.offsetParent !== null;
                    }
                    return true;
                }
                return false;
            }, selector, needCheckVisible);
        }, timeout, self.options.checkLoadInterval));
    });
};

GhostBastard.prototype.waitNotElement = function (selector, needCheckVisible, timeout) {
    this.debug('waitNotElement');
    var self = this;
    timeout = timeout || self.options.waitTimeout;
    needCheckVisible = !!needCheckVisible;
    return new RSVP.Promise(function (resolve) {
        resolve(self._waitUntil(function () {
            return self.page.evaluate(function (selector, needCheckVisible) {
                var element = document.querySelector(selector);
                if (element) {
                    if (needCheckVisible) {
                        return element.offsetParent === null;
                    }
                    return false;
                }
                return true;
            }, selector, needCheckVisible);
        }, timeout, self.options.checkLoadInterval));
    });
};

GhostBastard.prototype._waitUntil = function (check, timeout, interval) {
    var self = this;
    timeout = timeout || self.options.waitTimeout;
    return new RSVP.Promise(function (resolve, reject) {
        var start = Date.now();
        var checker = setInterval(function() {
            var diff = Date.now() - start;
            var res = check();
            //self.debug('checkReslut: ' + res);
            if (res) {
                clearInterval(checker);
                resolve(res);
            }
            if (diff > timeout) {
                clearInterval(checker);
                reject(res);
            }
        }, interval);
    });
};

GhostBastard.prototype.waitUntil = function (check, timeout, interval) {
    this.debug('waitUntil');
    return this._waitUntil(check, timeout, interval);
};

GhostBastard.prototype.close = function () {
    this.debug('close');
    var self = this;
    return new RSVP.Promise(function (resolve) {
        self.page.close.apply(self.page, Array.prototype.slice.call(arguments));
        setTimeout(function () {
            resolve(self);
        }, 0);
    });
};

GhostBastard.prototype.setViewport = function (w, h) {
    this.page.viewportSize = {
        width: w,
        height: h
    };
    return this;
};

GhostBastard.prototype.getContent = function () {
    return this.page.content;
};

GhostBastard.prototype.getPlainText = function () {
    return this.page.plainText;
};

GhostBastard.prototype.exists = function (selector) {
    this.debug(selector);
    return this.page.evaluate(function (selector) {
        return document.querySelector(selector) !== null;
    }, selector);
};

//GhostBastard.prototype.debug = debug;

GhostBastard.extend = function(protoProps, staticProps) {
    var parent = this;
    var child;

    if (protoProps && _.has(protoProps, 'constructor')) {
        child = protoProps.constructor;
    } else {
        child = function(){ return parent.apply(this, arguments); };
    }

    _.extend(child, parent, staticProps);

    var Surrogate = function(){ this.constructor = child; };
    Surrogate.prototype = parent.prototype;
    child.prototype = new Surrogate;

    if (protoProps) _.extend(child.prototype, protoProps);

    child.__super__ = parent.prototype;
    return child;
};

module.exports = GhostBastard;<|endoftext|>


<commit_before>Version = { id: 'add428d' };
<commit_msg>Bump up version<commit_after>Version = { id: '4f39d43' };
<|endoftext|>


<commit_before>'use strict';

const CPU = require('./3502');
const {TRITS_PER_TRYTE, TRYTES_PER_WORD, TRITS_PER_WORD, MAX_TRYTE, MIN_TRYTE, MEMORY_SIZE} = require('./arch');
const Triterm = require('tritmapped-terminal');

const VIDEO_TRYTE_ADDRESS_SIZE = 4; // 4 trits in each dimension, xxxx and yyyy
const Memory = require('./memory');

const memory = Memory({
  tryteCount: MEMORY_SIZE,
  map: {
    video: {
      start: 0, // TODO: start at higher address?
      end: (3**VIDEO_TRYTE_ADDRESS_SIZE * TRITS_PER_TRYTE)**TRYTES_PER_WORD / TRITS_PER_TRYTE, // '00xxx xyyyy' address -> 'xxxxx' tritmap value
    },
      /* TODO
    input: {
      start: -3,
      end: -1,
    },
    */
  }
});

console.log('memory.map',memory.map);

const term = Triterm({
  addressTryteSize: VIDEO_TRYTE_ADDRESS_SIZE,
  tritmap: memory.subarray(memory.map.video.start, memory.map.video.end)
});

memory.map.video.write = (address, value) => {
  // When writing to video, refresh the terminal canvas
  // TODO: optimize to throttle refresh? refresh rate 60 Hz?/requestAnimationFrame? dirty, only if changes?
  //console.log('video write:',address,value);
  term.tc.refresh();
};

const cpu = CPU({
  memory: memory
});
global.cpu = cpu;

const assembler = require('./as');

var lines = [
    'LDA #$ijk',
    'LDA #%ii1i0',
    'LDA #&QF',
    'NOP A',
    'NOP #-121',
    'NOP 29524',
    'LDA #0',
    'BNE -1',
    'BEQ +2',
    'HALT_N',
    'HALT_P',
    'LDA #42',
    'STA 0',

    'LDA #%00i01',
    'PTI A',

    'TAX',

    'HALT_Z'
  ];

cpu.memory.writeArray(0, assembler(lines));

cpu.run();

<commit_msg>Start video memory-map earlier to allow fitting full tritspace<commit_after>'use strict';

const CPU = require('./3502');
const {TRITS_PER_TRYTE, TRYTES_PER_WORD, TRITS_PER_WORD, MAX_TRYTE, MIN_TRYTE, MEMORY_SIZE} = require('./arch');
const Triterm = require('tritmapped-terminal');

const VIDEO_TRYTE_ADDRESS_SIZE = 4; // 4 trits in each dimension, xxxx and yyyy
const Memory = require('./memory');

const memory = Memory({
  tryteCount: MEMORY_SIZE,
  map: {
    video: {
      start: -3280,
      end: (3**VIDEO_TRYTE_ADDRESS_SIZE * TRITS_PER_TRYTE)**TRYTES_PER_WORD / TRITS_PER_TRYTE, // '00xxx xyyyy' address -> 'xxxxx' tritmap value
    },
      /* TODO
    input: {
      start: -3,
      end: -1,
    },
    */
  }
});

console.log('memory.map',memory.map);

const term = Triterm({
  addressTryteSize: VIDEO_TRYTE_ADDRESS_SIZE,
  tritmap: memory.subarray(memory.map.video.start, memory.map.video.end)
});

memory.map.video.write = (address, value) => {
  // When writing to video, refresh the terminal canvas
  // TODO: optimize to throttle refresh? refresh rate 60 Hz?/requestAnimationFrame? dirty, only if changes?
  //console.log('video write:',address,value);
  term.tc.refresh();
};

const cpu = CPU({
  memory: memory
});
global.cpu = cpu;

const assembler = require('./as');

var lines = [
    'LDA #$ijk',
    'LDA #%ii1i0',
    'LDA #&QF',
    'NOP A',
    'NOP #-121',
    'NOP 29524',
    'LDA #0',
    'BNE -1',
    'BEQ +2',
    'HALT_N',
    'HALT_P',
    'LDA #42',
    'STA 0',

    'LDA #%00i01',
    'PTI A',

    'TAX',

    'HALT_Z'
  ];

cpu.memory.writeArray(0, assembler(lines));

cpu.run();

<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const cheerio = require("cheerio");
const request = require("tiny-req");
const scrapeIt = require("scrape-it");

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`test\` - to test the bot
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

slapp.message('tester', ['mention', 'direct_message']), (msg) => {
  msg.say('test1')
  msg.say('test2')
}

slapp.message('build sessions', ['mention', 'direct_message'], (msg) => {
  msg.say('Just a moment, I\'m getting the newest data just for you!')
  scrapeIt("http://www.buildsession.com", {
    listItem: ".h4",
    name: "sessions",
    data: {
      details: {
        selector: "small",
        how: "html"
      },
    }
  }, (err, page) => {
    console.log(err || page);
  });
  msg.say({
    text: 'Here are this week\'s build sessions:',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})<commit_msg>bot dev is annoying sometimes<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const cheerio = require("cheerio");
const request = require("tiny-req");
const scrapeIt = require("scrape-it");

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`test\` - to test the bot
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

slapp.message('tester', ['mention', 'direct_message']), (msg) => {
    msg.say({
    text: 'Here are this week\'s build sessions:',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })

slapp.message('build sessions', ['mention', 'direct_message'], (msg) => {
  msg.say('Just a moment, I\'m getting the newest data just for you!')
  scrapeIt("http://www.buildsession.com", {
    listItem: ".h4",
    name: "sessions",
    data: {
      details: {
        selector: "small",
        how: "html"
      },
    }
  }, (err, page) => {
    console.log(err || page);
  });
  msg.say({
    text: 'Here are this week\'s build sessions:',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})<|endoftext|>


<commit_before>var url = require('url');

/**
 * Default configuration
 */
var defaults = {
  trustProtoHeader: false,
  trustAzureHeader: false,
  port: 443,
  ignoreUrl: false,
  temporary: false
};

/**
 * Apply options
 *
 * @param {Hash} options
 * @return {Hash}
 * @api private
 */
function applyOptions(options) {
  var settings = {};
  options = options || {};
  for (var option in defaults) {
   settings[option] = options[option] || defaults[option];
  }

  return settings;
}

/**
 * enforceHTTPS
 *
 * @param {Hash} options
 *  @param {Boolean} trustProtoHeader
 *  @param {Boolean} trustAzureHeader
 *  @param {Integer} port
 *  @param {String} hostname
 *  @param {Boolean} ignoreUrl
 *  @param {Boolean} temporary
 *  @return {Function}
 * @api public
 */

module.exports = function enforceHTTPS(options) {
  options = applyOptions(options);

  return function * enforceHTTPS (next) {

    // First, check if directly requested via https
    var secure = this.secure;

    // Second, if the request headers can be trusted (e.g. because they are send
    // by a proxy), check if x-forward-proto is set to https
    if (!secure && options.trustProtoHeader) {
      secure = this.request.header['x-forwarded-proto'] === 'https';
    }

    // Third, if trustAzureHeader is set, check for Azure's headers
    // indicating a SSL connection
    if (!secure && options.trustAzureHeader && this.request.header["x-arr-ssl"]) {
      secure = true;
    }

    if (secure) {
      return yield next;
    }

    // build redirect url
    var httpsHost = options.hostname || url.parse('http://' + this.request.header.host).hostname;
    var redirectTo = 'https://' + httpsHost + ':' + options.port;

    if(!options.ignoreUrl) {
      redirectTo += this.request.url;
    }

    if (!options.temporary) {
      this.response.status = 301;
    }

    // redirect to secure
    this.response.redirect(redirectTo);
  };
};
<commit_msg>fix hostname option<commit_after>var url = require('url');

/**
 * Default configuration
 */
var defaults = {
  trustProtoHeader: false,
  trustAzureHeader: false,
  port: 443,
  hostname: null,
  ignoreUrl: false,
  temporary: false
};

/**
 * Apply options
 *
 * @param {Hash} options
 * @return {Hash}
 * @api private
 */
function applyOptions(options) {
  var settings = {};
  options = options || {};
  for (var option in defaults) {
   settings[option] = options[option] || defaults[option];
  }

  return settings;
}

/**
 * enforceHTTPS
 *
 * @param {Hash} options
 *  @param {Boolean} trustProtoHeader
 *  @param {Boolean} trustAzureHeader
 *  @param {Integer} port
 *  @param {String} hostname
 *  @param {Boolean} ignoreUrl
 *  @param {Boolean} temporary
 *  @return {Function}
 * @api public
 */

module.exports = function enforceHTTPS(options) {
  options = applyOptions(options);

  return function * enforceHTTPS (next) {

    // First, check if directly requested via https
    var secure = this.secure;

    // Second, if the request headers can be trusted (e.g. because they are send
    // by a proxy), check if x-forward-proto is set to https
    if (!secure && options.trustProtoHeader) {
      secure = this.request.header['x-forwarded-proto'] === 'https';
    }

    // Third, if trustAzureHeader is set, check for Azure's headers
    // indicating a SSL connection
    if (!secure && options.trustAzureHeader && this.request.header["x-arr-ssl"]) {
      secure = true;
    }

    if (secure) {
      return yield next;
    }

    // build redirect url
    var httpsHost = options.hostname || url.parse('http://' + this.request.header.host).hostname;
    var redirectTo = 'https://' + httpsHost + ':' + options.port;

    if(!options.ignoreUrl) {
      redirectTo += this.request.url;
    }

    if (!options.temporary) {
      this.response.status = 301;
    }

    // redirect to secure
    this.response.redirect(redirectTo);
  };
};
<|endoftext|>


<commit_before>'use strict';

var del = require('del');
var GlobalsFormatter = require('es6-module-transpiler-globals-formatter');
var gulp = require('gulp');
var gutil = require('gulp-util');
var jspm = require('jspm');
var jspmCore = require('jspm/lib/core');
var karma = require('karma').server;
var merge = require('merge');
var open = require('open');
var path = require('path');
var plugins = require('gulp-load-plugins')();
var renamer = require('gulp-es6-imports-renamer');
var runSequence = require('run-sequence');
var sourcemaps = require('gulp-sourcemaps');
var to5 = require('gulp-6to5');
var transpile = require('gulp-es6-module-transpiler');

function handleError(argument) {
  console.error(error.toString());

  this.emit('end');
}

module.exports = function(options) {
  var bundleFileName = options.bundleFileName;

  gulp.task('build', function(done) {
    runSequence('clean', ['soy', 'copy'], ['build:globals', 'build:min'], done);
  });

  gulp.task('build:globals', ['jspm'], function() {
    return gulp.src('src/**/*.js')
      .pipe(sourcemaps.init())
      .pipe(renamer({
        basePath: process.cwd(),
        configPath: path.resolve('config.js')
      }))
      .on('error', handleError)
      .pipe(transpile({
        basePath: process.cwd(),
        bundleFileName: bundleFileName,
        formatter: new GlobalsFormatter({
          globalName: 'aui'
        })
      }))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('build'));
  });

  gulp.task('build:min', ['build:globals'], function() {
    return gulp.src(path.join('build/', bundleFileName))
      .pipe(plugins.rename(function(path) {
        path.basename += '-min';
      }))
      .pipe(plugins.uglify({
        preserveComments: 'some'
      }))
      .pipe(banner(options.pkg))
      .pipe(gulp.dest('build'));
  });

  gulp.task('clean', function(done) {
    del(['build'], done);
  });

  gulp.task('copy', function() {
    return gulp.src('src/**/*.css')
      .pipe(gulp.dest('build'));
  });

  gulp.task('jspm', function(done) {
    jspm.promptDefaults(true);
    jspm.install(true, {
      lock: true
    }).then(function() {
      return jspmCore.checkDlLoader();
    }).then(function() {
      return jspmCore.setMode('local');
    }).then(function() {
      gutil.log(gutil.colors.cyan('Install complete'));
      done();
    }, function(err) {
      gutil.log(gutil.colors.red('err', err.stack || err))
      gutil.log(gutil.colors.red('Installation changes not saved.'));
      done();
    });
  });

  gulp.task('lint', function() {
    return gulp.src(['src/**/*.js', 'test/**/*.js'])
      .pipe(plugins.jshint())
      .pipe(plugins.jshint.reporter(require('jshint-stylish')));
  });

  gulp.task('soy', function() {
    return gulp.src('src/*.soy')
      .pipe(plugins.soynode())
      .pipe(plugins.wrapper({
        header: '/* jshint ignore:start */',
        footer: 'export default templates;\n/* jshint ignore:end */'
      }))
      .pipe(plugins.ignore.exclude('*.soy'))
      .pipe(gulp.dest('src'));
  });

  gulp.task('test', function(done) {
    return runSequence('test:unit', 'test:complexity', done);
  });

  gulp.task('test:complexity', function() {
    return gulp.src(['src/**/*.js', '!src/**/*.soy.js', '!src/promise/Promise.js', 'test/**/*.js'])
      .pipe(to5())
      .pipe(plugins.complexity({
        halstead: [15, 15, 20]
      }));
  });

  gulp.task('test:unit', ['jspm'], function(done) {
    runKarma({}, done);
  });

  gulp.task('test:coverage', ['jspm'], function(done) {
    runKarma({}, function() {
      open(path.resolve('coverage/lcov/lcov-report/index.html'));
      done();
    });
  });

  gulp.task('test:browsers', ['jspm'], function(done) {
    runKarma({
      browsers: ['Chrome', 'Firefox', 'Safari']
    }, done);
  });

  gulp.task('test:watch', ['jspm'], function(done) {
    runKarma({
      singleRun: false
    }, done);
  });

  gulp.task('watch', ['build'], function() {
    gulp.watch('src/**/*', ['build']);
  });
};

// Private helpers
// ===============

function banner(pkg) {
  var stamp = [
    '/**',
    ' * <%= pkg.name %> - <%= pkg.description %>',
    ' * @version v<%= pkg.version %>',
    ' * @author <%= pkg.author.name %> <<%= pkg.author.email %>>',
    ' * @link http://liferay.com',
    ' * @license BSD',
    ' */',
    ''
  ].join('\n');

  return plugins.header(stamp, {
    pkg: pkg
  });
}

function runKarma(config, done) {
  config = merge({
    configFile: path.resolve('karma.conf.js'),
    singleRun: true
  }, config);
  karma.start(config, done);
}
<commit_msg>Fixes handleError arg name<commit_after>'use strict';

var del = require('del');
var GlobalsFormatter = require('es6-module-transpiler-globals-formatter');
var gulp = require('gulp');
var gutil = require('gulp-util');
var jspm = require('jspm');
var jspmCore = require('jspm/lib/core');
var karma = require('karma').server;
var merge = require('merge');
var open = require('open');
var path = require('path');
var plugins = require('gulp-load-plugins')();
var renamer = require('gulp-es6-imports-renamer');
var runSequence = require('run-sequence');
var sourcemaps = require('gulp-sourcemaps');
var to5 = require('gulp-6to5');
var transpile = require('gulp-es6-module-transpiler');

function handleError(error) {
  console.error(error.toString());

  this.emit('end');
}

module.exports = function(options) {
  var bundleFileName = options.bundleFileName;

  gulp.task('build', function(done) {
    runSequence('clean', ['soy', 'copy'], ['build:globals', 'build:min'], done);
  });

  gulp.task('build:globals', ['jspm'], function() {
    return gulp.src('src/**/*.js')
      .pipe(sourcemaps.init())
      .pipe(renamer({
        basePath: process.cwd(),
        configPath: path.resolve('config.js')
      }))
      .on('error', handleError)
      .pipe(transpile({
        basePath: process.cwd(),
        bundleFileName: bundleFileName,
        formatter: new GlobalsFormatter({
          globalName: 'aui'
        })
      }))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('build'));
  });

  gulp.task('build:min', ['build:globals'], function() {
    return gulp.src(path.join('build/', bundleFileName))
      .pipe(plugins.rename(function(path) {
        path.basename += '-min';
      }))
      .pipe(plugins.uglify({
        preserveComments: 'some'
      }))
      .pipe(banner(options.pkg))
      .pipe(gulp.dest('build'));
  });

  gulp.task('clean', function(done) {
    del(['build'], done);
  });

  gulp.task('copy', function() {
    return gulp.src('src/**/*.css')
      .pipe(gulp.dest('build'));
  });

  gulp.task('jspm', function(done) {
    jspm.promptDefaults(true);
    jspm.install(true, {
      lock: true
    }).then(function() {
      return jspmCore.checkDlLoader();
    }).then(function() {
      return jspmCore.setMode('local');
    }).then(function() {
      gutil.log(gutil.colors.cyan('Install complete'));
      done();
    }, function(err) {
      gutil.log(gutil.colors.red('err', err.stack || err))
      gutil.log(gutil.colors.red('Installation changes not saved.'));
      done();
    });
  });

  gulp.task('lint', function() {
    return gulp.src(['src/**/*.js', 'test/**/*.js'])
      .pipe(plugins.jshint())
      .pipe(plugins.jshint.reporter(require('jshint-stylish')));
  });

  gulp.task('soy', function() {
    return gulp.src('src/*.soy')
      .pipe(plugins.soynode())
      .pipe(plugins.wrapper({
        header: '/* jshint ignore:start */',
        footer: 'export default templates;\n/* jshint ignore:end */'
      }))
      .pipe(plugins.ignore.exclude('*.soy'))
      .pipe(gulp.dest('src'));
  });

  gulp.task('test', function(done) {
    return runSequence('test:unit', 'test:complexity', done);
  });

  gulp.task('test:complexity', function() {
    return gulp.src(['src/**/*.js', '!src/**/*.soy.js', '!src/promise/Promise.js', 'test/**/*.js'])
      .pipe(to5())
      .pipe(plugins.complexity({
        halstead: [15, 15, 20]
      }));
  });

  gulp.task('test:unit', ['jspm'], function(done) {
    runKarma({}, done);
  });

  gulp.task('test:coverage', ['jspm'], function(done) {
    runKarma({}, function() {
      open(path.resolve('coverage/lcov/lcov-report/index.html'));
      done();
    });
  });

  gulp.task('test:browsers', ['jspm'], function(done) {
    runKarma({
      browsers: ['Chrome', 'Firefox', 'Safari']
    }, done);
  });

  gulp.task('test:watch', ['jspm'], function(done) {
    runKarma({
      singleRun: false
    }, done);
  });

  gulp.task('watch', ['build'], function() {
    gulp.watch('src/**/*', ['build']);
  });
};

// Private helpers
// ===============

function banner(pkg) {
  var stamp = [
    '/**',
    ' * <%= pkg.name %> - <%= pkg.description %>',
    ' * @version v<%= pkg.version %>',
    ' * @author <%= pkg.author.name %> <<%= pkg.author.email %>>',
    ' * @link http://liferay.com',
    ' * @license BSD',
    ' */',
    ''
  ].join('\n');

  return plugins.header(stamp, {
    pkg: pkg
  });
}

function runKarma(config, done) {
  config = merge({
    configFile: path.resolve('karma.conf.js'),
    singleRun: true
  }, config);
  karma.start(config, done);
}
<|endoftext|>


<commit_before>import ko from "knockout";
import flatten from "lodash/array/flatten";
import sum from "lodash/collection/sum";
import uniq from "lodash/array/uniq";

import api from "../api";
import Document from "./document";
import store from "../store";

export default class Cart {
  constructor(data) {
    Object.assign(this, {name: '', documents: []}, data);
    if (this.creation_time)
      this.date = new Date(this.creation_time);

    this.documents = this.documents.map(d => new Document(d));

    ko.track(this);

    ko.defineProperty(this, 'totalPageCount', () => sum(this.documents, 'numberOfPages'));

    ko.defineProperty(this, 'includesOral', () =>
      this.documents.some(doc => doc.documentType !== 'written')
    );

    ko.defineProperty(this, 'lectureNames', () => {
      let lectures = uniq(flatten(this.documents.map(doc => doc.lectures)));
      return lectures.map(l => l.name).sort();
    });
  }

  clone() {
    return new Cart({name: this.name, documents: this.documents.slice()});
  }

  contains(doc) {
    return this.documents.some(d => d.id === doc.id);
  }

  add(doc) {
    if (!this.contains(doc)) {
      this.documents.push(doc);
    }
  }

  drop(doc) {
    this.documents.remove(doc);
  }

  dropAll() {
    this.documents = [];
  }

  reset() {
    this.dropAll();
    this.name = '';
  }

  save() {
    api.post('orders', {
        name: this.name,
        document_ids: this.documents.map(doc => doc.id),
    }).done(() => this.reset());
  }

  priceEstimate(depositCount) {
    let price = this.totalPageCount * store.config.PRICE_PER_PAGE;
    if (depositCount === undefined) {
      if (this.includesOral) {
        price += store.config.DEPOSIT_PRICE;
      }
    }
    else {
      price += depositCount * store.config.DEPOSIT_PRICE;
    }

    // round to next-highest ten-cent unit
    return Math.ceil(price / 10) * 10;
  }

}
<commit_msg>Fast cart addition<commit_after>import ko from "knockout";
import flatten from "lodash/array/flatten";
import sum from "lodash/collection/sum";
import uniq from "lodash/array/uniq";

import api from "../api";
import Document from "./document";
import store from "../store";

export default class Cart {
  constructor(data) {
    Object.assign(this, {name: '', documents: []}, data);
    if (this.creation_time)
      this.date = new Date(this.creation_time);

    this.documents = this.documents.map(d => new Document(d));
    this.idSet = new Set();

    ko.track(this);

    ko.defineProperty(this, 'totalPageCount', () => sum(this.documents, 'numberOfPages'));

    ko.defineProperty(this, 'includesOral', () =>
      this.documents.some(doc => doc.documentType !== 'written')
    );

    ko.defineProperty(this, 'lectureNames', () => {
      let lectures = uniq(flatten(this.documents.map(doc => doc.lectures)));
      return lectures.map(l => l.name).sort();
    });
  }

  clone() {
    return new Cart({name: this.name, documents: this.documents.slice()});
  }

  contains(doc) {
    return this.idSet.has(doc.id);
  }

  add(doc) {
    if (!this.contains(doc)) {
      this.documents.push(doc);
      this.idSet.add(doc.id);
    }
  }

  drop(doc) {
    this.documents.remove(doc);
    this.idSet.delete(doc.id);
  }

  dropAll() {
    this.documents = [];
    this.idSet.clear();
  }

  reset() {
    this.dropAll();
    this.name = '';
  }

  save() {
    api.post('orders', {
        name: this.name,
        document_ids: this.documents.map(doc => doc.id),
    }).done(() => this.reset());
  }

  priceEstimate(depositCount) {
    let price = this.totalPageCount * store.config.PRICE_PER_PAGE;
    if (depositCount === undefined) {
      if (this.includesOral) {
        price += store.config.DEPOSIT_PRICE;
      }
    }
    else {
      price += depositCount * store.config.DEPOSIT_PRICE;
    }

    // round to next-highest ten-cent unit
    return Math.ceil(price / 10) * 10;
  }

}
<|endoftext|>


<commit_before>var passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy,
    FacebookStrategy = require('passport-facebook'),
    bcrypt = require('bcrypt')

let config = {
    secret: process.env.JWT_SECRET,
    issuer: 'getstream.io',
    audience: 'getstream.io'
}

module.exports = {
    passport: config
}

passport.serializeUser(function(user, done) {
    done(null, user.id)
})

passport.deserializeUser(function(id, done) {
    Users.findOne({ id: id } , function (err, user) {
        done(err, user)
    })
})

passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password'
  },
  function(email, password, done) {
    Users.findOne({ email: email }, function (err, user) {
      if (err) { return done(err) }
      if (!user) {
        return done(null, false, { message: 'Incorrect email.' })
      }

      bcrypt.compare(password, user.password, function (err, res) {
          if (!res)
            return done(null, false, {
              message: 'Invalid Password'
            })
          return done(null, user, {
            message: 'Logged In Successfully'
          })
        })
    })
  }
))

var JwtStrategy = require('passport-jwt').Strategy,
    ExtractJwt  = require('passport-jwt').ExtractJwt

var opts = {}

opts.jwtFromRequest = function(request) {
    let t = ExtractJwt.fromAuthHeader()(request)
    return t
}
opts.secretOrKey = config.secret
opts.issuer      = config.issuer

passport.use(new JwtStrategy(opts, function(jwt_payload, done) {

    Users.findOne({ id: jwt_payload.sub }, function(err, user) {

        if (err) {
            return done(err, false)
        }

        if (user) {
            return done(null, user)
        } else {
            return done(null, false)
        }

    })

}))

passport.use(new FacebookStrategy({
    clientID: process.env.FACEBOOK_API_KEY,
    clientSecret: process.env.FACEBOOK_API_SECRET,
    callbackURL: process.env.FACEBOOK_CALLBACK_URI,
    profileFields: ['id', 'email'],
}, function(accessToken, refreshToken, profile, done) {

    Users.findOrCreate({
        email: profile.emails[0].value
    }, {
        email: profile.emails[0].value,
        facebookId: profile.id
    }, function (err, user) {

        if (err || !user) {
            if (!_.isEmpty(sails.sentry)) {
                sails.sentry.captureMessage(err)
            } else {
                sails.log.warn(err)
            }
        }

        return done(null, user)

    })

}))
<commit_msg>Passport debugging<commit_after>var passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy,
    FacebookStrategy = require('passport-facebook'),
    bcrypt = require('bcrypt')

let config = {
    secret: process.env.JWT_SECRET,
    issuer: 'getstream.io',
    audience: 'getstream.io'
}

module.exports = {
    passport: config
}

passport.serializeUser(function(user, done) {
    done(null, user.id)
})

passport.deserializeUser(function(id, done) {
    Users.findOne({ id: id } , function (err, user) {
        done(err, user)
    })
})

passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password'
  },
  function(email, password, done) {
    Users.findOne({ email: email }, function (err, user) {
      if (err) { return done(err) }
      if (!user) {
        return done(null, false, { message: 'Incorrect email.' })
      }

      bcrypt.compare(password, user.password, function (err, res) {
          if (!res)
            return done(null, false, {
              message: 'Invalid Password'
            })
          return done(null, user, {
            message: 'Logged In Successfully'
          })
        })
    })
  }
))

var JwtStrategy = require('passport-jwt').Strategy,
    ExtractJwt  = require('passport-jwt').ExtractJwt

var opts = {}

opts.jwtFromRequest = function(request) {
    let t = ExtractJwt.fromAuthHeader()(request)
    return t
}
opts.secretOrKey = config.secret
opts.issuer      = config.issuer

passport.use(new JwtStrategy(opts, function(jwt_payload, done) {

    Users.findOne({ id: jwt_payload.sub }, function(err, user) {

        if (err) {
            return done(err, false)
        }

        if (user) {
            return done(null, user)
        } else {
            return done(null, false)
        }

    })

}))

passport.use(new FacebookStrategy({
    clientID: process.env.FACEBOOK_API_KEY,
    clientSecret: process.env.FACEBOOK_API_SECRET,
    callbackURL: process.env.FACEBOOK_CALLBACK_URI,
    profileFields: ['id', 'email'],
}, function(accessToken, refreshToken, profile, done) {

    console.log(profile)

    Users.findOrCreate({
        email: profile.emails[0].value
    }, {
        email: profile.emails[0].value,
        facebookId: profile.id
    }, function (err, user) {

        if (err || !user) {
            if (!_.isEmpty(sails.sentry)) {
                sails.sentry.captureMessage(err)
            } else {
                sails.log.warn(err)
            }
        }

        return done(null, user)

    })

}))
<|endoftext|>