<commit_before>var fs = require('fs');
var path = require('path');
var grunt = require('grunt');
var semver = require('semver');
var shell = require('shelljs');

var util = module.exports = {

  testDependencies: {
    unit: ['bower_components/jquery/jquery.min.js', 'lib/test/jquery.simulate.js', 'dist/release/ui-grid.css']
  },

  testFiles: {
    unit: ['src/js/core/bootstrap.js', 'src/js/**/*.js', 'test/unit/**/*.spec.js', 'src/features/*/js/**/*.js', 'src/features/*/test/**/*.spec.js', '.tmp/template.js']
  },

  // Return a list of angular files for a specific version
  angularFiles: function (version) {
    // Get the list of angulary files (angular.js, angular-mocks.js, etc)
    var files = grunt.file.readJSON('lib/test/angular/files.json');

    // Start with our test files
    var retFiles = []; //grunt.template.process('<%= karma.options.files %>').split(",");

    files.forEach(function(f) {
      var filePath = path.join('lib', 'test', 'angular', version, f);

      if (! fs.existsSync(filePath)) {
        grunt.fatal("Angular file " + filePath + " doesn't exist");
      }

      retFiles.push(filePath);
    });

    return retFiles;
  },

  startKarma: function(config, singleRun, done){
    var browsers = grunt.option('browsers');
    var reporters = grunt.option('reporters');
    var noColor = grunt.option('no-colors');
    var port = grunt.option('port');
    var p = spawn('node', ['node_modules/karma/bin/karma', 'start', config,
      singleRun ? '--single-run=true' : '',
      reporters ? '--reporters=' + reporters : '',
      browsers ? '--browsers=' + browsers : '',
      noColor ? '--no-colors' : '',
      port ? '--port=' + port : ''
    ]);
    p.stdout.pipe(process.stdout);
    p.stderr.pipe(process.stderr);
    p.on('exit', function(code){
      if(code !== 0) grunt.fail.warn("Karma test(s) failed. Exit code: " + code);
      done();
    });
  },

  customLaunchers: function() {
    return {
      'SL_Chrome': {
        base: 'SauceLabs',
        browserName: 'chrome'
      },
      'SL_Firefox': {
        base: 'SauceLabs',
        browserName: 'firefox'
      },
      'SL_Safari_5': {
        base: 'SauceLabs',
        browserName: 'safari',
        platform: 'Mac 10.6',
        version: '5'
      },
      'SL_Safari_6': {
        base: 'SauceLabs',
        browserName: 'safari',
        platform: 'Mac 10.8',
        version: '6'
      },
      'SL_Safari_7': {
        base: 'SauceLabs',
        browserName: 'safari',
        platform: 'Mac 10.9',
        version: '7'
      },
      // 'SL_IE_8_XP': {
      //   base: 'SauceLabs',
      //   browserName: 'internet explorer',
      //   platform: 'Windows XP',
      //   version: '8'
      // },
      // 'SL_IE_8': {
      //   base: 'SauceLabs',
      //   browserName: 'internet explorer',
      //   platform: 'Windows 7',
      //   version: '8'
      // },
      'SL_IE_9': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '9'
      },
      'SL_IE_10': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '10'
      },
      'SL_IE_11': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 8.1',
        version: '11'
      },
      'SL_Android_4': {
        base: 'SauceLabs',
        browserName: 'android',
        platform: 'Linux',
        version: '4.0'
      },
      'SL_Android_4.3': {
        base: 'SauceLabs',
        browserName: 'android',
        platform: 'Linux',
        version: '4.3'
      },
      'SL_Linux_Opera': {
        base: 'SauceLabs',
        browserName: 'opera',
        platform: 'Linux',
        version: '12'
      },

      // NOTE (c0bra): Currently both iOS 6 and 7 will run (w/ a 45 second activity timeout) and the tests pass, but after that the session just hangs indefinitely -- 20140320
      // 'SL_iOS_6': {
      //   base: 'SauceLabs',
      //   browserName: 'iphone',
      //   platform: 'OS X 10.8',
      //   version: '6.0'
      // },
      // 'SL_iOS_7': {
      //   base: 'SauceLabs',
      //   browserName: 'iphone',
      //   platform: 'OS X 10.9',
      //   version: '7.0'
      // }
    };
  },

  //
  browsers: function() {

  },

  angulars: function() {
    var angularLib = path.join('lib', 'test', 'angular');

    // Loop over all the files in the angular testlib directory
    var files = fs.readdirSync(angularLib);

    // For each file found, make sure it's a directory...
    var versions = [];
    files.forEach(function(file) {
      var dir = path.join(angularLib, file);
      if (! fs.lstatSync(dir).isDirectory()) return;

      if (! semver.valid(file)) return;

      versions.push(file);
    });

    return versions;
  },

  latestAngular: function() {
    function sortFn(a,b) {
      return semver.gt(b, a);
    };

    // For each file found, make sure it's a directory...
    var versions = util.angulars();

    return versions.sort(sortFn)[0];
  },

  /* Read in whatever angular versions are in lib/test/angular and register karma configs for them all! */
  createKarmangularConfig: function() {
    // For each file found, make sure it's a directory...
    var versions = grunt.option('angular') ? grunt.option('angular').split(/,/) : null || util.angulars();

    if (grunt.option('angular')) {
      grunt.log.writeln("Using angular " + grunt.util.pluralize(versions, "version/versions") + ": " + versions.join(', '));
    }

    versions.forEach(function (version) {
      // .. then create a karma config for it!
      var karmaConfigName = 'angular-' + grunt.config.escape(version);

      grunt.config('karma.' + karmaConfigName, {
        options: {
          files: util.testDependencies.unit
            .concat(util.angularFiles(version)
            .concat(util.testFiles.unit))
        }
      });
    });
  },

  // Take the SauceLabs browsers from the karma config file and split them into groups of 3
  createSauceConfig: function() {
    var launchers = util.customLaunchers();

    var chunkNames = Object.keys(launchers);
    var chunks = [].concat.apply([], chunkNames.map(function (c, i) {
      return i % 3 ? [] : [ chunkNames.slice(i, i + 3) ];
    }));

    // console.log(chunks);
    chunks.forEach(function (c, i) {
      grunt.config('karma.sauce-' + i, {
        background: false,
        singleRun: true,
        reporters: ['saucelabs'],
        browsers: c
      });
    });

    // console.log('tasks', chunks.map(function(c, i) { return 'karma:sauce-' + i }));

    grunt.config('serialsauce', chunks.map(function(c, i) { return 'karma:sauce-' + i }));
  },

  updateConfig: function() {
    grunt.config('customLaunchers', util.customLaunchers());
    util.createKarmangularConfig()
    util.createSauceConfig();

    if (process.env.TRAVIS) {
      grunt.config('gh-pages.gh-pages.options.user', {
        name: 'grud',
        email: 'nggridteam@gmail.com'
      });

      grunt.config('gh-pages.gh-pages.options.repo', 'https://' + process.env.GITHUB_NAME + ':' + process.env.GITHUB_PASS + '@github.com/angular-ui/ui-grid.info.git');
    }
  },

  // Get the current release version
  getVersion: function() {
    // Get the current git tag
    // var version = shell.exec('git describe', {silent:true}).output.trim();

    // Try to get a tag for the current version
    var out = shell.exec('git rev-list --all --max-count=1 | xargs git describe', {silent:true});

    var version;

    // If there's a tag on this commit, use it
    if (out.code == 0) {
      version = out.output.trim();
    }
    // ...otherwise, get the most recent stable tag
    else {
      version = shell.exec('git rev-list --tags --max-count=1 | xargs git describe', {silent:true}).output.trim();

      // Append the commit hash suffix
      var hash = shell.exec('git describe --always', {silent:true}).output.trim();
      version = version + '-' + hash;
    }

    // Clean up the tag (git describe --long comes out as: v1.0.0-123-a78fda, need to remove the middle part though with the above commands we should not have the build number)
    var tag = version.replace(/-\d+-/, '-');

    tag = semver.clean(tag);

    return tag;
  },

  getStableVersion: function() {
    var cmd = 'git log --date-order --graph --tags --simplify-by-decoration --pretty=format:\"%ai %h %d\"';
    // grunt.log.writeln(cmd);
    var out = shell.exec(cmd, {silent:true}).output;

    // grunt.log.writeln(lines);

    var lines = out.split('\n');
    for (var i in lines) {
      var l = lines[i];

      var match = l.match(/\(.*?tag: (.+?)(\)|,)/);
      if (! match || match.length < 2 || !match[1]) { continue; }
      var tag = match[1];

      var v = semver.clean(tag);

      if (!v.match(/-.+?$/)) {
        return v;
      }
    }
  }

};<commit_msg>Add coverage config to serialsauce tasks<commit_after>var fs = require('fs');
var path = require('path');
var grunt = require('grunt');
var semver = require('semver');
var shell = require('shelljs');

var util = module.exports = {

  testDependencies: {
    unit: ['bower_components/jquery/jquery.min.js', 'lib/test/jquery.simulate.js', 'dist/release/ui-grid.css']
  },

  testFiles: {
    unit: ['src/js/core/bootstrap.js', 'src/js/**/*.js', 'test/unit/**/*.spec.js', 'src/features/*/js/**/*.js', 'src/features/*/test/**/*.spec.js', '.tmp/template.js']
  },

  // Return a list of angular files for a specific version
  angularFiles: function (version) {
    // Get the list of angulary files (angular.js, angular-mocks.js, etc)
    var files = grunt.file.readJSON('lib/test/angular/files.json');

    // Start with our test files
    var retFiles = []; //grunt.template.process('<%= karma.options.files %>').split(",");

    files.forEach(function(f) {
      var filePath = path.join('lib', 'test', 'angular', version, f);

      if (! fs.existsSync(filePath)) {
        grunt.fatal("Angular file " + filePath + " doesn't exist");
      }

      retFiles.push(filePath);
    });

    return retFiles;
  },

  startKarma: function(config, singleRun, done){
    var browsers = grunt.option('browsers');
    var reporters = grunt.option('reporters');
    var noColor = grunt.option('no-colors');
    var port = grunt.option('port');
    var p = spawn('node', ['node_modules/karma/bin/karma', 'start', config,
      singleRun ? '--single-run=true' : '',
      reporters ? '--reporters=' + reporters : '',
      browsers ? '--browsers=' + browsers : '',
      noColor ? '--no-colors' : '',
      port ? '--port=' + port : ''
    ]);
    p.stdout.pipe(process.stdout);
    p.stderr.pipe(process.stderr);
    p.on('exit', function(code){
      if(code !== 0) grunt.fail.warn("Karma test(s) failed. Exit code: " + code);
      done();
    });
  },

  customLaunchers: function() {
    return {
      'SL_Chrome': {
        base: 'SauceLabs',
        browserName: 'chrome'
      },
      'SL_Firefox': {
        base: 'SauceLabs',
        browserName: 'firefox'
      },
      'SL_Safari_5': {
        base: 'SauceLabs',
        browserName: 'safari',
        platform: 'Mac 10.6',
        version: '5'
      },
      'SL_Safari_6': {
        base: 'SauceLabs',
        browserName: 'safari',
        platform: 'Mac 10.8',
        version: '6'
      },
      'SL_Safari_7': {
        base: 'SauceLabs',
        browserName: 'safari',
        platform: 'Mac 10.9',
        version: '7'
      },
      // 'SL_IE_8_XP': {
      //   base: 'SauceLabs',
      //   browserName: 'internet explorer',
      //   platform: 'Windows XP',
      //   version: '8'
      // },
      // 'SL_IE_8': {
      //   base: 'SauceLabs',
      //   browserName: 'internet explorer',
      //   platform: 'Windows 7',
      //   version: '8'
      // },
      'SL_IE_9': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '9'
      },
      'SL_IE_10': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 7',
        version: '10'
      },
      'SL_IE_11': {
        base: 'SauceLabs',
        browserName: 'internet explorer',
        platform: 'Windows 8.1',
        version: '11'
      },
      'SL_Android_4': {
        base: 'SauceLabs',
        browserName: 'android',
        platform: 'Linux',
        version: '4.0'
      },
      'SL_Android_4.3': {
        base: 'SauceLabs',
        browserName: 'android',
        platform: 'Linux',
        version: '4.3'
      },
      'SL_Linux_Opera': {
        base: 'SauceLabs',
        browserName: 'opera',
        platform: 'Linux',
        version: '12'
      },

      // NOTE (c0bra): Currently both iOS 6 and 7 will run (w/ a 45 second activity timeout) and the tests pass, but after that the session just hangs indefinitely -- 20140320
      // 'SL_iOS_6': {
      //   base: 'SauceLabs',
      //   browserName: 'iphone',
      //   platform: 'OS X 10.8',
      //   version: '6.0'
      // },
      // 'SL_iOS_7': {
      //   base: 'SauceLabs',
      //   browserName: 'iphone',
      //   platform: 'OS X 10.9',
      //   version: '7.0'
      // }
    };
  },

  //
  browsers: function() {

  },

  angulars: function() {
    var angularLib = path.join('lib', 'test', 'angular');

    // Loop over all the files in the angular testlib directory
    var files = fs.readdirSync(angularLib);

    // For each file found, make sure it's a directory...
    var versions = [];
    files.forEach(function(file) {
      var dir = path.join(angularLib, file);
      if (! fs.lstatSync(dir).isDirectory()) return;

      if (! semver.valid(file)) return;

      versions.push(file);
    });

    return versions;
  },

  latestAngular: function() {
    function sortFn(a,b) {
      return semver.gt(b, a);
    };

    // For each file found, make sure it's a directory...
    var versions = util.angulars();

    return versions.sort(sortFn)[0];
  },

  /* Read in whatever angular versions are in lib/test/angular and register karma configs for them all! */
  createKarmangularConfig: function() {
    // For each file found, make sure it's a directory...
    var versions = grunt.option('angular') ? grunt.option('angular').split(/,/) : null || util.angulars();

    if (grunt.option('angular')) {
      grunt.log.writeln("Using angular " + grunt.util.pluralize(versions, "version/versions") + ": " + versions.join(', '));
    }

    versions.forEach(function (version) {
      // .. then create a karma config for it!
      var karmaConfigName = 'angular-' + grunt.config.escape(version);

      grunt.config('karma.' + karmaConfigName, {
        options: {
          files: util.testDependencies.unit
            .concat(util.angularFiles(version)
            .concat(util.testFiles.unit))
        }
      });
    });
  },

  // Take the SauceLabs browsers from the karma config file and split them into groups of 3
  createSauceConfig: function() {
    var launchers = util.customLaunchers();

    var chunkNames = Object.keys(launchers);
    var chunks = [].concat.apply([], chunkNames.map(function (c, i) {
      return i % 3 ? [] : [ chunkNames.slice(i, i + 3) ];
    }));

    // console.log(chunks);
    chunks.forEach(function (c, i) {
      grunt.config('karma.sauce-' + i, {
        background: false,
        singleRun: true,
        reporters: ['saucelabs', 'coverage'],
        browsers: c,
        preprocessors: {
          'src/**/!(*.spec)+(.js)': ['coverage']
        },
        coverageReporter: {
          type: 'lcov',
          dir:  'coverage',
          subdir: '.'
        }
      });
    });

    // console.log('tasks', chunks.map(function(c, i) { return 'karma:sauce-' + i }));

    grunt.config('serialsauce', chunks.map(function(c, i) { return 'karma:sauce-' + i }));
  },

  updateConfig: function() {
    grunt.config('customLaunchers', util.customLaunchers());
    util.createKarmangularConfig()
    util.createSauceConfig();

    if (process.env.TRAVIS) {
      grunt.config('gh-pages.gh-pages.options.user', {
        name: 'grud',
        email: 'nggridteam@gmail.com'
      });

      grunt.config('gh-pages.gh-pages.options.repo', 'https://' + process.env.GITHUB_NAME + ':' + process.env.GITHUB_PASS + '@github.com/angular-ui/ui-grid.info.git');
    }
  },

  // Get the current release version
  getVersion: function() {
    // Get the current git tag
    // var version = shell.exec('git describe', {silent:true}).output.trim();

    // Try to get a tag for the current version
    var out = shell.exec('git rev-list --all --max-count=1 | xargs git describe', {silent:true});

    var version;

    // If there's a tag on this commit, use it
    if (out.code == 0) {
      version = out.output.trim();
    }
    // ...otherwise, get the most recent stable tag
    else {
      version = shell.exec('git rev-list --tags --max-count=1 | xargs git describe', {silent:true}).output.trim();

      // Append the commit hash suffix
      var hash = shell.exec('git describe --always', {silent:true}).output.trim();
      version = version + '-' + hash;
    }

    // Clean up the tag (git describe --long comes out as: v1.0.0-123-a78fda, need to remove the middle part though with the above commands we should not have the build number)
    var tag = version.replace(/-\d+-/, '-');

    tag = semver.clean(tag);

    return tag;
  },

  getStableVersion: function() {
    var cmd = 'git log --date-order --graph --tags --simplify-by-decoration --pretty=format:\"%ai %h %d\"';
    // grunt.log.writeln(cmd);
    var out = shell.exec(cmd, {silent:true}).output;

    // grunt.log.writeln(lines);

    var lines = out.split('\n');
    for (var i in lines) {
      var l = lines[i];

      var match = l.match(/\(.*?tag: (.+?)(\)|,)/);
      if (! match || match.length < 2 || !match[1]) { continue; }
      var tag = match[1];

      var v = semver.clean(tag);

      if (!v.match(/-.+?$/)) {
        return v;
      }
    }
  }

};<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

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

exports.default = function (_options) {
  checkJava();

  var options = formatOptions(_options);
  var parserDir = getClassDir(options);
  var mode = getMode(options);
  var ANTLR4 = getClasses(options);

  return _through2.default.obj(function (file, encoding, callback) {
    var _this = this;

    if (file.isNull()) {
      return callback(null, file);
    }

    if (file.isStream()) {
      this.emit('error', new _gulpUtil.PluginError(PLUGIN_NAME, 'Streams not supported (yet)!'));
    } else if (file.isBuffer()) {
      var inputFile = file.history[0];

      switch (_path2.default.extname(inputFile)) {
        case '.g4':
          return (0, _childProcessData2.default)((0, _child_process.spawn)('java', ['org.antlr.v4.Tool', '-Dlanguage=JavaScript', '-o', parserDir, inputFile])).then(function () {
            callback(null, file);
          }, function (err) {
            _this.emit('error', new _gulpUtil.PluginError(PLUGIN_NAME, new Error(err)));
          });

        default:
          if (ANTLR4.isProperlySetup()) {
            var data = file.contents.toString('utf8');
            var chars = new _antlr.InputStream(data, true);
            var lexer = new ANTLR4.Lexer(chars);
            var tokens = new _antlr.CommonTokenStream(lexer);
            var parser = new ANTLR4.Parser(tokens);
            parser.buildParseTrees = true;
            var tree = parser[ANTLR4.rule]();

            switch (mode) {
              case 'tree':
                console.log(tree.toStringTree(parser.ruleNames));
                break;

              case 'walk':
                var walker = new _tree.ParseTreeWalker();
                var listener = new ANTLR4.Listener();
                walker.walk(listener, tree);
                console.log('');
                break;
            }
          }

          return callback(null, file);
      }
    }
  });
};

var _gulpUtil = require('gulp-util');

var _through = require('through2');

var _through2 = _interopRequireDefault(_through);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _child_process = require('child_process');

var _childProcessData = require('child-process-data');

var _childProcessData2 = _interopRequireDefault(_childProcessData);

var _antlr = require('antlr4');

var _tree = require('antlr4/tree');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PLUGIN_NAME = 'gulp-antlr4';

function checkJava() {
  var CLASSPATH = process.env.CLASSPATH;

  if (!CLASSPATH) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new ReferenceError('Environment variable CLASSPATH is not defined'));
  }

  // Not matching '~' as it is not understood by Java anyway
  var matchJar = CLASSPATH.match(/.*:((\d|\w|\/|-|_|\.)+antlr-\d+\.\d+-complete\.jar):.*/);

  if (matchJar === null) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new ReferenceError('Cannot find ANTLR 4 .jar file'));
  }
}

function formatOptions(options) {
  if (typeof options === 'string') {
    return { parserDir: options };
  }
  return (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' ? Object.assign({
    listenerDir: options.parserDir }, options) : {};
}

function getClassDir(options) {
  var parserDir = options.parserDir;

  if (typeof parserDir !== 'string') {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new TypeError('You must provide the directory where to write or read\n     the generated lexing and parsing tools (option \'parserDir\')'));
  }

  return parserDir;
}

function getMode(options) {
  var mode = options.mode,
      listener = options.listener;

  if (typeof mode !== 'string' && mode !== undefined) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new TypeError('Bad option: ' + mode));
  }

  return listener ? 'walk' : mode;
}

function getClasses(options) {
  var grammar = options.grammar;

  if (!grammar) {
    return {
      isProperlySetup: function isProperlySetup() {
        return false;
      }
    };
  }

  return {
    rule: getRule(options),
    Lexer: getLexer(options),
    Parser: getParser(options),
    Listener: getListener(options),
    isProperlySetup: function isProperlySetup() {
      return true;
    }
  };
}

function getRule(options) {
  var rule = options.rule;

  if (!rule) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, 'Undefined starting rule (option \'rule\')');
  }

  return rule;
}

function getLexer(options) {
  var grammar = options.grammar,
      parserDir = options.parserDir;

  var lexer = grammar + 'Lexer';

  return require(_path2.default.join(parserDir, lexer))[lexer];
}

function getParser(options) {
  var grammar = options.grammar,
      parserDir = options.parserDir;

  var parser = grammar + 'Parser';

  return require(_path2.default.join(parserDir, parser))[parser];
}

function getListener(options) {
  var listener = options.listener,
      listenerDir = options.listenerDir;

  if (!listener) {
    return;
  }

  return require(_path2.default.join(listenerDir, listener))[listener];
}
module.exports = exports['default'];<commit_msg>prepublish<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

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

exports.default = function (_options) {
  checkJava();

  var options = formatOptions(_options);
  var parserDir = getClassDir(options);
  var mode = getMode(options);
  var ANTLR4 = getClasses(options);

  return _through2.default.obj(function (file, encoding, callback) {
    var _this = this;

    if (file.isNull()) {
      return callback(null, file);
    }

    if (file.isStream()) {
      this.emit('error', new _gulpUtil.PluginError(PLUGIN_NAME, 'Streams not supported (yet)!'));
    } else if (file.isBuffer()) {
      var inputFile = file.history[0];

      switch (_path2.default.extname(inputFile)) {
        case '.g4':
          return (0, _childProcessData2.default)((0, _child_process.spawn)('java', ['org.antlr.v4.Tool', '-Dlanguage=JavaScript', '-o', parserDir, inputFile])).then(function () {
            callback(null, file);
          }, function (err) {
            _this.emit('error', new _gulpUtil.PluginError(PLUGIN_NAME, new Error(err)));
          });

        default:
          if (ANTLR4.isProperlySetup()) {
            var data = file.contents.toString('utf8');
            var chars = new _antlr.InputStream(data, true);
            var lexer = new ANTLR4.Lexer(chars);
            var tokens = new _antlr.CommonTokenStream(lexer);
            var parser = new ANTLR4.Parser(tokens);
            parser.buildParseTrees = true;
            var tree = parser[ANTLR4.rule]();

            switch (mode) {
              case 'tree':
                console.log(tree.toStringTree(parser.ruleNames));
                break;

              case 'walk':
                var walker = new _tree.ParseTreeWalker();
                var listener = new ANTLR4.Listener();
                walker.walk(listener, tree);
                console.log('');
                break;
            }
          }

          return callback(null, file);
      }
    }
  });
};

var _gulpUtil = require('gulp-util');

var _through = require('through2');

var _through2 = _interopRequireDefault(_through);

var _path = require('path');

var _path2 = _interopRequireDefault(_path);

var _child_process = require('child_process');

var _childProcessData = require('child-process-data');

var _childProcessData2 = _interopRequireDefault(_childProcessData);

var _antlr = require('antlr4');

var _tree = require('antlr4/tree');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PLUGIN_NAME = 'gulp-antlr4';

function checkJava() {
  var CLASSPATH = process.env.CLASSPATH;

  if (!CLASSPATH) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new ReferenceError('Environment variable CLASSPATH is not defined'));
  }

  // Not matching '~' as it is not understood by Java anyway
  var matchJar = CLASSPATH.match(/.*:((\d|\w|\/|-|_|\.)+antlr-\d+\.\d+-complete\.jar):.*/);

  if (matchJar === null) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new ReferenceError('Cannot find ANTLR 4 .jar file'));
  }
}

function formatOptions(options) {
  if (typeof options === 'string') {
    return { parserDir: options };
  }
  return (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' ? Object.assign({
    listenerDir: options.parserDir }, options) : {};
}

function getClassDir(options) {
  var parserDir = options.parserDir;

  if (typeof parserDir !== 'string') {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new TypeError('You must provide the directory where to write or read\n     the generated lexing and parsing tools (option \'parserDir\')'));
  }

  return parserDir;
}

function getMode(options) {
  var mode = options.mode,
      listener = options.listener;

  if (typeof mode !== 'string' && mode !== undefined) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, new TypeError('Bad option: ' + mode));
  }

  return listener ? 'walk' : mode;
}

function getClasses(options) {
  var grammar = options.grammar;

  if (!grammar) {
    return {
      isProperlySetup: function isProperlySetup() {
        return false;
      }
    };
  }

  return {
    rule: getRule(options),
    Lexer: getLexer(options),
    Parser: getParser(options),
    Listener: getListener(options),
    isProperlySetup: function isProperlySetup() {
      return true;
    }
  };
}

function getRule(options) {
  var rule = options.rule;

  if (!rule) {
    throw new _gulpUtil.PluginError(PLUGIN_NAME, 'Undefined starting rule (option \'rule\')');
  }

  return rule;
}

function getLexer(options) {
  var grammar = options.grammar,
      parserDir = options.parserDir;

  var lexer = grammar + 'Lexer';

  // Convert relative to absolute path
  var base = process.cwd();
  var rel = _path2.default.relative(base, parserDir);
  return require(_path2.default.join(base, rel, lexer))[lexer];
}

function getParser(options) {
  var grammar = options.grammar,
      parserDir = options.parserDir;

  var parser = grammar + 'Parser';

  // Convert relative to absolute path
  var base = process.cwd();
  var rel = _path2.default.relative(base, parserDir);
  return require(_path2.default.join(base, rel, parser))[parser];
}

function getListener(options) {
  var listener = options.listener,
      listenerDir = options.listenerDir;

  if (!listener) {
    return;
  }

  // Convert relative to absolute path
  var base = process.cwd();
  var rel = _path2.default.relative(base, listenerDir);
  return require(_path2.default.join(base, rel, listener))[listener];
}
module.exports = exports['default'];<|endoftext|>


<commit_before>var React = require('react');
var RegExpPropType = require('./regExpPropType');
var escapeStringRegexp = require('escape-string-regexp');
var blacklist = require('blacklist');
var createReactClass = require('create-react-class');
var PropTypes = require('prop-types');

function removeDiacritics(str, blacklist) {
  if (!String.prototype.normalize) {
    // Fall back to original string
    return str;
  }

  if (!blacklist) {
    // No blacklist, just remove all
    return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
  }
  else {
    var blacklistChars = blacklist.split('');

    // Remove all diacritics that are not a part of a blacklisted character
    // First char cannot be a diacritic
    return str.normalize('NFD').replace(/.[\u0300-\u036f]+/g, function(m) {
      return blacklistChars.indexOf(m.normalize()) > -1 ? m.normalize() : m[0];
    });
  }
}

var Highlighter = createReactClass({
  displayName: 'Highlighter',
  count: 0,
  propTypes: {
    search: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number,
      PropTypes.bool,
      RegExpPropType
    ]).isRequired,
    caseSensitive: PropTypes.bool,
    ignoreDiacritics: PropTypes.bool,
    diacriticsBlacklist: PropTypes.string,
    matchElement: PropTypes.string,
    matchClass: PropTypes.string,
    matchStyle: PropTypes.object
  },

  render: function() {
    var props = blacklist(
      this.props,
      'search',
      'caseSensitive',
      'ignoreDiacritics',
      'diacriticsBlacklist',
      'matchElement',
      'matchClass',
      'matchStyle'
    );

    return React.createElement('span', props, this.renderElement(this.props.children));
  },

  /**
   * A wrapper to the highlight method to determine when the highlighting
   * process should occur.
   *
   * @param  {string} subject
   *   The body of text that will be searched for highlighted words.
   *
   * @return {Array}
   *   An array of ReactElements
   */
  renderElement: function(subject) {
    if (this.isScalar() && this.hasSearch()) {
      var search = this.getSearch();
      return this.highlightChildren(subject, search);
    }

    return this.props.children;
  },

  /**
   * Determine if props are valid types for processing.
   *
   * @return {Boolean}
   */
  isScalar: function() {
    return (/string|number|boolean/).test(typeof this.props.children);
  },

  /**
   * Determine if required search prop is defined and valid.
   *
   * @return {Boolean}
   */
  hasSearch: function() {
    return (typeof this.props.search !== 'undefined') && this.props.search;
  },

  /**
   * Get the search prop, but always in the form of a regular expression. Use
   * this as a proxy to this.props.search for consistency.
   *
   * @return {RegExp}
   */
  getSearch: function() {
    if (this.props.search instanceof RegExp) {
      return this.props.search;
    }

    var flags = '';
    if (!this.props.caseSensitive) {
      flags +='i';
    }

    var search = this.props.search;
    if (typeof this.props.search === 'string') {
      search = escapeStringRegexp(search);
    }

    if (this.props.ignoreDiacritics) {
      search = removeDiacritics(search, this.props.diacriticsBlacklist);
    }

    return new RegExp(search, flags);
  },

  /**
   * Get the indexes of the first and last characters of the matched string.
   *
   * @param  {string} subject
   *   The string to search against.
   *
   * @param  {RegExp} search
   *   The regex search query.
   *
   * @return {Object}
   *   An object consisting of "first" and "last" properties representing the
   *   indexes of the first and last characters of a matching string.
   */
  getMatchBoundaries: function(subject, search) {
    var matches = search.exec(subject);
    if (matches) {
      return {
        first: matches.index,
        last: matches.index + matches[0].length
      };
    }
  },

  /**
   * Determines which strings of text should be highlighted or not.
   *
   * @param  {string} subject
   *   The body of text that will be searched for highlighted words.
   * @param  {string} search
   *   The search used to search for highlighted words.
   *
   * @return {Array}
   *   An array of ReactElements
   */
  highlightChildren: function(subject, search) {
    var children = [];
    var remaining = subject;

    while (remaining) {
      var remainingCleaned = (this.props.ignoreDiacritics
        ? removeDiacritics(remaining, this.props.diacriticsBlacklist)
        : remaining
      );

      if (!search.test(remainingCleaned)) {
        children.push(this.renderPlain(remaining));
        return children;
      }

      var boundaries = this.getMatchBoundaries(remainingCleaned, search);

      if (boundaries.first === 0 && boundaries.last === 0) {
        // Regex zero-width match
        return children;
      }

      // Capture the string that leads up to a match...
      var nonMatch = remaining.slice(0, boundaries.first);
      if (nonMatch) {
        children.push(this.renderPlain(nonMatch));
      }

      // Now, capture the matching string...
      var match = remaining.slice(boundaries.first, boundaries.last);
      if (match) {
        children.push(this.renderHighlight(match));
      }

      // And if there's anything left over, recursively run this method again.
      remaining = remaining.slice(boundaries.last);

    }

    return children;
  },

  /**
   * Responsible for rending a non-highlighted element.
   *
   * @param  {string} string
   *   A string value to wrap an element around.
   *
   * @return {ReactElement}
   */
  renderPlain: function(string) {
    this.count++;
    return React.createElement('span', { key: this.count, children: string });
  },

  /**
   * Responsible for rending a highlighted element.
   *
   * @param  {string} string
   *   A string value to wrap an element around.
   *
   * @return {ReactElement}
   */
  renderHighlight: function(string) {
    this.count++;
    return React.createElement(this.props.matchElement, {
      key: this.count,
      className: this.props.matchClass,
      style: this.props.matchStyle,
      children: string
    });
  }
});

Highlighter.defaultProps = {
  caseSensitive: false,
  ignoreDiacritics: false,
  diacriticsBlacklist: '',
  matchElement: 'mark',
  matchClass: 'highlight',
  matchStyle: {}
};

module.exports = Highlighter;
<commit_msg>Allow passing React components as matchElement<commit_after>var React = require('react');
var RegExpPropType = require('./regExpPropType');
var escapeStringRegexp = require('escape-string-regexp');
var blacklist = require('blacklist');
var createReactClass = require('create-react-class');
var PropTypes = require('prop-types');

function removeDiacritics(str, blacklist) {
  if (!String.prototype.normalize) {
    // Fall back to original string
    return str;
  }

  if (!blacklist) {
    // No blacklist, just remove all
    return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
  }
  else {
    var blacklistChars = blacklist.split('');

    // Remove all diacritics that are not a part of a blacklisted character
    // First char cannot be a diacritic
    return str.normalize('NFD').replace(/.[\u0300-\u036f]+/g, function(m) {
      return blacklistChars.indexOf(m.normalize()) > -1 ? m.normalize() : m[0];
    });
  }
}

var Highlighter = createReactClass({
  displayName: 'Highlighter',
  count: 0,
  propTypes: {
    search: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number,
      PropTypes.bool,
      RegExpPropType
    ]).isRequired,
    caseSensitive: PropTypes.bool,
    ignoreDiacritics: PropTypes.bool,
    diacriticsBlacklist: PropTypes.string,
    matchElement: PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.func]),
    matchClass: PropTypes.string,
    matchStyle: PropTypes.object
  },

  render: function() {
    var props = blacklist(
      this.props,
      'search',
      'caseSensitive',
      'ignoreDiacritics',
      'diacriticsBlacklist',
      'matchElement',
      'matchClass',
      'matchStyle'
    );

    return React.createElement('span', props, this.renderElement(this.props.children));
  },

  /**
   * A wrapper to the highlight method to determine when the highlighting
   * process should occur.
   *
   * @param  {string} subject
   *   The body of text that will be searched for highlighted words.
   *
   * @return {Array}
   *   An array of ReactElements
   */
  renderElement: function(subject) {
    if (this.isScalar() && this.hasSearch()) {
      var search = this.getSearch();
      return this.highlightChildren(subject, search);
    }

    return this.props.children;
  },

  /**
   * Determine if props are valid types for processing.
   *
   * @return {Boolean}
   */
  isScalar: function() {
    return (/string|number|boolean/).test(typeof this.props.children);
  },

  /**
   * Determine if required search prop is defined and valid.
   *
   * @return {Boolean}
   */
  hasSearch: function() {
    return (typeof this.props.search !== 'undefined') && this.props.search;
  },

  /**
   * Get the search prop, but always in the form of a regular expression. Use
   * this as a proxy to this.props.search for consistency.
   *
   * @return {RegExp}
   */
  getSearch: function() {
    if (this.props.search instanceof RegExp) {
      return this.props.search;
    }

    var flags = '';
    if (!this.props.caseSensitive) {
      flags +='i';
    }

    var search = this.props.search;
    if (typeof this.props.search === 'string') {
      search = escapeStringRegexp(search);
    }

    if (this.props.ignoreDiacritics) {
      search = removeDiacritics(search, this.props.diacriticsBlacklist);
    }

    return new RegExp(search, flags);
  },

  /**
   * Get the indexes of the first and last characters of the matched string.
   *
   * @param  {string} subject
   *   The string to search against.
   *
   * @param  {RegExp} search
   *   The regex search query.
   *
   * @return {Object}
   *   An object consisting of "first" and "last" properties representing the
   *   indexes of the first and last characters of a matching string.
   */
  getMatchBoundaries: function(subject, search) {
    var matches = search.exec(subject);
    if (matches) {
      return {
        first: matches.index,
        last: matches.index + matches[0].length
      };
    }
  },

  /**
   * Determines which strings of text should be highlighted or not.
   *
   * @param  {string} subject
   *   The body of text that will be searched for highlighted words.
   * @param  {string} search
   *   The search used to search for highlighted words.
   *
   * @return {Array}
   *   An array of ReactElements
   */
  highlightChildren: function(subject, search) {
    var children = [];
    var remaining = subject;

    while (remaining) {
      var remainingCleaned = (this.props.ignoreDiacritics
        ? removeDiacritics(remaining, this.props.diacriticsBlacklist)
        : remaining
      );

      if (!search.test(remainingCleaned)) {
        children.push(this.renderPlain(remaining));
        return children;
      }

      var boundaries = this.getMatchBoundaries(remainingCleaned, search);

      if (boundaries.first === 0 && boundaries.last === 0) {
        // Regex zero-width match
        return children;
      }

      // Capture the string that leads up to a match...
      var nonMatch = remaining.slice(0, boundaries.first);
      if (nonMatch) {
        children.push(this.renderPlain(nonMatch));
      }

      // Now, capture the matching string...
      var match = remaining.slice(boundaries.first, boundaries.last);
      if (match) {
        children.push(this.renderHighlight(match));
      }

      // And if there's anything left over, recursively run this method again.
      remaining = remaining.slice(boundaries.last);

    }

    return children;
  },

  /**
   * Responsible for rending a non-highlighted element.
   *
   * @param  {string} string
   *   A string value to wrap an element around.
   *
   * @return {ReactElement}
   */
  renderPlain: function(string) {
    this.count++;
    return React.createElement('span', { key: this.count, children: string });
  },

  /**
   * Responsible for rending a highlighted element.
   *
   * @param  {string} string
   *   A string value to wrap an element around.
   *
   * @return {ReactElement}
   */
  renderHighlight: function(string) {
    this.count++;
    return React.createElement(this.props.matchElement, {
      key: this.count,
      className: this.props.matchClass,
      style: this.props.matchStyle,
      children: string
    });
  }
});

Highlighter.defaultProps = {
  caseSensitive: false,
  ignoreDiacritics: false,
  diacriticsBlacklist: '',
  matchElement: 'mark',
  matchClass: 'highlight',
  matchStyle: {}
};

module.exports = Highlighter;
<|endoftext|>


<commit_before>// @see https://devcenter.heroku.com/articles/nodejs#write-your-app

var express = require('express')
  , fs      = require('fs') // node
  , gm      = require('gm')
  , http    = require('http') // node
  , https   = require('https') // node
  , mime    = require('mime')
  , url     = require('url') // node
  // @see http://aaronheckmann.posterous.com/graphicsmagick-on-heroku-with-nodejs
  , app = express()
  , imageMagick = gm.subClass({imageMagick: true})
  , whitelist = process.env.WHITELIST || [] // [/\.gov$/, /google\.com$/]
  , delay = parseInt(process.env.DELAY) || 5000
  , mimeTypes = [
    'image/gif',
    'image/jpeg',
    'image/png',
    // Common typos
    'image/jpg'
  ];

function retrieveRemote(remote, width, height) {
  console.log('DEBUG - remote=' + remote);
  console.log('DEBUG - width=' + width);
  console.log('DEBUG - height=' + height);
  // @see http://nodejs.org/api/url.html#url_url
  var options = url.parse(remote);
  // @see https://github.com/substack/hyperquest
  options.agent = false;
  if (options.protocol !== 'http:' && options.protocol !== 'https:') {
    return res.status(404).send('Expected URI scheme to be HTTP or HTTPS');
  }
  if (!options.hostname) {
    return res.status(404).send('Expected URI host to be non-empty');
  }
  options.headers = {'User-Agent': 'image-proxy/0.0.6'}

  var agent = options.protocol === 'http:' ? http : https
    , timeout = false
      // @see http://nodejs.org/api/http.html#http_http_get_options_callback
    , request = agent.get(options, function (response) {
        if (timeout) {
          // Status code 504 already sent.
          return;
        }

        // @see http://nodejs.org/api/http.html#http_response_statuscode
        if ((response.statusCode === 301 || response.statusCode === 302) && response.headers['location']) {
          var redirect = url.parse(response.headers['location']);
          // @see https://tools.ietf.org/html/rfc7231#section-7.1.2
          if (!redirect.protocol) {
            redirect.protocol = options.protocol;
          }
          if (!redirect.hostname) {
            redirect.hostname = options.hostname;
          }
          if (!redirect.port) {
            redirect.port = options.port;
          }
          if (!redirect.hash) {
            redirect.hash = options.hash;
          }
          return retrieveRemote(url.format(redirect), weight, height);
        }

        // The image must return status code 200.
        if (response.statusCode !== 200) {
          return res.status(404).send('Expected response code 200, got ' + response.statusCode);
        }

        // The image must be a valid content type.
        // @see http://nodejs.org/api/http.html#http_request_headers
        var mimeType;
        if (extension) {
          mimeType = mime.lookup(extension);
        }
        else {
          mimeType = (response.headers['content-type'] || '').replace(/;.*/, '');
          extension = mime.extension(mimeType);
        }
        if (mimeTypes.indexOf(mimeType) === -1) {
          return res.status(404).send('Expected content type ' + mimeTypes.join(', ') + ', got ' + mimeType);
        }

        // @see https://github.com/aheckmann/gm#constructor
        var im = imageMagick(response, 'image.' + extension);
          // @see http://www.imagemagick.org/Usage/thumbnails/#cut
        if (width) {
          if (height) {
            im.resize(width, height + '^>');
          } else {
            im.resize(width);
          }
        }

        im.gravity('Center'); // faces are most often near the center
        if (width && height) {
          im.extent(width, height);
        }

        im.stream(function (err, stdout, stderr) {
            if (err) return next(err);
            // Log errors in production.
            stderr.pipe(process.stderr);
            // @see http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html
            res.writeHead(200, {
              'Content-Type': mimeType,
              'Cache-Control': 'max-age=31536000, public', // 1 year
            });
            stdout.pipe(res);
          });
      }).on('error', next);

  // Timeout after five seconds. Better luck next time.
  request.setTimeout(delay, function () {
    timeout = true; // if we abort, we'll get a "socket hang up" error
    return res.status(504).send();
  });
}

module.exports = function () {
  app.get('/:url', function (req, res, next) {
  });

  app.get('/:url/:width/:height.:extension?', function (req, res, next) {
    var width = req.params.width
      , height = req.params.height
      , extension = req.params.extension;

    // Validate parameters.
    if (whitelist.length) {
      var parts = url.parse(req.params.url);
      if (parts.hostname) {
        var any = false, _i, _len;
        if (typeof whitelist === 'string') {
          whitelist = whitelist.split(',');
        }
        for (_i = 0, _len = whitelist.length; _i < _len; _i++) {
          if (typeof whitelist[_i] === 'string') {
            // Escape periods and add anchor.
            whitelist[_i] = new RegExp(whitelist[_i].replace('.', '\\.') + '$')
          }
          if (whitelist[_i].test(parts.hostname)) {
            any = true;
            break;
          }
        }
        if (!any) { // if none
          return res.status(404).send('Expected URI host to be whitelisted');
        }
      }
    }
    if (isNaN(parseInt(width))) {
      return res.status(404).send('Expected width to be an integer');
    }
    if (parseInt(width) > 1000) {
      return res.status(404).send('Expected width to be less than or equal to 1000');
    }
    if (isNaN(parseInt(height))) {
      return res.status(404).send('Expected height to be an integer');
    }
    if (parseInt(height) > 1000) {
      return res.status(404).send('Expected height to be less than or equal to 1000');
    }
    retrieveRemote('http://s3.amazonaws.com/qmerce-static-media/' + req.params.url, width, height);
  });

  return app;
};
<commit_msg>support no sizes.<commit_after>// @see https://devcenter.heroku.com/articles/nodejs#write-your-app

var express = require('express')
  , fs      = require('fs') // node
  , gm      = require('gm')
  , http    = require('http') // node
  , https   = require('https') // node
  , mime    = require('mime')
  , url     = require('url') // node
  // @see http://aaronheckmann.posterous.com/graphicsmagick-on-heroku-with-nodejs
  , app = express()
  , imageMagick = gm.subClass({imageMagick: true})
  , whitelist = process.env.WHITELIST || [] // [/\.gov$/, /google\.com$/]
  , delay = parseInt(process.env.DELAY) || 5000
  , mimeTypes = [
    'image/gif',
    'image/jpeg',
    'image/png',
    // Common typos
    'image/jpg'
  ];

function retrieveRemote(remote, width, height, extention) {
  console.log('DEBUG - remote=' + remote);
  console.log('DEBUG - width=' + width);
  console.log('DEBUG - height=' + height);
  // @see http://nodejs.org/api/url.html#url_url
  var options = url.parse(remote);
  // @see https://github.com/substack/hyperquest
  options.agent = false;
  if (options.protocol !== 'http:' && options.protocol !== 'https:') {
    return res.status(404).send('Expected URI scheme to be HTTP or HTTPS');
  }
  if (!options.hostname) {
    return res.status(404).send('Expected URI host to be non-empty');
  }
  options.headers = {'User-Agent': 'image-proxy/0.0.6'}

  var agent = options.protocol === 'http:' ? http : https
    , timeout = false
      // @see http://nodejs.org/api/http.html#http_http_get_options_callback
    , request = agent.get(options, function (response) {
        if (timeout) {
          // Status code 504 already sent.
          return;
        }

        // @see http://nodejs.org/api/http.html#http_response_statuscode
        if ((response.statusCode === 301 || response.statusCode === 302) && response.headers['location']) {
          var redirect = url.parse(response.headers['location']);
          // @see https://tools.ietf.org/html/rfc7231#section-7.1.2
          if (!redirect.protocol) {
            redirect.protocol = options.protocol;
          }
          if (!redirect.hostname) {
            redirect.hostname = options.hostname;
          }
          if (!redirect.port) {
            redirect.port = options.port;
          }
          if (!redirect.hash) {
            redirect.hash = options.hash;
          }
          return retrieveRemote(url.format(redirect), weight, height, extention);
        }

        // The image must return status code 200.
        if (response.statusCode !== 200) {
          return res.status(404).send('Expected response code 200, got ' + response.statusCode);
        }

        // The image must be a valid content type.
        // @see http://nodejs.org/api/http.html#http_request_headers
        var mimeType;
        if (extension) {
          mimeType = mime.lookup(extension);
        }
        else {
          mimeType = (response.headers['content-type'] || '').replace(/;.*/, '');
          extension = mime.extension(mimeType);
        }
        if (mimeTypes.indexOf(mimeType) === -1) {
          return res.status(404).send('Expected content type ' + mimeTypes.join(', ') + ', got ' + mimeType);
        }

        // @see https://github.com/aheckmann/gm#constructor
        var im = imageMagick(response, 'image.' + extension);
          // @see http://www.imagemagick.org/Usage/thumbnails/#cut
        if (width) {
          if (height) {
            im.resize(width, height + '^>');
          } else {
            im.resize(width);
          }
        }

        im.gravity('Center'); // faces are most often near the center
        if (width && height) {
          im.extent(width, height);
        }

        im.stream(function (err, stdout, stderr) {
            if (err) return next(err);
            // Log errors in production.
            stderr.pipe(process.stderr);
            // @see http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html
            res.writeHead(200, {
              'Content-Type': mimeType,
              'Cache-Control': 'max-age=31536000, public', // 1 year
            });
            stdout.pipe(res);
          });
      }).on('error', next);

  // Timeout after five seconds. Better luck next time.
  request.setTimeout(delay, function () {
    timeout = true; // if we abort, we'll get a "socket hang up" error
    return res.status(504).send();
  });
}

module.exports = function () {
  app.get('/:url', function (req, res, next) {
    // Validate parameters.
    if (whitelist.length) {
      var parts = url.parse(req.params.url);
      if (parts.hostname) {
        var any = false, _i, _len;
        if (typeof whitelist === 'string') {
          whitelist = whitelist.split(',');
        }
        for (_i = 0, _len = whitelist.length; _i < _len; _i++) {
          if (typeof whitelist[_i] === 'string') {
            // Escape periods and add anchor.
            whitelist[_i] = new RegExp(whitelist[_i].replace('.', '\\.') + '$')
          }
          if (whitelist[_i].test(parts.hostname)) {
            any = true;
            break;
          }
        }
        if (!any) { // if none
          return res.status(404).send('Expected URI host to be whitelisted');
        }
      }
    }
    if (isNaN(parseInt(width))) {
      return res.status(404).send('Expected width to be an integer');
    }
    if (parseInt(width) > 1000) {
      return res.status(404).send('Expected width to be less than or equal to 1000');
    }
    if (isNaN(parseInt(height))) {
      return res.status(404).send('Expected height to be an integer');
    }
    if (parseInt(height) > 1000) {
      return res.status(404).send('Expected height to be less than or equal to 1000');
    }
    retrieveRemote('http://s3.amazonaws.com/qmerce-static-media/' + req.params.url, null, null, null);
  });

  app.get('/:url/:width/:height.:extension?', function (req, res, next) {
    var width = req.params.width
      , height = req.params.height
      , extension = req.params.extension;

    // Validate parameters.
    if (whitelist.length) {
      var parts = url.parse(req.params.url);
      if (parts.hostname) {
        var any = false, _i, _len;
        if (typeof whitelist === 'string') {
          whitelist = whitelist.split(',');
        }
        for (_i = 0, _len = whitelist.length; _i < _len; _i++) {
          if (typeof whitelist[_i] === 'string') {
            // Escape periods and add anchor.
            whitelist[_i] = new RegExp(whitelist[_i].replace('.', '\\.') + '$')
          }
          if (whitelist[_i].test(parts.hostname)) {
            any = true;
            break;
          }
        }
        if (!any) { // if none
          return res.status(404).send('Expected URI host to be whitelisted');
        }
      }
    }
    if (isNaN(parseInt(width))) {
      return res.status(404).send('Expected width to be an integer');
    }
    if (parseInt(width) > 1000) {
      return res.status(404).send('Expected width to be less than or equal to 1000');
    }
    if (isNaN(parseInt(height))) {
      return res.status(404).send('Expected height to be an integer');
    }
    if (parseInt(height) > 1000) {
      return res.status(404).send('Expected height to be less than or equal to 1000');
    }
    retrieveRemote('http://s3.amazonaws.com/qmerce-static-media/' + req.params.url, width, height, extension);
  });

  return app;
};
<|endoftext|>


<commit_before>'use strict';
var ngram = require('../util/ngram'),
    redis = require("redis"),
    client = redis.createClient(),
    fs = require('fs'),
    byline = require('byline');

var index = {};

var indexing = function(no, str) {
  ngram(str, 2).forEach(function(gram, index, array) {
    client.sadd(gram, no);
    client.append(gram + "-" + no, index + ",");
  });
}

index.redis = function(path) {
  client.flushdb(function(err, didSucceed) {
    var stream = byline(fs.createReadStream(path, { encoding: 'utf8' }));

    var i=0;
    stream.on('data', function(line) {
      indexing(i, line);
      i++;
    });

    stream.on('finish', function(){
      client.end();
    });
  });
}

module.exports = index;

<commit_msg>変数名修正<commit_after>'use strict';
var ngram = require('../util/ngram'),
    redis = require("redis"),
    client = redis.createClient(),
    fs = require('fs'),
    byline = require('byline');

var index = {};

var indexing = function(no, str) {
  ngram(str, 2).forEach(function(gram, pos, array) {
    client.sadd(gram, no);
    client.append(gram + "-" + no, pos + ",");
  });
}

index.redis = function(path) {
  client.flushdb(function(err, didSucceed) {
    var stream = byline(fs.createReadStream(path, { encoding: 'utf8' }));

    var i=0;
    stream.on('data', function(line) {
      indexing(i, line);
      i++;
    });

    stream.on('finish', function(){
      client.end();
    });
  });
}

module.exports = index;

<|endoftext|>


<commit_before>"use strict";

/*global nodeca, _*/

// stdlib
var createHttpServer = require('http').createServer;

// 3rd-party
var Async = require('nlib').Vendor.Async;

// internal
var listener = require('./server/http');

////////////////////////////////////////////////////////////////////////////////

// helper that starts http server and waits for it to bind to specified host and
// port (see configuration listen section).
//
function startServer(host, port, next) {
  var server = createHttpServer();

  function handle_server_error(err) {
    var err_prefix = "Can't bind to <" + host + "> with port <" + port + ">: ";

    if ('EADDRINUSE' === err.code) {
      next(err_prefix + 'Address in use...');
      return;
    }

    if ('EADDRNOTAVAIL' === err.code) {
      // system has no such ip address
      next(err_prefix + 'Address is not available...');
      return;
    }

    if ('ENOENT' === err.code) {
      // failed resolve hostname to ip address
      next(err_prefix + "Failed to resolve IP address...");
      return;
    }

    // unexpected / unknown error
    next(err_prefix + err);
  }

  server.on('error', handle_server_error);

  // start server
  server.listen(port, host, function () {
    server.removeListener('error', handle_server_error);
    next(null, server);
  });
}

// MODULE EXPORTS //////////////////////////////////////////////////////////////

// starts http server and attach application HTTP server and Faye realtime
// servers to it
//
module.exports = function (next) {
  // create server
  var host = nodeca.config.router.bind['default'].listen.split(':').shift() || 'localhost';
  var port = nodeca.config.router.bind['default'].listen.split(':').pop() || 3000;

  try {
    // add support for webkit devtools
    require('webkit-devtools-agent');
    nodeca.logger.info('webkit-devtools-agent enabled');
  } catch (err) {
    // do nothing
    nodeca.logger.warn('webkit-devtools-agent disabled');
  }

  startServer(host, port, function (err, server) {
    if (err) {
      next(err);
      return;
    }

    listener.attach(server, next);
  });
};
<commit_msg>Listen to all requested listen points<commit_after>"use strict";

/*global nodeca, _*/

// stdlib
var createHttpServer = require('http').createServer;

// 3rd-party
var async   = require('nlib').Vendor.Async;
var treeGet = require('nlib').Support.tree.get;

// internal
var listener = require('./server/http');

////////////////////////////////////////////////////////////////////////////////

// helper that starts http server and waits for it to bind to specified host and
// port (see configuration listen section).
//
function startServer(address, port, next) {
  var server = createHttpServer();

  function handle_server_error(err) {
    var err_prefix = "Can't bind to <" + address + "> with port <" + port + ">: ";

    if ('EADDRINUSE' === err.code) {
      next(err_prefix + 'Address in use...');
      return;
    }

    if ('EADDRNOTAVAIL' === err.code) {
      // system has no such ip address
      next(err_prefix + 'Address is not available...');
      return;
    }

    if ('ENOENT' === err.code) {
      // failed resolve addressname to ip address
      next(err_prefix + "Failed to resolve IP address...");
      return;
    }

    // unexpected / unknown error
    next(err_prefix + err);
  }

  server.on('error', handle_server_error);

  // start server
  server.listen(port, address, function () {
    server.removeListener('error', handle_server_error);
    next(null, server);
  });
}

// Parse binding config and returns a parsed map:
//
//  {
//    '127.0.0.1:3000': {
//      address: '127.0.0.1',
//      port:    3000,
//      ssl:     false,
//      domains: [ 'localhost', ... ]
//    },
//    // ...
//  }
//
function extractBindings(config) {
  var result = {};

  _.each(config, function (options, key) {
    var domain;

    if ('_' === key) {
      // skip special case keyword
      return;
    }

    if (!result[options.listen]) {
      result[options.listen] = {
        domains:  [],
        address:  options.listen.split(':').shift() || '0.0.0.0',
        port:     options.listen.split(':').pop() || '3000'
      };
    }

    result[options.listen].ssl = !!(result[options.listen].ssl || options.ssl);

    domain = (/^(?:https?:)?\/\/([^\/]+)(\/|$)/).exec(options.mount)[1];
    if (-1 === result[options.listen].domains.indexOf(domain)) {
      result[options.listen].domains.push(domain);
    }
  });

  return result;
}

// Default action when host is not supposed to be served by listener
//
function domainNotFound(params, callback) {
  /*jshint validthis:true*/
  var hostname = (this.origin.http || this.origin.rpc).req.headers.host;
  callback(new Error('Hostname is not allowed: ' + hostname));
}

// MODULE EXPORTS //////////////////////////////////////////////////////////////

// starts http server and attach application HTTP server and Faye realtime
// servers to it
//
module.exports = function (next) {
  var config          = nodeca.config.router.bind,
      bindings        = extractBindings(config),
      invalid_domain  = treeGet(nodeca.server, config._, domainNotFound);

  try {
    // add support for webkit devtools
    require('webkit-devtools-agent');
    nodeca.logger.info('webkit-devtools-agent enabled');
  } catch (err) {
    // do nothing
    nodeca.logger.warn('webkit-devtools-agent disabled');
  }

  async.forEachSeries(_.keys(bindings), function (point, nextPoint) {
    var options = bindings[point];

    startServer(options.address, options.port, function (err, server) {
      if (err) {
        nextPoint(err);
        return;
      }

      nodeca.logger.info('Listening on ' + options.address + ':' + options.port);
      listener.attach(server, nextPoint);
    });
  }, next);
};
<|endoftext|>


<commit_before>'use strict'

const Button = require('./button');
const isTouchDevice = 'd' in document.documentElement;

module.exports = (scope, inst, options) => {

    const network = inst.network;

    if (isTouchDevice) {
        // Highlight traceback on click
        network.on('click', traceBack);
    } else {
        // Highlight traceback on hover
        network.on('hoverNode', function(params) {
            traceBack(params.node);
        });
        // un-traceback on un-hover
        network.on('blurNode', resetTrace);
    }

    let threshold = 200;
    let eventTime = 0;

    // Click > Expand/Collaps sub tree
    network.on('click', event => {
        let t = new Date();
        setTimeout(() => {
            if (t - eventTime > threshold) {
                expandCollapse(scope, inst, event);
            }
        }, threshold);
    });

    // Click & Hold > show context menu
    network.on('hold', event => {
        eventTime = new Date();
        contextMenu(scope, inst, event);
    });

    // 2x Click > show detail form
    network.on('doubleClick', event => {
        eventTime = new Date();
        detailView(scope, inst, event);
    });

    // Render context menus
    inst.contextMenus = {};
    let canvas = network.canvas.frame.canvas;

    /* TODO context menu needs refactoring */

    // draw buttons
    network.on('afterDrawing', (ctx) => {

        let nodeIds = Object.keys(inst.contextMenus);

        nodeIds.forEach(nodeId => {
            let node = inst.nodes.get(nodeId);
            if (!node || !inst.types[node.type]) {
                return;
            }

            let actions = inst.types[node.type].actions;

            if (!actions || !Object.keys(actions).length) {
                return;
            }

            // compute the button positions
            let menuY = network.getBoundingBox([nodeId]).bottom + 10;
            let menuX = inst.network.getPositions([nodeId])[nodeId].x;

            // create the necessary buttons and place them
            let buttonsWidth = 0;
            let buttons = [];
            Object.keys(actions).forEach(actionName => {
                let action = actions[actionName];
                let button = new Button(ctx, action.label, {
                    color: action.color,
                    fontColor: action.fontColor,
                    hoverColor: action.hoverColor
                });

                // append graph info to the button
                button.node = nodeId;
                button.event = actionName;

                buttonsWidth += buttonsWidth === 0 ? button.width : button.width + 10;
                buttons.push(button);
            });

            // start placing the buttons
            let currentX = menuX - buttonsWidth / 2;
            buttons.forEach(button => {
                button.draw(currentX, menuY);
                currentX += button.width + 10;
            });

            inst.contextMenus[nodeId] = buttons;
        });

        ctx.save();
    });

    // listen for events on context menus
    canvas.addEventListener('mousemove', event => {
        let mouse = network.DOMtoCanvas({x: event.clientX, y: event.clientY});

        Object.keys(inst.contextMenus).forEach(nodeId => {
            let buttons = inst.contextMenus[nodeId];
            buttons.forEach(button => {
                if (mouse.x >= button.x && mouse.x <= button.x + button.width && mouse.y >= button.y && mouse.y <= button.y + button.height) {
                    button.mouseOver();
                } else {
                    button.mouseAway();
                }
            });
        });
    }, false);

    // listen for click event on contex buttons
    canvas.addEventListener('mouseup', event => {
        let mouse = network.DOMtoCanvas({x: event.clientX, y: event.clientY});

        Object.keys(inst.contextMenus).forEach(nodeId => {
            let buttons = inst.contextMenus[nodeId];
            buttons.forEach(button => {
                if (mouse.x >= button.x && mouse.x <= button.x + button.width && mouse.y >= button.y && mouse.y <= button.y + button.height) {
                    button.mouseUp();
                }
            });
        });
    }, false);

    // listen for click event on contex buttons
    canvas.addEventListener('mousedown', event => {
        let mouse = network.DOMtoCanvas({x: event.clientX, y: event.clientY});

        Object.keys(inst.contextMenus).forEach(nodeId => {
            let buttons = inst.contextMenus[nodeId];
            buttons.forEach(button => {
                if (mouse.x >= button.x && mouse.x <= button.x + button.width && mouse.y >= button.y && mouse.y <= button.y + button.height) {
                    button.mouseDown();
                    scope.flow(inst._name + '/' + button.event).write({node: button.node});
                }
            });
        });
    }, false);
};

function expandCollapse (scope, inst, event) {

    const node = event.nodes.length ? inst.nodes.get(event.nodes[0]) : null;

    if (!node) {
        return;
    }

    switch (node.state) {
        case 'expand':
            node.state = 'collapse';
            break;
        case 'loading':
            return;
        default:
            node.state = 'expand';
    }

    // update position before updating the graph
    if (node.id) {
        let pos = inst.network.getPositions(node.id)[node.id];
        node.x = pos.x;
        node.y = pos.y;
    }

    inst.nodes.update(node);

    scope.flow(inst._name + '/' + node.state).write({node: node});
}

function contextMenu (scope, inst, event) {

    const node = event.nodes.length ? inst.nodes.get(event.nodes[0]) : null;

    if (!node || !inst.types[node.type]) {
        return;
    }

    // do not add menu if no actions defined
    let actions = inst.types[node.type].actions;
    if (!actions || !Object.keys(actions).length) {
        return;
    }

    if (!inst.contextMenus[node.id]) {
        inst.contextMenus[node.id] = {};
    } else {
        delete inst.contextMenus[node.id];
    }
}

function detailView () {console.log('Detail view:', arguments)}
function traceBack () {

    //console.log('Trace back:', arguments);

    // TODO touch traceback
    /*if (params.nodes.length) { //Was the click on a node?
        //The node clicked
        var page = params.nodes[0];
        //Highlight in blue all nodes tracing back to central node
        traceBack(page);
    } else {
        resetProperties();
    }*/

    /*if (node != selectedNode) {
        selectedNode = node;
        resetProperties();
        tracenodes = getTraceBackNodes(node);
        traceedges = getTraceBackEdges(tracenodes);
        //Color nodes yellow
        var modnodes = tracenodes.map(function(i){return nodes.get(i);});
        colorNodes(modnodes, 1);
        //Widen edges
        var modedges = traceedges.map(function(i){
            var e=edges.get(i);
            e.color={inherit:"to"};
                return e;
        });
        edgesWidth(modedges, 5);
    }*/
}

function resetTrace () {

    //console.log('Reset trace:', arguments);

    /*if (!isReset) {
        selectedNode = null;
        //Reset node color
        var modnodes = tracenodes.map(function(i){return nodes.get(i);});
        colorNodes(modnodes, 0);
        //Reset edge width and color
        var modedges = traceedges.map(function(i){
            var e=edges.get(i);
            e.color=getEdgeColor(nodes.get(e.to).level);
            return e;
        });
        edgesWidth(modedges, 1);
        tracenodes = [];
        traceedges = [];
    }*/
}
<commit_msg>fix "Button" module require<commit_after>'use strict'

const Button = require('./Button');
const isTouchDevice = 'd' in document.documentElement;

module.exports = (scope, inst, options) => {

    const network = inst.network;

    if (isTouchDevice) {
        // Highlight traceback on click
        network.on('click', traceBack);
    } else {
        // Highlight traceback on hover
        network.on('hoverNode', function(params) {
            traceBack(params.node);
        });
        // un-traceback on un-hover
        network.on('blurNode', resetTrace);
    }

    let threshold = 200;
    let eventTime = 0;

    // Click > Expand/Collaps sub tree
    network.on('click', event => {
        let t = new Date();
        setTimeout(() => {
            if (t - eventTime > threshold) {
                expandCollapse(scope, inst, event);
            }
        }, threshold);
    });

    // Click & Hold > show context menu
    network.on('hold', event => {
        eventTime = new Date();
        contextMenu(scope, inst, event);
    });

    // 2x Click > show detail form
    network.on('doubleClick', event => {
        eventTime = new Date();
        detailView(scope, inst, event);
    });

    // Render context menus
    inst.contextMenus = {};
    let canvas = network.canvas.frame.canvas;

    /* TODO context menu needs refactoring */

    // draw buttons
    network.on('afterDrawing', (ctx) => {

        let nodeIds = Object.keys(inst.contextMenus);

        nodeIds.forEach(nodeId => {
            let node = inst.nodes.get(nodeId);
            if (!node || !inst.types[node.type]) {
                return;
            }

            let actions = inst.types[node.type].actions;

            if (!actions || !Object.keys(actions).length) {
                return;
            }

            // compute the button positions
            let menuY = network.getBoundingBox([nodeId]).bottom + 10;
            let menuX = inst.network.getPositions([nodeId])[nodeId].x;

            // create the necessary buttons and place them
            let buttonsWidth = 0;
            let buttons = [];
            Object.keys(actions).forEach(actionName => {
                let action = actions[actionName];
                let button = new Button(ctx, action.label, {
                    color: action.color,
                    fontColor: action.fontColor,
                    hoverColor: action.hoverColor
                });

                // append graph info to the button
                button.node = nodeId;
                button.event = actionName;

                buttonsWidth += buttonsWidth === 0 ? button.width : button.width + 10;
                buttons.push(button);
            });

            // start placing the buttons
            let currentX = menuX - buttonsWidth / 2;
            buttons.forEach(button => {
                button.draw(currentX, menuY);
                currentX += button.width + 10;
            });

            inst.contextMenus[nodeId] = buttons;
        });

        ctx.save();
    });

    // listen for events on context menus
    canvas.addEventListener('mousemove', event => {
        let mouse = network.DOMtoCanvas({x: event.clientX, y: event.clientY});

        Object.keys(inst.contextMenus).forEach(nodeId => {
            let buttons = inst.contextMenus[nodeId];
            buttons.forEach(button => {
                if (mouse.x >= button.x && mouse.x <= button.x + button.width && mouse.y >= button.y && mouse.y <= button.y + button.height) {
                    button.mouseOver();
                } else {
                    button.mouseAway();
                }
            });
        });
    }, false);

    // listen for click event on contex buttons
    canvas.addEventListener('mouseup', event => {
        let mouse = network.DOMtoCanvas({x: event.clientX, y: event.clientY});

        Object.keys(inst.contextMenus).forEach(nodeId => {
            let buttons = inst.contextMenus[nodeId];
            buttons.forEach(button => {
                if (mouse.x >= button.x && mouse.x <= button.x + button.width && mouse.y >= button.y && mouse.y <= button.y + button.height) {
                    button.mouseUp();
                }
            });
        });
    }, false);

    // listen for click event on contex buttons
    canvas.addEventListener('mousedown', event => {
        let mouse = network.DOMtoCanvas({x: event.clientX, y: event.clientY});

        Object.keys(inst.contextMenus).forEach(nodeId => {
            let buttons = inst.contextMenus[nodeId];
            buttons.forEach(button => {
                if (mouse.x >= button.x && mouse.x <= button.x + button.width && mouse.y >= button.y && mouse.y <= button.y + button.height) {
                    button.mouseDown();
                    scope.flow(inst._name + '/' + button.event).write({node: button.node});
                }
            });
        });
    }, false);
};

function expandCollapse (scope, inst, event) {

    const node = event.nodes.length ? inst.nodes.get(event.nodes[0]) : null;

    if (!node) {
        return;
    }

    switch (node.state) {
        case 'expand':
            node.state = 'collapse';
            break;
        case 'loading':
            return;
        default:
            node.state = 'expand';
    }

    // update position before updating the graph
    if (node.id) {
        let pos = inst.network.getPositions(node.id)[node.id];
        node.x = pos.x;
        node.y = pos.y;
    }

    inst.nodes.update(node);

    scope.flow(inst._name + '/' + node.state).write({node: node});
}

function contextMenu (scope, inst, event) {

    const node = event.nodes.length ? inst.nodes.get(event.nodes[0]) : null;

    if (!node || !inst.types[node.type]) {
        return;
    }

    // do not add menu if no actions defined
    let actions = inst.types[node.type].actions;
    if (!actions || !Object.keys(actions).length) {
        return;
    }

    if (!inst.contextMenus[node.id]) {
        inst.contextMenus[node.id] = {};
    } else {
        delete inst.contextMenus[node.id];
    }
}

function detailView () {console.log('Detail view:', arguments)}
function traceBack () {

    //console.log('Trace back:', arguments);

    // TODO touch traceback
    /*if (params.nodes.length) { //Was the click on a node?
        //The node clicked
        var page = params.nodes[0];
        //Highlight in blue all nodes tracing back to central node
        traceBack(page);
    } else {
        resetProperties();
    }*/

    /*if (node != selectedNode) {
        selectedNode = node;
        resetProperties();
        tracenodes = getTraceBackNodes(node);
        traceedges = getTraceBackEdges(tracenodes);
        //Color nodes yellow
        var modnodes = tracenodes.map(function(i){return nodes.get(i);});
        colorNodes(modnodes, 1);
        //Widen edges
        var modedges = traceedges.map(function(i){
            var e=edges.get(i);
            e.color={inherit:"to"};
                return e;
        });
        edgesWidth(modedges, 5);
    }*/
}

function resetTrace () {

    //console.log('Reset trace:', arguments);

    /*if (!isReset) {
        selectedNode = null;
        //Reset node color
        var modnodes = tracenodes.map(function(i){return nodes.get(i);});
        colorNodes(modnodes, 0);
        //Reset edge width and color
        var modedges = traceedges.map(function(i){
            var e=edges.get(i);
            e.color=getEdgeColor(nodes.get(e.to).level);
            return e;
        });
        edgesWidth(modedges, 1);
        tracenodes = [];
        traceedges = [];
    }*/
}
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor';

/**
* @summary from a given ethereum address creates a user in the db
* @param {string} address 0x ethereum address
* @param {string} settings configuration object
*/
const _migrateAddress = (address, settings) => {
  const voter = Meteor.users.find({ 'profile.wallet.reserves': { $elemMatch: { publicAddress: address } } }).fetch();

  console.log(voter);

  // add new voter
  if (!voter.length) {
    const template = {
      username: address,
      profile: {
        configured: true,
        menu: [],
        picture: '/images/noprofile.png',
        wallet: {
          currency: 'WETH',
          ledger: [],
          placed: 0,
          available: 0,
          balance: 0,
          address: [],
          reserves: [{
            publicAddress: address,
            available: 0,
            balance: 0,
            token: 'WETH',
            placed: 0,
          }],
        },
      },
      createdAt: new Date(),
    };
    template.profile = Object.assign(template.profile, settings.profile);
    const voterId = Meteor.users.insert(template);
    console.log(`[web3] Inserted new user ${voterId}`);
  }
};

const _parseMapCode = (instruction, parameters) => {

}

export const parseMapCode = _parseMapCode;
export const migrateAddress = _migrateAddress;
<commit_msg>updates profiles if already in db<commit_after>import { Meteor } from 'meteor/meteor';

/**
* @summary from a given ethereum address creates a user in the db
* @param {string} address 0x ethereum address
* @param {string} settings configuration object
*/
const _migrateAddress = (address, settings) => {
  console.log(`[web3] Migrating address ${address}...`);
  const voter = Meteor.users.find({ username: address.toLowerCase() }).fetch();

  console.log(voter.length);

  // add new voter
  if (voter.length === 0) {
    const template = {
      username: address.toLowerCase(),
      profile: {
        configured: true,
        menu: [],
        picture: '/images/noprofile.png',
        wallet: {
          currency: 'WETH',
          ledger: [],
          placed: 0,
          available: 0,
          balance: 0,
          address: [],
          reserves: [{
            publicAddress: address,
            available: 0,
            balance: 0,
            token: 'WETH',
            placed: 0,
          }],
        },
      },
      createdAt: new Date(),
    };
    template.profile = Object.assign(template.profile, settings.profile);
    const voterId = Meteor.users.insert(template);
    console.log(`[web3] Inserted new user ${voterId}`);
  } else {
    console.log(`[web3] Updated user with new settings...`);
    Meteor.users.update({ _id: voter._id }, { $set: { profile: settings.profile } });
  }
};

const _parseMapCode = (instruction, parameters) => {

}

export const parseMapCode = _parseMapCode;
export const migrateAddress = _migrateAddress;
<|endoftext|>


<commit_before>var cp = require('child_process');
var path = require('path');
var zipper = require('zip-local');
var router = require('./router.js');

/*
 * packs the app into a zip file
 * @param job {Object}: the job specs
 * @return {Object}: a packed app descriptor
 */
function pack(job) {
    var app = path.parse(job.app);
    var packed_buff = zipper.sync.zip(app.dir).compress().memory();

    var descriptor = {
        entry: app.base,
        data: packed_buff.toString('base64')
    }

    return descriptor;
}

/*
 * runs the given subjob on the local machine
 * @param subjob {Object}: subjob description
 */
function runLocally(subjob) {

    for(var i = subjob.startId; i < subjob.size; i++) {

        var jobInstance = cp.spawn('node', [subjob.app, subjob.size, i], {
            stdio: [null, null, null, 'ipc']
        });

        // register a handler for instance's stdout data
        // reports back to the parent klyng process
        jobInstance.stdout.on('data', function(log) {
            log = log.toString().replace('\n', '');
            router.routeToParent({type: "process:stdout", data: {line: log}});
        });

        // register a handler for instance's stderr data
        // reports back to the parent klyng process
        jobInstance.stderr.on('data', function(elog) {
            elog = elog.toString().replace('\n', '');
            router.routeToParent({type: "process:stderr", data: {line: elog}});
        })

        // register a handler for instance exit event
        // reports back to the parent klyng process
        jobInstance.on('exit', function(code) {
            router.routeToParent({type: "process:exit", data: {code: code}});
        });

        // register a handler for instance's messages
        jobInstance.on('message', function(msg) {
            if(msg.type === 'klyng:msg') {
                router.routeTo(msg.header.to, msg);
            }
        });

        jobInstance.unref();

        router.setLocalChannel(i, jobInstance);
    }
};

module.exports = {
    pack: pack,
    runLocally: runLocally
};
<commit_msg>implemented unpaking functionality<commit_after>var cp = require('child_process');
var path = require('path');
var fs = require('fs');
var zipper = require('zip-local');
var router = require('./router.js');

/*
 * packs the app into a zip file
 * @param job {Object}: the job specs
 * @return {Object}: a packed app descriptor
 */
function pack(job) {
    var app = path.parse(job.app);
    var packed_buff = zipper.sync.zip(app.dir).compress().memory();

    var descriptor = {
        entry: app.base,
        data: packed_buff.toString('base64')
    }

    return descriptor;
}

/*
 * unpacks a packed app from remote root
 * @param app {Object}: the app descriptor recived from remote root
 */
 function unpack(app) {
     return new Promise(function(resolve, reject) {
         // check if the unpaking directory exists
         fs.stat('./.unpacks', function(err, stats) {
             if(err) {
                 fs.mkdirSync('./.unpacks');
             }

             var data = new Buffer(app.data, 'base64');
             var appdir = './.unpacks/app_' + Date.now();
             fs.mkdirSync(appdir);

             zipper.unzip(data, function(unzipped) {
                 unzipped.save(appdir, function() {
                     resolve(appdir + "/" + app.entry);
                 });
             });
         });
     });
 }

/*
 * runs the given subjob on the local machine
 * @param subjob {Object}: subjob description
 */
function runLocally(subjob) {

    for(var i = subjob.startId; i < subjob.size; i++) {

        var jobInstance = cp.spawn('node', [subjob.app, subjob.size, i], {
            stdio: [null, null, null, 'ipc']
        });

        // register a handler for instance's stdout data
        // reports back to the parent klyng process
        jobInstance.stdout.on('data', function(log) {
            log = log.toString().replace('\n', '');
            router.routeToParent({type: "process:stdout", data: {line: log}});
        });

        // register a handler for instance's stderr data
        // reports back to the parent klyng process
        jobInstance.stderr.on('data', function(elog) {
            elog = elog.toString().replace('\n', '');
            router.routeToParent({type: "process:stderr", data: {line: elog}});
        })

        // register a handler for instance exit event
        // reports back to the parent klyng process
        jobInstance.on('exit', function(code) {
            router.routeToParent({type: "process:exit", data: {code: code}});
        });

        // register a handler for instance's messages
        jobInstance.on('message', function(msg) {
            if(msg.type === 'klyng:msg') {
                router.routeTo(msg.header.to, msg);
            }
        });

        jobInstance.unref();

        router.setLocalChannel(i, jobInstance);
    }
};

module.exports = {
    pack: pack,
    unpack: unpack,
    runLocally: runLocally
};
<|endoftext|>


<commit_before>var _ = require('lodash'),
    Events = require('events'),
    exec = require('../exec').exec,
    Nipple = require('nipple'),
    request = require('request');

var CACHABLE_STATUS = {
  200: true,
  203: true,
  206: true,
  300: true,
  301: true,
  410: true
};

// TODO : Remove this in favor of HAPI smart caching
// TODO : Make this conditional as users that implement user behavior on the server will not
// want this.
var cache = {};

module.exports = exports = function($) {
  var ajax = new Events.EventEmitter(),
      requests,
      log,
      minimumCache;

  ajax.minimumCache = function() {
    return minimumCache;
  };

  ajax.toJSON = function() {
    // Custom seralization so we don't have to bounce back and forth between object
    // and string representation
    // NOTE: This assumes that no URLS are going to have the literal " (or any other non-encoded
    // javascript illegal characters)
    return '{'
        + _.map(log, function(value, key) { return '"' + key + '": ' + value; }).join(',')
      + '}';
  };
  ajax.allComplete = function() {
    return !_.any(log, function(value) { return value === null; });
  };
  ajax.reset = function() {
    _.each(requests, function(request) {
      request.abort();
    });

    requests = [];
    log = {};
    minimumCache = {
      'no-cache': false,
      private: false,
      expires: Number.MAX_VALUE
    };

    this.removeAllListeners();
  };

  $.ajax = function(options) {
    var jsonp;
    if (/=\?/.test(options.url)) {
      options.url = options.url.replace('=?', '=$jsonp$');
      jsonp = true;
    }

    var xhr = {
      readyState: 2,

      abort: function() {
        if (xhr.readyState === 2) {
          req.abort();
          callback('abort', undefined, '');
        }
      }
    };

    function callback(err, response, body) {
      // TODO : Handle any cookie info that might be necessary
      exec(function() {
        var type,
            fromCache = false;
        try {
          xhr.readyState = 4;
          xhr.status = (response && response.statusCode) || 0;
          xhr.responseText = body;

          if (!err && response.statusCode === 200) {
            if (_.isString(body) || Buffer.isBuffer(body)) {
              try {
                if (jsonp) {
                  body = body.replace(/.*?\$jsonp\$\((.*)\).*?$/, '$1');
                  xhr.responseText = body;
                }

                body = JSON.parse(body);
              } catch (err) {
                body = undefined;
                type = 'parsererror';
                return options.error && options.error(xhr, type, err);
              }
            } else {
              fromCache = true;
            }

            type = 'success';
            options.success && options.success(body, type, xhr);
          } else {
            body = false;
            type = err === 'abort' ? err : 'error';
            options.error && options.error(xhr, type, err);
          }
        } finally {
          options.complete && options.complete(xhr, type);

          // Update our minimum caching duration for the entire response
          var cachingInfo = (response && response.cachingInfo) || exports.cachingInfo(response);
          exports.calcCache(minimumCache, cachingInfo);

          if (!fromCache && type === 'success' && requestType === 'GET') {
            // Reparsing here to ensure that we have a clean object for future users
            cache[options.url] = body ? {caching: cachingInfo, data: JSON.parse(xhr.responseText)} : false;
          }

          // Store the response in the request log to send to the user
          if (type === 'success') {
            log[options.cacheUrl || options.url] = xhr.responseText || false;
            if (options.cacheUrl && options.cacheUrl !== options.url) {
              delete log[options.url];
            }
          } else {
            delete log[options.url];
          }

          ajax.emit('complete', options.url);
        }
      });
    }

    var requestType = options.type || 'GET';
    if (requestType === 'GET' && cache[options.url]) {
      setImmediate(function() {
        var cacheEntry = cache[options.url];
        callback(
            undefined,
            {statusCode: 200, cachingInfo: cacheEntry.caching},
            _.cloneDeep(cacheEntry.data));
      });
      xhr.readyState = 4;
      return xhr;
    }

    // Mark the request as in progress
    log[options.url] = null;

    var req = request({
        method: requestType,
        url: options.url,
        form: options.data
      },
      callback);
    requests.push(xhr);

    return xhr;
  };

  // Ensure that everything is initialized
  ajax.reset();

  return ajax;
};

exports.cachingInfo = function(res) {
  // Will failover to no-cache state
  res = res || {headers: {}, request: {}};

  var cacheControl = res.headers['cache-control'],
      expires = res.headers.expires,
      pragma = res.headers.pragma,

      cacheable = CACHABLE_STATUS[res.statusCode] && res.request.method === 'GET',

      noCache,
      expires;

  if (cacheControl) {
    cacheControl = Nipple.parseCacheControl(cacheControl);

    noCache = (!cacheable && !cacheControl.public) || !!cacheControl['no-cache'];

    // Converting to explicit timeout so we don't inadvertantly extend the cache
    // lifecycle when serving cached responses in the future
    expires = Date.now() + parseInt(cacheControl['max-age'], 0)*1000;
  } else {
    noCache = !cacheable || pragma === 'no-cache';
    expires = Date.parse(expires).valueOf();
  }

  if (isNaN(expires) || noCache) {
    expires = undefined;
  }

  return {
    'no-cache': !!noCache,
    private: !!(cacheControl && cacheControl.private),
    expires: expires
  };
};

exports.calcCache = function(minimumCache, cachingInfo) {
  minimumCache['no-cache'] = minimumCache['no-cache'] || cachingInfo['no-cache'];
  minimumCache.private = minimumCache.private || cachingInfo.private;
  minimumCache.expires = Math.min(minimumCache.expires, cachingInfo.expires);
  if (isNaN(minimumCache.expires) || minimumCache['no-cache']) {
    minimumCache.expires = undefined;
  }
};

exports.reset = function() {
  cache = {};
};

<commit_msg>Add method comments to ajax helpers<commit_after>var _ = require('lodash'),
    Events = require('events'),
    exec = require('../exec').exec,
    Nipple = require('nipple'),
    request = require('request');

var CACHABLE_STATUS = {
  200: true,
  203: true,
  206: true,
  300: true,
  301: true,
  410: true
};

// TODO : Remove this in favor of HAPI smart caching
// TODO : Make this conditional as users that implement user behavior on the server will not
// want this.
var cache = {};

module.exports = exports = function($) {
  var ajax = new Events.EventEmitter(),
      requests,
      log,
      minimumCache;

  ajax.minimumCache = function() {
    return minimumCache;
  };

  ajax.toJSON = function() {
    // Custom seralization so we don't have to bounce back and forth between object
    // and string representation
    // NOTE: This assumes that no URLS are going to have the literal " (or any other non-encoded
    // javascript illegal characters)
    return '{'
        + _.map(log, function(value, key) { return '"' + key + '": ' + value; }).join(',')
      + '}';
  };
  ajax.allComplete = function() {
    return !_.any(log, function(value) { return value === null; });
  };
  ajax.reset = function() {
    _.each(requests, function(request) {
      request.abort();
    });

    requests = [];
    log = {};
    minimumCache = {
      'no-cache': false,
      private: false,
      expires: Number.MAX_VALUE
    };

    this.removeAllListeners();
  };

  $.ajax = function(options) {
    var jsonp;
    if (/=\?/.test(options.url)) {
      options.url = options.url.replace('=?', '=$jsonp$');
      jsonp = true;
    }

    var xhr = {
      readyState: 2,

      abort: function() {
        if (xhr.readyState === 2) {
          req.abort();
          callback('abort', undefined, '');
        }
      }
    };

    function callback(err, response, body) {
      // TODO : Handle any cookie info that might be necessary
      exec(function() {
        var type,
            fromCache = false;
        try {
          xhr.readyState = 4;
          xhr.status = (response && response.statusCode) || 0;
          xhr.responseText = body;

          if (!err && response.statusCode === 200) {
            if (_.isString(body) || Buffer.isBuffer(body)) {
              try {
                if (jsonp) {
                  body = body.replace(/.*?\$jsonp\$\((.*)\).*?$/, '$1');
                  xhr.responseText = body;
                }

                body = JSON.parse(body);
              } catch (err) {
                body = undefined;
                type = 'parsererror';
                return options.error && options.error(xhr, type, err);
              }
            } else {
              fromCache = true;
            }

            type = 'success';
            options.success && options.success(body, type, xhr);
          } else {
            body = false;
            type = err === 'abort' ? err : 'error';
            options.error && options.error(xhr, type, err);
          }
        } finally {
          options.complete && options.complete(xhr, type);

          // Update our minimum caching duration for the entire response
          var cachingInfo = (response && response.cachingInfo) || exports.cachingInfo(response);
          exports.calcCache(minimumCache, cachingInfo);

          if (!fromCache && type === 'success' && requestType === 'GET') {
            // Reparsing here to ensure that we have a clean object for future users
            cache[options.url] = body ? {caching: cachingInfo, data: JSON.parse(xhr.responseText)} : false;
          }

          // Store the response in the request log to send to the user
          if (type === 'success') {
            log[options.cacheUrl || options.url] = xhr.responseText || false;
            if (options.cacheUrl && options.cacheUrl !== options.url) {
              delete log[options.url];
            }
          } else {
            delete log[options.url];
          }

          ajax.emit('complete', options.url);
        }
      });
    }

    var requestType = options.type || 'GET';
    if (requestType === 'GET' && cache[options.url]) {
      setImmediate(function() {
        var cacheEntry = cache[options.url];
        callback(
            undefined,
            {statusCode: 200, cachingInfo: cacheEntry.caching},
            _.cloneDeep(cacheEntry.data));
      });
      xhr.readyState = 4;
      return xhr;
    }

    // Mark the request as in progress
    log[options.url] = null;

    var req = request({
        method: requestType,
        url: options.url,
        form: options.data
      },
      callback);
    requests.push(xhr);

    return xhr;
  };

  // Ensure that everything is initialized
  ajax.reset();

  return ajax;
};

/*
 * Normalizes caching information defined in a response.
 */
exports.cachingInfo = function(res) {
  // Will failover to no-cache state
  res = res || {headers: {}, request: {}};

  var cacheControl = res.headers['cache-control'],
      expires = res.headers.expires,
      pragma = res.headers.pragma,

      cacheable = CACHABLE_STATUS[res.statusCode] && res.request.method === 'GET',

      noCache,
      expires;

  if (cacheControl) {
    cacheControl = Nipple.parseCacheControl(cacheControl);

    noCache = (!cacheable && !cacheControl.public) || !!cacheControl['no-cache'];

    // Converting to explicit timeout so we don't inadvertantly extend the cache
    // lifecycle when serving cached responses in the future
    expires = Date.now() + parseInt(cacheControl['max-age'], 0)*1000;
  } else {
    noCache = !cacheable || pragma === 'no-cache';
    expires = Date.parse(expires).valueOf();
  }

  if (isNaN(expires) || noCache) {
    expires = undefined;
  }

  return {
    'no-cache': !!noCache,
    private: !!(cacheControl && cacheControl.private),
    expires: expires
  };
};

/*
 * Determines the most restrictive caching arguments given two inputs.
 */
exports.calcCache = function(minimumCache, cachingInfo) {
  minimumCache['no-cache'] = minimumCache['no-cache'] || cachingInfo['no-cache'];
  minimumCache.private = minimumCache.private || cachingInfo.private;
  minimumCache.expires = Math.min(minimumCache.expires, cachingInfo.expires);
  if (isNaN(minimumCache.expires) || minimumCache['no-cache']) {
    minimumCache.expires = undefined;
  }
};

exports.reset = function() {
  cache = {};
};

<|endoftext|>