<commit_before>import setConfig from './config';
import Report from './report';
import { COLDSTART, VERSION } from './globals';
import { getDnsPromise } from './dns';
import { getHook } from './hooks';
import { convertToString } from './util';
import setupPlugins from './util/setupPlugins';
import getFileUploadMeta from './fileUploadMeta';
import {
  set as setInvocationContext,
  get as getInvocationContext
} from './invocationContext';

/*eslint-disable no-console*/

function setupTimeoutCapture(wrapperInstance) {
  const { context, sendReport, config } = wrapperInstance;
  const { getRemainingTimeInMillis = () => 0 } = context;

  // if getRemainingTimeInMillis returns a very small number, it's probably a local invoke (sls framework perhaps)
  if (config.timeoutWindow < 1 || getRemainingTimeInMillis() < 10) {
    return undefined;
  }

  const maxEndTime = 899900; /* Maximum execution: 100ms short of 15 minutes */
  const configEndTime = Math.max(
    0,
    getRemainingTimeInMillis() - config.timeoutWindow
  );

  const endTime = Math.min(configEndTime, maxEndTime);

  return setTimeout(() => {
    context.iopipe.label('@iopipe/timeout');
    sendReport.call(wrapperInstance, new Error('Timeout Exceeded.'), () => {});
  }, endTime);
}

process.on('unhandledRejection', error => {
  const ctx = getInvocationContext();
  if (ctx && ctx.iopipe && ctx.iopipe.label) {
    // default node behavior is to log these types of errors
    console.error(error);
    ctx.iopipe.label('@iopipe/unhandled-promise-rejection');
    ctx.iopipe.label('@iopipe/error');
  }
});

//TODO: refactor to abide by max-params rule*/
/*eslint-disable max-params*/

class IOpipeWrapperClass {
  constructor(
    originalIdentity,
    libFn,
    plugins = [],
    dnsPromise,
    config,
    userFunc,
    originalEvent,
    originalContext,
    originalCallback
  ) {
    this.startTime = process.hrtime();
    this.startTimestamp = Date.now();
    this.config = config;
    this.metrics = [];
    this.labels = new Set();
    this.originalIdentity = originalIdentity;
    this.event = originalEvent;
    this.originalContext = originalContext;
    this.originalCallback = originalCallback;
    this.userFunc = userFunc;
    this.hasSentReport = false;

    this.plugins = setupPlugins(this, plugins);

    this.runHook('pre:setup');

    // support deprecated iopipe.log
    libFn.log = (...logArgs) => {
      console.warn(
        'iopipe.log is deprecated and will be removed in a future version, please use context.iopipe.metric'
      );
      this.log(...logArgs);
    };

    if (COLDSTART) {
      this.dnsPromise = dnsPromise;
    } else {
      // assign a new dnsPromise if it's not a coldstart because dns could have changed
      this.dnsPromise = getDnsPromise(this.config.host);
    }

    this.setupContext();

    // assign modified methods and objects here
    this.context = Object.assign(this.originalContext, {
      // need to use .bind, otherwise, the this ref inside of each fn is NOT IOpipeWrapperClass
      succeed: this.succeed.bind(this),
      fail: this.fail.bind(this),
      done: this.done.bind(this),
      iopipe: {
        label: this.label.bind(this),
        log: this.log.bind(this),
        metric: this.metric.bind(this),
        version: VERSION,
        config: this.config
      }
    });

    setInvocationContext(this.context);

    this.callback = (err, data) => {
      this.sendReport(err, () => {
        typeof this.originalCallback === 'function' &&
          this.originalCallback(err, data);
      });
    };

    this.timeout = setupTimeoutCapture(this);
    this.report = new Report(this);

    this.runHook('post:setup');

    return this;
  }
  setupContext(reset) {
    // preserve original functions via a property name change
    ['succeed', 'fail', 'done'].forEach(method => {
      const descriptor = Object.getOwnPropertyDescriptor(
        this.originalContext,
        reset ? `original_${method}` : method
      );
      if (descriptor) {
        Object.defineProperty(
          this.originalContext,
          reset ? method : `original_${method}`,
          descriptor
        );
      }
      delete this.originalContext[reset ? `original_${method}` : method];
    });
  }
  debugLog(message, level = 'warn') {
    if (this.config.debug) {
      console[level](message);
    }
  }
  invoke() {
    this.runHook('pre:invoke');
    try {
      return this.userFunc.call(
        this.originalIdentity,
        this.event,
        this.context,
        this.callback
      );
    } catch (err) {
      this.sendReport(err, () => this.originalCallback(err));
      return err;
    }
  }
  async sendReport(err, cb = () => {}) {
    if (!this.hasSentReport) {
      this.hasSentReport = true;
      await this.runHook('post:invoke');
      await this.report.prepare(err);
      await this.runHook('pre:report');
      if (this.timeout) {
        clearTimeout(this.timeout);
      }
      this.report.send(async (...args) => {
        await this.runHook('post:report');
        setInvocationContext(undefined);
        // reset the context back to its original state, otherwise aws gets unhappy
        this.setupContext(true);
        cb(...args);
      });
    }
  }
  async runHook(hook) {
    const hookString = getHook(hook);
    const { plugins = [] } = this;
    try {
      await Promise.all(
        plugins.map(plugin => {
          try {
            const fn = plugin.hooks && plugin.hooks[hookString];
            if (typeof fn === 'function') {
              return fn(this);
            }
          } catch (err) {
            // if this.config is undefined, the hook is probably pre:setup
            // lets error out if that is the case
            if (this.config === undefined || this.config.debug) {
              console.error(err);
            }
          }
          return Promise.resolve();
        })
      );
    } catch (error) {
      if (this.config === undefined || this.config.debug) {
        console.error(error);
      }
    }
  }
  succeed(data) {
    this.sendReport(null, () => {
      this.originalContext.succeed(data);
    });
  }
  fail(err) {
    this.sendReport(err, () => {
      this.originalContext.fail(err);
    });
  }
  done(err, data) {
    this.sendReport(err, () => {
      this.originalContext.done(err, data);
    });
  }
  metric(keyInput, valueInput) {
    let numberValue, stringValue;
    const key = convertToString(keyInput);
    if (key.length > 128) {
      this.debugLog(
        `Metric with key name ${key} is longer than allowed length of 128, metric will not be saved`
      );
      return;
    }
    if (Number.isFinite(valueInput)) {
      numberValue = valueInput;
    } else {
      stringValue = convertToString(valueInput);
    }
    this.metrics.push({
      name: key,
      n: numberValue,
      s: stringValue
    });
    // Automatically label that this invocation contains metrics
    if (!key.startsWith('@iopipe')) {
      this.label('@iopipe/metrics');
    }
  }
  label(name) {
    if (typeof name !== 'string') {
      this.debugLog(`Label ${name} is not a string and will not be saved`);
      return;
    }
    if (name.length > 128) {
      this.debugLog(
        `Label with name ${name} is longer than allowed length of 128, label will not be saved`
      );
      return;
    }
    this.labels.add(name);
  }
  // DEPRECATED: This method is deprecated in favor of .metric and .label
  log(name, value) {
    this.debugLog(
      'context.iopipe.log is deprecated and will be removed in a future version, please use context.iopipe.metric'
    );
    this.metric(name, value);
  }
}

module.exports = options => {
  const config = setConfig(options);
  const { plugins } = config;

  const dnsPromise = getDnsPromise(config.host);
  const libFn = userFunc => {
    if (!config.enabled) {
      // No-op if agent is disabled
      return userFunc;
    }

    if (!config.clientId) {
      console.warn(
        'Your function is wrapped with iopipe, but a valid token was not found. Methods such as iopipe.context.log will fail.'
      );
      // No-op if user doesn't set an IOpipe token.
      return userFunc;
    }

    // Assign .log (deprecated) here to avoid type errors
    if (typeof libFn.log !== 'function') {
      libFn.log = () => {};
    }
    return function OriginalCaller(
      originalEvent,
      originalContext,
      originalCallback
    ) {
      const originalIdentity = this;
      return new IOpipeWrapperClass(
        originalIdentity,
        libFn,
        plugins,
        dnsPromise,
        config,
        userFunc,
        originalEvent,
        originalContext,
        originalCallback
      ).invoke();
    };
  };

  // Alias decorate to the wrapper function
  libFn.decorate = libFn;
  return libFn;
};

module.exports.getContext = getInvocationContext;

module.exports.util = {
  getFileUploadMeta
};
<commit_msg>fix: Fix this var for getRemainingTimeInMillis with NSolid layer (#329)<commit_after>import setConfig from './config';
import Report from './report';
import { COLDSTART, VERSION } from './globals';
import { getDnsPromise } from './dns';
import { getHook } from './hooks';
import { convertToString } from './util';
import setupPlugins from './util/setupPlugins';
import getFileUploadMeta from './fileUploadMeta';
import {
  set as setInvocationContext,
  get as getInvocationContext
} from './invocationContext';

/*eslint-disable no-console*/

function setupTimeoutCapture(wrapperInstance) {
  const { context, sendReport, config } = wrapperInstance;
  const { getRemainingTimeInMillis = () => 0 } = context;

  // if getRemainingTimeInMillis returns a very small number, it's probably a local invoke (sls framework perhaps)
  if (config.timeoutWindow < 1 || getRemainingTimeInMillis() < 10) {
    return undefined;
  }

  const maxEndTime = 899900; /* Maximum execution: 100ms short of 15 minutes */
  const configEndTime = Math.max(
    0,
    getRemainingTimeInMillis.call(context) - config.timeoutWindow
  );

  const endTime = Math.min(configEndTime, maxEndTime);

  return setTimeout(() => {
    context.iopipe.label('@iopipe/timeout');
    sendReport.call(wrapperInstance, new Error('Timeout Exceeded.'), () => {});
  }, endTime);
}

process.on('unhandledRejection', error => {
  const ctx = getInvocationContext();
  if (ctx && ctx.iopipe && ctx.iopipe.label) {
    // default node behavior is to log these types of errors
    console.error(error);
    ctx.iopipe.label('@iopipe/unhandled-promise-rejection');
    ctx.iopipe.label('@iopipe/error');
  }
});

//TODO: refactor to abide by max-params rule*/
/*eslint-disable max-params*/

class IOpipeWrapperClass {
  constructor(
    originalIdentity,
    libFn,
    plugins = [],
    dnsPromise,
    config,
    userFunc,
    originalEvent,
    originalContext,
    originalCallback
  ) {
    this.startTime = process.hrtime();
    this.startTimestamp = Date.now();
    this.config = config;
    this.metrics = [];
    this.labels = new Set();
    this.originalIdentity = originalIdentity;
    this.event = originalEvent;
    this.originalContext = originalContext;
    this.originalCallback = originalCallback;
    this.userFunc = userFunc;
    this.hasSentReport = false;

    this.plugins = setupPlugins(this, plugins);

    this.runHook('pre:setup');

    // support deprecated iopipe.log
    libFn.log = (...logArgs) => {
      console.warn(
        'iopipe.log is deprecated and will be removed in a future version, please use context.iopipe.metric'
      );
      this.log(...logArgs);
    };

    if (COLDSTART) {
      this.dnsPromise = dnsPromise;
    } else {
      // assign a new dnsPromise if it's not a coldstart because dns could have changed
      this.dnsPromise = getDnsPromise(this.config.host);
    }

    this.setupContext();

    // assign modified methods and objects here
    this.context = Object.assign(this.originalContext, {
      // need to use .bind, otherwise, the this ref inside of each fn is NOT IOpipeWrapperClass
      succeed: this.succeed.bind(this),
      fail: this.fail.bind(this),
      done: this.done.bind(this),
      iopipe: {
        label: this.label.bind(this),
        log: this.log.bind(this),
        metric: this.metric.bind(this),
        version: VERSION,
        config: this.config
      }
    });

    setInvocationContext(this.context);

    this.callback = (err, data) => {
      this.sendReport(err, () => {
        typeof this.originalCallback === 'function' &&
          this.originalCallback(err, data);
      });
    };

    this.timeout = setupTimeoutCapture(this);
    this.report = new Report(this);

    this.runHook('post:setup');

    return this;
  }
  setupContext(reset) {
    // preserve original functions via a property name change
    ['succeed', 'fail', 'done'].forEach(method => {
      const descriptor = Object.getOwnPropertyDescriptor(
        this.originalContext,
        reset ? `original_${method}` : method
      );
      if (descriptor) {
        Object.defineProperty(
          this.originalContext,
          reset ? method : `original_${method}`,
          descriptor
        );
      }
      delete this.originalContext[reset ? `original_${method}` : method];
    });
  }
  debugLog(message, level = 'warn') {
    if (this.config.debug) {
      console[level](message);
    }
  }
  invoke() {
    this.runHook('pre:invoke');
    try {
      return this.userFunc.call(
        this.originalIdentity,
        this.event,
        this.context,
        this.callback
      );
    } catch (err) {
      this.sendReport(err, () => this.originalCallback(err));
      return err;
    }
  }
  async sendReport(err, cb = () => {}) {
    if (!this.hasSentReport) {
      this.hasSentReport = true;
      await this.runHook('post:invoke');
      await this.report.prepare(err);
      await this.runHook('pre:report');
      if (this.timeout) {
        clearTimeout(this.timeout);
      }
      this.report.send(async (...args) => {
        await this.runHook('post:report');
        setInvocationContext(undefined);
        // reset the context back to its original state, otherwise aws gets unhappy
        this.setupContext(true);
        cb(...args);
      });
    }
  }
  async runHook(hook) {
    const hookString = getHook(hook);
    const { plugins = [] } = this;
    try {
      await Promise.all(
        plugins.map(plugin => {
          try {
            const fn = plugin.hooks && plugin.hooks[hookString];
            if (typeof fn === 'function') {
              return fn(this);
            }
          } catch (err) {
            // if this.config is undefined, the hook is probably pre:setup
            // lets error out if that is the case
            if (this.config === undefined || this.config.debug) {
              console.error(err);
            }
          }
          return Promise.resolve();
        })
      );
    } catch (error) {
      if (this.config === undefined || this.config.debug) {
        console.error(error);
      }
    }
  }
  succeed(data) {
    this.sendReport(null, () => {
      this.originalContext.succeed(data);
    });
  }
  fail(err) {
    this.sendReport(err, () => {
      this.originalContext.fail(err);
    });
  }
  done(err, data) {
    this.sendReport(err, () => {
      this.originalContext.done(err, data);
    });
  }
  metric(keyInput, valueInput) {
    let numberValue, stringValue;
    const key = convertToString(keyInput);
    if (key.length > 128) {
      this.debugLog(
        `Metric with key name ${key} is longer than allowed length of 128, metric will not be saved`
      );
      return;
    }
    if (Number.isFinite(valueInput)) {
      numberValue = valueInput;
    } else {
      stringValue = convertToString(valueInput);
    }
    this.metrics.push({
      name: key,
      n: numberValue,
      s: stringValue
    });
    // Automatically label that this invocation contains metrics
    if (!key.startsWith('@iopipe')) {
      this.label('@iopipe/metrics');
    }
  }
  label(name) {
    if (typeof name !== 'string') {
      this.debugLog(`Label ${name} is not a string and will not be saved`);
      return;
    }
    if (name.length > 128) {
      this.debugLog(
        `Label with name ${name} is longer than allowed length of 128, label will not be saved`
      );
      return;
    }
    this.labels.add(name);
  }
  // DEPRECATED: This method is deprecated in favor of .metric and .label
  log(name, value) {
    this.debugLog(
      'context.iopipe.log is deprecated and will be removed in a future version, please use context.iopipe.metric'
    );
    this.metric(name, value);
  }
}

module.exports = options => {
  const config = setConfig(options);
  const { plugins } = config;

  const dnsPromise = getDnsPromise(config.host);
  const libFn = userFunc => {
    if (!config.enabled) {
      // No-op if agent is disabled
      return userFunc;
    }

    if (!config.clientId) {
      console.warn(
        'Your function is wrapped with iopipe, but a valid token was not found. Methods such as iopipe.context.log will fail.'
      );
      // No-op if user doesn't set an IOpipe token.
      return userFunc;
    }

    // Assign .log (deprecated) here to avoid type errors
    if (typeof libFn.log !== 'function') {
      libFn.log = () => {};
    }
    return function OriginalCaller(
      originalEvent,
      originalContext,
      originalCallback
    ) {
      const originalIdentity = this;
      return new IOpipeWrapperClass(
        originalIdentity,
        libFn,
        plugins,
        dnsPromise,
        config,
        userFunc,
        originalEvent,
        originalContext,
        originalCallback
      ).invoke();
    };
  };

  // Alias decorate to the wrapper function
  libFn.decorate = libFn;
  return libFn;
};

module.exports.getContext = getInvocationContext;

module.exports.util = {
  getFileUploadMeta
};
<|endoftext|>


<commit_before>'use strict';
var Alexa = require("alexa-sdk");
var request = require('request');

exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.registerHandlers(handlers);
    alexa.execute();
};

var handlers = {
    'LaunchRequest': function () {
        this.emit('SayHello');
    },
    'HelloWorldIntent': function () {
        this.emit('SayHello')
    },
    'SayHello': function () {
        request('http://www.chapin.edu/data/calendar/rsscache/calendar_282.rss', function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body); // Show the HTML for the Modulus homepage.
                this.emit(':tell', body);
            }
            else {
                console.log(error);
            }
        });
        this.emit(':tell', "I don't see any lunch on the calendar today.");
    }
};
<commit_msg>Update index.js<commit_after>'use strict';
var Alexa = require("alexa-sdk");
var request = require('request');

exports.handler = function(event, context, callback) {
    var alexa = Alexa.handler(event, context);
    alexa.registerHandlers(handlers);
    alexa.execute();
};

var handlers = {
    'LaunchRequest': function () {
        this.emit('SayHello');
    },
    'HelloWorldIntent': function () {
        this.emit('SayHello')
    },
    'SayHello': function () {
        console.log('SayHello function start');
        request('http://www.chapin.edu/data/calendar/rsscache/calendar_282.rss', function (error, response, body) {
            console.log('request start');
            if (!error && response.statusCode == 200) {
                console.log(body); // Show the HTML for the Modulus homepage.
                this.emit(':tell', body);
            }
            else {
                console.log(error);
            }
        });
        console.log('SayHello function end');
        this.emit(':tell', "I don't see any lunch on the calendar today.");
    }
};
<|endoftext|>


<commit_before>/** A compiler for make-plural.js
 *
 *  Usage:
 *    ./bin/make-plural                 // checks all locale rules
 *    ./bin/make-plural [lc]            // prints the locale function for LC
 *    ./bin/make-plural [lc] [n] [ord]  // prints the (ORD ? ordinal : plural) category for N in locale LC
 */

var argv = require('minimist')(process.argv.slice(2), {
        default: { locale: null, value: null, ordinal: null, cardinal: null, categories: false },
        alias: { locale: 'l', value: 'v', ordinal: 'o', cardinal: 'c' },
        string: [ 'locale', 'value' ],
        boolean: [ 'categories' ]
    }),
    MakePlural = require('../make-plural').load(
        require('../data/plurals.json'),
        require('../data/ordinals.json')
    );

const commonPlurals = [

`function(n, ord) {
  if (ord) return 'other';
  return 'other';
}`,

`function(n, ord) {
  if (ord) return 'other';
  return (n == 1) ? 'one' : 'other';
}`,

`function(n, ord) {
  if (ord) return 'other';
  return ((n == 0
          || n == 1)) ? 'one' : 'other';
}`,

`function(n, ord) {
  var s = String(n).split('.'), v0 = !s[1];
  if (ord) return 'other';
  return (n == 1 && v0) ? 'one' : 'other';
}`

];

const commonCategories = [
    '{cardinal:["other"],ordinal:["other"]}',
    '{cardinal:["one","other"],ordinal:["other"]}',
    '{cardinal:["one","other"],ordinal:["one","other"]}',
    '{cardinal:["one","two","other"],ordinal:["other"]}'
];

// UMD pattern adapted from https://github.com/umdjs/umd/blob/master/returnExports.js
function umd(global, value) {
    return `
(function (root, ${global}) {
  if (typeof define === 'function' && define.amd) {
    define(${global});
  } else if (typeof exports === 'object') {
    module.exports = ${global};
  } else {
    root.${global} = ${global};
  }
}(this, {
${value}
}));`
}

function mapForEachLanguage(cb, opt) {
    const style = opt && !opt.cardinals ? 'ordinal' : 'cardinal';
    let languages = [];
    for (let lc in MakePlural.rules[style]) {
        const key = /^[A-Z_$][0-9A-Z_$]*$/i.test(lc) ? lc : JSON.stringify(lc),
              mp = new MakePlural(lc, opt).test();
        languages.push(key + ': ' + cb(mp));
    }
    return languages;
}

function printPluralsModule() {
    const plurals = mapForEachLanguage(mp => {
        let fn = mp.toString();
        commonPlurals.forEach(function(p, i) { if (fn === p) fn = `_cp[${i}]`; });
        return fn;
    });
    console.log('var _cp = [\n' + commonPlurals.join(',\n') + '\n];')
    console.log(umd('plurals', plurals.join(',\n\n')));
}

function printCategoriesModule() {
    const categories = mapForEachLanguage(mp => {
        let cat = JSON.stringify(mp.categories).replace(/"(\w+)":/g, '$1:');
        commonCategories.forEach(function(c, i) { if (cat === c) cat = `_cc[${i}]`; });
        return cat;
    });
    console.log('var _cc = [\n  ' + commonCategories.join(',\n  ') + '\n];')
    console.log(umd('pluralCategories', categories.join(',\n')));
}

function truthy(v) {
    if (v === '0' || v === 'false') return false;
    return !!v;
}

argv._.forEach(a => {
    if (argv.locale === null) argv.locale = a;
    else if (argv.value === null) argv.value = a;
    else if (argv.ordinal === null) argv.ordinal = a;
});

MakePlural.cardinals = (argv.cardinal !== null) ? truthy(argv.cardinal) : true;
MakePlural.ordinals = (argv.ordinal !== null) ? truthy(argv.ordinal) : true;

if (argv.locale) {
    const mp = new MakePlural(argv.locale).test();
    if (argv.categories) {
        const cats = mp.categories.cardinal
                         .concat(mp.categories.ordinal)
                         .filter((v, i, self) => self.indexOf(v) === i);
        console.log(cats.join(', '));
    } else if (argv.value !== null) {
        console.log(mp(argv.value, truthy(argv.ordinal)));
    } else {
        console.log(mp.toString(argv.locale));
    }
} else {
    if (argv.categories) {
        printCategoriesModule();
    } else {
        printPluralsModule();
    }
}
<commit_msg>Fix Issue #9 with special check for `in`<commit_after>/** A compiler for make-plural.js
 *
 *  Usage:
 *    ./bin/make-plural                 // checks all locale rules
 *    ./bin/make-plural [lc]            // prints the locale function for LC
 *    ./bin/make-plural [lc] [n] [ord]  // prints the (ORD ? ordinal : plural) category for N in locale LC
 */

var argv = require('minimist')(process.argv.slice(2), {
        default: { locale: null, value: null, ordinal: null, cardinal: null, categories: false },
        alias: { locale: 'l', value: 'v', ordinal: 'o', cardinal: 'c' },
        string: [ 'locale', 'value' ],
        boolean: [ 'categories' ]
    }),
    MakePlural = require('../make-plural').load(
        require('../data/plurals.json'),
        require('../data/ordinals.json')
    );

const commonPlurals = [

`function(n, ord) {
  if (ord) return 'other';
  return 'other';
}`,

`function(n, ord) {
  if (ord) return 'other';
  return (n == 1) ? 'one' : 'other';
}`,

`function(n, ord) {
  if (ord) return 'other';
  return ((n == 0
          || n == 1)) ? 'one' : 'other';
}`,

`function(n, ord) {
  var s = String(n).split('.'), v0 = !s[1];
  if (ord) return 'other';
  return (n == 1 && v0) ? 'one' : 'other';
}`

];

const commonCategories = [
    '{cardinal:["other"],ordinal:["other"]}',
    '{cardinal:["one","other"],ordinal:["other"]}',
    '{cardinal:["one","other"],ordinal:["one","other"]}',
    '{cardinal:["one","two","other"],ordinal:["other"]}'
];

// UMD pattern adapted from https://github.com/umdjs/umd/blob/master/returnExports.js
function umd(global, value) {
    return `
(function (root, ${global}) {
  if (typeof define === 'function' && define.amd) {
    define(${global});
  } else if (typeof exports === 'object') {
    module.exports = ${global};
  } else {
    root.${global} = ${global};
  }
}(this, {
${value}
}));`
}

function mapForEachLanguage(cb, opt) {
    const style = opt && !opt.cardinals ? 'ordinal' : 'cardinal';
    let languages = [];
    for (let lc in MakePlural.rules[style]) {
        const key = /^[A-Z_$][0-9A-Z_$]*$/i.test(lc) && (lc !== 'in') ? lc : JSON.stringify(lc),
              mp = new MakePlural(lc, opt).test();
        languages.push(key + ': ' + cb(mp));
    }
    return languages;
}

function printPluralsModule() {
    const plurals = mapForEachLanguage(mp => {
        let fn = mp.toString();
        commonPlurals.forEach(function(p, i) { if (fn === p) fn = `_cp[${i}]`; });
        return fn;
    });
    console.log('var _cp = [\n' + commonPlurals.join(',\n') + '\n];')
    console.log(umd('plurals', plurals.join(',\n\n')));
}

function printCategoriesModule() {
    const categories = mapForEachLanguage(mp => {
        let cat = JSON.stringify(mp.categories).replace(/"(\w+)":/g, '$1:');
        commonCategories.forEach(function(c, i) { if (cat === c) cat = `_cc[${i}]`; });
        return cat;
    });
    console.log('var _cc = [\n  ' + commonCategories.join(',\n  ') + '\n];')
    console.log(umd('pluralCategories', categories.join(',\n')));
}

function truthy(v) {
    if (v === '0' || v === 'false') return false;
    return !!v;
}

argv._.forEach(a => {
    if (argv.locale === null) argv.locale = a;
    else if (argv.value === null) argv.value = a;
    else if (argv.ordinal === null) argv.ordinal = a;
});

MakePlural.cardinals = (argv.cardinal !== null) ? truthy(argv.cardinal) : true;
MakePlural.ordinals = (argv.ordinal !== null) ? truthy(argv.ordinal) : true;

if (argv.locale) {
    const mp = new MakePlural(argv.locale).test();
    if (argv.categories) {
        const cats = mp.categories.cardinal
                         .concat(mp.categories.ordinal)
                         .filter((v, i, self) => self.indexOf(v) === i);
        console.log(cats.join(', '));
    } else if (argv.value !== null) {
        console.log(mp(argv.value, truthy(argv.ordinal)));
    } else {
        console.log(mp.toString(argv.locale));
    }
} else {
    if (argv.categories) {
        printCategoriesModule();
    } else {
        printPluralsModule();
    }
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import TextField from 'material-ui/TextField';

class MuiGeoSuggest extends Component {
    constructor(props) {
        super(props);

        this.onPlaceChange = props.onPlaceChange;
    }

    componentDidMount() {
        if (typeof window.google !== 'undefined' && typeof window.google.maps !== 'undefined') {

            const inputElement = document.getElementsByName(this.props.name)[0];

            this.apiObj = new window.google.maps.places.Autocomplete(inputElement, this.props.options);

            this.apiObj.addListener('place_changed', () => {
                this.onPlaceChange(this.apiObj.getPlace());
            });
        } else {
            console.error('Google API object is not defined');
        }
    }

    render() {
        const {
            onPlaceChange,
            ...props,
        } = this.props;

        if (onPlaceChange !== this.onPlaceChange) {
            this.onPlaceChange = onPlaceChange;
        }

        const finalProps = {
            ...props,
            placeholder: props.floatingLabelText || props.hintText ? '' : props.placeholder,
        };

        return (
          <TextField {...finalProps} />
        );
    }
};

MuiGeoSuggest.propTypes = {
    name: PropTypes.string,
    onPlaceChange: PropTypes.func,
    floatingLabelText: PropTypes.string,
    hintText: PropTypes.string,
    options: PropTypes.shape({}),
};

MuiGeoSuggest.defaultProps = {
    name: 'muiGeoSuggest',
    onPlaceChange: () => {},
    floatingLabelText: '',
    hintText: '',
    options: {},
};

export default MuiGeoSuggest;<commit_msg>Removed option property before passing props to input in order to avoid browser error<commit_after>import React, { Component, PropTypes } from 'react';
import TextField from 'material-ui/TextField';

class MuiGeoSuggest extends Component {
    constructor(props) {
        super(props);

        this.onPlaceChange = props.onPlaceChange;
    }

    componentDidMount() {
        if (typeof window.google !== 'undefined' && typeof window.google.maps !== 'undefined') {

            const inputElement = document.getElementsByName(this.props.name)[0];

            this.apiObj = new window.google.maps.places.Autocomplete(inputElement, this.props.options);

            this.apiObj.addListener('place_changed', () => {
                this.onPlaceChange(this.apiObj.getPlace());
            });
        } else {
            console.error('Google API object is not defined');
        }
    }

    render() {
        const {
            options,
            onPlaceChange,
            ...props,
        } = this.props;

        if (onPlaceChange !== this.onPlaceChange) {
            this.onPlaceChange = onPlaceChange;
        }

        const finalProps = {
            ...props,
            placeholder: props.floatingLabelText || props.hintText ? '' : props.placeholder,
        };

        return (
          <TextField {...finalProps} />
        );
    }
};

MuiGeoSuggest.propTypes = {
    name: PropTypes.string,
    onPlaceChange: PropTypes.func,
    floatingLabelText: PropTypes.string,
    hintText: PropTypes.string,
    options: PropTypes.shape({}),
};

MuiGeoSuggest.defaultProps = {
    name: 'muiGeoSuggest',
    onPlaceChange: () => {},
    floatingLabelText: '',
    hintText: '',
    options: {},
};

export default MuiGeoSuggest;<|endoftext|>


<commit_before>import _Button from 'components/Button';
import _Card from 'components/Card';
import _StudentCard from 'components/StudentCard';
import _StudentPicture from 'components/StudentPicture';
import _Grid from 'components/Grid';
import _Dialog from 'components/Dialog';
import _Form from 'components/Form';
import _Table from 'components/Table';
import _TopNav from 'components/TopNav';
import _ProgressBar from 'components/ProgressBar';
import _Tabs from 'components/Tabs';
import _createBuildRoute from 'domain/createBuildRoute';
import _connect from 'domain/connect';

export const Button = _Button;
export const Card = _Card;
export const StudentCard = _StudentCard;
export const StudentPicture = _StudentPicture;
export const Grid = _Grid;
export const Dialog = _Dialog;
export const Form = _Form;
export const Table = _Table;
export const TopNav = _TopNav;
export const ProgressBar = _ProgressBar;
export const Tabs = _Tabs;
export const createBuildRoute = _createBuildRoute;
export const connect = _connect;
<commit_msg>Gender is exported<commit_after>import _Button from 'components/Button';
import _Card from 'components/Card';
import _StudentCard from 'components/StudentCard';
import _StudentPicture from 'components/StudentPicture';
import _Grid from 'components/Grid';
import _Dialog from 'components/Dialog';
import _Form from 'components/Form';
import _Table from 'components/Table';
import _TopNav from 'components/TopNav';
import _ProgressBar from 'components/ProgressBar';
import _Tabs from 'components/Tabs';
import _createBuildRoute from 'domain/createBuildRoute';
import _connect from 'domain/connect';
import _Gender from 'domain/Gender';

export const Button = _Button;
export const Card = _Card;
export const StudentCard = _StudentCard;
export const StudentPicture = _StudentPicture;
export const Grid = _Grid;
export const Dialog = _Dialog;
export const Form = _Form;
export const Table = _Table;
export const TopNav = _TopNav;
export const ProgressBar = _ProgressBar;
export const Tabs = _Tabs;
export const createBuildRoute = _createBuildRoute;
export const connect = _connect;
export const Gender = _Gender;
<|endoftext|>


<commit_before>// Module must be started with parameters
//
//  --accesskey="api.ai client access key"
//  --subscriptionkey="api.ai subscription key"
//  --slackkey="slack bot key"
//  --filterambient="true or false to filter ambient messages processing (not all)"
//

'use strict';

var Botkit = require('botkit');

var apiai = require('apiai');
var uuid = require('node-uuid');
var argv = require('minimist')(process.argv.slice(2));

var Entities = require('html-entities').XmlEntities;
var decoder = new Entities();

var apiAiService = apiai(argv.accesskey, argv.subscriptionkey);
var filterAmbient = (argv.filterambient === 'true');

var sessionIds = {};

var controller = Botkit.slackbot({
    debug: false
    //include "log: false" to disable logging
});

var bot = controller.spawn({
    token: argv.slackkey
}).startRTM();

controller.hears(['.*'], ['direct_message', 'direct_mention', 'mention', 'ambient'], function (bot, message) {

    console.log(message.text);

    if (message.type == 'message') {
        if (message.user == bot.identity.id) {
            // message from bot can be skipped
        }
        else if (message.text.indexOf("<@U") == 0) {
            // skip other users direct mentions
        }
        else {
            var requestText = decoder.decode(message.text);

            var channel = message.channel;
            var messageType = message.event;

            console.log(messageType);

            if (!(channel in sessionIds)) {
                sessionIds[channel] = uuid.v1();
            }

            var request = apiAiService.textRequest(requestText,
                {
                    sessionId: sessionIds[channel]
                });

            request.on('response', function (response) {
                console.log(response);

                if (response.result) {
                    var responseText = response.result.fulfillment.speech;
                    var action = response.result.action;
                    var actionIncomplete = response.result.actionIncomplete;

                    console.log("a: " + action + " incomplete: " + actionIncomplete);

                    if (messageType == 'ambient' && filterAmbient) {
                        console.log('ambient, check for action type');

                        if (action &&
                            action.indexOf('smalltalk.') == 0 ||
                            action.indexOf('translate.') == 0 ||
                            action.indexOf('wisdom.') == 0 ||
                            action.indexOf('entertainment.') == 0 ||
                            action.indexOf('weather.') == 0) {

                            console.log('action for ambient');

                            if (responseText) {
                                bot.reply(message, responseText);
                            }
                        }
                    }
                    else {
                        console.log('not ambient, post answer');

                        if (responseText) {
                            bot.reply(message, responseText);
                        }
                    }
                }
            });

            request.on('error', function (error) {
                console.log(error);
            });

            request.end();
        }
    }
});<commit_msg>Check for empty string<commit_after>// Module must be started with parameters
//
//  --accesskey="api.ai client access key"
//  --subscriptionkey="api.ai subscription key"
//  --slackkey="slack bot key"
//  --filterambient="true or false to filter ambient messages processing (not all)"
//

'use strict';

var Botkit = require('botkit');

var apiai = require('apiai');
var uuid = require('node-uuid');
var argv = require('minimist')(process.argv.slice(2));

var Entities = require('html-entities').XmlEntities;
var decoder = new Entities();

var apiAiService = apiai(argv.accesskey, argv.subscriptionkey);
var filterAmbient = (argv.filterambient === 'true');

var sessionIds = {};

var controller = Botkit.slackbot({
    debug: false
    //include "log: false" to disable logging
});

var bot = controller.spawn({
    token: argv.slackkey
}).startRTM();

function isDefined(obj) {
    if(typeof obj == 'undefined') {
        return false;
    }

    if (!obj) {
        return false;
    }

    return obj != null;
}

controller.hears(['.*'], ['direct_message', 'direct_mention', 'mention', 'ambient'], function (bot, message) {

    console.log(message.text);

    if (message.type == 'message') {
        if (message.user == bot.identity.id) {
            // message from bot can be skipped
        }
        else if (message.text.indexOf("<@U") == 0) {
            // skip other users direct mentions
        }
        else {
            var requestText = decoder.decode(message.text);

            var channel = message.channel;
            var messageType = message.event;

            console.log(messageType);

            if (!(channel in sessionIds)) {
                sessionIds[channel] = uuid.v1();
            }

            var request = apiAiService.textRequest(requestText,
                {
                    sessionId: sessionIds[channel]
                });

            request.on('response', function (response) {
                console.log(response);

                if (isDefined(response.result)) {
                    var responseText = response.result.fulfillment.speech;
                    var action = response.result.action;
                    var actionIncomplete = response.result.actionIncomplete;

                    console.log("a: " + action + " incomplete: " + actionIncomplete);

                    if (messageType == 'ambient' && filterAmbient) {
                        console.log('ambient, check for action type');

                        if (isDefined(action) &&
                            action.indexOf('smalltalk.') == 0 ||
                            action.indexOf('translate.') == 0 ||
                            action.indexOf('wisdom.') == 0 ||
                            action.indexOf('entertainment.') == 0 ||
                            action.indexOf('weather.') == 0) {

                            console.log('action for ambient');

                            if (isDefined(responseText)) {
                                bot.reply(message, responseText);
                            }
                        }
                    }
                    else {
                        console.log('not ambient, post answer');

                        if (isDefined(responseText)) {
                            bot.reply(message, responseText);
                        }
                    }
                }
            });

            request.on('error', function (error) {
                console.log(error);
            });

            request.end();
        }
    }
});<|endoftext|>


<commit_before>const REQUEST = '[REQUEST]';
const SUCCESS = '[SUCCESS]';
const ERROR = '[ERROR]';

const actionTypeCreator = status => type => {
  return `${type} ${status}`;
}

export function onRequest(type) {
  return actionTypeCreator(REQUEST)(type);
}
export function onError(type) {
  return actionTypeCreator(ERROR)(type);
}
export function onSuccess(type) {
  return actionTypeCreator(SUCCESS)(type);
}

export function asyncActionCreator({ type, promise, ...rest }) {

  return (dispatch, getState) => {

    dispatch({ type: onRequest(type), ...rest });

    return promise.then(data => dispatch({ type: onSuccess(type) , data, ...rest }))
      .catch(error => dispatch({ type: onError(type), error, ...rest }));

  }
}

export const promiseMiddleware = ({ dispatch }) => next => action => {

  const { type, promise, ...rest} = action;

  if (promise instanceof Promise) {

    dispatch({ type: onRequest(type), ...rest });

    return promise
      .then(data => next({ type: onSuccess(type), data, extra: rest }))
      .catch(error => next({ type: onError(type), error, ...rest }));

  }

  return next(action);

}

export default {
  onRequest,
  onError,
  onSuccess,
  asyncActionCreator,
  promiseMiddleware
}
<commit_msg>improved promise detection<commit_after>const REQUEST = '[REQUEST]';
const SUCCESS = '[SUCCESS]';
const ERROR = '[ERROR]';

const actionTypeCreator = status => type => {
  return `${type} ${status}`;
}

export function onRequest(type) {
  return actionTypeCreator(REQUEST)(type);
}
export function onError(type) {
  return actionTypeCreator(ERROR)(type);
}
export function onSuccess(type) {
  return actionTypeCreator(SUCCESS)(type);
}

export function asyncActionCreator({ type, promise, ...rest }) {

  return (dispatch, getState) => {

    dispatch({ type: onRequest(type), ...rest });

    return promise.then(data => dispatch({ type: onSuccess(type) , data, ...rest }))
      .catch(error => dispatch({ type: onError(type), error, ...rest }));

  }
}

export const promiseMiddleware = ({ dispatch }) => next => action => {

  const { type, promise, ...rest} = action;

  const isPromise = typeof (promise || {}).then === 'function'

  if (!isPromise) return next(action);

  dispatch({ type: onRequest(type), ...rest });

  return promise
    .then(data => next({ type: onSuccess(type), data, extra: rest }))
    .catch(error => next({ type: onError(type), error, ...rest }));

}

export default {
  onRequest,
  onError,
  onSuccess,
  asyncActionCreator,
  promiseMiddleware
}
<|endoftext|>


<commit_before>/*

This file contains a linker for bundles of (redux) actions and reducers,
(redux-saga) selectors and sagas, and (React) views.

A bundle is implemented as a generator that yields linker steps to:

  - include another bundle;
  - declare the use of dependencies defined by other bundles;
  - define an action, selector, or view;
  - add an action reducer or a saga

A bundle's generator function takes as its single argument an object which
the linker populates with the definitions made or used by the bundle.
A shared flat namespace is used for actions, selectors, and views.

Actions are redux actions and have string values.

Selectors are cheap functions that take the global state and extract a limited
view of it.  A selector may be defined in terms of other selectors, and may
also be used in action reducers and sagas.

Multiple action reducers for the same action are currently not supported (an
exception is thrown at link time), but they could be composed in link order.

If a selector match the name of a view name, the view is connected to the
store using the selector.

*/

import {createStore, applyMiddleware, compose} from 'redux';
import createSagaMiddleware from 'redux-saga';
import {delay} from 'redux-saga';
import {call, cancelled, fork} from 'redux-saga/effects';
import {connect} from 'react-redux';

function makeSafeProxy (obj, onError) {
  if (typeof Proxy !== 'function') {
    return obj;
  }
  const safeGet = function (target, property) {
    if (property in target) {
      return target[property];
    } else {
      return onError(target, property);
    }
  }
  return new Proxy(obj, {get: safeGet});
}

export function include (bundle) {
  return {type: 'include', bundle};
};

export function use (...names) {
  return {type: 'use', names};
};

export const def = defineValue;

export function defineValue (name, value) {
  return {type: 'define', name, value};
};

export function defineAction (name, action) {
  return {type: 'defineAction', name, action};
};

export function defineSelector (name, selector) {
  return {type: 'defineSelector', name, selector};
};

export function defineView (name, selector, view) {
  if (view === undefined) {
    view = selector;
    selector = undefined;
  }
  return {type: 'defineView', name, view, selector};
};

// Add an action reducer.
export function addReducer (name, reducer) {
  return {type: 'addReducer', name, reducer};
};

export function addSaga (saga) {
  return {type: 'addSaga', saga};
};

export function addEnhancer (enhancer) {
  return {type: 'addEnhancer', enhancer};
};

export function link (rootBundle) {

  // name → value
  const scope = {};

  // Map(action type → action name)
  const nameForActionType = new Map();

  // action name → action reducer
  const reducerMap = new Map();

  const sagas = [];

  const enhancers = [];

  // Reducer linking is deferred until all actions have been defined.
  const reducerQueue = [];

  // 'use' directives are queued and dependency objects are populated after
  // all definitions have taken effect.
  const useQueue = [];

  // View linking is defered until all selectors have been added.
  const viewQueue = [];

  const linkErrors = [];

  function undeclaredDependencyError (target, property) {
    throw new Error(`use of undeclared dependency ${property}`);
  }

  const depsBase = {
    get: function (name) {
      return scope[name];
    }
  };

  function include_ (bundle) {
    const base = Object.create(depsBase);
    const deps = makeSafeProxy(base, undeclaredDependencyError);
    let it;
    try {
      it = bundle(deps);
    } catch (ex) {
      console.error('error in bundle', bundle);
      throw ex;
    }
    let result = it.next();
    while (!result.done) {
      interpretDirective(result.value, deps);
      result = it.next();
    }
  }

  function defineAction_ (name, action) {
    if (name in scope) {
      throw new Error(`linker conflict on ${name}`);
    }
    if (nameForActionType.has(action)) {
      throw `action type conflict: ${action}`;
    }
    scope[name] = action;
    nameForActionType.set(action, name);
  }

  function define_ (name, value) {
    if (name in scope) {
      throw new Error(`linker conflict on ${name}`);
    }
    scope[name] = value;
  }

  function addReducer_ (name, reducer) {
    if (!(name in scope)) {
      throw new Error(`reducer for undefined action ${name}`);
    }
    const actionType = scope[name];
    if (reducerMap.has(actionType)) {
      const prevReducer = reducerMap.get(actionType);
      reducerMap.set(actionType, function (state, action) {
        return reducer(prevReducer(state, action), action);
      });
    } else {
      reducerMap.set(actionType, reducer);
    }
  }

  function interpretDirective (dir, deps) {
    switch (dir.type) {
      case 'include':
        include_(dir.bundle);
        break;
      case 'use':
        useQueue.push([deps, dir.names]);
        break;
      case 'define':
        define_(dir.name, dir.value);
        useQueue.push([deps, dir.name]);
        break;
      case 'defineAction':
        defineAction_(dir.name, dir.action);
        useQueue.push([deps, dir.name]);
        break;
      case 'defineSelector':
        define_(dir.name, dir.selector);
        useQueue.push([deps, dir.name]);
        break;
      case 'defineView':
        viewQueue.push(dir);
        useQueue.push([deps, dir.name]);
        break;
      case 'addReducer':
        reducerQueue.push(dir);
        break;
      case 'addSaga':
        sagas.push(dir.saga);
        break;
      case 'addEnhancer':
        enhancers.push(dir.enhancer);
        break;
      default:
        throw `unhandled link directive type ${dir.type}`;
    }
  }

  function provide (deps, name) {
    if (name in scope) {
      deps[name] = scope[name];
    } else {
      throw new Error(`undefined dependency: ${name}`);
    }
  }

  include_(rootBundle);

  // Define reducers.
  reducerQueue.forEach(function (dir) {
    addReducer_(dir.name, dir.reducer);
  });

  // Define and connect views.
  viewQueue.forEach(function (dir) {
    let {name, selector, view} = dir;
    if (selector in scope) {
      view = connect(scope[selector])(view);
      view.displayName = `View(${name})`;
    }
    scope[name] = view;
  });

  // Provide dependencies.
  useQueue.forEach(function (item) {
    const deps = item[0];
    if (typeof item[1] === 'string') {
      provide(deps, item[1]);
    } else if (Array.isArray(item[1])) {
      item[1].forEach(name => provide(deps, name));
    } else {
      throw new Error('invalid use');
    }
  });

  // Build the reducer.
  const reducer = function (state, action) {
    // TODO: add support for reducer hooks
    if (reducerMap.has(action.type)) {
      try {
        state = reducerMap.get(action.type)(state, action);
      } catch (ex) {
        console.log('exception in reducer', action, state, ex);
      }
    }
    return state;
  }

  const sagaMiddleware = createSagaMiddleware();
  let enhancer = applyMiddleware(sagaMiddleware);
  enhancers.forEach(function (other) {
    enhancer = compose(enhancer, other);
  });

  // Create the store.
  const store = createStore(reducer, null, enhancer);

  function* runSaga (saga) {
    try {
      yield call(saga);
    } catch (ex) {
      console.log(`saga ${saga.name} has exited`, ex);
    }
  }

  // Start the sagas.
  function* rootSaga () {
    yield sagas.map(saga => fork(runSaga, saga));
  }

  function start () {
    sagaMiddleware.run(rootSaga);
  }

  return {store, scope, start};
};
<commit_msg>support plain function selectors in defineView<commit_after>/*

This file contains a linker for bundles of (redux) actions and reducers,
(redux-saga) selectors and sagas, and (React) views.

A bundle is implemented as a generator that yields linker steps to:

  - include another bundle;
  - declare the use of dependencies defined by other bundles;
  - define an action, selector, or view;
  - add an action reducer or a saga

A bundle's generator function takes as its single argument an object which
the linker populates with the definitions made or used by the bundle.
A shared flat namespace is used for actions, selectors, and views.

Actions are redux actions and have string values.

Selectors are cheap functions that take the global state and extract a limited
view of it.  A selector may be defined in terms of other selectors, and may
also be used in action reducers and sagas.

Multiple action reducers for the same action are currently not supported (an
exception is thrown at link time), but they could be composed in link order.

If a selector match the name of a view name, the view is connected to the
store using the selector.

*/

import {createStore, applyMiddleware, compose} from 'redux';
import createSagaMiddleware from 'redux-saga';
import {delay} from 'redux-saga';
import {call, cancelled, fork} from 'redux-saga/effects';
import {connect} from 'react-redux';

function makeSafeProxy (obj, onError) {
  if (typeof Proxy !== 'function') {
    return obj;
  }
  const safeGet = function (target, property) {
    if (property in target) {
      return target[property];
    } else {
      return onError(target, property);
    }
  }
  return new Proxy(obj, {get: safeGet});
}

export function include (bundle) {
  return {type: 'include', bundle};
};

export function use (...names) {
  return {type: 'use', names};
};

export const def = defineValue;

export function defineValue (name, value) {
  return {type: 'define', name, value};
};

export function defineAction (name, action) {
  return {type: 'defineAction', name, action};
};

export function defineSelector (name, selector) {
  return {type: 'defineSelector', name, selector};
};

export function defineView (name, selector, view) {
  if (view === undefined) {
    view = selector;
    selector = undefined;
  }
  return {type: 'defineView', name, view, selector};
};

// Add an action reducer.
export function addReducer (name, reducer) {
  return {type: 'addReducer', name, reducer};
};

export function addSaga (saga) {
  return {type: 'addSaga', saga};
};

export function addEnhancer (enhancer) {
  return {type: 'addEnhancer', enhancer};
};

export function link (rootBundle) {

  // name → value
  const scope = {};

  // Map(action type → action name)
  const nameForActionType = new Map();

  // action name → action reducer
  const reducerMap = new Map();

  const sagas = [];

  const enhancers = [];

  // Reducer linking is deferred until all actions have been defined.
  const reducerQueue = [];

  // 'use' directives are queued and dependency objects are populated after
  // all definitions have taken effect.
  const useQueue = [];

  // View linking is defered until all selectors have been added.
  const viewQueue = [];

  const linkErrors = [];

  function undeclaredDependencyError (target, property) {
    throw new Error(`use of undeclared dependency ${property}`);
  }

  const depsBase = {
    get: function (name) {
      return scope[name];
    }
  };

  function include_ (bundle) {
    const base = Object.create(depsBase);
    const deps = makeSafeProxy(base, undeclaredDependencyError);
    let it;
    try {
      it = bundle(deps);
    } catch (ex) {
      console.error('error in bundle', bundle);
      throw ex;
    }
    let result = it.next();
    while (!result.done) {
      interpretDirective(result.value, deps);
      result = it.next();
    }
  }

  function defineAction_ (name, action) {
    if (name in scope) {
      throw new Error(`linker conflict on ${name}`);
    }
    if (nameForActionType.has(action)) {
      throw `action type conflict: ${action}`;
    }
    scope[name] = action;
    nameForActionType.set(action, name);
  }

  function define_ (name, value) {
    if (name in scope) {
      throw new Error(`linker conflict on ${name}`);
    }
    scope[name] = value;
  }

  function addReducer_ (name, reducer) {
    if (!(name in scope)) {
      throw new Error(`reducer for undefined action ${name}`);
    }
    const actionType = scope[name];
    if (reducerMap.has(actionType)) {
      const prevReducer = reducerMap.get(actionType);
      reducerMap.set(actionType, function (state, action) {
        return reducer(prevReducer(state, action), action);
      });
    } else {
      reducerMap.set(actionType, reducer);
    }
  }

  function interpretDirective (dir, deps) {
    switch (dir.type) {
      case 'include':
        include_(dir.bundle);
        break;
      case 'use':
        useQueue.push([deps, dir.names]);
        break;
      case 'define':
        define_(dir.name, dir.value);
        useQueue.push([deps, dir.name]);
        break;
      case 'defineAction':
        defineAction_(dir.name, dir.action);
        useQueue.push([deps, dir.name]);
        break;
      case 'defineSelector':
        define_(dir.name, dir.selector);
        useQueue.push([deps, dir.name]);
        break;
      case 'defineView':
        viewQueue.push(dir);
        useQueue.push([deps, dir.name]);
        break;
      case 'addReducer':
        reducerQueue.push(dir);
        break;
      case 'addSaga':
        sagas.push(dir.saga);
        break;
      case 'addEnhancer':
        enhancers.push(dir.enhancer);
        break;
      default:
        throw `unhandled link directive type ${dir.type}`;
    }
  }

  function provide (deps, name) {
    if (name in scope) {
      deps[name] = scope[name];
    } else {
      throw new Error(`undefined dependency: ${name}`);
    }
  }

  include_(rootBundle);

  // Define reducers.
  reducerQueue.forEach(function (dir) {
    addReducer_(dir.name, dir.reducer);
  });

  // Define and connect views.
  viewQueue.forEach(function (dir) {
    let {name, selector, view} = dir;
    if (selector !== undefined) {
      if (typeof selector === 'string') {
        selector = scope[selector];
      }
    }
    if (typeof selector === 'function') {
      view = connect(selector)(view);
    }
    view.displayName = `View(${name})`;
    scope[name] = view;
  });

  // Provide dependencies.
  useQueue.forEach(function (item) {
    const deps = item[0];
    if (typeof item[1] === 'string') {
      provide(deps, item[1]);
    } else if (Array.isArray(item[1])) {
      item[1].forEach(name => provide(deps, name));
    } else {
      throw new Error('invalid use');
    }
  });

  // Build the reducer.
  const reducer = function (state, action) {
    // TODO: add support for reducer hooks
    if (reducerMap.has(action.type)) {
      try {
        state = reducerMap.get(action.type)(state, action);
      } catch (ex) {
        console.log('exception in reducer', action, state, ex);
      }
    }
    return state;
  }

  const sagaMiddleware = createSagaMiddleware();
  let enhancer = applyMiddleware(sagaMiddleware);
  enhancers.forEach(function (other) {
    enhancer = compose(enhancer, other);
  });

  // Create the store.
  const store = createStore(reducer, null, enhancer);

  function* runSaga (saga) {
    try {
      yield call(saga);
    } catch (ex) {
      console.log(`saga ${saga.name} has exited`, ex);
    }
  }

  // Start the sagas.
  function* rootSaga () {
    yield sagas.map(saga => fork(runSaga, saga));
  }

  function start () {
    sagaMiddleware.run(rootSaga);
  }

  return {store, scope, start};
};
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { render } from 'react-dom'

import AppContainer from './AppContainer'

import {
  getGmailLocationToInject,
  widgetInsidePanel,
  labelControlsContainer,
  gmailControlsContainer,
  hambugerMenuContainer
} from './config'

const GMAIL_QUICK_LINKS_CONTAINER = 'gmailQuickLinksContainer'

const beginReact = accountName => location => {
  render(
    <AppContainer accountName={accountName} location={location} />,
    document.getElementById(GMAIL_QUICK_LINKS_CONTAINER)
  )
}

const injectReact = location => {
  // create a div for our react container to be injected
  const gmailQuickLinksContainer = document.createElement('div')
  gmailQuickLinksContainer.id = GMAIL_QUICK_LINKS_CONTAINER

  if (location === 'widget') {
    widgetInsidePanel().append(gmailQuickLinksContainer)
  } else {
    if (isMaterialUi()) {
      labelControlsContainer().insertAdjacentElement(
        'beforebegin',
        gmailQuickLinksContainer
      )
    } else {
      getGmailLocationToInject().append(gmailQuickLinksContainer)
    }
  }

  console.log('Loaded Gmail Quick Links')

  //TODO: what is the person isn't signed in?  Does this crash extension?
  const currentAccountName = isMaterialUi()
    ? //new gmail ui
      (
        document.querySelectorAll('a[class="gb_b gb_ib gb_R"]')[0] ||
        document.querySelectorAll('a[class="gb_b gb_db gb_R"]')[0]
      ).attributes['aria-label'].nodeValue.match(/\(([^)]+)\)/)[1]
    : //old gmail ui
      document
        .querySelectorAll('a[href*="accounts.google.com"]')[0]
        .title.match(/\(([^)]+)\)/)[1]

  //load react
  beginReact(currentAccountName)(location)
}

const checkWidgetPanel = untilStop => {
  const startTime = new Date().getTime()

  const intervalId = setInterval(() => {
    if (new Date().getTime() - startTime > untilStop * 1000) {
      clearInterval(intervalId)
    }

    if (widgetInsidePanel()) {
      clearInterval(intervalId)

      console.log('unloading Gmail Quick Links due to presense of widget panel')
      document.getElementById(GMAIL_QUICK_LINKS_CONTAINER).remove()

      injectReact('widget')
    }
  }, 500)
}

//is this the new gmail?  do we have an image showing the new gmail ui logo?
const isMaterialUi = () =>
  document.getElementsByClassName('gb_1a')[1] ||
  document.getElementsByClassName('gb_Va')[1]
    ? true
    : false

// there are cases where the gmail left nav panel isn't loaded yet,
// so we need to check for it until it exists before we can proceed
const checkDomElementExist = setInterval(() => {
  if (getGmailLocationToInject()) {
    clearInterval(checkDomElementExist)

    //TODO: if hamburger menu is collapsed, then remove quick links, else show
    // //add event listener to hamburger menu if it exists
    // if (hambugerMenuContainer()) {
    //   document
    //     .getElementsByClassName('gb_jc')[0]
    //     .addEventListener('click', () => {
    //       if (gmailControlsContainer().offsetWidth < 100) {
    //         document.getElementById(GMAIL_QUICK_LINKS_CONTAINER) &&
    //           document.getElementById(GMAIL_QUICK_LINKS_CONTAINER).remove()
    //       } else {
    //         document.getElementById(GMAIL_QUICK_LINKS_CONTAINER) &&
    //           document.getElementById(GMAIL_QUICK_LINKS_CONTAINER).remove()
    //         injectReact()
    //       }
    //     })
    // }

    //check the presense of a widget panel for 20 seconds, then stop checking
    checkWidgetPanel(20)

    injectReact()
  }
}, 200)
<commit_msg>update gmail querySelectors due to gmail changes<commit_after>import React, { Component } from 'react'
import { render } from 'react-dom'

import AppContainer from './AppContainer'

import {
  getGmailLocationToInject,
  widgetInsidePanel,
  labelControlsContainer,
  gmailControlsContainer,
  hambugerMenuContainer
} from './config'

const GMAIL_QUICK_LINKS_CONTAINER = 'gmailQuickLinksContainer'

const beginReact = accountName => location => {
  render(
    <AppContainer accountName={accountName} location={location} />,
    document.getElementById(GMAIL_QUICK_LINKS_CONTAINER)
  )
}

const injectReact = location => {
  // create a div for our react container to be injected
  const gmailQuickLinksContainer = document.createElement('div')
  gmailQuickLinksContainer.id = GMAIL_QUICK_LINKS_CONTAINER

  if (location === 'widget') {
    widgetInsidePanel().append(gmailQuickLinksContainer)
  } else {
    if (isMaterialUi()) {
      labelControlsContainer().insertAdjacentElement(
        'beforebegin',
        gmailQuickLinksContainer
      )
    } else {
      getGmailLocationToInject().append(gmailQuickLinksContainer)
    }
  }

  console.log('Loaded Gmail Quick Links')

  //TODO: what is the person isn't signed in?  Does this crash extension?
  const currentAccountName = isMaterialUi()
    ? //new gmail ui
      (
        document.querySelectorAll('a[class="gb_b gb_eb gb_R"]')[0] ||
        document.querySelectorAll('a[class="gb_b gb_db gb_R"]')[0]
      ).attributes['aria-label'].nodeValue.match(/\(([^)]+)\)/)[1]
    : //old gmail ui
      document
        .querySelectorAll('a[href*="accounts.google.com"]')[0]
        .title.match(/\(([^)]+)\)/)[1]

  //load react
  beginReact(currentAccountName)(location)
}

const checkWidgetPanel = untilStop => {
  const startTime = new Date().getTime()

  const intervalId = setInterval(() => {
    if (new Date().getTime() - startTime > untilStop * 1000) {
      clearInterval(intervalId)
    }

    if (widgetInsidePanel()) {
      clearInterval(intervalId)

      console.log('unloading Gmail Quick Links due to presense of widget panel')
      document.getElementById(GMAIL_QUICK_LINKS_CONTAINER).remove()

      injectReact('widget')
    }
  }, 500)
}

//is this the new gmail?  do we have an image showing the new gmail ui logo?
const isMaterialUi = () =>
  document.getElementsByClassName('gb_Wa')[1] ||
  document.getElementsByClassName('gb_Va')[1]
    ? true
    : false

// there are cases where the gmail left nav panel isn't loaded yet,
// so we need to check for it until it exists before we can proceed
const checkDomElementExist = setInterval(() => {
  if (getGmailLocationToInject()) {
    clearInterval(checkDomElementExist)

    //TODO: if hamburger menu is collapsed, then remove quick links, else show
    // //add event listener to hamburger menu if it exists
    // if (hambugerMenuContainer()) {
    //   document
    //     .getElementsByClassName('gb_jc')[0]
    //     .addEventListener('click', () => {
    //       if (gmailControlsContainer().offsetWidth < 100) {
    //         document.getElementById(GMAIL_QUICK_LINKS_CONTAINER) &&
    //           document.getElementById(GMAIL_QUICK_LINKS_CONTAINER).remove()
    //       } else {
    //         document.getElementById(GMAIL_QUICK_LINKS_CONTAINER) &&
    //           document.getElementById(GMAIL_QUICK_LINKS_CONTAINER).remove()
    //         injectReact()
    //       }
    //     })
    // }

    //check the presense of a widget panel for 20 seconds, then stop checking
    checkWidgetPanel(20)

    injectReact()
  }
}, 200)
<|endoftext|>


<commit_before>var gulp = require('gulp');
var path = require('path');
var chalk = require('chalk');
var fs = require('fs-extra');
require('date-format-lite');

var config = fs.readJsonSync('conf/config.json');
var liferayHome = config.liferayHome;
var bundleHome = config.bundleHome;

var docrootHome = path.join(liferayHome, 'portal-web', 'docroot');
var rootHome = path.join(bundleHome, 'tomcat-7.0.42', 'webapps', 'ROOT');

function startGulpWatch(src, dest) {
	console.log(chalk.bgBlack.gray('Starting watcher...'));

	gulp.watch(path.join(src,'**/*.*'), function(event) {
		var filePath = path.dirname(event.path).replace(src, dest);

		gulp.src(event.path)
			.pipe(gulp.dest(filePath));

		var now = new Date();
		var time = now.format("hh:mm:ss")

		console.log(chalk.yellow(time) + ' - ' +  chalk.green('Updated file: ') + event.path.replace(src, ''));
	});

	console.log(chalk.bgBlack.gray('Listening for changes to') + chalk.bgBlack(' \"docroot\".') + '\n');
}

function printError(error) {
	console.log(chalk.red(error));
}

if (!liferayHome.length || !bundleHome.length) {
	printError('Please run \"npm run config\" to configure your source and bundle paths');
}
else if (fs.existsSync(docrootHome) && fs.existsSync(rootHome)) {
	startGulpWatch(docrootHome, rootHome);
}
else {
	printError('Make sure \"liferayHome\" is pointed to your Liferay source directory.');
	printError('Make sure \"bundleHome\" is pointed to the top-level bundle directory.');
}

<commit_msg>Use gulp-watcher instead (faster startup and built-in output)<commit_after>var gulp = require('gulp');
var path = require('path');
var chalk = require('chalk');
var fs = require('fs-extra');
var watch = require('gulp-watch');
require('date-format-lite');

// Variables

var config = fs.readJsonSync('conf/config.json');

var liferayHome = config.liferayHome;
var bundleHome = config.bundleHome;

var docrootHome = path.join(liferayHome, 'portal-web', 'docroot');
var rootHome = path.join(bundleHome, 'tomcat-7.0.42', 'webapps', 'ROOT');

var watcherOptions = {
	name: 'Liferay Source Watcher',
	verbose: true
};

// Methods

function printError(error) {
	console.log(chalk.red(error));
}

function startGulpWatch(src, dest) {
	console.log(chalk.bgBlack.gray('Starting watcher...'));

	watch(path.join(src,'**/*.*'), watcherOptions)
		.pipe(gulp.dest(dest));

	console.log(chalk.bgBlack.gray('Listening for changes to') + chalk.bgBlack(' \"docroot\".') + '\n');
}

if (!liferayHome.length || !bundleHome.length) {
	printError('Please run \"npm run config\" to configure your source and bundle paths');
}
else if (fs.existsSync(docrootHome) && fs.existsSync(rootHome)) {
	startGulpWatch(docrootHome, rootHome);
}
else {
	printError('Make sure \"liferayHome\" is pointed to your Liferay source directory.');
	printError('Make sure \"bundleHome\" is pointed to the top-level bundle directory.');
}

<|endoftext|>


<commit_before>"use strict";
const fs = require('graceful-fs');
const path = require('path');
const co = require('co');
const cheerio = require('cheerio');
const _ = require('lodash');
const ProgressBar = require('progress');

class Parser {
    constructor(resourcePath) {
        this.resourcePath = resourcePath;
        this.debugMode = false;
        this.defaultEncoding = 'utf8';
        this.progressBar = undefined;
    }

    run(callback) {
        co.call(this, function *() {
            let exists = yield this.isExist();
            if (!exists) {
                throw new Error(this.resourcePath + ' is NOT exists.');
            }
            let stats = yield this.isDirectory();
            if (stats.isDirectory()) {
                let files = yield this.getFiles();
                this.progressBar = new ProgressBar('  Parsing [:bar] :percent :etas :file :timestamp', {
                    complete: '=',
                    incomplete: ' ',
                    width: 20,
                    total: files.length
                });
                let promiseList = [];
                for (let file of files) {
                    promiseList.push(this.parse(path.join(this.resourcePath, file)));
                }
                yield promiseList;
            } else {
                return yield this.parse(this.resourcePath);
            }
        }).then(()=> {
            callback();
        }).catch((e)=> {
            this.log(e);
        });
    }

    log(msg) {
        if (!msg || !this.debugMode) {
            return;
        }
        console.log(msg);
    }

    isExist() {
        return new Promise((fulfill) => {
            fs.access(this.resourcePath, fs.constants.R_OK, (e) => {
                if (e) {
                    fulfill(false);
                    this.log(`[INFO] ${this.resourcePath} is NOT exists.`);
                } else {
                    fulfill(true);
                    this.log(`[INFO] ${this.resourcePath} is exists.`);
                }
            });
        });
    }

    isDirectory() {
        return new Promise((fulfill, reject) => {
            fs.lstat(this.resourcePath, (e, stats) => {
                if (e) {
                    reject(err);
                    this.debugMode && console.log(e);
                } else {
                    fulfill(stats);
                    this.log(`[INFO] ${this.resourcePath} is ${stats.isDirectory() ? 'directory.' : 'file'}.`);
                }
            });
        });
    }

    getFiles() {
        return new Promise((fulfill, reject) => {
            fs.readdir(this.resourcePath, this.defaultEncoding, (e, files) => {
                if (e) {
                    reject(e);
                } else {
                    files = files.filter((file)=> {
                        return path.extname(file) === '.html';
                    });
                    fulfill(files);
                    this.log(`[INFO] ${this.resourcePath}' has ${files.length} files.`);
                }
            });
        });
    }

    parse(filePath) {
        return co.call(this, function *() {
            let data = yield this.getData(filePath);
            let $ = cheerio.load(data, {normalizeWhitespace: true});
            if (this.progressBar) {
                this.progressBar.tick({
                    'file': path.basename(filePath),
                    'timestamp': $('span.post_permalink').text()
                });
            }
        }).catch((e)=> {
            this.log(e);
        });
    }

    getData(filePath) {
        return new Promise((fulfill, reject) => {
            fs.readFile(filePath, this.defaultEncoding, (e, data) => {
                if (e) {
                    reject(e);
                    this.log(`[INFO] ${filePath} is NOT loaded.`);
                } else {
                    fulfill(data);
                    this.log(`[INFO] ${filePath} is loaded.`);
                }
            });
        });
    }
}

module.exports = Parser;<commit_msg>기존 버전을 v1으로 픽스하고 다시 만듬. graceful-fs, progress-bar 라이브러리 추가. 비동기 방식으로 파일을 열어서 읽도록 변경.<commit_after>"use strict";
const fs = require('graceful-fs');
const path = require('path');
const co = require('co');
const cheerio = require('cheerio');
const _ = require('lodash');
const ProgressBar = require('progress');

class Parser {
    constructor(resourcePath) {
        this.resourcePath = resourcePath;
        this.debugMode = true;
        this.defaultEncoding = 'utf8';
        this.progressBar = undefined;
    }

    run(callback) {
        co.call(this, function *() {
            let exists = yield this.isExist();
            if (!exists) {
                throw new Error(this.resourcePath + ' is NOT exists.');
            }
            let stats = yield this.isDirectory();
            if (stats.isDirectory()) {
                let files = yield this.getFiles();
                if (!this.debugMode) {
                    this.progressBar = new ProgressBar('  Parsing [:bar] :percent :etas :file :timestamp', {
                        complete: '=',
                        incomplete: ' ',
                        width: 20,
                        total: files.length
                    });
                }

                let promiseList = [];
                for (let file of files) {
                    promiseList.push(this.parse(path.join(this.resourcePath, file)));
                }
                yield promiseList;
            } else {
                return yield this.parse(this.resourcePath);
            }
        }).then(()=> {
            callback();
        }).catch((e)=> {
            this.log(e);
        });
    }

    log(msg) {
        if (!msg || !this.debugMode) {
            return;
        }
        console.log(msg);
    }

    isExist() {
        return new Promise((fulfill) => {
            fs.access(this.resourcePath, fs.constants.R_OK, (e) => {
                if (e) {
                    fulfill(false);
                    this.log(`[INFO] ${this.resourcePath} is NOT exists.`);
                } else {
                    fulfill(true);
                    this.log(`[INFO] ${this.resourcePath} is exists.`);
                }
            });
        });
    }

    isDirectory() {
        return new Promise((fulfill, reject) => {
            fs.lstat(this.resourcePath, (e, stats) => {
                if (e) {
                    reject(err);
                    this.debugMode && console.log(e);
                } else {
                    fulfill(stats);
                    this.log(`[INFO] ${this.resourcePath} is ${stats.isDirectory() ? 'directory.' : 'file'}.`);
                }
            });
        });
    }

    getFiles() {
        return new Promise((fulfill, reject) => {
            fs.readdir(this.resourcePath, this.defaultEncoding, (e, files) => {
                if (e) {
                    reject(e);
                } else {
                    files = files.filter((file)=> {
                        return path.extname(file) === '.html';
                    });
                    fulfill(files);
                    this.log(`[INFO] ${this.resourcePath}' has ${files.length} files.`);
                }
            });
        });
    }

    parse(filePath) {
        return co.call(this, function *() {
            let data = yield this.getData(filePath);
            let $ = cheerio.load(data, {normalizeWhitespace: true});
            if (!this.debugMode) {
                this.progressBar.tick({
                    'file': path.basename(filePath),
                    'timestamp': $('span.post_permalink').text()
                });
            }
        }).catch((e)=> {
            this.log(e);
        });
    }

    getData(filePath) {
        return new Promise((fulfill, reject) => {
            fs.readFile(filePath, this.defaultEncoding, (e, data) => {
                if (e) {
                    reject(e);
                    this.log(`[INFO] ${filePath} is NOT loaded.`);
                } else {
                    fulfill(data);
                    this.log(`[INFO] ${filePath} is loaded.`);
                }
            });
        });
    }
}

module.exports = Parser;<|endoftext|>


<commit_before>/**
* A simple LDAP query machine
*/

import ldap from 'ldapjs';
import Promise from 'bluebird';
import _ from 'lodash';

function _cleanEntry(entryObj) {
  return _.chain(entryObj)
    .omit('controls')
    .mapValues((value) => {
      // 'TRUE' to true
      if (value === 'TRUE') { return true; }

      // if integer string, convert to number
      if (/^\d+$/.test(value)) { return parseInt(value, 10); }

      // otherwise the regular value
      return value;
    }).value();
}

export default class SimpleLDAPGet {
  constructor({ url, base, bind }) {
    this.settings = { url, base, bind };
    this._client = ldap.createClient({ url });
    this._isBoundTo = null;
    Promise.promisifyAll(this._client);
  }

  bindToDN() {
    const { dn, password } = this.settings.bind;

    return new Promise((resolve, reject) => {
      // resolve immediately if we've already bound to this dn
      if (this._isBoundTo === dn) {
        resolve();
      }

      this._client.bindAsync(dn, password)
        .then(() => {
          console.log('successful bind');
          this._isBoundTo = dn;
          resolve();
        })
        .catch((err) => {
          console.log('Something wrong with the binding');
          reject(err);
        });
    });
  }

  get(filter = '(objectclass=*)', attributes) {
    const self = this;

    const opts = {
      filter,
      scope: 'sub',
      attributes,
    };

    return this.bindToDN()
      .then(() => {
        return self._client.searchAsync(self.settings.base, opts);
      })
      .then((response) => {
        return new Promise((resolve, reject) => {
          const data = [];

          response.on('searchEntry', (entry) => {
            data.push(_cleanEntry(entry.object));
          });

          response.on('error', (err) => {
            reject(err);
          });

          response.on('end', () => {
            resolve(data);
          });
        });
      });
  }
}
<commit_msg>fix(log): Fix noisy logging on successful bind<commit_after>/**
* A simple LDAP query machine
*/

import ldap from 'ldapjs';
import Promise from 'bluebird';
import _ from 'lodash';

function _cleanEntry(entryObj) {
  return _.chain(entryObj)
    .omit('controls')
    .mapValues((value) => {
      // 'TRUE' to true
      if (value === 'TRUE') { return true; }

      // if integer string, convert to number
      if (/^\d+$/.test(value)) { return parseInt(value, 10); }

      // otherwise the regular value
      return value;
    }).value();
}

export default class SimpleLDAPGet {
  constructor({ url, base, bind }) {
    this.settings = { url, base, bind };
    this._client = ldap.createClient({ url });
    this._isBoundTo = null;
    Promise.promisifyAll(this._client);
  }

  bindToDN() {
    const { dn, password } = this.settings.bind;

    return new Promise((resolve, reject) => {
      // resolve immediately if we've already bound to this dn
      if (this._isBoundTo === dn) {
        resolve();
      }

      this._client.bindAsync(dn, password)
        .then(() => {
          // successful bind
          this._isBoundTo = dn;
          resolve();
        })
        .catch((err) => {
          console.error('Something wrong with the binding', err);
          reject(err);
        });
    });
  }

  get(filter = '(objectclass=*)', attributes) {
    const self = this;

    const opts = {
      filter,
      scope: 'sub',
      attributes,
    };

    return this.bindToDN()
      .then(() => {
        return self._client.searchAsync(self.settings.base, opts);
      })
      .then((response) => {
        return new Promise((resolve, reject) => {
          const data = [];

          response.on('searchEntry', (entry) => {
            data.push(_cleanEntry(entry.object));
          });

          response.on('error', (err) => {
            reject(err);
          });

          response.on('end', () => {
            resolve(data);
          });
        });
      });
  }
}
<|endoftext|>


<commit_before>import partial from './partial';
import reduceBuffArray from './reduceBuffArray';

function cloakGuess(bonus, level) {
  if (bonus > level * 10 ||
      bonus < level) {
    return bonus;
  }
  return level * 10;
}

function updateForCloak(obj) {
  obj.attackValue = cloakGuess(obj.attackBonus, obj.levelValue);
  obj.defenseValue = cloakGuess(obj.defenseBonus, obj.levelValue);
  obj.armorValue = cloakGuess(obj.armorBonus, obj.levelValue);
  obj.damageValue = cloakGuess(obj.damageBonus, obj.levelValue);
  obj.hpValue = obj.hpBonus;
}

var statList = [
  ['levelValue', 'level'],
  ['attackValue', 'attack'],
  ['attackBonus', 'bonus_attack'],
  ['defenseValue', 'defense'],
  ['defenseBonus', 'bonus_defense'],
  ['armorValue', 'armor'],
  ['armorBonus', 'bonus_armor'],
  ['damageValue', 'damage'],
  ['damageBonus', 'bonus_damage'],
  ['hpValue', 'hp'],
  ['hpBonus', 'bonus_hp'],
  ['killStreakValue', 'killstreak']
];

function assignStats(obj, json, arr) {obj[arr[0]] = Number(json[arr[1]]);}

function importStats(obj, json) {
  statList.forEach(partial(assignStats, obj, json));
}

var buffList = [
  ['counterAttackLevel', 'Counter Attack'],
  ['doublerLevel', 'Doubler'],
  ['deathDealerLevel', 'Death Dealer'],
  ['darkCurseLevel', 'Dark Curse'],
  ['holyFlameLevel', 'Holy Flame'],
  ['constitutionLevel', 'Constitution'],
  ['sanctuaryLevel', 'Sanctuary'],
  ['flinchLevel', 'Flinch'],
  ['nightmareVisageLevel', 'Nightmare Visage'],
  ['superEliteSlayerLevel', 'Super Elite Slayer'],
  ['fortitudeLevel', 'Fortitude'],
  ['chiStrikeLevel', 'Chi Strike'],
  ['terrorizeLevel', 'Terrorize'],
  ['barricadeLevel', 'Barricade'],
  ['reignOfTerrorLevel', 'Reign Of Terror'],
  ['anchoredLevel', 'Anchored'],
  ['severeConditionLevel', 'Severe Condition'],
  ['entrenchLevel', 'Entrench'],
  ['cloakLevel', 'Cloak']
];

function assignBuffs(obj, buffs, arr) {obj[arr[0]] = buffs[arr[1]] || 0;}

function importBuffs(obj, buffs) {
  buffList.forEach(partial(assignBuffs, obj, buffs));
}

export default function playerDataObject(json) {
  var buffs = reduceBuffArray(json._skills);
  var obj = {};
  importStats(obj, json);
  importBuffs(obj, buffs);
  obj.superEliteSlayerMultiplier = Math.round(0.002 *
    obj.superEliteSlayerLevel * 100) / 100;
  if (obj.cloakLevel !== 0) {updateForCloak(obj);}
  return obj;
}
<commit_msg>fix for self cloaked<commit_after>import isNaN from './isNaN';
import partial from './partial';
import reduceBuffArray from './reduceBuffArray';

function cloakGuess(bonus, level) {
  if (bonus > level * 10 || bonus < level) {
    return bonus;
  }
  return level * 10;
}

function updateForCloak(obj) {
  obj.attackValue = cloakGuess(obj.attackBonus, obj.levelValue);
  obj.defenseValue = cloakGuess(obj.defenseBonus, obj.levelValue);
  obj.armorValue = cloakGuess(obj.armorBonus, obj.levelValue);
  obj.damageValue = cloakGuess(obj.damageBonus, obj.levelValue);
  obj.hpValue = obj.hpBonus;
}

var statList = [
  ['levelValue', 'level'],
  ['attackValue', 'attack'],
  ['attackBonus', 'bonus_attack'],
  ['defenseValue', 'defense'],
  ['defenseBonus', 'bonus_defense'],
  ['armorValue', 'armor'],
  ['armorBonus', 'bonus_armor'],
  ['damageValue', 'damage'],
  ['damageBonus', 'bonus_damage'],
  ['hpValue', 'hp'],
  ['hpBonus', 'bonus_hp'],
  ['killStreakValue', 'killstreak']
];

function assignStats(obj, json, arr) {obj[arr[0]] = Number(json[arr[1]]);}

function importStats(obj, json) {
  statList.forEach(partial(assignStats, obj, json));
}

var buffList = [
  ['counterAttackLevel', 'Counter Attack'],
  ['doublerLevel', 'Doubler'],
  ['deathDealerLevel', 'Death Dealer'],
  ['darkCurseLevel', 'Dark Curse'],
  ['holyFlameLevel', 'Holy Flame'],
  ['constitutionLevel', 'Constitution'],
  ['sanctuaryLevel', 'Sanctuary'],
  ['flinchLevel', 'Flinch'],
  ['nightmareVisageLevel', 'Nightmare Visage'],
  ['superEliteSlayerLevel', 'Super Elite Slayer'],
  ['fortitudeLevel', 'Fortitude'],
  ['chiStrikeLevel', 'Chi Strike'],
  ['terrorizeLevel', 'Terrorize'],
  ['barricadeLevel', 'Barricade'],
  ['reignOfTerrorLevel', 'Reign Of Terror'],
  ['anchoredLevel', 'Anchored'],
  ['severeConditionLevel', 'Severe Condition'],
  ['entrenchLevel', 'Entrench'],
  ['cloakLevel', 'Cloak']
];

function assignBuffs(obj, buffs, arr) {obj[arr[0]] = buffs[arr[1]] || 0;}

function importBuffs(obj, buffs) {
  buffList.forEach(partial(assignBuffs, obj, buffs));
}

export default function playerDataObject(json) {
  var buffs = reduceBuffArray(json._skills);
  var obj = {};
  importStats(obj, json);
  importBuffs(obj, buffs);
  obj.superEliteSlayerMultiplier = Math.round(0.002 *
    obj.superEliteSlayerLevel * 100) / 100;
  if (isNaN(obj.armorValue)) {updateForCloak(obj);}
  return obj;
}
<|endoftext|>


<commit_before>export const sum = (a, b) => {
  return new Promise(resolve => resolve(a + b));
};
<commit_msg>Removed example function<commit_after>// Package goes here
<|endoftext|>


<commit_before>const postcss = require('postcss');
const parser = require('postcss-selector-parser');

/**
 * Ensure that attributes with different quotes match.
 * @param {Object} selector - postcss selector node
 */
function normalizeAttributes(selector) {
  selector.walkAttributes((node) => {
    if (node.value) {
      // remove quotes
      node.value = node.value.replace(/'|\\'|"|\\"/g, '');
    }
  });
}

/**
 * Sort class and id groups alphabetically
 * @param {Object} selector - postcss selector node
 */
function sortGroups(selector) {
  selector.each((subSelector) => {
    subSelector.nodes.sort((a, b) => {
      // different types cannot be sorted
      if (a.type !== b.type) {
        return 0;
      }

      // sort alphabetically
      return a.value < b.value ? -1 : 1;
    });
  });
}

/**
 * Remove duplicated properties
 * @param {Object} selector - postcss selector node
 */
function removeDupProperties(selector) {
  // Remove duplicated properties from bottom to top ()
  for (let actIndex = selector.nodes.length - 1; actIndex >= 1; actIndex--) {
    for (let befIndex = actIndex - 1; befIndex >= 0; befIndex--) {
      if (selector.nodes[actIndex].prop === selector.nodes[befIndex].prop) {
        selector.nodes[befIndex].remove();
        actIndex--;
      }
    }
  }
}

const uniformStyle = parser(
  (selector) => {
    normalizeAttributes(selector);
    sortGroups(selector);
  }
);

const defaultOptions = {
  removeDuplicatedProperties: false,
};

module.exports = postcss.plugin('postcss-combine-duplicated-selectors', (options = defaultOptions) => {
  return (css) => {
    // Create a map to store maps
    const mapTable = new Map();
    // root map to store root selectors
    mapTable.set('root', new Map());

    css.walkRules((rule) => {
      let map;
      // Check selector parent for any at rule
      if (rule.parent.type === 'atrule') {
        // Use the query params as the key
        const query = rule.parent.params.replace(/\s+/g, '');
        // See if this query key is already in the map table
        map = mapTable.has(query) ?
          // If it is use it
          mapTable.get(query) :
          // if not set it and get it
          mapTable.set(query, new Map()).get(query);
      } else {
        // Otherwise we are dealing with a selector in the root
        map = mapTable.get('root');
      }

      const selector = uniformStyle.process(
        rule.selector, {
          lossless: false,
        }
      ).result;

      if (map.has(selector)) {
        // store original rule as destination
        const destination = map.get(selector);
        // move declarations to original rule
        while (rule.nodes.length > 0) {
          rule.nodes[0].moveTo(destination);
        }
        // remove duplicated rule
        rule.remove();

        if (options.removeDuplicatedProperties) {
          removeDupProperties(destination);
        }
      } else {
        if (options.removeDuplicatedProperties) {
          removeDupProperties(rule);
        }
        // add new selector to symbol table
        map.set(selector, rule);
      }
    });
  };
});
<commit_msg>Fix Linter Error<commit_after>const postcss = require('postcss');
const parser = require('postcss-selector-parser');

/**
 * Ensure that attributes with different quotes match.
 * @param {Object} selector - postcss selector node
 */
function normalizeAttributes(selector) {
  selector.walkAttributes((node) => {
    if (node.value) {
      // remove quotes
      node.value = node.value.replace(/'|\\'|"|\\"/g, '');
    }
  });
}

/**
 * Sort class and id groups alphabetically
 * @param {Object} selector - postcss selector node
 */
function sortGroups(selector) {
  selector.each((subSelector) => {
    subSelector.nodes.sort((a, b) => {
      // different types cannot be sorted
      if (a.type !== b.type) {
        return 0;
      }

      // sort alphabetically
      return a.value < b.value ? -1 : 1;
    });
  });
}

/**
 * Remove duplicated properties
 * @param {Object} selector - postcss selector node
 */
function removeDupProperties(selector) {
  // Remove duplicated properties from bottom to top ()
  for (let actIndex = selector.nodes.length - 1; actIndex >= 1; actIndex--) {
    for (let befIndex = actIndex - 1; befIndex >= 0; befIndex--) {
      if (selector.nodes[actIndex].prop === selector.nodes[befIndex].prop) {
        selector.nodes[befIndex].remove();
        actIndex--;
      }
    }
  }
}

const uniformStyle = parser(
  (selector) => {
    normalizeAttributes(selector);
    sortGroups(selector);
  }
);

const defaultOptions = {
  removeDuplicatedProperties: false,
};
<<<<<<< HEAD
=======

module.exports = postcss.plugin('postcss-combine-duplicated-selectors', (options = defaultOptions) => {
>>>>>>> 75dbeff16efbe8c5c9830dac460c0c9cd56c2aa0

module.exports = postcss.plugin('postcss-combine-duplicated-selectors', (options = defaultOptions) => {
  return (css) => {
    // Create a map to store maps
    const mapTable = new Map();
    // root map to store root selectors
    mapTable.set('root', new Map());

    css.walkRules((rule) => {
      let map;
      // Check selector parent for any at rule
      if (rule.parent.type === 'atrule') {
        // Use the query params as the key
        const query = rule.parent.params.replace(/\s+/g, '');
        // See if this query key is already in the map table
        map = mapTable.has(query) ?
          // If it is use it
          mapTable.get(query) :
          // if not set it and get it
          mapTable.set(query, new Map()).get(query);
      } else {
        // Otherwise we are dealing with a selector in the root
        map = mapTable.get('root');
      }

      const selector = uniformStyle.process(
        rule.selector, {
          lossless: false,
        }
      ).result;

      if (map.has(selector)) {
        // store original rule as destination
        const destination = map.get(selector);
        // move declarations to original rule
        while (rule.nodes.length > 0) {
          rule.nodes[0].moveTo(destination);
        }
        // remove duplicated rule
        rule.remove();

        if (options.removeDuplicatedProperties) {
          removeDupProperties(destination);
        }
      } else {
        if (options.removeDuplicatedProperties) {
          removeDupProperties(rule);
        }
        // add new selector to symbol table
        map.set(selector, rule);
      }
    });
  };
});
<|endoftext|>


<commit_before>/*!
 * IdleTimeout
 *
 * @version 0.0.2
 * @overview A basic idle state detector written in ES6.
 * @author Jacob Müller [jacob.mueller.elz@gmail.com]
 * @see {@link https://github.com/jackmu95/idle-timeout|GitHub}
 */

'use strict';

import {extend} from './utils';

class IdleTimeout {
  constructor(callback, options = {}) {
    this.CLASS_NAME = 'IdleTimeout';

    this._timeoutFunction = null;
    this._idle = false;

    this._boundHandleEvent = event => this._handleEvent(event);
    this._eventNames = [
      'DOMMouseScroll',
      'mousedown', 'mousemove', 'mousewheel',
      'MSPointerDown', 'MSPointerMove',
      'keydown',
      'touchmove', 'touchstart',
      'wheel'
    ];

    this._lastPageX = -1;
    this._lastPageY = -1;

    this._callback = callback;
    this._options = extend({
      timeout: 60 * 1000 * 5,
      loop: false
    }, options);

    this._init();
  }

  _init() {
    this._eventNames.forEach(eventName => {
      document.addEventListener(eventName, this._boundHandleEvent);
    });

    this._reset();
  }

  _reset() {
    if (this._timeoutFunction) {
      clearTimeout(this._timeoutFunction);
      this._timeoutFunction = null;
    }

    if (this._idle && !this._options.loop) {
      return;
    }

    this._timeoutFunction = setTimeout(() => {
      this._handleTimeout();
    }, this._options.timeout);
  }

  _handleEvent(event) {
    if (event.type === 'mousemove') {
      if ((typeof event.pageX === 'undefined' &&
              typeof event.pageY === 'undefined') ||
          (event.pageX === this._lastPageX &&
              event.pageY === this._lastPageY)) {
        return;
      }

      this._lastPageX = event.pageX;
      this._lastPageY = event.pageY;
    }

    this._reset();
  }

  _handleTimeout() {
    this._idle = true;
    this._reset();

    this._callback();
  }

  reset() {
    this._idle = false;
    this._reset();
  }

  destroy() {
    this._eventNames.forEach(eventName => {
      document.removeEventListener(eventName, this._boundHandleEvent);
    });

    if (this._timeoutFunction) {
      clearTimeout(this._timeoutFunction);
    }

    this._timeoutFunction = null;
    this._idle = null;
    this._boundHandleEvent = null;
    this._eventNames = null;
    this._lastPageX = null;
    this._lastPageY = null;
    this._callback = null;
    this._options = null;
  }

  get idle() {
    return this._idle;
  }

  set timeout(value) {
    this._options.timeout = value;
  }

  set loop(value) {
    this._options.loop = value;
  }

  set idle(value) {
    if (value) {
      this._handleTimeout();
    } else {
      this.reset();
    }
  }
}

window.IdleTimeout = IdleTimeout;
export default IdleTimeout;
<commit_msg>Remove unneeded `CLASS_NAME` variable<commit_after>/*!
 * IdleTimeout
 *
 * @version 0.0.2
 * @overview A basic idle state detector written in ES6.
 * @author Jacob Müller [jacob.mueller.elz@gmail.com]
 * @see {@link https://github.com/jackmu95/idle-timeout|GitHub}
 */

'use strict';

import {extend} from './utils';

class IdleTimeout {
  constructor(callback, options = {}) {
    this._timeoutFunction = null;
    this._idle = false;

    this._boundHandleEvent = event => this._handleEvent(event);
    this._eventNames = [
      'DOMMouseScroll',
      'mousedown', 'mousemove', 'mousewheel',
      'MSPointerDown', 'MSPointerMove',
      'keydown',
      'touchmove', 'touchstart',
      'wheel'
    ];

    this._lastPageX = -1;
    this._lastPageY = -1;

    this._callback = callback;
    this._options = extend({
      timeout: 60 * 1000 * 5,
      loop: false
    }, options);

    this._init();
  }

  _init() {
    this._eventNames.forEach(eventName => {
      document.addEventListener(eventName, this._boundHandleEvent);
    });

    this._reset();
  }

  _reset() {
    if (this._timeoutFunction) {
      clearTimeout(this._timeoutFunction);
      this._timeoutFunction = null;
    }

    if (this._idle && !this._options.loop) {
      return;
    }

    this._timeoutFunction = setTimeout(() => {
      this._handleTimeout();
    }, this._options.timeout);
  }

  _handleEvent(event) {
    if (event.type === 'mousemove') {
      if ((typeof event.pageX === 'undefined' &&
              typeof event.pageY === 'undefined') ||
          (event.pageX === this._lastPageX &&
              event.pageY === this._lastPageY)) {
        return;
      }

      this._lastPageX = event.pageX;
      this._lastPageY = event.pageY;
    }

    this._reset();
  }

  _handleTimeout() {
    this._idle = true;
    this._reset();

    this._callback();
  }

  reset() {
    this._idle = false;
    this._reset();
  }

  destroy() {
    this._eventNames.forEach(eventName => {
      document.removeEventListener(eventName, this._boundHandleEvent);
    });

    if (this._timeoutFunction) {
      clearTimeout(this._timeoutFunction);
    }

    this._timeoutFunction = null;
    this._idle = null;
    this._boundHandleEvent = null;
    this._eventNames = null;
    this._lastPageX = null;
    this._lastPageY = null;
    this._callback = null;
    this._options = null;
  }

  get idle() {
    return this._idle;
  }

  set timeout(value) {
    this._options.timeout = value;
  }

  set loop(value) {
    this._options.loop = value;
  }

  set idle(value) {
    if (value) {
      this._handleTimeout();
    } else {
      this.reset();
    }
  }
}

window.IdleTimeout = IdleTimeout;
export default IdleTimeout;
<|endoftext|>