<commit_before>/* globals global, documentMetadata, util, uicontrol, ui, catcher */
/* globals XMLHttpRequest, window, location, alert, domainFromUrl, randomString */
/* globals document, setTimeout, location */

"use strict";

this.shooter = (function() { // eslint-disable-line no-unused-vars
  let exports = {};
  const { AbstractShot } = window.shot;

  const RANDOM_STRING_LENGTH = 16;
  let backend;
  let shot;
  let supportsDrawWindow;
  const callBackground = global.callBackground;
  const clipboard = global.clipboard;

  function regexpEscape(str) {
    // http://stackoverflow.com/questions/3115150/how-to-escape-regular-expression-special-characters-using-javascript
    return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  }

  function sanitizeError(data) {
    const href = new RegExp(regexpEscape(window.location.href), 'g');
    const origin = new RegExp(`${regexpEscape(window.location.origin)}[^\s",>]*`, 'g');
    const json = JSON.stringify(data)
      .replace(href, 'REDACTED_HREF')
      .replace(origin, 'REDACTED_URL');
    const result = JSON.parse(json);
    return result;
  }

  catcher.registerHandler((errorObj) => {
    callBackground("reportError", sanitizeError(errorObj));
  });

  {
    let canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
    let ctx = canvas.getContext('2d');
    supportsDrawWindow = !!ctx.drawWindow;
  }

  function screenshotPage(selectedPos) {
    if (!supportsDrawWindow) {
      return null;
    }
    let height = selectedPos.bottom - selectedPos.top;
    let width = selectedPos.right - selectedPos.left;
    let canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
    canvas.width = width * window.devicePixelRatio;
    canvas.height = height * window.devicePixelRatio;
    let ctx = canvas.getContext('2d');
    if (window.devicePixelRatio !== 1) {
      ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
    }
    ui.iframe.hide();
    try {
      ctx.drawWindow(window, selectedPos.left, selectedPos.top, width, height, "#fff");
    } finally {
      ui.iframe.unhide();
    }
    return canvas.toDataURL();
  }

  let isSaving = null;

  exports.takeShot = function(captureType, selectedPos) {
    // isSaving indicates we're aleady in the middle of saving
    // we use a timeout so in the case of a failure the button will
    // still start working again
    const uicontrol = global.uicontrol;
    let deactivateAfterFinish = true;
    if (isSaving) {
      return;
    }
    isSaving = setTimeout(() => {
      isSaving = null;
    }, 1000);
    selectedPos = selectedPos.asJson();
    let captureText = util.captureEnclosedText(selectedPos);
    let dataUrl = screenshotPage(selectedPos);
    if (dataUrl) {
      shot.addClip({
        createdDate: Date.now(),
        image: {
          url: dataUrl,
          captureType,
          text: captureText,
          location: selectedPos,
          dimensions: {
            x: selectedPos.right - selectedPos.left,
            y: selectedPos.bottom - selectedPos.top
          }
        }
      });
    }
    catcher.watchPromise(callBackground("takeShot", {
      captureType,
      captureText,
      scroll: {
        scrollX: window.scrollX,
        scrollY: window.scrollY,
        innerHeight: window.innerHeight,
        innerWidth: window.innerWidth
      },
      selectedPos,
      shotId: shot.id,
      shot: shot.asJson()
    }).then((url) => {
      const copied = clipboard.copy(url);
      return callBackground("openShot", { url, copied });
    }, (error) => {
      if ('popupMessage' in error && (error.popupMessage = "REQUEST_ERROR" || error.popupMessage == 'CONNECTION_ERROR')) {
        // The error has been signaled to the user, but unlike other errors (or
        // success) we should not abort the selection
        deactivateAfterFinish = false;
        return;
      }
      if (error.name != "BackgroundError") {
        // BackgroundError errors are reported in the Background page
        throw error;
      }
    }).then(() => {
      if (deactivateAfterFinish) {
        uicontrol.deactivate();
      }
    }));
  };

  exports.downloadShot = function(selectedPos) {
    let dataUrl = screenshotPage(selectedPos);
    let promise = Promise.resolve(dataUrl);
    if (!dataUrl) {
      promise = callBackground(
        "screenshotPage",
        selectedPos.asJson(),
        {
          scrollX: window.scrollX,
          scrollY: window.scrollY,
          innerHeight: window.innerHeight,
          innerWidth: window.innerWidth
        });
    }
    catcher.watchPromise(promise.then((dataUrl) => {
      ui.triggerDownload(dataUrl, shot.filename);
      uicontrol.deactivate();
    }));
  };

  exports.sendEvent = function(...args) {
    callBackground("sendEvent", ...args);
  };

  shot = new AbstractShot(
    backend,
    randomString(RANDOM_STRING_LENGTH) + "/" + domainFromUrl(location),
    {
      origin: window.shot.originFromUrl(location.href)
    }
  );
  shot.update(documentMetadata());

  return exports;
})();
null;
<commit_msg>fixed = typo<commit_after>/* globals global, documentMetadata, util, uicontrol, ui, catcher */
/* globals XMLHttpRequest, window, location, alert, domainFromUrl, randomString */
/* globals document, setTimeout, location */

"use strict";

this.shooter = (function() { // eslint-disable-line no-unused-vars
  let exports = {};
  const { AbstractShot } = window.shot;

  const RANDOM_STRING_LENGTH = 16;
  let backend;
  let shot;
  let supportsDrawWindow;
  const callBackground = global.callBackground;
  const clipboard = global.clipboard;

  function regexpEscape(str) {
    // http://stackoverflow.com/questions/3115150/how-to-escape-regular-expression-special-characters-using-javascript
    return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  }

  function sanitizeError(data) {
    const href = new RegExp(regexpEscape(window.location.href), 'g');
    const origin = new RegExp(`${regexpEscape(window.location.origin)}[^\s",>]*`, 'g');
    const json = JSON.stringify(data)
      .replace(href, 'REDACTED_HREF')
      .replace(origin, 'REDACTED_URL');
    const result = JSON.parse(json);
    return result;
  }

  catcher.registerHandler((errorObj) => {
    callBackground("reportError", sanitizeError(errorObj));
  });

  {
    let canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
    let ctx = canvas.getContext('2d');
    supportsDrawWindow = !!ctx.drawWindow;
  }

  function screenshotPage(selectedPos) {
    if (!supportsDrawWindow) {
      return null;
    }
    let height = selectedPos.bottom - selectedPos.top;
    let width = selectedPos.right - selectedPos.left;
    let canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
    canvas.width = width * window.devicePixelRatio;
    canvas.height = height * window.devicePixelRatio;
    let ctx = canvas.getContext('2d');
    if (window.devicePixelRatio !== 1) {
      ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
    }
    ui.iframe.hide();
    try {
      ctx.drawWindow(window, selectedPos.left, selectedPos.top, width, height, "#fff");
    } finally {
      ui.iframe.unhide();
    }
    return canvas.toDataURL();
  }

  let isSaving = null;

  exports.takeShot = function(captureType, selectedPos) {
    // isSaving indicates we're aleady in the middle of saving
    // we use a timeout so in the case of a failure the button will
    // still start working again
    const uicontrol = global.uicontrol;
    let deactivateAfterFinish = true;
    if (isSaving) {
      return;
    }
    isSaving = setTimeout(() => {
      isSaving = null;
    }, 1000);
    selectedPos = selectedPos.asJson();
    let captureText = util.captureEnclosedText(selectedPos);
    let dataUrl = screenshotPage(selectedPos);
    if (dataUrl) {
      shot.addClip({
        createdDate: Date.now(),
        image: {
          url: dataUrl,
          captureType,
          text: captureText,
          location: selectedPos,
          dimensions: {
            x: selectedPos.right - selectedPos.left,
            y: selectedPos.bottom - selectedPos.top
          }
        }
      });
    }
    catcher.watchPromise(callBackground("takeShot", {
      captureType,
      captureText,
      scroll: {
        scrollX: window.scrollX,
        scrollY: window.scrollY,
        innerHeight: window.innerHeight,
        innerWidth: window.innerWidth
      },
      selectedPos,
      shotId: shot.id,
      shot: shot.asJson()
    }).then((url) => {
      const copied = clipboard.copy(url);
      return callBackground("openShot", { url, copied });
    }, (error) => {
      if ('popupMessage' in error && (error.popupMessage == "REQUEST_ERROR" || error.popupMessage == 'CONNECTION_ERROR')) {
        // The error has been signaled to the user, but unlike other errors (or
        // success) we should not abort the selection
        deactivateAfterFinish = false;
        return;
      }
      if (error.name != "BackgroundError") {
        // BackgroundError errors are reported in the Background page
        throw error;
      }
    }).then(() => {
      if (deactivateAfterFinish) {
        uicontrol.deactivate();
      }
    }));
  };

  exports.downloadShot = function(selectedPos) {
    let dataUrl = screenshotPage(selectedPos);
    let promise = Promise.resolve(dataUrl);
    if (!dataUrl) {
      promise = callBackground(
        "screenshotPage",
        selectedPos.asJson(),
        {
          scrollX: window.scrollX,
          scrollY: window.scrollY,
          innerHeight: window.innerHeight,
          innerWidth: window.innerWidth
        });
    }
    catcher.watchPromise(promise.then((dataUrl) => {
      ui.triggerDownload(dataUrl, shot.filename);
      uicontrol.deactivate();
    }));
  };

  exports.sendEvent = function(...args) {
    callBackground("sendEvent", ...args);
  };

  shot = new AbstractShot(
    backend,
    randomString(RANDOM_STRING_LENGTH) + "/" + domainFromUrl(location),
    {
      origin: window.shot.originFromUrl(location.href)
    }
  );
  shot.update(documentMetadata());

  return exports;
})();
null;
<|endoftext|>


<commit_before>
module.exports = function(server, config, log) {

    return {
        inject: function(path) {
            return require(path)(server, config, log);
        }
    }
};
<commit_msg>Always resolve modules from the project root<commit_after>var Path = require('path');

module.exports = function(server, config, log) {

    return {
        inject: function(path) {
            return require(Path.resolve(path))(server, config, log);
        }
    }
};
<|endoftext|>


<commit_before>/**
 * Created by daniel.irwin on 6/6/17.
 * resources used : https://davidwalsh.name/javascript-arguments
 */
'use strict';
module.exports = function (injectables, func, wrapperFunction, hook) {
    const LOG = injectables.logger?new injectables.logger('Injector', hook): { warn : () => {} };

    function getArgs(func) {
        let args = func.toString()
            .replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, '')
            .replace(/=>.*$/mg, '')
            .replace(/=[^,]+/mg, '')
            .match(/\((.*)\)/);
        if (args) {
            return args[1].match(/([^\s,]+)/g) || [];
        }
        return [];
    }

    function injectFunction(fnc, inj, args) {
        let functionCallValue = {};

        if(typeof fnc === 'function'){
            functionCallValue = fnc.apply(null, (args?args:getArgs(fnc).map(argName => inj[argName])));
        }

        if(typeof wrapperFunction === 'function'){
            return wrapperFunction(functionCallValue);
        }
        return functionCallValue;
    }

    function injectArray(array) {
        return array.reduce((acc, v) => {
            acc.push(function (req, res, next) {
                injectFunction(v, Object.assign({req: req, next: next}, injectables));
            });
            return acc;
        }, []);
    }

    /**
     * Injects an object such as the Services directory
     * @param object
     * @param attemptToResolveOrderedDepedendencies
     * @returns {{}}
     */
    function injectObject(object) {
        const injectees = Object.keys(object);
        const MAX_RUNS = injectees.length * injectees.length;

        let injecteeMap = {};
        injectees.forEach((injectee) => {
            if (typeof object[injectee] === 'function') {
                injecteeMap[injectee] = getArgs(object[injectee]);
            }
        });

        let runs = 0;
        while(injectees.length > 0 && MAX_RUNS > ++runs){
            let injecteeName = injectees.shift();

            if (typeof object[injecteeName] === 'function') {
                if(typeof injectables.logger === 'function') {
                    injectables.LOG = new injectables.logger(injecteeName, hook);
                    injectables.console = injectables.LOG;//so you can just inject console
                }

                let dependencies = injecteeMap[injecteeName].map(e => injectables[e]);
                let allDependenciesResolved = dependencies.every(e => e);

                if(allDependenciesResolved) {
                    injectables[injecteeName] = injectFunction(object[injecteeName], injectables, dependencies);
                }
                else {
                    injectees.push(injecteeName);
                }
            }
            else {
                injectables[injecteeName] = object[injecteeName];
            }
        }

        if(injectees.length > 0) {
            injectees.forEach( injecteeName => {
                if (typeof object[injecteeName] === 'function') {
                    let dependencies = injecteeMap[injecteeName].map(e => injectables[e]);
                    let missingDependencies = injecteeMap[injecteeName].filter(e => !injectables[e]);
                    LOG.warn(`last fail injecting ${injecteeName} even though missing ${missingDependencies}`);
                    injectables[injecteeName] = injectFunction(object[injecteeName], injectables, dependencies);
                }
            });
        }

        return injectables;
    }

    // Decision Tree
    // 4 possibilities,
    //  - 1 not acceptable (injectables is not an object or func is not useable)
    //  - 2 func is function do a direct inject on it
    //  - 3 func is object do an inject on function child properties
    //  - 4 func is array do an inject on function values
    let result = {};
    if (typeof injectables === 'object') {
        if (typeof func === 'function') {
            result = injectFunction(func, injectables);
        }

        if (typeof func === 'object') {
            if (Array.isArray(func)) {
                result = injectArray(func);
            }
            else {
                result = injectObject(func);
            }
        }
    }
    return result;
};<commit_msg>make injector a little more verbose in logging<commit_after>/**
 * Created by daniel.irwin on 6/6/17.
 * resources used : https://davidwalsh.name/javascript-arguments
 */
'use strict';
module.exports = function (injectables, func, wrapperFunction, hook) {
    const logger = require('./logger');
    const LOG = new logger('Arupex-Injector');

    function getArgs(func) {
        let args = func.toString()
            .replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, '')
            .replace(/=>.*$/mg, '')
            .replace(/=[^,]+/mg, '')
            .match(/\((.*)\)/);
        if (args) {
            return args[1].match(/([^\s,]+)/g) || [];
        }
        return [];
    }

    function injectFunction(fnc, inj, args) {
        let functionCallValue = {};

        if(typeof fnc === 'function') {
            const argArray = (args ? args : getArgs(fnc)).map(argName => {
                if (inj[argName]) {
                    return inj[argName]
                }
                LOG.critical(`you requested ${argName} but it is not available for injection`);
            });

            functionCallValue = fnc.apply(null, argArray);
        }

        if(typeof wrapperFunction === 'function'){
            return wrapperFunction(functionCallValue);
        }
        return functionCallValue;
    }

    function injectArray(array) {
        return array.reduce((acc, v) => {
            acc.push(function (req, res, next) {
                injectFunction(v, Object.assign({req: req, next: next}, injectables), null);
            });
            return acc;
        }, []);
    }

    /**
     * Injects an object such as the Services directory
     * @param object
     * @param attemptToResolveOrderedDepedendencies
     * @returns {{}}
     */
    function injectObject(object) {
        const injectees = Object.keys(object);
        const MAX_RUNS = injectees.length * injectees.length;

        let injecteeMap = {};
        injectees.forEach((injectee) => {
            if (typeof object[injectee] === 'function') {
                injecteeMap[injectee] = getArgs(object[injectee]);
            }
        });

        let runs = 0;
        while(injectees.length > 0 && MAX_RUNS > ++runs){
            let injecteeName = injectees.shift();

            if (typeof object[injecteeName] === 'function') {
                if(typeof injectables.logger === 'function') {
                    injectables.LOG = new injectables.logger(injecteeName, hook);
                    injectables.console = injectables.LOG;//so you can just inject console
                }

                let dependencies = injecteeMap[injecteeName].map(e => injectables[e]);
                let allDependenciesResolved = dependencies.every(e => e);

                if(allDependenciesResolved) {
                    injectables[injecteeName] = injectFunction(object[injecteeName], injectables, injecteeMap[injecteeName]);
                }
                else {
                    injectees.push(injecteeName);
                }
            }
            else {
                injectables[injecteeName] = object[injecteeName];
            }
        }

        if(injectees.length > 0) {
            injectees.forEach( injecteeName => {
                if (typeof object[injecteeName] === 'function') {
                    let dependencies = injecteeMap[injecteeName].map(e => injectables[e]);
                    let missingDependencies = injecteeMap[injecteeName].filter(e => !injectables[e]);
                    LOG.warn(`last fail injecting ${injecteeName} even though missing ${missingDependencies}`);
                    injectables[injecteeName] = injectFunction(object[injecteeName], injectables, injecteeMap[injecteeName]);
                }
            });
        }

        return injectables;
    }

    // Decision Tree
    // 4 possibilities,
    //  - 1 not acceptable (injectables is not an object or func is not useable)
    //  - 2 func is function do a direct inject on it
    //  - 3 func is object do an inject on function child properties
    //  - 4 func is array do an inject on function values
    let result = {};
    if (typeof injectables === 'object') {
        if (typeof func === 'function') {
            result = injectFunction(func, injectables);
        }

        if (typeof func === 'object') {
            if (Array.isArray(func)) {
                result = injectArray(func);
            }
            else {
                result = injectObject(func);
            }
        }
    }
    return result;
};<|endoftext|>


<commit_before>import Module from './module';

import {
  parse as autoAnnotate,
  annotate
} from './annotation';

import { isArray } from './util';

export default function Injector(modules, parent) {
  parent = parent || {
    get: function(name, strict) {
      currentlyResolving.push(name);

      if (strict === false) {
        return null;
      } else {
        throw error('No provider for "' + name + '"!');
      }
    }
  };

  var currentlyResolving = [];
  var providers = this._providers = Object.create(parent._providers || null);
  var instances = this._instances = Object.create(null);

  var self = instances.injector = this;

  var error = function(msg) {
    var stack = currentlyResolving.join(' -> ');
    currentlyResolving.length = 0;
    return new Error(stack ? msg + ' (Resolving: ' + stack + ')' : msg);
  };

  /**
   * Return a named service.
   *
   * @param {String} name
   * @param {Boolean} [strict=true] if false, resolve missing services to null
   *
   * @return {Object}
   */
  var get = function(name, strict) {
    if (!providers[name] && name.indexOf('.') !== -1) {
      var parts = name.split('.');
      var pivot = get(parts.shift());

      while (parts.length) {
        pivot = pivot[parts.shift()];
      }

      return pivot;
    }

    if (hasProp(instances, name)) {
      return instances[name];
    }

    if (hasProp(providers, name)) {
      if (currentlyResolving.indexOf(name) !== -1) {
        currentlyResolving.push(name);
        throw error('Cannot resolve circular dependency!');
      }

      currentlyResolving.push(name);
      instances[name] = providers[name][0](providers[name][1]);
      currentlyResolving.pop();

      return instances[name];
    }

    return parent.get(name, strict);
  };

  var fnDef = function(fn, locals = {}) {
    if (typeof fn !== 'function') {
      if (isArray(fn)) {
        fn = annotate(fn.slice());
      } else {
        throw new Error('Cannot invoke "' + fn + '". Expected a function!');
      }
    }

    var inject = fn.$inject || autoAnnotate(fn);
    var dependencies = inject.map(function(dep) {
      if (hasProp(locals, dep)) {
        return locals[dep];
      } else {
        return get(dep);
      }
    });

    return {
      fn,
      dependencies
    };
  };

  var instantiate = function(Type) {
    var {
      dependencies,
      fn
    } = fnDef(Type);

    return new fn(...dependencies);
  };

  var invoke = function(func, context, locals) {

    var {
      dependencies,
      fn
    } = fnDef(func, locals);

    return fn.call(context, ...dependencies);
  };

  var createPrivateInjectorFactory = function(privateChildInjector) {
    return annotate(function(key) {
      return privateChildInjector.get(key);
    });
  };

  var createChild = function(modules, forceNewInstances) {
    if (forceNewInstances && forceNewInstances.length) {
      var fromParentModule = Object.create(null);
      var matchedScopes = Object.create(null);

      var privateInjectorsCache = [];
      var privateChildInjectors = [];
      var privateChildFactories = [];

      var provider;
      var cacheIdx;
      var privateChildInjector;
      var privateChildInjectorFactory;
      for (var name in providers) {
        provider = providers[name];

        if (forceNewInstances.indexOf(name) !== -1) {
          if (provider[2] === 'private') {
            cacheIdx = privateInjectorsCache.indexOf(provider[3]);
            if (cacheIdx === -1) {
              privateChildInjector = provider[3].createChild([], forceNewInstances);
              privateChildInjectorFactory = createPrivateInjectorFactory(privateChildInjector);
              privateInjectorsCache.push(provider[3]);
              privateChildInjectors.push(privateChildInjector);
              privateChildFactories.push(privateChildInjectorFactory);
              fromParentModule[name] = [privateChildInjectorFactory, name, 'private', privateChildInjector];
            } else {
              fromParentModule[name] = [privateChildFactories[cacheIdx], name, 'private', privateChildInjectors[cacheIdx]];
            }
          } else {
            fromParentModule[name] = [provider[2], provider[1]];
          }
          matchedScopes[name] = true;
        }

        if ((provider[2] === 'factory' || provider[2] === 'type') && provider[1].$scope) {
          /* jshint -W083 */
          forceNewInstances.forEach(function(scope) {
            if (provider[1].$scope.indexOf(scope) !== -1) {
              fromParentModule[name] = [provider[2], provider[1]];
              matchedScopes[scope] = true;
            }
          });
        }
      }

      forceNewInstances.forEach(function(scope) {
        if (!matchedScopes[scope]) {
          throw new Error('No provider for "' + scope + '". Cannot use provider from the parent!');
        }
      });

      modules.unshift(fromParentModule);
    }

    return new Injector(modules, self);
  };

  var factoryMap = {
    factory: invoke,
    type: instantiate,
    value: function(value) {
      return value;
    }
  };

  modules.forEach(function(module) {

    function arrayUnwrap(type, value) {
      if (type !== 'value' && isArray(value)) {
        value = annotate(value.slice());
      }

      return value;
    }

    // TODO(vojta): handle wrong inputs (modules)
    if (module instanceof Module) {
      module.forEach(function(provider) {
        var name = provider[0];
        var type = provider[1];
        var value = provider[2];

        providers[name] = [factoryMap[type], arrayUnwrap(type, value), type];
      });
    } else if (typeof module === 'object') {
      if (module.__exports__) {
        var clonedModule = Object.keys(module).reduce(function(m, key) {
          if (key.substring(0, 2) !== '__') {
            m[key] = module[key];
          }
          return m;
        }, Object.create(null));

        var privateInjector = new Injector((module.__modules__ || []).concat([clonedModule]), self);
        var getFromPrivateInjector = annotate(function(key) {
          return privateInjector.get(key);
        });
        module.__exports__.forEach(function(key) {
          providers[key] = [getFromPrivateInjector, key, 'private', privateInjector];
        });
      } else {
        Object.keys(module).forEach(function(name) {
          if (module[name][2] === 'private') {
            providers[name] = module[name];
            return;
          }

          var type = module[name][0];
          var value = module[name][1];

          providers[name] = [factoryMap[type], arrayUnwrap(type, value), type];
        });
      }
    }
  });

  // public API
  this.get = get;
  this.invoke = invoke;
  this.instantiate = instantiate;
  this.createChild = createChild;
}

// helpers /////////////////

function hasProp(obj, prop) {
  return Object.hasOwnProperty.call(obj, prop);
}<commit_msg>fix(injector): use Object.prototype.hasOwnPropery<commit_after>import Module from './module';

import {
  parse as autoAnnotate,
  annotate
} from './annotation';

import { isArray } from './util';

export default function Injector(modules, parent) {
  parent = parent || {
    get: function(name, strict) {
      currentlyResolving.push(name);

      if (strict === false) {
        return null;
      } else {
        throw error('No provider for "' + name + '"!');
      }
    }
  };

  var currentlyResolving = [];
  var providers = this._providers = Object.create(parent._providers || null);
  var instances = this._instances = Object.create(null);

  var self = instances.injector = this;

  var error = function(msg) {
    var stack = currentlyResolving.join(' -> ');
    currentlyResolving.length = 0;
    return new Error(stack ? msg + ' (Resolving: ' + stack + ')' : msg);
  };

  /**
   * Return a named service.
   *
   * @param {String} name
   * @param {Boolean} [strict=true] if false, resolve missing services to null
   *
   * @return {Object}
   */
  var get = function(name, strict) {
    if (!providers[name] && name.indexOf('.') !== -1) {
      var parts = name.split('.');
      var pivot = get(parts.shift());

      while (parts.length) {
        pivot = pivot[parts.shift()];
      }

      return pivot;
    }

    if (hasProp(instances, name)) {
      return instances[name];
    }

    if (hasProp(providers, name)) {
      if (currentlyResolving.indexOf(name) !== -1) {
        currentlyResolving.push(name);
        throw error('Cannot resolve circular dependency!');
      }

      currentlyResolving.push(name);
      instances[name] = providers[name][0](providers[name][1]);
      currentlyResolving.pop();

      return instances[name];
    }

    return parent.get(name, strict);
  };

  var fnDef = function(fn, locals = {}) {
    if (typeof fn !== 'function') {
      if (isArray(fn)) {
        fn = annotate(fn.slice());
      } else {
        throw new Error('Cannot invoke "' + fn + '". Expected a function!');
      }
    }

    var inject = fn.$inject || autoAnnotate(fn);
    var dependencies = inject.map(function(dep) {
      if (hasProp(locals, dep)) {
        return locals[dep];
      } else {
        return get(dep);
      }
    });

    return {
      fn,
      dependencies
    };
  };

  var instantiate = function(Type) {
    var {
      dependencies,
      fn
    } = fnDef(Type);

    return new fn(...dependencies);
  };

  var invoke = function(func, context, locals) {

    var {
      dependencies,
      fn
    } = fnDef(func, locals);

    return fn.call(context, ...dependencies);
  };

  var createPrivateInjectorFactory = function(privateChildInjector) {
    return annotate(function(key) {
      return privateChildInjector.get(key);
    });
  };

  var createChild = function(modules, forceNewInstances) {
    if (forceNewInstances && forceNewInstances.length) {
      var fromParentModule = Object.create(null);
      var matchedScopes = Object.create(null);

      var privateInjectorsCache = [];
      var privateChildInjectors = [];
      var privateChildFactories = [];

      var provider;
      var cacheIdx;
      var privateChildInjector;
      var privateChildInjectorFactory;
      for (var name in providers) {
        provider = providers[name];

        if (forceNewInstances.indexOf(name) !== -1) {
          if (provider[2] === 'private') {
            cacheIdx = privateInjectorsCache.indexOf(provider[3]);
            if (cacheIdx === -1) {
              privateChildInjector = provider[3].createChild([], forceNewInstances);
              privateChildInjectorFactory = createPrivateInjectorFactory(privateChildInjector);
              privateInjectorsCache.push(provider[3]);
              privateChildInjectors.push(privateChildInjector);
              privateChildFactories.push(privateChildInjectorFactory);
              fromParentModule[name] = [privateChildInjectorFactory, name, 'private', privateChildInjector];
            } else {
              fromParentModule[name] = [privateChildFactories[cacheIdx], name, 'private', privateChildInjectors[cacheIdx]];
            }
          } else {
            fromParentModule[name] = [provider[2], provider[1]];
          }
          matchedScopes[name] = true;
        }

        if ((provider[2] === 'factory' || provider[2] === 'type') && provider[1].$scope) {
          /* jshint -W083 */
          forceNewInstances.forEach(function(scope) {
            if (provider[1].$scope.indexOf(scope) !== -1) {
              fromParentModule[name] = [provider[2], provider[1]];
              matchedScopes[scope] = true;
            }
          });
        }
      }

      forceNewInstances.forEach(function(scope) {
        if (!matchedScopes[scope]) {
          throw new Error('No provider for "' + scope + '". Cannot use provider from the parent!');
        }
      });

      modules.unshift(fromParentModule);
    }

    return new Injector(modules, self);
  };

  var factoryMap = {
    factory: invoke,
    type: instantiate,
    value: function(value) {
      return value;
    }
  };

  modules.forEach(function(module) {

    function arrayUnwrap(type, value) {
      if (type !== 'value' && isArray(value)) {
        value = annotate(value.slice());
      }

      return value;
    }

    // TODO(vojta): handle wrong inputs (modules)
    if (module instanceof Module) {
      module.forEach(function(provider) {
        var name = provider[0];
        var type = provider[1];
        var value = provider[2];

        providers[name] = [factoryMap[type], arrayUnwrap(type, value), type];
      });
    } else if (typeof module === 'object') {
      if (module.__exports__) {
        var clonedModule = Object.keys(module).reduce(function(m, key) {
          if (key.substring(0, 2) !== '__') {
            m[key] = module[key];
          }
          return m;
        }, Object.create(null));

        var privateInjector = new Injector((module.__modules__ || []).concat([clonedModule]), self);
        var getFromPrivateInjector = annotate(function(key) {
          return privateInjector.get(key);
        });
        module.__exports__.forEach(function(key) {
          providers[key] = [getFromPrivateInjector, key, 'private', privateInjector];
        });
      } else {
        Object.keys(module).forEach(function(name) {
          if (module[name][2] === 'private') {
            providers[name] = module[name];
            return;
          }

          var type = module[name][0];
          var value = module[name][1];

          providers[name] = [factoryMap[type], arrayUnwrap(type, value), type];
        });
      }
    }
  });

  // public API
  this.get = get;
  this.invoke = invoke;
  this.instantiate = instantiate;
  this.createChild = createChild;
}

// helpers /////////////////

function hasProp(obj, prop) {
  return Object.prototype.hasOwnProperty.call(obj, prop);
}<|endoftext|>


<commit_before>/* eslint new-cap:0 */
var _ = require('lodash');
var debug = require('debug')('mongodb-js-metrics:intercom');

var intercom = function() {
  intercom.c(arguments);
};
intercom.q = [];
intercom.c = function(args) {
  intercom.q.push(args);
};

exports.app = null;

/**
 * App state has been updated so notfiy intercom of it.
 */
exports.update = function() {
  window.Intercom('update');
};

// @todo (imlucas): Expose to main renderer via IPC so the server can track
// whatever events it needs to as well.
exports.track = function(eventName, data) {
  if (!exports.app.isFeatureEnabled('intercom')) {
    return;
  }
  intercom('trackEvent', eventName, data);
};

function boot() {
  var config = _.extend(exports.app.user.toJSON(), {
    app_id: _.get(exports.app.config, 'intercom.app_id')
  });
  config.user_id = exports.app.user.id;
  debug('Syncing user info w/ intercom', config);
  intercom('boot', config);
}

exports.open = function(opts) {
  if (opts && opts.message) {
    intercom('showNewMessage', opts.message);
  } else {
    intercom('show');
  }
};

exports.show = function() {
  var el = document.querySelector('#intercom-container .intercom-launcher');
  if (el) {
    el.classList.remove('hidden');
  }
};

exports.hide = function() {
  var el = document.querySelector('#intercom-container .intercom-launcher');
  if (!el) {
    return setTimeout(exports.hide, 100);
  }
  el.classList.add('hidden');
};

/**
 * Injects the intercom client script.
 * @param {Object} app
 */
exports.listen = function(app) {
  exports.app = app;

  if (!app.isFeatureEnabled('intercom')) {
    debug('intercom is not enabled');
    return;
  }

  if (typeof window === 'undefined') {
    /**
     * @todo (imlucas) Update to use new intercom module
     * that works in browser or server.
     */
    return;
  }

  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://widget.intercom.io/widget/p57suhg7';
  head.appendChild(script);
  if (app.user) {
    debug('adding listener to user to boot intercom');
    app.user.on('sync', boot.bind(null, app));
  }

  if (app.router) {
    debug('adding listener to router to update intercom');
    app.router.on('page', exports.update);
  }
};

if (typeof window !== 'undefined') {
  window.Intercom = intercom;
}

module.exports = exports;
<commit_msg>:zap: debugging<commit_after>/* eslint new-cap:0 */
var _ = require('lodash');
var debug = require('debug')('mongodb-js-metrics:intercom');

var intercom = function() {
  intercom.c(arguments);
};
intercom.q = [];
intercom.c = function(args) {
  intercom.q.push(args);
};

exports.app = null;

/**
 * App state has been updated so notfiy intercom of it.
 */
exports.update = function() {
  window.Intercom('update');
};

// @todo (imlucas): Expose to main renderer via IPC so the server can track
// whatever events it needs to as well.
exports.track = function(eventName, data) {
  if (!exports.app.isFeatureEnabled('intercom')) {
    return;
  }
  intercom('trackEvent', eventName, data);
};

function boot() {
  var config = _.extend(exports.app.user.toJSON(), {
    app_id: _.get(exports.app.config, 'intercom.app_id')
  });
  config.user_id = exports.app.user.id;
  debug('Syncing user info w/ intercom', config);
  intercom('boot', config);
}

exports.open = function(opts) {
  if (opts && opts.message) {
    intercom('showNewMessage', opts.message);
  } else {
    intercom('show');
  }
};

exports.show = function() {
  var el = document.querySelector('#intercom-container .intercom-launcher');
  if (el) {
    el.classList.remove('hidden');
  }
};

exports.hide = function() {
  var el = document.querySelector('#intercom-container .intercom-launcher');
  if (!el) {
    return setTimeout(exports.hide, 100);
  }
  el.classList.add('hidden');
};

/**
 * Injects the intercom client script.
 * @param {Object} app
 */
exports.listen = function(app) {
  exports.app = app;

  if (!app.isFeatureEnabled('intercom')) {
    debug('intercom is not enabled');
    return;
  }

  if (typeof window === 'undefined') {
    /**
     * @todo (imlucas) Update to use new intercom module
     * that works in browser or server.
     */
    return;
  }

  debug('injecting widget');
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://widget.intercom.io/widget/p57suhg7';
  head.appendChild(script);
  debug('adding listener to user to boot intercom');
  app.user.on('sync', boot.bind(null, app));

  debug('adding listener to router to update intercom');
  app.router.on('page', exports.update);
};

if (typeof window !== 'undefined') {
  window.Intercom = intercom;
}

module.exports = exports;
<|endoftext|>


<commit_before>// Friendly interval
// Initialize once, then start, stop & restart with single calls

'use strict';

var o = {
	init: function (f, i, start) {
		this.f = f;
		this.i = i;
		if (start) {
			this.start();
		}
		return this;
	},
	start: function () {
		if (!this.t) {
			this.t = setInterval(this.f, this.i);
		}
	},
	stop: function () {
		if (this.t) {
			clearInterval(this.t);
		}
	},
	restart: function () {
		this.stop();
		this.start();
	}
};

module.exports = function (f, i, start) {
	return Object.create(o).init(f, i, start);
};
<commit_msg>interval rely on events<commit_after>// Friendly interval
// Initialize once, then start, stop & restart with single calls

'use strict';

var ee    = require('event-emitter')
  , ntick = require('./next-tick');

var o = ee({
	init: function (i, start) {
		this.f = this.emit.bind(this, 'tick');
		this.i = i;
		if (start) {
			ntick(this.start.bind(this));
		}
		return this;
	},
	start: function () {
		if (!this.t) {
			this.t = setInterval(this.f, this.i);
			this.running = true;
			this.emit('start');
		}
	},
	stop: function () {
		if (this.t) {
			clearInterval(this.t);
			this.t = null;
			this.running = false;
			this.emit('stop');
		}
	},
	restart: function () {
		this.stop();
		this.start();
	}
});

module.exports = function (i, start) {
	return Object.create(o).init(i, start);
};
<|endoftext|>


<commit_before>var buf = require('buffer');
var Buffer = buf.Buffer;

// could use Buffer.isBuffer but this is the same exact thing...
module.exports = Buffer.isBuffer;
<commit_msg>also remove old comment<commit_after>var buf = require('buffer');
var Buffer = buf.Buffer;

module.exports = Buffer.isBuffer;
<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////
//// cron jobs for updating/fetching data
/////////////////////////////////////////////////////////////////////

const CronJob = require('cron').CronJob;
const blockchainApi = require('./../lib/blockchain-info-api');
const BitcoinValue = require('./../model/BitcoinValue.js');
const BitcoinValueHourlyAvg = require('./../model/BitcoinValueHourlyAvg.js');
const BitcoinValueDailyAvg = require('./../model/BitcoinValueDailyAvg.js');
const BitcoinValueMonthlyAvg = require('./../model/BitcoinValueMonthlyAvg.js');
const tools = require('./../lib/tools');

var mongoCallback = function(error, data) {
  if(error)
    console.log(error);
  // else
  //   console.log(data);
}

// cron job every 15 minutes
// var job1 = new CronJob('00 */5 * * * *', function() {
var job1 = new CronJob('00 00,15,30,45 * * * *', function() {
    blockchainApi.fetchCurrentPrice(function (body) {
        BitcoinValue.create({
            value: body.USD.last,
            timestamp: tools.getCurrentTimestamp()
        }, mongoCallback);
    });
}, null, true, 'UTC');

// cron job every hour at :05 minutes
// calc and write avg bitcoin value for previous hour
var job2 = new CronJob('00 05 * * * *', function() {
    // current timestamp in UTC
    var UTCtimestamp = parseInt(new Date().getTime() / 1000);
    // current rouned hour timestamp in UTC
    var roundHourUTCtimestamp = UTCtimestamp - (UTCtimestamp % 3600);
    // previous rouned hour timestamp in UTC
    var prevHourUTCtimestamp = roundHourUTCtimestamp - 3600;

    // get all values for past hour
    // if it's 14:05, then get values between 13:00 and 14:00 (UTC)
    BitcoinValue.find({
        timestamp: {
            $gte: prevHourUTCtimestamp,
            $lte: roundHourUTCtimestamp
        }
    }, function(error, data) {
        // error check
        if(error) {
          console.log(error);
          return false;
        }

        var hourAvg = tools.getDataAverage(data, 'value');

        // skip update if avarage is null
        if (hourAvg === null) return;

        // write hourly avg value to db
        BitcoinValueHourlyAvg.create({
            value: hourAvg,
            timestamp: prevHourUTCtimestamp
        }, mongoCallback);
    });

}, null, true, 'UTC');

// cron job every hour at :59 minutes
// calc and write avg bitcoin value for current day up to this moment
var job3 = new CronJob('00 59 * * * *', function() {

    // // proceed only if it's 0 Hours UTC (12 AM)
    // if (new Date().getUTCHours() != 0) {
    //     return;
    // }

    // current timestamp in UTC
    var UTCtimestamp = parseInt(new Date().getTime() / 1000);
    // current rouned day timestamp in UTC
    var roundDayUTCtimestamp = UTCtimestamp - (UTCtimestamp % (24 * 3600));

    // // previous rouned day timestamp in UTC
    // var prevDayUTCtimestamp = roundDayUTCtimestamp - (24 * 3600);

    // get all hourly average values for past day
    // and calc the average value
    BitcoinValueHourlyAvg.find({
        timestamp: {
            $gte: roundDayUTCtimestamp,
            $lte: UTCtimestamp
        }
    }, function(error, data) {
        // error check
        if(error) {
          console.log(error);
          return false;
        }

        var dailyAvg = tools.getDataAverage(data, 'value');

        // skip update if avarage is null
        if (dailyAvg === null) return;

        // check if there is a daily avg value with this timestamp
        // update/create accordingly
        BitcoinValueDailyAvg.update({
            timestamp: roundDayUTCtimestamp
        },
        { value: dailyAvg},
        function (err, raw) {
            if(err) {
              console.log(err);
            }

            // if not matching object exist,
            // then create new with these values
            if (raw.n == 0) {
                BitcoinValueDailyAvg.create({
                    value: dailyAvg,
                    timestamp: roundDayUTCtimestamp
                }, mongoCallback);
            }
        });
    });

}, null, true, 'UTC');

// cron job every day at 23:55 minutes
// calc and write avg bitcoin value for current month up to this moment
var job4 = new CronJob('00 55 23 * * *', function() {
    // get current year and month
    // build monthly string like '2017-07-01' and convert it to timestamp
    var year = new Date().getUTCFullYear();
    var monthString = tools.monthIntToString(new Date().getUTCMonth());
    var monthlyTimestamp = new Date(
        year + '-' + monthString + '-01'
    ).getTime() / 1000;

    // get all daily average values for past month
    BitcoinValueDailyAvg.find({
        timestamp: {
            $gte: monthlyTimestamp,
        }
    }, function(error, data) {
        // error check
        if(error) {
          console.log(error);
          return false;
        }

        var monthlyAvg = tools.getDataAverage(data, 'value');

        // skip update if avarage is null
        if (monthlyAvg === null) return;

        // check if there is a monthly avg value with this timestamp
        // update/create accordingly
        BitcoinValueMonthlyAvg.update({
            timestamp: monthlyTimestamp
        },
        { value: monthlyAvg},
        function (error, raw) {
            if(error) {
              console.log(error);
              return false;
            }

            // if not matching object exist,
            // then create new with these values
            if (raw.n == 0) {
                BitcoinValueMonthlyAvg.create({
                    value: monthlyAvg,
                    timestamp: monthlyTimestamp
                }, mongoCallback);
            }
        });
    });

}, null, true, 'UTC');

// exports
module.exports = {
    fetchCurrentValue: job1,
    updateHourlyValue: job2,
    updateDailyValue: job3,
    updateMonthlyValue: job4
};
<commit_msg>Add updateHourlyAvgValue() callback and use it in cron job1<commit_after>/////////////////////////////////////////////////////////////////////
//// cron jobs for updating/fetching data
/////////////////////////////////////////////////////////////////////

const CronJob = require('cron').CronJob;
const blockchainApi = require('./../lib/blockchain-info-api');
const BitcoinValue = require('./../model/BitcoinValue.js');
const BitcoinValueHourlyAvg = require('./../model/BitcoinValueHourlyAvg.js');
const BitcoinValueDailyAvg = require('./../model/BitcoinValueDailyAvg.js');
const BitcoinValueMonthlyAvg = require('./../model/BitcoinValueMonthlyAvg.js');
const tools = require('./../lib/tools');

var mongoCallback = function(error, data) {
  if(error)
    console.log(error);
  // else
  //   console.log(data);
}

var updateHourlyAvgValue = function(error, data) {
    // current timestamp in UTC
    var UTCtimestamp = parseInt(new Date().getTime() / 1000);
    // current rouned hour timestamp in UTC
    var roundHourUTCtimestamp = UTCtimestamp - (UTCtimestamp % 3600);

    // get all values for from start of current hour up to now
    // if it's 14:30, then get values between 14:00 and 14:30
    BitcoinValue.find({
        timestamp: {
            $gte: roundHourUTCtimestamp,
            $lte: UTCtimestamp
        }
    }, function(error, data) {
        // error check
        if(error) {
          console.log(error);
          return false;
        }

        var hourAvg = tools.getDataAverage(data, 'value');

        // skip update if avarage is null
        if (hourAvg === null) return;

        // check if there is an hourly avg value with this timestamp
        // update/create accordingly
        BitcoinValueHourlyAvg.update({
            timestamp: roundHourUTCtimestamp
        },
        { value: hourAvg},
        function (err, raw) {
            if(err) {
              console.log(err);
            }

            // if not matching object exist,
            // then create new with these values
            if (raw.n == 0) {
                BitcoinValueHourlyAvg.create({
                    value: hourAvg,
                    timestamp: roundHourUTCtimestamp
                }, mongoCallback);
            }
        });
    });
}

// cron job every 15 minutes
// var job1 = new CronJob('00 */5 * * * *', function() {
var job1 = new CronJob('00 00,15,30,45 * * * *', function() {
    blockchainApi.fetchCurrentPrice(function (body) {
        BitcoinValue.create({
            value: body.USD.last,
            timestamp: tools.getCurrentTimestamp()
        }, updateHourlyAvgValue);
    });
}, null, true, 'UTC');

// // cron job every hour at :05 minutes
// // calc and write avg bitcoin value for previous hour
// var job2 = new CronJob('00 05 * * * *', function() {
//     // current timestamp in UTC
//     var UTCtimestamp = parseInt(new Date().getTime() / 1000);
//     // current rouned hour timestamp in UTC
//     var roundHourUTCtimestamp = UTCtimestamp - (UTCtimestamp % 3600);
//     // previous rouned hour timestamp in UTC
//     var prevHourUTCtimestamp = roundHourUTCtimestamp - 3600;
//
//     // get all values for past hour
//     // if it's 14:05, then get values between 13:00 and 14:00 (UTC)
//     BitcoinValue.find({
//         timestamp: {
//             $gte: prevHourUTCtimestamp,
//             $lte: roundHourUTCtimestamp
//         }
//     }, function(error, data) {
//         // error check
//         if(error) {
//           console.log(error);
//           return false;
//         }
//
//         var hourAvg = tools.getDataAverage(data, 'value');
//
//         // skip update if avarage is null
//         if (hourAvg === null) return;
//
//         // write hourly avg value to db
//         BitcoinValueHourlyAvg.create({
//             value: hourAvg,
//             timestamp: prevHourUTCtimestamp
//         }, mongoCallback);
//     });
//
// }, null, true, 'UTC');

// cron job every hour at :59 minutes
// calc and write avg bitcoin value for current day up to this moment
var job3 = new CronJob('00 59 * * * *', function() {

    // // proceed only if it's 0 Hours UTC (12 AM)
    // if (new Date().getUTCHours() != 0) {
    //     return;
    // }

    // current timestamp in UTC
    var UTCtimestamp = parseInt(new Date().getTime() / 1000);
    // current rouned day timestamp in UTC
    var roundDayUTCtimestamp = UTCtimestamp - (UTCtimestamp % (24 * 3600));

    // // previous rouned day timestamp in UTC
    // var prevDayUTCtimestamp = roundDayUTCtimestamp - (24 * 3600);

    // get all hourly average values for past day
    // and calc the average value
    BitcoinValueHourlyAvg.find({
        timestamp: {
            $gte: roundDayUTCtimestamp,
            $lte: UTCtimestamp
        }
    }, function(error, data) {
        // error check
        if(error) {
          console.log(error);
          return false;
        }

        var dailyAvg = tools.getDataAverage(data, 'value');

        // skip update if avarage is null
        if (dailyAvg === null) return;

        // check if there is a daily avg value with this timestamp
        // update/create accordingly
        BitcoinValueDailyAvg.update({
            timestamp: roundDayUTCtimestamp
        },
        { value: dailyAvg},
        function (err, raw) {
            if(err) {
              console.log(err);
            }

            // if not matching object exist,
            // then create new with these values
            if (raw.n == 0) {
                BitcoinValueDailyAvg.create({
                    value: dailyAvg,
                    timestamp: roundDayUTCtimestamp
                }, mongoCallback);
            }
        });
    });

}, null, true, 'UTC');

// cron job every day at 23:55 minutes
// calc and write avg bitcoin value for current month up to this moment
var job4 = new CronJob('00 55 23 * * *', function() {
    // get current year and month
    // build monthly string like '2017-07-01' and convert it to timestamp
    var year = new Date().getUTCFullYear();
    var monthString = tools.monthIntToString(new Date().getUTCMonth());
    var monthlyTimestamp = new Date(
        year + '-' + monthString + '-01'
    ).getTime() / 1000;

    // get all daily average values for past month
    BitcoinValueDailyAvg.find({
        timestamp: {
            $gte: monthlyTimestamp,
        }
    }, function(error, data) {
        // error check
        if(error) {
          console.log(error);
          return false;
        }

        var monthlyAvg = tools.getDataAverage(data, 'value');

        // skip update if avarage is null
        if (monthlyAvg === null) return;

        // check if there is a monthly avg value with this timestamp
        // update/create accordingly
        BitcoinValueMonthlyAvg.update({
            timestamp: monthlyTimestamp
        },
        { value: monthlyAvg},
        function (error, raw) {
            if(error) {
              console.log(error);
              return false;
            }

            // if not matching object exist,
            // then create new with these values
            if (raw.n == 0) {
                BitcoinValueMonthlyAvg.create({
                    value: monthlyAvg,
                    timestamp: monthlyTimestamp
                }, mongoCallback);
            }
        });
    });

}, null, true, 'UTC');

// exports
module.exports = {
    fetchCurrentValue: job1,
    // updateHourlyValue: job2,
    updateDailyValue: job3,
    updateMonthlyValue: job4
};
<|endoftext|>


<commit_before>/**
 * Item View
 *
 * This is the item view, it is rendered when users visit a page of a specific
 * item. This mainly renders the form to edit the item content in.
 */

import React from 'react';
import { Container, Spinner } from 'elemental';
import { connect } from 'react-redux';
import { Link } from 'react-router';

import { listsByKey } from '../../../utils/lists';
import CreateForm from '../../shared/CreateForm';
import EditForm from './components/EditForm';
import EditFormHeader from './components/EditFormHeader';
import RelatedItemsList from './components/RelatedItemsList';
// import FlashMessages from '../../shared/FlashMessages';

import {
	selectItem,
	loadItemData,
} from './actions';

import {
	selectList,
} from '../List/actions';

var ItemView = React.createClass({
	displayName: 'ItemView',
	contextTypes: {
		router: React.PropTypes.object.isRequired,
	},
	getInitialState () {
		return {
			createIsOpen: false,
		};
	},
	componentDidMount () {
		// When we directly navigate to an item without coming from another client
		// side routed page before, we need to select the list before initializing the item
		if (!this.props.currentList) {
			this.props.dispatch(selectList(this.props.params.listId));
		}
		this.initializeItem(this.props.params.itemId);
	},
	componentWillReceiveProps (nextProps) {
		// We've opened a new item from the client side routing, so initialize
		// again with the new item id
		if (nextProps.params.itemId !== this.props.params.itemId) {
			this.props.dispatch(selectList(nextProps.params.listId));
			this.initializeItem(nextProps.params.itemId);
		}
	},
	// Initialize an item
	initializeItem (itemId) {
		this.props.dispatch(selectItem(itemId));
		this.props.dispatch(loadItemData());
	},
	// Called when a new item is created
	onCreate (item) {
		// Hide the create form
		this.toggleCreateModal(false);
		// Redirect to newly created item path
		const list = this.props.currentList;
		this.context.router.push(`${Keystone.adminPath}/${list.path}/${item.id}`);
	},
	// Open and close the create new item modal
	toggleCreateModal (visible) {
		this.setState({
			createIsOpen: visible,
		});
	},
	// Render this items relationships
	renderRelationships () {
		const { relationships } = this.props.currentList;
		const keys = Object.keys(relationships);
		if (!keys.length) return;
		return (

				<Container>

Relationships

					{keys.map(key => {
						const relationship = relationships[key];
						const refList = listsByKey[relationship.ref];
						return (
							<RelatedItemsList
								key={relationship.path}
								list={this.props.currentList}
								refList={refList}
								relatedItemId={this.props.params.itemId}
								relationship={relationship}
							/>
						);
					})}
				</Container>

		);
	},
	// Handle errors
	handleError (error) {
		const detail = error.detail;
		if (detail) {
			// Item not found
			if (detail.name === 'CastError'
				&& detail.path === '_id') {
				return (
					<Container>

Item not found!

						<Link to={`${Keystone.adminPath}/${this.props.routeParams.listId}`}>
							Go to list
						</Link>
					</Container>
				);
			}
		}
		if (error.message) {
			// Server down + possibly other errors
			if (error.message === 'Internal XMLHttpRequest Error') {
				return (
					<Container>

We encountered some network problems, please try refreshing!

					</Container>
				);
			}
		}
		return (
Error!
);
	},
	render () {
		// If we don't have any data yet, show the loading indicator
		if (!this.props.ready) {
			return (

					<Spinner size="md" />

			);
		}

		// When we have the data, render the item view with it
		return (

				{(this.props.error) ? this.handleError(this.props.error) : (

						<Container>
							<EditFormHeader
								list={this.props.currentList}
								data={this.props.data}
								toggleCreate={this.toggleCreateModal}
							/>
							<CreateForm
								list={this.props.currentList}
								isOpen={this.state.createIsOpen}
								onCancel={() => this.toggleCreateModal(false)}
								onCreate={(item) => this.onCreate(item)}
							/>
							<EditForm
								list={this.props.currentList}
								data={this.props.data}
								dispatch={this.props.dispatch}
								router={this.context.router}
							/>
						</Container>
						{this.renderRelationships()}

				)}

		);
	},
});

module.exports = connect((state) => ({
	data: state.item.data,
	loading: state.item.loading,
	ready: state.item.ready,
	error: state.item.error,
	currentList: state.lists.currentList,
}))(ItemView);
<commit_msg>Fix ItemView's componentDidMount function. Fixes #3528<commit_after>/**
 * Item View
 *
 * This is the item view, it is rendered when users visit a page of a specific
 * item. This mainly renders the form to edit the item content in.
 */

import React from 'react';
import { Container, Spinner } from 'elemental';
import { connect } from 'react-redux';
import { Link } from 'react-router';

import { listsByKey } from '../../../utils/lists';
import CreateForm from '../../shared/CreateForm';
import EditForm from './components/EditForm';
import EditFormHeader from './components/EditFormHeader';
import RelatedItemsList from './components/RelatedItemsList';
// import FlashMessages from '../../shared/FlashMessages';

import {
	selectItem,
	loadItemData,
} from './actions';

import {
	selectList,
} from '../List/actions';

var ItemView = React.createClass({
	displayName: 'ItemView',
	contextTypes: {
		router: React.PropTypes.object.isRequired,
	},
	getInitialState () {
		return {
			createIsOpen: false,
		};
	},
	componentDidMount () {
		// When we directly navigate to an item without coming from another client
		// side routed page before, we need to select the list before initializing the item
		// We also need to update when the list id has changed
		if (!this.props.currentList || this.props.currentList.id !== this.props.params.listId) {
			this.props.dispatch(selectList(this.props.params.listId));
		}
		this.initializeItem(this.props.params.itemId);
	},
	componentWillReceiveProps (nextProps) {
		// We've opened a new item from the client side routing, so initialize
		// again with the new item id
		if (nextProps.params.itemId !== this.props.params.itemId) {
			this.props.dispatch(selectList(nextProps.params.listId));
			this.initializeItem(nextProps.params.itemId);
		}
	},
	// Initialize an item
	initializeItem (itemId) {
		this.props.dispatch(selectItem(itemId));
		this.props.dispatch(loadItemData());
	},
	// Called when a new item is created
	onCreate (item) {
		// Hide the create form
		this.toggleCreateModal(false);
		// Redirect to newly created item path
		const list = this.props.currentList;
		this.context.router.push(`${Keystone.adminPath}/${list.path}/${item.id}`);
	},
	// Open and close the create new item modal
	toggleCreateModal (visible) {
		this.setState({
			createIsOpen: visible,
		});
	},
	// Render this items relationships
	renderRelationships () {
		const { relationships } = this.props.currentList;
		const keys = Object.keys(relationships);
		if (!keys.length) return;
		return (

				<Container>

Relationships

					{keys.map(key => {
						const relationship = relationships[key];
						const refList = listsByKey[relationship.ref];
						return (
							<RelatedItemsList
								key={relationship.path}
								list={this.props.currentList}
								refList={refList}
								relatedItemId={this.props.params.itemId}
								relationship={relationship}
							/>
						);
					})}
				</Container>

		);
	},
	// Handle errors
	handleError (error) {
		const detail = error.detail;
		if (detail) {
			// Item not found
			if (detail.name === 'CastError'
				&& detail.path === '_id') {
				return (
					<Container>

Item not found!

						<Link to={`${Keystone.adminPath}/${this.props.routeParams.listId}`}>
							Go to list
						</Link>
					</Container>
				);
			}
		}
		if (error.message) {
			// Server down + possibly other errors
			if (error.message === 'Internal XMLHttpRequest Error') {
				return (
					<Container>

We encountered some network problems, please try refreshing!

					</Container>
				);
			}
		}
		return (
Error!
);
	},
	render () {
		// If we don't have any data yet, show the loading indicator
		if (!this.props.ready) {
			return (

					<Spinner size="md" />

			);
		}

		// When we have the data, render the item view with it
		return (

				{(this.props.error) ? this.handleError(this.props.error) : (

						<Container>
							<EditFormHeader
								list={this.props.currentList}
								data={this.props.data}
								toggleCreate={this.toggleCreateModal}
							/>
							<CreateForm
								list={this.props.currentList}
								isOpen={this.state.createIsOpen}
								onCancel={() => this.toggleCreateModal(false)}
								onCreate={(item) => this.onCreate(item)}
							/>
							<EditForm
								list={this.props.currentList}
								data={this.props.data}
								dispatch={this.props.dispatch}
								router={this.context.router}
							/>
						</Container>
						{this.renderRelationships()}

				)}

		);
	},
});

module.exports = connect((state) => ({
	data: state.item.data,
	loading: state.item.loading,
	ready: state.item.ready,
	error: state.item.error,
	currentList: state.lists.currentList,
}))(ItemView);
<|endoftext|>


<commit_before>'use strict'

const proxy = Symbol('proxy')
const unobserverSet = Symbol('unobserverSet')
const observing = Symbol('observing')

const targets = new WeakMap()
const observerSet = new Set()
let currentObserver

module.exports = {
  observe,
  unobserve,
  observable,
  isObservable
}

function observe (fn) {
  if (typeof fn !== 'function') {
    throw new TypeError('first argument must be a function')
  }
  if (!fn[observing]) {
    fn[observing] = true
    fn[unobserverSet] = new Set()
    queueObserver(fn)
  }
}

function unobserve (fn) {
  if (typeof fn !== 'function') {
    throw new TypeError('first argument must be a function')
  }
  if (fn[observing]) {
    fn[unobserverSet].forEach(runUnobserver)
    fn[unobserverSet] = undefined
  }
  fn[observing] = false
}

function observable (obj) {
  if (obj === undefined) {
    obj = {}
  }
  if (typeof obj !== 'object') {
    throw new TypeError('first argument must be an object or undefined')
  }
  if (isObservable(obj)) {
    return obj
  }
  if (typeof obj[proxy] === 'object') {
    return obj[proxy]
  }
  obj[proxy] = new Proxy(obj, {get: get, set: set, deleteProperty: deleteProperty})
  targets.set(obj, new Map())
  return obj[proxy]
}

function isObservable (obj) {
  if (typeof obj !== 'object') {
    throw new TypeError('first argument must be an object')
  }
  return (obj[proxy] === true)
}

function get (target, key, receiver) {
  if (key === proxy) {
    return true
  }
  const result = Reflect.get(target, key, receiver)
  if (currentObserver) {
    registerObserver(target, key, currentObserver)
    if (typeof result === 'object' && !(result instanceof Date)) {
      return observable(result)
    }
  }
  if (typeof result === 'object' && typeof result[proxy] === 'object') {
    return result[proxy]
  }
  return result
}

function registerObserver (target, key, observer) {
  let observersForKey = targets.get(target).get(key)
  if (!observersForKey) {
    observersForKey = new Set()
    targets.get(target).set(key, observersForKey)
  }
  if (!observersForKey.has(observer)) {
    observersForKey.add(observer)
    observer[unobserverSet].add(() => observersForKey.delete(observer))
  }
}

function set (target, key, value, receiver) {
  if (targets.get(target).has(key)) {
    targets.get(target).get(key).forEach(queueObserver)
  }
  return Reflect.set(target, key, value, receiver)
}

function deleteProperty (target, key) {
  if (targets.get(target).has(key)) {
    targets.get(target).get(key).forEach(queueObserver)
  }
  return Reflect.deleteProperty(target, key)
}

function queueObserver (observer) {
  if (observerSet.size === 0) {
    Promise.resolve().then(runObservers)
  }
  observerSet.add(observer)
}

function runObservers () {
  try {
    observerSet.forEach(runObserver)
  } finally {
    currentObserver = undefined
    observerSet.clear()
  }
}

function runObserver (observer) {
  if (observer[observing]) {
    currentObserver = observer
    observer()
  }
}

function runUnobserver (unobserver) {
  unobserver()
}
<commit_msg>feat(observable): add $raw to observables<commit_after>'use strict'

const proxy = Symbol('proxy')
const unobserverSet = Symbol('unobserverSet')
const observing = Symbol('observing')

const targets = new WeakMap()
const observerSet = new Set()
let currentObserver

module.exports = {
  observe,
  unobserve,
  observable,
  isObservable
}

function observe (fn) {
  if (typeof fn !== 'function') {
    throw new TypeError('first argument must be a function')
  }
  if (!fn[observing]) {
    fn[observing] = true
    fn[unobserverSet] = new Set()
    runObserver(fn)
  }
}

function unobserve (fn) {
  if (typeof fn !== 'function') {
    throw new TypeError('first argument must be a function')
  }
  if (fn[observing]) {
    fn[unobserverSet].forEach(runUnobserver)
    fn[unobserverSet] = undefined
  }
  fn[observing] = false
}

function observable (obj) {
  if (obj === undefined) {
    obj = {}
  }
  if (typeof obj !== 'object') {
    throw new TypeError('first argument must be an object or undefined')
  }
  if (isObservable(obj)) {
    return obj
  }
  if (typeof obj[proxy] === 'object') {
    return obj[proxy]
  }
  obj[proxy] = new Proxy(obj, {get: get, set: set, deleteProperty: deleteProperty})
  targets.set(obj, new Map())
  return obj[proxy]
}

function isObservable (obj) {
  if (typeof obj !== 'object') {
    throw new TypeError('first argument must be an object')
  }
  return (obj[proxy] === true)
}

function get (target, key, receiver) {
  if (key === proxy) {
    return true
  } else if (key === '$raw') {
    return target
  }
  const result = Reflect.get(target, key, receiver)
  if (currentObserver) {
    registerObserver(target, key, currentObserver)
    if (typeof result === 'object' && !(result instanceof Date)) {
      return observable(result)
    }
  }
  if (typeof result === 'object' && typeof result[proxy] === 'object') {
    return result[proxy]
  }
  return result
}

function registerObserver (target, key, observer) {
  let observersForKey = targets.get(target).get(key)
  if (!observersForKey) {
    observersForKey = new Set()
    targets.get(target).set(key, observersForKey)
  }
  if (!observersForKey.has(observer)) {
    observersForKey.add(observer)
    observer[unobserverSet].add(() => observersForKey.delete(observer))
  }
}

function set (target, key, value, receiver) {
  if (targets.get(target).has(key)) {
    targets.get(target).get(key).forEach(queueObserver)
  }
  return Reflect.set(target, key, value, receiver)
}

function deleteProperty (target, key) {
  if (targets.get(target).has(key)) {
    targets.get(target).get(key).forEach(queueObserver)
  }
  return Reflect.deleteProperty(target, key)
}

function queueObserver (observer) {
  if (observerSet.size === 0) {
    Promise.resolve().then(runObservers)
  }
  observerSet.add(observer)
}

function runObservers () {
  try {
    observerSet.forEach(runObserver)
  } finally {
    observerSet.clear()
  }
}

function runObserver (observer) {
  if (observer[observing]) {
    currentObserver = observer
    try {
      observer()
    } finally {
      currentObserver = undefined
    }
  }
}

function runUnobserver (unobserver) {
  unobserver()
}
<|endoftext|>


<commit_before>// Given a binary tree, find its minimum depth.

// The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

/**
 * @param {TreeNode} root
 * @return {number}
 */

var minDepth = function(root) {
  if( root === null ) return 0;
    var queue = [],
        j = 0;
    queue.push( root );
    while( queue.length ){
        j++;
        var k = queue.length;
        for( var i = 0; i < k; i++ ){
            var node = queue[0];
            if( !node.left && !node.right ) return j;
            queue.shift();
            if( node.left ) queue.push( node.left );
            if( node.right ) queue.push( node.right );
        }
    }
};

// -------------------------------

var minDepth = function(root) { // 139ms runtime
    if( root === null ) return 0;
    var left = minDepth(root.left),
        right = minDepth(root.right);
    // gather smallest depth and add 1 because depth starts at 1
    return (left === 0 || right === 0) ? left + right + 1: Math.min( left,right ) + 1;
};

// -----------------------------------------------

var minDepth = function(root) {
    if( root === null ) return 0;
    if( root.left !== null && root.right !== null ){
        return Math.min( minDepth(root.left), minDepth(root.right) )+1;
    } else {
        return Math.max( minDepth(root.left), minDepth(root.right) )+1;
    }
};

// ---------------------------------------------------------------------

<commit_msg>add notes<commit_after>// Given a binary tree, find its minimum depth.

// The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

/**
 * @param {TreeNode} root
 * @return {number}
 */

// Breadth First Search
var minDepth = function(root) { // 119 ms runtime
  if( root === null ) return 0;
    var queue = [],
        j = 0;
    queue.push( root ); // push root to q
    while( queue.length ){ // as long as root contains anything
        j++;
        var k = queue.length; // reset q's length every pass
        for( var i = 0; i < k; i++ ){ // loop through q
            var node = queue[0]; // store first nod
            if( !node.left && !node.right ) return j; // if no children we reached min depth
            queue.shift(); // de q
            if( node.left ) queue.push( node.left ); // push if node exists
            if( node.right ) queue.push( node.right ); // push if node exists
        }
    }
};

// -------------------------------

var minDepth = function(root) { // 139ms runtime
    if( root === null ) return 0;
    var left = minDepth(root.left),
        right = minDepth(root.right);
    // gather smallest depth and add 1 because depth starts at 1
    return (left === 0 || right === 0) ? left + right + 1: Math.min( left,right ) + 1;
};

// -----------------------------------------------

var minDepth = function(root) {
    if( root === null ) return 0;
    if( root.left !== null && root.right !== null ){
        return Math.min( minDepth(root.left), minDepth(root.right) )+1;
    } else {
        return Math.max( minDepth(root.left), minDepth(root.right) )+1;
    }
};

// ---------------------------------------------------------------------

<|endoftext|>


<commit_before>'use strict';
let pxToIn = px => { return px / 96.75 };
let hexColor = color => {
  if (color[0] === '#') {
    return color;
  } else {
    let rgb = color.match(/\d+/g).map(num => { return parseInt(num).toString(16) });
    return `#${rgb.join('')}`;
  }
}

let commits = $('li.commit');
commits.attr('data-octotrax-hash', function () {
  return this.dataset.channel.split(':').slice(-1)[0];
});

let head = commits.first();
let headHash = head.attr('data-octotrax-hash');
let color = hexColor(head.find('.commit-author').first().css('color'));
let rowHeight = head.height();
let nodeHeight = 9;
let ranksep = rowHeight - nodeHeight;
let dot =
`
digraph "commit graph" {
  rankdir = TB;
  ranksep = "${pxToIn(ranksep)} equally"
  splines = line;
  edge [arrowhead = none, color = "${color}"];
  node [shape = circle, label = "", height = "${pxToIn(nodeHeight)}", color = "${color}"];

  subgraph levels {
    edge [style = invis];
    node [style = invis, height = 0];
    ${Array.from(new Array(commits.length), (_, i) => `"L${i}"`).join(' -> ')};
  }
`;

let username = $('.entry-title .author').text();
let repo = $('.entry-title [itemprop="name"]').text();
let octokat = new Octokat();
octokat.repos(username, repo).commits.fetch(
  {sha: headHash, per_page: commits.length}
).then(rawInfo => {
  let commitInfo = {};
  rawInfo.forEach(commit => {
    commitInfo[commit.sha] = commit;
  });

  commits.toArray().forEach((commit, index) => {
    let hash = commit.dataset.octotraxHash;
    let shortHash = hash.slice(0, 7);
    commitInfo[hash].parents.forEach(parent => {
      dot += `  "${hash}" -> "${parent.sha}";\n`;
    });
    dot += `  { rank = same; "${hash}"; "L${index}"; }\n`
  });
  dot += '}';

  let svg = $(Viz(dot));
  let svgDiv = $('

').attr({id: 'octotrax-commit-graph'}).append(svg);
  svgDiv.css('margin-top', ((rowHeight - nodeHeight) - 2) / 2);
  let commitsListing = $('.commits-listing');
  svgDiv.insertBefore(commitsListing);
  commitsListing.width((_, oldWidth) => {
    return (oldWidth - svgDiv.width()) - 1;
  });
});
<commit_msg>Go back go curved splines. [#5]<commit_after>'use strict';
let pxToIn = px => { return px / 96.75 };
let hexColor = color => {
  if (color[0] === '#') {
    return color;
  } else {
    let rgb = color.match(/\d+/g).map(num => { return parseInt(num).toString(16) });
    return `#${rgb.join('')}`;
  }
}

let commits = $('li.commit');
commits.attr('data-octotrax-hash', function () {
  return this.dataset.channel.split(':').slice(-1)[0];
});

let head = commits.first();
let headHash = head.attr('data-octotrax-hash');
let color = hexColor(head.find('.commit-author').first().css('color'));
let rowHeight = head.height();
let nodeHeight = 9;
let ranksep = rowHeight - nodeHeight;
let dot =
`
digraph "commit graph" {
  rankdir = TB;
  ranksep = "${pxToIn(ranksep)} equally"
  edge [arrowhead = none, color = "${color}"];
  node [shape = circle, label = "", height = "${pxToIn(nodeHeight)}", color = "${color}"];

  subgraph levels {
    edge [style = invis];
    node [style = invis, height = 0];
    ${Array.from(new Array(commits.length), (_, i) => `"L${i}"`).join(' -> ')};
  }
`;

let username = $('.entry-title .author').text();
let repo = $('.entry-title [itemprop="name"]').text();
let octokat = new Octokat();
octokat.repos(username, repo).commits.fetch(
  {sha: headHash, per_page: commits.length}
).then(rawInfo => {
  let commitInfo = {};
  rawInfo.forEach(commit => {
    commitInfo[commit.sha] = commit;
  });

  commits.toArray().forEach((commit, index) => {
    let hash = commit.dataset.octotraxHash;
    let shortHash = hash.slice(0, 7);
    commitInfo[hash].parents.forEach(parent => {
      dot += `  "${hash}" -> "${parent.sha}";\n`;
    });
    dot += `  { rank = same; "${hash}"; "L${index}"; }\n`
  });
  dot += '}';

  let svg = $(Viz(dot));
  let svgDiv = $('

').attr({id: 'octotrax-commit-graph'}).append(svg);
  svgDiv.css('margin-top', ((rowHeight - nodeHeight) - 2) / 2);
  let commitsListing = $('.commits-listing');
  svgDiv.insertBefore(commitsListing);
  commitsListing.width((_, oldWidth) => {
    return (oldWidth - svgDiv.width()) - 1;
  });
});
<|endoftext|>


<commit_before>// Welcome!
// Add your github user if you accepted the challenge!

var players = [
    'raphamorim',
    'israelst',
    'afonsopacifer',
    'rafaelfragosom',
    'paulinhoerry',
    'enieber',
    'alanrsoares',
    'viniciusdacal',
    'thiagosantana',
    'brunodsgn',
    'danilorb',
    'douglasPinheiro',
    'michelwilhelm',
    'rafaelstz',
    'andersonweb',
    'luhad',
    'pablobfonseca',
    'willianjusten',
    'vitorleal',
    'IAMFELIPEMATTOS',
    'JulianSansat',
    'brenopolanski',
    'Pompeu',
    'filipedeschamps',
    'felipesousa',
    'gpedro',
    'leaofelipe',
    'wedneyyuri',
    'jonathanveg',
    'filipe1309',
    'afgoulart',
    'helquisson',
    'vulcanobr',
    'guilouro',
    'pedropolisenso',
    'jozadaquebatista',
    'alfv89',
    'jugoncalves',
    'guilhermeepaixaoo',
    'morvanabonin',
    'andrecgro',
    'thulioph',
    'lucasviola',
    'iceberg20',
    'hugolnx',
    'rafael-neri',
    'chocsx',
    'rtancman',
    'welksonramos',
    'igorsantos07',
    'marabesi',
    'diegosaraujo',
    'mauriciojunior',
    'Rodrigo54',
    'woliveiras',
    'AgtLucas',
    'fredericksilva',
    'theandersonn',
    'jpklzm',
    'edueo',
    'vicnicius',
    'jhonmike',
    'fdaciuk',
    'cesardeazevedo',
    'vinimdocarmo',
    'deseao',
    'henriquebelfort',
    'mabrasil',
    'MacgyverMartins',
    'jackmakiyama',
    'hocraveiro',
    'Gcampes',
    'Nipher'
];

module.exports = players;
<commit_msg>Add Felipe as a challenger<commit_after>// Welcome!
// Add your github user if you accepted the challenge!

var players = [
    'raphamorim',
    'israelst',
    'afonsopacifer',
    'rafaelfragosom',
    'paulinhoerry',
    'enieber',
    'alanrsoares',
    'viniciusdacal',
    'thiagosantana',
    'brunodsgn',
    'danilorb',
    'douglasPinheiro',
    'michelwilhelm',
    'rafaelstz',
    'andersonweb',
    'luhad',
    'pablobfonseca',
    'willianjusten',
    'vitorleal',
    'IAMFELIPEMATTOS',
    'JulianSansat',
    'brenopolanski',
    'Pompeu',
    'filipedeschamps',
    'felipesousa',
    'gpedro',
    'leaofelipe',
    'wedneyyuri',
    'jonathanveg',
    'filipe1309',
    'afgoulart',
    'helquisson',
    'vulcanobr',
    'guilouro',
    'pedropolisenso',
    'jozadaquebatista',
    'alfv89',
    'jugoncalves',
    'guilhermeepaixaoo',
    'morvanabonin',
    'andrecgro',
    'thulioph',
    'lucasviola',
    'iceberg20',
    'hugolnx',
    'rafael-neri',
    'chocsx',
    'rtancman',
    'welksonramos',
    'igorsantos07',
    'marabesi',
    'diegosaraujo',
    'mauriciojunior',
    'Rodrigo54',
    'woliveiras',
    'AgtLucas',
    'fredericksilva',
    'theandersonn',
    'jpklzm',
    'edueo',
    'vicnicius',
    'jhonmike',
    'fdaciuk',
    'cesardeazevedo',
    'vinimdocarmo',
    'deseao',
    'henriquebelfort',
    'mabrasil',
    'MacgyverMartins',
    'jackmakiyama',
    'hocraveiro',
    'Gcampes',
    'Nipher',
    'abysmum'
];

module.exports = players;
<|endoftext|>


<commit_before>/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */
(function(kroll) {
	var TAG = "kroll";
	var global = this;

	kroll.extend = function(thisObject, otherObject)
	{
		if (!otherObject) {
			// extend with what?!  denied!
			return;
		}

		for (var name in otherObject) {
			if (otherObject.hasOwnProperty(name)) {
				thisObject[name] = otherObject[name];
			}
		}

		return thisObject;
	}

	function startup() {
		startup.globalVariables();
		startup.runMain();
	}

	// Used just to differentiate scope vars on java side by
	// using a unique constructor name
	function ScopeVars(vars) {
		if (!vars) {
			return this;
		}

		var keys = Object.keys(vars);
		var length = keys.length;

		for (var i = 0; i < length; ++i) {
			var key = keys[i];
			this[key] = vars[key];
		}
	}

	startup.globalVariables = function() {
		global.kroll = kroll;
		kroll.ScopeVars = ScopeVars;
		kroll.NativeModule = NativeModule; // So external module bootstrap.js can call NativeModule.require directly.

		NativeModule.require('events');
		global.Ti = global.Titanium = NativeModule.require('titanium');
		global.Module = NativeModule.require("module");
	};

	startup.runMain = function(mainModuleID) {
	};

	var runInThisContext = kroll.binding('evals').Script.runInThisContext;

	function NativeModule(id) {
		this.filename = id + '.js';
		this.id = id;
		this.exports = {};
		this.loaded = false;
	}

	NativeModule._source = kroll.binding('natives');
	NativeModule._cache = {};

	NativeModule.require = function(id) {
		if (id == 'native_module') {
			return NativeModule;
		}

		var cached = NativeModule.getCached(id);
		if (cached) {
			return cached.exports;
		}

		if (!NativeModule.exists(id)) {
			throw new Error('No such native module ' + id);
		}

		var nativeModule = new NativeModule(id);

		nativeModule.compile();
		nativeModule.cache();

		return nativeModule.exports;
	};

	NativeModule.getCached = function(id) {
		return NativeModule._cache[id];
	}

	NativeModule.exists = function(id) {
		return (id in NativeModule._source);
	}

	NativeModule.getSource = function(id) {
		return NativeModule._source[id];
	}

	NativeModule.wrap = function(script) {
		return NativeModule.wrapper[0] + script + NativeModule.wrapper[1];
	};

	NativeModule.wrapper = [
		'(function (exports, require, module, __filename, __dirname, Titanium, Ti, global, kroll) {\n',
		'\n});' ];

	NativeModule.prototype.compile = function() {
		if (kroll.runtime == "rhino") {
			// We need to call back into compiled JS Scripts in Rhino
			kroll.requireNative(this.id, this.exports, NativeModule.require, this, this.filename, null, global.Ti, global.Ti, global, kroll);

		} else {
			var source = NativeModule.getSource(this.id);
			source = NativeModule.wrap(source);

			// All native modules have their filename prefixed with ti:/
			var filename = 'ti:/' + this.filename;

			var fn = runInThisContext(source, filename, true);
			fn(this.exports, NativeModule.require, this, this.filename, null, global.Ti, global.Ti, global, kroll);
		}

		this.loaded = true;
	};

	NativeModule.prototype.cache = function() {
		NativeModule._cache[this.id] = this;
	};

	startup();
});
<commit_msg>Fix issue with kroll.extend on Rhino.<commit_after>/**
 * Appcelerator Titanium Mobile
 * Copyright (c) 2011 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Apache Public License
 * Please see the LICENSE included with this distribution for details.
 */
(function(kroll) {
	var TAG = "kroll";
	var global = this;

	// Works identical to Object.hasOwnProperty, except
	// also works if the given object does not have the method
	// on its prototype or it has been masked.
	function hasOwnProperty(object, property) {
		return Object.hasOwnProperty.call(object, property);
	}

	kroll.extend = function(thisObject, otherObject)
	{
		if (!otherObject) {
			// extend with what?!  denied!
			return;
		}

		for (var name in otherObject) {
			if (hasOwnProperty(otherObject, name)) {
				thisObject[name] = otherObject[name];
			}
		}

		return thisObject;
	}

	function startup() {
		startup.globalVariables();
		startup.runMain();
	}

	// Used just to differentiate scope vars on java side by
	// using a unique constructor name
	function ScopeVars(vars) {
		if (!vars) {
			return this;
		}

		var keys = Object.keys(vars);
		var length = keys.length;

		for (var i = 0; i < length; ++i) {
			var key = keys[i];
			this[key] = vars[key];
		}
	}

	startup.globalVariables = function() {
		global.kroll = kroll;
		kroll.ScopeVars = ScopeVars;
		kroll.NativeModule = NativeModule; // So external module bootstrap.js can call NativeModule.require directly.

		NativeModule.require('events');
		global.Ti = global.Titanium = NativeModule.require('titanium');
		global.Module = NativeModule.require("module");
	};

	startup.runMain = function(mainModuleID) {
	};

	var runInThisContext = kroll.binding('evals').Script.runInThisContext;

	function NativeModule(id) {
		this.filename = id + '.js';
		this.id = id;
		this.exports = {};
		this.loaded = false;
	}

	NativeModule._source = kroll.binding('natives');
	NativeModule._cache = {};

	NativeModule.require = function(id) {
		if (id == 'native_module') {
			return NativeModule;
		}

		var cached = NativeModule.getCached(id);
		if (cached) {
			return cached.exports;
		}

		if (!NativeModule.exists(id)) {
			throw new Error('No such native module ' + id);
		}

		var nativeModule = new NativeModule(id);

		nativeModule.compile();
		nativeModule.cache();

		return nativeModule.exports;
	};

	NativeModule.getCached = function(id) {
		return NativeModule._cache[id];
	}

	NativeModule.exists = function(id) {
		return (id in NativeModule._source);
	}

	NativeModule.getSource = function(id) {
		return NativeModule._source[id];
	}

	NativeModule.wrap = function(script) {
		return NativeModule.wrapper[0] + script + NativeModule.wrapper[1];
	};

	NativeModule.wrapper = [
		'(function (exports, require, module, __filename, __dirname, Titanium, Ti, global, kroll) {\n',
		'\n});' ];

	NativeModule.prototype.compile = function() {
		if (kroll.runtime == "rhino") {
			// We need to call back into compiled JS Scripts in Rhino
			kroll.requireNative(this.id, this.exports, NativeModule.require, this, this.filename, null, global.Ti, global.Ti, global, kroll);

		} else {
			var source = NativeModule.getSource(this.id);
			source = NativeModule.wrap(source);

			// All native modules have their filename prefixed with ti:/
			var filename = 'ti:/' + this.filename;

			var fn = runInThisContext(source, filename, true);
			fn(this.exports, NativeModule.require, this, this.filename, null, global.Ti, global.Ti, global, kroll);
		}

		this.loaded = true;
	};

	NativeModule.prototype.cache = function() {
		NativeModule._cache[this.id] = this;
	};

	startup();
});
<|endoftext|>


<commit_before>'use strict'
const Controller = require('trails-controller')
/**
 * Footprint Controller
 *
 * Parse the path and query params and forward them to the FootprintService.
 * The FootprintService is provided by any ORM trailpack, e.g.
 * trailpack-waterline, trailpack-sequelize, etc.
 *
 * @see {@link http://expressjs.com/en/4x/api.html#req}
 */
module.exports = class FootprintController extends Controller {
  create(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)

    FootprintService.create(req.params.model, req.body, options)
      .then(function (elements) {
        res.status(200).json(elements)
      }).catch(function (error) {
      res.boom.wrap(error)
    })
  }

  find(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)
    const criteria = this.app.packs.express4.getCriteriaFromQuery(req.query)
    const id = req.params.id

    let response
    if (id) {
      response = FootprintService.find(req.params.model, id, options)
    }
    else {
      response = FootprintService.find(req.params.model, criteria, options)
    }

    response.then(function (elements) {
      res.status(elements ? 200 : 404).json(elements)
    }).catch(function (error) {
      res.boom.wrap(error)
    })
  }

  update(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)
    const criteria = this.app.packs.express4.getCriteriaFromQuery(req.query)

    const id = req.params.id

    this.log.debug('[FootprintController] (update) model =',
      req.params.model, ', criteria =', req.query, req.params.id,
      ', values = ', req.body)

    let response
    if (id) {
      response = FootprintService.update(req.params.model, id, req.body, options)
    }
    else {
      response = FootprintService.update(req.params.model, criteria, req.body)
    }

    response.then(function (elements) {
      res.status(200).json(elements)
    }).catch(function (error) {
      res.boom.wrap(error)
    })
  }

  destroy(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)
    const criteria = this.app.packs.express4.getCriteriaFromQuery(req.query)
    const id = req.params.id

    let response
    if (id) {
      response = FootprintService.destroy(req.params.model, id, options)
    }
    else {
      response = FootprintService.destroy(req.params.model, criteria, options)
    }

    response.then(function (elements) {
      res.status(200).json(elements)
    }).catch(function (error) {
      res.boom.wrap(error)
    })
  }

  createAssociation(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)

    FootprintService.createAssociation(req.params.parentModel, req.params.parentId, req.params.childAttribute, req.body, options)
      .then(function (elements) {
        res.status(200).json(elements)
      }).catch(function (error) {
      res.boom.wrap(error)
    })
  }

  findAssociation(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)
    const criteria = this.app.packs.express4.getCriteriaFromQuery(req.query)
    const parentModel = req.params.parentModel
    const parentId = req.params.parentId
    const childAttribute = req.params.childAttribute
    const childId = req.params.childId

    let response
    if (childId) {
      response = FootprintService.findAssociation(parentModel, parentId, childAttribute, childId, options)
    }
    else {
      response = FootprintService.findAssociation(parentModel, parentId, childAttribute, criteria, options)
    }

    response.then(function (elements) {
      res.status(elements ? 200 : 404).json(elements)
    }).catch(function (error) {
      res.boom.wrap(error)
    })
  }

  updateAssociation(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)
    const criteria = this.app.packs.express4.getCriteriaFromQuery(req.query)
    const parentModel = req.params.parentModel
    const parentId = req.params.parentId
    const childAttribute = req.params.childAttribute
    const childId = req.params.childId

    let response
    if (childId) {
      response = FootprintService.updateAssociation(parentModel, parentId, childAttribute, childId, req.body, options)
    }
    else {
      response = FootprintService.updateAssociation(parentModel, parentId, childAttribute, criteria, req.body, options)
    }

    response.then(function (elements) {
      res.status(200).json(elements)
    }).catch(function (error) {
      res.boom.wrap(error)
    })
  }

  destroyAssociation(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)
    const criteria = this.app.packs.express4.getCriteriaFromQuery(req.query)
    const parentModel = req.params.parentModel
    const parentId = req.params.parentId
    const childAttribute = req.params.childAttribute
    const childId = req.params.childId

    let response
    if (childId) {
      response = FootprintService.destroyAssociation(parentModel, parentId, childAttribute, childId, options)
    }
    else {
      response = FootprintService.destroyAssociation(parentModel, parentId, childAttribute, criteria, options)
    }

    response.then(function (elements) {
      res.status(200).json(elements)
    }).catch(function (error) {
      res.boom.wrap(error)
    })
  }
}
<commit_msg>Fix eslint error<commit_after>'use strict'
const Controller = require('trails-controller')
/**
 * Footprint Controller
 *
 * Parse the path and query params and forward them to the FootprintService.
 * The FootprintService is provided by any ORM trailpack, e.g.
 * trailpack-waterline, trailpack-sequelize, etc.
 *
 * @see {@link http://expressjs.com/en/4x/api.html#req}
 */
module.exports = class FootprintController extends Controller {
  create(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)

    FootprintService.create(req.params.model, req.body, options)
      .then(function (elements) {
        res.status(200).json(elements)
      }).catch(function (error) {
        res.boom.wrap(error)
      })
  }

  find(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)
    const criteria = this.app.packs.express4.getCriteriaFromQuery(req.query)
    const id = req.params.id

    let response
    if (id) {
      response = FootprintService.find(req.params.model, id, options)
    }
    else {
      response = FootprintService.find(req.params.model, criteria, options)
    }

    response.then(function (elements) {
      res.status(elements ? 200 : 404).json(elements)
    }).catch(function (error) {
      res.boom.wrap(error)
    })
  }

  update(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)
    const criteria = this.app.packs.express4.getCriteriaFromQuery(req.query)

    const id = req.params.id

    this.log.debug('[FootprintController] (update) model =',
      req.params.model, ', criteria =', req.query, req.params.id,
      ', values = ', req.body)

    let response
    if (id) {
      response = FootprintService.update(req.params.model, id, req.body, options)
    }
    else {
      response = FootprintService.update(req.params.model, criteria, req.body)
    }

    response.then(function (elements) {
      res.status(200).json(elements)
    }).catch(function (error) {
      res.boom.wrap(error)
    })
  }

  destroy(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)
    const criteria = this.app.packs.express4.getCriteriaFromQuery(req.query)
    const id = req.params.id

    let response
    if (id) {
      response = FootprintService.destroy(req.params.model, id, options)
    }
    else {
      response = FootprintService.destroy(req.params.model, criteria, options)
    }

    response.then(function (elements) {
      res.status(200).json(elements)
    }).catch(function (error) {
      res.boom.wrap(error)
    })
  }

  createAssociation(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)

    FootprintService.createAssociation(req.params.parentModel, req.params.parentId, req.params.childAttribute, req.body, options)
      .then(function (elements) {
        res.status(200).json(elements)
      }).catch(function (error) {
        res.boom.wrap(error)
      })
  }

  findAssociation(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)
    const criteria = this.app.packs.express4.getCriteriaFromQuery(req.query)
    const parentModel = req.params.parentModel
    const parentId = req.params.parentId
    const childAttribute = req.params.childAttribute
    const childId = req.params.childId

    let response
    if (childId) {
      response = FootprintService.findAssociation(parentModel, parentId, childAttribute, childId, options)
    }
    else {
      response = FootprintService.findAssociation(parentModel, parentId, childAttribute, criteria, options)
    }

    response.then(function (elements) {
      res.status(elements ? 200 : 404).json(elements)
    }).catch(function (error) {
      res.boom.wrap(error)
    })
  }

  updateAssociation(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)
    const criteria = this.app.packs.express4.getCriteriaFromQuery(req.query)
    const parentModel = req.params.parentModel
    const parentId = req.params.parentId
    const childAttribute = req.params.childAttribute
    const childId = req.params.childId

    let response
    if (childId) {
      response = FootprintService.updateAssociation(parentModel, parentId, childAttribute, childId, req.body, options)
    }
    else {
      response = FootprintService.updateAssociation(parentModel, parentId, childAttribute, criteria, req.body, options)
    }

    response.then(function (elements) {
      res.status(200).json(elements)
    }).catch(function (error) {
      res.boom.wrap(error)
    })
  }

  destroyAssociation(req, res) {
    const FootprintService = this.app.services.FootprintService
    const options = this.app.packs.express4.getOptionsFromQuery(req.query)
    const criteria = this.app.packs.express4.getCriteriaFromQuery(req.query)
    const parentModel = req.params.parentModel
    const parentId = req.params.parentId
    const childAttribute = req.params.childAttribute
    const childId = req.params.childId

    let response
    if (childId) {
      response = FootprintService.destroyAssociation(parentModel, parentId, childAttribute, childId, options)
    }
    else {
      response = FootprintService.destroyAssociation(parentModel, parentId, childAttribute, criteria, options)
    }

    response.then(function (elements) {
      res.status(200).json(elements)
    }).catch(function (error) {
      res.boom.wrap(error)
    })
  }
}
<|endoftext|>