<commit_before>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // default font size in pixels for all tabs
    fontSize: 18,

    // font family with optional fallbacks
    fontFamily: 'Operator Mono',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(248,28,229,0.8)',

    // `BEAM` for |, `UNDERLINE` for _, `BLOCK` for █
    cursorShape: 'BLOCK',

    // set to true for blinking cursor
    cursorBlink: false,

    // color of the text
    foregroundColor: '#fff',

    // terminal background color
    backgroundColor: '#000',

    // border color (window, tabs)
    borderColor: '#333',

    // custom css to embed in the main window
    css: '',

    // custom css to embed in the terminal window
    termCSS: '',

    // set to `true` (without backticks) if you're using a Linux setup that doesn't show native menus
    // default: `false` on Linux, `true` on Windows (ignored on macOS)
    showHamburgerMenu: '',

    // set to `false` if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` on windows and Linux (ignored on macOS)
    showWindowControls: '',

    // custom padding (css format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#ff0000',
      green: '#33ff00',
      yellow: '#ffff00',
      blue: '#0066ff',
      magenta: '#cc00ff',
      cyan: '#00ffff',
      white: '#d0d0d0',
      lightBlack: '#808080',
      lightRed: '#ff0000',
      lightGreen: '#33ff00',
      lightYellow: '#ffff00',
      lightBlue: '#0066ff',
      lightMagenta: '#cc00ff',
      lightCyan: '#00ffff',
      lightWhite: '#ffffff',
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    // make sure to use a full path if the binary name doesn't work
    // (e.g `C:\\Windows\\System32\\bash.exe` instead of just `bash.exe`)
    // if you're using powershell, make sure to remove the `--login` below
    shell: 'zsh',

    // for setting shell arguments (i.e. for using interactive shellArgs: ['-i'])
    // by default ['--login'] will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to false for no bell
    bell: 'SOUND',

    // if true, selected text will automatically be copied to the clipboard
    copyOnSelect: false,

    // if true, on right click selected text will be copied or pasted if no
    // selection is present (true by default on Windows)
    // quickEdit: true

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: [
    'hyper-snazzy',
    'hypercwd',
    'hyperlinks',
    'hyper-statusline',
    'hyperterm-overlay',
  ],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  overlay: {
    alwaysOnTop: true,
    animate: true,
    hasShadow: false,
    hideDock: false,
    hideOnBlur: false,
    hotkeys: ['Option+Space'],
    position: 'top',
    primaryDisplay: false,
    resizable: true,
    startAlone: false,
    startup: false,
    size: 0.4,
    tray: true,
    unique: false,
  },
}
<commit_msg>Update Hyper config<commit_after>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    updateChannel: "stable",

    // default font size in pixels for all tabs
    fontSize: 18,

    // font family with optional fallbacks
    fontFamily: 'Operator Mono Lig',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(248,28,229,0.8)',

    // `BEAM` for |, `UNDERLINE` for _, `BLOCK` for █
    cursorShape: 'BLOCK',

    // set to true for blinking cursor
    cursorBlink: false,

    // color of the text
    foregroundColor: '#fff',

    // terminal background color
    backgroundColor: '#000',

    // border color (window, tabs)
    borderColor: '#333',

    // custom css to embed in the main window
    css: '',

    // custom css to embed in the terminal window
    termCSS: '',

    // set to `true` (without backticks) if you're using a Linux setup that doesn't show native menus
    // default: `false` on Linux, `true` on Windows (ignored on macOS)
    showHamburgerMenu: '',

    // set to `false` if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` on windows and Linux (ignored on macOS)
    showWindowControls: '',

    // custom padding (css format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#ff0000',
      green: '#33ff00',
      yellow: '#ffff00',
      blue: '#0066ff',
      magenta: '#cc00ff',
      cyan: '#00ffff',
      white: '#d0d0d0',
      lightBlack: '#808080',
      lightRed: '#ff0000',
      lightGreen: '#33ff00',
      lightYellow: '#ffff00',
      lightBlue: '#0066ff',
      lightMagenta: '#cc00ff',
      lightCyan: '#00ffff',
      lightWhite: '#ffffff',
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    // make sure to use a full path if the binary name doesn't work
    // (e.g `C:\\Windows\\System32\\bash.exe` instead of just `bash.exe`)
    // if you're using powershell, make sure to remove the `--login` below
    shell: 'zsh',

    // for setting shell arguments (i.e. for using interactive shellArgs: ['-i'])
    // by default ['--login'] will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to false for no bell
    bell: 'SOUND',

    // if true, selected text will automatically be copied to the clipboard
    copyOnSelect: false,

    // if true, on right click selected text will be copied or pasted if no
    // selection is present (true by default on Windows)
    // quickEdit: true

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: [
    'hyper-snazzy',
    'hypercwd',
    'hyper-statusline',
    'hyperterm-overlay',
    'hyper-search',
    'hyper-pane',
  ],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  overlay: {
    alwaysOnTop: true,
    animate: true,
    hasShadow: false,
    hideDock: false,
    hideOnBlur: false,
    hotkeys: ['Option+Space'],
    position: 'top',
    primaryDisplay: false,
    resizable: true,
    startAlone: false,
    startup: false,
    size: 0.4,
    tray: true,
    unique: false,
  },
}
<|endoftext|>


<commit_before>const child_process = require('child_process');
const async = require('async');
const fs = require('fs-extra');
const os = require('os');
const path = require('path');
const downloadFileSync = require('download-file-sync');
const commandExistsSync = require('command-exists').sync;

const config = require('pelias-config').generate(require('../schema'));

const wofDataHost = config.get('imports.whosonfirst.dataHost') || 'https://dist.whosonfirst.org';

function download(callback) {
  //ensure required directory structure exists
  fs.ensureDirSync(path.join(config.imports.whosonfirst.datapath, 'sqlite'));

  // download one bundle for every other CPU (tar and bzip2 can both max out one core)
  // (the maximum is configurable, to keep things from getting too intense, and defaults to 4)
  //lower this number to make the downloader more CPU friendly
  //raise this number to (possibly) make it faster
  const maxSimultaneousDownloads = config.get('imports.whosonfirst.maxDownloads') || 4;
  const cpuCount = os.cpus().length;
  const simultaneousDownloads = Math.max(maxSimultaneousDownloads, Math.min(1, cpuCount / 2));

  const generateSQLites = () => {
    const files = {};
    const content = JSON.parse(downloadFileSync(`${wofDataHost}/sqlite/inventory.json`))
      // Only latest compressed files
      .filter(e => e.name_compressed.indexOf('latest') >= 0)
      // Postalcodes only when importPostalcodes is ture and without --admin-only arg
      .filter(e => e.name_compressed.indexOf('postalcode') < 0 ||
        (config.imports.whosonfirst.importPostalcodes && process.argv[2] !== '--admin-only'))
      // Venues only when importVenues is true and without --admin-only arg
      .filter(e => e.name_compressed.indexOf('venue') < 0 ||
        (config.imports.whosonfirst.importVenues && process.argv[2] !== '--admin-only'))
      // We don't need constituency and intersection ?
      .filter(e => e.name_compressed.indexOf('constituency') < 0 && e.name_compressed.indexOf('intersection') < 0)
      // Remove duplicates based on name, we can have differents name_compressed
      // (for example whosonfirst-data-latest.db.bz2 and whosonfirst-data-latest.db.tar.bz2)
      // but with the same name... We will take the newer version.
      .forEach(e => {
        if (files[e.name] && new Date(e.last_modified) > new Date(files[e.name].last_modified)) {
          files[e.name] = e;
        } else if (!files[e.name]) {
          files[e.name] = e;
        }
      });
    return Object.values(files);
  };

  const generateCommand = (sqlite, directory) => {
    let extract;
    if (/\.db\.bz2$/.test(sqlite.name_compressed)) {
      // Check if we have lbzip2 installed
      if (commandExistsSync('lbzip2')) {
        extract = 'lbzip2';
      } else {
        extract = 'bunzip';
      }
    } else if (/\.db\.tar\.bz2$/.test(sqlite.name_compressed)) {
      // Check if we have lbzip2 installed
      if (commandExistsSync('lbzip2')) {
        extract = 'tar -xO --use-compress-program=lbzip2';
      } else {
        extract = 'tar -xj';
      }
    } else {
      throw new Error('What is this extension ?!?');
    }

    return `curl -s ${wofDataHost}/sqlite/${sqlite.name_compressed} | ${extract} > ${path.join(directory, 'sqlite', sqlite.name)}`;
  };

  const downloadFunctions = generateSQLites().map(function (sqlite) {
    return function downloadABundle(callback) {
      const cmd = generateCommand(sqlite, config.imports.whosonfirst.datapath);
      console.log('Downloading ' + sqlite.name_compressed);
      child_process.exec(cmd, function commandCallback(error, stdout, stderr) {
        console.log('done downloading ' + sqlite.name_compressed);
        if (error) {
          console.error('error downloading ' + sqlite.name_compressed + error);
          console.log(stderr);
        }
        callback();
      });
    };
  });

  async.parallelLimit(downloadFunctions, simultaneousDownloads, callback);
}

module.exports.download = download;
<commit_msg>fix(download): Use correct `bunzip2`<commit_after>const child_process = require('child_process');
const async = require('async');
const fs = require('fs-extra');
const os = require('os');
const path = require('path');
const downloadFileSync = require('download-file-sync');
const commandExistsSync = require('command-exists').sync;

const config = require('pelias-config').generate(require('../schema'));

const wofDataHost = config.get('imports.whosonfirst.dataHost') || 'https://dist.whosonfirst.org';

function download(callback) {
  //ensure required directory structure exists
  fs.ensureDirSync(path.join(config.imports.whosonfirst.datapath, 'sqlite'));

  // download one bundle for every other CPU (tar and bzip2 can both max out one core)
  // (the maximum is configurable, to keep things from getting too intense, and defaults to 4)
  //lower this number to make the downloader more CPU friendly
  //raise this number to (possibly) make it faster
  const maxSimultaneousDownloads = config.get('imports.whosonfirst.maxDownloads') || 4;
  const cpuCount = os.cpus().length;
  const simultaneousDownloads = Math.max(maxSimultaneousDownloads, Math.min(1, cpuCount / 2));

  const generateSQLites = () => {
    const files = {};
    const content = JSON.parse(downloadFileSync(`${wofDataHost}/sqlite/inventory.json`))
      // Only latest compressed files
      .filter(e => e.name_compressed.indexOf('latest') >= 0)
      // Postalcodes only when importPostalcodes is ture and without --admin-only arg
      .filter(e => e.name_compressed.indexOf('postalcode') < 0 ||
        (config.imports.whosonfirst.importPostalcodes && process.argv[2] !== '--admin-only'))
      // Venues only when importVenues is true and without --admin-only arg
      .filter(e => e.name_compressed.indexOf('venue') < 0 ||
        (config.imports.whosonfirst.importVenues && process.argv[2] !== '--admin-only'))
      // We don't need constituency and intersection ?
      .filter(e => e.name_compressed.indexOf('constituency') < 0 && e.name_compressed.indexOf('intersection') < 0)
      // Remove duplicates based on name, we can have differents name_compressed
      // (for example whosonfirst-data-latest.db.bz2 and whosonfirst-data-latest.db.tar.bz2)
      // but with the same name... We will take the newer version.
      .forEach(e => {
        if (files[e.name] && new Date(e.last_modified) > new Date(files[e.name].last_modified)) {
          files[e.name] = e;
        } else if (!files[e.name]) {
          files[e.name] = e;
        }
      });
    return Object.values(files);
  };

  const generateCommand = (sqlite, directory) => {
    let extract;
    if (/\.db\.bz2$/.test(sqlite.name_compressed)) {
      // Check if we have lbzip2 installed
      if (commandExistsSync('lbzip2')) {
        extract = 'lbzip2';
      } else {
        extract = 'bunzip2';
      }
    } else if (/\.db\.tar\.bz2$/.test(sqlite.name_compressed)) {
      // Check if we have lbzip2 installed
      if (commandExistsSync('lbzip2')) {
        extract = 'tar -xO --use-compress-program=lbzip2';
      } else {
        extract = 'tar -xj';
      }
    } else {
      throw new Error('What is this extension ?!?');
    }

    return `curl -s ${wofDataHost}/sqlite/${sqlite.name_compressed} | ${extract} > ${path.join(directory, 'sqlite', sqlite.name)}`;
  };

  const downloadFunctions = generateSQLites().map(function (sqlite) {
    return function downloadABundle(callback) {
      const cmd = generateCommand(sqlite, config.imports.whosonfirst.datapath);
      console.log('Downloading ' + sqlite.name_compressed);
      child_process.exec(cmd, function commandCallback(error, stdout, stderr) {
        console.log('done downloading ' + sqlite.name_compressed);
        if (error) {
          console.error('error downloading ' + sqlite.name_compressed + error);
          console.log(stderr);
        }
        callback();
      });
    };
  });

  async.parallelLimit(downloadFunctions, simultaneousDownloads, callback);
}

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


<commit_before>var PLUGINS = ['./plugins/greet', './plugins/weather'];
var jQuery =require('jQuery');
var requirejs = require('requirejs');
requirejs.config({
    //Use node's special variable __dirname to
    //get the directory containing this file.
    //Useful if building a library that will
    //be used in node but does not require the
    //use of node outside
    baseUrl: __dirname,

    //Pass the top-level main.js/index.js require
    //function to requirejs so that node modules
    //are loaded relative to the top-level JS file.
    nodeRequire: require
});
var responsePlugins = [];

function initializePlugins(pluginNames) {

jQuery.each(pluginNames, function(index,name) {
requirejs([name],
function   (plugin) {
    responsePlugins.push(plugin);
});

});
}

function handleQuery(input) {

    var responses = [];

jQuery.each(responsePlugins, function(index,plugin) {
    responses[plugin.name] = plugin.reply({ rawInput: input, jQuery: jQuery } );
});
    return responses;
}

initializePlugins(PLUGINS);

var input = process.argv[2];
console.log(handleQuery(input));

<commit_msg>refactor the harness to repl nicely, start to librarize rei<commit_after>var PLUGINS = ['./plugins/greet', './plugins/weather'];
var jQuery =require('jQuery');
var requirejs = require('requirejs');
var repl = require("repl");

requirejs.config({
    //Use node's special variable __dirname to
    //get the directory containing this file.
    //Useful if building a library that will
    //be used in node but does not require the
    //use of node outside
    baseUrl: __dirname,

    //Pass the top-level main.js/index.js require
    //function to requirejs so that node modules
    //are loaded relative to the top-level JS file.
    nodeRequire: require
});

var Rei = { responsePlugins: [],

initializePlugins: function(pluginNames) {
    var that = this;

jQuery.each(pluginNames, function(index,name) {
requirejs([name],
function   (plugin) {
    that.responsePlugins.push(plugin);

});

});
},

    handleQuery: function(input) {
        var that = this;
    var responses = [];

jQuery.each(that.responsePlugins, function(index,plugin) {
    responses[plugin.name] = plugin.reply({ rawInput: input, jQuery: jQuery } );
});
    return responses;
}};

Rei.initializePlugins(PLUGINS);

// Hack up the REPL to do something useful for basic text input
function reiEval(cmd, context, filename, callback) {
    cmd = cmd.replace(/^./,'').replace(/.$/,'');
        var response = Rei.handleQuery(cmd);
        callback(null, response);
}

//A "local" node repl with a custom prompt
var local = repl.start({ eval: reiEval, prompt: "Say something? "    } );
<|endoftext|>


<commit_before>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // Choose either "stable" for receiving highly polished,
    // or "canary" for less polished but more frequent updates
    updateChannel: 'stable',

    // default font size in pixels for all tabs
    fontSize: 16,

    // font family with optional fallbacks
    fontFamily: 'MonoLisa, "Input Mono", "Anka/Coder", "Anonymous Pro", "SFMono-Light", Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(248,28,229,0.8)',

    // `BEAM` for |, `UNDERLINE` for _, `BLOCK` for █
    cursorShape: 'BLOCK',

    // set to true for blinking cursor
    cursorBlink: false,

    // color of the text
    foregroundColor: '#fff',

    // terminal background color
    backgroundColor: '#000',

    // border color (window, tabs)
    borderColor: '#333',

    // custom css to embed in the main window
    css: '.tabs_title { font-size: 14px; }',

    // custom css to embed in the terminal window
    termCSS: '',

    // set to `true` (without backticks) if you're using a Linux setup that doesn't show native menus
    // default: `false` on Linux, `true` on Windows (ignored on macOS)
    showHamburgerMenu: '',

    // set to `false` if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` on windows and Linux (ignored on macOS)
    showWindowControls: '',

    // custom padding (css format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#ff0000',
      green: '#33ff00',
      yellow: '#ffff00',
      blue: '#0066ff',
      magenta: '#cc00ff',
      cyan: '#00ffff',
      white: '#d0d0d0',
      lightBlack: '#808080',
      lightRed: '#ff0000',
      lightGreen: '#33ff00',
      lightYellow: '#ffff00',
      lightBlue: '#0066ff',
      lightMagenta: '#cc00ff',
      lightCyan: '#00ffff',
      lightWhite: '#ffffff'
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    //
    // Windows
    // - Make sure to use a full path if the binary name doesn't work
    // - Remove `--login` in shellArgs
    //
    // Bash on Windows
    // - Example: `C:\\Windows\\System32\\bash.exe`
    //
    // Powershell on Windows
    // - Example: `C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
    shell: '',

    // for setting shell arguments (i.e. for using interactive shellArgs: ['-i'])
    // by default ['--login'] will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to false for no bell
    bell: 'SOUND',

    // if true, selected text will automatically be copied to the clipboard
    copyOnSelect: false

    // if true, on right click selected text will be copied or pasted if no
    // selection is present (true by default on Windows)
    // quickEdit: true

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: ["hyperlinks", "hyper-one-dark"],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  keymaps: {
    // Example
    // 'window:devtools': 'cmd+alt+o',
  }
};
<commit_msg>Use SFMono for terminal font<commit_after>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // Choose either "stable" for receiving highly polished,
    // or "canary" for less polished but more frequent updates
    updateChannel: 'stable',

    // default font size in pixels for all tabs
    fontSize: 16,

    // font family with optional fallbacks
    fontFamily: 'SFMono-Regular, MonoLisa, "Input Mono", "Anka/Coder", "Anonymous Pro", Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

    // terminal cursor background color and opacity (hex, rgb, hsl, hsv, hwb or cmyk)
    cursorColor: 'rgba(248,28,229,0.8)',

    // `BEAM` for |, `UNDERLINE` for _, `BLOCK` for █
    cursorShape: 'BLOCK',

    // set to true for blinking cursor
    cursorBlink: false,

    // color of the text
    foregroundColor: '#fff',

    // terminal background color
    backgroundColor: '#000',

    // border color (window, tabs)
    borderColor: '#333',

    // custom css to embed in the main window
    css: '.tabs_title { font-size: 14px; }',

    // custom css to embed in the terminal window
    termCSS: '',

    // set to `true` (without backticks) if you're using a Linux setup that doesn't show native menus
    // default: `false` on Linux, `true` on Windows (ignored on macOS)
    showHamburgerMenu: '',

    // set to `false` if you want to hide the minimize, maximize and close buttons
    // additionally, set to `'left'` if you want them on the left, like in Ubuntu
    // default: `true` on windows and Linux (ignored on macOS)
    showWindowControls: '',

    // custom padding (css format, i.e.: `top right bottom left`)
    padding: '12px 14px',

    // the full list. if you're going to provide the full color palette,
    // including the 6 x 6 color cubes and the grayscale map, just provide
    // an array here instead of a color map object
    colors: {
      black: '#000000',
      red: '#ff0000',
      green: '#33ff00',
      yellow: '#ffff00',
      blue: '#0066ff',
      magenta: '#cc00ff',
      cyan: '#00ffff',
      white: '#d0d0d0',
      lightBlack: '#808080',
      lightRed: '#ff0000',
      lightGreen: '#33ff00',
      lightYellow: '#ffff00',
      lightBlue: '#0066ff',
      lightMagenta: '#cc00ff',
      lightCyan: '#00ffff',
      lightWhite: '#ffffff'
    },

    // the shell to run when spawning a new session (i.e. /usr/local/bin/fish)
    // if left empty, your system's login shell will be used by default
    //
    // Windows
    // - Make sure to use a full path if the binary name doesn't work
    // - Remove `--login` in shellArgs
    //
    // Bash on Windows
    // - Example: `C:\\Windows\\System32\\bash.exe`
    //
    // Powershell on Windows
    // - Example: `C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`
    shell: '',

    // for setting shell arguments (i.e. for using interactive shellArgs: ['-i'])
    // by default ['--login'] will be used
    shellArgs: ['--login'],

    // for environment variables
    env: {},

    // set to false for no bell
    bell: 'SOUND',

    // if true, selected text will automatically be copied to the clipboard
    copyOnSelect: false

    // if true, on right click selected text will be copied or pasted if no
    // selection is present (true by default on Windows)
    // quickEdit: true

    // URL to custom bell
    // bellSoundURL: 'http://example.com/bell.mp3',

    // for advanced config flags please refer to https://hyper.is/#cfg
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: ["hyperlinks", "hyper-one-dark"],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: [],

  keymaps: {
    // Example
    // 'window:devtools': 'cmd+alt+o',
  }
};
<|endoftext|>


<commit_before>(function () {

	var getId = function () {
		return Date.now() * Math.floor(Math.random() * 7);
	};

	var TodoStore = {
		subscribers: {},
		todos: (function () {
			if (localStorage.getItem('react-todo')) {
				return JSON.parse(localStorage.getItem('react-todo'));
			} else {
				return [];
			}
		})()
	};

	TodoStore.prototype = Object.prototype;

	TodoStore.prototype.publish = function (event) {
		if (!this.subscribers[event]) {
			return;
		}
		for (var i = 0; i < this.subscribers[event].length; i++) {
			this.subscribers[event][i]();
		}
	};

	TodoStore.prototype.subscribe = function (ev, func) {
		if (this.subscribers[ev]) {
			this.subscribers[ev].push(func)
		} else {
			this.subscribers[ev] = [func];
		}
	};

	TodoStore.prototype.save = function (todo) {
		todo.id = getId();
		this.todos.push(todo);
		this.publish('change');
	};

	TodoStore.prototype.toggleComplete = function (todo) {
		todo.completed = !todo.completed;
		this.publish('change');
	};

	TodoStore.prototype.completeAll = function () {
		this.todos.map(function (todo) {
			return todo.completed = true;
		});
		this.publish('change');
	};

	TodoStore.prototype.clearCompleted = function () {
		this.todos = this.todos.filter(function (todo) {
			return !todo.completed;
		}, this);
		this.publish('change');
	};

	TodoStore.prototype.clearAll = function () {
		this.todos = [];
		this.publish('change');
	};

	TodoStore.subscribe('change', function () {
		localStorage.setItem('react-todo', JSON.stringify(TodoStore.todos));
	});

	window.TodoStore = TodoStore;
})();<commit_msg>Change TodoStore to use Object.create.<commit_after>(function () {

	var getId = function () {
		return Date.now() * Math.floor(Math.random() * 7);
	};

	var TodoStore = Object.create({
		subscribers: {},
		todos: (function () {
			if (localStorage.getItem('react-todo')) {
				return JSON.parse(localStorage.getItem('react-todo'));
			} else {
				return [];
			}
		})(),

		publish: function (event) {
			if (!this.subscribers[event]) {
				return;
			}
			for (var i = 0; i < this.subscribers[event].length; i++) {
				this.subscribers[event][i]();
			}
		},

		subscribe: function (ev, func) {
			if (this.subscribers[ev]) {
				this.subscribers[ev].push(func)
			} else {
				this.subscribers[ev] = [func];
			}
		},

		save: function (todo) {
			todo.id = getId();
			this.todos.push(todo);
			this.publish('change');
		},

		toggleComplete: function (todo) {
			todo.completed = !todo.completed;
			this.publish('change');
		},

		completeAll: function () {
			this.todos.map(function (todo) {
				return todo.completed = true;
			});
			this.publish('change');
		},

		clearCompleted: function () {
			this.todos = this.todos.filter(function (todo) {
				return !todo.completed;
			}, this);
			this.publish('change');
		},

		clearAll: function () {
			this.todos = [];
			this.publish('change');
		}
	});

	TodoStore.subscribe('change', function () {
		localStorage.setItem('react-todo', JSON.stringify(TodoStore.todos));
	});

	window.TodoStore = TodoStore;
})();<|endoftext|>


<commit_before>// DarkFO
// Copyright (c) 2014 darkf
// Licensed under the terms of the zlib license

var ActionPoints = function(obj) {
	this.combat = 0;
	this.move = 0;
	this.attachedObject = obj
	this.resetAP()
}

ActionPoints.prototype.getMaxAP = function() {
	var bonusCombatAP = 0 //todo: replace with get function
	var bonusMoveAP = 0 //todo: replace with get function
	return {combat: 5 + Math.floor(this.attachedObject.stats.AGI/2) + bonusCombatAP, move: bonusMoveAP}
}

ActionPoints.prototype.resetAP = function() {
	var AP = this.getMaxAP();
	this.combat = AP.combat;
	this.move = AP.move;
}

ActionPoints.prototype.getAvailableMoveAP = function() {
	return this.combat + this.move
}

ActionPoints.prototype.getAvailableCombatAP = function() {
	return this.combat
}

ActionPoints.prototype.substractMoveAP = function(value) {
	if(this.getAvailableMoveAP() >= value)
	{
		this.move -= value
		if(this.move < 0)
		{
			var combatSubstract = -this.move
			if(this.substractCombatAP(combatSubstract))
			{
				this.move = 0
				return true
			}else{
				return false
			}
		}else{
			return true
		}
	}else{
		return false
	}
}

ActionPoints.prototype.substractCombatAP = function(value) {
	if(this.combat >= value)
	{
		this.combat -= value
		return true
	}else{
		return false
	}
}

var AI = function(combatant) {
	this.combatant = combatant

	if(AI.aiTxt === null) { // load AI.TXT
		AI.aiTxt = {}
		var ini = parseIni(getFileText("data/data/AI.TXT"))
		if(ini === null) throw "couldn't load AI.TXT"
		for(var key in ini) {
			ini[key].keyName = key
			AI.aiTxt[ini[key].packet_num] = ini[key]
		}
	}

	this.info = AI.aiTxt[this.combatant.pro.extra.AI]
	if(this.info === undefined)
		throw "no AI packet for " + combatant.toString() +
			  " (packet " + this.combatant.pro.extra.AI + ")"
}

AI.aiTxt = null // AI.TXT: packet num -> key/value

var Combat = function(objects, player) {
	this.combatants = []
	for(var i = 0; i < objects.length; i++) {
		if(objects[i].type === "critter") {
			this.combatants.push(objects[i])
			objects[i].ai = new AI(objects[i])

			if(objects[i].stats === undefined)
				throw "no stats"
			objects[i].dead = false
			objects[i].AP = new ActionPoints(objects[i])
		}
	}
	this.player = player
	if(this.player.stats === undefined)
		throw "no player stats"
	this.player.AP = new ActionPoints(player)
	this.turnNum = 0
	this.whoseTurn = -2
	this.inPlayerTurn = false
}

Combat.prototype.log = function(msg) {
	// Combat-related debug log
	console.log(msg)
}

Combat.prototype.getHitAndCrit = function (obj, target, region) {
	var WeaponSkill = 70
	var AC = 0
	var baseCrit = 50
	var critModifer = 0
	var hitChance = WeaponSkill - AC - regionHitChanceDecTable[region]
	var critChance = baseCrit + regionHitChanceDecTable[region]
	if(isNaN(hitChance)) throw "something went wrong with hit chance calculation"
	var returnThings = {}
	if(rollSkillCheck(hitChance, 0, true) === true) {
		if(rollSkillCheck(critChance, 0, true) === true) {
			var critLevel = Math.floor(Math.max(0, getRandomInt(critModifer,100+critModifer)) / 20)
			this.log("Crit level is: "+critLevel)
			//todo: find proper table
			var temp = CritterTable[0][region][critLevel].DoEffectsOn(target)
			returnThings = {hit:true, crit:true, DM: temp.DM, msgID: temp.msgID}
		}else{
			returnThings = {hit:true, crit:false}
		}
	}else{
		returnThings = {hit:false}
	}
	return returnThings
}

Combat.prototype.getDamageDone = function(obj, target,critModifer) {
	var wep = obj.leftHand

	var RD = getRandomInt(wep.minDmg, wep.maxDmg) // rand damage min..max
	var RB = 0 // ranged bonus (via perk)
	var CM = critModifer // critical hit damage multiplier
	var ADR = 0 // damage resistance (TODO: armor)
	var ADT = 0 // damage threshold (TODO: armor)
	var X = 2 // ammo dividend
	var Y = 1 // ammo divisor
	var RM = 0 // ammo resistance modifier
	var CD = 100 // combat difficulty modifier (easy = 75%, normal = 100%, hard = 125%)

	var ammoDamageMult = X / Y

	var baseDamage = (CM/2) * ammoDamageMult * (RD+RB) * (CD / 100)
	var adjustedDamage = Math.max(0, baseDamage - ADT)

	return Math.ceil(adjustedDamage * (1 - (ADR+RM)/100))
}

Combat.prototype.getCombatMsg = function(ID)
{
	return getMessage("combat",ID)
}

Combat.prototype.attack = function(obj, target, callback) {
	// turn to face the target
	var hex = hexNearestNeighbor(obj.position, target.position)
	if(hex !== null)
		obj.orientation = hex.direction

	// attack!
	critterStaticAnim(obj, "attack", callback)

	var who = obj.isPlayer ? "You" : critterGetName(obj)
	var targetName = target.isPlayer ? "you" : critterGetName(target)
	var hitCritAndMore = this.getHitAndCrit(obj,target,"torso")

	// todo: critical misses

	if(hitCritAndMore.hit === true) {
		var critModifier = hitCritAndMore.crit ? hitCritAndMore.DM : 2
		var damage = this.getDamageDone(obj, target, critModifier)
		this.log(who + " hit " + targetName + " for " + damage + " damage")

		if(hitCritAndMore.crit === true)
			this.log(this.getCombatMsg(hitCritAndMore.msgID))

		target.stats.HP -= damage
		if(target.stats.HP <= 0)
			combat.perish(target)
	}
	else
		this.log(who + " missed " + targetName)
}

Combat.prototype.perish = function(obj){
	this.log("...And killed them.")
	obj.dead = true
	if(critterHasAnim(obj, "death"))
		critterStaticAnim(obj, "death", function() {
		// todo: corpse-ify
		obj.frame-- // go to last frame
		obj.anim = undefined
	})
	//this.combatants.pop(obj)
}

Combat.prototype.getCombatAIMessage = function(id) {
	return getMessage("combatai", id)
}

Combat.prototype.maybeTaunt = function(obj, type, roll) {
	if(roll === false) return
	var msgID = getRandomInt(parseInt(obj.ai.info[type+"_start"]),
	                         parseInt(obj.ai.info[type+"_end"]))
	this.log("[TAUNT " + critterGetName(obj) + ": " + this.getCombatAIMessage(msgID) + "]")
}

Combat.prototype.findTarget = function(obj) {
	// todo: find target according to AI rules
	return this.player
}

Combat.prototype.walkUpTo = function(obj, idx, target, maxDistance, callback) {
	// Walk up to `maxDistance` hexes, adjusting AP to fit
	if(critterWalkTo(obj, target, false, callback, maxDistance) !== false) {
		// OK
		this.AP[idx] -= obj.path.path.length
		return true
	}

	return false
}

Combat.prototype.doAITurn = function(obj, idx) {
	var that = this
	var target = this.findTarget(obj)
	var distance = hexDistance(obj.position, target.position)
	var AP = obj.AP
	var messageRoll = rollSkillCheck(obj.ai.info.chance,0,false)

	if(AP.getAvailableMoveAP() <= 0) // out of AP
		return this.nextTurn()

	// behaviors

	if(obj.stats.HP <= obj.ai.info.min_hp) { // hp <= min fleeing hp, so flee
		this.log("[AI FLEES]")
		// todo: pick the closest edge of the map
		this.maybeTaunt(obj, "run", messageRoll)
		var targetPos = {x: 128, y: obj.position.y} // left edge
		this.walkUpTo(obj, idx, targetPos, AP, function() {
			critterStopWalking(obj)
			that.doAITurn(obj, idx) // if we can, do another turn
		})
		return
	}

	var weapon = critterGetEquippedWeapon(obj)
	var fireDistance = weapon.getMaximumRange(1)
	this.log("DEBUG: weapon: " + weapon + " fireDistance: " + fireDistance +
		     " obj: " + obj.art + " distance: " + distance)
	// are we in firing distance?
	if(distance > fireDistance) {
		// todo: some sane direction, and also path checking
		this.log("[AI CREEPS]")
		var neighbors = hexNeighbors(target.position)
		var maxDistance = Math.min(AP.getAvailableMoveAP(), fireDistance)
		this.maybeTaunt(obj, "move", messageRoll)

		for(var i = 0; i < neighbors.length; i++) {
			if(critterWalkTo(obj, neighbors[i], false, function() {
				critterStopWalking(obj)
				that.doAITurn(obj, idx) // if we can, do another turn
			}, maxDistance) !== false) {
				// OK
				if(AP.substractMoveAP(obj.path.path.length) === false) throw "substraction Issue: has AP:"+AP.getAvailableMoveAP()+" needs AP:"+obj.path.path.length+" and maxDist was:"+maxDistance
				return
			}
		}

		// no path
		this.log("[NO PATH]")
		that.doAITurn(obj, idx) // if we can, do another turn
	}
	else if(AP.getAvailableCombatAP() >= 4) { // if we are in range, do we have enough AP to attack?
		this.log("[ATTACKING]")
		AP.substractCombatAP(4)

		if(critterGetEquippedWeapon(obj) === null)
			throw "combatant has no equipped weapon"

		this.attack(obj, target, function() {
			critterStopWalking(obj)
			that.doAITurn(obj, idx) // if we can, do another turn
		})
	}
	else this.nextTurn()
}

Combat.prototype.numAlive = function() {
	var count = 0
	for(var i = 0; i < this.combatants.length; i++) {
		if(this.combatants[i].dead !== true)
			count++
	}
	return count
}

Combat.prototype.end = function() {
	console.log("[end combat]")
	combat = null // todo: invert control
	inCombat = false
}

Combat.prototype.nextTurn = function() {
	if(this.numAlive() === 0)
		return this.end()

	this.whoseTurn++
	if(this.whoseTurn >= this.combatants.length) {
		// end of turn
		this.whoseTurn = -1
	}

	if(this.whoseTurn === -1) {
		// player
		this.inPlayerTurn = true
		this.player.AP.resetAP()
	}
	else {
		this.inPlayerTurn = false
		var critter = this.combatants[this.whoseTurn]
		if(critter.dead === true)
			return this.nextTurn()
		// todo: convert unused AP into AC
		critter.AP.resetAP()
		this.doAITurn(critter, this.whoseTurn)
	}
}<commit_msg>combat: clean up getHitAndCrit -> rollHit<commit_after>// DarkFO
// Copyright (c) 2014 darkf
// Licensed under the terms of the zlib license

var ActionPoints = function(obj) {
	this.combat = 0;
	this.move = 0;
	this.attachedObject = obj
	this.resetAP()
}

ActionPoints.prototype.getMaxAP = function() {
	var bonusCombatAP = 0 //todo: replace with get function
	var bonusMoveAP = 0 //todo: replace with get function
	return {combat: 5 + Math.floor(this.attachedObject.stats.AGI/2) + bonusCombatAP, move: bonusMoveAP}
}

ActionPoints.prototype.resetAP = function() {
	var AP = this.getMaxAP();
	this.combat = AP.combat;
	this.move = AP.move;
}

ActionPoints.prototype.getAvailableMoveAP = function() {
	return this.combat + this.move
}

ActionPoints.prototype.getAvailableCombatAP = function() {
	return this.combat
}

ActionPoints.prototype.substractMoveAP = function(value) {
	if(this.getAvailableMoveAP() >= value)
	{
		this.move -= value
		if(this.move < 0)
		{
			var combatSubstract = -this.move
			if(this.substractCombatAP(combatSubstract))
			{
				this.move = 0
				return true
			}else{
				return false
			}
		}else{
			return true
		}
	}else{
		return false
	}
}

ActionPoints.prototype.substractCombatAP = function(value) {
	if(this.combat >= value)
	{
		this.combat -= value
		return true
	}else{
		return false
	}
}

var AI = function(combatant) {
	this.combatant = combatant

	if(AI.aiTxt === null) { // load AI.TXT
		AI.aiTxt = {}
		var ini = parseIni(getFileText("data/data/AI.TXT"))
		if(ini === null) throw "couldn't load AI.TXT"
		for(var key in ini) {
			ini[key].keyName = key
			AI.aiTxt[ini[key].packet_num] = ini[key]
		}
	}

	this.info = AI.aiTxt[this.combatant.pro.extra.AI]
	if(this.info === undefined)
		throw "no AI packet for " + combatant.toString() +
			  " (packet " + this.combatant.pro.extra.AI + ")"
}

AI.aiTxt = null // AI.TXT: packet num -> key/value

var Combat = function(objects, player) {
	this.combatants = []
	for(var i = 0; i < objects.length; i++) {
		if(objects[i].type === "critter") {
			this.combatants.push(objects[i])
			objects[i].ai = new AI(objects[i])

			if(objects[i].stats === undefined)
				throw "no stats"
			objects[i].dead = false
			objects[i].AP = new ActionPoints(objects[i])
		}
	}
	this.player = player
	if(this.player.stats === undefined)
		throw "no player stats"
	this.player.AP = new ActionPoints(player)
	this.turnNum = 0
	this.whoseTurn = -2
	this.inPlayerTurn = false
}

Combat.prototype.log = function(msg) {
	// Combat-related debug log
	console.log(msg)
}

Combat.prototype.getHitChance = function(obj, target, region, critModifer) {
	var WeaponSkill = 70
	var AC = 0
	var baseCrit = 50
	var hitChance = WeaponSkill - AC - regionHitChanceDecTable[region]
	var critChance = baseCrit + regionHitChanceDecTable[region]
	if(isNaN(hitChance)) throw "something went wrong with hit chance calculation"
	return {hit: hitChance, crit: critChance}
}

Combat.prototype.rollHit = function (obj, target, region) {
	var critModifer = 0
	var hitChance = this.getHitChance(obj, target, region, critModifer)

	if(rollSkillCheck(hitChance.hit, 0, true) === true) {
		if(rollSkillCheck(hitChance.crit, 0, true) === true) {
			var critLevel = Math.floor(Math.max(0, getRandomInt(critModifer,100+critModifer)) / 20)
			this.log("crit level: " + critLevel)
			// todo: find proper table
			var temp = CritterTable[0][region][critLevel].DoEffectsOn(target)
			return {hit: true, crit: true, DM: temp.DM, msgID: temp.msgID} // crit
		}

		return {hit: true, crit: false} // hit
	}

	return {hit: false, crit: false} // miss
}

Combat.prototype.getDamageDone = function(obj, target, critModifer) {
	var wep = obj.leftHand

	var RD = getRandomInt(wep.minDmg, wep.maxDmg) // rand damage min..max
	var RB = 0 // ranged bonus (via perk)
	var CM = critModifer // critical hit damage multiplier
	var ADR = 0 // damage resistance (TODO: armor)
	var ADT = 0 // damage threshold (TODO: armor)
	var X = 2 // ammo dividend
	var Y = 1 // ammo divisor
	var RM = 0 // ammo resistance modifier
	var CD = 100 // combat difficulty modifier (easy = 75%, normal = 100%, hard = 125%)

	var ammoDamageMult = X / Y

	var baseDamage = (CM/2) * ammoDamageMult * (RD+RB) * (CD / 100)
	var adjustedDamage = Math.max(0, baseDamage - ADT)

	return Math.ceil(adjustedDamage * (1 - (ADR+RM)/100))
}

Combat.prototype.getCombatMsg = function(ID)
{
	return getMessage("combat",ID)
}

Combat.prototype.attack = function(obj, target, callback) {
	// turn to face the target
	var hex = hexNearestNeighbor(obj.position, target.position)
	if(hex !== null)
		obj.orientation = hex.direction

	// attack!
	critterStaticAnim(obj, "attack", callback)

	var who = obj.isPlayer ? "You" : critterGetName(obj)
	var targetName = target.isPlayer ? "you" : critterGetName(target)
	var hitRoll = this.rollHit(obj,target,"torso")

	// todo: critical misses

	if(hitRoll.hit === true) {
		var critModifier = hitRoll.crit ? hitRoll.DM : 2
		var damage = this.getDamageDone(obj, target, critModifier)
		this.log(who + " hit " + targetName + " for " + damage + " damage")

		if(hitRoll.crit === true)
			this.log(this.getCombatMsg(hitRoll.msgID))

		target.stats.HP -= damage
		if(target.stats.HP <= 0)
			combat.perish(target)
	}
	else
		this.log(who + " missed " + targetName)
}

Combat.prototype.perish = function(obj){
	this.log("...And killed them.")
	obj.dead = true
	if(critterHasAnim(obj, "death"))
		critterStaticAnim(obj, "death", function() {
		// todo: corpse-ify
		obj.frame-- // go to last frame
		obj.anim = undefined
	})
	//this.combatants.pop(obj)
}

Combat.prototype.getCombatAIMessage = function(id) {
	return getMessage("combatai", id)
}

Combat.prototype.maybeTaunt = function(obj, type, roll) {
	if(roll === false) return
	var msgID = getRandomInt(parseInt(obj.ai.info[type+"_start"]),
	                         parseInt(obj.ai.info[type+"_end"]))
	this.log("[TAUNT " + critterGetName(obj) + ": " + this.getCombatAIMessage(msgID) + "]")
}

Combat.prototype.findTarget = function(obj) {
	// todo: find target according to AI rules
	return this.player
}

Combat.prototype.walkUpTo = function(obj, idx, target, maxDistance, callback) {
	// Walk up to `maxDistance` hexes, adjusting AP to fit
	if(critterWalkTo(obj, target, false, callback, maxDistance) !== false) {
		// OK
		this.AP[idx] -= obj.path.path.length
		return true
	}

	return false
}

Combat.prototype.doAITurn = function(obj, idx) {
	var that = this
	var target = this.findTarget(obj)
	var distance = hexDistance(obj.position, target.position)
	var AP = obj.AP
	var messageRoll = rollSkillCheck(obj.ai.info.chance,0,false)

	if(AP.getAvailableMoveAP() <= 0) // out of AP
		return this.nextTurn()

	// behaviors

	if(obj.stats.HP <= obj.ai.info.min_hp) { // hp <= min fleeing hp, so flee
		this.log("[AI FLEES]")
		// todo: pick the closest edge of the map
		this.maybeTaunt(obj, "run", messageRoll)
		var targetPos = {x: 128, y: obj.position.y} // left edge
		this.walkUpTo(obj, idx, targetPos, AP, function() {
			critterStopWalking(obj)
			that.doAITurn(obj, idx) // if we can, do another turn
		})
		return
	}

	var weapon = critterGetEquippedWeapon(obj)
	var fireDistance = weapon.getMaximumRange(1)
	this.log("DEBUG: weapon: " + weapon + " fireDistance: " + fireDistance +
		     " obj: " + obj.art + " distance: " + distance)
	// are we in firing distance?
	if(distance > fireDistance) {
		// todo: some sane direction, and also path checking
		this.log("[AI CREEPS]")
		var neighbors = hexNeighbors(target.position)
		var maxDistance = Math.min(AP.getAvailableMoveAP(), fireDistance)
		this.maybeTaunt(obj, "move", messageRoll)

		for(var i = 0; i < neighbors.length; i++) {
			if(critterWalkTo(obj, neighbors[i], false, function() {
				critterStopWalking(obj)
				that.doAITurn(obj, idx) // if we can, do another turn
			}, maxDistance) !== false) {
				// OK
				if(AP.substractMoveAP(obj.path.path.length) === false) throw "substraction Issue: has AP:"+AP.getAvailableMoveAP()+" needs AP:"+obj.path.path.length+" and maxDist was:"+maxDistance
				return
			}
		}

		// no path
		this.log("[NO PATH]")
		that.doAITurn(obj, idx) // if we can, do another turn
	}
	else if(AP.getAvailableCombatAP() >= 4) { // if we are in range, do we have enough AP to attack?
		this.log("[ATTACKING]")
		AP.substractCombatAP(4)

		if(critterGetEquippedWeapon(obj) === null)
			throw "combatant has no equipped weapon"

		this.attack(obj, target, function() {
			critterStopWalking(obj)
			that.doAITurn(obj, idx) // if we can, do another turn
		})
	}
	else this.nextTurn()
}

Combat.prototype.numAlive = function() {
	var count = 0
	for(var i = 0; i < this.combatants.length; i++) {
		if(this.combatants[i].dead !== true)
			count++
	}
	return count
}

Combat.prototype.end = function() {
	console.log("[end combat]")
	combat = null // todo: invert control
	inCombat = false
}

Combat.prototype.nextTurn = function() {
	if(this.numAlive() === 0)
		return this.end()

	this.whoseTurn++
	if(this.whoseTurn >= this.combatants.length) {
		// end of turn
		this.whoseTurn = -1
	}

	if(this.whoseTurn === -1) {
		// player
		this.inPlayerTurn = true
		this.player.AP.resetAP()
	}
	else {
		this.inPlayerTurn = false
		var critter = this.combatants[this.whoseTurn]
		if(critter.dead === true)
			return this.nextTurn()
		// todo: convert unused AP into AC
		critter.AP.resetAP()
		this.doAITurn(critter, this.whoseTurn)
	}
}<|endoftext|>


<commit_before>
module.exports = {
  Combinator: require("./src/baconjs/Combinator"),
  combineVDOM: require("./src/baconjs/combineVDOM"),
  createComponent: require("./src/baconjs/createComponent"),
  createContainer: require("./src/baconjs/createContainer")
}

<commit_msg>Fix baconjs imports <commit_after>
module.exports = {
  Combinator: require("./lib/baconjs/Combinator"),
  combineVDOM: require("./lib/baconjs/combineVDOM"),
  createComponent: require("./lib/baconjs/createComponent"),
  createContainer: require("./lib/baconjs/createContainer")
}

<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme up<commit_msg>Correcting style<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme upd<|endoftext|>


<commit_before>/**
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * 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.
 */

const RED_COLOR = '\x1b[31m';
const GREEN_COLOR = '\x1b[32m';
const YELLOW_COLOR = '\x1b[33m';
const RESET_COLOR = '\x1b[0m';

class Reporter {
  constructor(runner, testFolder = null) {
    this._runner = runner;
    this._testFolder = testFolder;
    runner.on('started', this._onStarted.bind(this));
    runner.on('terminated', this._onTerminated.bind(this));
    runner.on('finished', this._onFinished.bind(this));
    runner.on('teststarted', this._onTestStarted.bind(this));
    runner.on('testfinished', this._onTestFinished.bind(this));
    this._workersState = new Map();
  }

  _onStarted() {
    this._timestamp = Date.now();
    console.log(`Running ${YELLOW_COLOR}${this._runner.parallel()}${RESET_COLOR} worker(s):\n`);
  }

  _onTerminated(message, error) {
    this._printTestResults();
    console.log(`${RED_COLOR}## TERMINATED ##${RESET_COLOR}`);
    console.log('Message:');
    console.log(`  ${RED_COLOR}${message}${RESET_COLOR}`);
    if (error && error.stack) {
      console.log('Stack:');
      console.log(error.stack.split('\n').map(line => '  ' + line).join('\n'));
    }
    console.log('WORKERS STATE');
    const workerIds = Array.from(this._workersState.keys());
    workerIds.sort();
    for (const workerId of workerIds) {
      const {isRunning, test} = this._workersState.get(workerId);
      let description = '';
      if (isRunning)
        description = `${YELLOW_COLOR}RUNNING${RESET_COLOR}`;
      else if (test.result === 'ok')
        description = `${GREEN_COLOR}OK${RESET_COLOR}`;
      else if (test.result === 'skipped')
        description = `${YELLOW_COLOR}SKIPPED${RESET_COLOR}`;
      else if (test.result === 'failed')
        description = `${RED_COLOR}FAILED${RESET_COLOR}`;
      else if (test.result === 'timedout')
        description = `${RED_COLOR}TIMEDOUT${RESET_COLOR}`;
      else
        description = `${RED_COLOR}<UNKNOWN>${RESET_COLOR}`;
      console.log(`  ${workerId}: [${description}] ${test.fullName} (${formatTestLocation(test)})`);
    }
    process.exit(2);
  }

  _onFinished() {
    this._printTestResults();
    const failedTests = this._runner.failedTests();
    process.exit(failedTests.length > 0 ? 1 : 0);
  }

  _printTestResults() {
    // 2 newlines after completing all tests.
    console.log('\n');

    const failedTests = this._runner.failedTests();
    if (failedTests.length > 0) {
      console.log('\nFailures:');
      for (let i = 0; i < failedTests.length; ++i) {
        const test = failedTests[i];
        console.log(`${i + 1}) ${test.fullName} (${formatTestLocation(test)})`);
        if (test.result === 'timedout') {
          console.log('  Message:');
          console.log(`    ${YELLOW_COLOR}Timeout Exceeded ${this._runner.timeout()}ms${RESET_COLOR}`);
        } else {
          console.log('  Message:');
          console.log(`    ${RED_COLOR}${test.error.message || test.error}${RESET_COLOR}`);
          console.log('  Stack:');
          if (test.error.stack)
            console.log(this._beautifyStack(test.error.stack));
        }
        if (test.output) {
          console.log('  Output:');
          console.log(test.output.split('\n').map(line => '    ' + line).join('\n'));
        }
        console.log('');
      }
    }

    const tests = this._runner.tests();
    const skippedTests = tests.filter(test => test.result === 'skipped');
    if (skippedTests.length > 0) {
      console.log('\nSkipped:');
      for (let i = 0; i < skippedTests.length; ++i) {
        const test = skippedTests[i];
        console.log(`${i + 1}) ${test.fullName}`);
        console.log(`  ${YELLOW_COLOR}Temporary disabled with xit${RESET_COLOR} ${formatTestLocation(test)}\n`);
      }
    }

    const executedTests = tests.filter(test => test.result);
    console.log(`\nRan ${executedTests.length} of ${tests.length} test(s)`);
    const milliseconds = Date.now() - this._timestamp;
    const seconds = milliseconds / 1000;
    console.log(`Finished in ${YELLOW_COLOR}${seconds}${RESET_COLOR} seconds`);
  }

  _beautifyStack(stack) {
    if (!this._testFolder)
      return stack;
    const lines = stack.split('\n').map(line => '    ' + line);
    // Find last stack line that include testrunner code.
    let index = 0;
    while (index < lines.length && !lines[index].includes(__dirname))
      ++index;
    while (index < lines.length && lines[index].includes(__dirname))
      ++index;
    if (index >= lines.length)
      return stack;
    const line = lines[index];
    const fromIndex = line.lastIndexOf(this._testFolder) + this._testFolder.length;
    const toIndex = line.lastIndexOf(')');
    lines[index] = line.substring(0, fromIndex) + YELLOW_COLOR + line.substring(fromIndex, toIndex) + RESET_COLOR + line.substring(toIndex);
    return lines.join('\n');
  }

  _onTestStarted(test, workerId) {
    this._workersState.set(workerId, {test, isRunning: true});
  }

  _onTestFinished(test, workerId) {
    this._workersState.set(workerId, {test, isRunning: false});
    if (test.result === 'ok')
      process.stdout.write(`${GREEN_COLOR}.${RESET_COLOR}`);
    else if (test.result === 'skipped')
      process.stdout.write(`${YELLOW_COLOR}*${RESET_COLOR}`);
    else if (test.result === 'failed')
      process.stdout.write(`${RED_COLOR}F${RESET_COLOR}`);
    else if (test.result === 'timedout')
      process.stdout.write(`${RED_COLOR}T${RESET_COLOR}`);
  }
}

function formatTestLocation(test) {
  const location = test.location;
  if (!location)
    return '';
  return `${location.fileName}:${location.lineNumber}:${location.columnNumber}`;
}

module.exports = Reporter;
<commit_msg>chore(testrunner): sort workers numerically when terminating (#3782)<commit_after>/**
 * Copyright 2017 Google Inc. All rights reserved.
 *
 * 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.
 */

const RED_COLOR = '\x1b[31m';
const GREEN_COLOR = '\x1b[32m';
const YELLOW_COLOR = '\x1b[33m';
const RESET_COLOR = '\x1b[0m';

class Reporter {
  constructor(runner, testFolder = null) {
    this._runner = runner;
    this._testFolder = testFolder;
    runner.on('started', this._onStarted.bind(this));
    runner.on('terminated', this._onTerminated.bind(this));
    runner.on('finished', this._onFinished.bind(this));
    runner.on('teststarted', this._onTestStarted.bind(this));
    runner.on('testfinished', this._onTestFinished.bind(this));
    this._workersState = new Map();
  }

  _onStarted() {
    this._timestamp = Date.now();
    console.log(`Running ${YELLOW_COLOR}${this._runner.parallel()}${RESET_COLOR} worker(s):\n`);
  }

  _onTerminated(message, error) {
    this._printTestResults();
    console.log(`${RED_COLOR}## TERMINATED ##${RESET_COLOR}`);
    console.log('Message:');
    console.log(`  ${RED_COLOR}${message}${RESET_COLOR}`);
    if (error && error.stack) {
      console.log('Stack:');
      console.log(error.stack.split('\n').map(line => '  ' + line).join('\n'));
    }
    console.log('WORKERS STATE');
    const workerIds = Array.from(this._workersState.keys());
    workerIds.sort((a, b) => a - b);
    for (const workerId of workerIds) {
      const {isRunning, test} = this._workersState.get(workerId);
      let description = '';
      if (isRunning)
        description = `${YELLOW_COLOR}RUNNING${RESET_COLOR}`;
      else if (test.result === 'ok')
        description = `${GREEN_COLOR}OK${RESET_COLOR}`;
      else if (test.result === 'skipped')
        description = `${YELLOW_COLOR}SKIPPED${RESET_COLOR}`;
      else if (test.result === 'failed')
        description = `${RED_COLOR}FAILED${RESET_COLOR}`;
      else if (test.result === 'timedout')
        description = `${RED_COLOR}TIMEDOUT${RESET_COLOR}`;
      else
        description = `${RED_COLOR}<UNKNOWN>${RESET_COLOR}`;
      console.log(`  ${workerId}: [${description}] ${test.fullName} (${formatTestLocation(test)})`);
    }
    process.exit(2);
  }

  _onFinished() {
    this._printTestResults();
    const failedTests = this._runner.failedTests();
    process.exit(failedTests.length > 0 ? 1 : 0);
  }

  _printTestResults() {
    // 2 newlines after completing all tests.
    console.log('\n');

    const failedTests = this._runner.failedTests();
    if (failedTests.length > 0) {
      console.log('\nFailures:');
      for (let i = 0; i < failedTests.length; ++i) {
        const test = failedTests[i];
        console.log(`${i + 1}) ${test.fullName} (${formatTestLocation(test)})`);
        if (test.result === 'timedout') {
          console.log('  Message:');
          console.log(`    ${YELLOW_COLOR}Timeout Exceeded ${this._runner.timeout()}ms${RESET_COLOR}`);
        } else {
          console.log('  Message:');
          console.log(`    ${RED_COLOR}${test.error.message || test.error}${RESET_COLOR}`);
          console.log('  Stack:');
          if (test.error.stack)
            console.log(this._beautifyStack(test.error.stack));
        }
        if (test.output) {
          console.log('  Output:');
          console.log(test.output.split('\n').map(line => '    ' + line).join('\n'));
        }
        console.log('');
      }
    }

    const tests = this._runner.tests();
    const skippedTests = tests.filter(test => test.result === 'skipped');
    if (skippedTests.length > 0) {
      console.log('\nSkipped:');
      for (let i = 0; i < skippedTests.length; ++i) {
        const test = skippedTests[i];
        console.log(`${i + 1}) ${test.fullName}`);
        console.log(`  ${YELLOW_COLOR}Temporary disabled with xit${RESET_COLOR} ${formatTestLocation(test)}\n`);
      }
    }

    const executedTests = tests.filter(test => test.result);
    console.log(`\nRan ${executedTests.length} of ${tests.length} test(s)`);
    const milliseconds = Date.now() - this._timestamp;
    const seconds = milliseconds / 1000;
    console.log(`Finished in ${YELLOW_COLOR}${seconds}${RESET_COLOR} seconds`);
  }

  _beautifyStack(stack) {
    if (!this._testFolder)
      return stack;
    const lines = stack.split('\n').map(line => '    ' + line);
    // Find last stack line that include testrunner code.
    let index = 0;
    while (index < lines.length && !lines[index].includes(__dirname))
      ++index;
    while (index < lines.length && lines[index].includes(__dirname))
      ++index;
    if (index >= lines.length)
      return stack;
    const line = lines[index];
    const fromIndex = line.lastIndexOf(this._testFolder) + this._testFolder.length;
    const toIndex = line.lastIndexOf(')');
    lines[index] = line.substring(0, fromIndex) + YELLOW_COLOR + line.substring(fromIndex, toIndex) + RESET_COLOR + line.substring(toIndex);
    return lines.join('\n');
  }

  _onTestStarted(test, workerId) {
    this._workersState.set(workerId, {test, isRunning: true});
  }

  _onTestFinished(test, workerId) {
    this._workersState.set(workerId, {test, isRunning: false});
    if (test.result === 'ok')
      process.stdout.write(`${GREEN_COLOR}.${RESET_COLOR}`);
    else if (test.result === 'skipped')
      process.stdout.write(`${YELLOW_COLOR}*${RESET_COLOR}`);
    else if (test.result === 'failed')
      process.stdout.write(`${RED_COLOR}F${RESET_COLOR}`);
    else if (test.result === 'timedout')
      process.stdout.write(`${RED_COLOR}T${RESET_COLOR}`);
  }
}

function formatTestLocation(test) {
  const location = test.location;
  if (!location)
    return '';
  return `${location.fileName}:${location.lineNumber}:${location.columnNumber}`;
}

module.exports = Reporter;
<|endoftext|>


<commit_before>/*jslint node: true */

'use strict';

var provider = require('./provider');
var async = require('async');
var request = require('request');
var fs = require('fs');
var AdmZip = require('adm-zip');
var path = require('path');
var log = require('winston');
var srt2vtt = require('srt2vtt');
var openSRT = require('popcorn-opensubtitles');

exports.getMovieSubs = function (imdb_code, cb) {
    request
        .get({
            url: provider.subtitles().url + '/' + imdb_code,
            json: true
        }, function (err, response, body) {
            if (!err && response.statusCode === 200 && !!body && body.success && body.subtitles > 0) {
                var subtitles = body.subs[imdb_code];
                cb(null, subtitles);
                _download(subtitles, imdb_code);
            }

            request
                .get({
                    url: provider.subtitles().mirrorUrl + '/' + imdb_code,
                    json: true
                }, function (err, response, body) {
                    if (err || response.statusCode >= 400 || !body || !body.success) {
                        return cb(err);
                    }

                    var subtitles = body.subtitles > 0 ? body.subs[imdb_code] : [];
                    cb(null, subtitles);
                    _download(subtitles, imdb_code);
                });
        });
};

/**
 *
 * @param {object} query {
 *  moviehash,
 *  imdbid,
 *  season,
 *  episode,
 *  tag
 * }
 * @param cb
 */
exports.getSerieSubs = function (query, cb) {
    var userAgent = 'MovieShark';
    openSRT.searchEpisode(query, userAgent).then(console.log);
};

var _download = function (subtitles, imdb_code) {
    if (!subtitles)
        return;

    var moviePath = path.resolve(__dirname, '..', 'public/subtitles/' + imdb_code) + '/';
    if (!fs.existsSync(moviePath)) {
        fs.mkdirSync(moviePath);

        var zipPath = moviePath + 'zip/';
        if (!fs.existsSync(zipPath)) {
            fs.mkdirSync(zipPath);
        }

        var srtPath = moviePath + 'srt/';
        if (!fs.existsSync(srtPath)) {
            fs.mkdirSync(srtPath);
        }

        var vttPath = moviePath + 'vtt/';
        if (!fs.existsSync(vttPath)) {
            fs.mkdirSync(vttPath);
        }

        async.each(subtitles, function (language, cb) {
            var subtitle = language.sort(function (a, b) {
                return a.rating < b.rating
            })[0];
            var url = provider.subtitles().prefix + subtitle.url;
            var extension = url.replace(/.*\./, '');

            switch (extension) {
                case 'zip':
                    _downloadZip(zipPath, srtPath, vttPath, url);
                    break;
                case 'srt':
                    _downloadSrt(srtPath, vttPath, url);
                    break;
                case 'vtt':
                    _downloadVtt(vttPath, url);
                    break;
            }

            cb();

        });
    }
};

var _downloadZip = function (zipPath, srtPath, vttPath, url) {
    var filename = zipPath + url.replace(/.*\//, '');
    var out = fs.createWriteStream(filename);
    request(url)
        .on('end', function () {
            out.end(function () {
                try {
                    var zip = new AdmZip(filename);
                    zip.extractAllTo(srtPath, true);
                    var zipEntries = zip.getEntries();
                    async.each(zipEntries, function (entry, cbEntry) {
                        if (entry.entryName.indexOf('.srt') === -1)
                            return cbEntry();

                        var entryPath = srtPath + entry.entryName
                        var newName = path.join(srtPath, filename.replace(/.*\//, '').replace('.zip', '.srt'));
                        fs.renameSync(entryPath, newName);
                        _convertSrtToVtt(vttPath, newName);
                        cbEntry();
                    });
                } catch (err) {
                    log.error('Error unzip subtitle: ', filename);
                }
            });
        })
        .pipe(out);
}

var _downloadSrt = function (srtPath, vttPath, url) {
    var filename = srtPath + url.replace(/.*\//, '');
    var out = fs.createWriteStream(filename);
    request(url)
        .on('end', function () {
            out.end(function () {
                try {
                    _convertSrtToVtt(vttPath, filename);
                } catch (err) {
                    log.error('Error unzip subtitle: ', filename);
                }
            });
        })
        .pipe(out);
};

var _downloadVtt = function (vttPath, url) {
    var filename = vttPath + url.replace(/.*\//, '');
    var out = fs.createWriteStream(filename);
    request(url).pipe(out);
};

var _convertSrtToVtt = function (vttPath, filename) {
    var srtData = fs.readFileSync(filename);
    srt2vtt(srtData, function (err, vttData) {
        if (err)
            return log.error(err);

        var file = filename.replace(/.*\//, '');
        var vttFile = vttPath + file.replace('.srt', '.vtt');
        fs.writeFileSync(vttFile, vttData);
    });
};
<commit_msg>opensubtitles initial implementation<commit_after>/*jslint node: true */

'use strict';

var provider = require('./provider');
var async = require('async');
var request = require('request');
var fs = require('fs');
var AdmZip = require('adm-zip');
var path = require('path');
var log = require('winston');
var srt2vtt = require('srt2vtt');
var openSRT = require('popcorn-opensubtitles');

exports.getMovieSubs = function (imdb_code, cb) {
    request
        .get({
            url: provider.subtitles().url + '/' + imdb_code,
            json: true
        }, function (err, response, body) {
            if (!err && response.statusCode === 200 && !!body && body.success && body.subtitles > 0) {
                var subtitles = body.subs[imdb_code];
                cb(null, subtitles);
                _download(subtitles, imdb_code);
            }

            request
                .get({
                    url: provider.subtitles().mirrorUrl + '/' + imdb_code,
                    json: true
                }, function (err, response, body) {
                    if (err || response.statusCode >= 400 || !body || !body.success) {
                        return cb(err);
                    }

                    var subtitles = body.subtitles > 0 ? body.subs[imdb_code] : [];
                    cb(null, subtitles);
                    _download(subtitles, imdb_code);
                });
        });
};

/**
 *
 * @param {object} query {
 *  moviehash,
 *  imdbid,
 *  season,
 *  episode,
 *  tag
 * }
 * @param cb
 */
exports.getSerieSubs = function (query, cb) {
    var userAgent = 'MovieShark';
    openSRT.searchEpisode(query, userAgent).then(function (subtitles) {
        cb(null, subtitles);
    });
};

var _download = function (subtitles, imdb_code) {
    if (!subtitles)
        return;

    var moviePath = path.resolve(__dirname, '..', 'public/subtitles/' + imdb_code) + '/';
    if (!fs.existsSync(moviePath)) {
        fs.mkdirSync(moviePath);

        var zipPath = moviePath + 'zip/';
        if (!fs.existsSync(zipPath)) {
            fs.mkdirSync(zipPath);
        }

        var srtPath = moviePath + 'srt/';
        if (!fs.existsSync(srtPath)) {
            fs.mkdirSync(srtPath);
        }

        var vttPath = moviePath + 'vtt/';
        if (!fs.existsSync(vttPath)) {
            fs.mkdirSync(vttPath);
        }

        async.each(subtitles, function (language, cb) {
            var subtitle = language.sort(function (a, b) {
                return a.rating < b.rating
            })[0];
            var url = provider.subtitles().prefix + subtitle.url;
            var extension = url.replace(/.*\./, '');

            switch (extension) {
                case 'zip':
                    _downloadZip(zipPath, srtPath, vttPath, url);
                    break;
                case 'srt':
                    _downloadSrt(srtPath, vttPath, url);
                    break;
                case 'vtt':
                    _downloadVtt(vttPath, url);
                    break;
            }

            cb();

        });
    }
};

var _downloadZip = function (zipPath, srtPath, vttPath, url) {
    var filename = zipPath + url.replace(/.*\//, '');
    var out = fs.createWriteStream(filename);
    request(url)
        .on('end', function () {
            out.end(function () {
                try {
                    var zip = new AdmZip(filename);
                    zip.extractAllTo(srtPath, true);
                    var zipEntries = zip.getEntries();
                    async.each(zipEntries, function (entry, cbEntry) {
                        if (entry.entryName.indexOf('.srt') === -1)
                            return cbEntry();

                        var entryPath = srtPath + entry.entryName
                        var newName = path.join(srtPath, filename.replace(/.*\//, '').replace('.zip', '.srt'));
                        fs.renameSync(entryPath, newName);
                        _convertSrtToVtt(vttPath, newName);
                        cbEntry();
                    });
                } catch (err) {
                    log.error('Error unzip subtitle: ', filename);
                }
            });
        })
        .pipe(out);
}

var _downloadSrt = function (srtPath, vttPath, url) {
    var filename = srtPath + url.replace(/.*\//, '');
    var out = fs.createWriteStream(filename);
    request(url)
        .on('end', function () {
            out.end(function () {
                try {
                    _convertSrtToVtt(vttPath, filename);
                } catch (err) {
                    log.error('Error unzip subtitle: ', filename);
                }
            });
        })
        .pipe(out);
};

var _downloadVtt = function (vttPath, url) {
    var filename = vttPath + url.replace(/.*\//, '');
    var out = fs.createWriteStream(filename);
    request(url).pipe(out);
};

var _convertSrtToVtt = function (vttPath, filename) {
    var srtData = fs.readFileSync(filename);
    srt2vtt(srtData, function (err, vttData) {
        if (err)
            return log.error(err);

        var file = filename.replace(/.*\//, '');
        var vttFile = vttPath + file.replace('.srt', '.vtt');
        fs.writeFileSync(vttFile, vttData);
    });
};
<|endoftext|>


<commit_before>feelings = new Mongo.Collection( "feelings" );

addthis_share = {
   url: "http://www.mesinto.net",
   title: "Me Sinto"
}

addthis_config = {
  pubid: "ra-54e10de11e511825"

}

if (Meteor.isClient) {

  var scene;

  var sub = Meteor.subscribe( "feelingsSmallSet", function onReady() {
    var array = feelings.find().fetch();
    Session.set("Tile0", array[0].user.profile_image_url_https );
    Session.set("Tile1", array[1].user.profile_image_url_https );
    Session.set("Tile2", array[2].user.profile_image_url_https );
    Session.set("Tile3", array[3].user.profile_image_url_https );
    sub.stop();
  } );

  Tracker.autorun( function() { document.title = i18n( "appName" ); } );

  configInternationalization();

  maxNumberOfContainers = 6;
  var backgroundPhotos = []
  var backgroundProfile = []

  function now() { return +(new Date()); }
  function rand() { return Math.round( Math.random() * 1000000 ); }

  Session.set( "Counter 0", 0 );
  Session.set( "Counter 1", 0 );
  Session.set( "Counter 2", 0 );
  Session.set( "Counter 3", 0 );
  Session.set( "Counter 4", 0 );
  Session.set( "Counter 5", 0 );
  Session.set( "Images", [] );
  Session.setDefault( "WordList", [] );
  Session.setDefault( "WordCounter", [] );

  function buildPlot() {

    d3.select("#demo").selectAll("#vs").remove();
    d3.select("#demo").append("div").attr("id", "vs");

    var modelArray = [];
    var strataArray = [];
    var list = [];

    for(var i = 0; i < maxNumberOfContainers; ++i) {
      list.push( { label : "" } );
    }

    _.each( list, function( word ) {
      strataArray.push( [ { initValue : 10 } ] );
    } );

    var divWidth = parseInt( d3.select("#plotDiv").style('width') ) - 30;
    var viewportWidth = divWidth;
    var chartX = 10;
    var chartY = 50;
    var chartWidth = viewportWidth - 2 * chartX;
    var settings = {
      width  : viewportWidth,
      height : 300,
      data:{
            model: list,
            strata: strataArray,
            stream:{
              provider:'none'
            },
          },
      sedimentation:{
        token:{
          size:{original:20,minimum:3}
        },
        aggregation:{height:180},
        suspension:{
          decay: { power : 1.005 }
        }
      },
      options:{
        layout:false
      },
      chart:{
        x: chartX,
        y: chartY,
        height : 280,
        width : chartWidth,
        type : "StackedAreaChart",
        wallColor : "rgba(230,230,230,0.5)",
        label : true,
        spacer : 1,
      }
    };

    scene = $("#vs").vs(settings).data('visualSedimentation');

  }

  Template.BodyT.rendered = function() {
    $LAB.script( "https://s7.addthis.com/js/250/addthis_widget.js" ).wait();
  }

  Template.VisualSedimentationT.rendered = function() {
    buildPlot();
    Tracker.autorun( updateLegend );
  };
  Tracker.autorun( observeData );

  var backgroundHandler;
  function restartBackgroundLoop() {

    if( _.isUndefined( backgroundHandler ) == false ) {
      clearInterval( backgroundHandler );
    }

    backgroundHandler = setInterval( function() {

      if( _.isEmpty( backgroundPhotos ) ) {
        if( _.isEmpty( backgroundProfile ) ) {
          return
        }
        backgroundProfile = _.shuffle( backgroundProfile );
        Session.set( "Image", backgroundProfile.pop() );
      } else {
        backgroundPhotos = _.shuffle( backgroundPhotos );
        Session.set( "Image", backgroundPhotos.pop() );
      }

    }, 20000 );
  }
  restartBackgroundLoop();

  setInterval( function() {

    if( _.isUndefined( scene ) ) {
      return;
    }

    var array = myPop();
    _.each(array, function( p ) {
      setTimeout( function() {
        var counterId = "Counter " + p.category;
        Session.set( counterId, Session.get( counterId ) + 1 );
        scene.addToken( p );
      }, rand() % 5000 );
    } );

  }, 5000 );

  function observeData() {
    var wordList = Session.get( "WordList" );

    Session.set( "DataIsReady", false );
    Meteor.subscribe( "feelings", wordList, function() {
      Session.set( "DataIsReady", true );
      feelings.find({}).observeChanges( {
        added : function( id, tweet ) {

          if( _.size( tweet ) == 1 ) {
            return;
          }

          //
          // Twitter API appends RT @screen_name to retweets.
          // We want to ignore those as they are repeated over
          // and over as background
          //
          if( _.isUndefined( tweet.retweeted_status ) == false ) {
            return;
          }

          obj = buildBackgroundObject( tweet );

          if( _.isEqual( obj.type, "photo" ) == false &&
            backgroundProfile.length < 1000 ) {
            backgroundProfile.push( obj );
          }

          if( _.isEqual( obj.type, "photo" ) == true &&
              backgroundPhotos.length < 1000 ) {
              backgroundPhotos.push( obj )  ;
          }

          allowChangesToBackground = true;
          var wordList = Session.get( "WordList" )
          var text = tweet.text.toLowerCase();
          _.each( wordList, function( word, idx ) {
            if( text.indexOf( word ) != -1 ) {
              myEnqueue( {
                tweet : tweet,
                size : 60 / maxNumberOfContainers,
                category : idx,
                callback : {
                  onclick : function( token ) {
                    var obj = buildBackgroundObject( token.myobj.m_userData.tweet );
                    Session.set( "Image", obj );
                    restartBackgroundLoop();
                    allowChangesToBackground = false;
                    setTimeout( function() {
                      allowChangesToBackground = true;
                    }, 3000 )
                  },
                  mouseover : function( token ) {
                    if( allowChangesToBackground == false ) {
                      return;
                    }
                    var obj = buildBackgroundObject( token.myobj.m_userData.tweet );
                    Session.set( "Image", obj );
                    restartBackgroundLoop();
                  }
                }
              } );
            }
          } );
        }
      } ) ;
    } );
  }

  function updateLegend() {

    d3.select("svg").select("#legend").remove();

    var wordList = Session.get( "WordList" );
    var textNode = d3.select("svg").append("g").attr("id", "legend");
    var textXDelta = settings.chart.width / maxNumberOfContainers;
    var textX = settings.chart.x + textXDelta * 0.5;
    var textYA = settings.chart.y - 30;
    var textYB = settings.chart.y - 10;

    _.each( wordList, function( word, idx ) {
      textNode
        .append("g")
        .append("text")
        .attr( "font-size", 20)
        .attr( "font-family", "HelveticaNeue-Light")
        .attr( "font-weight", 300)
        .attr( "fill", "white")
        .attr( "text-anchor", "middle")
        .attr( "pointer-events", "all")
        .attr( "cursor", "pointer")
        .text( word )
        .on("click", function( d ) {
          var w = d3.select(this).text().toLowerCase();
          var wordList = Session.get( "WordList" );
          wordList = _.filter( wordList, function( word ) {
            return _.isEqual( word, w ) == false;
          } );
          Session.set( "WordList", wordList );
        } )
        .attr("transform", function() {
          if( idx % 2 == 0 ) {
            return "translate(" + textX + "," + textYA + ")"
          }
          return "translate(" + textX + "," + textYB + ")"
        });
      textX += textXDelta;
    } );
  }

}

if (Meteor.isServer) {
  Meteor.startup(function () {
    var termsCollection = new Mongo.Collection( "commonTerms" );

    Meteor.publish( "feelingsSmallSet", function( ) {
      var options = {
        fields : { "user.profile_image_url_https" : 1 },
        limit : 4
      };
      return feelings.find( { }, options );
    } );

    Meteor.publish( "feelings", function( words, lang ) {

      var list = "";
      _.each( words, function( word ) {
        var query = {};
        var modfiers = {};
        var increment = {};
        query[ word ] = { $exists : true } ;

        var cursor = termsCollection.find( query );
        if( cursor.count() == 0 ) {
          var term = {};
          term[ word ] = 1;
          termsCollection.insert( term );
        } else {
          var array = cursor.fetch();
          increment[ word ] = +1;
          modfiers[ "$inc" ] = increment;
          termsCollection.update( { _id : array[ 0 ]._id }, modfiers );
        }

        list += word + " ";
      } );

      var query = {
        $text : {
          $search : list,
          $language : "en"
        }
      };
      var options = {
        fields : {
          id_str : 1,
          text : 1,
          created_at : 1,
          "entities.media" : 1,
          "user.screen_name" : 1,
          "user.profile_image_url_https" : 1,
          "retweeted_status.id_str" : 1
        }
      };
      return feelings.find( query, options );
    } );
  });
}
<commit_msg>Temporarily switched to _.isEmpty<commit_after>feelings = new Mongo.Collection( "feelings" );

addthis_share = {
   url: "http://www.mesinto.net",
   title: "Me Sinto"
}

addthis_config = {
  pubid: "ra-54e10de11e511825"

}

if (Meteor.isClient) {

  var scene;

  var sub = Meteor.subscribe( "feelingsSmallSet", function onReady() {
    var array = feelings.find().fetch();
    Session.set("Tile0", array[0].user.profile_image_url_https );
    Session.set("Tile1", array[1].user.profile_image_url_https );
    Session.set("Tile2", array[2].user.profile_image_url_https );
    Session.set("Tile3", array[3].user.profile_image_url_https );
    sub.stop();
  } );

  Tracker.autorun( function() { document.title = i18n( "appName" ); } );

  configInternationalization();

  maxNumberOfContainers = 6;
  var backgroundPhotos = []
  var backgroundProfile = []

  function now() { return +(new Date()); }
  function rand() { return Math.round( Math.random() * 1000000 ); }

  Session.set( "Counter 0", 0 );
  Session.set( "Counter 1", 0 );
  Session.set( "Counter 2", 0 );
  Session.set( "Counter 3", 0 );
  Session.set( "Counter 4", 0 );
  Session.set( "Counter 5", 0 );
  Session.set( "Images", [] );
  Session.setDefault( "WordList", [] );
  Session.setDefault( "WordCounter", [] );

  function buildPlot() {

    d3.select("#demo").selectAll("#vs").remove();
    d3.select("#demo").append("div").attr("id", "vs");

    var modelArray = [];
    var strataArray = [];
    var list = [];

    for(var i = 0; i < maxNumberOfContainers; ++i) {
      list.push( { label : "" } );
    }

    _.each( list, function( word ) {
      strataArray.push( [ { initValue : 10 } ] );
    } );

    var divWidth = parseInt( d3.select("#plotDiv").style('width') ) - 30;
    var viewportWidth = divWidth;
    var chartX = 10;
    var chartY = 50;
    var chartWidth = viewportWidth - 2 * chartX;
    var settings = {
      width  : viewportWidth,
      height : 300,
      data:{
            model: list,
            strata: strataArray,
            stream:{
              provider:'none'
            },
          },
      sedimentation:{
        token:{
          size:{original:20,minimum:3}
        },
        aggregation:{height:180},
        suspension:{
          decay: { power : 1.005 }
        }
      },
      options:{
        layout:false
      },
      chart:{
        x: chartX,
        y: chartY,
        height : 280,
        width : chartWidth,
        type : "StackedAreaChart",
        wallColor : "rgba(230,230,230,0.5)",
        label : true,
        spacer : 1,
      }
    };

    scene = $("#vs").vs(settings).data('visualSedimentation');

  }

  Template.BodyT.rendered = function() {
    $LAB.script( "https://s7.addthis.com/js/250/addthis_widget.js" ).wait();
  }

  Template.VisualSedimentationT.rendered = function() {
    buildPlot();
    Tracker.autorun( updateLegend );
  };
  Tracker.autorun( observeData );

  var backgroundHandler;
  function restartBackgroundLoop() {

    if( _.isUndefined( backgroundHandler ) == false ) {
      clearInterval( backgroundHandler );
    }

    backgroundHandler = setInterval( function() {

      if( _.isEmpty( backgroundPhotos ) ) {
        if( _.isEmpty( backgroundProfile ) ) {
          return
        }
        backgroundProfile = _.shuffle( backgroundProfile );
        Session.set( "Image", backgroundProfile.pop() );
      } else {
        backgroundPhotos = _.shuffle( backgroundPhotos );
        Session.set( "Image", backgroundPhotos.pop() );
      }

    }, 20000 );
  }
  restartBackgroundLoop();

  setInterval( function() {

    if( _.isUndefined( scene ) ) {
      return;
    }

    var array = myPop();
    _.each(array, function( p ) {
      setTimeout( function() {
        var counterId = "Counter " + p.category;
        Session.set( counterId, Session.get( counterId ) + 1 );
        scene.addToken( p );
      }, rand() % 5000 );
    } );

  }, 5000 );

  function observeData() {
    var wordList = Session.get( "WordList" );

    Session.set( "DataIsReady", false );
    Meteor.subscribe( "feelings", wordList, function() {
      Session.set( "DataIsReady", true );
      feelings.find({}).observeChanges( {
        added : function( id, tweet ) {

          if( _.size( tweet ) == 1 ) {
            return;
          }

          //
          // Twitter API appends RT @screen_name to retweets.
          // We want to ignore those as they are repeated over
          // and over as background
          //
          if( _.isEmpty( tweet.retweeted_status ) == true ) {
            return;
          }

          obj = buildBackgroundObject( tweet );

          if( _.isEqual( obj.type, "photo" ) == false &&
            backgroundProfile.length < 1000 ) {
            backgroundProfile.push( obj );
          }

          if( _.isEqual( obj.type, "photo" ) == true &&
              backgroundPhotos.length < 1000 ) {
              backgroundPhotos.push( obj )  ;
          }

          allowChangesToBackground = true;
          var wordList = Session.get( "WordList" )
          var text = tweet.text.toLowerCase();
          _.each( wordList, function( word, idx ) {
            if( text.indexOf( word ) != -1 ) {
              myEnqueue( {
                tweet : tweet,
                size : 60 / maxNumberOfContainers,
                category : idx,
                callback : {
                  onclick : function( token ) {
                    var obj = buildBackgroundObject( token.myobj.m_userData.tweet );
                    Session.set( "Image", obj );
                    restartBackgroundLoop();
                    allowChangesToBackground = false;
                    setTimeout( function() {
                      allowChangesToBackground = true;
                    }, 3000 )
                  },
                  mouseover : function( token ) {
                    if( allowChangesToBackground == false ) {
                      return;
                    }
                    var obj = buildBackgroundObject( token.myobj.m_userData.tweet );
                    Session.set( "Image", obj );
                    restartBackgroundLoop();
                  }
                }
              } );
            }
          } );
        }
      } ) ;
    } );
  }

  function updateLegend() {

    d3.select("svg").select("#legend").remove();

    var wordList = Session.get( "WordList" );
    var textNode = d3.select("svg").append("g").attr("id", "legend");
    var textXDelta = settings.chart.width / maxNumberOfContainers;
    var textX = settings.chart.x + textXDelta * 0.5;
    var textYA = settings.chart.y - 30;
    var textYB = settings.chart.y - 10;

    _.each( wordList, function( word, idx ) {
      textNode
        .append("g")
        .append("text")
        .attr( "font-size", 20)
        .attr( "font-family", "HelveticaNeue-Light")
        .attr( "font-weight", 300)
        .attr( "fill", "white")
        .attr( "text-anchor", "middle")
        .attr( "pointer-events", "all")
        .attr( "cursor", "pointer")
        .text( word )
        .on("click", function( d ) {
          var w = d3.select(this).text().toLowerCase();
          var wordList = Session.get( "WordList" );
          wordList = _.filter( wordList, function( word ) {
            return _.isEqual( word, w ) == false;
          } );
          Session.set( "WordList", wordList );
        } )
        .attr("transform", function() {
          if( idx % 2 == 0 ) {
            return "translate(" + textX + "," + textYA + ")"
          }
          return "translate(" + textX + "," + textYB + ")"
        });
      textX += textXDelta;
    } );
  }

}

if (Meteor.isServer) {
  Meteor.startup(function () {
    var termsCollection = new Mongo.Collection( "commonTerms" );

    Meteor.publish( "feelingsSmallSet", function( ) {
      var options = {
        fields : { "user.profile_image_url_https" : 1 },
        limit : 4
      };
      return feelings.find( { }, options );
    } );

    Meteor.publish( "feelings", function( words, lang ) {

      var list = "";
      _.each( words, function( word ) {
        var query = {};
        var modfiers = {};
        var increment = {};
        query[ word ] = { $exists : true } ;

        var cursor = termsCollection.find( query );
        if( cursor.count() == 0 ) {
          var term = {};
          term[ word ] = 1;
          termsCollection.insert( term );
        } else {
          var array = cursor.fetch();
          increment[ word ] = +1;
          modfiers[ "$inc" ] = increment;
          termsCollection.update( { _id : array[ 0 ]._id }, modfiers );
        }

        list += word + " ";
      } );

      var query = {
        $text : {
          $search : list,
          $language : "en"
        }
      };
      var options = {
        fields : {
          id_str : 1,
          text : 1,
          created_at : 1,
          "entities.media" : 1,
          "user.screen_name" : 1,
          "user.profile_image_url_https" : 1,
          "retweeted_status.id_str" : 1
        }
      };
      return feelings.find( query, options );
    } );
  });
}
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.rando<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var args = ['commit', outFile, '-m', 'Update character']
    for (var counter = 0; counter < length; counter++)
    {
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 <commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]<|endoftext|>


<commit_before>export default {
  'vt-source': 'http://da-tiles.osm-analytics.org', // source of current vector tiles
  'vt-hist-source': 'http://da-tiles.osm-analytics.org', // source of historic vector tiles for compare feature
}
<commit_msg>point to Vizzuality.com tile endpoint<commit_after>export default {
  'vt-source': 'http://osm-analytics.vizzuality.com', // source of current vector tiles
  'vt-hist-source': 'http://osm-analytics.vizzuality.com', // source of historic vector tiles for compare feature
}
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600<commit_msg>Fixed memory parsing error #1337<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var commit_time_hour = Math.floor(commit_time / 3600)
    var commit_time_rem = commit_time - (commit_<|endoftext|>