<commit_before>'use strict';
const BN = require('bn.js'),
    Hashids = require('hashids');

exports.init = ShortDUID;

function ShortDUID(shard_id, salt, epoch_start) {
    if (!(this instanceof ShortDUID)) return new ShortDUID(shard_id, salt, epoch_start);
    const duid = this;

    duid.shard_id = new BN(shard_id, 10).maskn(10);
    duid.salt = salt;

    const now = new BN(+new Date(), 10);
    duid.epoch_start = new BN(epoch_start, 10);
    if(now.cmp( duid.epoch_start ) === -1) {
        duid.epoch_start = new BN(0, 10);
    }

    duid.time_drift = new BN(0, 10);
    duid.hashids = new Hashids(duid.salt);

    duid.sequence = new BN(0, 10);
    duid.ts_sequence = [];

    return duid;
};

ShortDUID.prototype.getDUID = function (count) {
    let ret = [];
    let cnt;

    if( count === 0 ) return [];

    (count > 8192 || count < 1 ) ? cnt = 1 : cnt = count;

    for(let i = 0; i < cnt; i++) {
        ret.push(this.hashids.encodeHex(this.getID().toString(16)));
    }

    return ret;
};

ShortDUID.prototype.getDUIDInt = function (count) {
    let ret = [];
    let cnt;

    if( count === 0 ) return [];

    (count > 8192 || count < 0 ) ? cnt = 1 : cnt = count;

    for(let i = 0; i < cnt; i++) {
        ret.push(this.getID().toString(10));
    }

    return ret;
};

ShortDUID.prototype.getID = function () {
    const duid = this;

    // Calculate time part
    let now = new BN(+new Date(), 10).sub(duid.epoch_start.add(duid.time_drift)).maskn(42);

    // Calculate shard id part
    const shid = duid.shard_id.ushln(12).clone(); // Shift left by 12 bit

    // Calculate sequence part
    const seq = duid.sequence.iadd(new BN(1, 10)).maskn(12).clone();
    if(duid.ts_sequence[seq] !== undefined &&
        (duid.ts_sequence[seq].cmp(now) === 0 ||
         duid.ts_sequence[seq].cmp(now) === 1)
      ) { // Overflowing or drifting backwards
        now = duid.ts_sequence[seq].clone();
        now.iadd(new BN(1, 10));
        now.imaskn(42);
    }
    duid.ts_sequence[seq] = now.clone();
    now.iushln(22);

    // Calculate final ID
    return now.or(shid.or(seq));
};

ShortDUID.prototype.getShardID = function() {
    return parseInt(this.shard_id.toString(10), 10);
};

ShortDUID.prototype.getEpochStart = function() {
    return this.epoch_start.toString(10);
};

ShortDUID.prototype.getSalt = function() {
    return this.salt;
};

ShortDUID.prototype.getCurrentTimeMs = function() {
    const duid = this;
    const estart = duid.epoch_start.clone();
    let now = new BN(+new Date(), 10); // Current system time in milliseconds converted to BN object

    now.isub(estart).imaskn(42); // Calculate custom epoch and add/subtract drift time
    return now.toString(10);
};

ShortDUID.prototype.driftTime = function(drift) {
    if(drift !== undefined) {
        this.time_drift = new BN(drift, 10);
    }

    return parseInt(this.time_drift.toString(10), 10);
};
<commit_msg>Update index.js<commit_after>'use strict';
const BN = require('bn.js'),
    Hashids = require('hashids');

exports.init = ShortDUID;

function ShortDUID(shard_id, salt, epoch_start) {
    if (!(this instanceof ShortDUID)) return new ShortDUID(shard_id, salt, epoch_start);
    const duid = this;

    duid.shard_id = new BN(shard_id, 10).maskn(10);
    duid.salt = salt;

    const now = new BN(+new Date(), 10);
    duid.epoch_start = new BN(epoch_start, 10);
    if(now.cmp( duid.epoch_start ) === -1) {
        duid.epoch_start = new BN(0, 10);
    }

    duid.time_drift = new BN(0, 10);
    duid.hashids = new Hashids(duid.salt);

    duid.sequence = new BN(0, 10);
    duid.ts_sequence = [];

    return duid;
}

ShortDUID.prototype.getDUID = function (count) {
    let ret = [];
    let cnt;

    if ( count === 0 ) return [];

    if ( count > 8192 || count < 1 ) {
        cnt = 1;
    } else {
        cnt = count;
    }

    for(let i = 0; i < cnt; i++) {
        ret.push(this.hashids.encodeHex(this.getID().toString(16)));
    }

    return ret;
}

ShortDUID.prototype.getDUIDInt = function (count) {
    let ret = [];
    let cnt;

    if ( count === 0 ) return [];

    if ( count > 8192 || count < 0 ) {
        cnt = 1;
    } else {
        cnt = count;
    }

    for(let i = 0; i < cnt; i++) {
        ret.push(this.getID().toString(10));
    }

    return ret;
}

ShortDUID.prototype.getID = function () {
    const duid = this;

    // Calculate time part
    let now = new BN(+new Date(), 10).sub(duid.epoch_start.add(duid.time_drift)).maskn(42);

    // Calculate shard id part
    const shid = duid.shard_id.ushln(12).clone(); // Shift left by 12 bit

    // Calculate sequence part
    const seq = duid.sequence.iadd(new BN(1, 10)).maskn(12).clone();
    if(duid.ts_sequence[seq] !== undefined &&
        (duid.ts_sequence[seq].cmp(now) === 0 ||
         duid.ts_sequence[seq].cmp(now) === 1)
      ) { // Overflowing or drifting backwards
        now = duid.ts_sequence[seq].clone();
        now.iadd(new BN(1, 10));
        now.imaskn(42);
    }
    duid.ts_sequence[seq] = now.clone();
    now.iushln(22);

    // Calculate final ID
    return now.or(shid.or(seq));
}

ShortDUID.prototype.getShardID = function() {
    return parseInt(this.shard_id.toString(10), 10);
}

ShortDUID.prototype.getEpochStart = function() {
    return this.epoch_start.toString(10);
}

ShortDUID.prototype.getSalt = function() {
    return this.salt;
}

ShortDUID.prototype.getCurrentTimeMs = function() {
    const duid = this;
    const estart = duid.epoch_start.clone();
    let now = new BN(+new Date(), 10); // Current system time in milliseconds converted to BN object

    now.isub(estart).imaskn(42); // Calculate custom epoch and add/subtract drift time
    return now.toString(10);
}

ShortDUID.prototype.driftTime = function(drift) {
    if(drift !== undefined) {
        this.time_drift = new BN(drift, 10);
    }

    return parseInt(this.time_drift.toString(10), 10);
}
<|endoftext|>


<commit_before>var async = require('async');
var request = require('request');
var cheerio = require('cheerio');
var Bitly = require('bitly');

var log = require('logmagic').local('treslek.plugins.url');
var config = require('./config.json');

/*
 * URL plugin
 *   - creates a hook that checks for urls. It then grabs the title
 *     and outputs that to the channel.
 */
var Url = function() {
  this.hooks = ['url'];

  // Enable bitly shortification by adding credentials here
  this.bitly = {
    user: '',
    apiKey: '',
  };
};

/*
 * Helper function for shortening a url with bitly.
 */
var shortenUrl = function(bitly, url, callback) {
  if (!bitly) {
    callback(null, url);
    return;
  }

  bitly.shorten(url, function(err, resp) {
    if (err) {
      log.error('Error shortening url', {err: err, url: url});
      callback(err);
      return;
    }

    callback(null, resp.data.url || url);
  });
};

/*
 * URL hook.
 *   Searchs a message for any urls, and then request each url.
 *   If the url returns a content-type of 'text/html', attempt
 *   to get the page title. If not, return the content type. If
 *   bitly is configured, shorten urls as well.
 */
Url.prototype.url = function(bot, to, from, msg, callback) {
  var urlReg = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
      matches = msg.match(urlReg),
      bitly;

  if (!matches) {
    callback();
    return;
  }

  if (config.bitlyUser !== '' && config.bitlyApiKey !== '') {
    bitly = new Bitly(config.bitlyUser, config.bitlyApiKey);
  }

  async.forEach(matches, function(url, callback) {
    request(url, function(err, res, body) {
      var response,
          parsed,
          title,
          contentType;

      if (err || res.statusCode === 404) {
        if (err) {
          log.error('Error retrieving url', {url: url, err: err});
          callback();
          return;
        } else {
          log.error('Error retrieving url. Got response.', {url: url, err: err});
          callback();
          return;
        }
      }

      if (res.statusCode === 200) {
        contentType = res.headers['content-type'].split(';')[0];
        if (contentType !== 'text/html') {
          title = contentType;
        } else {
          parsed = cheerio.load(body);
          title = parsed('title').text().replace(/\n/g, '').replace(/^\s+/, '');
        }
      }

      title = title || contentType;

      shortenUrl(bitly, url, function(err, shortUrl) {
        response = title + ' | ' + shortUrl;
        bot.say(to, response);
        callback();
      });

    });
  }, callback);
};

exports.Plugin = Url;
<commit_msg>Add logic for special parsing of youtube and twitter<commit_after>var util = require('util');
var urlLib = require('url');

var async = require('async');
var request = require('request');
var cheerio = require('cheerio');
var Bitly = require('bitly');

var log = require('logmagic').local('treslek.plugins.url');
var config = require('./config.json');

request = request.defaults({
  sendImmediately: true,
  timeout: 10000,
  headers: {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36"
  }
});

/*
 * URL plugin
 *   - creates a hook that checks for urls. It then grabs the title
 *     and outputs that to the channel.
 *   Thanks to https://github.com/Floobits/floobot for scraping logic
 */
var Url = function() {
  this.hooks = ['url'];
};

/*
 * Helper function for shortening a url with bitly.
 */
var shortenUrl = function(bitly, url, callback) {
  if (!bitly) {
    callback(null, url);
    return;
  }

  bitly.shorten(url, function(err, resp) {
    if (err) {
      log.error('Error shortening url', {err: err, url: url});
      callback(err);
      return;
    }

    callback(null, resp.data.url || url);
  });
};

function parseYoutube(path, parsed) {
  var title, views, likes, dislikes, rating;

  if (path.match(/^\/watch/) === null) {
    return;
  }

  title = parsed('#eow-title').text().replace(/\n/g, '').replace(/^\s+/, '').replace(/\s+$/, '');
  views = parsed('#watch7-views-info > div.watch-view-count').text().replace(/[\s]/g, '') || 0;
  likes = parsed('#watch-like > span.yt-uix-button-content').text().replace(/[\s,]/g, '') || 0;
  dislikes = parsed('#watch-dislike > span.yt-uix-button-content').text().replace(/[\s,]/g, '') || 0;
  likes = parseInt(likes, 10);
  dislikes = parseInt(dislikes, 10);
  console.log(likes, dislikes);
  rating = Math.round(100 * likes / (likes + dislikes));

  return util.format("%s | %s views %s%% like", title, views, rating);
}

function parseTwitter(path, parsed) {
  var user, title, retweets, favorites;

  if (path.match("^\\/\\w+\\/status\\/\\d+") === null) {
    return;
  }

  user = parsed("div.permalink-tweet-container div.permalink-header a > span.username.js-action-profile-name > b").text();
  title = parsed("div.permalink-tweet-container p.tweet-text").text().replace(/\n/g, '').replace(/^\s+/, '').replace(/\s+$/, '');
  retweets = parsed("div.tweet-stats-container > ul.stats > li.js-stat-count.js-stat-retweets.stat-count > a > strong").text().replace(/\s/g, "") || 0;
  favorites = parsed("div.tweet-stats-container > ul.stats > li.js-stat-count.js-stat-favorites.stat-count > a > strong").text().replace(/\s/g, "") || 0;

  return util.format("<@%s> %s (%s retweets, %s favorites)", user, title, retweets, favorites);
}

/*
 * URL hook.
 *   Searchs a message for any urls, and then request each url.
 *   If the url returns a content-type of 'text/html', attempt
 *   to get the page title. If not, return the content type. If
 *   bitly is configured, shorten urls as well.
 */
Url.prototype.url = function(bot, to, from, msg, callback) {
  var urlReg = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
      matches = msg.match(urlReg),
      bitly;

  if (!matches) {
    callback();
    return;
  }

  if (config.bitlyUser !== '' && config.bitlyApiKey !== '') {
    bitly = new Bitly(config.bitlyUser, config.bitlyApiKey);
  }

  async.forEach(matches, function(url, callback) {
    request(url, function(err, res, body) {
      var response,
          parsed,
          parsedUrl,
          title,
          contentType;

      if (err || res.statusCode === 404) {
        if (err) {
          log.error('Error retrieving url', {url: url, err: err});
          callback();
          return;
        } else {
          log.error('Error retrieving url. Got response.', {url: url, err: err});
          callback();
          return;
        }
      }

      if (res.statusCode === 200) {
        contentType = res.headers['content-type'].split(';')[0];
        if (contentType !== 'text/html') {
          title = contentType;
        } else {
          parsed = cheerio.load(body);
          title = parsed('title').text().replace(/\n/g, '').replace(/^\s+/, '');
        }
      }

      title = title || contentType;

      shortenUrl(bitly, url, function(err, shortUrl) {
        parsedUrl = urlLib.parse(url);
        domain = parsedUrl.hostname.split('.').slice(-2).join('.');
        if (domain === 'youtube.com') {
          response = parseYoutube(parsedUrl.path, parsed) + ' | ' + shortUrl;
        } else if (domain === 'twitter.com') {
          response = parseTwitter(parsedUrl.path, parsed) + ' | ' + shortUrl;
        } else {
          response = title + ' | ' + shortUrl;
        }
        bot.say(to, response);
        callback();
      });

    });
  }, callback);
};

exports.Plugin = Url;
<|endoftext|>


<commit_before>const crypto = require('crypto'),
    debug = require('debug'),
    minimatch = require('minimatch'),
    path = require('path');

const defaultOptions = {
    algo: 'sha1',       // see crypto.getHashes() for options
    encoding: 'base64', // 'base64', 'hex' or 'binary'
    files: {
        exclude: [],
        include: [],
        matchBasename: true,
        matchPath: false,
        ignoreBasename: false,
        ignoreRootName: false
    },
    folders: {
        exclude: [],
        include: [],
        matchBasename: true,
        matchPath: false,
        ignoreBasename: false,
        ignoreRootName: false
    }
};

// Use the environment variable DEBUG to log output, e.g. `set DEBUG=fhash:*`
const log = {
    match: debug('fhash:match'),
    params: (params) => {
        debug('fhash:parameters')(params);
        return params;
    }
};

function prep(fs, Promise) {
    function hashElement(name, dir, options, callback) {
        callback = arguments[arguments.length - 1];

        return parseParameters(arguments)
            .then(({ basename, dir, options }) => {
                // this is only used for the root level
                options.skipMatching = true;
                return hashElementPromise(basename, dir, options, true);
            })
            .then(result => {
                if (typeof callback === 'function') {
                    return callback(undefined, result);
                } else {
                    return result;
                }
            })
            .catch(reason => {
                if (typeof callback === 'function') {
                    return callback(reason);
                } else {
                    throw reason;
                }
            });
    }

    function hashElementPromise(basename, dirname, options, isRootElement = false) {
        return stat(path.join(dirname, basename)).then(stats => {
            if (stats.isDirectory()) {
                return hashFolderPromise(basename, dirname, options, isRootElement);
            } else if (stats.isFile()) {
                return hashFilePromise(basename, dirname, options, isRootElement);
            } else {
                return {
                    name: basename,
                    hash: 'unknown element type'
                };
            }
        });
    }

    function stat(filepath) {
        return new Promise((resolve, reject) => {
            fs.stat(filepath, (err, stats) => {
                if (err) {
                    return reject(err);
                } else {
                    return resolve(stats);
                }
            });
        });
    }

    function hashFolderPromise(name, dir, options, isRootElement = false) {
        const folderPath = path.join(dir, name);

        if (options.skipMatching) {
            // this is currently only used for the root folder
            log.match(`skipped '${folderPath}'`);
            delete options.skipMatching;
        } else if (ignore(name, folderPath, options.folders)) {
            return undefined;
        }

        return readdir(folderPath).then(files => {
            const children = files.map(child => {
                return hashElementPromise(child, folderPath, options);
            });

            return Promise.all(children).then(children => {
                const hash = new HashedFolder(name, children.filter(notUndefined), options, isRootElement);
                return hash;
            });
        });
    }

    function readdir(folderPath) {
        return new Promise((resolve, reject) => {
            fs.readdir(folderPath, (err, files) => {
                if (err) {
                    console.error(err);
                    return reject(err);
                } else {
                    return resolve(files.sort());
                }
            });
        });
    }

    function hashFilePromise(name, dir, options, isRootElement = false) {
        const filePath = path.join(dir, name);

        if (options.skipMatching) {
            // this is currently only used for the root folder
            log.match(`skipped '${filePath}'`);
            delete options.skipMatching;
        } else if (ignore(name, filePath, options.files)) {
            return undefined;
        }

        return new Promise((resolve, reject) => {
            try {
                const hash = crypto.createHash(options.algo);
                if (options.files.ignoreBasename ||
                    (isRootElement && options.files.ignoreRootName))
                {
                    log.match(`omitted name of ${filePath} from hash`)
                } else {
                    hash.write(name);
                }

                const f = fs.createReadStream(filePath);
                f.pipe(hash, { end: false });

                f.on('end', () => {
                    const hashedFile = new HashedFile(name, hash, options.encoding);
                    return resolve(hashedFile);
                });
            } catch (ex) {
                return reject(ex);
            }
        });
    }

    function ignore(name, path, rules) {
        if (rules.exclude) {
            if (rules.matchBasename && rules.exclude(name)) {
                log.match(`exclude basename '${path}'`);
                return true;
            } else if (rules.matchPath && rules.exclude(path)) {
                log.match(`exclude path '${path}'`);
                return true;
            }
        } else if (rules.include) {
            if (rules.matchBasename && rules.include(name)) {
                log.match(`include basename '${path}'`);
                return false;
            } else if (rules.matchPath && rules.include(path)) {
                log.match(`include path '${path}'`);
                return false;
            } else {
                return true;
            }
        }

        log.match(`unmatched '${path}'`);
        return false;
    }

    const HashedFolder = function HashedFolder(name, children, options, isRootElement = false) {
        this.name = name;
        this.children = children;

        const hash = crypto.createHash(options.algo);
        if (options.folders.ignoreBasename ||
            (isRootElement && options.folders.ignoreRootName))
        {
            log.match(`omitted name of folder ${name} from hash`)
        } else {
            hash.write(name);
        }
        children.forEach(child => {
            if (child.hash) {
                hash.write(child.hash);
            }
        });

        this.hash = hash.digest(options.encoding);
    };

    HashedFolder.prototype.toString = function (padding = '') {
        const first = `${padding}{ name: '${this.name}', hash: '${this.hash},'\n`;
        padding += '  ';

        return `${first}${padding}children: ${this.childrenToString(padding)}}`;
    };

    HashedFolder.prototype.childrenToString = function (padding = '') {
        if (this.children.length === 0) {
            return '[]';
        } else {
            const nextPadding = padding + '  ';
            const children = this.children
                .map(child => child.toString(nextPadding))
                .join('\n');
            return `[\n${children}\n${padding}]`;
        }
    };

    const HashedFile = function HashedFile(name, hash, encoding) {
        this.name = name;
        this.hash = hash.digest(encoding);
    };

    HashedFile.prototype.toString = function (padding = '') {
        return padding + '{ name: \'' + this.name + '\', hash: \'' + this.hash + '\' }';
    };

    return hashElement;
}

function parseParameters(args) {
    let basename = args[0],
        dir = args[1],
        options_ = args[2];

    if (!isString(basename)) {
        return Promise.reject(new TypeError('First argument must be a string'));
    }

    if (!isString(dir)) {
        dir = path.dirname(basename);
        basename = path.basename(basename);
        options_ = args[1];
    }

    // parse options (fallback default options)
    if (!isObject(options_)) options_ = {};
    const options = {
        algo: options_.algo || defaultOptions.algo,
        encoding: options_.encoding || defaultOptions.encoding,
        files: Object.assign({}, defaultOptions.files, options_.files),
        folders: Object.assign({}, defaultOptions.folders, options_.folders),
        match: Object.assign({}, defaultOptions.match, options_.match)
    };

    // transform match globs to Regex
    options.files.exclude = reduceGlobPatterns(options.files.exclude);
    options.files.include = reduceGlobPatterns(options.files.include);
    options.folders.exclude = reduceGlobPatterns(options.folders.exclude);
    options.folders.include = reduceGlobPatterns(options.folders.include);

    return Promise.resolve(log.params({ basename, dir, options }));
}

function isString(str) {
    return typeof str === 'string' || str instanceof String;
}

function isObject(obj) {
    return obj !== null && typeof obj === 'object';
}

function notUndefined(obj) {
    return typeof obj !== 'undefined';
}

function reduceGlobPatterns(globs) {
    if (typeof globs === 'function') {
      return globs;
    }
    else if (!globs || !Array.isArray(globs) || globs.length === 0) {
        return undefined;
    } else {
        // combine globs into one single RegEx
        const regex = new RegExp(globs.reduce((acc, exclude) => {
            return acc + '|' + minimatch.makeRe(exclude).source;
        }, '').substr(1));
        return param => regex.test(param);
    }
}

module.exports = {
    defaults: defaultOptions,
    hashElement: prep(require("graceful-fs"), Promise),
    // exposed for testing
    prep: prep,
    parseParameters: parseParameters
};
<commit_msg>Add isFunction() helper<commit_after>const crypto = require('crypto'),
    debug = require('debug'),
    minimatch = require('minimatch'),
    path = require('path');

const defaultOptions = {
    algo: 'sha1',       // see crypto.getHashes() for options
    encoding: 'base64', // 'base64', 'hex' or 'binary'
    files: {
        exclude: [],
        include: [],
        matchBasename: true,
        matchPath: false,
        ignoreBasename: false,
        ignoreRootName: false
    },
    folders: {
        exclude: [],
        include: [],
        matchBasename: true,
        matchPath: false,
        ignoreBasename: false,
        ignoreRootName: false
    }
};

// Use the environment variable DEBUG to log output, e.g. `set DEBUG=fhash:*`
const log = {
    match: debug('fhash:match'),
    params: (params) => {
        debug('fhash:parameters')(params);
        return params;
    }
};

function prep(fs, Promise) {
    function hashElement(name, dir, options, callback) {
        callback = arguments[arguments.length - 1];

        return parseParameters(arguments)
            .then(({ basename, dir, options }) => {
                // this is only used for the root level
                options.skipMatching = true;
                return hashElementPromise(basename, dir, options, true);
            })
            .then(result => {
                if (isFunction(callback)) {
                    return callback(undefined, result);
                } else {
                    return result;
                }
            })
            .catch(reason => {
                if (isFunction(callback)) {
                    return callback(reason);
                } else {
                    throw reason;
                }
            });
    }

    function hashElementPromise(basename, dirname, options, isRootElement = false) {
        return stat(path.join(dirname, basename)).then(stats => {
            if (stats.isDirectory()) {
                return hashFolderPromise(basename, dirname, options, isRootElement);
            } else if (stats.isFile()) {
                return hashFilePromise(basename, dirname, options, isRootElement);
            } else {
                return {
                    name: basename,
                    hash: 'unknown element type'
                };
            }
        });
    }

    function stat(filepath) {
        return new Promise((resolve, reject) => {
            fs.stat(filepath, (err, stats) => {
                if (err) {
                    return reject(err);
                } else {
                    return resolve(stats);
                }
            });
        });
    }

    function hashFolderPromise(name, dir, options, isRootElement = false) {
        const folderPath = path.join(dir, name);

        if (options.skipMatching) {
            // this is currently only used for the root folder
            log.match(`skipped '${folderPath}'`);
            delete options.skipMatching;
        } else if (ignore(name, folderPath, options.folders)) {
            return undefined;
        }

        return readdir(folderPath).then(files => {
            const children = files.map(child => {
                return hashElementPromise(child, folderPath, options);
            });

            return Promise.all(children).then(children => {
                const hash = new HashedFolder(name, children.filter(notUndefined), options, isRootElement);
                return hash;
            });
        });
    }

    function readdir(folderPath) {
        return new Promise((resolve, reject) => {
            fs.readdir(folderPath, (err, files) => {
                if (err) {
                    console.error(err);
                    return reject(err);
                } else {
                    return resolve(files.sort());
                }
            });
        });
    }

    function hashFilePromise(name, dir, options, isRootElement = false) {
        const filePath = path.join(dir, name);

        if (options.skipMatching) {
            // this is currently only used for the root folder
            log.match(`skipped '${filePath}'`);
            delete options.skipMatching;
        } else if (ignore(name, filePath, options.files)) {
            return undefined;
        }

        return new Promise((resolve, reject) => {
            try {
                const hash = crypto.createHash(options.algo);
                if (options.files.ignoreBasename ||
                    (isRootElement && options.files.ignoreRootName))
                {
                    log.match(`omitted name of ${filePath} from hash`)
                } else {
                    hash.write(name);
                }

                const f = fs.createReadStream(filePath);
                f.pipe(hash, { end: false });

                f.on('end', () => {
                    const hashedFile = new HashedFile(name, hash, options.encoding);
                    return resolve(hashedFile);
                });
            } catch (ex) {
                return reject(ex);
            }
        });
    }

    function ignore(name, path, rules) {
        if (rules.exclude) {
            if (rules.matchBasename && rules.exclude(name)) {
                log.match(`exclude basename '${path}'`);
                return true;
            } else if (rules.matchPath && rules.exclude(path)) {
                log.match(`exclude path '${path}'`);
                return true;
            }
        } else if (rules.include) {
            if (rules.matchBasename && rules.include(name)) {
                log.match(`include basename '${path}'`);
                return false;
            } else if (rules.matchPath && rules.include(path)) {
                log.match(`include path '${path}'`);
                return false;
            } else {
                return true;
            }
        }

        log.match(`unmatched '${path}'`);
        return false;
    }

    const HashedFolder = function HashedFolder(name, children, options, isRootElement = false) {
        this.name = name;
        this.children = children;

        const hash = crypto.createHash(options.algo);
        if (options.folders.ignoreBasename ||
            (isRootElement && options.folders.ignoreRootName))
        {
            log.match(`omitted name of folder ${name} from hash`)
        } else {
            hash.write(name);
        }
        children.forEach(child => {
            if (child.hash) {
                hash.write(child.hash);
            }
        });

        this.hash = hash.digest(options.encoding);
    };

    HashedFolder.prototype.toString = function (padding = '') {
        const first = `${padding}{ name: '${this.name}', hash: '${this.hash},'\n`;
        padding += '  ';

        return `${first}${padding}children: ${this.childrenToString(padding)}}`;
    };

    HashedFolder.prototype.childrenToString = function (padding = '') {
        if (this.children.length === 0) {
            return '[]';
        } else {
            const nextPadding = padding + '  ';
            const children = this.children
                .map(child => child.toString(nextPadding))
                .join('\n');
            return `[\n${children}\n${padding}]`;
        }
    };

    const HashedFile = function HashedFile(name, hash, encoding) {
        this.name = name;
        this.hash = hash.digest(encoding);
    };

    HashedFile.prototype.toString = function (padding = '') {
        return padding + '{ name: \'' + this.name + '\', hash: \'' + this.hash + '\' }';
    };

    return hashElement;
}

function parseParameters(args) {
    let basename = args[0],
        dir = args[1],
        options_ = args[2];

    if (!isString(basename)) {
        return Promise.reject(new TypeError('First argument must be a string'));
    }

    if (!isString(dir)) {
        dir = path.dirname(basename);
        basename = path.basename(basename);
        options_ = args[1];
    }

    // parse options (fallback default options)
    if (!isObject(options_)) options_ = {};
    const options = {
        algo: options_.algo || defaultOptions.algo,
        encoding: options_.encoding || defaultOptions.encoding,
        files: Object.assign({}, defaultOptions.files, options_.files),
        folders: Object.assign({}, defaultOptions.folders, options_.folders),
        match: Object.assign({}, defaultOptions.match, options_.match)
    };

    // transform match globs to Regex
    options.files.exclude = reduceGlobPatterns(options.files.exclude);
    options.files.include = reduceGlobPatterns(options.files.include);
    options.folders.exclude = reduceGlobPatterns(options.folders.exclude);
    options.folders.include = reduceGlobPatterns(options.folders.include);

    return Promise.resolve(log.params({ basename, dir, options }));
}

function isFunction(any) {
    return typeof any === 'function';
}

function isString(str) {
    return typeof str === 'string' || str instanceof String;
}

function isObject(obj) {
    return obj !== null && typeof obj === 'object';
}

function notUndefined(obj) {
    return typeof obj !== 'undefined';
}

function reduceGlobPatterns(globs) {
    if (isFunction(globs)) {
      return globs;
    }
    else if (!globs || !Array.isArray(globs) || globs.length === 0) {
        return undefined;
    } else {
        // combine globs into one single RegEx
        const regex = new RegExp(globs.reduce((acc, exclude) => {
            return acc + '|' + minimatch.makeRe(exclude).source;
        }, '').substr(1));
        return param => regex.test(param);
    }
}

module.exports = {
    defaults: defaultOptions,
    hashElement: prep(require("graceful-fs"), Promise),
    // exposed for testing
    prep: prep,
    parseParameters: parseParameters
};
<|endoftext|>


<commit_before>'use strict'

var navigator = require('global/window').navigator

module.exports = typeof navigator !== "undefined" &&
  (/iPad|iPhone|iPod/.test(navigator.userAgent || '') ||
  (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) // iPad iOS 13
<commit_msg>standard --fix<commit_after>'use strict'

var navigator = require('global/window').navigator

module.exports = typeof navigator !== 'undefined' &&
  (/iPad|iPhone|iPod/.test(navigator.userAgent || '') ||
  (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) // iPad iOS 13
<|endoftext|>


<commit_before>/*!
 * helper-cache <https://github.com/jonschlinkert/helper-cache>
 *
 * Copyright (c) 2014 Jon Schlinkert, Brian Woodward
 * Licensed under the MIT license.
 */

'use strict';

var loader = require('load-helpers');
var randomize = require('randomatic');
var _ = require('lodash');

/**
 * Create an instance of `Helpers`, optionally passing
 * default `options`.
 *
 * ```js
 * var Helpers = require('helper-cache');
 * var helpers = new Helpers();
 * ```
 *
 * @param {Object} `options` Default options to use.
 *   @option {Boolean} [options] `bind` Bind functions to `this`. Defaults to `false`.
 *   @option {Boolean} [options] `thisArg` The context to use.
 * @api public
 */

function Helpers(options) {
  if (!(this instanceof Helpers)) {
    return new Helpers(options);
  }

  var opts = _.defaults({}, options, {
    bind: false,
    thisArg: this
  });

  defineGetter(this, 'options', function () {
    return opts;
  });

  var obj = {asyncHelpers: {}, waiting: []};
  defineGetter(this, '_', function () {
    return obj;
  });
}

/**
 * Set helpers on the cache.
 *
 * @param {String} `key` The name of the helper.
 * @param {Function} `fn` Helper function.
 * @api public
 */

defineGetter(Helpers.prototype, 'addHelper', function () {
  return function (key, fn, thisArg) {
    thisArg = thisArg || this.options.thisArg;

    if (typeof key !== 'string') {
      _.extend(this, key);
    } else {
      if (this.options.bind) {
        this[key] = _.bind(fn, thisArg);
      } else {
        this[key] = fn;
      }
    }
    return this;
  }.bind(this);
});

/**
 * Set async helpers on the cache.
 *
 * @param {String} `key` The name of the helper.
 * @param {Function} `fn` Helper function.
 * @api public
 */

defineGetter(Helpers.prototype, 'addAsyncHelper', function () {
  return function(key, fn, thisArg) {
    thisArg = thisArg || this.options.thisArg;
    if (typeof key !== 'string') {
      _.forOwn(key, function (value, k) {
        this.addAsyncHelper(k, value, thisArg);
      }, this);
    } else {
      var self = this;
      if (this.options.bind) {
        this._.asyncHelpers[key] = _.bind(fn, thisArg || this);
      } else {
        this._.asyncHelpers[key] = fn;
      }
      this.addHelper(key, function () {
        var id = '__async_helper_id__' + randomize('Aa0', 42) + '__';
        var args = [].slice.call(arguments);
        self._.waiting.push({id: id, key: key, args: args, fn: fn.bind(this)});
        return id;
      });
    }
    return this;
  }
});

/**
 * Add an object of helpers to the cache.
 *
 * See [load-helpers] for issues, API details and the full range of options.
 *
 * @param {String} `key` The name of the helper.
 * @param {Function} `fn` Helper function.
 * @api public
 */

defineGetter(Helpers.prototype, 'addHelpers', function () {
  return function () {
    var thisArg = this.options.thisArg;

    loader.init();

    var helpers = loader.load.apply(loader, arguments);
    _.forIn(helpers.cache, function (value, key) {
      var o = {};
      if (this.options.bind) {
        o[key] = _.bind(value, thisArg);
      } else {
        o[key] = value;
      }
      _.extend(this, o);
    }, this);

    return this;
  }.bind(this);
});

/**
 * Add an object of async helpers to the cache.
 *
 * See [load-helpers] for issues, API details and the full range of options.
 *
 * @param {String} `key` The name of the helper.
 * @param {Function} `fn` Helper function.
 * @api public
 */

defineGetter(Helpers.prototype, 'addAsyncHelpers', function () {
  return function () {
    var thisArg = this.options.thisArg;
    loader.init();
    var helpers = loader.load.apply(loader, arguments);
    return this.addAsyncHelper(helpers.cache);
  }.bind(this);
});

/**
 * Get a helper from the cache.
 *
 * @param  {String} `key` The helper to get.
 * @return {Object} The specified helper. If no `key` is passed, the entire cache is returned.
 * @api public
 */

defineGetter(Helpers.prototype, 'getHelper', function () {
  return function(key) {
    if (!key) {
      return this;
    }
    return this[key];
  }.bind(this);
});

/**
 * Get an async helper from the cache.
 *
 * @param  {String} `key` The helper to get.
 * @return {Object} The specified helper. If no `key` is passed, the entire cache is returned.
 * @api public
 */

defineGetter(Helpers.prototype, 'getAsyncHelper', function () {
  return function(key) {
    if (!key) {
      return this._.asyncHelpers;
    }
    return this._.asyncHelpers[key];
  }.bind(this);
});

/**
 * Getter method to resolve async helper values that were called during
 * the render process.
 *
 * @param {String} `content` Rendered string containing async ids
 * @param {Function} `cb`
 * @api public
 */

defineGetter(Helpers.prototype, 'resolve', function () {
  return function (content, cb) {
    var self = this;
    var i = self._.waiting.length;
    var next = function (err, content) {
      // current helper info
      var helper = self._.waiting[--i];

      if (helper) {
        // original async helper
        var fn = helper.fn;

        if (!fn) return next(null, content);
        if (content.indexOf(helper.id) === -1) {
          return next(null, content);
        }
        // replacing this helper id so remove it from the waiting list

        // call the async helper and replace id with results
        var args = helper.args || [];
        var nextCallback = function (err, results) {
          if (err) return cb(err);
          content = content.replace(helper.id, results);
          // remove the helper from the waiting list
          self._.waiting.splice(i+1, 1);
          next(null, content);
        };
        if (args[args.length-1].toString() !== nextCallback.toString()) {
          args.push(nextCallback);
        }

        fn.apply(fn, args);

      } else {
        // call final callback
        return cb(null, content);
      }
    }
    return next(null, content);
  };
});

/**
 * Utility method to define getters.
 *
 * @param  {Object} `obj`
 * @param  {String} `name`
 * @param  {Function} `getter`
 * @return {Getter}
 * @api private
 */

function defineGetter(obj, name, getter) {
  Object.defineProperty(obj, name, {
    configurable: false,
    enumerable: false,
    get: getter,
    set: function() {}
  });
}

module.exports = Helpers;
<commit_msg>fixes naming conflict:<commit_after>/*!
 * helper-cache <https://github.com/jonschlinkert/helper-cache>
 *
 * Copyright (c) 2014-2015 Jon Schlinkert, Brian Woodward
 * Licensed under the MIT license.
 */

'use strict';

var loader = require('load-helpers');
var randomize = require('randomatic');
var _ = require('lodash');

/**
 * Create an instance of `Helpers`, optionally passing
 * default `options`.
 *
 * ```js
 * var Helpers = require('helper-cache');
 * var helpers = new Helpers();
 * ```
 *
 * @param {Object} `options` Default options to use.
 *   @option {Boolean} [options] `bind` Bind functions to `this`. Defaults to `false`.
 *   @option {Boolean} [options] `thisArg` The context to use.
 * @api public
 */

function Helpers(options) {
  if (!(this instanceof Helpers)) {
    return new Helpers(options);
  }

  var opts = _.defaults({}, options, {
    bind: false,
    thisArg: this
  });

  defineGetter(this, 'options', function () {
    return opts;
  });

  var obj = {asyncHelpers: {}, waiting: []};
  defineGetter(this, '_', function () {
    return obj;
  });
}

/**
 * Register a helper.
 *
 * ```js
 * helpers.addHelper('lower', function(str) {
 *   return str.toLowerCase();
 * });
 * ```
 *
 * @name .addHelper
 * @param {String} `name` The name of the helper.
 * @param {Function} `fn` Helper function.
 * @api public
 */

defineGetter(Helpers.prototype, 'addHelper', function () {
  return function (name, fn, thisArg) {
    thisArg = thisArg || this.options.thisArg;

    if (typeof name !== 'string') {
      _.extend(this, name);
    } else {
      if (this.options.bind) {
        this[name] = _.bind(fn, thisArg);
      } else {
        this[name] = fn;
      }
    }
    return this;
  }.bind(this);
});

/**
 * Register an async helper.
 *
 * ```js
 * helpers.addAsyncHelper('foo', function (str, callback) {
 *   callback(null, str + ' foo');
 * });
 * ```
 *
 * @name .addAsyncHelper
 * @param {String} `key` The name of the helper.
 * @param {Function} `fn` Helper function.
 * @api public
 */

defineGetter(Helpers.prototype, 'addAsyncHelper', function () {
  return function(key, fn, thisArg) {
    thisArg = thisArg || this.options.thisArg;
    if (typeof key !== 'string') {
      _.forOwn(key, function (value, k) {
        this.addAsyncHelper(k, value, thisArg);
      }, this);
    } else {
      var self = this;
      if (this.options.bind) {
        this._.asyncHelpers[key] = _.bind(fn, thisArg || this);
      } else {
        this._.asyncHelpers[key] = fn;
      }
      this.addHelper(key, function () {
        var id = '__async_helper_id__' + randomize('Aa0', 42) + '__';
        var args = [].slice.call(arguments);
        self._.waiting.push({id: id, key: key, args: args, fn: fn.bind(this)});
        return id;
      });
    }
    return this;
  }
});

/**
 * Load a glob or object of helpers.
 *
 * ```js
 * // glob patterns
 * helpers.addHelpers('helpers/*.js');
 * helpers.addHelpers(['helpers/a.js', 'helpers/{b,c}.js']);
 * // object of helper functions
 * helpers.addHelpers({
 *   a: function() {},
 *   b: function() {},
 *   c: function() {},
 * });
 * ```
 *
 * See [load-helpers] for issues, API details and the full range of options.
 *
 * @name .addHelpers
 * @param {String} `key` The name of the helper.
 * @param {Function} `fn` Helper function.
 * @api public
 */

defineGetter(Helpers.prototype, 'addHelpers', function () {
  return function () {
    var thisArg = this.options.thisArg;

    loader.init();

    var helpers = loader.load.apply(loader, arguments);
    _.forIn(helpers.cache, function (value, key) {
      var o = {};
      if (this.options.bind) {
        o[key] = _.bind(value, thisArg);
      } else {
        o[key] = value;
      }
      _.extend(this, o);
    }, this);

    return this;
  }.bind(this);
});

/**
 * Load a glob or object of async helpers.
 *
 * ```js
 * // glob patterns
 * helpers.addAsyncHelpers('helpers/*.js');
 * helpers.addAsyncHelpers(['helpers/a.js', 'helpers/{b,c}.js']);
 * // object of helper functions
 * helpers.addAsyncHelpers({
 *   a: function() {},
 *   b: function() {},
 *   c: function() {},
 * });
 * ```
 *
 * See [load-helpers] for issues, API details and the full range of options.
 *
 * @name .addAsyncHelpers
 * @param {String} `key` The name of the helper.
 * @param {Function} `fn` Helper function.
 * @api public
 */

defineGetter(Helpers.prototype, 'addAsyncHelpers', function () {
  return function () {
    var thisArg = this.options.thisArg;
    loader.init();
    var helpers = loader.load.apply(loader, arguments);
    return this.addAsyncHelper(helpers.cache);
  }.bind(this);
});

/**
 * Get a registered helper.
 *
 * ```js
 * helpers.getHelper('foo');
 * ```
 *
 * @name .getHelper
 * @param  {String} `key` The helper to get.
 * @return {Object} The specified helper. If no `key` is passed, the entire cache is returned.
 * @api public
 */

defineGetter(Helpers.prototype, 'getHelper', function () {
  return function(key) {
    if (!key) {
      return this;
    }
    return this[key];
  }.bind(this);
});

/**
 * Get a registered async helper.
 *
 * ```js
 * helpers.getAsyncHelper('foo');
 * ```
 *
 * @name .getAsyncHelper
 * @param  {String} `key` The helper to get.
 * @return {Object} The specified helper. If no `key` is passed, the entire cache is returned.
 * @api public
 */

defineGetter(Helpers.prototype, 'getAsyncHelper', function () {
  return function(key) {
    if (!key) {
      return this._.asyncHelpers;
    }
    return this._.asyncHelpers[key];
  }.bind(this);
});

/**
 * Getter method to resolve async helper values that were called during
 * the render process. Rendering is done by whatever engine you've registered
 * the helpers with.
 *
 * ```js
 * helper.resolveHelper(str, function (err, content) {
 *   if (err) return done(err);
 *   // do stuff with `content`
 *   done();
 * });
 * ```
 * @name .resolveHelper
 * @param {String} `content` Rendered string containing async ids
 * @param {Function} `cb`
 * @api public
 */

defineGetter(Helpers.prototype, 'resolveHelper', function () {
  return function (content, cb) {
    var self = this;
    var i = self._.waiting.length;
    var next = function (err, content) {
      // current helper info
      var helper = self._.waiting[--i];

      if (helper) {
        // original async helper
        var fn = helper.fn;

        if (!fn) return next(null, content);
        if (content.indexOf(helper.id) === -1) {
          return next(null, content);
        }

        // replacing this helper id, so remove it from the waiting list
        // call the async helper and replace id with results
        var args = helper.args || [];
        var nextCallback = function (err, results) {
          if (err) return cb(err);
          content = content.replace(helper.id, results);
          // remove the helper from the waiting list
          self._.waiting.splice(i+1, 1);
          next(null, content);
        };
        if (args[args.length-1].toString() !== nextCallback.toString()) {
          args.push(nextCallback);
        }

        fn.apply(fn, args);
      } else {
        // call final callback
        return cb(null, content);
      }
    }
    return next(null, content);
  };
});

/**
 * Utility method to define getters.
 *
 * @param  {Object} `obj`
 * @param  {String} `name`
 * @param  {Function} `getter`
 * @return {Getter}
 * @api private
 */

function defineGetter(obj, name, getter) {
  Object.defineProperty(obj, name, {
    configurable: false,
    enumerable: false,
    get: getter,
    set: function() {}
  });
}

module.exports = Helpers;
<|endoftext|>


<commit_before>require('coffee-script/register');
require('./index.coffee');
<commit_msg>Fixed index.js to export<commit_after>require('coffee-script/register');
module.exports = require('./index.coffee');
<|endoftext|>


<commit_before>module.exports = require('./lib/table.jsx');
<commit_msg>Expose more than just a table<commit_after>var Table     = require('./lib/table.jsx');
var Formatter = require('./lib/formatter.jsx');
var Cell      = require('./lib/cell.jsx');

module.exports = {
  Table     : Table,
  Formatter : Formatter,
  Cell      : Cell
};
<|endoftext|>


<commit_before>var FramingBuffer = require('framing-buffer'),
    OffsetBuffer = require('offset-buffer'),
    debug = false,
    net = require('net'),
    events = require('events'),
    util = require('util'),
    when = require('when'),
    errors = require('./errors.js')(util);

module.exports = require('./framing-socket.js')(
    FramingBuffer,
    OffsetBuffer,
    debug,
    net,
    events,
    util,
    when,
    errors,
    console
);<commit_msg>updated to remove the when library<commit_after>var FramingBuffer = require('framing-buffer'),
    OffsetBuffer = require('offset-buffer'),
    debug = false,
    net = require('net'),
    events = require('events'),
    util = require('util'),
    errors = require('./errors.js')(util);

module.exports = require('./framing-socket.js')(
    FramingBuffer,
    OffsetBuffer,
    debug,
    net,
    events,
    util,
    errors,
    console
);<|endoftext|>


<commit_before>'use strict'

const express = require('express'),
 bodyParser = require('body-parser'),
 request = require('request'),
 app = express();

// should this just be declared in FB bot module?
const token = process.env.FB_PAGE_ACCESS_TOKEN
// is this even used?
const GH_token = process.env.GH_API_ACCESS_TOKEN

var hellobot = require('./hellobot.js'),
 dicebot = require('./dicebot.js');
 // ghSlackBot = require('./gh-slack-promises.js'),
 // ghFacebookBot = require('./gh-facebook-bot.js');

var port = process.env.PORT || 3000;

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(400).send(err.message);
});

// test route
app.get('/', function (req, res) { res.status(200).send('Hello world!') });

// hellobot - keep for testing
app.post('/hello', hellobot);
// dicebot - keep for testing
app.post('/roll', dicebot);
// gethuman bot for Slack - to be deprecated
// app.post('/gethuman', ghSlackBot);
// gethuman bot for FB - to be deprecated
// app.post('/webhook/', ghFacebookBot);

// for Facebook verification
app.get('/webhook/', function (req, res) {
    if (req.query['hub.verify_token'] === 'my_voice_is_my_password_verify_me') {
        res.send(req.query['hub.challenge'])
    }
    res.send('Error, wrong token');
})

app.listen(port, function () {
  console.log('Fusion bot listening on port ' + port);
});

// ***************************************
// unified api endpoint
// ***********************

// -Temporarily using this endpoint, change to V3/ when Slack issue handled
app.post('/gethuman', function (req, res) {
// app.post('/v3/webhook', function (req, res) {
  // put data from the Express req object into our custom context object
  var platformRequestContext = { userRequest: req.body };
  // get a BotHandler object based on the context
  getBotHandler(platformRequestContext)
    .then(function (botHandler) {
      // hit the API and form up a payload for response
      return botHandler.getResponsePayload(platformRequestContext);
    })
    // this is an object that contains { raw: {}, data: {}, context: {} }
    .then(function (responsePayload) {
      // this is the response to the original request
      // (comment this out if for now if needed return for Facebook/other bots)
      res.send(responsePayload.raw);
      // this is really only if need brand new request back to platform
      // i.e. used for slack (but messenger this may be empty)
      botHandler.sendResponseToPlatform(responsePayload)
      // possibly an if/else required if two different Sends will break it
    })
    .then(function () {
      res.status(200).end();
    })
    .catch(function (err) {
      // get response object that contains the thing you want to send to
      // the bot when an error occurs
      var errorPayload = botHandler.getErrorPayload(err, platformRequestContext);
      // send response to original request
      res.send(errorPayload.raw);
      // this should log error and then call botHandler.sendResponseToPlatform()
      // under the scenes
      botHandler.sendErrorResponse(errorPayload)
        .then(function () {
          res.status(200).end();
        });
    });
});

// export this to a module
var handlers = [require('./slack-handler'), require('./messenger-handler')];

function getBotHandler(platformRequestContext) {
  // loop through handlers and call handlers[i].isHandlerForRequest(platformRequestContext)
  var botFound = false;

  for (let i = 0; i < handlers.length; i++) {
    if (handlers[i].isHandlerForRequest(platformRequestContext)) {
      botfound = true;
      return handlers[i];
    };
  };
  // else if handler not found, throw error
  if (!botFound) {
    throw "Request coming from unrecognized platform";
  };

}<commit_msg>Debug<commit_after>'use strict'

const express = require('express'),
 bodyParser = require('body-parser'),
 request = require('request'),
 app = express();

// should this just be declared in FB bot module?
const token = process.env.FB_PAGE_ACCESS_TOKEN
// is this even used?
const GH_token = process.env.GH_API_ACCESS_TOKEN

var hellobot = require('./hellobot.js'),
 dicebot = require('./dicebot.js');
 // ghSlackBot = require('./gh-slack-promises.js'),
 // ghFacebookBot = require('./gh-facebook-bot.js');

var port = process.env.PORT || 3000;

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(400).send(err.message);
});

// test route
app.get('/', function (req, res) { res.status(200).send('Hello world!') });

// hellobot - keep for testing
app.post('/hello', hellobot);
// dicebot - keep for testing
app.post('/roll', dicebot);
// gethuman bot for Slack - to be deprecated
// app.post('/gethuman', ghSlackBot);
// gethuman bot for FB - to be deprecated
// app.post('/webhook/', ghFacebookBot);

// for Facebook verification
app.get('/webhook/', function (req, res) {
    if (req.query['hub.verify_token'] === 'my_voice_is_my_password_verify_me') {
        res.send(req.query['hub.challenge'])
    }
    res.send('Error, wrong token');
})

app.listen(port, function () {
  console.log('Fusion bot listening on port ' + port);
});

// ***************************************
// unified api endpoint
// ***********************

// -Temporarily using this endpoint, change to V3/ when Slack issue handled
app.post('/gethuman', function (req, res) {
// app.post('/v3/webhook', function (req, res) {
  // put data from the Express req object into our custom context object
  var platformRequestContext = { userRequest: req.body };
  // get a BotHandler object based on the context
  getBotHandler(platformRequestContext)
    .then(function (botHandler) {
      // hit the API and form up a payload for response
      return botHandler.getResponsePayload(platformRequestContext);
    })
    // this is an object that contains { raw: {}, data: {}, context: {} }
    .then(function (responsePayload) {
      // this is the response to the original request
      // (comment this out if for now if needed return for Facebook/other bots)
      res.send(responsePayload.raw);
      // this is really only if need brand new request back to platform
      // i.e. used for slack (but messenger this may be empty)
      botHandler.sendResponseToPlatform(responsePayload)
      // possibly an if/else required if two different Sends will break it
    })
    .then(function () {
      res.status(200).end();
    })
    .catch(function (err) {
      // get response object that contains the thing you want to send to
      // the bot when an error occurs
      var errorPayload = botHandler.getErrorPayload(err, platformRequestContext);
      // send response to original request
      res.send(errorPayload.raw);
      // this should log error and then call botHandler.sendResponseToPlatform()
      // under the scenes
      botHandler.sendErrorResponse(errorPayload)
        .then(function () {
          res.status(200).end();
        });
    });
});

// export this to a module
var handlers = [require('./slack-handler'), require('./messenger-handler')];

function getBotHandler(platformRequestContext) {
  // loop through handlers and call handlers[i].isHandlerForRequest(platformRequestContext)
  var botFound = false;

  for (let i = 0; i < handlers.length; i++) {
    if (handlers[i].isHandlerForRequest(platformRequestContext)) {
      botFound = true;
      return handlers[i];
    };
  };
  // else if handler not found, throw error
  if (!botFound) {
    throw "Request coming from unrecognized platform";
  };

}<|endoftext|>


<commit_before>export { default as OpsProvider } from './OpsProvider'

export class MemorySIDStore {
  _sid: null
  async get() { return this._sid }
  async set(sid) { this._sid = sid }
}

export default class OpsClient {
  static CONNECTING_CHECK_INTERVAL = 10
  static CONNECTION_TIMEOUT = 10000

  _currentRequestID = 0

  constructor(ws, sidStore = new MemorySIDStore(), getExtra = () => ({})) {
    this._ws = ws
    this._sidStore = sidStore
    this._getExtra = getExtra
  }

  _makeSureConnected() {
    return new Promise((resolve, reject) => {
      if (this._ws.readyState === WebSocket.OPEN) {
        resolve()
        return
      }

      const timeout = setTimeout(() => {
        clearInterval(checkInterval) // eslint-disable-line no-use-before-define
        reject('WebSocket connection timed out.')
      }, OpsClient.CONNECTION_TIMEOUT)

      const checkInterval = setInterval(() => {
        if (this._ws.readyState !== WebSocket.OPEN) return
        clearTimeout(timeout)
        clearInterval(checkInterval)
        resolve()
      }, OpsClient.CONNECTING_CHECK_INTERVAL)
    })
  }

  request(name, payload) {
    return this._makeSureConnected()
      .then(this._sidStore.get)
      .then(_sid => new Promise((resolve, reject) => {
        const id = ++this._currentRequestID

        // One-off listener for this message
        const listener = message => {
          const response = JSON.parse(message.data)

          if (response.id !== id) return

          this._ws.removeEventListener('message', listener)

          if (response.error) {
            reject(response.error)
            return
          }

          // If the server returns a different _sid, update it here, client-side
          if (_sid !== response._sid) {
            this._sidStore.set(response._sid).then(() => resolve(response.result))
            return
          }

          resolve(response.result)
        }

        this._ws.addEventListener('message', listener)
        this._ws.send(JSON.stringify({ _sid, id, name, payload, extra: this._getExtra() }))
      }))
  }
}
<commit_msg>Fix _sid/sid<commit_after>export { default as OpsProvider } from './OpsProvider'

export class MemorySIDStore {
  _sid: null
  async get() { return this._sid }
  async set(sid) { this._sid = sid }
}

export default class OpsClient {
  static CONNECTING_CHECK_INTERVAL = 10
  static CONNECTION_TIMEOUT = 10000

  _currentRequestID = 0

  constructor(ws, sidStore = new MemorySIDStore(), getExtra = () => ({})) {
    this._ws = ws
    this._sidStore = sidStore
    this._getExtra = getExtra
  }

  _makeSureConnected() {
    return new Promise((resolve, reject) => {
      if (this._ws.readyState === WebSocket.OPEN) {
        resolve()
        return
      }

      const timeout = setTimeout(() => {
        clearInterval(checkInterval) // eslint-disable-line no-use-before-define
        reject('WebSocket connection timed out.')
      }, OpsClient.CONNECTION_TIMEOUT)

      const checkInterval = setInterval(() => {
        if (this._ws.readyState !== WebSocket.OPEN) return
        clearTimeout(timeout)
        clearInterval(checkInterval)
        resolve()
      }, OpsClient.CONNECTING_CHECK_INTERVAL)
    })
  }

  request(name, payload) {
    return this._makeSureConnected()
      .then(this._sidStore.get)
      .then(_sid => new Promise((resolve, reject) => {
        const id = ++this._currentRequestID

        // One-off listener for this message
        const listener = message => {
          const response = JSON.parse(message.data)

          if (response.id !== id) return

          this._ws.removeEventListener('message', listener)

          if (response.error) {
            reject(response.error)
            return
          }

          // If the server returns a different _sid, update it here, client-side
          if (_sid !== response.sid) {
            this._sidStore.set(response.sid).then(() => resolve(response.result))
            return
          }

          resolve(response.result)
        }

        this._ws.addEventListener('message', listener)
        this._ws.send(JSON.stringify({ sid: _sid, id, name, payload, extra: this._getExtra() }))
      }))
  }
}
<|endoftext|>


<commit_before>var net = require('net');
var _ = require('lodash');

function parseData(chunk, idx) {
    return chunk.readInt16LE(idx*2);
}

var processData = function(chunk) {

    if(chunk == null || chunk.length <= 0 || chunk.length != 320)
        return;

    var sum = 0;
    var n = 160;
    while(n --> 0) {
        var val = parseData(chunk, n);
        sum += Math.pow(val, 2);
    }

    var rms = Math.sqrt(sum/160);
    var status = rms >= 90 ? "sound" : "no sound";

    console.log(status + "\r");
}

net.createServer(function (client) {
    client.on('data', _.throttle(processData, 100));
}).listen(3333);

var gpio = require('rpi-gpio');

gpio.setup(12, gpio.DIR_OUT, callback);

var val = false;
function callback(err) {

    if (err) throw err;

    setInterval(function() {
        val = !val;
        delayedWrite(12, val, function(err) {
            if (err) throw err;
            console.log('Written to pin');
        });
    }, 1000);

}

function delayedWrite(pin, value, callback) {
    setTimeout(function() {
        gpio.write(pin, value, callback);
    }, 500);
}

<commit_msg>be clienti instead<commit_after>var net = require('net');
var _ = require('lodash');

function parseData(chunk, idx) {
    return chunk.readInt16LE(idx*2);
}

var processData = function(chunk) {

    if(chunk == null || chunk.length <= 0 || chunk.length != 320)
        return;

    var sum = 0;
    var n = 160;
    while(n --> 0) {
        var val = parseData(chunk, n);
        sum += Math.pow(val, 2);
    }

    var rms = Math.sqrt(sum/160);
    var status = rms >= 90 ? "sound" : "no sound";

    console.log(status + "\r");
}

var client = net.connect({
    port: 3333
},
function() {
  console.log('connected to arecord');
});

client.on('data', _.throttle(processData, 100));

var gpio = require('rpi-gpio');

gpio.setup(12, gpio.DIR_OUT, callback);

var val = false;
function callback(err) {

    if (err) throw err;

    setInterval(function() {
        val = !val;
        delayedWrite(12, val, function(err) {
            if (err) throw err;
            console.log('Written to pin');
        });
    }, 1000);

}

function delayedWrite(pin, value, callback) {
    setTimeout(function() {
        gpio.write(pin, value, callback);
    }, 500);
}

<|endoftext|>


<commit_before>// Dependencies
//const modules = require('./lib/modules');
//const instances = require('./lib/instances');
//const events = require('./lib/events');
const cayley = require('cayley');
const Adapter = require('./lib/cayley_adapter');
const VIS = require('./lib/cayley_vis');
const GET = require('./lib/cayley_get');
const POST = require('./lib/cayley_post');
const DELETE = require('./lib/cayley_delete');
const utils = require('./lib/utils');

function connect (state, db) {
    state.client = cayley(db);
    state.g = state.client.graph;
}

function getHandler (Methods, fn, params) {

    if (typeof Methods[fn] !== 'function') {
        throw new Error('Flow-api.cayley: Method "' + fn + '" doesn\' exists.');
    }

    return (scope, state, args, data, next) => {

        // create db client for state
        if (!state.client) {
            connect(state, scope.env.db);
        }

        let query_args = [state.g];
        for (let i = 0, l = params.length; i < l; ++i) {

            if (typeof data[params[i]] === 'undefined') {
                return next(new Error('Flow-api.get.' + fn  + ': Missing parameter "' + params[i]  + '".'));
            }

            query_args.push(data[params[i]]);
        };

        query_args.push(!data.session || !data.session.role ? scope.env.role : data.session.role);

        data.readable = Methods[fn].apply(null, query_args);

        try {
            if (data.readable instanceof Array) {
                data.readable.forEach(stream => stream.pause());
            } else {
                data.readable.pause();
            }
        } catch (err) {
            return next(err);
        }

        data.resume = data.readable;
        next(null, data);
    }
}

function postHandler (scope, state, args, data, next) {

    // create db client for state
    if (!state.client) {
        connect(state, scope.env.db);
    }

    let count = 0;
    const errors = [];
    const success = [];

    // parse request
    data.req.on('data', req => {
        POST(state.client, req, (err, res) => {
            if (err) {
                errors.push(err);
            } else {
                success.push(res);
            }
        });
    });

    data.req.on('error', (err) => next(err));

    // parse end
    data.req.on('end', () => {

        data.body = {
            success: success,
            errors: errors
        };

        next(null, data);
    });
}

function deleteHandler (scope, state, args, data, next) {

    // create db client for state
    if (!state.client) {
        connect(state, scope.env.db);
    }

    DELETE(state.client, data.req.url);
    data.body = {status: "ok"};
    next(null, data);
}

// export API methods
module.exports = {
    _connect: connect,
    utils: utils,
    flow: getHandler(Adapter, 'flow', ['id']),
    vis: {
        networks: getHandler(VIS, 'vis_networks', ['id']),
        entrypoints: getHandler(VIS, 'vis_entrypoints', ['id']),
        entrypoint: getHandler(VIS, 'vis_entrypoint', ['id']),
        sequence: getHandler(VIS, 'vis_sequence', ['id']),
        handler: getHandler(VIS, 'vis_handler', ['id']),
        object: getHandler(VIS, 'vis_object', ['id'])
    },
    get: getHandler(GET, 'get', ['id', 'type']),
    post: postHandler,
    remove: deleteHandler,
    del: {}
};
<commit_msg>fix timing<commit_after>// Dependencies
//const modules = require('./lib/modules');
//const instances = require('./lib/instances');
//const events = require('./lib/events');
const cayley = require('cayley');
const Adapter = require('./lib/cayley_adapter');
const VIS = require('./lib/cayley_vis');
const GET = require('./lib/cayley_get');
const POST = require('./lib/cayley_post');
const DELETE = require('./lib/cayley_delete');
const utils = require('./lib/utils');

function connect (state, db) {
    state.client = cayley(db);
    state.g = state.client.graph;
}

function getHandler (Methods, fn, params) {

    if (typeof Methods[fn] !== 'function') {
        throw new Error('Flow-api.cayley: Method "' + fn + '" doesn\' exists.');
    }

    return (scope, state, args, data, next) => {

        // create db client for state
        if (!state.client) {
            connect(state, scope.env.db);
        }

        let query_args = [state.g];
        for (let i = 0, l = params.length; i < l; ++i) {

            if (typeof data[params[i]] === 'undefined') {
                return next(new Error('Flow-api.get.' + fn  + ': Missing parameter "' + params[i]  + '".'));
            }

            query_args.push(data[params[i]]);
        };

        query_args.push(!data.session || !data.session.role ? scope.env.role : data.session.role);

        data.readable = Methods[fn].apply(null, query_args);

        try {
            if (data.readable instanceof Array) {
                data.readable.forEach(stream => stream.pause());
            } else {
                data.readable.pause();
            }
        } catch (err) {
            return next(err);
        }

        data.resume = data.readable;
        next(null, data);
    }
}

function postHandler (scope, state, args, data, next) {

    // create db client for state
    if (!state.client) {
        connect(state, scope.env.db);
    }

    let count = 1;
    const errors = [];
    const success = [];
    const done = () => {
        data.body = {
            success: success,
            errors: errors
        };

        next(null, data);
    };

    // parse request
    data.req.on('data', req => {
        ++count
        POST(state.client, req, (err, res) => {

            if (err) {
                errors.push(err);
            } else {
                success.push(res);
            }

            if (--count === 0) {
                done();
            }
        });
    });

    data.req.on('error', (err) => next(err));

    // parse end
    data.req.on('end', () => {
        if (--count === 0) {
            done();
        }
    });
}

function deleteHandler (scope, state, args, data, next) {

    // create db client for state
    if (!state.client) {
        connect(state, scope.env.db);
    }

    DELETE(state.client, data.req.url);
    data.body = {status: "ok"};
    next(null, data);
}

// export API methods
module.exports = {
    _connect: connect,
    utils: utils,
    flow: getHandler(Adapter, 'flow', ['id']),
    vis: {
        networks: getHandler(VIS, 'vis_networks', ['id']),
        entrypoints: getHandler(VIS, 'vis_entrypoints', ['id']),
        entrypoint: getHandler(VIS, 'vis_entrypoint', ['id']),
        sequence: getHandler(VIS, 'vis_sequence', ['id']),
        handler: getHandler(VIS, 'vis_handler', ['id']),
        object: getHandler(VIS, 'vis_object', ['id'])
    },
    get: getHandler(GET, 'get', ['id', 'type']),
    post: postHandler,
    remove: deleteHandler,
    del: {}
};
<|endoftext|>


<commit_before>module.exports = [
    "don't worry. no one actually knows what they're doing."
  , "this is Hard Stuff, but you can do it!"
];
<commit_msg>Adds encouragement<commit_after>module.exports = [
    "don't worry. no one actually knows what they're doing."
  , "this is Hard Stuff, but you can do it!"
  , "If you can see this message it means you got it working and that's something to celebrate! ['hip','hip']!"
];
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('canonical-path');
var gutil = require('gulp-util');
var through = require('through');
var mustache = require('mustache');
var sizeOf = require('image-size');
var mime = require('mime');
var md5 = require('md5');
var appRoot = require('app-root-path').path;

module.exports = function (options) {
  var images = [];
  //var images_path = options.images_path || '';

  if (!options) options = {};

  if (!options.template)
      options.template = path.join(__dirname, 'compass-imagehelper.mustache');

  if (!options.targetFile)
      options.targetFile = '_compass-imagehelper.scss';

  if (!options.prefix)
      options.prefix = '';

  var template = fs.readFileSync(options.template).toString();

  var pathPrefix = function () {
    var result = '';
    if (options.http_images_path) {
      result = options.http_images_path;
    } else if (options.css_path && options.images_path) {
      // relative path from css folder to images
      result = path.relative(options.css_path, options.images_path);
    } else if (options.images_path) {
      // relative from project url
      result = path.relative(appRoot, options.images_path);
    }

    // make sure pathPrefix ends with a trailing slash
    if (result && result.substr(-1) != '/') {
      result = result + '/';
    }

    return result;
  };

  var bufferContents = function (file) {
    if (!options.images_path) {
      // autodetect images_path with the first file
      options.images_path = path.relative(appRoot,  file.base);
    }

    var imageInfo = {};
    var data;
    var encoding;

    var mimetype = mime.lookup(file.path);
    var dimensions;

    if (mimetype == 'image/svg+xml') {
      data = file.contents.toString()
          .replace(/"/g, '\'')
          .replace(/%/g, '%25')
          .replace(/</g, '%3C')
          .replace(/>/g, '%3E')
          .replace(/&/g, '%26')
          .replace(/#/g, '%23')
          .replace(/\s+/g, ' ')
          .trim();
      encoding = 'charset=US-ASCII';
      dimensions = sizeOf(file.path);
    } else {
      data = file.contents.toString('base64');
      encoding = 'base64';
      dimensions = sizeOf(file.path);
    }

    imageInfo.width = dimensions.width;
    imageInfo.height = dimensions.height;
    imageInfo.mime = mimetype;
    imageInfo.filename = path.basename(file.path);
    imageInfo.basename = path.basename(file.path, path.extname(file.path));
    imageInfo.dirname = path.basename(path.dirname(file.path));
    imageInfo.ext = path.extname(file.path);
    imageInfo.path = path.relative(options.images_path, file.path);
    // Replace /, \ and . with -
    imageInfo.fullname = imageInfo.path.replace(/[\/\\\.]/g, '-');
    imageInfo.hash = md5(file.contents);
    imageInfo.data = 'url("data:' + mimetype + ';' + encoding + ',' + data + '")';
    images.push(imageInfo);

  };

  var endStream = function () {
    this.emit('data', new gutil.File({
      contents: new Buffer(mustache.render(template, {
        prefix: options.prefix,
        path_prefix: pathPrefix(),
        items: images,
      }), 'utf8'),
      path: options.targetFile,
    }));
    this.emit('end');
  };

  return new through(bufferContents, endStream);
};
<commit_msg>minor formatting changes<commit_after>var fs = require('fs');
var path = require('canonical-path');
var gutil = require('gulp-util');
var through = require('through');
var mustache = require('mustache');
var sizeOf = require('image-size');
var mime = require('mime');
var md5 = require('md5');
var appRoot = require('app-root-path').path;

module.exports = function (options) {
  var images = [];
  //var images_path = options.images_path || '';

  if (!options) options = {};

  if (!options.template)
    options.template = path.join(__dirname, 'compass-imagehelper.mustache');

  if (!options.targetFile)
    options.targetFile = '_compass-imagehelper.scss';

  if (!options.prefix)
    options.prefix = '';

  var template = fs.readFileSync(options.template).toString();

  var pathPrefix = function () {
    var result = '';
    if (options.http_images_path) {
      result = options.http_images_path;
    } else if (options.css_path && options.images_path) {
      // relative path from css folder to images
      result = path.relative(options.css_path, options.images_path);
    } else if (options.images_path) {
      // relative from project url
      result = path.relative(appRoot, options.images_path);
    }

    // make sure pathPrefix ends with a trailing slash
    if (result && result.substr(-1) != '/') {
      result = result + '/';
    }

    return result;
  };

  var bufferContents = function (file) {
    if (!options.images_path) {
      // autodetect images_path with the first file
      options.images_path = path.relative(appRoot, file.base);
    }

    var imageInfo = {};
    var data;
    var encoding;

    var mimetype = mime.lookup(file.path);
    var dimensions;

    if (mimetype == 'image/svg+xml') {
      data = file.contents.toString()
          .replace(/"/g, '\'')
          .replace(/%/g, '%25')
          .replace(/</g, '%3C')
          .replace(/>/g, '%3E')
          .replace(/&/g, '%26')
          .replace(/#/g, '%23')
          .replace(/\s+/g, ' ')
          .trim();
      encoding = 'charset=US-ASCII';
      dimensions = sizeOf(file.path);
    } else {
      data = file.contents.toString('base64');
      encoding = 'base64';
      dimensions = sizeOf(file.path);
    }

    imageInfo.width = dimensions.width;
    imageInfo.height = dimensions.height;
    imageInfo.mime = mimetype;
    imageInfo.filename = path.basename(file.path);
    imageInfo.basename = path.basename(file.path, path.extname(file.path));
    imageInfo.dirname = path.basename(path.dirname(file.path));
    imageInfo.ext = path.extname(file.path);
    imageInfo.path = path.relative(options.images_path, file.path);
    // Replace /, \ and . with -
    imageInfo.fullname = imageInfo.path.replace(/[\/\\\.]/g, '-');
    imageInfo.hash = md5(file.contents);
    imageInfo.data = 'url("data:' + mimetype + ';' + encoding + ',' + data + '")';
    images.push(imageInfo);

  };

  var endStream = function () {
    this.emit('data', new gutil.File({
      contents: new Buffer(mustache.render(template, {
        prefix: options.prefix,
        path_prefix: pathPrefix(),
        items: images,
      }), 'utf8'),
      path: options.targetFile,
    }));
    this.emit('end');
  };

  return new through(bufferContents, endStream);
};
<|endoftext|>


<commit_before>require('dotenv').config();
const slides = require('./slides');
const bigquery = require('./bigquery');

console.log('-- Start generating slides. --')
slides.getClientSecrets()
  .then((credentials) => Promise.all([
    slides.authorize(credentials), bigquery.getLicenseData()
  ]))
  .then(slides.createSlides)
  .then(slides.openSlidesInBrowser)
  .then(() => {
    console.log('-- Finished generating slides. --');
  });
<commit_msg>Add small comment in index.js<commit_after>require('dotenv').config();
const slides = require('./slides');
const bigquery = require('./bigquery');

/**
 * Generates slides using the Google Slides, Drive, and BigQuery APIs.
 */
console.log('-- Start generating slides. --')
slides.getClientSecrets()
  .then((credentials) => Promise.all([
    slides.authorize(credentials), bigquery.getLicenseData()
  ]))
  .then(slides.createSlides)
  .then(slides.openSlidesInBrowser)
  .then(() => {
    console.log('-- Finished generating slides. --');
  });
<|endoftext|>


<commit_before>var holder = d3.select("body").append("div");
var svg = holder.append("svg").attr("class", "mapSvg").attr("width", "75%").attr("height", "75%");
var textInfo = holder.append("div").attr("width", "100%").attr("height", "100%");
var svgGroup = svg.append("g");
var width = parseInt(svg.style('width'));
var height = parseInt(svg.style('height'));
var projection = d3.geoEquirectangular().scale(135).center([48, 25]).translate([width / 2, height / 2]);
var path = d3.geoPath().projection(projection);
var slider, colorScale;

d3.queue()
  .defer(d3.json, "countries.geo.json")
  .await(drawMap);

function drawMap(error, countries){
  svgGroup.append("g")
            .selectAll("path")
            .data(countries.features)
            .enter().append("path")
            .attr("class", "country")
            .attr("d", path)
            .on("click", function(d){
              console.log(d);
              });

  svg.call(d3.zoom()
               .scaleExtent([1 / 2, 500])
               .on("zoom", zoomed));
}

function zoomed() {
    svgGroup.attr("transform", d3.event.transform);
}
<commit_msg>filter csv data by country name<commit_after>var holder = d3.select("body").append("div");
var svg = holder.append("svg").attr("class", "mapSvg").attr("width", "75%").attr("height", "75%");
var textInfo = holder.append("div").attr("width", "100%").attr("height", "100%");
var svgGroup = svg.append("g");
var width = parseInt(svg.style('width'));
var height = parseInt(svg.style('height'));
var projection = d3.geoEquirectangular().scale(135).center([48, 25]).translate([width / 2, height / 2]);
var path = d3.geoPath().projection(projection);
var slider, colorScale;

d3.queue()
  .defer(d3.json, "countries.geo.json")
  .defer(d3.csv, "FAOSTAT_data_4-12-2017.csv")
  .await(drawMap);

function drawMap(error, countries, emissions){
  if(error)
    return error;
  svgGroup.append("g")
            .selectAll("path")
            .data(countries.features)
            .enter().append("path")
            .attr("class", "country")
            .attr("d", path)
            .on("click", function(d){
              console.log(d.properties.name);
              console.log(emissions.filter(function(e){return e.Area.includes(d.properties.name);}));
              });

  svg.call(d3.zoom()
               .scaleExtent([1 / 2, 500])
               .on("zoom", zoomed));
}

function zoomed() {
    svgGroup.attr("transform", d3.event.transform);
}
<|endoftext|>


<commit_before>module.exports = function (sails) {

    var exec = require('./lib/milight.exec.js');
    var setup = require('./lib/milight.setup.js');
    var init = require('./lib/milight.init.js');
    var shared = require('./lib/milight.shared.js');

    gladys.on('ready', function(){
        init()
    });

    return {
        exec,
        setup,
        init,
        shared() {
          return shared
        }
    };
};
<commit_msg>getBridge(id)<commit_after>module.exports = function (sails) {

    var exec = require('./lib/milight.exec.js');
    var setup = require('./lib/milight.setup.js');
    var init = require('./lib/milight.init.js');
    var shared = require('./lib/milight.shared.js');

    gladys.on('ready', function(){
        init()
    });

    return {
        exec,
        setup,
        init,
        getBridge(id) {
          return shared.bridges[id]
        }
    };
};
<|endoftext|>


<commit_before>#! /usr/bin/env node
"use strict";

/**
 * @module BrowserSync
 */
var pjson         = require("./package.json");
var BrowserSync   = require("./lib/browser-sync");
var utils         = require("./lib/utils");
var events        = require("events");
var logger        = require("eazy-logger").Logger({
    useLevelPrefixes: true
});

var singleton        = false;
var singletonPlugins = [];
var instances        = [];

/**
 * @type {boolean|EventEmitter}
 */
var singletonEmitter = false;

/**
 * @method browserSync
 * @param {Object} [config] This is the main configuration for your BrowserSync instance and can contain any of the [available options]({{site.links.options}})
 *  If you do not pass a config an argument for configuration, BrowserSync will still run; but it will be in the `snippet` mode
 * @param {Function} [cb] If you pass a callback function, it will be called when BrowserSync has completed all setup tasks and is ready to use. This
 * is useful when you need to wait for information (for example: urls, port etc) or perform other tasks synchronously.
 * @returns {BrowserSync}
 */
module.exports         = initSingleton;
module.exports.init    = initSingleton;

/**
 * Register a plugin. Must implement at least a 'plugin' method that returns a
 * callable function.
 *
 * @method use
 * @param {String} name The name of the plugin
 * @param {Object} module The object to be `required`.
 * @param {Function} [cb] A callback function that will return any errors.
 */
module.exports.use     = function () {
    var args = Array.prototype.slice.call(arguments);
    singletonPlugins.push({
        args: args
    });
};

/**
 * The `reload` method will inform all browsers about changed files and will either cause the browser to refresh, or inject the files where possible.
 *
 * @method reload
 * @param {String|Array|Object} [arg] The file or files to be reloaded. For
 * details and examples of Streams support, please see the [GulpJS]({{site.links.gulp}}) examples
 * @returns {*}
 */
module.exports.reload  = noop("reload");

/**
 * Helper method for browser notifications
 *
 * @method notify
 * @param {String|HTML} msg Can be a simple message such as 'Connected' or HTML
 * @param {Number} [timeout] How long the message will remain in the browser. @since 1.3.0
 */
module.exports.notify  = noop("notify");

/**
 * This method will close any running server, stop file watching & exit the current process.
 *
 * @method exit
 */
module.exports.exit    = noop("exit");

/**
 * Method to pause file change events
 *
 * @method pause
 */
module.exports.pause   = noop("pause");

/**
 * Method to resume paused watchers
 *
 * @method resume
 */
module.exports.resume  = noop("resume");

/**
 * Add properties fo
 */
Object.defineProperties(module.exports, {
    /**
     * The internal Event Emitter used by the running BrowserSync instance (if there is one).
     * You can use this to emit your own events, such as changed files, logging etc.
     *
     * @property emitter
     */
    "emitter": {
        get: function () {
            if (!singletonEmitter) {
                singletonEmitter = newEmitter();
                return singletonEmitter;
            }
            return singletonEmitter;
        }
    },
    /**
     * A simple true/false flag that you can use to determine if there's a currently-running BrowserSync instance.
     *
     * @property active
     */
    "active": {
        get: getSingletonValue.bind(null, "active")
    },
    /**
     * A simple true/false flag to determine if the current instance is paused
     *
     * @property paused
     */
    "paused": {
        get: getSingletonValue.bind(null, "paused")
    }
});

/**
 * Event emitter factory
 * @returns {EventEmitter}
 */
function newEmitter() {
    var emitter       = new events.EventEmitter();
    emitter.setMaxListeners(20);
    return emitter;
}

/**
 * Get the singleton's emitter, or a new one.
 * @returns {EventEmitter}
 */
function getSingletonEmitter() {
    if (singletonEmitter) {
        return singletonEmitter;
    }
    singletonEmitter = newEmitter();
    return singletonEmitter;
}

/**
 * Helper to allow methods to be called on the module export
 * before there's a running instance
 * @param {String} name
 * @returns {Function}
 */
function noop(name) {
    return function () {
        var args = Array.prototype.slice.call(arguments);
        if (singleton) {
            return singleton[name].apply(singleton, args);
        } else {
            if (name === "reload" && args[0] && args[0].stream) {
                return utils.noopStream();
            }
            deprecated(name); //todo - silent fail here or deprecated message?
        }
    };
}

/**
 * @param name
 */
function deprecated(name) {
    logger.error("This functionality will change in BrowserSync 2.0. You'll have to first call browserSync.create() before {cyan:`.%s()`", name);
}

/**
 * Create a single instance when module export is used directly via browserSync({});
 * This is mostly for back-compatibility, for also for the nicer api.
 * This will never be removed to ensure we never break user-land, but
 * we should discourage it's use.
 * @returns {*}
 */
function initSingleton() {
    var instance;
    if (instances.length) {
        instance = instances.filter(function (item) {
            return item.name === "singleton";
        });
        if (instance.length) {
            logger.error("{yellow:You tried to start BrowserSync twice!} To create multiple instances, use {cyan:browserSync.create().init()");
            return instance;
        }
    }
    var args = Array.prototype.slice.call(arguments);
    singleton = create("singleton", getSingletonEmitter());

    if (singletonPlugins.length) {
        singletonPlugins.forEach(function (obj) {
            singleton.instance.registerPlugin.apply(singleton.instance, obj.args);
        });
    }

    singleton.init.apply(null, args);
    return singleton;
}

/**
 * @param {String} prop
 * @returns {Object|Boolean}
 */
function getSingletonValue(prop) {
    var single = getSingle("singleton");
    if (single) {
        return single[prop];
    }
    return false;
}

/**
 * Get a single instance by name
 * @param {String} name
 * @returns {Object|Boolean}
 */
function getSingle(name) {
    if (instances.length) {
        var match = instances.filter(function (item) {
            return item.name === name;
        });
        if (match.length) {
            return match[0];
        }
    }
    return false;
}

/**
 * Create an instance of BrowserSync
 * @param {String} [name]
 * @param {EventEmitter} [emitter]
 * @returns {{init: *, exit: (exit|exports), notify: *, reload: *, cleanup: *, emitter: (BrowserSync.events|*), use: *}}
 */
function create(name, emitter) {

    name = name || new Date().getTime();
    var browserSync = new BrowserSync(emitter || newEmitter(), name);

    var instance = {
        name:      name,
        instance:  browserSync,
        init:      require("./lib/public/init")(browserSync, name, pjson),
        exit:      require("./lib/public/exit")(browserSync),
        notify:    require("./lib/public/notify")(browserSync),
        pause:     require("./lib/public/pause")(browserSync),
        resume:    require("./lib/public/resume")(browserSync),
        reload:    require("./lib/public/reload")(emitter),
        cleanup:   browserSync.cleanup.bind(browserSync),
        use:       browserSync.registerPlugin.bind(browserSync),
        getOption: browserSync.getOption.bind(browserSync),
        emitter:   browserSync.events
    };

    Object.defineProperty(instance, "active", {
        get: function () {
            return browserSync.active;
        }
    });

    Object.defineProperty(instance, "paused", {
        get: function () {
            return browserSync.paused;
        }
    });

    instances.push(instance);

    return instance;
}

/**
 * Reset the state of the module.
 * (should only be needed for test environments)
 */
module.exports.reset = function () {
    instances.forEach(function (item) {
        item.cleanup();
    });
    instances        = [];
    singletonPlugins = [];
    singletonEmitter = false;
    singleton        = false;
    process.removeAllListeners();
};

/**
 * Get a single instance by name
 * @param {String} name
 * @returns {Object|Boolean}
 */
module.exports.get   = function (name) {
    var instance = getSingle(name);
    if (instance) {
        return instance;
    }
    throw new Error("An instance with the name {yellow:`%s`} was not found.".replace("%s", name));
};

/**
 * @type {Array}
 */
module.exports.instances = instances;

/**
 * Create an instance of BrowserSync
 * @type {create}
 */
module.exports.create    = create;
<commit_msg>don't log deprecated messages by default<commit_after>#! /usr/bin/env node
"use strict";

/**
 * @module BrowserSync
 */
var pjson         = require("./package.json");
var BrowserSync   = require("./lib/browser-sync");
var utils         = require("./lib/utils");
var events        = require("events");
var logger        = require("eazy-logger").Logger({
    useLevelPrefixes: true
});

var singleton        = false;
var singletonPlugins = [];
var instances        = [];

/**
 * @type {boolean|EventEmitter}
 */
var singletonEmitter = false;

/**
 * @method browserSync
 * @param {Object} [config] This is the main configuration for your BrowserSync instance and can contain any of the [available options]({{site.links.options}})
 *  If you do not pass a config an argument for configuration, BrowserSync will still run; but it will be in the `snippet` mode
 * @param {Function} [cb] If you pass a callback function, it will be called when BrowserSync has completed all setup tasks and is ready to use. This
 * is useful when you need to wait for information (for example: urls, port etc) or perform other tasks synchronously.
 * @returns {BrowserSync}
 */
module.exports         = initSingleton;
module.exports.init    = initSingleton;

/**
 * Register a plugin. Must implement at least a 'plugin' method that returns a
 * callable function.
 *
 * @method use
 * @param {String} name The name of the plugin
 * @param {Object} module The object to be `required`.
 * @param {Function} [cb] A callback function that will return any errors.
 */
module.exports.use     = function () {
    var args = Array.prototype.slice.call(arguments);
    singletonPlugins.push({
        args: args
    });
};

/**
 * The `reload` method will inform all browsers about changed files and will either cause the browser to refresh, or inject the files where possible.
 *
 * @method reload
 * @param {String|Array|Object} [arg] The file or files to be reloaded. For
 * details and examples of Streams support, please see the [GulpJS]({{site.links.gulp}}) examples
 * @returns {*}
 */
module.exports.reload  = noop("reload");

/**
 * Helper method for browser notifications
 *
 * @method notify
 * @param {String|HTML} msg Can be a simple message such as 'Connected' or HTML
 * @param {Number} [timeout] How long the message will remain in the browser. @since 1.3.0
 */
module.exports.notify  = noop("notify");

/**
 * This method will close any running server, stop file watching & exit the current process.
 *
 * @method exit
 */
module.exports.exit    = noop("exit");

/**
 * Method to pause file change events
 *
 * @method pause
 */
module.exports.pause   = noop("pause");

/**
 * Method to resume paused watchers
 *
 * @method resume
 */
module.exports.resume  = noop("resume");

/**
 * Add properties fo
 */
Object.defineProperties(module.exports, {
    /**
     * The internal Event Emitter used by the running BrowserSync instance (if there is one).
     * You can use this to emit your own events, such as changed files, logging etc.
     *
     * @property emitter
     */
    "emitter": {
        get: function () {
            if (!singletonEmitter) {
                singletonEmitter = newEmitter();
                return singletonEmitter;
            }
            return singletonEmitter;
        }
    },
    /**
     * A simple true/false flag that you can use to determine if there's a currently-running BrowserSync instance.
     *
     * @property active
     */
    "active": {
        get: getSingletonValue.bind(null, "active")
    },
    /**
     * A simple true/false flag to determine if the current instance is paused
     *
     * @property paused
     */
    "paused": {
        get: getSingletonValue.bind(null, "paused")
    }
});

/**
 * Event emitter factory
 * @returns {EventEmitter}
 */
function newEmitter() {
    var emitter       = new events.EventEmitter();
    emitter.setMaxListeners(20);
    return emitter;
}

/**
 * Get the singleton's emitter, or a new one.
 * @returns {EventEmitter}
 */
function getSingletonEmitter() {
    if (singletonEmitter) {
        return singletonEmitter;
    }
    singletonEmitter = newEmitter();
    return singletonEmitter;
}

/**
 * Helper to allow methods to be called on the module export
 * before there's a running instance
 * @param {String} name
 * @returns {Function}
 */
function noop(name) {
    return function () {
        var args = Array.prototype.slice.call(arguments);
        if (singleton) {
            return singleton[name].apply(singleton, args);
        } else {
            if (name === "reload" && args[0] && args[0].stream) {
                return utils.noopStream();
            }
            //deprecated(name); //todo - silent fail here or deprecated message?
        }
    };
}

/**
 * @param name
 */
function deprecated(name) {
    logger.error("This functionality will change in BrowserSync 2.0. You'll have to first call browserSync.create() before {cyan:`.%s()`", name);
}

/**
 * Create a single instance when module export is used directly via browserSync({});
 * This is mostly for back-compatibility, for also for the nicer api.
 * This will never be removed to ensure we never break user-land, but
 * we should discourage it's use.
 * @returns {*}
 */
function initSingleton() {
    var instance;
    if (instances.length) {
        instance = instances.filter(function (item) {
            return item.name === "singleton";
        });
        if (instance.length) {
            logger.error("{yellow:You tried to start BrowserSync twice!} To create multiple instances, use {cyan:browserSync.create().init()");
            return instance;
        }
    }
    var args = Array.prototype.slice.call(arguments);
    singleton = create("singleton", getSingletonEmitter());

    if (singletonPlugins.length) {
        singletonPlugins.forEach(function (obj) {
            singleton.instance.registerPlugin.apply(singleton.instance, obj.args);
        });
    }

    singleton.init.apply(null, args);
    return singleton;
}

/**
 * @param {String} prop
 * @returns {Object|Boolean}
 */
function getSingletonValue(prop) {
    var single = getSingle("singleton");
    if (single) {
        return single[prop];
    }
    return false;
}

/**
 * Get a single instance by name
 * @param {String} name
 * @returns {Object|Boolean}
 */
function getSingle(name) {
    if (instances.length) {
        var match = instances.filter(function (item) {
            return item.name === name;
        });
        if (match.length) {
            return match[0];
        }
    }
    return false;
}

/**
 * Create an instance of BrowserSync
 * @param {String} [name]
 * @param {EventEmitter} [emitter]
 * @returns {{init: *, exit: (exit|exports), notify: *, reload: *, cleanup: *, emitter: (BrowserSync.events|*), use: *}}
 */
function create(name, emitter) {

    name = name || new Date().getTime();
    var browserSync = new BrowserSync(emitter || newEmitter(), name);

    var instance = {
        name:      name,
        instance:  browserSync,
        init:      require("./lib/public/init")(browserSync, name, pjson),
        exit:      require("./lib/public/exit")(browserSync),
        notify:    require("./lib/public/notify")(browserSync),
        pause:     require("./lib/public/pause")(browserSync),
        resume:    require("./lib/public/resume")(browserSync),
        reload:    require("./lib/public/reload")(emitter),
        cleanup:   browserSync.cleanup.bind(browserSync),
        use:       browserSync.registerPlugin.bind(browserSync),
        getOption: browserSync.getOption.bind(browserSync),
        emitter:   browserSync.events
    };

    Object.defineProperty(instance, "active", {
        get: function () {
            return browserSync.active;
        }
    });

    Object.defineProperty(instance, "paused", {
        get: function () {
            return browserSync.paused;
        }
    });

    instances.push(instance);

    return instance;
}

/**
 * Reset the state of the module.
 * (should only be needed for test environments)
 */
module.exports.reset = function () {
    instances.forEach(function (item) {
        item.cleanup();
    });
    instances        = [];
    singletonPlugins = [];
    singletonEmitter = false;
    singleton        = false;
    process.removeAllListeners();
};

/**
 * Get a single instance by name
 * @param {String} name
 * @returns {Object|Boolean}
 */
module.exports.get   = function (name) {
    var instance = getSingle(name);
    if (instance) {
        return instance;
    }
    throw new Error("An instance with the name {yellow:`%s`} was not found.".replace("%s", name));
};

/**
 * @type {Array}
 */
module.exports.instances = instances;

/**
 * Create an instance of BrowserSync
 * @type {create}
 */
module.exports.create    = create;
<|endoftext|>