<commit_before>import path from 'path';
import postcss from 'postcss';
import slash from 'slash';

const defaultResolutions = [
  '(min--moz-device-pixel-ratio: 1.5)',
  '(-o-min-device-pixel-ratio: 3/2)',
  '(-webkit-min-device-pixel-ratio: 1.5)',
  '(min-device-pixel-ratio: 1.5)',
  '(min-resolution: 144dpi)',
  '(min-resolution: 1.5dppx)'
];

export default postcss.plugin('postcss-at2x', at2x);

function at2x({ identifier = '@2x' } = {}) {
  return function(root) {
    root.eachRule((rule) => {

      const mediaParent = rule.parent;

      // If retina image is within a media query then ensure each size gets
      // the retina resolutions
      let retinaMediaParams;
      if (mediaParent.name === 'media') {
        retinaMediaParams = combineMediaQuery(mediaParent.params.split(/,\s*/), defaultResolutions);
      } else {
        retinaMediaParams = defaultResolutions.join(', ');
      }

      let mediaRule = postcss.atRule({ name: 'media', params: retinaMediaParams });

      // Check for any `background-size` declarations and keep a reference to it
      // These need to be added again to prevent it being overriden by usage of
      // the `background` shorthand
      let backgroundSize;
      rule.eachDecl('background-size', decl => backgroundSize = decl);

      rule.eachDecl(/^background/, (decl) => {
        // Exit if it's a normal background declaration
        if (!backgroundWithHiResURL(decl)) {
          return;
        }

        // Construct a duplicate rule but with the image urls
        // replaced with retina versions
        let retinaRule = postcss.rule({ selector: decl.parent.selector });
        retinaRule.append(postcss.decl({
          prop: decl.prop,
          value: parseUrl(decl, identifier)
        }));

        // Add back any `background-size` value
        if (backgroundSize) {
          retinaRule.append(postcss.decl(backgroundSize));
        }

        // Add the new rules to the bottom of the stylesheet
        mediaRule.append(retinaRule);
        root.append(mediaRule);
      });
    });
  };
}

/**
 * Add all the resolutions to each media query to scope them
 */
function combineMediaQuery(queries, resolutions) {
  return queries.reduce((finalQuery, query) => {
    resolutions.forEach(resolution => finalQuery.push(`${query} and ${resolution}`));
    return finalQuery;
  }, []).join(', ');
}

function parseUrl(decl, identifier) {
  // Strip out `at-2x`
  var val = decl.value.replace(/\s+(at-2x)\s*(;|$)/, '$2');
  decl.value = val;

  var i = val.indexOf('url(');
  var url = val.slice(i + 4, val.indexOf(')', i));
  var ext = path.extname(url);

  // ignore .svg
  if (ext === '.svg') {
    return;
  }

  // @2x url value
  var retinaUrl = path.join(path.dirname(url), path.basename(url, ext) + identifier + ext);

  // path.join uses backslash on windows, which breaks in CSS. Reverse that
  retinaUrl = slash(retinaUrl);

  // Replace all instances of `url(a/path/test.png)` with `url(a/path/test@2x.png)`.
  // This preserves other values set by background such as no-repeat, color etc
  return val.replace(/url\((.*?)\)/g, 'url(' + retinaUrl + ')');
}

function backgroundWithHiResURL(decl) {
  return decl.value.indexOf('url(') !== -1 &&
         decl.value.indexOf('at-2x') !== -1;
}
<commit_msg>Move stripping of at-2x keyword into main plugin function<commit_after>import path from 'path';
import postcss from 'postcss';
import slash from 'slash';

const defaultResolutions = [
  '(min--moz-device-pixel-ratio: 1.5)',
  '(-o-min-device-pixel-ratio: 3/2)',
  '(-webkit-min-device-pixel-ratio: 1.5)',
  '(min-device-pixel-ratio: 1.5)',
  '(min-resolution: 144dpi)',
  '(min-resolution: 1.5dppx)'
];

export default postcss.plugin('postcss-at2x', at2x);

function at2x({ identifier = '@2x' } = {}) {
  return function(root) {
    root.eachRule((rule) => {

      const mediaParent = rule.parent;

      // If retina image is within a media query then ensure each size gets
      // the retina resolutions
      let retinaMediaParams;
      if (mediaParent.name === 'media') {
        retinaMediaParams = combineMediaQuery(mediaParent.params.split(/,\s*/), defaultResolutions);
      } else {
        retinaMediaParams = defaultResolutions.join(', ');
      }

      let mediaRule = postcss.atRule({ name: 'media', params: retinaMediaParams });

      // Check for any `background-size` declarations and keep a reference to it
      // These need to be added again to prevent it being overriden by usage of
      // the `background` shorthand
      let backgroundSize;
      rule.eachDecl('background-size', decl => backgroundSize = decl);

      rule.eachDecl(/^background/, (decl) => {
        // Exit if it's a normal background declaration
        if (!backgroundWithHiResURL(decl)) {
          return;
        }

        // Strip out `at-2x` from image url
        decl.value = decl.value.replace(/\s+(at-2x)\s*(;|$)/, '$2');

        // Construct a duplicate rule but with the image urls
        // replaced with retina versions
        let retinaRule = postcss.rule({ selector: decl.parent.selector });
        retinaRule.append(postcss.decl({
          prop: decl.prop,
          value: createRetinaUrl(decl.value, identifier)
        }));

        // Add back any `background-size` value
        if (backgroundSize) {
          retinaRule.append(postcss.decl(backgroundSize));
        }

        // Add the new rules to the bottom of the stylesheet
        mediaRule.append(retinaRule);
        root.append(mediaRule);
      });
    });
  };
}

/**
 * Add all the resolutions to each media query to scope them
 */
function combineMediaQuery(queries, resolutions) {
  return queries.reduce((finalQuery, query) => {
    resolutions.forEach(resolution => finalQuery.push(`${query} and ${resolution}`));
    return finalQuery;
  }, []).join(', ');
}

function createRetinaUrl(value, identifier) {
  var i = value.indexOf('url(');
  var url = value.slice(i + 4, value.indexOf(')', i));
  var ext = path.extname(url);

  // ignore .svg
  if (ext === '.svg') {
    return;
  }

  // @2x url value
  var retinaUrl = path.join(path.dirname(url), path.basename(url, ext) + identifier + ext);

  // path.join uses backslash on windows, which breaks in CSS. Reverse that
  retinaUrl = slash(retinaUrl);

  // Replace all instances of `url(a/path/test.png)` with `url(a/path/test@2x.png)`.
  // This preserves other values set by background such as no-repeat, color etc
  return value.replace(/url\((.*?)\)/g, 'url(' + retinaUrl + ')');
}

function backgroundWithHiResURL(decl) {
  return decl.value.indexOf('url(') !== -1 &&
         decl.value.indexOf('at-2x') !== -1;
}
<|endoftext|>


<commit_before>var os = require('os'),
    flatiron = require('flatiron'),
    Understudy = require('understudy').Understudy

exports.start = function (options) {
  var app = Understudy.call(flatiron.app);

  app.config.argv().file(configFile).env().defaults({
    directories: {
      tmp: __dirname + '/../tmp'
    },
    node: {
      gypdir: process.env.HOME + '/.node-gyp',
      versions: [process.version.slice(1)]
    },
    spawning: {
      platform: os.platform(),
      arch: os.arch(),
      env: {
        npm_config_production: 'true'
      },
      user: 'nobody',
      group: 'nobody'
    },
    defaults: {
      build: {
        version: '0.8.x'
      }
    }
  });

  //
  // Monitor and Repository support
  //
  app.use(require('.plugins/pluggable'));
  app.use(require('./plugins/servers'));
  app.use(require('./plugins/http'));
  require('./routes')(app, app.config.get('routes'));

  //
  // Start the application
  //
  app.init();
};<commit_msg>[api minor] Ensure that require('module-foundry') returns the flatiron app<commit_after>var os = require('os'),
    flatiron = require('flatiron'),
    Understudy = require('understudy').Understudy;

var app = module.exports = Understudy.call(flatiron.app);

app.start = function (options, callback) {
  options = options || {};
  callback = callback || function () { };

  app.config
    .argv()
    .file(options.configFile)
    .env()
    .defaults({
      directories: {
        tmp: __dirname + '/../tmp'
      },
      node: {
        gypdir: process.env.HOME + '/.node-gyp',
        versions: [process.version.slice(1)]
      },
      spawning: {
        platform: os.platform(),
        arch: os.arch(),
        env: {
          npm_config_production: 'true'
        },
        user: 'nobody',
        group: 'nobody'
      },
      defaults: {
        build: {
          version: '0.8.x'
        }
      }
    });

  //
  // Monitor and Repository support
  //
  app.use(require('./plugins/pluggable'));
  app.use(require('./plugins/servers'));
  app.use(require('./plugins/http'));
  require('./routes')(app, app.config.get('routes'));

  //
  // Start the application
  //
  app.init(callback);
};<|endoftext|>


<commit_before>const http = require('http');
const ws = require('ws');
const path = require('path');
const events = require('events');
const util = require('util');
const async = require('async');
const url = require('url');
const stream = require('stream');

function Client() {
  events.EventEmitter.call(this);

  this._socket = null;

  this._callbacks = [];
  this._counter = 0;

  this._scripts = [];
  this._console = new stream.Readable({ objectMode: true });
  this._console._read = function() { };
}

util.inherits(Client, events.EventEmitter);

Object.defineProperty(Client.prototype, 'socket', {
  get: function() {
    return this._socket;
  },
});

Object.defineProperty(Client.prototype, 'console', {
  get: function() {
    return this._console;
  },
});

Client.prototype.sendCommand = function(method, params, callback) {
  try {
    var id = this._counter++;

    this._socket.send(JSON.stringify({
      id: id,
      method: method,
      params: params
    }));
    this._callbacks[id] = callback;
  } catch (error) {
    return callback(error);
  }
};

Client.prototype.processCommand = function(message) {
  var callback = this._callbacks[message.id];

  if (callback) {
    if (message.error) {
      return callback(message.error);
    } else if (message.result) {
      return callback(null, message.result);
    } else if (message.params) {
      return callback(null, message.params);
    }
  }

  if (message.method === 'Console.messageAdded') {
    return this._console.push(message.params.message);
  }

  if (message.method === 'Debugger.scriptParsed') {
    this._scripts = this._scripts.filter(function(script) {
      return message.params.url !== script.url;
    });

    this._scripts.push(message.params);
    return this.emit('scriptParse', message.params);
  }
};

Client.prototype.attach = function attach(target) {
  if (typeof target === 'object') {
    target = target.webSocketDebuggerUrl;
  }

  var socket = ws.connect(target);
  var self = this;

  socket.on('open', function() {
    self.emit('attach');
  });

  socket.on('close', function() {
    self.emit('detatch');
  });

  socket.on('error', function(error) {
    self.emit('error', error);
  });

  socket.on('message', function(data) {
    try {
      var message = JSON.parse(data);
      self.processCommand(message);
    } catch (error) {
      self.emit('error', error);
    }
  });

  this._socket = socket;
};

Client.prototype.detatch = function() {
  if (this._socket) {
    this._socket.close();
  }
};

Client.prototype.evaluate = function evaluate(expression, callback) {
  this.sendCommand('Runtime.evaluate', {
    expression: expression,
  }, callback);
};

Client.prototype.getScripts = function scripts(callback) {
  callback(this._scripts);
};

Client.prototype.getScriptSource = function(script, callback) {
  this.sendCommand('Debugger.getScriptSource', {
    scriptId: script.scriptId,
  }, callback);
};

Client.prototype.setScriptSource = function source(script, contents, callback) {
  this.sendCommand('Debugger.setScriptSource', {
    scriptId: script.scriptId,
    scriptSource: contents
  }, callback);
};

module.exports.Client = Client;

function createClient() {
  var client = new Client();
  return client;
}

module.exports.createClient = createClient;

function get(port, host, callback) {
  var request = http.get({
    port: port,
    host: host,
    path: '/json'
  });

  request.on('response', function(response) {
    var body = '';

    response.on('data', function(chunk) {
      body += chunk;
    });

    response.on('end', function() {
      try {
        var targets = JSON.parse(body);
        return callback(null, targets);
      } catch (error) {
        return callback(error);
      }
    });
  });

  request.on('error', function(error) {
    return callback(error);
  });
};

module.exports.get = get;
<commit_msg>Emit message event from Client.prototype.sendCommand<commit_after>const http = require('http');
const ws = require('ws');
const path = require('path');
const events = require('events');
const util = require('util');
const async = require('async');
const url = require('url');
const stream = require('stream');

function Client() {
  events.EventEmitter.call(this);

  this._socket = null;

  this._callbacks = [];
  this._counter = 0;

  this._scripts = [];
  this._console = new stream.Readable({ objectMode: true });
  this._console._read = function() { };
}

util.inherits(Client, events.EventEmitter);

Object.defineProperty(Client.prototype, 'socket', {
  get: function() {
    return this._socket;
  },
});

Object.defineProperty(Client.prototype, 'console', {
  get: function() {
    return this._console;
  },
});

Client.prototype.sendCommand = function(method, params, callback) {
  try {
    var id = this._counter++;

    this._socket.send(JSON.stringify({
      id: id,
      method: method,
      params: params
    }));
    this._callbacks[id] = callback;
  } catch (error) {
    return callback(error);
  }
};

Client.prototype.processCommand = function(message) {
  if (message.id) {
    var callback = this._callbacks[message.id];

    if (callback) {
      if (message.error) {
        callback(message.error);
      } else if (message.result) {
        callback(null, message.result);
      } else if (message.params) {
        callback(null, message.params);
      }
    }
  } else {
    this.emit('message', message);
    if (message.method === 'Console.messageAdded') {
      this._console.push(message.params.message);
    }

    if (message.method === 'Debugger.scriptParsed') {
      this._scripts = this._scripts.filter(function(script) {
        return message.params.url !== script.url;
      });

      this._scripts.push(message.params);
      this.emit('scriptParse', message.params);
    }
  }
};

Client.prototype.attach = function attach(target) {
  if (typeof target === 'object') {
    target = target.webSocketDebuggerUrl;
  }

  var socket = ws.connect(target);
  var self = this;

  socket.on('open', function() {
    self.emit('attach');
  });

  socket.on('close', function() {
    self.emit('detatch');
  });

  socket.on('error', function(error) {
    self.emit('error', error);
  });

  socket.on('message', function(data) {
    try {
      var message = JSON.parse(data);
      self.processCommand(message);
    } catch (error) {
      self.emit('error', error);
    }
  });

  this._socket = socket;
};

Client.prototype.detatch = function() {
  if (this._socket) {
    this._socket.close();
  }
};

Client.prototype.evaluate = function evaluate(expression, callback) {
  this.sendCommand('Runtime.evaluate', {
    expression: expression,
  }, callback);
};

Client.prototype.getScripts = function scripts(callback) {
  callback(this._scripts);
};

Client.prototype.getScriptSource = function(script, callback) {
  this.sendCommand('Debugger.getScriptSource', {
    scriptId: script.scriptId,
  }, callback);
};

Client.prototype.setScriptSource = function source(script, contents, callback) {
  this.sendCommand('Debugger.setScriptSource', {
    scriptId: script.scriptId,
    scriptSource: contents
  }, callback);
};

module.exports.Client = Client;

function createClient() {
  var client = new Client();
  return client;
}

module.exports.createClient = createClient;

function get(port, host, callback) {
  var request = http.get({
    port: port,
    host: host,
    path: '/json'
  });

  request.on('response', function(response) {
    var body = '';

    response.on('data', function(chunk) {
      body += chunk;
    });

    response.on('end', function() {
      try {
        var targets = JSON.parse(body);
        return callback(null, targets);
      } catch (error) {
        return callback(error);
      }
    });
  });

  request.on('error', function(error) {
    return callback(error);
  });
};

module.exports.get = get;
<|endoftext|>


<commit_before>module.exports = {
  youube: require('./extractors/youtube'),
  vimeo: require('./extractors/vimeo'),
  dailymotion: require('../extractors/dailymotion')
};<commit_msg>fix the way extractors are exported from index<commit_after>var YoutubeExtactor = require('./extractors/youtube'),
  VimeoExtractor = require('./extractors/vimeo'),
  DailymotionExtractor = require('../extractors/dailymotion'),
  config = require('../config/config');

module.exports = {
  Youtube: new YoutubeExtactor(),
  Vimeo: new VimeoExtractor(config),
  Dailymotion: new DailymotionExtractor(config)
};<|endoftext|>


<commit_before>module.exports = function SocketioProtocol () {
  this.name = 'socketio';
  this.isDummy = false;
  this.io = null;
  this.context = null;

  this.init = function (config, context, isDummy) {
    if (!config) {
      /*eslint no-console: 0*/
      return console.error(new Error('plugin-socketio: A configuration parameter is required'));
    }

    if (!config.port) {
      /*eslint no-console: 0*/
      return console.error(new Error('plugin-socketio: the \'port\' attribute, with the port to listen to, is required'));
    }

    this.isDummy = isDummy;
    this.context = context;

    if (this.isDummy) {
      return this;
    }

    this.io = require('socket.io')(config.port);
    this.io.set('origins', '*:*');

    this.io.on('connection', socket => {
      this.newConnection(socket);
    });

    this.io.on('error', err => {
      /*eslint no-console: 0*/
      console.error('Unable to connect: ', err);
    });

    return this;
  };

  this.broadcast = function (channel, response) {
    if (this.isDummy) {
      return false;
    }

    this.io.to(channel).emit(channel, response);
  };

  this.joinChannel = function (channel, id) {
    if (this.isDummy) {
      return false;
    }
console.log(this.io);
    this.io.sockets.connected[id].join(channel);
  };

  this.leaveChannel = function (channel, id) {
    if (this.isDummy) {
      return false;
    }

    if (this.io.sockets.connected[id]) {
      this.io.sockets.connected[id].leave(channel);
    }
  };

  this.newConnection = function (socket) {
    if (this.isDummy) {
      return false;
    }

    this.context.getRouter().newConnection(this.name, socket.id)
      .then(connection => {
        socket.on(this.context.getRouter().routeName, data => {
          var requestObject = new this.context.RequestObject(data, {}, this.name);

          this.context.getRouter().execute(data.headers, requestObject, connection)
            .then(responseObject => {
              this.io.to(socket.id).emit(requestObject.requestId, responseObject.toJson());
            })
            .catch(error => {
              this.io.to(socket.id).emit(requestObject.requestId, error.toJson());
            });
        });

        this.io.on('disconnect', () => {
          this.context.getRouter().removeConnection(connection);
        });

        this.io.on('error', () => {
          this.context.getRouter().removeConnection(connection);
        });
      })
      .catch(err => {
        /*eslint no-console: 0*/
        console.error('Unable to declare new connection: ', err);
      });
  };

  this.protocolInterface = {
    name: this.name,
    broadcast: this.broadcast,
    joinChannel: this.joinChannel,
    leaveChannel: this.leaveChannel
  };
};
<commit_msg>added context binding<commit_after>module.exports = function SocketioProtocol () {
  this.name = 'socketio';
  this.isDummy = false;
  this.io = null;
  this.context = null;

  this.init = function (config, context, isDummy) {
    if (!config) {
      /*eslint no-console: 0*/
      return console.error(new Error('plugin-socketio: A configuration parameter is required'));
    }

    if (!config.port) {
      /*eslint no-console: 0*/
      return console.error(new Error('plugin-socketio: the \'port\' attribute, with the port to listen to, is required'));
    }

    this.isDummy = isDummy;
    this.context = context;

    if (this.isDummy) {
      return this;
    }

    this.io = require('socket.io')(config.port);
    this.io.set('origins', '*:*');

    this.io.on('connection', socket => {
      this.newConnection(socket);
    });

    this.io.on('error', err => {
      /*eslint no-console: 0*/
      console.error('Unable to connect: ', err);
    });

    return this;
  };

  this.broadcast = function (channel, response) {
    if (this.isDummy) {
      return false;
    }

    this.io.to(channel).emit(channel, response);
  };

  this.joinChannel = function (channel, id) {
    if (this.isDummy) {
      return false;
    }
console.log(this.io);
    this.io.sockets.connected[id].join(channel);
  };

  this.leaveChannel = function (channel, id) {
    if (this.isDummy) {
      return false;
    }

    if (this.io.sockets.connected[id]) {
      this.io.sockets.connected[id].leave(channel);
    }
  };

  this.newConnection = function (socket) {
    if (this.isDummy) {
      return false;
    }

    this.context.getRouter().newConnection(this.name, socket.id)
      .then(connection => {
        socket.on(this.context.getRouter().routeName, data => {
          var requestObject = new this.context.RequestObject(data, {}, this.name);

          this.context.getRouter().execute(data.headers, requestObject, connection)
            .then(responseObject => {
              this.io.to(socket.id).emit(requestObject.requestId, responseObject.toJson());
            })
            .catch(error => {
              this.io.to(socket.id).emit(requestObject.requestId, error.toJson());
            });
        });

        this.io.on('disconnect', () => {
          this.context.getRouter().removeConnection(connection);
        });

        this.io.on('error', () => {
          this.context.getRouter().removeConnection(connection);
        });
      })
      .catch(err => {
        /*eslint no-console: 0*/
        console.error('Unable to declare new connection: ', err);
      });
  };

  this.protocolInterface = {
    name: this.name,
    broadcast: this.broadcast.bind(this),
    joinChannel: this.joinChannel.bind(this),
    leaveChannel: this.leaveChannel.bind(this)
  };
};
<|endoftext|>


<commit_before>
/*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://yuilibrary.com/license/
*/

var UNKNOWN = 'UNKNOWN';
var fs = require('fs');
var path = require('path');
var read = require('read-installed');
var chalk = require('chalk');
var treeify = require('treeify');
var license = require('./license');

var flatten = function(options) {
    var moduleInfo = { licenses: UNKNOWN },
        json = options.deps,
        data = options.data,
        key = json.name + '@' + json.version,
        colorize = options.color,
        unknown = options.unknown,
        licenseData, files = [], licenseFile;

    /*istanbul ignore next*/
    if (colorize) {
        moduleInfo = { licenses: chalk.bold.red(UNKNOWN) };
        key = chalk.blue(json.name) + chalk.dim('@') + chalk.green(json.version);
    }

    // If we have processed this key already, just return the data object.
    // This was added so that we don't recurse forever if there was a circular
    // dependency in the dependency tree.
    /*istanbul ignore next*/
    if (data[key]) {
        return data;
    }

    data[key] = moduleInfo;

    if (json.repository) {
        /*istanbul ignore else*/
        if (typeof json.repository === 'object' && typeof json.repository.url === 'string') {
            moduleInfo.repository = json.repository.url.replace('git+ssh://git@', 'git://').replace('.git', '');
            moduleInfo.repository = moduleInfo.repository.replace('git://github.com', 'https://github.com').replace('.git', '');
            moduleInfo.repository = moduleInfo.repository.replace('git@github.com:', 'https://github.com/').replace('.git', '');
        }
    }
    if (json.url) {
        /*istanbul ignore next*/
        if (typeof json.url === 'object') {
            moduleInfo.url = json.url.web;
        }
    }

    /*istanbul ignore next*/
    if (unknown) {
        moduleInfo.dependencyPath = json.path;
    }

    /*istanbul ignore next*/
    if (options.customFormat) {
        Object.keys(options.customFormat).forEach(function forEachCallback(item) {
            if (json[item]) {
                //For now, we only support strings, not JSON objects
                if (typeof json[item] === 'string') {
                    moduleInfo[item] = json[item];
                }
            } else {
                moduleInfo[item] = options.customFormat[item];
            }
        });
    }

    licenseData = json.license || json.licenses || undefined;
    if (licenseData) {
        /*istanbul ignore else*/
        if (Array.isArray(licenseData) && licenseData.length > 0) {
            moduleInfo.licenses = licenseData.map(function(license){
                /*istanbul ignore else*/
                if (typeof license === 'object') {
                    return license.type;
                } else if (typeof license === 'string') {
                    return license;
                }
            });
        } else if (typeof licenseData === 'object' && licenseData.type) {
            moduleInfo.licenses = licenseData.type;
        } else if (typeof licenseData === 'string') {
            moduleInfo.licenses = licenseData;
        }
    } else if (license(json.readme)) {
        moduleInfo.licenses = license(json.readme);
    }

    /*istanbul ignore else*/
    if (json.path && fs.existsSync(json.path)) {
        files = fs.readdirSync(json.path).filter(function(filename) {
            filename = filename.toUpperCase();
            return filename.indexOf('LICENSE') > -1 || filename.indexOf('LICENCE') > -1 ;
        });
    }

    files.forEach(function(filename) {
        licenseFile = path.join(json.path, filename);
        // Checking that the file is in fact a normal file and not a directory for example.
        /*istanbul ignore else*/
        if (fs.lstatSync(licenseFile).isFile()) {
            if (!moduleInfo.licenses || moduleInfo.licenses.indexOf(UNKNOWN) > -1) {
                //Only re-check the license if we didn't get it from elsewhere
                moduleInfo.licenses = license(fs.readFileSync(licenseFile, {encoding: 'utf8'}));
            }
            moduleInfo.licenseFile = licenseFile;
        }
    });

    if (Array.isArray(moduleInfo.licenses)) {
        /*istanbul ignore else*/
        if (moduleInfo.licenses.length === 1) {
            moduleInfo.licenses = moduleInfo.licenses[0];
        }
    }

    /*istanbul ignore else*/
    if (json.dependencies) {
        Object.keys(json.dependencies).forEach(function(name) {
            var childDependency = json.dependencies[name],
            dependencyId = childDependency.name + '@' + childDependency.version;
            if (options.filter && options.filter(name, childDependency)) {
                return;
            }
            if (data[dependencyId]) { // already exists
                return;
            }
            data = flatten({
                deps: childDependency,
                data: data,
                color: colorize,
                unknown: unknown,
                customFormat: options.customFormat
            });
        });
    }
    return data;
};

exports.init = function(options, callback) {
    console.error('scanning' , options.start);

    if (options.customPath) {
        options.customFormat = this.parseJson(options.customPath);
    }

    read(options.start, { dev: true }, function(err, json) {
        var data = flatten({
                deps: json,
                data: {},
                color: options.color,
                unknown: options.unknown,
                customFormat: options.customFormat,
                filter: options.filter
            }),
            colorize = options.color,
            sorted = {},
            filtered = {},
            exclude = options.exclude && options.exclude.replace(/^\s+|\s+$/g, '').split(/\s*,\s*/);
        Object.keys(data).sort().forEach(function(item) {
            if (options.unknown) {
                if (data[item].licenses && data[item].licenses !== UNKNOWN) {
                    if (data[item].licenses.indexOf('*') > -1) {
                        /*istanbul ignore if*/
                        if (colorize) {
                            data[item].licenses = chalk.bold.red(UNKNOWN);
                        } else {
                            data[item].licenses = UNKNOWN;
                        }
                    }
                }
            }
            /*istanbul ignore else*/
            if (data[item]) {
                if (options.onlyunknown) {
                    if (data[item].licenses.indexOf('*') > -1 ||
                        data[item].licenses.indexOf('UNKNOWN') > -1) {
                        sorted[item] = data[item];
                    }
                } else {
                    sorted[item] = data[item];
                }
            }
        });
        if (exclude) {
            Object.keys(sorted).forEach(function(item) {
                if (!(sorted[item].licenses && exclude.indexOf(sorted[item].licenses) !== -1)) {
                    filtered[item] = sorted[item];
                }
            });
        } else {
            filtered = sorted;
        }
        callback(filtered);
    });
};

/*istanbul ignore next*/
exports.print = function(sorted) {
    console.log(exports.asTree(sorted));
};

exports.asTree = function(sorted) {
    return treeify.asTree(sorted, true);
};

exports.asCSV = function(sorted, customFormat) {
    var text = [ ], textArr = [ ], lineArr = [ ];

    if (customFormat && Object.keys(customFormat).length > 0) {
        textArr = [ ];
        textArr.push('"module name"');

        Object.keys(customFormat).forEach(function forEachCallback(item) {
            textArr.push('"' + item + '"');
        });

        text.push(textArr.join(','));
    } else {
        text.push(['"module name"','"license"','"repository"'].join(','));
    }

    Object.keys(sorted).forEach(function(key) {
        var module = sorted[key],
        line = '';
        lineArr = [ ];

        //Grab the custom keys from the custom format
        if (customFormat && Object.keys(customFormat).length > 0) {
            lineArr.push('"' + key + '"');
            Object.keys(customFormat).forEach(function forEachCallback(item) {
                lineArr.push('"' + module[item] + '"');
            });
            line = lineArr.join(',');
        } else {
            line = [
                '"' + key + '"',
                '"' + (module.licenses || '') + '"',
                '"' + (module.repository || '') + '"'
            ].join(',');
        }
        text.push(line);
    });

    return text.join('\n');
};

/**
* Exports data as markdown (*.md) file which has it's own syntax.
* @method
* @param  {JSON} sorted       The sorted JSON data from all packages.
* @param  {JSON} customFormat The custom format with information about the needed keys.
* @return {String}            The returning plain text.
*/
exports.asMarkDown = function(sorted, customFormat) {

    var text = [];
    if (customFormat && Object.keys(customFormat).length > 0) {

        Object.keys(sorted).forEach(function sortedCallback(sortedItem) {

            text.push(' - **[' + sortedItem + '](' + sorted[sortedItem].repository + ')**');
            Object.keys(customFormat).forEach(function customCallback(customItem) {

                text.push('    - ' +  customItem + ': ' + sorted[sortedItem][customItem]);
            });
        });

        text = text.join('\n');
    } else {

        Object.keys(sorted).forEach(function(key) {

            var module = sorted[key];
            text.push('[' + key + '](' + module.repository + ') - ' + module.licenses);
        });

        text = text.join('\n');
    }

    return text;
};

/*istanbul ignore next*/
exports.parseJson = function(jsonPath) {
    if (typeof jsonPath !== 'string') {
        return new Error('did not specify a path');
    }

    var jsonFileContents = '';
    var result = { };

    try {
        jsonFileContents = fs.readFileSync(jsonPath, {encoding: 'utf8'});
        result = JSON.parse(jsonFileContents);
    } catch (err) {
        result = err;
    } finally {
      return result;
    }
};
<commit_msg>Remove unused filter option (never used)<commit_after>
/*
Copyright (c) 2013, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://yuilibrary.com/license/
*/

var UNKNOWN = 'UNKNOWN';
var fs = require('fs');
var path = require('path');
var read = require('read-installed');
var chalk = require('chalk');
var treeify = require('treeify');
var license = require('./license');

var flatten = function(options) {
    var moduleInfo = { licenses: UNKNOWN },
        json = options.deps,
        data = options.data,
        key = json.name + '@' + json.version,
        colorize = options.color,
        unknown = options.unknown,
        licenseData, files = [], licenseFile;

    /*istanbul ignore next*/
    if (colorize) {
        moduleInfo = { licenses: chalk.bold.red(UNKNOWN) };
        key = chalk.blue(json.name) + chalk.dim('@') + chalk.green(json.version);
    }

    // If we have processed this key already, just return the data object.
    // This was added so that we don't recurse forever if there was a circular
    // dependency in the dependency tree.
    /*istanbul ignore next*/
    if (data[key]) {
        return data;
    }

    data[key] = moduleInfo;

    if (json.repository) {
        /*istanbul ignore else*/
        if (typeof json.repository === 'object' && typeof json.repository.url === 'string') {
            moduleInfo.repository = json.repository.url.replace('git+ssh://git@', 'git://').replace('.git', '');
            moduleInfo.repository = moduleInfo.repository.replace('git://github.com', 'https://github.com').replace('.git', '');
            moduleInfo.repository = moduleInfo.repository.replace('git@github.com:', 'https://github.com/').replace('.git', '');
        }
    }
    if (json.url) {
        /*istanbul ignore next*/
        if (typeof json.url === 'object') {
            moduleInfo.url = json.url.web;
        }
    }

    /*istanbul ignore next*/
    if (unknown) {
        moduleInfo.dependencyPath = json.path;
    }

    /*istanbul ignore next*/
    if (options.customFormat) {
        Object.keys(options.customFormat).forEach(function forEachCallback(item) {
            if (json[item]) {
                //For now, we only support strings, not JSON objects
                if (typeof json[item] === 'string') {
                    moduleInfo[item] = json[item];
                }
            } else {
                moduleInfo[item] = options.customFormat[item];
            }
        });
    }

    licenseData = json.license || json.licenses || undefined;
    if (licenseData) {
        /*istanbul ignore else*/
        if (Array.isArray(licenseData) && licenseData.length > 0) {
            moduleInfo.licenses = licenseData.map(function(license){
                /*istanbul ignore else*/
                if (typeof license === 'object') {
                    return license.type;
                } else if (typeof license === 'string') {
                    return license;
                }
            });
        } else if (typeof licenseData === 'object' && licenseData.type) {
            moduleInfo.licenses = licenseData.type;
        } else if (typeof licenseData === 'string') {
            moduleInfo.licenses = licenseData;
        }
    } else if (license(json.readme)) {
        moduleInfo.licenses = license(json.readme);
    }

    /*istanbul ignore else*/
    if (json.path && fs.existsSync(json.path)) {
        files = fs.readdirSync(json.path).filter(function(filename) {
            filename = filename.toUpperCase();
            return filename.indexOf('LICENSE') > -1 || filename.indexOf('LICENCE') > -1 ;
        });
    }

    files.forEach(function(filename) {
        licenseFile = path.join(json.path, filename);
        // Checking that the file is in fact a normal file and not a directory for example.
        /*istanbul ignore else*/
        if (fs.lstatSync(licenseFile).isFile()) {
            if (!moduleInfo.licenses || moduleInfo.licenses.indexOf(UNKNOWN) > -1) {
                //Only re-check the license if we didn't get it from elsewhere
                moduleInfo.licenses = license(fs.readFileSync(licenseFile, {encoding: 'utf8'}));
            }
            moduleInfo.licenseFile = licenseFile;
        }
    });

    if (Array.isArray(moduleInfo.licenses)) {
        /*istanbul ignore else*/
        if (moduleInfo.licenses.length === 1) {
            moduleInfo.licenses = moduleInfo.licenses[0];
        }
    }

    /*istanbul ignore else*/
    if (json.dependencies) {
        Object.keys(json.dependencies).forEach(function(name) {
            var childDependency = json.dependencies[name],
            dependencyId = childDependency.name + '@' + childDependency.version;
            if (data[dependencyId]) { // already exists
                return;
            }
            data = flatten({
                deps: childDependency,
                data: data,
                color: colorize,
                unknown: unknown,
                customFormat: options.customFormat
            });
        });
    }
    return data;
};

exports.init = function(options, callback) {
    console.error('scanning' , options.start);

    if (options.customPath) {
        options.customFormat = this.parseJson(options.customPath);
    }

    read(options.start, { dev: true }, function(err, json) {
        var data = flatten({
                deps: json,
                data: {},
                color: options.color,
                unknown: options.unknown,
                customFormat: options.customFormat
            }),

            colorize = options.color,
            sorted = {},
            filtered = {},
            exclude = options.exclude && options.exclude.replace(/^\s+|\s+$/g, '').split(/\s*,\s*/);
        Object.keys(data).sort().forEach(function(item) {
            if (options.unknown) {
                if (data[item].licenses && data[item].licenses !== UNKNOWN) {
                    if (data[item].licenses.indexOf('*') > -1) {
                        /*istanbul ignore if*/
                        if (colorize) {
                            data[item].licenses = chalk.bold.red(UNKNOWN);
                        } else {
                            data[item].licenses = UNKNOWN;
                        }
                    }
                }
            }
            /*istanbul ignore else*/
            if (data[item]) {
                if (options.onlyunknown) {
                    if (data[item].licenses.indexOf('*') > -1 ||
                        data[item].licenses.indexOf('UNKNOWN') > -1) {
                        sorted[item] = data[item];
                    }
                } else {
                    sorted[item] = data[item];
                }
            }
        });
        if (exclude) {
            Object.keys(sorted).forEach(function(item) {
                if (!(sorted[item].licenses && exclude.indexOf(sorted[item].licenses) !== -1)) {
                    filtered[item] = sorted[item];
                }
            });
        } else {
            filtered = sorted;
        }
        callback(filtered);
    });
};

/*istanbul ignore next*/
exports.print = function(sorted) {
    console.log(exports.asTree(sorted));
};

exports.asTree = function(sorted) {
    return treeify.asTree(sorted, true);
};

exports.asCSV = function(sorted, customFormat) {
    var text = [ ], textArr = [ ], lineArr = [ ];

    if (customFormat && Object.keys(customFormat).length > 0) {
        textArr = [ ];
        textArr.push('"module name"');

        Object.keys(customFormat).forEach(function forEachCallback(item) {
            textArr.push('"' + item + '"');
        });

        text.push(textArr.join(','));
    } else {
        text.push(['"module name"','"license"','"repository"'].join(','));
    }

    Object.keys(sorted).forEach(function(key) {
        var module = sorted[key],
        line = '';
        lineArr = [ ];

        //Grab the custom keys from the custom format
        if (customFormat && Object.keys(customFormat).length > 0) {
            lineArr.push('"' + key + '"');
            Object.keys(customFormat).forEach(function forEachCallback(item) {
                lineArr.push('"' + module[item] + '"');
            });
            line = lineArr.join(',');
        } else {
            line = [
                '"' + key + '"',
                '"' + (module.licenses || '') + '"',
                '"' + (module.repository || '') + '"'
            ].join(',');
        }
        text.push(line);
    });

    return text.join('\n');
};

/**
* Exports data as markdown (*.md) file which has it's own syntax.
* @method
* @param  {JSON} sorted       The sorted JSON data from all packages.
* @param  {JSON} customFormat The custom format with information about the needed keys.
* @return {String}            The returning plain text.
*/
exports.asMarkDown = function(sorted, customFormat) {

    var text = [];
    if (customFormat && Object.keys(customFormat).length > 0) {

        Object.keys(sorted).forEach(function sortedCallback(sortedItem) {

            text.push(' - **[' + sortedItem + '](' + sorted[sortedItem].repository + ')**');
            Object.keys(customFormat).forEach(function customCallback(customItem) {

                text.push('    - ' +  customItem + ': ' + sorted[sortedItem][customItem]);
            });
        });

        text = text.join('\n');
    } else {

        Object.keys(sorted).forEach(function(key) {

            var module = sorted[key];
            text.push('[' + key + '](' + module.repository + ') - ' + module.licenses);
        });

        text = text.join('\n');
    }

    return text;
};

/*istanbul ignore next*/
exports.parseJson = function(jsonPath) {
    if (typeof jsonPath !== 'string') {
        return new Error('did not specify a path');
    }

    var jsonFileContents = '';
    var result = { };

    try {
        jsonFileContents = fs.readFileSync(jsonPath, {encoding: 'utf8'});
        result = JSON.parse(jsonFileContents);
    } catch (err) {
        result = err;
    } finally {
      return result;
    }
};
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var afinn = require(__dirname + '/AFINN.json');
var stop = require(__dirname + '/stopwords.json');

var tokenized = function(text) {
  var cleanedText = text.replace(/[^\w\s]/gi, '').toLowerCase();
  return cleanedText.split(/\s+/);
};

var tokens = tokenized;
var words = [];
var vNegTerms = [];
var negTerms = [];
var posTerms = [];
var vPosTerms = [];
var sentimentWords = [];
var sentimentValue = 0;

for(var i = 0; tokens.length; i++);
  if(!stopWords.contains(tokens[i])) {
    sentimentWords.push(tokens[i])
  };

 for(var i = 0; sentimentWords.length; i++);
  if(afinn.contains(sentimentWords[i])) {
    sentimentValue += afinn[sentimentWords[i]];
    if(afinn[sentimentWords[i]] == -5 || -4 ) {
      vNegTerms.push();
    }
    if(afinn[sentimentWords[i]] == -3 || -2 || -1) {
      negTerms.push();
    }
    if(afinn[sentimentWords[i]] == 3 || 2 || 1) {
      posTerms.push();
    }
    if(afinn[sentimentWords[i]] == 4 || 5) {
      vPosTerms.push();
    }
  };
  console.log(vNegTerms[], negTerms[], posTerms[], vPosTerms[]);

<commit_msg>updates index<commit_after>
var fs = require('fs');
var stopWords = fs.readFileSync(__dirname + '/stopwords.json');
var afinn = fs.readFileSync(__dirname + '/AFINN.json');

var tokenized = function(text) {
  var cleanedText = text.replace(/[^\w\s]/gi, '').toLowerCase();
  return cleanedText.split(/\s+/);
};

var tokens = tokenized;
var words = [];
var vNegTerms = [];
var negTerms = [];
var posTerms = [];
var vPosTerms = [];
var sentimentWords = [];
var sentimentValue = 0;

for(var i = 0; tokens.length; i++);
  if(!stopWords.contains(tokens[i])) {
    sentimentWords.push(tokens[i]);
  }

 for(var i = 0; sentimentWords.length; i++);
  if(afinn.contains(sentimentWords[i])) {
    sentimentValue += afinn[sentimentWords[i]];
    if(afinn[sentimentWords[i]] == -5 || -4 ) {
      vNegTerms.push();
    }
    if(afinn[sentimentWords[i]] == -3 || -2 || -1) {
      negTerms.push();
    }
    if(afinn[sentimentWords[i]] == 3 || 2 || 1) {
      posTerms.push();
    }
    if(afinn[sentimentWords[i]] == 4 || 5) {
      vPosTerms.push();
    }
  }
  console.log(vNegTerms, negTerms, posTerms, vPosTerms);

<|endoftext|>


<commit_before>'use strict';

(function () {

  /**
   * Get random value from an array or generate min random number between to number
   * @param min (Number|Array) Min random integer or an array where to pick min value
   * @param max (Number) Max random integer
   * @param multiply (Number) number to multiply the result
   *
   * @example
   *
   * random(1,2) => 1 or 2
   * random('cerise','banane','poire','pomme']) => cerise, or banane or poire, etc....
   * random(10, 250, 1000) => 10000, 15000, 20000, ... 100000, 250000
   */
  function random(min, max, multiply) {
    var num;
    if (min instanceof Array) {
      num = Math.round(Math.random() * (min.length - 1));
      return min[num];
    }
    return (Math.round(Math.random() * (max - min)) + min) * (multiply || 1);
  }

  /**
   * Generate an array with values by ratio.
   * @name byRatio
   * @param source
   * @returns {Array}
   *
   * @example
   *   byRatio({
*      man: 3,
*      woman: 7,
*   });
   *
   *   => ['man','man','man','woman','woman','woman','woman','woman','woman','woman']
   *
   *   byRatio({
*      1: 3,
*      2: 2,
*      3: 4
*   });
   *
   *   => [1,1,1,2,2,3,3,3,3]
   */
  function ratioArray(source) {
    var newArray = [];
    var key;
    for (key in source) {
      /* istanbul ignore else */
      if (source.hasOwnProperty(key)) {
        newArray = newArray.concat(new Array(source[key] + 1).join(',' + key).split(',').slice(1));
      }
    }
    return newArray;
  }

  var byRatioStore = {};

  /**
   * Return value by ratio
   * @param id
   * @param values
   * @returns {*}
   *
   * @example
   *
   */
  function byRatio(id, values) {
    if (!byRatioStore[id]) {
      byRatioStore[id] = ratioArray(values);
    }
    return random(byRatioStore[id]);
  }

  /* eslint-disable */
  function fy(a, b, c, d) {// array,placeholder,placeholder,placeholder
    c = a.length;
    while (c)b = Math.random() * c-- | 0, d = a[c], a[c] = a[b], a[b] = d; // eslint ignore:line
  }

  /* eslint-enable */

  /**
   * Get some values into
   * @param {Array} array - array of data
   * @param {Number} [numOfElementsToTake] - Number of elements to take in the array, if no number is given, the number of element is random
   * @returns {Array} - Array of values taken into the array. The values are unique.
   */
  function randomArray(array, numOfElementsToTake) {
    var arrayOfNumbers = [];
    var i;
    var list;

    numOfElementsToTake = numOfElementsToTake || random(1, array.length);
    for (i = 0; i < array.length; i++) {
      arrayOfNumbers.push(i);
    }
    fy(arrayOfNumbers);
    list = arrayOfNumbers.slice(0, numOfElementsToTake);
    return list.map(function (num) {
      return array[num];
    });
  }

  var randomValues = {
    random: random,
    ratioArray: ratioArray,
    byRatio: byRatio,
    randomArray: randomArray
  };

  if (typeof module != 'undefined' && module.exports) {
    module.exports = randomValues;
  } else {
    window.randomValues = randomValues;
  }
})();
<commit_msg>add / fix code coverage<commit_after>'use strict';

(function () {

  /**
   * Get random value from an array or generate min random number between to number
   * @param min (Number|Array) Min random integer or an array where to pick min value
   * @param max (Number) Max random integer
   * @param multiply (Number) number to multiply the result
   *
   * @example
   *
   * random(1,2) => 1 or 2
   * random('cerise','banane','poire','pomme']) => cerise, or banane or poire, etc....
   * random(10, 250, 1000) => 10000, 15000, 20000, ... 100000, 250000
   */
  function random(min, max, multiply) {
    var num;
    if (min instanceof Array) {
      num = Math.round(Math.random() * (min.length - 1));
      return min[num];
    }
    return (Math.round(Math.random() * (max - min)) + min) * (multiply || 1);
  }

  /**
   * Generate an array with values by ratio.
   * @name byRatio
   * @param source
   * @returns {Array}
   *
   * @example
   *   byRatio({
*      man: 3,
*      woman: 7,
*   });
   *
   *   => ['man','man','man','woman','woman','woman','woman','woman','woman','woman']
   *
   *   byRatio({
*      1: 3,
*      2: 2,
*      3: 4
*   });
   *
   *   => [1,1,1,2,2,3,3,3,3]
   */
  function ratioArray(source) {
    var newArray = [];
    var key;
    for (key in source) {
      /* istanbul ignore else */
      if (source.hasOwnProperty(key)) {
        newArray = newArray.concat(new Array(source[key] + 1).join(',' + key).split(',').slice(1));
      }
    }
    return newArray;
  }

  var byRatioStore = {};

  /**
   * Return value by ratio
   * @param id
   * @param values
   * @returns {*}
   *
   * @example
   *
   */
  function byRatio(id, values) {
    if (!byRatioStore[id]) {
      byRatioStore[id] = ratioArray(values);
    }
    return random(byRatioStore[id]);
  }

  /* eslint-disable */
  function fy(a, b, c, d) {// array,placeholder,placeholder,placeholder
    c = a.length;
    while (c)b = Math.random() * c-- | 0, d = a[c], a[c] = a[b], a[b] = d; // eslint ignore:line
  }

  /* eslint-enable */

  /**
   * Get some values into
   * @param {Array} array - array of data
   * @param {Number} [numOfElementsToTake] - Number of elements to take in the array, if no number is given, the number of element is random
   * @returns {Array} - Array of values taken into the array. The values are unique.
   */
  function randomArray(array, numOfElementsToTake) {
    var arrayOfNumbers = [];
    var i;
    var list;

    numOfElementsToTake = numOfElementsToTake || random(1, array.length);
    for (i = 0; i < array.length; i++) {
      arrayOfNumbers.push(i);
    }
    fy(arrayOfNumbers);
    list = arrayOfNumbers.slice(0, numOfElementsToTake);
    return list.map(function (num) {
      return array[num];
    });
  }

  var randomValues = {
    random: random,
    ratioArray: ratioArray,
    byRatio: byRatio,
    randomArray: randomArray
  };

  /* istanbul ignore else */
  if (typeof module != 'undefined' && module.exports) {
    module.exports = randomValues;
  } else {
    window.randomValues = randomValues;
  }
})();
<|endoftext|>


<commit_before>module.exports = {
  Button: require('./button'),
  css: require('styled-components').css,
  Icon: require('./icon'),
  IconDefinitions: require('./icon').definitions,
  injectGlobal: require('styled-components').injectGlobal,
  keyframes: require('styled-components').keyframes,
  Link: require('./link'),
  MainHeader: require('./main-header'),
  MainNavigation: require('./main-navigation'),
  NavigationItem: require('./main-navigation'),
  NavigationToolbar: require('./navigation-toolbar'),
  NavigationTree: require('./navigation-tree'),
  ServerStyleSheet: require('styled-components').ServerStyleSheet,
  styled: require('styled-components').default,
  StyleSheetManager: require('styled-components').StyleSheetManager,
  Symbol: require('./icon').Symbol,
  ThemeProvider: require('styled-components').ThemeProvider,
  themes: require('./themes')
};
<commit_msg>feat: expose network<commit_after>module.exports = {
  Button: require('./button'),
  css: require('styled-components').css,
  Icon: require('./icon'),
  IconDefinitions: require('./icon').definitions,
  injectGlobal: require('styled-components').injectGlobal,
  keyframes: require('styled-components').keyframes,
  Link: require('./link'),
  MainHeader: require('./main-header'),
  MainNavigation: require('./main-navigation'),
  NavigationItem: require('./main-navigation'),
  NavigationToolbar: require('./navigation-toolbar'),
  NavigationTree: require('./navigation-tree'),
  Network: require('./network'),
  ServerStyleSheet: require('styled-components').ServerStyleSheet,
  styled: require('styled-components').default,
  StyleSheetManager: require('styled-components').StyleSheetManager,
  Symbol: require('./icon').Symbol,
  ThemeProvider: require('styled-components').ThemeProvider,
  themes: require('./themes')
};
<|endoftext|>


<commit_before>/*jslint indent: 2*/
/*global require: true, module: true*/

(function () {

  'use strict';

  var defaults = {
    origin: '*',
    methods: 'GET,HEAD,PUT,POST,DELETE'
  };

  function configureOrigin(options, req) {
    var origin = options.origin;
    if (origin === true) {
      origin = req.headers['origin'];
    } else if (!origin) {
      origin = '*';
    }
    return {
      key: 'Access-Control-Allow-Origin',
      value: origin
    };
  }

  function configureMethods(options) {
    var methods = options.methods || defaults.methods;
    if (methods.join) {
      methods = options.methods.join(','); // .methods is an array, so turn it into a string
    }
    return {
      key: 'Access-Control-Allow-Methods',
      value: methods
    };
  }

  function configureCredentials(options) {
    if (options.credentials === true) {
      return {
        key: 'Access-Control-Allow-Credentials',
        value: 'true'
      };
    }
    return null;
  }

  function configureHeaders(options, req) {
    var headers = options.headers;
    if (!headers) {
      headers = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers
    } else if (headers.join) {
      headers = headers.join(','); // .headers is an array, so turn it into a string
    }
    if (headers && headers.length) {
      return {
        key: 'Access-Control-Allow-Headers',
        value: headers
      };
    }
    return null;
  }

  function configureMaxAge(options) {
    var maxAge = options.maxAge && options.maxAge.toString();
    if (maxAge && maxAge.length) {
      return {
        key: 'Access-Control-Allow-Max-Age',
        value: maxAge
      };
    }
    return null;
  }

  function cors(options, req, res, next) {
    var headers = [],
      applyHeaders = function (headers, res) {
        headers.forEach(function (header) {
          if (header && header.value) {
            res.setHeader(header.key, header.value);
          }
        });
      };

    if (req.method === 'OPTIONS') {
      headers.push(configureOrigin(options, req));
      headers.push(configureCredentials(options, req));
      headers.push(configureMethods(options, req));
      headers.push(configureHeaders(options, req));
      headers.push(configureMaxAge(options, req));
      applyHeaders(headers, res);
      res.statusCode = 204;
      res.end();
    } else {
      headers.push(configureOrigin(options, req));
      headers.push(configureCredentials(options, req));
      applyHeaders(headers, res);
      next();
    }
  }

  function middlewareWrapper(o) {
    // if no options were passed in, use the defaults
    if (!o) {
      o = {};
    }
    if (o.origin === undefined) {
      o.origin = defaults.origin;
    }
    if (o.methods === undefined) {
      o.methods = defaults.methods;
    }

    // if options are static (either via defaults or custom options passed in), wrap in a function
    var optionsCallback = null;
    if (typeof o === 'function') {
      optionsCallback = o;
    } else {
      /*jslint unparam: true*/ // `req` is part of the signature, but isn't used for this stub
      optionsCallback = function (req, cb) {
        cb(null, o);
      };
      /*jslint unparam: false*/
    }

    return function (req, res, next) {
      req.pause(); // make sure downstream middleware don't miss any data events
      optionsCallback(req, function (err, options) {
        req.resume();
        if (err) {
          next(err);
        } else {
          var originCallback = null;
          if (options.origin && typeof options.origin === 'function') {
            originCallback = options.origin;
          } else if (options.origin) {
            /*jslint unparam: true*/ // `origin` is part of the signature, but isn't used for this stub
            originCallback = function (origin, cb) {
              cb(null, options.origin);
            };
            /*jslint unparam: false*/
          }

          if (originCallback) {
            req.pause(); // make sure downstream middleware don't miss any data events
            originCallback(req.headers['origin'], function (err, origin) {
              req.resume();
              if (err || !origin) {
                next(err);
              } else {
                options.origin = origin;
                cors(options, req, res, next);
              }
            });
          } else {
            next();
          }
        }
      });
    };
  }

  // can pass either an options hash, an options delegate, or nothing
  module.exports = middlewareWrapper;

}());

<commit_msg>praying at the altar of JSLint<commit_after>/*jslint indent: 2*/
/*global require: true, module: true*/

(function () {

  'use strict';

  var defaults = {
    origin: '*',
    methods: 'GET,HEAD,PUT,POST,DELETE'
  };

  function configureOrigin(options, req) {
    var origin = options.origin;
    if (origin === true) {
      origin = req.headers.origin;
    } else if (!origin) {
      origin = '*';
    }
    return {
      key: 'Access-Control-Allow-Origin',
      value: origin
    };
  }

  function configureMethods(options) {
    var methods = options.methods || defaults.methods;
    if (methods.join) {
      methods = options.methods.join(','); // .methods is an array, so turn it into a string
    }
    return {
      key: 'Access-Control-Allow-Methods',
      value: methods
    };
  }

  function configureCredentials(options) {
    if (options.credentials === true) {
      return {
        key: 'Access-Control-Allow-Credentials',
        value: 'true'
      };
    }
    return null;
  }

  function configureHeaders(options, req) {
    var headers = options.headers;
    if (!headers) {
      headers = req.headers['access-control-request-headers']; // .headers wasn't specified, so reflect the request headers
    } else if (headers.join) {
      headers = headers.join(','); // .headers is an array, so turn it into a string
    }
    if (headers && headers.length) {
      return {
        key: 'Access-Control-Allow-Headers',
        value: headers
      };
    }
    return null;
  }

  function configureMaxAge(options) {
    var maxAge = options.maxAge && options.maxAge.toString();
    if (maxAge && maxAge.length) {
      return {
        key: 'Access-Control-Allow-Max-Age',
        value: maxAge
      };
    }
    return null;
  }

  function cors(options, req, res, next) {
    var headers = [],
      applyHeaders = function (headers, res) {
        headers.forEach(function (header) {
          if (header && header.value) {
            res.setHeader(header.key, header.value);
          }
        });
      };

    if (req.method === 'OPTIONS') {
      headers.push(configureOrigin(options, req));
      headers.push(configureCredentials(options, req));
      headers.push(configureMethods(options, req));
      headers.push(configureHeaders(options, req));
      headers.push(configureMaxAge(options, req));
      applyHeaders(headers, res);
      res.statusCode = 204;
      res.end();
    } else {
      headers.push(configureOrigin(options, req));
      headers.push(configureCredentials(options, req));
      applyHeaders(headers, res);
      next();
    }
  }

  function middlewareWrapper(o) {
    // if no options were passed in, use the defaults
    if (!o) {
      o = {};
    }
    if (o.origin === undefined) {
      o.origin = defaults.origin;
    }
    if (o.methods === undefined) {
      o.methods = defaults.methods;
    }

    // if options are static (either via defaults or custom options passed in), wrap in a function
    var optionsCallback = null;
    if (typeof o === 'function') {
      optionsCallback = o;
    } else {
      /*jslint unparam: true*/ // `req` is part of the signature, but isn't used for this stub
      optionsCallback = function (req, cb) {
        cb(null, o);
      };
      /*jslint unparam: false*/
    }

    return function (req, res, next) {
      req.pause(); // make sure downstream middleware don't miss any data events
      optionsCallback(req, function (err, options) {
        req.resume();
        if (err) {
          next(err);
        } else {
          var originCallback = null;
          if (options.origin && typeof options.origin === 'function') {
            originCallback = options.origin;
          } else if (options.origin) {
            /*jslint unparam: true*/ // `origin` is part of the signature, but isn't used for this stub
            originCallback = function (origin, cb) {
              cb(null, options.origin);
            };
            /*jslint unparam: false*/
          }

          if (originCallback) {
            req.pause(); // make sure downstream middleware don't miss any data events
            originCallback(req.headers.origin, function (err, origin) {
              req.resume();
              if (err || !origin) {
                next(err);
              } else {
                options.origin = origin;
                cors(options, req, res, next);
              }
            });
          } else {
            next();
          }
        }
      });
    };
  }

  // can pass either an options hash, an options delegate, or nothing
  module.exports = middlewareWrapper;

}());

<|endoftext|>


<commit_before>export default class MappingShader {
  static directionToEquirectangularUV() {
    return `
      vec2 directionToEquirectangularUV(vec3 direction) {
        float u = atan(-direction.z, direction.x) * 0.15915494309189535 + .5;
        float v = asin(clamp(direction.y, -1., 1.)) * 0.3183098861837907 + .5;
        return vec2(u, v);
      }
    `;
  }
}
<commit_msg>MappingShader: fix UVs<commit_after>export default class MappingShader {
  static directionToEquirectangularUV() {
    return `
      vec2 directionToEquirectangularUV(vec3 direction) {
        float u = atan(direction.x, direction.z) * 0.15915494309189535 + .5;
        float v = asin(clamp(-direction.y, -1., 1.)) * 0.3183098861837907 + .5;
        return vec2(u, v);
      }
    `;
  }
}
<|endoftext|>


<commit_before>'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };

var ADD_WATCHED = '@@reduxTimeout/ADD_WATCHED';
var REMOVE_WATCHED = '@@reduxTimeout/REMOVE_WATCHED';
var WATCH_ALL = '@@reduxTimeout/WATCH_ALL';

var watch = {};

var add = function add(threshold, action, toDispatch) {
  if (typeof threshold !== 'number') {
    return new Error('Expected threshold to be a number');
  }
  if (typeof action !== 'string' && !(action instanceof Array)) {
    return new Error('Expected action to be a string or an array');
  }
  if ((typeof toDispatch === 'undefined' ? 'undefined' : _typeof(toDispatch)) !== 'object' && typeof toDispatch !== 'function') {
    return new Error('Expected toDispatch to be an object or a function that would return an object');
  }

  // ensures all objects are watching the same object
  var monitor = {
    threshold: threshold,
    toDispatch: toDispatch,
    lastAction: Date.now()
  };

  var addAction = function addAction(a) {
    if (typeof a !== 'string') {
      return new Error('Expected action to be a string');
    }
    watch[a] = monitor;
  };

  if (action instanceof Array) {
    action.forEach(function (a) {
      addAction(a);
    });
  } else {
    addAction(action);
  }
};

var remove = function remove(action) {
  delete watch[action];
};

/**
 * dispatches an action if an action has not been dispatched within the specified threshold
 * @param  {Number} threshold The time in ms to allow before dispatching an action
 * @param {String | [String]} action The action, or array of actions, to monitor
 * @param {Function} toDispatch An action creator, lib agnostic (redux-thunk, redux-promise etc.)
 */
var reduxTimeout = function reduxTimeout(threshold, action, toDispatch) {
  // if any argument is passed through assume they're attempting to initialize the middleware
  if (threshold) {
    add(threshold, action, toDispatch);
  }

  return function (store) {
    return function (next) {
      return function (action) {
        var now = Date.now();

        var trigger = function trigger(action) {
          // check if object is being monitored at the moment
          var monitor = watch[action];
          if (monitor) {
            // if the threshold has been reached, dispatch the action
            if (now - monitor.lastAction > monitor.threshold && !monitor.dispatching) {
              monitor.dispatching = true;
              store.dispatch(monitor.toDispatch);
            }
            monitor.lastAction = now;
            monitor.dispatching = false;
          }
        };

        trigger(action.type);
        trigger(WATCH_ALL);

        if (action.type === REMOVE_WATCHED && action.payload && action.payload.action) {
          remove(action.payload.action);
        }
        if (action.type === ADD_WATCHED && action.payload) {
          var payload = action.payload;

          add(payload.threshold, payload.action, payload.toDispatch);
        }
        return next(action);
      };
    };
  };
};

module.exports = {
  reduxTimeout: reduxTimeout,
  _watch: watch,
  ADD_WATCHED: ADD_WATCHED,
  REMOVE_WATCHED: REMOVE_WATCHED,
  WATCH_ALL: WATCH_ALL
};
<commit_msg>remove built files from git<commit_after><|endoftext|>


<commit_before>var is = require('is')
var axios = require('axios')

/**
 * The APIs exposed to the user.
 * @type {Object}
 * @private
 */
var resources = {
  stats: require('./stats'),
  catalog: require('./catalog')
}

/**
 * Create a new apiGateway instance with give confgi
 * @param {Object/String} configs
 */
function ApiGateway (config) {
  if (!config) {
    throw new Error('Access token is required.')
  }

  if (!(this instanceof ApiGateway)) {
    return new ApiGateway(config)
  }

  if (is.object(config) && is.undef(config.accessToken)) {
    throw new Error('Access token is required.')
  }

  if (is.string(config)) {
    config = {
      accessToken: config
    }
  }

  config = {
    baseURL: config.baseURL || 'https://api.envato.com/v1',
    timeout: config.timeout || 2000,
    headers: {
      Authorization: 'Bearer' + ' ' + config.accessToken
    }
  }

  this._request = axios.create(config)

  this._prepResources()
}

ApiGateway.prototype = {
  _prepResources: function () {
    for (var name in resources) {
      this[name] = new resources[name](this._request)
    }
  }
}

module.exports = ApiGateway
<commit_msg>Refactor the default baseURL<commit_after>var is = require('is')
var axios = require('axios')

/**
 * The APIs exposed to the user.
 * @type {Object}
 * @private
 */
var resources = {
  stats: require('./stats'),
  catalog: require('./catalog')
}

var DEFAULT_BASE_URL = 'https://api.envato.com/v1'

/**
 * Create a new apiGateway instance with give confgi
 * @param {Object/String} configs
 */
function ApiGateway (config) {
  if (!config) {
    throw new Error('Access token is required.')
  }

  if (!(this instanceof ApiGateway)) {
    return new ApiGateway(config)
  }

  if (is.object(config) && is.undef(config.accessToken)) {
    throw new Error('Access token is required.')
  }

  if (is.string(config)) {
    config = {
      accessToken: config
    }
  }

  config = {
    baseURL: config.baseURL || DEFAULT_BASE_URL,
    timeout: config.timeout || 2000,
    headers: {
      Authorization: 'Bearer' + ' ' + config.accessToken
    }
  }

  this._request = axios.create(config)

  this._prepResources()
}

ApiGateway.prototype = {
  _prepResources: function () {
    for (var name in resources) {
      this[name] = new resources[name](this._request)
    }
  }
}

module.exports = ApiGateway
<|endoftext|>