<commit_before>
var NEUTRAL_DIE =  ['B', 'd', 'd', 's', 's', 'N'];
var OFFENSE_DIE =  ['B', '',  '',  '4', '4', 'S'];
var DEFENSE_DIE =  ['B', '',  '',  '4', '4', 'D'];
var WOUND_DIE =    ['B', '-', '',  '',  '',  ''];
var FATIGUE_DIE =  ['-', '-', '',  '',  '',  ''];
var dieSize = NEUTRAL_DIE.length;

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function htmlForDie(name, die, id) {
  var html = '';
  html += '' + name + '';
  html += '
';
  html += '<input type="number" min="0" class="form-control" id="p' + id + name + '" value="0">';
  html += '
';
  html += '
';
  for (var i in die) {
    html += '
' + die[i] + '
';
  }
  html += '
';
  return html;
}

var players = new Array(
  {
    disabledCrits: 0,
    crits: 0,
    botches: 0,
    drops: 0,
    disabled: 0,
    rolls: [],
    dice: 0
  }
);

function createDieRoll(die, type, roll) {
  return {
    'type': type,
    'roll': roll,
    'result': die[roll-1],
    'isCrit': die[roll-1] == 'N' || die[roll-1] == 'S' || die[roll-1] == 'D',
    'isBotch': die[roll-1] == 'B',
    'enabled': true,
    'isDrop': die[roll-1] == '-'
  };
}

function plural(number, single, multiple) {
  return (number == 1) ? single : multiple;
}

function rollStatus(player) {
  var totalDisabled = player.disabledCrits + player.disabled;
  var totalValid = player.dice + player.crits;
  var activeDrops = player.drops > 0 ? player.drops - player.disabled - player.disabledCrits: 0;
  var activeCrits = player.crits - player.disabledCrits;
  var activeDice = player.dice - player.disabled;
  var remaining = activeDice + activeCrits;

  if (activeDrops > 0) {
    if (totalValid <= totalDisabled)
      return "";
    else if (activeDrops > 1)
      return activeDrops + ' dice need to be dropped';
    else if (activeDrops == 1)
      return activeDrops + ' die needs to be dropped';
  }

  var netBotches = player.botches > 0 ? player.botches - (player.disabled + player.disabledCrits - player.drops) : 0;
  if (netBotches < 0)
    netBotches = 0;
  if (netBotches > remaining)
    netBotches = remaining;

  var status = '';
  if (netBotches > 0) {
    if (activeCrits > 0) {
      if (netBotches > activeCrits)
        status = activeCrits + ' ' + plural(activeCrits, 'crit needs', 'crits need') + ' to be dropped';
      else
        status = netBotches + ' ' + plural(netBotches, 'crit needs', 'crits need') + ' to be dropped';
    } else {
      if (activeDice > 0) {
        status = netBotches +  ' ' + plural(netBotches, 'die needs', 'dice needs') + ' to be dropped';
      }
    }
  } else {
    if (player.disabledCrits < player.botches && activeCrits > 0) {
      netBotches = activeCrits > player.botches ? player.botches : activeCrits;
      status = netBotches + ' ' + plural(netBotches, 'crit needs', 'crits need') + ' to be dropped';
    }
  }

  return status;
 }

function netResultMarkup(player) {
  var html = '';
  var botchesToDisplay = player.botches - (player.disabled + player.disabledCrits - player.drops);
  if (botchesToDisplay > 0)
    for (var i in player.rolls)
      if (player.rolls[i].isBotch && botchesToDisplay > 0) {
        botchesToDisplay--;
        html += dieHTML(player.rolls[i], '', i)
      }
  for (var i in player.rolls)
    if (rollCanBeDisplayed(player.rolls[i]))
      html += dieHTML(player.rolls[i], '', i);
  return html;
}

function rollCanBeDisplayed(roll) {
  if (!roll.enabled)
    return false;
  else if (roll.result == '•')
    return false;
  else if (roll.result == '')
    return false;
  else if (roll.result == ' ')
    return false;
  else if (roll.isBotch)
    return false;
  else if (roll.isDrop)
    return false;
  return true;
}

function dieHTML(die, id, i) {
  var html = '
' + die.result + '
';
  return html;
}

function botchesOk(player) {
  if (!dropsOk(player))
    return false;

  var totalDisabled = player.disabled + player.disabledCrits;
  var totalDice = player.dice + player.crits;
  var needToBeDisabled = player.drops + player.botches;

  if (player.botches == 0)
    return true;
  else if (player.disabledCrits < player.botches && player.crits > player.disabledCrits)
    return false;
  else if (player.disabledCrits >= player.crits && player.disabled >= player.dice)
    return true;
  else if (totalDisabled < totalDice && needToBeDisabled > totalDisabled)
    return false;
  else if (player.crits > player.disabledCrits && player.botches > player.disabledCrits)
    return false;
  else if (player.disabledCrits + player.disabled >= player.botches)
    return true;
  else
    return false;
}

function dropsOk(player) {
  if (player.drops == 0)
    return true;
  if (player.drops <= player.disabled)
    return true;
  if (player.dice > player.disabled)
    return false;
  return true;
}

function isDie(face) {
  if (face == '')
    return 0;
  else if (face == 4)
    return 1;
  else if (face == face.toUpperCase())
    return 0;
  else if (face == '-')
    return 0;
  else if (face == ' ')
    return 0;
  else
    return 1;
}
<commit_msg>code clean up<commit_after>
var NEUTRAL_DIE =  ['B', 'd', 'd', 's', 's', 'N'];
var OFFENSE_DIE =  ['B', '',  '',  '4', '4', 'S'];
var DEFENSE_DIE =  ['B', '',  '',  '4', '4', 'D'];
var WOUND_DIE =    ['B', '-', '',  '',  '',  ''];
var FATIGUE_DIE =  ['-', '-', '',  '',  '',  ''];
var dieSize = NEUTRAL_DIE.length;

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function htmlForDie(name, die, id) {
  var html = '';
  html += '' + name + '';
  html += '
';
  html += '<input type="number" min="0" class="form-control" id="p' + id + name + '" value="0">';
  html += '
';
  html += '
';
  for (var i in die) {
    html += '
' + die[i] + '
';
  }
  html += '
';
  return html;
}

var players = new Array(
  {
    disabledCrits: 0,
    crits: 0,
    botches: 0,
    drops: 0,
    disabled: 0,
    rolls: [],
    dice: 0
  }
);

function createDieRoll(die, type, roll) {
  return {
    'type': type,
    'roll': roll,
    'result': die[roll-1],
    'isCrit': die[roll-1] == 'N' || die[roll-1] == 'S' || die[roll-1] == 'D',
    'isBotch': die[roll-1] == 'B',
    'enabled': true,
    'isDrop': die[roll-1] == '-'
  };
}

function plural(number, single, multiple) {
  return (number == 1) ? single : multiple;
}

function rollStatus(player) {
  var totalDisabled = player.disabledCrits + player.disabled;
  var totalValid = player.dice + player.crits;
  var activeDrops = player.drops > 0 ? player.drops - player.disabled - player.disabledCrits: 0;
  var activeCrits = player.crits - player.disabledCrits;
  var activeDice = player.dice - player.disabled;
  var remaining = activeDice + activeCrits;

  if (activeDrops > 0) {
    if (totalValid <= totalDisabled)
      return "";
    else if (activeDrops > 1)
      return activeDrops + ' dice need to be dropped';
    else if (activeDrops == 1)
      return activeDrops + ' die needs to be dropped';
  }

  var netBotches = player.botches > 0 ? player.botches - (player.disabled + player.disabledCrits - player.drops) : 0;
  if (netBotches < 0)
    netBotches = 0;
  if (netBotches > remaining)
    netBotches = remaining;

  var status = '';
  if (netBotches > 0) {
    if (activeCrits > 0) {
      if (netBotches > activeCrits)
        status = activeCrits + ' ' + plural(activeCrits, 'crit needs', 'crits need') + ' to be dropped';
      else
        status = netBotches + ' ' + plural(netBotches, 'crit needs', 'crits need') + ' to be dropped';
    } else {
      if (activeDice > 0) {
        status = netBotches +  ' ' + plural(netBotches, 'die needs', 'dice needs') + ' to be dropped';
      }
    }
  } else {
    if (player.disabledCrits < player.botches && activeCrits > 0) {
      netBotches = activeCrits > player.botches ? player.botches : activeCrits;
      status = netBotches + ' ' + plural(netBotches, 'crit needs', 'crits need') + ' to be dropped';
    }
  }

  return status;
 }

function netResultMarkup(player) {
  var html = '';
  var botchesToDisplay = player.botches - (player.disabled + player.disabledCrits - player.drops);
  if (botchesToDisplay > 0)
    for (var i in player.rolls)
      if (player.rolls[i].isBotch && botchesToDisplay > 0) {
        botchesToDisplay--;
        html += dieHTML(player.rolls[i], '', i)
      }
  for (i in player.rolls)
    if (rollCanBeDisplayed(player.rolls[i]))
      html += dieHTML(player.rolls[i], '', i);
  return html;
}

function rollCanBeDisplayed(roll) {
  if (!roll.enabled)
    return false;
  else if (roll.result == '•')
    return false;
  else if (roll.result == '')
    return false;
  else if (roll.result == ' ')
    return false;
  else if (roll.isBotch)
    return false;
  else if (roll.isDrop)
    return false;
  return true;
}

function dieHTML(die, id, i) {
  var html = '
' + die.result + '
';
  return html;
}

function botchesOk(player) {
  if (!dropsOk(player))
    return false;

  var totalDisabled = player.disabled + player.disabledCrits;
  var totalDice = player.dice + player.crits;
  var needToBeDisabled = player.drops + player.botches;

  if (player.botches == 0)
    return true;
  else if (player.disabledCrits < player.botches && player.crits > player.disabledCrits)
    return false;
  else if (player.disabledCrits >= player.crits && player.disabled >= player.dice)
    return true;
  else if (totalDisabled < totalDice && needToBeDisabled > totalDisabled)
    return false;
  else if (player.crits > player.disabledCrits && player.botches > player.disabledCrits)
    return false;
  else
    return player.disabledCrits + player.disabled >= player.botches;
}

function dropsOk(player) {
  if (player.drops == 0)
    return true;
  if (player.drops <= player.disabled)
    return true;
  return !(player.dice > player.disabled);
}

function isDie(face) {
  if (face == '')
    return 0;
  if (face == 4)
    return 1;
  if (face == face.toUpperCase())
    return 0;
  if (face == '-')
    return 0;
  if (face == ' ')
    return 0;
  else
    return 1;
}
<|endoftext|>


<commit_before>/** @babel */

import _ from 'underscore-plus'
import ChildProcess from 'child_process'
import {Emitter} from 'event-kit'
import path from 'path'

// Extended: A wrapper which provides standard error/output line buffering for
// Node's ChildProcess.
//
// ## Examples
//
// ```js
// {BufferedProcess} = require('atom')
//
// const command = 'ps'
// const args = ['-ef']
// const stdout = (output) => console.log(output)
// const exit = (code) => console.log("ps -ef exited with #{code}")
// const process = new BufferedProcess({command, args, stdout, exit})
// ```
export default class BufferedProcess {
  /*
  Section: Construction
  */

  // Public: Runs the given command by spawning a new child process.
  //
  // * `options` An {Object} with the following keys:
  //   * `command` The {String} command to execute.
  //   * `args` The {Array} of arguments to pass to the command (optional).
  //   * `options` {Object} (optional) The options {Object} to pass to Node's
  //     `ChildProcess.spawn` method.
  //   * `stdout` {Function} (optional) The callback that receives a single
  //     argument which contains the standard output from the command. The
  //     callback is called as data is received but it's buffered to ensure only
  //     complete lines are passed until the source stream closes. After the
  //     source stream has closed all remaining data is sent in a final call.
  //     * `data` {String}
  //   * `stderr` {Function} (optional) The callback that receives a single
  //     argument which contains the standard error output from the command. The
  //     callback is called as data is received but it's buffered to ensure only
  //     complete lines are passed until the source stream closes. After the
  //     source stream has closed all remaining data is sent in a final call.
  //     * `data` {String}
  //   * `exit` {Function} (optional) The callback which receives a single
  //     argument containing the exit status.
  //     * `code` {Number}
  constructor ({command, args, options = {}, stdout, stderr, exit} = {}) {
    this.emitter = new Emitter()
    this.command = command
    // Related to joyent/node#2318
    if (process.platform === 'win32' && options.shell === undefined) {
      this.spawnWithEscapedWindowsArgs(command, args, options)
    } else {
      this.spawn(command, args, options)
    }

    this.killed = false
    this.handleEvents(stdout, stderr, exit)
  }

  // Windows has a bunch of special rules that node still doesn't take care of for you
  spawnWithEscapedWindowsArgs (command, args, options) {
    let cmdArgs = []
    // Quote all arguments and escapes inner quotes
    if (args) {
      cmdArgs = args.filter((arg) => arg != null)
        .map((arg) => {
          if (this.isExplorerCommand(command) && /^\/[a-zA-Z]+,.*$/.test(arg)) {
            // Don't wrap /root,C:\folder style arguments to explorer calls in
            // quotes since they will not be interpreted correctly if they are
            return arg
          } else {
            // Escape double quotes by putting a backslash in front of them
            return `\"${arg.toString().replace(/"/g, '\\"')}\"`
          }
        })
    }

    // The command itself is quoted if it contains spaces, &, ^ or | chars
    cmdArgs.unshift(/\s|&|\^|\|/.test(command) ? `\"${command}\"` : command)

    const cmdOptions = _.clone(options)
    cmdOptions.windowsVerbatimArguments = true

    this.spawn(this.getCmdPath(), ['/s', '/d', '/c', `\"${cmdArgs.join(' ')}\"`], cmdOptions)
  }

  /*
  Section: Event Subscription
  */

  // Public: Will call your callback when an error will be raised by the process.
  // Usually this is due to the command not being available or not on the PATH.
  // You can call `handle()` on the object passed to your callback to indicate
  // that you have handled this error.
  //
  // * `callback` {Function} callback
  //   * `errorObject` {Object}
  //     * `error` {Object} the error object
  //     * `handle` {Function} call this to indicate you have handled the error.
  //       The error will not be thrown if this function is called.
  //
  // Returns a {Disposable}
  onWillThrowError (callback) {
    return this.emitter.on('will-throw-error', callback)
  }

  /*
  Section: Helper Methods
  */

  // Helper method to pass data line by line.
  //
  // * `stream` The Stream to read from.
  // * `onLines` The callback to call with each line of data.
  // * `onDone` The callback to call when the stream has closed.
  bufferStream (stream, onLines, onDone) {
    stream.setEncoding('utf8')
    let buffered = ''

    stream.on('data', (data) => {
      if (this.killed) return

      let bufferedLength = buffered.length
      buffered += data
      let lastNewlineIndex = data.lastIndexOf('\n')

      if (lastNewlineIndex !== -1) {
        let lineLength = lastNewlineIndex + bufferedLength + 1
        onLines(buffered.substring(0, lineLength))
        buffered = buffered.substring(lineLength)
      }
    })

    stream.on('close', () => {
      if (this.killed) return
      if (buffered.length > 0) onLines(buffered)
      onDone()
    })
  }

  // Kill all child processes of the spawned cmd.exe process on Windows.
  //
  // This is required since killing the cmd.exe does not terminate child
  // processes.
  killOnWindows () {
    if (!this.process) return

    const parentPid = this.process.pid
    const cmd = 'wmic'
    const args = [
      'process',
      'where',
      `(ParentProcessId=${parentPid})`,
      'get',
      'processid'
    ]

    let wmicProcess

    try {
      wmicProcess = ChildProcess.spawn(cmd, args)
    } catch (spawnError) {
      this.killProcess()
      return
    }

    wmicProcess.on('error', () => {}) // ignore errors

    let output = ''
    wmicProcess.stdout.on('data', (data) => {
      output += data
    })
    wmicProcess.stdout.on('close', () => {
      const pidsToKill = output.split(/\s+/)
        .filter((pid) => /^\d+$/.test(pid))
        .map((pid) => parseInt(pid))
        .filter((pid) => pid !== parentPid && pid > 0 && pid < Infinity)

      for (let pid of pidsToKill) {
        try {
          process.kill(pid)
        } catch (error) {}
      }

      this.killProcess()
    })
  }

  killProcess () {
    if (this.process) this.process.kill()
    this.process = null
  }

  isExplorerCommand (command) {
    if (command === 'explorer.exe' || command === 'explorer') {
      return true
    } else if (process.env.SystemRoot) {
      return command === path.join(process.env.SystemRoot, 'explorer.exe') || command === path.join(process.env.SystemRoot, 'explorer')
    } else {
      return false
    }
  }

  getCmdPath () {
    if (process.env.comspec) {
      return process.env.comspec
    } else if (process.env.SystemRoot) {
      return path.join(process.env.SystemRoot, 'System32', 'cmd.exe')
    } else {
      return 'cmd.exe'
    }
  }

  // Public: Terminate the process.
  kill () {
    if (this.killed) return

    this.killed = true
    if (process.platform === 'win32') {
      this.killOnWindows()
    } else {
      this.killProcess()
    }
  }

  spawn (command, args, options) {
    try {
      this.process = ChildProcess.spawn(command, args, options)
    } catch (spawnError) {
      process.nextTick(() => this.handleError(spawnError))
    }
  }

  handleEvents (stdout, stderr, exit) {
    if (!this.process) return

    const triggerExitCallback = () => {
      if (this.killed) return
      if (stdoutClosed && stderrClosed && processExited && typeof exit === 'function') {
        exit(exitCode)
      }
    }

    let stdoutClosed = true
    let stderrClosed = true
    let processExited = true
    let exitCode = 0

    if (stdout) {
      stdoutClosed = false
      this.bufferStream(this.process.stdout, stdout, () => {
        stdoutClosed = true
        triggerExitCallback()
      })
    }

    if (stderr) {
      stderrClosed = false
      this.bufferStream(this.process.stderr, stderr, () => {
        stderrClosed = true
        triggerExitCallback()
      })
    }

    if (exit) {
      processExited = false
      this.process.on('exit', (code) => {
        exitCode = code
        processExited = true
        triggerExitCallback()
      })
    }

    this.process.on('error', (error) => {
      this.handleError(error)
    })
  }

  handleError (error) {
    let handled = false

    const handle = () => {
      handled = true
    }

    this.emitter.emit('will-throw-error', {error, handle})

    if (error.code === 'ENOENT' && error.syscall.indexOf('spawn') === 0) {
      error = new Error(`Failed to spawn command \`${this.command}\`. Make sure \`${this.command}\` is installed and on your PATH`, error.path)
      error.name = 'BufferedProcessError'
    }

    if (!handled) throw error
  }
}
<commit_msg>Brackets inexplicably need to be quoted in the command bit (but not in args). Fixes #13346<commit_after>/** @babel */

import _ from 'underscore-plus'
import ChildProcess from 'child_process'
import {Emitter} from 'event-kit'
import path from 'path'

// Extended: A wrapper which provides standard error/output line buffering for
// Node's ChildProcess.
//
// ## Examples
//
// ```js
// {BufferedProcess} = require('atom')
//
// const command = 'ps'
// const args = ['-ef']
// const stdout = (output) => console.log(output)
// const exit = (code) => console.log("ps -ef exited with #{code}")
// const process = new BufferedProcess({command, args, stdout, exit})
// ```
export default class BufferedProcess {
  /*
  Section: Construction
  */

  // Public: Runs the given command by spawning a new child process.
  //
  // * `options` An {Object} with the following keys:
  //   * `command` The {String} command to execute.
  //   * `args` The {Array} of arguments to pass to the command (optional).
  //   * `options` {Object} (optional) The options {Object} to pass to Node's
  //     `ChildProcess.spawn` method.
  //   * `stdout` {Function} (optional) The callback that receives a single
  //     argument which contains the standard output from the command. The
  //     callback is called as data is received but it's buffered to ensure only
  //     complete lines are passed until the source stream closes. After the
  //     source stream has closed all remaining data is sent in a final call.
  //     * `data` {String}
  //   * `stderr` {Function} (optional) The callback that receives a single
  //     argument which contains the standard error output from the command. The
  //     callback is called as data is received but it's buffered to ensure only
  //     complete lines are passed until the source stream closes. After the
  //     source stream has closed all remaining data is sent in a final call.
  //     * `data` {String}
  //   * `exit` {Function} (optional) The callback which receives a single
  //     argument containing the exit status.
  //     * `code` {Number}
  constructor ({command, args, options = {}, stdout, stderr, exit} = {}) {
    this.emitter = new Emitter()
    this.command = command
    // Related to joyent/node#2318
    if (process.platform === 'win32' && options.shell === undefined) {
      this.spawnWithEscapedWindowsArgs(command, args, options)
    } else {
      this.spawn(command, args, options)
    }

    this.killed = false
    this.handleEvents(stdout, stderr, exit)
  }

  // Windows has a bunch of special rules that node still doesn't take care of for you
  spawnWithEscapedWindowsArgs (command, args, options) {
    let cmdArgs = []
    // Quote all arguments and escapes inner quotes
    if (args) {
      cmdArgs = args.filter((arg) => arg != null)
        .map((arg) => {
          if (this.isExplorerCommand(command) && /^\/[a-zA-Z]+,.*$/.test(arg)) {
            // Don't wrap /root,C:\folder style arguments to explorer calls in
            // quotes since they will not be interpreted correctly if they are
            return arg
          } else {
            // Escape double quotes by putting a backslash in front of them
            return `\"${arg.toString().replace(/"/g, '\\"')}\"`
          }
        })
    }

    // The command itself is quoted if it contains spaces, &, ^ or | chars
    cmdArgs.unshift(/\s|&|\^|\(|\)|\|/.test(command) ? `\"${command}\"` : command)

    const cmdOptions = _.clone(options)
    cmdOptions.windowsVerbatimArguments = true

    this.spawn(this.getCmdPath(), ['/s', '/d', '/c', `\"${cmdArgs.join(' ')}\"`], cmdOptions)
  }

  /*
  Section: Event Subscription
  */

  // Public: Will call your callback when an error will be raised by the process.
  // Usually this is due to the command not being available or not on the PATH.
  // You can call `handle()` on the object passed to your callback to indicate
  // that you have handled this error.
  //
  // * `callback` {Function} callback
  //   * `errorObject` {Object}
  //     * `error` {Object} the error object
  //     * `handle` {Function} call this to indicate you have handled the error.
  //       The error will not be thrown if this function is called.
  //
  // Returns a {Disposable}
  onWillThrowError (callback) {
    return this.emitter.on('will-throw-error', callback)
  }

  /*
  Section: Helper Methods
  */

  // Helper method to pass data line by line.
  //
  // * `stream` The Stream to read from.
  // * `onLines` The callback to call with each line of data.
  // * `onDone` The callback to call when the stream has closed.
  bufferStream (stream, onLines, onDone) {
    stream.setEncoding('utf8')
    let buffered = ''

    stream.on('data', (data) => {
      if (this.killed) return

      let bufferedLength = buffered.length
      buffered += data
      let lastNewlineIndex = data.lastIndexOf('\n')

      if (lastNewlineIndex !== -1) {
        let lineLength = lastNewlineIndex + bufferedLength + 1
        onLines(buffered.substring(0, lineLength))
        buffered = buffered.substring(lineLength)
      }
    })

    stream.on('close', () => {
      if (this.killed) return
      if (buffered.length > 0) onLines(buffered)
      onDone()
    })
  }

  // Kill all child processes of the spawned cmd.exe process on Windows.
  //
  // This is required since killing the cmd.exe does not terminate child
  // processes.
  killOnWindows () {
    if (!this.process) return

    const parentPid = this.process.pid
    const cmd = 'wmic'
    const args = [
      'process',
      'where',
      `(ParentProcessId=${parentPid})`,
      'get',
      'processid'
    ]

    let wmicProcess

    try {
      wmicProcess = ChildProcess.spawn(cmd, args)
    } catch (spawnError) {
      this.killProcess()
      return
    }

    wmicProcess.on('error', () => {}) // ignore errors

    let output = ''
    wmicProcess.stdout.on('data', (data) => {
      output += data
    })
    wmicProcess.stdout.on('close', () => {
      const pidsToKill = output.split(/\s+/)
        .filter((pid) => /^\d+$/.test(pid))
        .map((pid) => parseInt(pid))
        .filter((pid) => pid !== parentPid && pid > 0 && pid < Infinity)

      for (let pid of pidsToKill) {
        try {
          process.kill(pid)
        } catch (error) {}
      }

      this.killProcess()
    })
  }

  killProcess () {
    if (this.process) this.process.kill()
    this.process = null
  }

  isExplorerCommand (command) {
    if (command === 'explorer.exe' || command === 'explorer') {
      return true
    } else if (process.env.SystemRoot) {
      return command === path.join(process.env.SystemRoot, 'explorer.exe') || command === path.join(process.env.SystemRoot, 'explorer')
    } else {
      return false
    }
  }

  getCmdPath () {
    if (process.env.comspec) {
      return process.env.comspec
    } else if (process.env.SystemRoot) {
      return path.join(process.env.SystemRoot, 'System32', 'cmd.exe')
    } else {
      return 'cmd.exe'
    }
  }

  // Public: Terminate the process.
  kill () {
    if (this.killed) return

    this.killed = true
    if (process.platform === 'win32') {
      this.killOnWindows()
    } else {
      this.killProcess()
    }
  }

  spawn (command, args, options) {
    try {
      this.process = ChildProcess.spawn(command, args, options)
    } catch (spawnError) {
      process.nextTick(() => this.handleError(spawnError))
    }
  }

  handleEvents (stdout, stderr, exit) {
    if (!this.process) return

    const triggerExitCallback = () => {
      if (this.killed) return
      if (stdoutClosed && stderrClosed && processExited && typeof exit === 'function') {
        exit(exitCode)
      }
    }

    let stdoutClosed = true
    let stderrClosed = true
    let processExited = true
    let exitCode = 0

    if (stdout) {
      stdoutClosed = false
      this.bufferStream(this.process.stdout, stdout, () => {
        stdoutClosed = true
        triggerExitCallback()
      })
    }

    if (stderr) {
      stderrClosed = false
      this.bufferStream(this.process.stderr, stderr, () => {
        stderrClosed = true
        triggerExitCallback()
      })
    }

    if (exit) {
      processExited = false
      this.process.on('exit', (code) => {
        exitCode = code
        processExited = true
        triggerExitCallback()
      })
    }

    this.process.on('error', (error) => {
      this.handleError(error)
    })
  }

  handleError (error) {
    let handled = false

    const handle = () => {
      handled = true
    }

    this.emitter.emit('will-throw-error', {error, handle})

    if (error.code === 'ENOENT' && error.syscall.indexOf('spawn') === 0) {
      error = new Error(`Failed to spawn command \`${this.command}\`. Make sure \`${this.command}\` is installed and on your PATH`, error.path)
      error.name = 'BufferedProcessError'
    }

    if (!handled) throw error
  }
}
<|endoftext|>


<commit_before>var CultureMinistry = require('./CultureMinistry.js');

export default class Culture {
    constructor() {
        CultureMinistry.setCulture(this);
    }

    get id() {
        return this.id_;
    }

    get el() {
        var rv = this.element;
        if (!rv) rv = this.element = document.getElementById(this.id);

        return rv;
    }

    toString() {
        return this.templates_base();
    }

    $$(selector) {
        var rv = null, el = this.el;

        if (el) rv = el.querySelectorAll(selector);

        if (!rv.length) rv = null;

        return rv;
    }

    $(selector) {
        var rv = null, el = this.el;

        if (el) rv = selector == undefined ? el : el.querySelector(selector);

        return rv;
    }

    render(opt_base, opt_index) {
        if (opt_base) {
            this.element = CultureMinistry.createElement(this.toString());
            this.element.id = this.id;
            opt_base.insertBefore(this.element, opt_base.childNodes[opt_index] || null);
        }
    }

    template() {
        return `<div></div>`;
    }

    dispose() {
        CultureMinistry.removeCulture(this);
        this.element && this.element.parentNode.removeChild(this.element);
        this.element = null;
        this.id_ = null;
    }
};
<commit_msg>[Culture] Fix toString method template call<commit_after>var CultureMinistry = require('./CultureMinistry.js');

export default class Culture {
    constructor() {
        CultureMinistry.setCulture(this);
    }

    get id() {
        return this.id_;
    }

    get el() {
        var rv = this.element;
        if (!rv) rv = this.element = document.getElementById(this.id);

        return rv;
    }

    toString() {
        return this.template();
    }

    $$(selector) {
        var rv = null, el = this.el;

        if (el) rv = el.querySelectorAll(selector);

        if (!rv.length) rv = null;

        return rv;
    }

    $(selector) {
        var rv = null, el = this.el;

        if (el) rv = selector == undefined ? el : el.querySelector(selector);

        return rv;
    }

    render(opt_base, opt_index) {
        if (opt_base) {
            this.element = CultureMinistry.createElement(this.toString());
            this.element.id = this.id;
            opt_base.insertBefore(this.element, opt_base.childNodes[opt_index] || null);
        }
    }

    template() {
        return `<div></div>`;
    }

    dispose() {
        CultureMinistry.removeCulture(this);
        this.element && this.element.parentNode.removeChild(this.element);
        this.element = null;
        this.id_ = null;
    }
};
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var githelper = require('../utils/git.js');

function handlePing(req) {
    console.log('Ping!');
    console.log(req.zen);
}

function handlePush(req) {
    console.log(req.ref);
    if (req.ref != "refs/heads/master") {
        console.log("This commit is not for master branch.");
        return;
    }
    console.log("Head Commit: " + req.head_commit.id);
    console.log("Commit Message: " + req.head_commit.message);
    console.log("\t Author: " + req.head_commit.author.name + "(" + req.head_commit.author.username + ")");
    githelper.cloneRepo(req.repository.clone_url);
}

/* GET users listing. */
router.get('/', function(req, res) {
    res.send('respond with a resource');
});

router.post('/webhook', function(req, res) {
    var event_type = req.get('X-GitHub-Event');
    switch (event_type) {
        case 'ping':
            handlePing(req.body);
            break;
        case 'push':
            handlePush(req.body);
            break;
        default:
            console.log(req.body);
            break;
    }
    res.send('Thanks for the update! <3');
});

module.exports = router;
<commit_msg>made github route use promises and generate docs<commit_after>var express = require('express');
var router = express.Router();
var git = require('../utils/git.js');
var doxygen = require('../utils/doxygen.js');

function handlePing(req) {
    console.log('Ping!');
    console.log(req.zen);
}

function handlePush(req) {
    console.log(req.ref);
    if (req.ref != "refs/heads/master") {
        console.log("This commit is not for master branch.");
        return;
    }
    console.log("Head Commit: " + req.head_commit.id);
    console.log("Commit Message: " + req.head_commit.message);
    console.log("\t Author: " + req.head_commit.author.name + "(" + req.head_commit.author.username + ")");
    git.process(req.repository).then(function(repo) {
       doxygen.process(repo).then(function() {
           //create new repo
           // copy docs into repo
       });
    });
}

/* GET users listing. */
router.get('/', function(req, res) {
    res.send('respond with a resource');
});

router.post('/webhook', function(req, res) {
    var event_type = req.get('X-GitHub-Event');
    switch (event_type) {
        case 'ping':
            handlePing(req.body);
            break;
        case 'push':
            handlePush(req.body);
            break;
        default:
            console.log(req.body);
            break;
    }
    res.send('Thanks for the update! <3');
});

module.exports = router;
<|endoftext|>


<commit_before>import express from 'express';
import bodyParser from 'body-parser';
import Movie from '../models/movie';
const jsonParser = bodyParser.json();
const router = module.exports = express.Router();

router
  // Retrieve all Movies
  .get('/', (req, res, next) => {
    Movie
      .find({})
      .lean()
      .then(movies => {
        res.json(movies);
      })
      .catch(err => next({
        error: err,
        code: 404,
        msg: 'No movies found',
      }));
  })

  // Retrieve a specific Movie
  .get('/:movieId', (req, res, next) => {
    Movie
      .findById(req.params.movieId)
      .lean()
      .then(movie => {
        res.json(movie);
      })
      .catch(err => {
        next({
          code: 404,
          msg: 'Movie not found',
          error: err,
        });
      });
  })

// POST a Movie
  .post('/', jsonParser, (req, res, next) => {
    new Movie(req.body)
      .save()
      .then(movie => {
        res.json({
          status: 'posted',
          result: movie,
        });
      })
      .catch(err => {
        next({
          status: 'error',
          result: 'server err',
          error: err,
        });
      });
  })

// PUT (aka update/change) a Movie

  .put('/:id', jsonParser, (req, res, next) => {
    Movie
    .findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true, runValidators: true }
    )
      .then(updatedMovie => {
        if (updatedMovie) res.json({ result: updatedMovie });
      })
      .catch(err => {
        next({
          code: 500,
          msg: 'unable to modify movie',
          error: err,
        });
      });
  });

// // DELETE a Company
//
//   .delete('/:id', (req, res, next) => {
//     Company
//     .findByIdAndRemove(req.params.id)
//       .then(removedCompany => {
//         if (removedCompany) res.json({ result: removedCompany });
//       })
//       .catch(err => {
//         next({
//           code: 500,
//           msg: 'unable to remove company',
//           error: err,
//         });
//       });
//   });

export default router;
<commit_msg>can now delete movies<commit_after>import express from 'express';
import bodyParser from 'body-parser';
import Movie from '../models/movie';
const jsonParser = bodyParser.json();
const router = module.exports = express.Router();

router
  // Retrieve all Movies
  .get('/', (req, res, next) => {
    Movie
      .find({})
      .lean()
      .then(movies => {
        res.json(movies);
      })
      .catch(err => next({
        error: err,
        code: 404,
        msg: 'No movies found',
      }));
  })

  // Retrieve a specific Movie
  .get('/:movieId', (req, res, next) => {
    Movie
      .findById(req.params.movieId)
      .lean()
      .then(movie => {
        res.json(movie);
      })
      .catch(err => {
        next({
          code: 404,
          msg: 'Movie not found',
          error: err,
        });
      });
  })

// POST a Movie
  .post('/', jsonParser, (req, res, next) => {
    new Movie(req.body)
      .save()
      .then(movie => {
        res.json({
          status: 'posted',
          result: movie,
        });
      })
      .catch(err => {
        next({
          status: 'error',
          result: 'server err',
          error: err,
        });
      });
  })

// PUT (aka update/change) a Movie

  .put('/:id', jsonParser, (req, res, next) => {
    Movie
    .findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true, runValidators: true }
    )
      .then(updatedMovie => {
        if (updatedMovie) res.json({ result: updatedMovie });
      })
      .catch(err => {
        next({
          code: 500,
          msg: 'unable to modify movie',
          error: err,
        });
      });
  })

// DELETE a Company

  .delete('/:id', (req, res, next) => {
    Movie
    .findByIdAndRemove(req.params.id)
      .then(removedMovie => {
        if (removedMovie) res.json({ result: removedMovie });
      })
      .catch(err => {
        next({
          code: 500,
          msg: 'unable to remove movie',
          error: err,
        });
      });
  });

export default router;
<|endoftext|>


<commit_before>import {isArray, isObject, nest as nestObject} from "../util.js";
import {colors} from "../color.js";
import {getPalette} from "../palette.js";
import {getExpressionSources} from "./expression.js";

//Get value from context
export function value (props, datum, defaultValue) {
    let context = this;
    //Check for undefined property value
    if (typeof props === "undefined") {
        return defaultValue;
    }
    //Check for non object or null props
    else if (typeof props !== "object" || props === null) {
        return props;
    }
    //Check if props is an array: multiple choice
    else if (isArray(props) === true) {
        //Check all conditions
        for (let i = 0; i < props.length; i++) {
            if (typeof props[i] === "object" && props[i] !== null) {
                //Check if test entry has beel provided
                if (typeof props[i].test === "string") {
                    //Check if this item does not passes the test
                    if (context.expression(props[i].test, {"datum": datum}) !== true) {
                        continue;
                    }
                }
            }
            //Return this value
            return context.value(props[i], datum, null);
        }
        //Exit loop: throw error
        //TODO
        return null;
    }
    //Get the initial value
    let value = datum; //defaultValue;
    //let value = (typeof props.field === "string") ? viz.object.get(datum, props.field) : datum;
    //Check for color value
    if (typeof props.color === "string") {
        value = (typeof context.theme.colors[props.color] === "string") ? context.theme.colors[props.color] : colors.black;
    }
    //Check for color palette
    else if (typeof props.palette === "string" || isObject(props.palette)) {
        value = getPalette(context.value(props.palette, "default", "default")); //Get color palette
    }
    //Check for expression value
    else if (typeof props.expr === "string") {
        value = context.expression(props.expr, {
            "datum": datum
        });
    }
    //Check for custom value provided
    else if (typeof props.value !== "undefined" && props.value !== null) {
        value = props.value;
    }
    //Check for value from draw context
    else if (typeof props.draw === "string") {
        //value = context.draw.computed[props.draw]; //Get computed width or height value
        value = context.panels.value[props.draw]; //Get the panel width or height value
    }
    //Check for value from state
    else if (typeof props.state === "string") {
        let keys = props.state.replace(/\[["']?(\w+)['"]?\]/g, ".$1").replace(/^\./, "").split(".");
        let stateName = keys.shift(); // <-- Extract state name
        //value = object.get(context.state, props.state);
        value = nestObject(context.state[stateName].value, keys.join("."));
    }
    //Check for field value
    else if (typeof props.field === "string") {
        value = nestObject(datum, props.field); //TODO: fix this
    }
    //Check for scale to apply to the current value
    if (typeof props.scale === "string") {
        let scale = context.scales[props.scale].value;
        //let value = (typeof props.field === "string") ? viz.object.get(datum, props.field) : datum;
        //Get the scaled value
        //value = scale(value);
        //Check for interval scale and position property provided
        if (scale.type === "interval" && typeof props.interval !== "undefined") {
            value = scale(value) + scale.step * Number(props.interval);
        }
        //Other scale type: apply the scale to the current value
        else {
            value = scale(value);
        }
        //Return the scaled value
        //return value;
    }
    //Return the value
    return value;
}

//Get value source
export function getValueSources (context, value) {
    let sources = [];
    //Check if value is not an object
    if (typeof value !== "object" || value === null) {
        return []; //No sources
    }
    //Check for array --> test value: parse each test key and each value key
    else if (isArray(value) === true) {
        value.forEach(function (item) {
            //Get the sources on the test expression
            if (typeof item.test === "string") {
                getExpressionSources(context, item.test).forEach(function (source) {
                    sources.push(source);
                });
            }
            //Parse the sources on this item
            getValueSources(context, item).forEach(function (source) {
                sources.push(source);
            });
        });
        //Return the sources
        return sources;
    }
    //Check for state values
    if (typeof value.state === "string") {
        //Bug: the state value can be an object path
        let keys = value.state.replace(/\[["']?(\w+)['"]?\]/g, ".$1").replace(/^\./, "").split(".");
        let stateName = keys.shift(); // <-- Extract state name
        sources.push(context.state[stateName]);
    }
    //Check for scale value
    if (typeof value.scale === "string") {
        sources.push(context.scales[value.scale]);
    }
    //Check for draw value
    if (typeof value.draw === "string") {
        //sources.push(context.draw[value.draw]);
        sources.push(context.panels); //Add panels as dependency instead of draw
    }
    //Check for expression value
    if (typeof value.expr === "string") {
        getExpressionSources(context, value.expr).forEach(function (source) {
            sources.push(source);
        });
    }
    //Other value: return empty sources
    return sources;
}

<commit_msg>runtime: allow getting interval offset from context value instead of getting a fixed number<commit_after>import {isArray, isObject, nest as nestObject} from "../util.js";
import {colors} from "../color.js";
import {getPalette} from "../palette.js";
import {getExpressionSources} from "./expression.js";

//Get value from context
export function value (props, datum, defaultValue) {
    let context = this;
    //Check for undefined property value
    if (typeof props === "undefined") {
        return defaultValue;
    }
    //Check for non object or null props
    else if (typeof props !== "object" || props === null) {
        return props;
    }
    //Check if props is an array: multiple choice
    else if (isArray(props) === true) {
        //Check all conditions
        for (let i = 0; i < props.length; i++) {
            if (typeof props[i] === "object" && props[i] !== null) {
                //Check if test entry has beel provided
                if (typeof props[i].test === "string") {
                    //Check if this item does not passes the test
                    if (context.expression(props[i].test, {"datum": datum}) !== true) {
                        continue;
                    }
                }
            }
            //Return this value
            return context.value(props[i], datum, null);
        }
        //Exit loop: throw error
        //TODO
        return null;
    }
    //Get the initial value
    let value = datum; //defaultValue;
    //let value = (typeof props.field === "string") ? viz.object.get(datum, props.field) : datum;
    //Check for color value
    if (typeof props.color === "string") {
        value = (typeof context.theme.colors[props.color] === "string") ? context.theme.colors[props.color] : colors.black;
    }
    //Check for color palette
    else if (typeof props.palette === "string" || isObject(props.palette)) {
        value = getPalette(context.value(props.palette, "default", "default")); //Get color palette
    }
    //Check for expression value
    else if (typeof props.expr === "string") {
        value = context.expression(props.expr, {
            "datum": datum
        });
    }
    //Check for custom value provided
    else if (typeof props.value !== "undefined" && props.value !== null) {
        value = props.value;
    }
    //Check for value from draw context
    else if (typeof props.draw === "string") {
        //value = context.draw.computed[props.draw]; //Get computed width or height value
        value = context.panels.value[props.draw]; //Get the panel width or height value
    }
    //Check for value from state
    else if (typeof props.state === "string") {
        let keys = props.state.replace(/\[["']?(\w+)['"]?\]/g, ".$1").replace(/^\./, "").split(".");
        let stateName = keys.shift(); // <-- Extract state name
        //value = object.get(context.state, props.state);
        value = nestObject(context.state[stateName].value, keys.join("."));
    }
    //Check for field value
    else if (typeof props.field === "string") {
        value = nestObject(datum, props.field); //TODO: fix this
    }
    //Check for scale to apply to the current value
    if (typeof props.scale === "string") {
        let scale = context.scales[props.scale].value;
        //let value = (typeof props.field === "string") ? viz.object.get(datum, props.field) : datum;
        //Get the scaled value
        value = scale(value);
        //Check for interval scale and position property provided
        if (scale.type === "interval" && typeof props.interval !== "undefined") {
            let intervalValue = Number(context.value(props.interval, datum, 0)); //Get interval value
            value = value + scale.step * ((isNaN(intervalValue)) ? 0 : intervalValue);
        }
        //Return the scaled value
        //return value;
    }
    //Return the value
    return value;
}

//Get value source
export function getValueSources (context, value) {
    let sources = [];
    //Check if value is not an object
    if (typeof value !== "object" || value === null) {
        return []; //No sources
    }
    //Check for array --> test value: parse each test key and each value key
    else if (isArray(value) === true) {
        value.forEach(function (item) {
            //Get the sources on the test expression
            if (typeof item.test === "string") {
                getExpressionSources(context, item.test).forEach(function (source) {
                    sources.push(source);
                });
            }
            //Parse the sources on this item
            getValueSources(context, item).forEach(function (source) {
                sources.push(source);
            });
        });
        //Return the sources
        return sources;
    }
    //Check for state values
    if (typeof value.state === "string") {
        //Bug: the state value can be an object path
        let keys = value.state.replace(/\[["']?(\w+)['"]?\]/g, ".$1").replace(/^\./, "").split(".");
        let stateName = keys.shift(); // <-- Extract state name
        sources.push(context.state[stateName]);
    }
    //Check for scale value
    if (typeof value.scale === "string") {
        sources.push(context.scales[value.scale]);
    }
    //Check for draw value
    if (typeof value.draw === "string") {
        //sources.push(context.draw[value.draw]);
        sources.push(context.panels); //Add panels as dependency instead of draw
    }
    //Check for expression value
    if (typeof value.expr === "string") {
        getExpressionSources(context, value.expr).forEach(function (source) {
            sources.push(source);
        });
    }
    //Other value: return empty sources
    return sources;
}

<|endoftext|>


<commit_before>
export const BOTUI_TYPES = {
  WAIT: 'wait',
  ACTION: 'action',
  MESSAGE: 'message',
}

const createBlock = (type = '', meta = {}, data = {}) => {
  return {
    type: type,
    meta: meta,
    data: data
  }
}

export const botuiControl = () => {
  const history = []
  let resolver = null
  let _currentAction = null

  let callback = () => {}
  const doCallback = () => {
    callback(_currentAction, history)
  }

  const doResolve = (...args) => {
    resolver(...args)
  }

  const currentAction = {
    set: (action) => {
      _currentAction = action
      doCallback()
    },
    get: () => action,
    clear: () => {
      _currentAction = null
      doCallback()
    }
  }

  const msg = {
    add: (block) => {
      const length = history.push(block)
      doCallback()
      return length - 1
    },
    update: (index, block) => {
      history[index] = block
      doCallback()
    },
    remove: (index) => {
      history.splice(index, 1)
      doCallback()
    }
  }

  return {
    message: (meta = {}, data = { text: '' }) => {
      return new Promise((resolve) => {
        resolver = resolve
        msg.add(createBlock(BOTUI_TYPES.MESSAGE, meta, data))
        doResolve()
      })
    },
    wait: (meta = { time: 0 }) => {
      return new Promise((resolve) => {
        resolver = resolve
        currentAction.set(createBlock(BOTUI_TYPES.WAIT, meta))
        setTimeout(() => {
          currentAction.clear()
          doResolve()
        }, meta.time)
      })
    },
    action: (meta = {}, data = { text: '' }) => {
      return new Promise((resolve) => {
        const action = createBlock(BOTUI_TYPES.ACTION, meta, data)
        currentAction.set(action)

        resolver = (...args) => {
          currentAction.clear()

          msg.add(createBlock(BOTUI_TYPES.MESSAGE, {
            type: BOTUI_TYPES.ACTION
          }, ...args))

          resolve(...args)
        }
      })
    },
    onCallback: (cb = () => {}) => {
      callback = cb
    },
    next: (...args) => {
      doResolve(...args)
    }
  }
}
<commit_msg>using local state instead of direct vars<commit_after>
export const BOTUI_TYPES = {
  WAIT: 'wait',
  ACTION: 'action',
  MESSAGE: 'message',
}

const createBlock = (type = '', meta = {}, data = {}) => {
  return {
    type: type,
    meta: meta,
    data: data
  }
}

export const botuiControl = () => {
  const localState = {
    history: [],
    resolver: () => {},
    currentAction: null
  }

  let callback = () => {}
  const doCallback = () => {
    callback(localState.currentAction, localState.history)
  }

  const doResolve = (...args) => {
    localState.resolver(...args)
  }

  const currentAction = {
    set: (action) => {
      localState.currentAction = action
      doCallback()
    },
    get: () => localState.currentAction,
    clear: () => {
      localState.currentAction = null
      doCallback()
    }
  }

  const msg = {
    add: (block) => {
      const length = localState.history.push(block)
      doCallback()
      return length - 1
    },
    update: (index, block) => {
      localState.history[index] = block
      doCallback()
    },
    remove: (index) => {
      localState.history.splice(index, 1)
      doCallback()
    }
  }

  return {
    message: (meta = {}, data = { text: '' }) => {
      return new Promise((resolve) => {
        localState.resolver = resolve
        msg.add(createBlock(BOTUI_TYPES.MESSAGE, meta, data))
        doResolve()
      })
    },
    wait: (meta = { time: 0 }) => {
      return new Promise((resolve) => {
        localState.resolver = resolve
        currentAction.set(createBlock(BOTUI_TYPES.WAIT, meta))
        setTimeout(() => {
          currentAction.clear()
          doResolve()
        }, meta.time)
      })
    },
    action: (meta = {}, data = { text: '' }) => {
      return new Promise((resolve) => {
        const action = createBlock(BOTUI_TYPES.ACTION, meta, data)
        currentAction.set(action)

        localState.resolver = (...args) => {
          currentAction.clear()

          msg.add(createBlock(BOTUI_TYPES.MESSAGE, {
            type: BOTUI_TYPES.ACTION
          }, ...args))

          resolve(...args)
        }
      })
    },
    onCallback: (cb = () => {}) => {
      callback = cb
    },
    next: (...args) => {
      doResolve(...args)
    }
  }
}
<|endoftext|>


<commit_before>
import Tyr from '../tyr';

import Component from '../core/component';

const Secure {

};

Tyr.mixin(Secure, Component);

Tyr.Secure = Secure;

export default Secure;
<commit_msg>fix a typo<commit_after>
import Tyr from '../tyr';

import Component from '../core/component';

const Secure = {

};

Tyr.mixin(Secure, Component);

Tyr.Secure = Secure;

export default Secure;
<|endoftext|>


<commit_before>
AppStarter = {

    /**
     * Initialize the application
     *  // TODO this pg attr is library dependent, should rather be an url or an RDF document body serialized
     * @param pg the initial pointed graph
     * @param currentScriptUrl: required to resolve relative paths of other JS files to load
     */
    initialize : function(pg,currentScriptUrl) {
        console.debug("Initializing with PG=",pg);
        var baseUrl = this.getBaseUrl(currentScriptUrl);
        console.debug("Will use baseUrl=",baseUrl);

        // TODO do not use global initialPG variable but inject it in the require app
        window.initialPG = pg;

        this.loadRequireJS(
            baseUrl+"/js/main",
            baseUrl+"/js/lib/require/require.js",
            undefined
        )

    },

    loadRequireJS: function(dataMain,requireLib,callback) {
        var script = document.createElement('script');
        script.setAttribute("data-main", dataMain);
        script.src = requireLib;
        document.body.appendChild(script);
        if(callback) callback();
    },

    /**
     * The baseUrl is the absolute path of the folder of the app.
     * We can't use the html baseUrl to resolve paths because.
     *
     * @param scriptUrl
     * @return baseUrl (doesn't end with a / )
     */
    getBaseUrl: function(currentScriptUrl) {
        if ( currentScriptUrl && currentScriptUrl.indexOf(".js") != -1 && currentScriptUrl.indexOf("/") != -1 ) {
            var scriptFolder = currentScriptUrl.substr( 0 , currentScriptUrl.lastIndexOf("/") );
            return scriptFolder;
        }
        else {
            throw new Error("Bad or missing scriptUrl attribute: "+currentScriptUrl + " . " +
                "It is required to start the app with AppStarter.initialize(pg,currentScriptUrl)." +
                "Note currentScriptUrl should at least contain one / so you can use ./AppStarter.js but not AppStarter.js");
        }
    }

}<commit_msg>Refactor AppStarter to not use a requirejs datamain<commit_after>
AppStarter = {

    /**
     * Initialize the application
     *  // TODO this pg attr is library dependent, should rather be an url or an RDF document body serialized
     * @param pointedGraph the initial pointed graph
     * @param currentScriptUrl: required to resolve relative paths of other JS files to load
     */
    initialize : function(pointedGraph,currentScriptUrl) {
        var self = this
        console.debug("Initializing with PG=",pointedGraph);
        var appBaseUrl = this.getAppBaseUrl(currentScriptUrl);
        console.debug("Will use appBaseUrl=",appBaseUrl);

        var requireJsUrl = appBaseUrl+"/js/lib/require/require.js"
        this.loadScript(requireJsUrl,function() {
            self.startRequire(appBaseUrl,pointedGraph);
        })
    },

    /**
     * Triggers the dynamic loading of a new JS file
     * @param scriptSrc
     * @param callback
     */
    loadScript: function(scriptSrc, callback) {
        var oHead = document.getElementsByTagName('head')[0];
        var oScript = document.createElement('script');
        oScript.type = 'text/javascript';
        oScript.src = scriptSrc;
        // Then bind the event to the callback function.
        oScript.onreadystatechange = callback;   // IE 6 & 7
        oScript.onload = callback;
        oHead.appendChild(oScript);
    },

    /**
     * The baseUrl is the absolute path of the folder of the app.
     * We can't use the html baseUrl to resolve paths because.
     *
     * @param scriptUrl
     * @return baseUrl (doesn't end with a / )
     */
    getAppBaseUrl: function(currentScriptUrl) {
        if ( currentScriptUrl && currentScriptUrl.indexOf(".js") != -1 && currentScriptUrl.indexOf("/") != -1 ) {
            var scriptFolder = currentScriptUrl.substr( 0 , currentScriptUrl.lastIndexOf("/") );
            return scriptFolder;
        }
        else {
            throw new Error("Bad or missing scriptUrl attribute: "+currentScriptUrl + " . " +
                "It is required to start the app with AppStarter.initialize(pg,currentScriptUrl)." +
                "Note currentScriptUrl should at least contain one / so you can use ./AppStarter.js but not AppStarter.js");
        }
    },

    /**
     * Start require
     * @param appBaseUrl
     * @param pg
     */
    startRequire: function(appBaseUrl, pointedGraph) {

        require.config({
            baseUrl: appBaseUrl,

            map: {
                "*": {
                    // doesn't work well if declared with "paths"
                    "less": "js/lib/require/require-less-0.1.1/less"
                }
            },

            paths: {

                /*
                 * RequireJS Plugins
                 */
                "jsx": "js/lib/require/require-jsx/jsx",
                "JSXTransformer": "js/lib/require/require-jsx/JSXTransformer",

                /*
                 * Libs
                 */
                "jquery": "js/lib/jquery-2.1.0.min",
                "react": "js/lib/react-0.8.0",
                "reactAddons": "js/lib/react-with-addons-0.8.0",
                "underscore":"js/lib/underscore",
                "lodash": "js/lib/lodash.underscore",
                "rx": "js/lib/rx",
                "rxAsync": "js/lib/rx.async",
                "q": "js/lib/q",
                "rdflib": "js/lib/rdflib/rdflib-stample-0.1.0",
                "rdflib-pg-extension": "js/lib/rdflib/rdflib-stample-pg-extension-0.1.0",
                "director": "js/lib/director",

                /*
                 * Utils
                 */
                "foafUtils": "js/scripts/foafUtils",
                "httpUtils": "js/scripts/httpUtils",

                "mixins": "js/scripts/mixins",
                "routing": "js/scripts/routing",
                "PGReact": "js/scripts/PGReact",

                /*
                 *    REACT Components.
                 */
                "App": "js/scripts/App",
                "Window": "js/scripts/windows/Window",
                "FoafWindow": "js/scripts/windows/FoafWindow",
                "MainSearchBox": "js/scripts/layout/MainSearchBox",
                "ContentSpace": "js/scripts/layout/ContentSpace",
                "FooterItem": "js/scripts/layout/FooterItem",

                "Pix": "js/scripts/common/Pix",
                "PersonContactOnProfileBasicInfo": "js/scripts/contacts/PersonContactOnProfileBasicInfo",
                "PersonContactOnProfileMoreInfo": "js/scripts/contacts/PersonContactOnProfileMoreInfo",
                "PersonContactOnProfileNotifications": "js/scripts/contacts/PersonContactOnProfileNotifications",
                "PersonContactOnProfileMessage": "js/scripts/contacts/PersonContactOnProfileMessage",
                "PersonContactOnProfilePix": "js/scripts/contacts/PersonContactOnProfilePix",
                "PersonContactOnProfile": "js/scripts/contacts/PersonContactOnProfile",
                "PersonContactOnProfileJumpWrapper": "js/scripts/contacts/PersonContactOnProfileJumpWrapper",
                "PersonContacts": "js/scripts/contacts/PersonContacts",
                "SearchBox": "js/scripts/contacts/SearchBox",

                "PersonBasicInfo": "js/scripts/person/PersonBasicInfo",
                "PersonNotifications": "js/scripts/person/PersonNotifications",
                "PersonMessage": "js/scripts/person/PersonMessage",
                "PersonMoreInfo": "js/scripts/person/PersonMoreInfo",
                "PersonAddress": "js/scripts/person/PersonAddress",
                "PersonWebId": "js/scripts/person/PersonWebId",
                "PersonEditProfile": "js/scripts/person/PersonEditProfile",
                "Person": "js/scripts/person/Person"

                /*
                 * CSS : Use less.
                 */

            },

            shim: {
                JSXTransformer: {
                    exports: "JSXTransformer"
                },

                "rdflib-pg-extension": {
                    "deps": ["rdflib","q","underscore"],
                    "exports":"$rdf.PG"
                },

                "foafUtils": {
                    "exports":"foafUtils"
                },

                "httpUtils": {
                    "exports":"httpUtils"
                }

                /*
                 "reactAddons": {
                 "exports":"React.addons"
                 }*/

            }
        });

        require(
            [
                "jquery",
                "react",
                "rdflib",
                "rdflib-pg-extension",
                "q",
                "rx",
                "rxAsync",
                "routing",
                "jsx!App",
                "less!css/base.less"
            ],
            function ($, React, rdflib, rdflibPg, Q, rx, rxAsync, routing, App, baseLess) {
                // Make these variable globals.
                window.Q = Q; //TODO: find better way to deal with Q

                // TODO remove these global image paths !!!
                avatar = require.toUrl("img/avatar.png");
                friendIcon = require.toUrl("img/friends_icon_yellow.png");
                closeIcon = require.toUrl("img/close_icon.png");
                webIdIcon = require.toUrl("img/webid.png");

                // proxy
                //$rdf.Fetcher.fetcherWithPromiseCrossSiteProxyTemplate = "https://www.stample.io/srv/cors?url=";
                //$rdf.Fetcher.fetcherWithPromiseCrossSiteProxyTemplate = "http://localhost:9000/srv/cors?url=";
                //$rdf.Fetcher.fetcherWithPromiseCrossSiteProxyTemplate = "http://data.fm/proxy?uri=";
                //$rdf.Fetcher.homeServer = "http://localhost:9000/"

                window.foafSpec = "http://xmlns.com/foaf/spec/"; // Do I need this?

                var fetcherTimeout = 4000;

                // TODO fix global variable issue :(
                store = rdflibPg.createNewStore(fetcherTimeout);

                // Set the bootstrap URL with the initial PG pointer.
                // TODO bad !!!
                if ( pointedGraph) {
                    foafDocURL = pointedGraph.pointer.uri;
                } else {
                    foafDocURL = "http://bblfish.net/people/henry/card#me";
                    //var foafDocURL = "https://my-profile.eu/people/deiu/card#me";
                    //foafDocURL = "https://localhost:8443/2013/backbone#me";
                    // TODO need to add hash if needed: we do not look for primary topic anymore
                    //var foafDocURL = "https://my-profile.eu/people/mtita/card";// Not working
                    //var foafDocURL = "http://presbrey.mit.edu/foaf";
                    //var foafDocURL = 'https://ameliemelo3.localhost:8443/card';
                    //var foafDocURL = "https://my-profile.eu/people/tim/card";
                    //var foafDocURL = "https://my-profile.eu/people/deiu/card";
                }

                // TODO maybe this should be injected as props???
                routeHelper = new RouteHelper();

                // Launch the App.
                var mountNode = document.getElementById('container');
                React.renderComponent(App({profileURL:foafDocURL}), mountNode);

            });
    }

}<|endoftext|>


<commit_before>/**
 * @file to JSON serialization
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfAttributesGet*/ // Get attributes defined for the object / class
/*global _gpfAttributesSerializable*/ // Shortcut for gpf.attributes.Serializable
/*global _gpfFunctionBuild*/ // Build function from description and context
/*global _gpfObjectForEach*/ // Similar to [].forEach but for objects
/*#endif*/

function _gpfSerialRawBuildMembers (SerializableClass) {
    var serial = _gpfAttributesGet(SerializableClass, _gpfAttributesSerializable),
        members = [];
    _gpfObjectForEach(serial, function (attributes, member) {
        var property = attributes[0].getProperty();
        members.push("\t\t" + property.name + ": instance." + member);
    });
    return members;
}

function _gpfSerialRawBuild (SerializableClass) {
    return _gpfFunctionBuild({
        body: "return function (instance) {\n"
            + "\tif (!(instance instanceof SerializableClass)) gpf.Error.invalidParameter();\n\treturn {\n"
            + _gpfSerialRawBuildMembers(SerializableClass).join(",")
            + "\t};\n};",
        parameters: ["SerializableClass"]
    })(SerializableClass);
}

/**
 * Generates a function aimed to converts instances of the given class to a simpler dictionary containing only
 * serializable properties' value.
 *
 * @param {Function} SerializableClass Class containing {@ling gpf.attributes.Serializable} attributes
 * @return {Function} A function that accepts only instances of the given class and returns a dictionary with all
 * serializable properties (indexed by member names)
 * @throws {gpf.Error.InvalidParameter}
 */
gpf.serial.buildToRaw = function (SerializableClass) {
    if ("function" !== typeof SerializableClass) {
        gpf.Error.invalidParameter();
    }
    return _gpfSerialRawBuild(SerializableClass);
};
<commit_msg>Use _gpfSerialGet (#287)<commit_after>/**
 * @file to raw serialization
 */
/*#ifndef(UMD)*/
"use strict";
/*global _gpfFunctionBuild*/ // Build function from description and context
/*global _gpfObjectForEach*/ // Similar to [].forEach but for objects
/*global _gpfSerialGet*/ // Collect gpf.typedef.serializableProperty defined for the object / class
/*#endif*/

function _gpfSerialRawBuildMembers (SerializableClass) {
    var properties = _gpfSerialGet(SerializableClass),
        members = [];
    _gpfObjectForEach(properties, function (property, member) {
        members.push("\t\t" + property.name + ": instance." + member);
    });
    return members;
}

function _gpfSerialRawBuild (SerializableClass) {
    return _gpfFunctionBuild({
        body: "return function (instance) {\n"
            + "\tif (!(instance instanceof SerializableClass)) gpf.Error.invalidParameter();\n\treturn {\n"
            + _gpfSerialRawBuildMembers(SerializableClass).join(",")
            + "\t};\n};",
        parameters: ["SerializableClass"]
    })(SerializableClass);
}

/**
 * Generates a function aimed to converts instances of the given class to a simpler dictionary containing only
 * serializable properties' value.
 *
 * @param {Function} SerializableClass Class containing {@ling gpf.attributes.Serializable} attributes
 * @return {Function} A function that accepts only instances of the given class and returns a dictionary with all
 * serializable properties (indexed by member names)
 * @throws {gpf.Error.InvalidParameter}
 */
gpf.serial.buildToRaw = function (SerializableClass) {
    if ("function" !== typeof SerializableClass) {
        gpf.Error.invalidParameter();
    }
    return _gpfSerialRawBuild(SerializableClass);
};
<|endoftext|>


<commit_before>var express = require('express');
var r = module.exports = express.Router();
//var _ = require('lodash');
var logger = require('winston')
//var Promise = require('bluebird');

var user = process.env.DEWDROP_USER;
var pass = process.env.DEWDROP_PASS;

if (!user) logger.warn("no DEWDROP_USER set")
if (!pass) logger.warn("no DEWDROP_PASS set")
if (!user && !pass) logger.warn('everyone is authorized!')
else logger.warn("hey! make sure you're using SSL!")

function authorize(req, res, next) {
  var ok = req.body.username === user && req.body.password === pass
  if (ok) next()
  else res.status(401).end()
}

function act(req, res, next) {
  actions[req.query.action](req, res, next)
}

var actions = {
  /*
   * ?action=verify POST username=[YOUR USERNAME] password=[YOUR PASSWORD] // returns JSON, you can check data.success
   */
  verify: function (req, res, next) {
    res.status(200).send({success: {}})
    next()
  },

}

r.route('/').post(authorize, act)

/*
 * ?action=upload POST username=[USERNAME] password=[PASSWORD] filenames=FILENAME file file should be called "userfile" // returns data.success for whether it succeeded or not, and data.message for the URL or error message
 *
 * ?action=browse POST username=[USERNAME] password=[PASSWORD] // returns data.success for true/false, files as an array of: filename, extension, size
 *
 * ?action=get-last-uploaded-file POST username=[USERNAME] password=[PASSWORD] // returns data.success for true/false, file with properties: filename, extension, size
 *
 * ?action=thumb POST filename=[THE FILENAME YOU WANT A THUMB FOR] // returns a graphical representation - use it as an
 *
 * ?action=remove&filename=[FILENAME] POST username=[USERNAME] password=[PASSWORD] // returns data.success for true/false
 */
<commit_msg>stub upload<commit_after>var express = require('express');
var r = module.exports = express.Router();
//var _ = require('lodash');
var logger = require('winston')
//var Promise = require('bluebird');

var user = process.env.DEWDROP_USER;
var pass = process.env.DEWDROP_PASS;

if (!user) logger.warn("no DEWDROP_USER set")
if (!pass) logger.warn("no DEWDROP_PASS set")
if (!user && !pass) logger.warn('everyone is authorized!')
else logger.warn("hey! make sure you're using SSL!")

function authorize(req, res, next) {
  var ok = req.body.username === user && req.body.password === pass
  if (ok) next()
  else res.status(401).end()
}

function act(req, res, next) {
  actions[req.query.action](req, res, next)
}

var actions = {
  /*
   * ?action=verify POST username=[YOUR USERNAME] password=[YOUR PASSWORD] // returns JSON, you can check data.success
   */
  verify: function (req, res, next) {
    res.status(200).send({success: true})
  },
  /*
   * ?action=upload POST username=[USERNAME] password=[PASSWORD] filenames=FILENAME file file should be called "userfile" // returns data.success for whether it succeeded or not, and data.message for the URL or error message
   */
  upload: function (req, res, next) {
    res.status(501).end()
  }
}

r.route('/').post(authorize, act)

/*
 * ?action=browse POST username=[USERNAME] password=[PASSWORD] // returns data.success for true/false, files as an array of: filename, extension, size
 *
 * ?action=get-last-uploaded-file POST username=[USERNAME] password=[PASSWORD] // returns data.success for true/false, file with properties: filename, extension, size
 *
 * ?action=thumb POST filename=[THE FILENAME YOU WANT A THUMB FOR] // returns a graphical representation - use it as an
 *
 * ?action=remove&filename=[FILENAME] POST username=[USERNAME] password=[PASSWORD] // returns data.success for true/false
 */
<|endoftext|>


<commit_before>// #!/usr/bin/env node
'use strict';
import app from './app';
import http from 'http';
import config from '../../config';

const server = http.createServer(app);
const port = normalizePort(config.server.port);

app.set('port', port);

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

// Normalize a port into a number, string, or false.
function normalizePort(val) {
    let port = parseInt(val, 10);
    if (isNaN(port)) return val;  // named pipe
    if (port >= 0) return port;   // port number
    return false;
}

// Event listener for HTTP server "error" event.
function onError(error) {
    if (error.syscall !== 'listen') log.error(error);

    const bind = typeof port === 'string'
        ? 'Pipe ' + port
        : 'Port ' + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
        case 'EACCES':
            log.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;

        case 'EADDRINUSE':
            log.error(bind + ' is already in use');
            process.exit(1);
            break;

        case 'ETIMEDOUT':
            log.error('Timeout error');
            process.exit(1);
            break;

        default:
            log.error('LOG TEST:')
            log.error(error.message)
            log.error(error.code)
            throw error
    }
}

// Event listener for HTTP server "listening" event.
function onListening() {
    const addr = server.address();
    const bind = typeof addr === 'string'
        ? 'pipe ' + addr
        : 'port ' + addr.port;
    log.http(`Connected to localhost:${port}`)
}
<commit_msg>fix(server): Import path<commit_after>// #!/usr/bin/env node
'use strict';
import app from './app';
import http from 'http';
import config from '../config';

const server = http.createServer(app);
const port = normalizePort(config.server.port);

app.set('port', port);

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

// Normalize a port into a number, string, or false.
function normalizePort(val) {
    let port = parseInt(val, 10);
    if (isNaN(port)) return val;  // named pipe
    if (port >= 0) return port;   // port number
    return false;
}

// Event listener for HTTP server "error" event.
function onError(error) {
    if (error.syscall !== 'listen') log.error(error);

    const bind = typeof port === 'string'
        ? 'Pipe ' + port
        : 'Port ' + port;

    // handle specific listen errors with friendly messages
    switch (error.code) {
        case 'EACCES':
            log.error(bind + ' requires elevated privileges');
            process.exit(1);
            break;

        case 'EADDRINUSE':
            log.error(bind + ' is already in use');
            process.exit(1);
            break;

        case 'ETIMEDOUT':
            log.error('Timeout error');
            process.exit(1);
            break;

        default:
            log.error('LOG TEST:')
            log.error(error.message)
            log.error(error.code)
            throw error
    }
}

// Event listener for HTTP server "listening" event.
function onListening() {
    const addr = server.address();
    const bind = typeof addr === 'string'
        ? 'pipe ' + addr
        : 'port ' + addr.port;
    log.http(`Connected to localhost:${port}`)
}
<|endoftext|>


<commit_before>import express from "express";
import engine  from "ejs-locals";
import favicon from 'serve-favicon';
import controllers from './controllers';
import serverApi from './api';
import sassMiddleware from 'node-sass-middleware';
import sass from 'node-sass';
import fs from 'fs';
import mongo from 'mongod';
import monk from 'monk';
var bodyParser = require('body-parser');

const db = monk('localhost:27017/ml-monitor');
const app = express();

app.set("env", process.env.NODE_ENV || "development");
app.set("port", process.env.PORT || 3000);

app.use(bodyParser.json());

app.engine('ejs', engine);//Support for layout for templates
app.set('view engine', 'ejs');

app.set('views', './views');
app.use(favicon( './public/images/favicon/favicon.ico'));

var srcPath = './';
var destPath = './public';

//TODO: If folder does not exist, its not moved.
var moveFile = function(from, to) {
    if(fs.existsSync(to)) {
        return;
    }
    fs.readFile(from, function (err, data) {
        if (err) throw err;
        fs.writeFile(to, data, function (err) {
            if (err) throw err;
            console.log('It\'s saved! ' + to);
        });
    });
};

var createFolder = function(path, name) {
    var dir = path + name;
    if (!fs.existsSync(dir)){
        fs.mkdirSync(dir);
    }
};

createFolder('./public/', 'style');
moveFile('./node_modules/muicss/dist/css/mui.min.css', './public/style/mui.min.css');
moveFile('./node_modules/muicss/dist/js/mui.min.js', './public/js/mui.min.js');
moveFile('./node_modules/normalize.css/normalize.css', './public/style/normalize.css');
moveFile('./node_modules/react-notifications/lib/notifications.css', './public/style/notifications.css');
moveFile('./node_modules/rickshaw/rickshaw.min.css', './public/style/rickshaw.min.css');
moveFile('./node_modules/rickshaw/rickshaw.min.js', './public/js/rickshaw.min.js');
moveFile('./node_modules/rickshaw/vendor/d3.layout.min.js', './public/js/d3.layout.min.js');
moveFile('./node_modules/rickshaw/vendor/d3.min.js', './public/js/d3.min.js');

if(app.get('env') === 'development') {
    app.use(sassMiddleware({
        /* Options */
        src: srcPath,
        dest: destPath,
        debug: true,
        outputStyle: 'compressed',
        prefix:  '/prefix'
    }));
    app.use(express.static('./public')); //compiled sass and other stuff put in here
}
else {
    app.use(express.static('./public')); //compiled sass and other stuff put in here
}

//TODO: Move to build.js
if(app.get('env') === 'production') {
    console.log("==== Render SASS =====")
    //TODO: Dest in public not in public/style in production. Fix
    sass.render({
        file: srcPath + '/style/style.scss',
            outputStyle: 'compressed'
    },
    function(err, result) {
        if(err) {
            console.log(err);
            throw new Error("Could not render SASS")
        }
        else {
            fs.writeFile(destPath + '/style.css', result.css, function(err) {
                if(err) {
                    return console.log(err);
                    throw new Error("Could not write SASS")
                }
                console.log("The file was saved!");
            });
        }
    });
}

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST', 'DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
    next();
});

app.use(function(req,res,next){
    req.db = db;
    next();
});

serverApi.set(app);
controllers.set(app);

var server = app.listen(app.get("port"), function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);
});<commit_msg>Create js folder if not exists<commit_after>import express from "express";
import engine  from "ejs-locals";
import favicon from 'serve-favicon';
import controllers from './controllers';
import serverApi from './api';
import sassMiddleware from 'node-sass-middleware';
import sass from 'node-sass';
import fs from 'fs';
import mongo from 'mongod';
import monk from 'monk';
var bodyParser = require('body-parser');

const db = monk('localhost:27017/ml-monitor');
const app = express();

app.set("env", process.env.NODE_ENV || "development");
app.set("port", process.env.PORT || 3000);

app.use(bodyParser.json());

app.engine('ejs', engine);//Support for layout for templates
app.set('view engine', 'ejs');

app.set('views', './views');
app.use(favicon( './public/images/favicon/favicon.ico'));

var srcPath = './';
var destPath = './public';

//TODO: If folder does not exist, its not moved.
var moveFile = function(from, to) {
    if(fs.existsSync(to)) {
        return;
    }
    fs.readFile(from, function (err, data) {
        if (err) throw err;
        fs.writeFile(to, data, function (err) {
            if (err) throw err;
            console.log('It\'s saved! ' + to);
        });
    });
};

var createFolder = function(path, name) {
    var dir = path + name;
    if (!fs.existsSync(dir)){
        fs.mkdirSync(dir);
    }
};

createFolder('./public/', 'style');
createFolder('./public/', 'js');
moveFile('./node_modules/muicss/dist/css/mui.min.css', './public/style/mui.min.css');
moveFile('./node_modules/muicss/dist/js/mui.min.js', './public/js/mui.min.js');
moveFile('./node_modules/normalize.css/normalize.css', './public/style/normalize.css');
moveFile('./node_modules/react-notifications/lib/notifications.css', './public/style/notifications.css');
moveFile('./node_modules/rickshaw/rickshaw.min.css', './public/style/rickshaw.min.css');
moveFile('./node_modules/rickshaw/rickshaw.min.js', './public/js/rickshaw.min.js');
moveFile('./node_modules/rickshaw/vendor/d3.layout.min.js', './public/js/d3.layout.min.js');
moveFile('./node_modules/rickshaw/vendor/d3.min.js', './public/js/d3.min.js');

if(app.get('env') === 'development') {
    app.use(sassMiddleware({
        /* Options */
        src: srcPath,
        dest: destPath,
        debug: true,
        outputStyle: 'compressed',
        prefix:  '/prefix'
    }));
    app.use(express.static('./public')); //compiled sass and other stuff put in here
}
else {
    app.use(express.static('./public')); //compiled sass and other stuff put in here
}

//TODO: Move to build.js
if(app.get('env') === 'production') {
    console.log("==== Render SASS =====")
    //TODO: Dest in public not in public/style in production. Fix
    sass.render({
        file: srcPath + '/style/style.scss',
            outputStyle: 'compressed'
    },
    function(err, result) {
        if(err) {
            console.log(err);
            throw new Error("Could not render SASS")
        }
        else {
            fs.writeFile(destPath + '/style.css', result.css, function(err) {
                if(err) {
                    return console.log(err);
                    throw new Error("Could not write SASS")
                }
                console.log("The file was saved!");
            });
        }
    });
}

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST', 'DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
    next();
});

app.use(function(req,res,next){
    req.db = db;
    next();
});

serverApi.set(app);
controllers.set(app);

var server = app.listen(app.get("port"), function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);
});<|endoftext|>


<commit_before>(function() {
    "use strict";

    var homepageFile = "views/homepage.html";

    var http = require('http');
    var fs = require('fs-extra');
    var path = require('path');
    var Q = require("q");

    var database = require("./database.js");

    var express = require('express');
    var connectFlash = require("connect-flash");
    var expressWinston = require("express-winston");
    var winston = require('winston');

    var modelFor = require("./modelFor");

    var nconf = require('./config.js');

    var server;

    exports.start = function(port, callback) {

        var app = express();

        app.use(express.limit('4mb'));
        app.use(express.bodyParser({
                    keepExtensions: true,
                    uploadDir: nconf.tempPathForUploads()
                }));
        app.use(express.cookieParser());
        app.set('views', __dirname + '/views');
        app.set('view engine', 'jade');

        app.use(express.cookieSession({
                    secret: nconf.get("server_sessionKey")
                }));

        app.use(connectFlash());

        require("./google-auth")(port, app);
        require("./posts")(app);

        app.get("/", handleHomepageRequest);
        app.get("/status", handleStatusRequest);

        require("./feeds")(app);

        app.get("/crash", function() {
            throw new Error("Ooops!");
        });

        app.get("/main-built.js", function(req,res) {
            var mainBuilt = path.resolve(__dirname + '../../../temp/main-built.js');
            fs.exists(mainBuilt, function(exists) {
                if (exists) {
                    res.sendfile(mainBuilt);
                } else {
                    res.status(404).send("not found");
                }
            });
        });

        app.use("/client", express.static(__dirname + './../client/'));

        var errorLoggingFile = path.resolve(nconf.tempPathForLogs(), "errors.json");

        var transports = [];
        transports.push(new winston.transports.File({
                    filename: errorLoggingFile,
                    maxsize: 64 * 1024 * 1024,
                    maxFiles: 20,
                    json: true
                }));

        if (!nconf.isProduction) {
            transports.push(new winston.transports.Console({
                        json: true
                    }));
        }

        app.use(expressWinston.errorLogger({
                    transports: transports
                }));

        app.use(errorHandler);

        server = http.createServer(app);
        server.listen(port, callback);
    };

    exports.stop = function(callback) {
        if (server) {
            server.close(callback);
            server = null;
        }
    };

    function handleHomepageRequest(request, response, next) {

        var model = modelFor("homepage", request);

        if (model.isAuthenticated) {

            database.loadSubscriptions(request.user.id)
            .then(function(subscriptions) {
                console.log("subscriptions", subscriptions);
                if (subscriptions.length > 0) {
                    response.render('index', model);
                } else {
                    response.redirect("/feeds");
                }
            }, function(err) {
                next(err);
            });

        } else {
            response.render('index', model);
        }
    }

    function canWrite(owner, inGroup, mode) {
        return owner && (mode & 0x80) || // User is owner and owner can write.
        inGroup && (mode & 0x10) || // User is in group and group can write.
        (mode & 0x2); // Anyone can write.

    }

    function handleStatusRequest(request, response) {

        var model = modelFor('Status', request);

        database.getStatus(function(statusString) {
            model.databaseStatus = statusString;

            fs.stat(nconf.tempPathForUploads(), function(err, stat) {

                if (err) {
                    model.uploadPathStatus = err.toString();
                } else if (canWrite(process.uid === stat.uid, process.gid === stat.gid, stat.mode)) {
                    model.uploadPathStatus = "writeable";
                } else {
                    model.uploadPathStatus = "insufficient permissions";
                }

                response.render('status', model);
                response.end();
            });
        });
    }

    function errorHandler(err, req, res, next) {
        res.render("error500", modelFor("Error", req));
    }

})();<commit_msg>cleanup dead code<commit_after>(function() {
    "use strict";

    var http = require('http');
    var fs = require('fs-extra');
    var path = require('path');
    var Q = require("q");

    var database = require("./database.js");

    var express = require('express');
    var connectFlash = require("connect-flash");
    var expressWinston = require("express-winston");
    var winston = require('winston');

    var modelFor = require("./modelFor");

    var nconf = require('./config.js');

    var server;

    exports.start = function(port, callback) {

        var app = express();

        app.use(express.limit('4mb'));
        app.use(express.bodyParser({
                    keepExtensions: true,
                    uploadDir: nconf.tempPathForUploads()
                }));
        app.use(express.cookieParser());
        app.set('views', __dirname + '/views');
        app.set('view engine', 'jade');

        app.use(express.cookieSession({
                    secret: nconf.get("server_sessionKey")
                }));

        app.use(connectFlash());

        require("./google-auth")(port, app);
        require("./posts")(app);

        app.get("/", handleHomepageRequest);
        app.get("/status", handleStatusRequest);

        require("./feeds")(app);

        app.get("/crash", function() {
            throw new Error("Ooops!");
        });

        app.get("/main-built.js", function(req,res) {
            var mainBuilt = path.resolve(__dirname + '../../../temp/main-built.js');
            fs.exists(mainBuilt, function(exists) {
                if (exists) {
                    res.sendfile(mainBuilt);
                } else {
                    res.status(404).send("not found");
                }
            });
        });

        app.use("/client", express.static(__dirname + './../client/'));

        var errorLoggingFile = path.resolve(nconf.tempPathForLogs(), "errors.json");

        var transports = [];
        transports.push(new winston.transports.File({
                    filename: errorLoggingFile,
                    maxsize: 64 * 1024 * 1024,
                    maxFiles: 20,
                    json: true
                }));

        if (!nconf.isProduction) {
            transports.push(new winston.transports.Console({
                        json: true
                    }));
        }

        app.use(expressWinston.errorLogger({
                    transports: transports
                }));

        app.use(errorHandler);

        server = http.createServer(app);
        server.listen(port, callback);
    };

    exports.stop = function(callback) {
        if (server) {
            server.close(callback);
            server = null;
        }
    };

    function handleHomepageRequest(request, response, next) {

        var model = modelFor("homepage", request);

        if (model.isAuthenticated) {

            database.loadSubscriptions(request.user.id)
            .then(function(subscriptions) {
                console.log("subscriptions", subscriptions);
                if (subscriptions.length > 0) {
                    response.render('index', model);
                } else {
                    response.redirect("/feeds");
                }
            }, function(err) {
                next(err);
            });

        } else {
            response.render('index', model);
        }
    }

    function canWrite(owner, inGroup, mode) {
        return owner && (mode & 0x80) || // User is owner and owner can write.
        inGroup && (mode & 0x10) || // User is in group and group can write.
        (mode & 0x2); // Anyone can write.

    }

    function handleStatusRequest(request, response) {

        var model = modelFor('Status', request);

        database.getStatus(function(statusString) {
            model.databaseStatus = statusString;

            fs.stat(nconf.tempPathForUploads(), function(err, stat) {

                if (err) {
                    model.uploadPathStatus = err.toString();
                } else if (canWrite(process.uid === stat.uid, process.gid === stat.gid, stat.mode)) {
                    model.uploadPathStatus = "writeable";
                } else {
                    model.uploadPathStatus = "insufficient permissions";
                }

                response.render('status', model);
                response.end();
            });
        });
    }

    function errorHandler(err, req, res, next) {
        res.render("error500", modelFor("Error", req));
    }

})();<|endoftext|>


<commit_before>import invariant from 'invariant';
import isFunction from './utils/isFunction';
import isPlainObject from './utils/isPlainObject';
import identity from './utils/identity';
import isNil from './utils/isNil';
import isUndefined from './utils/isUndefined';
import toString from './utils/toString';
import { ACTION_TYPE_DELIMITER } from './constants';

export default function handleAction(type, reducer = identity, defaultState) {
  const types = toString(type).split(ACTION_TYPE_DELIMITER);
  invariant(
    !isUndefined(defaultState),
    `defaultState for reducer handling ${types.join(', ')} should be defined`
  );
  invariant(
    isFunction(reducer) || isPlainObject(reducer),
    'Expected reducer to be a function or object with next and throw reducers'
  );

  const [nextReducer, throwReducer] = isFunction(reducer)
    ? [reducer, reducer]
    : [reducer.next, reducer.throw].map(
        aReducer => (isNil(aReducer) ? identity : aReducer)
      );

  return (state = defaultState, action) => {
    const { type: actionType } = action;
    if (!actionType || !types.includes(toString(actionType))) {
      return state;
    }

    return (action.error === true ? throwReducer : nextReducer)(state, action);
  };
}
<commit_msg>IE11 does not support Array.prototype.includes (#313)<commit_after>import invariant from 'invariant';
import isFunction from './utils/isFunction';
import isPlainObject from './utils/isPlainObject';
import identity from './utils/identity';
import isNil from './utils/isNil';
import isUndefined from './utils/isUndefined';
import toString from './utils/toString';
import { ACTION_TYPE_DELIMITER } from './constants';

export default function handleAction(type, reducer = identity, defaultState) {
  const types = toString(type).split(ACTION_TYPE_DELIMITER);
  invariant(
    !isUndefined(defaultState),
    `defaultState for reducer handling ${types.join(', ')} should be defined`
  );
  invariant(
    isFunction(reducer) || isPlainObject(reducer),
    'Expected reducer to be a function or object with next and throw reducers'
  );

  const [nextReducer, throwReducer] = isFunction(reducer)
    ? [reducer, reducer]
    : [reducer.next, reducer.throw].map(
        aReducer => (isNil(aReducer) ? identity : aReducer)
      );

  return (state = defaultState, action) => {
    const { type: actionType } = action;
    if (!actionType || types.indexOf(toString(actionType)) === -1) {
      return state;
    }

    return (action.error === true ? throwReducer : nextReducer)(state, action);
  };
}
<|endoftext|>


<commit_before>'use strict'

const chalk = require('chalk')

let log

module.exports = function serverlessLog(msg) {
  log(msg, 'offline')
}

module.exports.setLog = function setLog(serverlessLogRef) {
  log = serverlessLogRef
}

// logs based on:
// https://github.com/serverless/serverless/blob/master/lib/classes/CLI.js

module.exports.errorLog = function errorLog(msg) {
  console.log()
  console.log(`offline: ${chalk.keyword('red')(msg)}`)
  console.log()
}

module.exports.logRoute = function logRoute(httpMethod, server, path) {
  console.log(
    `offline: ${chalk.keyword('dodgerblue')(`[${httpMethod}]`)} ${chalk
      .keyword('grey')
      .dim(`${server}`)}${chalk.keyword('lime')(path)}`,
  )
}
<commit_msg>Remove errorLog<commit_after>'use strict'

const chalk = require('chalk')

let log

module.exports = function serverlessLog(msg) {
  log(msg, 'offline')
}

module.exports.setLog = function setLog(serverlessLogRef) {
  log = serverlessLogRef
}

// logs based on:
// https://github.com/serverless/serverless/blob/master/lib/classes/CLI.js

module.exports.logRoute = function logRoute(httpMethod, server, path) {
  console.log(
    `offline: ${chalk.keyword('dodgerblue')(`[${httpMethod}]`)} ${chalk
      .keyword('grey')
      .dim(`${server}`)}${chalk.keyword('lime')(path)}`,
  )
}
<|endoftext|>


<commit_before>/**
 * @workInProgress
 * @ngdoc service
 * @name angular.service.$hover
 * @requires $browser
 * @requires $document
 *
 * @description
 *
 * @example
 */
angularServiceInject("$hover", function(browser, document) {
  var tooltip, self = this, error, width = 300, arrowWidth = 10, body = jqLite(document[0].body);
  browser.hover(function(element, show){
    if (show && (error = element.attr(NG_EXCEPTION) || element.attr(NG_VALIDATION_ERROR))) {
      if (!tooltip) {
        tooltip = {
            callout: jqLite('

'),
            arrow: jqLite('

'),
            title: jqLite('

'),
            content: jqLite('

')
        };
        tooltip.callout.append(tooltip.arrow);
        tooltip.callout.append(tooltip.title);
        tooltip.callout.append(tooltip.content);
        body.append(tooltip.callout);
      }
      var docRect = body[0].getBoundingClientRect(),
          elementRect = element[0].getBoundingClientRect(),
          leftSpace = docRect.right - elementRect.right - arrowWidth;
      tooltip.title.text(element.hasClass("ng-exception") ? "EXCEPTION:" : "Validation error...");
      tooltip.content.text(error);
      if (leftSpace < width) {
        tooltip.arrow.addClass('ng-arrow-right');
        tooltip.arrow.css({left: (width + 1)+'px'});
        tooltip.callout.css({
          position: 'fixed',
          left: (elementRect.left - arrowWidth - width - 4) + "px",
          top: (elementRect.top - 3) + "px",
          width: width + "px"
        });
      } else {
        tooltip.arrow.addClass('ng-arrow-left');
        tooltip.callout.css({
          position: 'fixed',
          left: (elementRect.right + arrowWidth) + "px",
          top: (elementRect.top - 3) + "px",
          width: width + "px"
        });
      }
    } else if (tooltip) {
      tooltip.callout.remove();
      tooltip = _null;
    }
  });
}, ['$browser', '$document']);
<commit_msg>re-eagarizing the $hover service - mea culpa<commit_after>/**
 * @workInProgress
 * @ngdoc service
 * @name angular.service.$hover
 * @requires $browser
 * @requires $document
 *
 * @description
 *
 * @example
 */
angularServiceInject("$hover", function(browser, document) {
  var tooltip, self = this, error, width = 300, arrowWidth = 10, body = jqLite(document[0].body);
  browser.hover(function(element, show){
    if (show && (error = element.attr(NG_EXCEPTION) || element.attr(NG_VALIDATION_ERROR))) {
      if (!tooltip) {
        tooltip = {
            callout: jqLite('

'),
            arrow: jqLite('

'),
            title: jqLite('

'),
            content: jqLite('

')
        };
        tooltip.callout.append(tooltip.arrow);
        tooltip.callout.append(tooltip.title);
        tooltip.callout.append(tooltip.content);
        body.append(tooltip.callout);
      }
      var docRect = body[0].getBoundingClientRect(),
          elementRect = element[0].getBoundingClientRect(),
          leftSpace = docRect.right - elementRect.right - arrowWidth;
      tooltip.title.text(element.hasClass("ng-exception") ? "EXCEPTION:" : "Validation error...");
      tooltip.content.text(error);
      if (leftSpace < width) {
        tooltip.arrow.addClass('ng-arrow-right');
        tooltip.arrow.css({left: (width + 1)+'px'});
        tooltip.callout.css({
          position: 'fixed',
          left: (elementRect.left - arrowWidth - width - 4) + "px",
          top: (elementRect.top - 3) + "px",
          width: width + "px"
        });
      } else {
        tooltip.arrow.addClass('ng-arrow-left');
        tooltip.callout.css({
          position: 'fixed',
          left: (elementRect.right + arrowWidth) + "px",
          top: (elementRect.top - 3) + "px",
          width: width + "px"
        });
      }
    } else if (tooltip) {
      tooltip.callout.remove();
      tooltip = _null;
    }
  });
}, ['$browser', '$document'], true);
<|endoftext|>