<commit_before>#!/usr/bin/env node
/*
 * mochify.js
 *
 * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
 *
 * @license MIT
 */
'use strict';

var watchify      = require('watchify');
var browserify    = require('browserify');
var coverify      = require('coverify');
var through       = require('through');
var resolve       = require('resolve');
var glob          = require('glob');
var path          = require('path');
var mocaccino     = require('mocaccino');
var phantomic     = require('phantomic');
var webdriver     = require('min-wd/lib/driver');
var webdriverOpts = require('min-wd/lib/options');
var spawn         = require('child_process').spawn;

var argv     = process.argv.slice(2);
var cwd      = process.cwd();
var reporter = 'dot';
var watch    = false;
var wd       = false;
var cover    = false;
var node     = false;
var failure  = false;
var debug    = false;
var port     = 0;
var yields   = 0;
var ps;
var arg;

while (argv.length && argv[0].indexOf('-') === 0) {
  arg = argv[0];
  if (arg === '--watch') {
    argv.shift();
    watch = true;
  } else if (arg === '--cover') {
    argv.shift();
    cover = true;
  } else if (arg === '--node') {
    argv.shift();
    node = true;
  } else if (arg === '--wd') {
    argv.shift();
    wd = true;
  } else if (arg === '--reporter' || arg === '-R') {
    argv.shift();
    reporter = argv.shift();
  } else if (arg === '--yields' || arg === '-y') {
    argv.shift();
    yields = parseInt(argv.shift(), 10);
  } else if (arg === '--debug') {
    argv.shift();
    debug = true;
  } else if (arg === '--port') {
    argv.shift();
    port = parseInt(argv.shift(), 10);
  } else if (arg === '--help' || arg === '-h') {
    argv.shift();
    console.log(require('fs').readFileSync(__dirname + '/help.txt', 'utf8'));
    process.exit(0);
  } else if (arg === '--version' || arg === '-v') {
    argv.shift();
    console.log(require('../package.json').version);
    process.exit(0);
  } else {
    console.log('Unknown argument: ' + arg);
    console.log('Run `mochify --help` for usage.\n');
    process.exit(1);
  }
}

if (cover && reporter === 'dot') {
  reporter = 'spec';
}

if (debug) {
  if (node) {
    console.log('--debug does not work with --node\n');
    process.exit(1);
  }
  if (wd) {
    console.log('--debug does not work with --wd\n');
    process.exit(1);
  }
}

var entries = [];
if (argv.length) {
  argv.forEach(function (arg) {
    if (arg.indexOf('*') === -1) {
      entries.push(arg);
    } else {
      Array.prototype.push.apply(entries, glob.sync(arg));
    }
  });
} else {
  entries = glob.sync("./test/*.js");
}

function error(err) {
  console.error(String(err));
}

var TRACE_RE  = /^\s+at [^:]+:[0-9]+\)?\s*$/;
var IGNORE_RE = /\/node_modules\/(browserify|mocha)\//;
var SOURCE_RE = /\/[^:]+/;

function relativePath(source) {
  return path.relative(cwd, source);
}

function tracebackFormatter() {
  var buf = '';
  return through(function (chunk) {
    buf += chunk;
    var l, p = buf.indexOf('\n');
    while (p !== -1) {
      l = buf.substring(0, p);
      if (TRACE_RE.test(l)) {
        if (!IGNORE_RE.test(l)) {
          l = l.replace(SOURCE_RE, relativePath);
          this.queue(l + '\n');
        }
      } else {
        this.queue(l + '\n');
      }
      buf = buf.substring(p + 1);
      p = buf.indexOf('\n');
    }
    if (!/^\s+/.test(buf) || (buf.length > 3 && !/^\s+at /.test(buf))) {
      this.queue(buf);
      buf = '';
    }
  });
}

function launcherCallback(callback) {
  return function (err) {
    if (!watch && !cover) {
      process.nextTick(function () {
        process.exit(err ? 1 : 0);
      });
    } else if (callback) {
      callback();
    }
  };
}

function launcherOut() {
  if (cover) {
    var c = spawn(resolve.sync('coverify', {
      baseDir: __dirname,
      packageFilter: function (pkg) {
        return { main : pkg.bin.coverify };
      }
    }));
    c.stdout.pipe(process.stdout);
    c.stderr.pipe(process.stderr);
    c.on('exit', function (code) {
      if (!watch) {
        process.nextTick(function () {
          process.exit(failure || code);
        });
      }
    });
    return c.stdin;
  }
  return process.stdout;
}

function launchNode(callback) {
  var n = spawn('node');
  n.stdout.pipe(tracebackFormatter()).pipe(launcherOut());
  n.stderr.pipe(tracebackFormatter()).pipe(process.stderr);
  n.on('exit', function (code) {
    failure = code;
    if (!watch) {
      if (!cover) {
        process.nextTick(function () {
          process.exit(code);
        });
      }
    } else {
      callback();
    }
  });
  ps.pipe(n.stdin);
}

function launchPhantom(callback) {
  phantomic(ps, {
    debug : debug,
    port  : port,
    brout : true
  }, launcherCallback(callback))
    .pipe(tracebackFormatter())
    .pipe(launcherOut());
}

function launchWebDriver(callback) {
  var wdOpts = webdriverOpts();
  if (!wdOpts.hasOwnProperty('timeout')) {
    wdOpts.timeout = 0;
  }
  webdriver(ps, wdOpts, launcherCallback(callback))
    .pipe(tracebackFormatter())
    .pipe(launcherOut());
}

function browserifyBundle(w) {
  var opts = {
    debug : true
  };
  if (node) {
    opts.detectGlobals = false;
    opts.insertGlobalVars = ['__dirname', '__filename'];
  }
  var wb = w.bundle(opts);
  wb.on('error', error);
  wb.pipe(ps);
}

function bundler(w, launcher) {
  (function run() {
    ps = through();
    launcher(run);
  }());
  return function () {
    browserifyBundle(w);
  };
}

var opts = {};
if (node) {
  opts.builtins = false;
  opts.commondir = false;
}
var b = browserify(opts);
if (wd) {
  var minWebDriverFile = resolve.sync('min-wd', {
    baseDir: __dirname,
    packageFilter: function (pkg) {
      return { main : pkg.browser };
    }
  });
  if (/^[A-Z]:\\/.test(minWebDriverFile)) {
    minWebDriverFile = minWebDriverFile.substring(3);
  }
  minWebDriverFile = minWebDriverFile.replace(/\\/g, '/');
  b.transform(function () {
    return through(function (data) {
      this.queue('require(' + JSON.stringify(minWebDriverFile) + ');');
      this.queue(data);
    });
  });
}

entries.forEach(function (entry) {
  b.add(entry);
});
b.plugin(mocaccino, { reporter : reporter, node : node, yields : yields });
if (cover) {
  b.transform(coverify);
}
b.on('error', error);

var launcher = null;
if (wd) {
  launcher = launchWebDriver;
} else if (node) {
  launcher = launchNode;
} else {
  launcher = launchPhantom;
}

if (watch) {

  var w = watchify(b);

  var bundle = bundler(w, launcher);
  w.on('update', bundle);
  w.on('error', error);
  bundle();

  process.on('SIGINT', function () {
    if (ps) {
      ps.on('end', function () {
        process.exit(0);
      });
      ps.queue(null);
    } else {
      process.exit(0);
    }
  });

  // Hack for Windows:
  if (require('os').platform() === 'win32') {
    var readline = require('readline');
    var rl = readline.createInterface({
      input  : process.stdin,
      output : process.stdout
    });
    rl.on('SIGINT', function () {
      process.emit('SIGINT');
    });
  }

} else {

  ps = through();
  launcher();
  browserifyBundle(b);

}
<commit_msg>Fix min-webdriver require for windows (take III)<commit_after>#!/usr/bin/env node
/*
 * mochify.js
 *
 * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
 *
 * @license MIT
 */
'use strict';

var watchify      = require('watchify');
var browserify    = require('browserify');
var coverify      = require('coverify');
var through       = require('through');
var resolve       = require('resolve');
var glob          = require('glob');
var path          = require('path');
var mocaccino     = require('mocaccino');
var phantomic     = require('phantomic');
var webdriver     = require('min-wd/lib/driver');
var webdriverOpts = require('min-wd/lib/options');
var spawn         = require('child_process').spawn;

var argv     = process.argv.slice(2);
var cwd      = process.cwd();
var reporter = 'dot';
var watch    = false;
var wd       = false;
var cover    = false;
var node     = false;
var failure  = false;
var debug    = false;
var port     = 0;
var yields   = 0;
var ps;
var arg;

while (argv.length && argv[0].indexOf('-') === 0) {
  arg = argv[0];
  if (arg === '--watch') {
    argv.shift();
    watch = true;
  } else if (arg === '--cover') {
    argv.shift();
    cover = true;
  } else if (arg === '--node') {
    argv.shift();
    node = true;
  } else if (arg === '--wd') {
    argv.shift();
    wd = true;
  } else if (arg === '--reporter' || arg === '-R') {
    argv.shift();
    reporter = argv.shift();
  } else if (arg === '--yields' || arg === '-y') {
    argv.shift();
    yields = parseInt(argv.shift(), 10);
  } else if (arg === '--debug') {
    argv.shift();
    debug = true;
  } else if (arg === '--port') {
    argv.shift();
    port = parseInt(argv.shift(), 10);
  } else if (arg === '--help' || arg === '-h') {
    argv.shift();
    console.log(require('fs').readFileSync(__dirname + '/help.txt', 'utf8'));
    process.exit(0);
  } else if (arg === '--version' || arg === '-v') {
    argv.shift();
    console.log(require('../package.json').version);
    process.exit(0);
  } else {
    console.log('Unknown argument: ' + arg);
    console.log('Run `mochify --help` for usage.\n');
    process.exit(1);
  }
}

if (cover && reporter === 'dot') {
  reporter = 'spec';
}

if (debug) {
  if (node) {
    console.log('--debug does not work with --node\n');
    process.exit(1);
  }
  if (wd) {
    console.log('--debug does not work with --wd\n');
    process.exit(1);
  }
}

var entries = [];
if (argv.length) {
  argv.forEach(function (arg) {
    if (arg.indexOf('*') === -1) {
      entries.push(arg);
    } else {
      Array.prototype.push.apply(entries, glob.sync(arg));
    }
  });
} else {
  entries = glob.sync("./test/*.js");
}

function error(err) {
  console.error(String(err));
}

var TRACE_RE  = /^\s+at [^:]+:[0-9]+\)?\s*$/;
var IGNORE_RE = /\/node_modules\/(browserify|mocha)\//;
var SOURCE_RE = /\/[^:]+/;

function relativePath(source) {
  return path.relative(cwd, source);
}

function tracebackFormatter() {
  var buf = '';
  return through(function (chunk) {
    buf += chunk;
    var l, p = buf.indexOf('\n');
    while (p !== -1) {
      l = buf.substring(0, p);
      if (TRACE_RE.test(l)) {
        if (!IGNORE_RE.test(l)) {
          l = l.replace(SOURCE_RE, relativePath);
          this.queue(l + '\n');
        }
      } else {
        this.queue(l + '\n');
      }
      buf = buf.substring(p + 1);
      p = buf.indexOf('\n');
    }
    if (!/^\s+/.test(buf) || (buf.length > 3 && !/^\s+at /.test(buf))) {
      this.queue(buf);
      buf = '';
    }
  });
}

function launcherCallback(callback) {
  return function (err) {
    if (!watch && !cover) {
      process.nextTick(function () {
        process.exit(err ? 1 : 0);
      });
    } else if (callback) {
      callback();
    }
  };
}

function launcherOut() {
  if (cover) {
    var c = spawn(resolve.sync('coverify', {
      baseDir: __dirname,
      packageFilter: function (pkg) {
        return { main : pkg.bin.coverify };
      }
    }));
    c.stdout.pipe(process.stdout);
    c.stderr.pipe(process.stderr);
    c.on('exit', function (code) {
      if (!watch) {
        process.nextTick(function () {
          process.exit(failure || code);
        });
      }
    });
    return c.stdin;
  }
  return process.stdout;
}

function launchNode(callback) {
  var n = spawn('node');
  n.stdout.pipe(tracebackFormatter()).pipe(launcherOut());
  n.stderr.pipe(tracebackFormatter()).pipe(process.stderr);
  n.on('exit', function (code) {
    failure = code;
    if (!watch) {
      if (!cover) {
        process.nextTick(function () {
          process.exit(code);
        });
      }
    } else {
      callback();
    }
  });
  ps.pipe(n.stdin);
}

function launchPhantom(callback) {
  phantomic(ps, {
    debug : debug,
    port  : port,
    brout : true
  }, launcherCallback(callback))
    .pipe(tracebackFormatter())
    .pipe(launcherOut());
}

function launchWebDriver(callback) {
  var wdOpts = webdriverOpts();
  if (!wdOpts.hasOwnProperty('timeout')) {
    wdOpts.timeout = 0;
  }
  webdriver(ps, wdOpts, launcherCallback(callback))
    .pipe(tracebackFormatter())
    .pipe(launcherOut());
}

function browserifyBundle(w) {
  var opts = {
    debug : true
  };
  if (node) {
    opts.detectGlobals = false;
    opts.insertGlobalVars = ['__dirname', '__filename'];
  }
  var wb = w.bundle(opts);
  wb.on('error', error);
  wb.pipe(ps);
}

function bundler(w, launcher) {
  (function run() {
    ps = through();
    launcher(run);
  }());
  return function () {
    browserifyBundle(w);
  };
}

var opts = {};
if (node) {
  opts.builtins = false;
  opts.commondir = false;
}
var b = browserify(opts);
if (wd) {
  var minWebDriverFile = resolve.sync('min-wd', {
    baseDir: __dirname,
    packageFilter: function (pkg) {
      return { main : pkg.browser };
    }
  });
  if (/^[A-Z]:\\/.test(minWebDriverFile)) {
    minWebDriverFile = minWebDriverFile.substring(2);
  }
  minWebDriverFile = minWebDriverFile.replace(/\\/g, '/');
  b.transform(function () {
    return through(function (data) {
      this.queue('require(' + JSON.stringify(minWebDriverFile) + ');');
      this.queue(data);
    });
  });
}

entries.forEach(function (entry) {
  b.add(entry);
});
b.plugin(mocaccino, { reporter : reporter, node : node, yields : yields });
if (cover) {
  b.transform(coverify);
}
b.on('error', error);

var launcher = null;
if (wd) {
  launcher = launchWebDriver;
} else if (node) {
  launcher = launchNode;
} else {
  launcher = launchPhantom;
}

if (watch) {

  var w = watchify(b);

  var bundle = bundler(w, launcher);
  w.on('update', bundle);
  w.on('error', error);
  bundle();

  process.on('SIGINT', function () {
    if (ps) {
      ps.on('end', function () {
        process.exit(0);
      });
      ps.queue(null);
    } else {
      process.exit(0);
    }
  });

  // Hack for Windows:
  if (require('os').platform() === 'win32') {
    var readline = require('readline');
    var rl = readline.createInterface({
      input  : process.stdin,
      output : process.stdout
    });
    rl.on('SIGINT', function () {
      process.emit('SIGINT');
    });
  }

} else {

  ps = through();
  launcher();
  browserifyBundle(b);

}
<|endoftext|>


<commit_before>module.exports = Cli

var defaults = require('defaults')
var minimist = require('minimist')
var multiline = require('multiline')
var getStdin = require('get-stdin')
var fs = require('fs')

function Cli (opts) {
  var standard = require('../').linter(opts)

  opts = defaults(opts, {
    cmd: 'standard-engine',
    tagline: 'JavaScript Custom Style',
    version: require('../package.json').version
  })

  var argv = minimist(process.argv.slice(2), {
    alias: {
      format: 'F',
      global: 'globals',
      help: 'h',
      verbose: 'v'
    },
    boolean: [
      'format',
      'help',
      'stdin',
      'verbose',
      'version'
    ],
    string: [
      'global',
      'parser'
    ]
  })

  if (argv.format) {
    var typeFormatter = typeof opts.formatter

    if (typeFormatter !== 'object' || typeof opts.formatter.transform !== 'function') {
      console.error('Invalid formatter API')
      process.exit(0)
    }
  }

  // flag `-` is equivalent to `--stdin`
  if (argv._[0] === '-') {
    argv.stdin = true
    argv._.shift()
  }

  if (argv.help) {
    var fmtMsg = ''
    if (opts.formatter) {
      fmtMsg = '-F, --format    Automatically format code.'
      if (opts.formatterName) fmtMsg += ' (using ' + opts.formatterName + ')'
    }
    if (opts.tagline) console.log('%s - %s (%s)', opts.cmd, opts.tagline, opts.homepage)
    console.log(multiline.stripIndent(function () {
      /*

        Usage:
            %s <flags> [FILES...]

            If FILES is omitted, then all JavaScript source files (*.js, *.jsx) in the current
            working directory are checked, recursively.

            Certain paths (node_modules/, .git/, coverage/, *.min.js, bundle.js) are
            automatically ignored.

        Flags:
            %s
            -v, --verbose   Show error codes. (so you can ignore specific rules)
                --stdin     Read file text from stdin.
                --global    Declare global variable
                --parser    Use custom js parser (e.g. babel-eslint)
                --version   Show current version
            -h, --help      Show usage information
      */
    }), opts.cmd, fmtMsg)
    process.exit(0)
  }

  if (argv.version) {
    console.log(opts.version)
    process.exit(0)
  }

  var lintOpts = {
    parser: argv.parser,
    global: argv.global
  }

  if (argv.stdin) {
    getStdin().then(function (text) {
      if (argv.format) {
        text = opts.formatter.transform(text)
        process.stdout.write(text)
      }
      standard.lintText(text, lintOpts, onResult)
    })
  } else {
    if (argv.format) {
      lintOpts._onFiles = function (files) {
        files.forEach(function (file) {
          var data = fs.readFileSync(file).toString()
          fs.writeFileSync(file, opts.formatter.transform(data))
        })
      }
    }
    standard.lintFiles(argv._, lintOpts, onResult)
  }

  function onResult (err, result) {
    if (err) return onError(err)
    if (!result.errorCount && !result.warningCount) process.exit(0)

    console.error(
      opts.cmd + ': %s (%s) ',
      opts.tagline,
      opts.homepage
    )

    result.results.forEach(function (result) {
      result.messages.forEach(function (message) {
        log(
          '  %s:%d:%d: %s%s',
          result.filePath, message.line || 0, message.column || 0, message.message,
          argv.verbose ? ' (' + message.ruleId + ')' : ''
        )
      })
    })

    process.exit(result.errorCount ? 1 : 0)
  }

  function onError (err) {
    console.error(opts.cmd + ': Unexpected linter output:\n')
    console.error(err.stack || err.message || err)
    console.error(
      '\nIf you think this is a bug in `%s`, open an issue: %s',
      opts.cmd, opts.bugs
    )
    process.exit(1)
  }

  /**
   * Print lint errors to stdout since this is expected output from `standard-engine`.
   * Note: When formatting code from stdin (`standard --stdin --format`), the transformed
   * code is printed to stdout, so print lint errors to stderr in this case.
   */
  function log () {
    if (argv.stdin && argv.format) {
      arguments[0] = opts.cmd + ': ' + arguments[0]
      console.error.apply(console, arguments)
    } else {
      console.log.apply(console, arguments)
    }
  }
}
<commit_msg>if `formatter` opt is string, print it<commit_after>module.exports = Cli

var defaults = require('defaults')
var minimist = require('minimist')
var multiline = require('multiline')
var getStdin = require('get-stdin')
var fs = require('fs')

function Cli (opts) {
  var standard = require('../').linter(opts)

  opts = defaults(opts, {
    cmd: 'standard-engine',
    tagline: 'JavaScript Custom Style',
    version: require('../package.json').version
  })

  var argv = minimist(process.argv.slice(2), {
    alias: {
      format: 'F',
      global: 'globals',
      help: 'h',
      verbose: 'v'
    },
    boolean: [
      'format',
      'help',
      'stdin',
      'verbose',
      'version'
    ],
    string: [
      'global',
      'parser'
    ]
  })

  if (argv.format) {
    if (typeof opts.formatter === 'string') {
      console.error(opts.cmd + ': ' + opts.formatter)
      process.exit(1)
    }
    if (typeof opts.formatter !== 'object' ||
        typeof opts.formatter.transform !== 'function') {
      console.error(opts.cmd + ': Invalid formatter API')
      process.exit(0)
    }
  }

  // flag `-` is equivalent to `--stdin`
  if (argv._[0] === '-') {
    argv.stdin = true
    argv._.shift()
  }

  if (argv.help) {
    var fmtMsg = ''
    if (opts.formatter) {
      fmtMsg = '-F, --format    Automatically format code.'
      if (opts.formatterName) fmtMsg += ' (using ' + opts.formatterName + ')'
    }
    if (opts.tagline) console.log('%s - %s (%s)', opts.cmd, opts.tagline, opts.homepage)
    console.log(multiline.stripIndent(function () {
      /*

        Usage:
            %s <flags> [FILES...]

            If FILES is omitted, then all JavaScript source files (*.js, *.jsx) in the current
            working directory are checked, recursively.

            Certain paths (node_modules/, .git/, coverage/, *.min.js, bundle.js) are
            automatically ignored.

        Flags:
            %s
            -v, --verbose   Show error codes. (so you can ignore specific rules)
                --stdin     Read file text from stdin.
                --global    Declare global variable
                --parser    Use custom js parser (e.g. babel-eslint)
                --version   Show current version
            -h, --help      Show usage information
      */
    }), opts.cmd, fmtMsg)
    process.exit(0)
  }

  if (argv.version) {
    console.log(opts.version)
    process.exit(0)
  }

  var lintOpts = {
    parser: argv.parser,
    global: argv.global
  }

  if (argv.stdin) {
    getStdin().then(function (text) {
      if (argv.format) {
        text = opts.formatter.transform(text)
        process.stdout.write(text)
      }
      standard.lintText(text, lintOpts, onResult)
    })
  } else {
    if (argv.format) {
      lintOpts._onFiles = function (files) {
        files.forEach(function (file) {
          var data = fs.readFileSync(file).toString()
          fs.writeFileSync(file, opts.formatter.transform(data))
        })
      }
    }
    standard.lintFiles(argv._, lintOpts, onResult)
  }

  function onResult (err, result) {
    if (err) return onError(err)
    if (!result.errorCount && !result.warningCount) process.exit(0)

    console.error(
      opts.cmd + ': %s (%s) ',
      opts.tagline,
      opts.homepage
    )

    result.results.forEach(function (result) {
      result.messages.forEach(function (message) {
        log(
          '  %s:%d:%d: %s%s',
          result.filePath, message.line || 0, message.column || 0, message.message,
          argv.verbose ? ' (' + message.ruleId + ')' : ''
        )
      })
    })

    process.exit(result.errorCount ? 1 : 0)
  }

  function onError (err) {
    console.error(opts.cmd + ': Unexpected linter output:\n')
    console.error(err.stack || err.message || err)
    console.error(
      '\nIf you think this is a bug in `%s`, open an issue: %s',
      opts.cmd, opts.bugs
    )
    process.exit(1)
  }

  /**
   * Print lint errors to stdout since this is expected output from `standard-engine`.
   * Note: When formatting code from stdin (`standard --stdin --format`), the transformed
   * code is printed to stdout, so print lint errors to stderr in this case.
   */
  function log () {
    if (argv.stdin && argv.format) {
      arguments[0] = opts.cmd + ': ' + arguments[0]
      console.error.apply(console, arguments)
    } else {
      console.log.apply(console, arguments)
    }
  }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs')
var parseTorrent = require('../')

function usage () {
  console.error('Usage: parse-torrent /path/to/torrent')
}

var torrentPath = process.argv[2]

if (!torrentPath) {
  return usage()
}

try {
  var parsedTorrent = parseTorrent(fs.readFileSync(torrentPath))
} catch (err) {
  console.error(err.message + '\n')
  usage()
}

delete parsedTorrent.info
delete parsedTorrent.infoBuffer

console.dir(parsedTorrent)<commit_msg>command line program output valid JSON<commit_after>#!/usr/bin/env node

var fs = require('fs')
var parseTorrent = require('../')

function usage () {
  console.error('Usage: parse-torrent /path/to/torrent')
}

var torrentPath = process.argv[2]

if (!torrentPath) {
  return usage()
}

try {
  var parsedTorrent = parseTorrent(fs.readFileSync(torrentPath))
} catch (err) {
  console.error(err.message + '\n')
  usage()
}

delete parsedTorrent.info
delete parsedTorrent.infoBuffer

console.log(JSON.stringify(parsedTorrent, undefined, 2))<|endoftext|>


<commit_before>#!/usr/bin/env node

var opts = require('../options.js')
require('standard-engine').cli(opts)

process.on('exit', function (status) {
  if (status === 0) {
    console.log(require('fs').readFileSync(__dirname + '/../seal.ans').toString())
  }else{
    console.log('The president cannot endorse this code.')
  }
})
<commit_msg>Standardify cmd.js<commit_after>#!/usr/bin/env node

var opts = require('../options.js')
require('standard-engine').cli(opts)

process.on('exit', function (status) {
  if (status === 0) {
    console.log(require('fs').readFileSync(__dirname + '/../seal.ans').toString())
  } else {
    console.log('The president cannot endorse this code.')
  }
})
<|endoftext|>


<commit_before>/*
 * Generic plot class to hold attributes and allow the creation of concrete
 * plots from a single set of data and parameters.
 *
 */

viz.Plot = function(data, attrs) {
    // TODO Track the type of data?
    if (data === undefined) {
        throw "missing parameter: data";
    }
    if (attrs === undefined) {
        attrs = {}
    }
    this._attrs = viz.util.extend(
            viz.plots.defaultAttrs,
            attrs);
    this._attrs.selection = d3.select(this._attrs.selector)
        .append('svg');
    this._attrs.plotData = data;
    // Create scales
    // TODO This shouldn't be here in case data aren't just xy
    var xMin = d3.min(data, function(d) { return d.x; });
    var xMax = d3.max(data, function(d) { return d.x; });
    var xDim = xMax - xMin;
    this._attrs.xScale = d3.scale[this._attrs.xScaleType]()
        .domain([xMin - this._attrs.xOffset * xDim,
                 xMax + this._attrs.xOffset * xDim])
        .range([this._attrs.plotPadding[3],
                this._attrs.plotWidth - this._attrs.plotPadding[1]]);
    var yMin = d3.min(data, function(d) { return d.y; });
    var yMax = d3.max(data, function(d) { return d.y; });
    var yDim = yMax - yMin;
    this._attrs.yScale = d3.scale[this._attrs.yScaleType]()
        .domain([yMin - this._attrs.yOffset * yDim,
                 yMax + this._attrs.yOffset * yDim])
        .range([this._attrs.plotHeight - this._attrs.plotPadding[2],
                this._attrs.plotPadding[0]]);
}

viz.Plot.prototype = {
    setAttr: function(a, v) {
        this._attr.set(a, v)
        return this;
    },
    getAttr: function(a) {
        return this._attrs.get(a);
    },
    updateAttrs: function(attrs) {
        this._attrs = viz.util.extend(this._attrs, attrs);
        return this;
    },
    attr: function(a, v) {
        if (v === undefined) {
            return this.getAttr(a);
        } else {
            return this.setAttr(a, v);
        }
    },
    create: function(type) {
        return new (viz.plots.registered[type])(this._data, this._attrs);
    }
}

viz.plots.defaultAttrs = {
    selector: "body",
    // Title
    plotTitle: undefined,
    plotTitleSize: 22,
    plotTitleFontFamily: "sans-serif",
    // Subtitle
    plotSubtitle: undefined,
    plotSubtitleSize: 16,
    plotSubtitleFontFamily: "sans-serif",
    // Dimensions
    plotWidth: 600,
    plotHeight: 300,
    plotPadding: [50, 50, 50, 50],
    xOffset: 0.25,
    yOffset: 0.25,
    // Grid lines
    xGridLines: undefined,
    yGridLines: undefined,
    gridLines: 10,
    xGridLineWidth: undefined,
    yGridLineWidth: undefined,
    gridLineWidth: 1,
    xGridLineColor: undefined,
    yGridLineColor: undefined,
    gridLineColor: "#000",
    xGridLineType: undefined,
    yGridLineType: undefined,
    gridLineType: "dotted",
    // Scales
    xScaleType: 'linear',
    yScaleType: 'linear',
    // Axes
    xAxis: undefined,
    yAxis: undefined,
    axes: undefined,
    xAxisTicks: undefined,
    yAxisTicks: undefined,
    axesTicks: undefined,
    xAxisTickSize: undefined,
    yAxisTickSize: undefined,
    axesTickSize: 5,
    xAxisTickWidth: undefined,
    yAxisTickWidth: undefined,
    axesTickWidth: 1,
    xAxisTickColor: undefined,
    yAxisTickColor: undefined,
    axesTickColor: '#000',
    xAxisTickType: undefined,
    yAxisTickType: undefined,
    axesTickType: 'solid',
    xAxisLineWidth: undefined,
    yAxisLineWidth: undefined,
    axesLineWidth: undefined,
    xAxisLineColor: undefined,
    yAxisLineColor: undefined,
    axesLineColor: undefined,
    xAxisLineType: undefined,
    yAxisLineType: undefined,
    axesLineType: undefined,
}

/*
 * Concrete plots can inject their own custom attribute defaults to avoid
 * having to deal with them separately. Overriding global defaults is not
 * allowed.
 *
 */
viz.plots.registered = {};
viz.plots.register(name, plotClass) {
    viz.plots.defaultAttrs = viz.util.merge(
            plotClass.defaultAttrs,
            viz.plots.defaultAttrs);
    viz.plots.registered[name] = plotClass;
}
<commit_msg>Fix getter and setter to use object instead of D3 map.<commit_after>/*
 * Generic plot class to hold attributes and allow the creation of concrete
 * plots from a single set of data and parameters.
 *
 */

viz.Plot = function(data, attrs) {
    // TODO Track the type of data?
    if (data === undefined) {
        throw "missing parameter: data";
    }
    if (attrs === undefined) {
        attrs = {}
    }
    this._attrs = viz.util.extend(
            viz.plots.defaultAttrs,
            attrs);
    this._attrs.selection = d3.select(this._attrs.selector)
        .append('svg');
    this._attrs.plotData = data;
    // Create scales
    // TODO This shouldn't be here in case data aren't just xy
    var xMin = d3.min(data, function(d) { return d.x; });
    var xMax = d3.max(data, function(d) { return d.x; });
    var xDim = xMax - xMin;
    this._attrs.xScale = d3.scale[this._attrs.xScaleType]()
        .domain([xMin - this._attrs.xOffset * xDim,
                 xMax + this._attrs.xOffset * xDim])
        .range([this._attrs.plotPadding[3],
                this._attrs.plotWidth - this._attrs.plotPadding[1]]);
    var yMin = d3.min(data, function(d) { return d.y; });
    var yMax = d3.max(data, function(d) { return d.y; });
    var yDim = yMax - yMin;
    this._attrs.yScale = d3.scale[this._attrs.yScaleType]()
        .domain([yMin - this._attrs.yOffset * yDim,
                 yMax + this._attrs.yOffset * yDim])
        .range([this._attrs.plotHeight - this._attrs.plotPadding[2],
                this._attrs.plotPadding[0]]);
}

viz.Plot.prototype = {
    setAttr: function(a, v) {
        this._attrs[a] = v;
        return this;
    },
    getAttr: function(a) {
        return this._attrs[a];
    },
    updateAttrs: function(attrs) {
        this._attrs = viz.util.extend(this._attrs, attrs);
        return this;
    },
    attr: function(a, v) {
        if (v === undefined) {
            return this.getAttr(a);
        } else {
            return this.setAttr(a, v);
        }
    },
    create: function(type) {
        return new (viz.plots.registered[type])(this._data, this._attrs);
    }
}

viz.plots.defaultAttrs = {
    selector: "body",
    // Title
    plotTitle: undefined,
    plotTitleSize: 22,
    plotTitleFontFamily: "sans-serif",
    // Subtitle
    plotSubtitle: undefined,
    plotSubtitleSize: 16,
    plotSubtitleFontFamily: "sans-serif",
    // Dimensions
    plotWidth: 600,
    plotHeight: 300,
    plotPadding: [50, 50, 50, 50],
    xOffset: 0.25,
    yOffset: 0.25,
    // Grid lines
    xGridLines: undefined,
    yGridLines: undefined,
    gridLines: 10,
    xGridLineWidth: undefined,
    yGridLineWidth: undefined,
    gridLineWidth: 1,
    xGridLineColor: undefined,
    yGridLineColor: undefined,
    gridLineColor: "#000",
    xGridLineType: undefined,
    yGridLineType: undefined,
    gridLineType: "dotted",
    // Scales
    xScaleType: 'linear',
    yScaleType: 'linear',
    // Axes
    xAxis: undefined,
    yAxis: undefined,
    axes: undefined,
    xAxisTicks: undefined,
    yAxisTicks: undefined,
    axesTicks: undefined,
    xAxisTickSize: undefined,
    yAxisTickSize: undefined,
    axesTickSize: 5,
    xAxisTickWidth: undefined,
    yAxisTickWidth: undefined,
    axesTickWidth: 1,
    xAxisTickColor: undefined,
    yAxisTickColor: undefined,
    axesTickColor: '#000',
    xAxisTickType: undefined,
    yAxisTickType: undefined,
    axesTickType: 'solid',
    xAxisLineWidth: undefined,
    yAxisLineWidth: undefined,
    axesLineWidth: undefined,
    xAxisLineColor: undefined,
    yAxisLineColor: undefined,
    axesLineColor: undefined,
    xAxisLineType: undefined,
    yAxisLineType: undefined,
    axesLineType: undefined,
}

/*
 * Concrete plots can inject their own custom attribute defaults to avoid
 * having to deal with them separately. Overriding global defaults is not
 * allowed.
 *
 */
viz.plots.registered = {};
viz.plots.register(name, plotClass) {
    viz.plots.defaultAttrs = viz.util.merge(
            plotClass.defaultAttrs,
            viz.plots.defaultAttrs);
    viz.plots.registered[name] = plotClass;
}
<|endoftext|>


<commit_before>/* eslint key-spacing:0 spaced-comment:0 */
const path = require('path');
const debug = require('debug')('app:config:project');
const argv = require('yargs').argv;
const ip = require('ip');

debug('Creating default configuration.');
// ========================================================
// Default Configuration
// ========================================================
const config = {
    env : process.env.NODE_ENV || 'development',

  // ----------------------------------
  // Project Structure
  // ----------------------------------
    path_base  : path.resolve(__dirname, '..'),
    dir_client : 'src',
    dir_dist   : 'dist',
    dir_public : 'public',
    dir_server : 'server',
    dir_test   : 'tests',

  // ----------------------------------
  // Server Configuration
  // ----------------------------------
    server_host : ip.address(), // use string 'localhost' to prevent exposure on local network
    server_port : process.env.PORT || 3000,

  // ----------------------------------
  // Compiler Configuration
  // ----------------------------------
    compiler_babel : {
        cacheDirectory : true,
        plugins        : ['transform-runtime'],
        presets        : ['es2015', 'react', 'stage-0'],
    },
    compiler_devtool         : 'source-map',
    compiler_hash_type       : 'hash',
    compiler_fail_on_warning : false,
    compiler_quiet           : false,
    compiler_public_path     : '/',
    compiler_stats           : {
        chunks : false,
        chunkModules : false,
        colors : true,
    },
    compiler_vendors : [
        'react',
        'react-redux',
        'react-router',
        'redux',
    ],

  // ----------------------------------
  // Test Configuration
  // ----------------------------------
    coverage_reporters : [
    { type : 'text-summary' },
    { type : 'lcov', dir : 'coverage' },
    ],
};

/************************************************
-------------------------------------------------

All Internal Configuration Below
Edit at Your Own Risk

-------------------------------------------------
************************************************/

// ------------------------------------
// Environment
// ------------------------------------
// N.B.: globals added here must _also_ be added to .eslintrc
config.globals = {
    'process.env'  : {
        'NODE_ENV' : JSON.stringify(config.env),
    },
    'NODE_ENV'     : config.env,
    '__DEV__'      : config.env === 'development',
    '__PROD__'     : config.env === 'production',
    '__TEST__'     : config.env === 'test',
    '__COVERAGE__' : !argv.watch && config.env === 'test',
    '__BASENAME__' : JSON.stringify(process.env.BASENAME || ''),
    API_BASE       : '"http://rock.positron.cz:8080"',
    MP3_BASE       : '"http://commondatastorage.googleapis.com/karel-makon-mp3/"',
};

// ------------------------------------
// Validate Vendor Dependencies
// ------------------------------------
const pkg = require('../package.json');

config.compiler_vendors = config.compiler_vendors
  .filter((dep) => {
      if (pkg.dependencies[dep]) return true;

      debug(
      `Package "${dep}" was not found as an npm dependency in package.json; ` +
      `it won't be included in the webpack vendor bundle.
       Consider removing it from \`compiler_vendors\` in ~/config/index.js`
    );
  });

// ------------------------------------
// Utilities
// ------------------------------------
function base () {
    const args = [config.path_base].concat([].slice.call(arguments));
    return path.resolve.apply(path, args);
}

config.paths = {
    base   : base,
    client : base.bind(null, config.dir_client),
    public : base.bind(null, config.dir_public),
    dist   : base.bind(null, config.dir_dist),
};

// ========================================================
// Environment Configuration
// ========================================================
debug(`Looking for environment overrides for NODE_ENV "${config.env}".`);
const environments = require('./environments.config');
const overrides = environments[config.env];
if (overrides) {
    debug('Found overrides, applying to default configuration.');
    Object.assign(config, overrides(config));
} else {
    debug('No environment overrides found, defaults will be used.');
}

module.exports = config;
<commit_msg>prefer local backend<commit_after>/* eslint key-spacing:0 spaced-comment:0 */
const path = require('path');
const debug = require('debug')('app:config:project');
const argv = require('yargs').argv;
const ip = require('ip');

debug('Creating default configuration.');
// ========================================================
// Default Configuration
// ========================================================
const config = {
    env : process.env.NODE_ENV || 'development',

  // ----------------------------------
  // Project Structure
  // ----------------------------------
    path_base  : path.resolve(__dirname, '..'),
    dir_client : 'src',
    dir_dist   : 'dist',
    dir_public : 'public',
    dir_server : 'server',
    dir_test   : 'tests',

  // ----------------------------------
  // Server Configuration
  // ----------------------------------
    server_host : ip.address(), // use string 'localhost' to prevent exposure on local network
    server_port : process.env.PORT || 3000,

  // ----------------------------------
  // Compiler Configuration
  // ----------------------------------
    compiler_babel : {
        cacheDirectory : true,
        plugins        : ['transform-runtime'],
        presets        : ['es2015', 'react', 'stage-0'],
    },
    compiler_devtool         : 'source-map',
    compiler_hash_type       : 'hash',
    compiler_fail_on_warning : false,
    compiler_quiet           : false,
    compiler_public_path     : '/',
    compiler_stats           : {
        chunks : false,
        chunkModules : false,
        colors : true,
    },
    compiler_vendors : [
        'react',
        'react-redux',
        'react-router',
        'redux',
    ],

  // ----------------------------------
  // Test Configuration
  // ----------------------------------
    coverage_reporters : [
    { type : 'text-summary' },
    { type : 'lcov', dir : 'coverage' },
    ],
};

/************************************************
-------------------------------------------------

All Internal Configuration Below
Edit at Your Own Risk

-------------------------------------------------
************************************************/

// ------------------------------------
// Environment
// ------------------------------------
// N.B.: globals added here must _also_ be added to .eslintrc
config.globals = {
    'process.env'  : {
        'NODE_ENV' : JSON.stringify(config.env),
    },
    'NODE_ENV'     : config.env,
    '__DEV__'      : config.env === 'development',
    '__PROD__'     : config.env === 'production',
    '__TEST__'     : config.env === 'test',
    '__COVERAGE__' : !argv.watch && config.env === 'test',
    '__BASENAME__' : JSON.stringify(process.env.BASENAME || ''),
//    API_BASE       : '"http://rock.positron.cz:8080"',
//    MP3_BASE       : '"http://commondatastorage.googleapis.com/karel-makon-mp3/"',
    API_BASE       : '"http://localhost:5000"',
    MP3_BASE       : '"http://localhost:5000/static/audio/"',
};

// ------------------------------------
// Validate Vendor Dependencies
// ------------------------------------
const pkg = require('../package.json');

config.compiler_vendors = config.compiler_vendors
  .filter((dep) => {
      if (pkg.dependencies[dep]) return true;

      debug(
      `Package "${dep}" was not found as an npm dependency in package.json; ` +
      `it won't be included in the webpack vendor bundle.
       Consider removing it from \`compiler_vendors\` in ~/config/index.js`
    );
  });

// ------------------------------------
// Utilities
// ------------------------------------
function base () {
    const args = [config.path_base].concat([].slice.call(arguments));
    return path.resolve.apply(path, args);
}

config.paths = {
    base   : base,
    client : base.bind(null, config.dir_client),
    public : base.bind(null, config.dir_public),
    dist   : base.bind(null, config.dir_dist),
};

// ========================================================
// Environment Configuration
// ========================================================
debug(`Looking for environment overrides for NODE_ENV "${config.env}".`);
const environments = require('./environments.config');
const overrides = environments[config.env];
if (overrides) {
    debug('Found overrides, applying to default configuration.');
    Object.assign(config, overrides(config));
} else {
    debug('No environment overrides found, defaults will be used.');
}

module.exports = config;
<|endoftext|>


<commit_before>const documentHeight = () => Math.max(
  document.body.scrollHeight,
  document.body.offsetHeight,
  document.documentElement.clientHeight,
  document.documentElement.scrollHeight,
  document.documentElement.offsetHeight,
);

function setBookmark() {
  const html = document.documentElement;
  const height = documentHeight();
  const postMeta = document.querySelector('meta[property="id"]');
  const postId = postMeta ? postMeta.getAttribute('content') : null;
  const scrollPosition = window.pageYOffset || html.scrollTop;
  const scrollPercent = scrollPosition / height;

  if (!window.localStorage) return;

  window.localStorage.setItem('bookmark', JSON.stringify({
    scrollPercent,
    url: window.location.href,
    postId,
  }));
}

function restoreBookmark() {
  if (!window.localStorage) return;

  const bookmark = JSON.parse(window.localStorage.getItem('bookmark'));
  if (window.location.href === bookmark.url && window.location.hash === 'bookmark') {
    const height = documentHeight();
    const offset = height * bookmark.scrollPercent;
    if (window.scrollTo) window.scrollTo(0, offset);
  }
}

if (window.location.href.indexOf('bolg.html') <= 0) {
  window.onbeforeunload = setBookmark;
  window.onunload = setBookmark;
  window.onload = restoreBookmark;
}
<commit_msg>Prevent error<commit_after>const documentHeight = () => Math.max(
  document.body.scrollHeight,
  document.body.offsetHeight,
  document.documentElement.clientHeight,
  document.documentElement.scrollHeight,
  document.documentElement.offsetHeight,
);

function setBookmark() {
  const html = document.documentElement;
  const height = documentHeight();
  const postMeta = document.querySelector('meta[property="id"]');
  const postId = postMeta ? postMeta.getAttribute('content') : null;
  const scrollPosition = window.pageYOffset || html.scrollTop;
  const scrollPercent = scrollPosition / height;

  if (!window.localStorage) return;

  window.localStorage.setItem('bookmark', JSON.stringify({
    scrollPercent,
    url: window.location.href,
    postId,
  }));
}

function restoreBookmark() {
  if (!window.localStorage) return;

  const bookmark = JSON.parse(window.localStorage.getItem('bookmark'));
  if (bookmark && window.location.href === bookmark.url && window.location.hash === 'bookmark') {
    const height = documentHeight();
    const offset = height * bookmark.scrollPercent;
    if (window.scrollTo) window.scrollTo(0, offset);
  }
}

if (window.location.href.indexOf('bolg.html') <= 0) {
  window.onbeforeunload = setBookmark;
  window.onunload = setBookmark;
  window.onload = restoreBookmark;
}
<|endoftext|>


<commit_before>import moment from 'moment'

export function postAttachment (post, extended) {
  let {
    commentsCount,
    postLikesCount,
    spoiler,
    nsfw,
    createdAt,
    editedAt,
    user,
    targetUser,
    targetGroup,
    media
  } = post

  let text = ''
  let fields = []
  let title_link = process.env.KITSU_HOST + '/posts/' + post.id
  let title = 'Post by ' + user.name
  title += targetUser ? `to ${targetUser.name}` : ''
  title += targetGroup ? `to ${targetGroup.name}` : ''
  let fallback = title + ' - ' + title_link

  nsfw = (targetGroup && targetGroup.nsfw) || nsfw

  if (nsfw) {
    text += ':smirk: [NSFW]'
    fallback += '\n[NSFW]'
  }

  if (spoiler) {
    text += '\n:exclamation: [SPOILER]'
    fallback += '\n[SPOILER]'
    if (media) {
      text += ` - <https://kitsu.io/${media.type}/${media.slug}|${media.canonicalTitle}>`
      fallback += ` - ${media.canonicalTitle}`
    }
  }

  if (!spoiler && !nsfw && post.content) {
    text = post.content
    fallback += `\n${post.content}`
  }

  if (commentsCount) {
    fields.push({
      title: ':speech_balloon: Comments',
      value: commentsCount,
      short: true
    })
    fallback += `\nComments: ${commentsCount}`
  }

  if (postLikesCount) {
    fields.push({
      title: ':heart: Likes',
      value: postLikesCount,
      short: true
    })
    fallback += `\nLikes: ${postLikesCount}`
  }

  if (createdAt) {
    let time = moment.utc(createdAt).fromNow()
    fields.push({
      title: ':clock3: Posted',
      value: time,
      short: true
    })
    fallback += `\nPosted: ${time}`
  }

  if (editedAt) {
    let time = moment.utc(editedAt).fromNow()
    fields.push({
      title: ':pencil2: Edited',
      value: time,
      short: true
    })
    fallback += `\nEdited: ${time}`
  }

  let attachment = {
    color: '#F65440',
    mrkdwn_in: ['text'],
    callback_id: post.id,
    title,
    title_link,
    text,
    thumb_url: user.avatar ? user.avatar.medium : null,
    fields,
    fallback,
    footer: 'Kitsu API',
    footer_icon: 'https://kitsu-slack.herokuapp.com/icon.png',
    ts: moment().unix()
    // actions: [{
    //   name: 'post',
    //   text: '',
    //   type: 'button'
    // }]
  }

  return attachment
}
<commit_msg>Fix post attachment<commit_after>import moment from 'moment'

export function postAttachment (post, extended) {
  let {
    commentsCount,
    postLikesCount,
    spoiler,
    nsfw,
    createdAt,
    editedAt,
    user,
    targetUser,
    targetGroup,
    media
  } = post

  let text = ''
  let fields = []
  let title_link = process.env.KITSU_HOST + '/posts/' + post.id
  let title = 'Post by ' + user.name
  title += targetUser ? ` to ${targetUser.name}` : ''
  title += targetGroup ? ` to ${targetGroup.name}` : ''
  let fallback = title + ' - ' + title_link

  nsfw = (targetGroup && targetGroup.nsfw) || nsfw

  if (nsfw) {
    text += ':smirk: [NSFW]'
    fallback += '\n[NSFW]'
  }

  if (spoiler) {
    text += '\n:exclamation: [SPOILER]'
    fallback += '\n[SPOILER]'
  }

  if (!spoiler && !nsfw && post.content) {
    text = post.content
    fallback += `\n${post.content}`
  }

  if (media) {
    let type = media.type.charAt(0).toUpperCase() + media.type.slice(1)
    let mediaTitle = (type === 'Anime' ? ':tv: ' : ':orange_book: ') + type
    fields.push({
      title: mediaTitle,
      value: `<https://kitsu.io/${type}/${media.slug}|${media.canonicalTitle}>`,
      short: true
    })
    fallback += `\n${type}: ${media.canonicalTitle}`
  }

  if (commentsCount) {
    fields.push({
      title: ':speech_balloon: Comments',
      value: commentsCount,
      short: true
    })
    fallback += `\nComments: ${commentsCount}`
  }

  if (postLikesCount) {
    fields.push({
      title: ':heart: Likes',
      value: postLikesCount,
      short: true
    })
    fallback += `\nLikes: ${postLikesCount}`
  }

  if (createdAt) {
    let time = moment.utc(createdAt).fromNow()
    fields.push({
      title: ':clock3: Posted',
      value: time,
      short: true
    })
    fallback += `\nPosted: ${time}`
  }

  if (editedAt) {
    let time = moment.utc(editedAt).fromNow()
    fields.push({
      title: ':pencil2: Edited',
      value: time,
      short: true
    })
    fallback += `\nEdited: ${time}`
  }

  let attachment = {
    color: '#F65440',
    mrkdwn_in: ['text'],
    callback_id: post.id,
    title,
    title_link,
    text,
    thumb_url: user.avatar ? user.avatar.medium : null,
    fields,
    fallback,
    footer: 'Kitsu API',
    footer_icon: 'https://kitsu-slack.herokuapp.com/icon.png',
    ts: moment().unix()
    // actions: [{
    //   name: 'post',
    //   text: '',
    //   type: 'button'
    // }]
  }

  return attachment
}
<|endoftext|>


<commit_before>exports.handle = handle;
exports.replyMention = replyMention;
exports.greet = greet;
exports.songChange = songChange;

function handle(data)
{
    for (var i=0;i<commands.length;i++)
    {
        if (data.message.slice(0,commands[i].name.length) === commands[i].name && data.from.role>=commands[i].level) {
            commands[i].handler(data);
            break;
        }
    }
    if (i==commands.length)
    {
        bot.sendChat("Unknown command, try .help");
    }
}

function replyMention(data)
{
    //basic test, want to add some conversation module
    var msg=data.message;
    if (msg.search("fish")!=-1)
        bot.sendChat("fish go m00");
    else if (msg.search("cows")!=-1)
        bot.sendChat("cows go blub");
    else if (msg.search(/(grande som|alto som|this is nice)/i)!=-1 && data.from.role>=3)
    {
        bot.woot();
        bot.sendChat("Indeed");
    }
    else if (msg.search("plz disconnect")!=-1 && data.from.role>=3)
    {
        bot.moderateDeleteChat(data.raw.cid);
        disconnect();
    }
    else bot.sendChat("Sup @"+data.raw.un);
}

function greet(data)
{
    if (data.username)
    {
        bot.sendChat("Hi @"+data.username+"!");
    }
}

function songChange(data)
{
    if (data.currentDJ.role>0)
    {
        //gotta woot the overlords
        bot.woot();
    }
}

// command levels: 0-user,1-dj,2-bouncer,3-manager,4-host

//add user to queue
var _add={
    "name":".add",
    "level":3,
    "handler":function(data){
        //add to queue
        //move() to requested position

    }
};

//move user in queue
var _move={
    "name":".add",
    "level":3,
    "handler":function(data){
        //move()
    }
};

var _help={
    "name":".help",
    "level":0,
    "handler":function(data){
        var str="";
        for (var i=0;i<commands.length;i++)
        {
            if (commands[i].level<1&&commands[i].hidden!==true) //only show user commands, mods have to know their shit
                str+=commands[i].name+" ";
        }
        bot.sendChat("Available commands: "+str);
    }
};

var _info={
    "name":".info",
    "level":0,
    "handler":function(data){
        bot.sendChat("NI's plug moderator bot! Check the source and contribute at https://github.com/NIAEFEUP/PlugBot");
    }
}

var _skip={
    "name":".skip",
    "level":0, //temporary so that the user tro.trololol can have acess to it.
    "hidden":true,
    "handler":function(data){
        //add message parsing for reason
        if (data.from.role>=2||data.raw.un==="tro.trololol") //remove the if after updating the level key to the intended value 2
        {
            bot.moderateForceSkip();
            bot.moderateDeleteChat(data.raw.cid);
        }
    }
}

var _woot={
    "name":".woot",
    "level":3,
    "handler":function(data){
        bot.woot();
        bot.moderateDeleteChat(data.raw.cid);
    }
}

//tro.trololol
var commands=[_add,_help,_info,_woot,_skip];

//helper functions (DO NOT REPEAT YOURSELF)
function move()
{

}

function disconnect()
{
    logger.success("Exiting at request");
    //bot.disconnect() doesn't exist, maybe implement it in the future
    process.exit(0);
}<commit_msg>Removed the temporary permission for skipping. Added skip reason parsing and messaging it back<commit_after>exports.handle = handle;
exports.replyMention = replyMention;
exports.greet = greet;
exports.songChange = songChange;

function handle(data)
{
    for (var i=0;i<commands.length;i++)
    {
        if (data.message.slice(0,commands[i].name.length) === commands[i].name && data.from.role>=commands[i].level) {
            commands[i].handler(data);
            break;
        }
    }
    if (i==commands.length)
    {
        bot.sendChat("Unknown command, try .help");
    }
}

function replyMention(data)
{
    //basic test, want to add some conversation module
    var msg=data.message;
    if (msg.search("fish")!=-1)
        bot.sendChat("fish go m00");
    else if (msg.search("cows")!=-1)
        bot.sendChat("cows go blub");
    else if (msg.search(/(grande som|alto som|this is nice)/i)!=-1 && data.from.role>=3)
    {
        bot.woot();
        bot.sendChat("Indeed");
    }
    else if (msg.search("plz disconnect")!=-1 && data.from.role>=3)
    {
        bot.moderateDeleteChat(data.raw.cid);
        disconnect();
    }
    else bot.sendChat("Sup @"+data.raw.un);
}

function greet(data)
{
    if (data.username)
    {
        bot.sendChat("Hi @"+data.username+"!");
    }
}

function songChange(data)
{
    if (data.currentDJ.role>0)
    {
        //gotta woot the overlords
        bot.woot();
    }
}

// command levels: 0-user,1-dj,2-bouncer,3-manager,4-host

//add user to queue
var _add={
    "name":".add",
    "level":3,
    "handler":function(data){
        //add to queue
        //move() to requested position

    }
};

//move user in queue
var _move={
    "name":".add",
    "level":3,
    "handler":function(data){
        //move()
    }
};

//show available user commands
var _help={
    "name":".help",
    "level":0,
    "handler":function(data){
        var str="";
        for (var i=0;i<commands.length;i++)
        {
            if (commands[i].level<1&&commands[i].hidden!==true) //only show user commands, mods have to know their shit
                str+=commands[i].name+" ";
        }
        bot.sendChat("Available commands: "+str);
    }
};

//display information about the bot
var _info={
    "name":".info",
    "level":0,
    "handler":function(data){
        bot.sendChat("NI's plug moderator bot! Check the source and contribute at https://github.com/NIAEFEUP/PlugBot");
    }
}

//skip the current song and provide a reason
var _skip={
    "name":".skip",
    "level":2,
    "hidden":true,
    "handler":function(data){
        bot.moderateForceSkip(function(){
            bot.sendChat("Music skipped by @"+data.raw.un+":"+data.msg.slice(_skip.name.length));
        });
        bot.moderateDeleteChat(data.raw.cid);
    }
}

//woots the current song
var _woot={
    "name":".woot",
    "level":3,
    "handler":function(data){
        bot.woot();
        bot.moderateDeleteChat(data.raw.cid);
    }
}

//tro.trololol
var commands=[_add,_help,_info,_woot,_skip];

//helper functions (DO NOT REPEAT YOURSELF)
function move()
{

}

function disconnect()
{
    logger.success("Exiting at request");
    //bot.disconnect() doesn't exist, maybe implement it in the future
    process.exit(0);
}<|endoftext|>


<commit_before>/**
 * @file File system read
 * @since 0.1.9
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfHost*/ // Host type
/*exported _gpfRead*/ // Generic read method
/*exported _gpfReadImplByHost*/ // gpf.read per host
/*#endif*/

/**
 * {@see gpf.read} per host
 *
 * @type {Object}
 * @since 0.2.2
 */
var _gpfReadImplByHost = {};

/**
 * Generic read method
 *
 * @param {String} path File path
 * @return {Promise<String>} Resolved with the file content
 * @since 0.2.2
 */
function _gpfRead (path) {
    return _gpfReadImplByHost[_gpfHost](path);
}

/**
 * @gpf:sameas _gpfRead
 * @since 0.2.6
 */
gpf.read = _gpfRead;

/* istanbul ignore else */ // flavor.1
if (gpf.fs) {

    /**
     * @gpf:sameas _gpfRead
     * @since 0.2.2
     * @deprecated since version 0.2.6, use {@link gpf.read} instead
     */
    gpf.fs.read = _gpfRead;

}
<commit_msg>Safer injection mechanism<commit_after>/**
 * @file File system read
 * @since 0.1.9
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfHost*/ // Host type
/*exported _gpfRead*/ // Generic read method
/*exported _gpfReadSetImplIf*/ // Set the read implementation if the host matches
/*#endif*/

/**
 * {@see gpf.read} per host
 *
 * @type {Object}
 * @since 0.2.2
 */
var _gpfReadImpl = {};

/**
 * Set the read implementation if the host matches
 *
 * @param {String} host host to test, if matching with the current one, the read implementation is set
 * @param {Function} readImpl read implementation function
 * @since 0.2.6
 */
function _gpfReadSetImplIf (host, readImpl) {
    if (host === _gpfHost) {
        _gpfReadImpl = readImpl;
    }
}

/**
 * Generic read method
 *
 * @param {String} path File path
 * @return {Promise<String>} Resolved with the file content
 * @since 0.2.2
 */
function _gpfRead (path) {
    return _gpfReadImpl(path);
}

/**
 * @gpf:sameas _gpfRead
 * @since 0.2.6
 */
gpf.read = _gpfRead;

/* istanbul ignore else */ // flavor.1
if (gpf.fs) {

    /**
     * @gpf:sameas _gpfRead
     * @since 0.2.2
     * @deprecated since version 0.2.6, use {@link gpf.read} instead
     */
    gpf.fs.read = _gpfRead;

}
<|endoftext|>


<commit_before>/**
 * JBoss, Home of Professional Open Source
 * Copyright 2016, Red Hat, Inc. and/or its affiliates, and individual
 * contributors by the @authors tag. See the copyright.txt in the
 * distribution for a full listing of individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var express = require('express');
var request = require('request');
var os = require('os');
var app = express();

function define_cors(resp){
    resp.set('Access-Control-Allow-Origin', '*');
}

function say_bonjour(){
    return "Bonjour de " + os.hostname();
}

app.get('/api/bonjour', function(req, resp) {
    define_cors(resp);
    resp.send(say_bonjour());
});

app.get('/api/bonjour-chaining', function(req, resp) {
    define_cors(resp);
    request('http://aloha:8080/aloha', {timeout: 2000}, function(error, response, body) {
        var replies = [];
        var aloha_return;
        if (!error && response.statusCode == 200) {
            aloha_return = body;
        }else{
            aloha_return = "Generic Aloha response";
        }
        replies.push(say_bonjour());
        replies.push(aloha_return);
        resp.send(JSON.stringify(replies));
    })
});

var server = app.listen(8080, '0.0.0.0', function() {
    var host = server.address().address
    var port = server.address().port

    console.log("Bonjour service running at http://%s:%s", host, port)
});
<commit_msg>Changed endpoint<commit_after>/**
 * JBoss, Home of Professional Open Source
 * Copyright 2016, Red Hat, Inc. and/or its affiliates, and individual
 * contributors by the @authors tag. See the copyright.txt in the
 * distribution for a full listing of individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var express = require('express');
var request = require('request');
var os = require('os');
var app = express();

function define_cors(resp){
    resp.set('Access-Control-Allow-Origin', '*');
}

function say_bonjour(){
    return "Bonjour de " + os.hostname();
}

app.get('/api/bonjour', function(req, resp) {
    define_cors(resp);
    resp.send(say_bonjour());
});

app.get('/api/bonjour-chaining', function(req, resp) {
    define_cors(resp);
    request('http://aloha:8080/api/aloha', {timeout: 2000}, function(error, response, body) {
        var replies = [];
        var aloha_return;
        if (!error && response.statusCode == 200) {
            aloha_return = body;
        }else{
            aloha_return = "Generic Aloha response (FallBack!)";
        }
        replies.push(say_bonjour());
        replies.push(aloha_return);
        resp.send(JSON.stringify(replies));
    })
});

var server = app.listen(8080, '0.0.0.0', function() {
    var host = server.address().address
    var port = server.address().port

    console.log("Bonjour service running at http://%s:%s", host, port)
});
<|endoftext|>


<commit_before>/**
 * JBoss, Home of Professional Open Source
 * Copyright 2016, Red Hat, Inc. and/or its affiliates, and individual
 * contributors by the @authors tag. See the copyright.txt in the
 * distribution for a full listing of individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var express = require('express');
var request = require('request');
var os = require('os');
var app = express();

function define_cors(resp){
    resp.set('Access-Control-Allow-Origin', '*');
}

function say_bonjour(){
    return "Bonjour de " + os.hostname();
}

app.get('/bonjour', function(req, resp) {
    define_cors(resp);
    resp.send(say_bonjour());
});

app.get('/bonjour-chaining', function(req, resp) {
    define_cors(resp);
    request('http://aloha:8080/aloha', {timeout: 2000}, function(error, response, body) {
        var replies = [];
        var aloha_return;
        if (!error && response.statusCode == 200) {
            aloha_return = body;
        }else{
            aloha_return = "Error connecting to [aloha] service - Error Code: [" + error.code + "]";
        }
        replies.push(say_bonjour());
        replies.push(aloha_return);
        resp.send(JSON.stringify(replies));
    })
});

var server = app.listen(8080, '0.0.0.0', function() {
    var host = server.address().address
    var port = server.address().port

    console.log("Bonjour service running at http://%s:%s", host, port)
});
<commit_msg>Implemented Generic response<commit_after>/**
 * JBoss, Home of Professional Open Source
 * Copyright 2016, Red Hat, Inc. and/or its affiliates, and individual
 * contributors by the @authors tag. See the copyright.txt in the
 * distribution for a full listing of individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var express = require('express');
var request = require('request');
var os = require('os');
var app = express();

function define_cors(resp){
    resp.set('Access-Control-Allow-Origin', '*');
}

function say_bonjour(){
    return "Bonjour de " + os.hostname();
}

app.get('/bonjour', function(req, resp) {
    define_cors(resp);
    resp.send(say_bonjour());
});

app.get('/bonjour-chaining', function(req, resp) {
    define_cors(resp);
    request('http://aloha:8080/aloha', {timeout: 2000}, function(error, response, body) {
        var replies = [];
        var aloha_return;
        if (!error && response.statusCode == 200) {
            aloha_return = body;
        }else{
            aloha_return = "Generic Aloha response";
        }
        replies.push(say_bonjour());
        replies.push(aloha_return);
        resp.send(JSON.stringify(replies));
    })
});

var server = app.listen(8080, '0.0.0.0', function() {
    var host = server.address().address
    var port = server.address().port

    console.log("Bonjour service running at http://%s:%s", host, port)
});
<|endoftext|>


<commit_before>//require('./wunderground.js');

var LCD = require('jsupm_i2clcd');

// Load i2clcd module
var LCD = require('jsupm_i2clcd');

var date = new Date();
//Initialize Jhd1313m1 at 0x62 (RGB_ADDRESS) and 0x3E (LCD_ADDRESS)
var myLcd = new LCD.Jhd1313m1(0, 0x3E, 0x62);
myLcd.setColor(64,255,64);
setInterval(function() {
	myLcd.setCursor(0,0);
	myLcd.write('Hello World: ' + getDateTime()); // doesn't work for some reason
},1000);

function getDateTime() {

    var date = new Date();

    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;

    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;

    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;

    var year = date.getFullYear();

    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;

    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;

    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;

}<commit_msg>added a quick test lcd with clock<commit_after>//require('./wunderground.js');

var LCD = require('jsupm_i2clcd');

// Load i2clcd module
var LCD = require('jsupm_i2clcd');

var date = new Date();
//Initialize Jhd1313m1 at 0x62 (RGB_ADDRESS) and 0x3E (LCD_ADDRESS)
var myLcd = new LCD.Jhd1313m1(0, 0x3E, 0x62);
myLcd.setColor(64,255,64);
setInterval(function() {
	myLcd.setCursor(0,0);
	myLcd.write(getDateTime()); // doesn't work for some reason
},1000);

function getDateTime() {

    var date = new Date();

    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;

    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;

    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;

    var year = date.getFullYear();

    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;

    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;

    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;

}<|endoftext|>


<commit_before>"use strict";
/*eslint-disable no-invalid-this*/ // Because of the 'simple' class generation relying on lamda functions
/* MUST NOT BE MIGRATED TO ES6 BECAUSE USED IN A BROWSER */

function _noop () {}

/**
 * Simple class helper
 *
 * @param {Function} Constructor Constructor function
 * @param {Object} members Members dictionary
 * @param {Function} [Base] Base class
 * @return {Function} New class constructor
 * @private
 */
function _class (Constructor, members, Base) {
    var ResultConstructor;
    if (Base) {
        ResultConstructor = function () {
            Base.apply(this, arguments);
            Constructor.apply(this, arguments);
        };
        ResultConstructor.prototype = new Base();
    } else {
        ResultConstructor = function () {
            Constructor.apply(this, arguments);
        };
    }
    if (members) {
        Object.keys(members).forEach(function (memberName) {
            ResultConstructor.prototype[memberName] = members[memberName];
        });
    }
    return ResultConstructor;
}

/**
 * Part (Statement, Function, Branch) statistics
 *
 * @constructor
 * @class CoverageReport.PartStatistics
 */
var _PartStatistics = _class(_noop, {

    /** number of instances for this part */
    count: 0,

    /** number of tested instances */
    tested: 0,

    /** number of ignored instances */
    ignored: 0,

    /**
     * Increase tested or ignored count accordingly to what happened
     *
     * @param {Number} numberOfCall Number of calls extracted from the coverage report
     * @param {Object} partDefinition Part definition
     * Only skip (Boolean) is tested
     */
    _testedOrIgnored: function (numberOfCall, partDefinition) {
        if (numberOfCall > 0) {
            ++this.tested;
        } else if (partDefinition.skip) {
            ++this.ignored;
        }
    },

    /**
     * Common coverage processing
     *
     * @param {Number} numberOfCall Number of calls extracted from the coverage report
     * @param {Object} partDefinition Part definition
     */
    processCoverage: function (numberOfCall, partDefinition) {
        ++this.count;
        this._testedOrIgnored(numberOfCall, partDefinition);
    },

    /**
     * Adds information from another part statistics
     *
     * @param {CoverageReport.PartStatistics} partStatistics Statistics to add
     */
    add: function (partStatistics) {
        this.count += partStatistics.count;
        this.tested += partStatistics.tested;
        this.ignored += partStatistics.ignored;
    },

    // Generates percent value
    _toPercent: function (count, total, rounded) {
        if (rounded) {
            return Math.floor(100 * count / total);
        }
        return Math.floor(10000 * count / total) / 100;
    },

    /**
     * @param {Boolean} [rounded] Truncate decimals when true
     * @return {Number} Coverage ratio in percent
     */
    getCoverageRatio: function (rounded) {
        if (this.count === 0) {
            return 100;
        }
        return this._toPercent(this.tested + this.ignored, this.count, rounded);
    },

    /**
     * @param {Boolean} [rounded] Truncate decimals when true
     * @return {Number} Ignored ratio in percent
     */
    getIgnoredRatio: function (rounded) {
        if (this.count === 0) {
            return 0;
        }
        return this._toPercent(this.ignored, this.count, rounded);
    }

});

/**
 * Statement statistics
 *
 * @constructor
 * @class CoverageReport.StatementStatistics
 */
var _StatementStatistics = _class(_noop, null, _PartStatistics);

/**
 * Function statistics
 *
 * @constructor
 * @class CoverageReport.FunctionStatistics
 */
var _FunctionStatistics = _class(_noop, null, _PartStatistics);

/**
 * Branch statistics
 *
 * @constructor
 * @class CoverageReport.BranchStatistics
 */
var _BranchStatistics = _class(_noop, {

    /**
     * Branch-specific coverage processing
     *
     * @param {Number[]} numberOfCalls Number of calls extracted from the coverage report (one per branch)
     * @param {Object} branchDefinition Branch definition
     * locations array will used to fetch skip property of each branch
     */
    processCoverage: function (numberOfCalls, branchDefinition) {
        this.count += 2;
        this._testedOrIgnored(numberOfCalls[0], branchDefinition.locations[0]);
        this._testedOrIgnored(numberOfCalls[1], branchDefinition.locations[1]);
    }

}, _PartStatistics);

//region Region File statistics structure

/**
 * File statistics
 *
 * @param {String} name
 * @constructor
 */
var _File = _class(function (optionalName) {
    if (optionalName) {
        this.name = optionalName.replace(/\\/g, "/").split("src/")[1].split(".js")[0];
    }
    this.statements = new _StatementStatistics();
    this.functions = new _FunctionStatistics();
    this.branches = new _BranchStatistics();
}, {

    /** file name */
    name: "",

    /**
     * Statements statistics
     *
     * @type {CoverageReport.StatementStatistics}
     */
    statements: null,

    /**
     * Functions statistics
     *
     * @type {CoverageReport.FunctionStatistics}
     */
    functions: null,

    /**
     * Branches statistics
     *
     * @type {CoverageReport.BranchStatistics}
     */
    branches: null

});

/**
 * Process the coverage data and generate a consolidated report
 *
 * @param {Object} coverageData Data produced by istanbul
 * @constructor
 * @class CoverageReport
 */
var CoverageReport = _class(function (coverageData) {
    this._data = coverageData;
    this._compute();
}, {

    /** coverage data */
    _data: null,

    /** dictionary of coverage per file */
    _files: null,

    /**
     * Global coverage
     *
     * @type {CoverageReport.File}
     */
    _global: null,

    /**
     * Compute coverage for one file
     *
     * @param {String} fileName File name
     * @return {CoverageReport.File} Coverage for one file
     */
    _computeFileCoverage: function (fileName) {
        var result = new _File(fileName),
            fileData = this._data[fileName];
        [{
            type: "statements",
            data: "s",
            map: "statementMap"
        }, {
            type: "functions",
            data: "f",
            map: "fnMap"
        }, {
            type: "branches",
            data: "b",
            map: "branchMap"
        }].forEach(function (part) {
            var map = fileData[part.map],
                data = fileData[part.data],
                statistics = result[part.type],
                index = 1;
            while (undefined !== data[index]) {
                statistics.processCoverage(data[index], map[index]);
                ++index;
            }
        });
        return result;
    },

    /** Compute all coverages */
    _compute: function () {
        this._files = {};
        this._global = new _File();
        Object.keys(this._data).forEach(function (fileName) {
            var fileCoverage = this._computeFileCoverage(fileName);
            this._files[fileCoverage.name] = fileCoverage;
            this._global.statements.add(fileCoverage.statements);
            this._global.functions.add(fileCoverage.functions);
            this._global.branches.add(fileCoverage.branches);
        }, this);
    },

    /**
     * Get file coverage information
     *
     * @param {String} fileName Name of the file to obtain
     * @return {_File|undefined} Coverage information
     */
    get: function (fileName) {
        return this._files[fileName];
    },

    /**
     * Get consolidated coverage information
     *
     * @return {_File} Coverage information
     */
    getGlobal: function () {
        return this._global;
    }

});

module.exports = CoverageReport;
<commit_msg>no-magic-numbers (#280)<commit_after>"use strict";
/*eslint-disable no-invalid-this*/ // Because of the 'simple' class generation relying on lamda functions
/* MUST NOT BE MIGRATED TO ES6 BECAUSE USED IN A BROWSER */

/*eslint no-magic-numbers: ["error", { "ignore": [-1, 0, 1, 100, 10000] }]*/

function _noop () {}

/**
 * Simple class helper
 *
 * @param {Function} Constructor Constructor function
 * @param {Object} members Members dictionary
 * @param {Function} [Base] Base class
 * @return {Function} New class constructor
 * @private
 */
function _class (Constructor, members, Base) {
    var ResultConstructor;
    if (Base) {
        ResultConstructor = function () {
            Base.apply(this, arguments);
            Constructor.apply(this, arguments);
        };
        ResultConstructor.prototype = new Base();
    } else {
        ResultConstructor = function () {
            Constructor.apply(this, arguments);
        };
    }
    if (members) {
        Object.keys(members).forEach(function (memberName) {
            ResultConstructor.prototype[memberName] = members[memberName];
        });
    }
    return ResultConstructor;
}

/**
 * Part (Statement, Function, Branch) statistics
 *
 * @constructor
 * @class CoverageReport.PartStatistics
 */
var _PartStatistics = _class(_noop, {

    /** number of instances for this part */
    count: 0,

    /** number of tested instances */
    tested: 0,

    /** number of ignored instances */
    ignored: 0,

    /**
     * Increase tested or ignored count accordingly to what happened
     *
     * @param {Number} numberOfCall Number of calls extracted from the coverage report
     * @param {Object} partDefinition Part definition
     * Only skip (Boolean) is tested
     */
    _testedOrIgnored: function (numberOfCall, partDefinition) {
        if (numberOfCall > 0) {
            ++this.tested;
        } else if (partDefinition.skip) {
            ++this.ignored;
        }
    },

    /**
     * Common coverage processing
     *
     * @param {Number} numberOfCall Number of calls extracted from the coverage report
     * @param {Object} partDefinition Part definition
     */
    processCoverage: function (numberOfCall, partDefinition) {
        ++this.count;
        this._testedOrIgnored(numberOfCall, partDefinition);
    },

    /**
     * Adds information from another part statistics
     *
     * @param {CoverageReport.PartStatistics} partStatistics Statistics to add
     */
    add: function (partStatistics) {
        this.count += partStatistics.count;
        this.tested += partStatistics.tested;
        this.ignored += partStatistics.ignored;
    },

    // Generates percent value
    _toPercent: function (count, total, rounded) {
        if (rounded) {
            return Math.floor(100 * count / total);
        }
        return Math.floor(10000 * count / total) / 100;
    },

    /**
     * @param {Boolean} [rounded] Truncate decimals when true
     * @return {Number} Coverage ratio in percent
     */
    getCoverageRatio: function (rounded) {
        if (this.count === 0) {
            return 100;
        }
        return this._toPercent(this.tested + this.ignored, this.count, rounded);
    },

    /**
     * @param {Boolean} [rounded] Truncate decimals when true
     * @return {Number} Ignored ratio in percent
     */
    getIgnoredRatio: function (rounded) {
        if (this.count === 0) {
            return 0;
        }
        return this._toPercent(this.ignored, this.count, rounded);
    }

});

/**
 * Statement statistics
 *
 * @constructor
 * @class CoverageReport.StatementStatistics
 */
var _StatementStatistics = _class(_noop, null, _PartStatistics);

/**
 * Function statistics
 *
 * @constructor
 * @class CoverageReport.FunctionStatistics
 */
var _FunctionStatistics = _class(_noop, null, _PartStatistics);

/**
 * Branch statistics
 *
 * @constructor
 * @class CoverageReport.BranchStatistics
 */
var _BranchStatistics = _class(_noop, {

    /**
     * Branch-specific coverage processing
     *
     * @param {Number[]} numberOfCalls Number of calls extracted from the coverage report (one per branch)
     * @param {Object} branchDefinition Branch definition
     * locations array will used to fetch skip property of each branch
     */
    processCoverage: function (numberOfCalls, branchDefinition) {
        this.count += 2;
        this._testedOrIgnored(numberOfCalls[0], branchDefinition.locations[0]);
        this._testedOrIgnored(numberOfCalls[1], branchDefinition.locations[1]);
    }

}, _PartStatistics);

//region Region File statistics structure

/**
 * File statistics
 *
 * @param {String} name
 * @constructor
 */
var _File = _class(function (optionalName) {
    if (optionalName) {
        this.name = optionalName.replace(/\\/g, "/").split("src/")[1].split(".js")[0];
    }
    this.statements = new _StatementStatistics();
    this.functions = new _FunctionStatistics();
    this.branches = new _BranchStatistics();
}, {

    /** file name */
    name: "",

    /**
     * Statements statistics
     *
     * @type {CoverageReport.StatementStatistics}
     */
    statements: null,

    /**
     * Functions statistics
     *
     * @type {CoverageReport.FunctionStatistics}
     */
    functions: null,

    /**
     * Branches statistics
     *
     * @type {CoverageReport.BranchStatistics}
     */
    branches: null

});

/**
 * Process the coverage data and generate a consolidated report
 *
 * @param {Object} coverageData Data produced by istanbul
 * @constructor
 * @class CoverageReport
 */
var CoverageReport = _class(function (coverageData) {
    this._data = coverageData;
    this._compute();
}, {

    /** coverage data */
    _data: null,

    /** dictionary of coverage per file */
    _files: null,

    /**
     * Global coverage
     *
     * @type {CoverageReport.File}
     */
    _global: null,

    /**
     * Compute coverage for one file
     *
     * @param {String} fileName File name
     * @return {CoverageReport.File} Coverage for one file
     */
    _computeFileCoverage: function (fileName) {
        var result = new _File(fileName),
            fileData = this._data[fileName];
        [{
            type: "statements",
            data: "s",
            map: "statementMap"
        }, {
            type: "functions",
            data: "f",
            map: "fnMap"
        }, {
            type: "branches",
            data: "b",
            map: "branchMap"
        }].forEach(function (part) {
            var map = fileData[part.map],
                data = fileData[part.data],
                statistics = result[part.type],
                index = 1;
            while (undefined !== data[index]) {
                statistics.processCoverage(data[index], map[index]);
                ++index;
            }
        });
        return result;
    },

    /** Compute all coverages */
    _compute: function () {
        this._files = {};
        this._global = new _File();
        Object.keys(this._data).forEach(function (fileName) {
            var fileCoverage = this._computeFileCoverage(fileName);
            this._files[fileCoverage.name] = fileCoverage;
            this._global.statements.add(fileCoverage.statements);
            this._global.functions.add(fileCoverage.functions);
            this._global.branches.add(fileCoverage.branches);
        }, this);
    },

    /**
     * Get file coverage information
     *
     * @param {String} fileName Name of the file to obtain
     * @return {_File|undefined} Coverage information
     */
    get: function (fileName) {
        return this._files[fileName];
    },

    /**
     * Get consolidated coverage information
     *
     * @return {_File} Coverage information
     */
    getGlobal: function () {
        return this._global;
    }

});

module.exports = CoverageReport;
<|endoftext|>


<commit_before>#!/usr/bin/env node

var blake = require('../lib/blake.js')

;(function () {
  var arg = process.argv.splice(2)
    , isValid = !(arg && arg.length >= 2)

  if (isValid) {
    return console.error('Usage: blake source_directory target_directory [source_file ...]');
  }

  var source = arg.shift()
    , target = arg.shift()
    , files = arg

  blake(source, target, files, function (err) {
    if (err) return console.error(err)
    console.log('blake OK')
  }).on('item', function (item) {
    console.log('blake WRITE %s', item.path)
  })
})()
<commit_msg>Improve CLI<commit_after>#!/usr/bin/env node

var blake = require('../lib/blake.js')

;(function () {
  var arg = process.argv.splice(2)
    , isValid = !(arg && arg.length >= 2)

  if (isValid) {
    return console.error('Usage: blake source_directory target_directory [source_file ...]');
  }

  blake(arg.shift(), arg.shift(), arg, function (err) {
    if (err) return console.error(err)
    console.log('OK')
  }).on('item', function (item) {
    console.log(item.path)
  })
})()
<|endoftext|>


<commit_before>#!/usr/bin/env node
/**
		lucidtail
		i.e. lucidtail file*.log --udp4 514 -p 8080
		Copyright (C) 2013	David Duong

		https://github.com/davidnqd/lucidtail

		This program is free software: you can redistribute it and/or modify
		it under the terms of the GNU Affero General Public License as published by
		the Free Software Foundation, either version 3 of the License, or
		(at your option) any later version.

		This program is distributed in the hope that it will be useful,
		but WITHOUT ANY WARRANTY; without even the implied warranty of
		MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
		GNU Affero General Public License for more details.

		You should have received a copy of the GNU Affero General Public License
		along with this program.	If not, see <http://www.gnu.org/licenses/>.
*/

// Specify command line arguments
var optimist = require('optimist')
    .usage('A real-time zero-configuration web-based tail\nUsage: $0 [options] [file ...]')

    .alias('h', 'help')
    .alias('h', '?')
    .boolean('h')
    .default('h', false)
    .describe('h', 'Show this help')

    .alias('p', 'http_port')
    .describe('p', 'Specify the http port lucidtail services')
    .default('p', 8080)

    .alias('u', 'udp4')
    .describe('u', 'Emit incoming UDP messages on the specified port')

    .alias('t', 'test')
    .describe('t', 'Emit a test log message every second with the specified source name');

// Show usage
if (optimist.argv.help) {
	optimist.showHelp();
	process.exit(1);
}

var lucidtail = require('../lib');

// Create aggregate emitter
var emitter = new lucidtail(optimist.argv.http_port)
	.on('error', console.error.bind(console));

// Use Test listener
if (optimist.argv.test) {
	var arg = optimist.argv.test === true? 'Test' : optimist.argv.test;
	console.log('Recognized --test:', arg);
	try {
		emitter.listen(lucidtail.createEmitter('test', optimist.argv.test));
	} catch (e) {
		console.error('Invalid argument (--test):', e.message);
	}
}

// Use UDP4 listener
if (optimist.argv.udp4) {
	console.log('Recognized --udp4:', optimist.argv.udp4);
	try {
		emitter.listen(lucidtail.createEmitter('udp4', optimist.argv.udp4));
	} catch (e) {
		console.error('Invalid argument (--port):', e.message);
	}
}

// Use file listeners
// FIXME: Use a native approach instead of tail: e.g. fs.watch
for (var i = 0; i < optimist.argv._.length; i++) {
	console.log('Recognized --file:', optimist.argv._[i]);
	try {
		emitter.listen(lucidtail.createEmitter('tail', optimist.argv._[i]));
	} catch (e) {
		console.error('Invalid argument (--file):', e.message);
	}
}<commit_msg>Got rid of unneccessary error handling<commit_after>#!/usr/bin/env node
/**
		lucidtail
		i.e. lucidtail file*.log --udp4 514 -p 8080
		Copyright (C) 2013	David Duong

		https://github.com/davidnqd/lucidtail

		This program is free software: you can redistribute it and/or modify
		it under the terms of the GNU Affero General Public License as published by
		the Free Software Foundation, either version 3 of the License, or
		(at your option) any later version.

		This program is distributed in the hope that it will be useful,
		but WITHOUT ANY WARRANTY; without even the implied warranty of
		MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
		GNU Affero General Public License for more details.

		You should have received a copy of the GNU Affero General Public License
		along with this program.	If not, see <http://www.gnu.org/licenses/>.
*/

// Specify command line arguments
var optimist = require('optimist')
    .usage('A real-time zero-configuration web-based tail\nUsage: $0 [options] [file ...]')

    .alias('h', 'help')
    .alias('h', '?')
    .boolean('h')
    .default('h', false)
    .describe('h', 'Show this help')

    .alias('p', 'http_port')
    .describe('p', 'Specify the http port lucidtail services')
    .default('p', 8080)

    .alias('u', 'udp4')
    .describe('u', 'Emit incoming UDP messages on the specified port')

    .alias('t', 'test')
    .describe('t', 'Emit a test log message every second with the specified source name');

// Show usage
if (optimist.argv.help) {
	optimist.showHelp();
	process.exit(0);
}

// Create aggregate emitter
var lucidtail = require('../lib');
var emitter = new lucidtail(optimist.argv.http_port)
	.on('error', console.error.bind(console));

// Use Test listener
if (optimist.argv.test) {
	var arg = optimist.argv.test === true? 'Test' : optimist.argv.test;
	console.log('Recognized --test:', arg);
	emitter.listen(lucidtail.createEmitter('test', optimist.argv.test));
}

// Use UDP4 listener
if (optimist.argv.udp4) {
	console.log('Recognized --udp4:', optimist.argv.udp4);
	emitter.listen(lucidtail.createEmitter('udp4', optimist.argv.udp4));
}

// Use file listeners
// FIXME: Use a native approach instead of tail: e.g. fs.watch
for (var i = 0; i < optimist.argv._.length; i++) {
	console.log('Recognized --file:', optimist.argv._[i]);
	emitter.listen(lucidtail.createEmitter('tail', optimist.argv._[i]));
}<|endoftext|>