<commit_before>var angular = require('angular');

angular.module('MolApp').controller('FullScreenMoleculeCtrl', ['$rootScope','$scope', '$window', '$location', function($rootScope, $scope, $window, $location){
  // When showing this route: fullscreen mode activate
  $rootScope.fullScreenMode = true;
  // When not this route fullscreen mode deactivate
  $scope.$on("$destroy", function() {
    $rootScope.fullScreenMode = false;
  });

    // set the width and height dynamically to fill screen
  $scope.viewerWidth = $window.innerWidth;
  $scope.viewerHeight = $window.innerHeight;
  angular.element($window).bind('resize', function(){
    $scope.viewerWidth = $window.innerWidth;
    $scope.viewerHeight = $window.innerHeight;

    // manuall $digest required as resize event
    // is outside of angular
    $scope.$digest();
  });

  $scope.goBack = function(){
    $location.path("schedule");
  };

}]);
<commit_msg>fixed routing error<commit_after>var angular = require('angular');

angular.module('MolApp').controller('FullScreenMoleculeCtrl', ['$rootScope','$scope', '$window', '$location', function($rootScope, $scope, $window, $location){
  // When showing this route: fullscreen mode activate
  $rootScope.fullScreenMode = true;
  // When not this route fullscreen mode deactivate
  $scope.$on("$destroy", function() {
    $rootScope.fullScreenMode = false;
  });

    // set the width and height dynamically to fill screen
  $scope.viewerWidth = $window.innerWidth;
  $scope.viewerHeight = $window.innerHeight;
  angular.element($window).bind('resize', function(){
    $scope.viewerWidth = $window.innerWidth;
    $scope.viewerHeight = $window.innerHeight;

    // manuall $digest required as resize event
    // is outside of angular
    $scope.$digest();
  });

  $scope.goBack = function(){
    $location.path("/schedule");
  };

}]);
<|endoftext|>


<commit_before>import { autorun, reaction } from 'mobx';

import { DEFAULT_FEATURES_CONFIG } from '../../config';

const debug = require('debug')('Franz:feature:spellchecker');

export const config = {
  isPremiumFeature: DEFAULT_FEATURES_CONFIG.isSpellcheckerPremiumFeature,
};

export default function init(stores) {
  reaction(
    () => stores.features.features.isSpellcheckerPremiumFeature,
    (enabled, r) => {
      debug('Initializing `spellchecker` feature');

      // Dispose the reaction to run this only once
      r.dispose();

      const { isSpellcheckerPremiumFeature } = stores.features.features;

      config.isPremiumFeature = isSpellcheckerPremiumFeature !== undefined ? isSpellcheckerPremiumFeature : DEFAULT_FEATURES_CONFIG.isSpellcheckerPremiumFeature;

      autorun(() => {
        if (!stores.user.data.isPremium && config.isPremiumFeature) {
          debug('Override settings.spellcheckerEnabled flag to false');

          Object.assign(stores.settings.all.app, {
            enableSpellchecking: false,
          });
        }
      });
    },
  );
}

<commit_msg>Simplify spellchecker feature init<commit_after>import { autorun, observable } from 'mobx';

import { DEFAULT_FEATURES_CONFIG } from '../../config';

const debug = require('debug')('Franz:feature:spellchecker');

export const config = observable({
  isPremiumFeature: DEFAULT_FEATURES_CONFIG.isSpellcheckerPremiumFeature,
});

export default function init(stores) {
  debug('Initializing `spellchecker` feature');

  autorun(() => {
    const { isSpellcheckerPremiumFeature } = stores.features.features;

    config.isPremiumFeature = isSpellcheckerPremiumFeature !== undefined ? isSpellcheckerPremiumFeature : DEFAULT_FEATURES_CONFIG.isSpellcheckerPremiumFeature;

    if (!stores.user.data.isPremium && config.isPremiumFeature && stores.settings.app.enableSpellchecking) {
      debug('Override settings.spellcheckerEnabled flag to false');

      Object.assign(stores.settings.app, {
        enableSpellchecking: false,
      });
    }
  });
}
<|endoftext|>


<commit_before>let filename = config.production
  ? '[name].[hash:7].[ext]'
  : '[name].[ext]';

const URL_LOADER = [
  {
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url-loader',
    options: {
      limit: 10000,
      name: File.assetsPath(`${config.paths.target.img}/${filename}`)
    }
  }, {
    test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
    loader: 'url-loader',
    options: {
      limit: 10000,
      name: File.assetsPath(`${config.paths.target.media}/${filename}`)
    }
  }, {
    test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
    loader: 'url-loader',
    options: {
      limit: 10000,
      name: File.assetsPath(`${config.paths.target.font}/${filename}`)
    }
  }
];

export default URL_LOADER;
<commit_msg>cache bugfix<commit_after>let filename = '[name].[ext]';

const URL_LOADER = [
  {
    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
    loader: 'url-loader',
    options: {
      limit: 10000,
      name: File.assetsPath(`${config.paths.target.img}/${filename}`)
    }
  }, {
    test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
    loader: 'url-loader',
    options: {
      limit: 10000,
      name: File.assetsPath(`${config.paths.target.media}/${filename}`)
    }
  }, {
    test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
    loader: 'url-loader',
    options: {
      limit: 10000,
      name: File.assetsPath(`${config.paths.target.font}/${filename}`)
    }
  }
];

export default URL_LOADER;
<|endoftext|>


<commit_before>var winningChances = require('ceval').winningChances;
var treePath = require('tree').path;
var winningChances = require('ceval').winningChances;
var pv2san = require('ceval').pv2san;
var m = require('mithril');

module.exports = function(root) {

  var running = m.prop(true);
  var comment = m.prop();
  var hovering = m.prop();
  var hinting = m.prop();
  var played = m.prop(false);

  var ensureCevalRunnning = function() {
    if (!root.vm.showComputer()) root.toggleComputer();
    if (!root.ceval.enabled()) root.toggleCeval();
    if (root.vm.threatMode) root.toggleThreatMode();
  };

  var commentable = function(node, bonus) {
    if (root.gameOver(node)) return true;
    var ceval = node.ceval;
    return ceval && ((ceval.depth + (bonus || 0)) >= 15 || (ceval.depth >= 13 && ceval.millis > 3000));
  };
  var playable = function(node) {
    var ceval = node.ceval;
    return ceval && (ceval.depth >= 18 || (ceval.depth >= 16 && ceval.millis > 7000));
  };

  var altCastles = {
    e1a1: 'e1c1',
    e1h1: 'e1g1',
    e8a8: 'e8c8',
    e8h8: 'e8g8'
  };

  var makeComment = function(prev, node, path) {
    var nodeEval = node.ceval;
    var over = root.gameOver(node);
    if (over === 'draw') nodeEval = {
      cp: 0
    };
    else if (over === 'checkmate') nodeEval = {
      mate: 0
    };
    var shift = -winningChances.povDiff(root.bottomColor(), nodeEval, prev.ceval);

    var best = prev.ceval.best;
    if (best === node.uci || best === altCastles[node.uci]) best = null;

    var c;
    if (!best) c = 'good';
    else if (shift < 0.025) c = 'good';
    else if (shift < 0.06) c = 'inaccuracy';
    else if (shift < 0.14) c = 'mistake';
    else c = 'blunder';

    return {
      prev: prev,
      node: node,
      path: path,
      verdict: c,
      best: best ? {
        uci: best,
        san: pv2san(root.data.game.variant.key, prev.fen, false, best)
      } : null
    };
  }

  var isMyTurn = function() {
    return root.turnColor() === root.bottomColor();
  };

  var checkCeval = function() {
    if (!running()) {
      comment(null);
      m.redraw();
      return;
    }
    ensureCevalRunnning();
    var node = root.vm.node;
    if (isMyTurn()) {
      var h = hinting();
      if (h) {
        h.uci = node.ceval.best;
        root.setAutoShapes();
      }
    } else {
      comment(null);
      if (node.san && commentable(node)) {
        var parentNode = root.tree.nodeAtPath(treePath.init(root.vm.path));
        if (commentable(parentNode, +1))
          comment(makeComment(parentNode, node, root.vm.path));
      }
      if (!played() && playable(node)) {
        root.playUci(node.ceval.best);
        played(true);
      }
    }
  };

  var resume = function() {
    running(true);
    checkCeval();
  };

  checkCeval();

  return {
    onCeval: checkCeval,
    onJump: function() {
      played(false);
      hinting(null);
      checkCeval();
      // because running(false) is called after the jump
      // setTimeout(checkCeval, 50)
    },
    isMyTurn: isMyTurn,
    comment: comment,
    running: running,
    hovering: hovering,
    hinting: hinting,
    resume: resume,
    reset: function() {
      comment(null);
      hinting(null);
    },
    preUserJump: function(from, to) {
      if (from !== to) {
        running(false);
        comment(null);
      }
    },
    postUserJump: function(from, to) {
      if (from !== to && isMyTurn()) resume();
    },
    onUserMove: function() {
      running(true);
    },
    playCommentBest: function() {
      var c = comment();
      if (!c) return;
      root.jump(treePath.init(c.path));
      root.playUci(c.best.uci);
    },
    commentShape: function(enable) {
      var c = comment();
      if (!enable || !c) hovering(null);
      else hovering({
        uci: c.best.uci
      });
      root.setAutoShapes();
    },
    hint: function() {
      var best = root.vm.node.ceval ? root.vm.node.ceval.best : null;
      var prev = hinting();
      if (!best || (prev && prev.mode === 'move')) hinting(null);
      else hinting({
        mode: prev ? 'move' : 'piece',
        uci: best
      });
      root.setAutoShapes();
    }
  };
};
<commit_msg>fix practice comment on mate - closes #2594<commit_after>var winningChances = require('ceval').winningChances;
var treePath = require('tree').path;
var winningChances = require('ceval').winningChances;
var pv2san = require('ceval').pv2san;
var m = require('mithril');

module.exports = function(root) {

  var running = m.prop(true);
  var comment = m.prop();
  var hovering = m.prop();
  var hinting = m.prop();
  var played = m.prop(false);

  var ensureCevalRunnning = function() {
    if (!root.vm.showComputer()) root.toggleComputer();
    if (!root.ceval.enabled()) root.toggleCeval();
    if (root.vm.threatMode) root.toggleThreatMode();
  };

  var commentable = function(node, bonus) {
    if (root.gameOver(node)) return true;
    var ceval = node.ceval;
    return ceval && ((ceval.depth + (bonus || 0)) >= 15 || (ceval.depth >= 13 && ceval.millis > 3000));
  };
  var playable = function(node) {
    var ceval = node.ceval;
    return ceval && (ceval.depth >= 18 || (ceval.depth >= 16 && ceval.millis > 7000));
  };

  var altCastles = {
    e1a1: 'e1c1',
    e1h1: 'e1g1',
    e8a8: 'e8c8',
    e8h8: 'e8g8'
  };

  var makeComment = function(prev, node, path) {
    var verdict, best;
    var over = root.gameOver(node);

    if (over === 'checkmate') verdict = 'good';
    else {
      var nodeEval = node.ceval = over === 'draw' ? {
        cp: 0
      } : node.ceval;
      var shift = -winningChances.povDiff(root.bottomColor(), nodeEval, prev.ceval);

      best = prev.ceval.best;
      if (best === node.uci || best === altCastles[node.uci]) best = null;

      if (!best) verdict = 'good';
      else if (shift < 0.025) verdict = 'good';
      else if (shift < 0.06) verdict = 'inaccuracy';
      else if (shift < 0.14) verdict = 'mistake';
      else verdict = 'blunder';
    }

    return {
      prev: prev,
      node: node,
      path: path,
      verdict: verdict,
      best: best ? {
        uci: best,
        san: pv2san(root.data.game.variant.key, prev.fen, false, best)
      } : null
    };
  }

  var isMyTurn = function() {
    return root.turnColor() === root.bottomColor();
  };

  var checkCeval = function() {
    if (!running()) {
      comment(null);
      m.redraw();
      return;
    }
    ensureCevalRunnning();
    var node = root.vm.node;
    if (isMyTurn()) {
      var h = hinting();
      if (h) {
        h.uci = node.ceval.best;
        root.setAutoShapes();
      }
    } else {
      comment(null);
      if (node.san && commentable(node)) {
        var parentNode = root.tree.nodeAtPath(treePath.init(root.vm.path));
        if (commentable(parentNode, +1))
          comment(makeComment(parentNode, node, root.vm.path));
      }
      if (!played() && playable(node)) {
        root.playUci(node.ceval.best);
        played(true);
      }
    }
  };

  var resume = function() {
    running(true);
    checkCeval();
  };

  checkCeval();

  return {
    onCeval: checkCeval,
    onJump: function() {
      played(false);
      hinting(null);
      checkCeval();
      // because running(false) is called after the jump
      // setTimeout(checkCeval, 50)
    },
    isMyTurn: isMyTurn,
    comment: comment,
    running: running,
    hovering: hovering,
    hinting: hinting,
    resume: resume,
    reset: function() {
      comment(null);
      hinting(null);
    },
    preUserJump: function(from, to) {
      if (from !== to) {
        running(false);
        comment(null);
      }
    },
    postUserJump: function(from, to) {
      if (from !== to && isMyTurn()) resume();
    },
    onUserMove: function() {
      running(true);
    },
    playCommentBest: function() {
      var c = comment();
      if (!c) return;
      root.jump(treePath.init(c.path));
      root.playUci(c.best.uci);
    },
    commentShape: function(enable) {
      var c = comment();
      if (!enable || !c) hovering(null);
      else hovering({
        uci: c.best.uci
      });
      root.setAutoShapes();
    },
    hint: function() {
      var best = root.vm.node.ceval ? root.vm.node.ceval.best : null;
      var prev = hinting();
      if (!best || (prev && prev.mode === 'move')) hinting(null);
      else hinting({
        mode: prev ? 'move' : 'piece',
        uci: best
      });
      root.setAutoShapes();
    }
  };
};
<|endoftext|>


<commit_before><commit_msg>use ref by createRef<commit_after><|endoftext|>


<commit_before>var net = require('net')
var Socket = net.Socket
var async = require('async')

/**
 * Finds the first port with a status of 'open', implying the port is in use and
 * there is likely a service listening on it.
 */
/**
 * @param {Number} startPort - Port to begin status check on (inclusive).
 * @param {Number} [endPort=65535] - Last port to check status on (inclusive).
 * @param {String} [host='127.0.0.1'] - Host of where to scan.
 * @param {findPortCallback} callback - Function to call back with error or results.
 * @example
 * // scans through 3000 to 3002 (inclusive)
 * portscanner.findAPortInUse(3000, 3002, '127.0.0.1', console.log)
 * @example
 * // scans through 3000 to 65535 on '127.0.0.1'
 * portscanner.findAPortInUse(3000, console.log)
 */
/**
 * @param {Array} postList - Array of ports to check status on.
 * @param {String} [host='127.0.0.1'] - Host of where to scan.
 * @param {findPortCallback} callback - Function to call back with error or results.
 * @example
 * // scans 3000 and 3002 only, not 3001.
 * portscanner.findAPortInUse([3000, 3002], console.log)
 */
function findAPortInUse (params) {
  findAPortWithStatus('open', arguments)
}

/**
 * Finds the first port with a status of 'closed', implying the port is not in
 * use. Accepts identical parameters as {@link findAPortInUse}
 */
function findAPortNotInUse (params) {
  findAPortWithStatus('closed', arguments)
}

/**
 * Checks the status of an individual port.
 */
/**
 * @param {Number} port - Port to check status on.
 * @param {String} [host='127.0.0.1'] - Host of where to scan.
 * @param {checkPortCallback} callback - Function to call back with error or results.
 */
/**
 * @param {Number} port - Port to check status on.
 * @param {Object} [opts={}] - Options object.
 * @param {String} [opts.host='127.0.0.1'] - Host of where to scan.
 * @param {Number} [opts.timeout=400] - Connection timeout in ms.
 * @param {checkPortCallback} callback - Function to call back with error or results.
 */
function checkPortStatus (port, arg2, arg3) {
  var options = {}
  var callback

  if (typeof arg2 === 'string') {
    // Assume this param is the host option
    options = { host: arg2 }
  }

  /**
   * Callback for {@link checkPortStatus}
   * @callback checkPortCallback
   * @param {Error|null} error - Any error that occurred while port scanning, or null.
   * @param {String} status - Status: 'open' if the port is in use, 'closed' if the port is available.
   */
  callback = Array.prototype.slice.call(arguments).slice(-1)[0]

  var host = options.host || '127.0.0.1'
  var timeout = options.timeout || 400
  var connectionRefused = false

  var socket = new Socket()
  var status = null
  var error = null

  // Socket connection established, port is open
  socket.on('connect', function () {
    status = 'open'
    socket.destroy()
  })

  // If no response, assume port is not listening
  socket.setTimeout(timeout)
  socket.on('timeout', function () {
    status = 'closed'
    error = new Error('Timeout (' + timeout + 'ms) occurred waiting for ' + host + ':' + port + ' to be available')
    socket.destroy()
  })

  // Assuming the port is not open if an error. May need to refine based on
  // exception
  socket.on('error', function (exception) {
    if (exception.code !== 'ECONNREFUSED') {
      error = exception
    } else {
      connectionRefused = true
    }
    status = 'closed'
  })

  // Return after the socket has closed
  socket.on('close', function (exception) {
    if (exception && !connectionRefused) { error = error || exception } else { error = null }
    callback(error, status)
  })

  socket.connect(port, host)
}

/**
 * Internal helper function used by {@link findAPortInUse} and {@link findAPortNotInUse}
 * to find a port from a range or a list with a specific status.
 */
/**
 * @param {String} status - Status to check.
 * @param {...params} params - Params as passed exactly to {@link findAPortInUse} and {@link findAPortNotInUse}.
 */
function findAPortWithStatus (status, params) {
  var host, callback

  if (typeof params[0] === 'object') {
    var ports = params[0]
    host = typeof params[1] === 'string' ? params[1] : null
  } else if (typeof params[0] === 'number') {
    var startPort = params[0]
    var endPort = params[1]
    host = typeof params[2] === 'string' ? params[2] : null
  }

  /**
   * Callback for {@link findAPortWithStatus}, and by that extension, for {@link findAPortInUse} and {@link findAPortNotInUse}.
   * @callback findPortCallback
   * @param {Error|null} error - Any error that occurred while port scanning, or null.
   * @param {Number|Boolean} port - The first open port found. Note, this is the first port that returns status as 'open', not necessarily the first open port checked. If no open port is found, the value is false.
   */
  callback = Array.prototype.slice.call(params).slice(-1)[0]

  endPort = endPort || 65535

  var foundPort = false
  var numberOfPortsChecked = 0
  var port = ports ? ports[0] : startPort

  // Returns true if a port with matching status has been found or if checked
  // the entire range of ports
  var hasFoundPort = function () {
    return foundPort || numberOfPortsChecked === (ports ? ports.length : endPort - startPort + 1)
  }

  // Checks the status of the port
  var checkNextPort = function (callback) {
    checkPortStatus(port, host, function (error, statusOfPort) {
      numberOfPortsChecked++
      if (statusOfPort === status) {
        foundPort = true
        callback(error)
      } else {
        port = ports ? ports[numberOfPortsChecked] : port + 1
        callback(null)
      }
    })
  }

  // Check the status of each port until one with a matching status has been
  // found or the range of ports has been exhausted
  async.until(hasFoundPort, checkNextPort, function (error) {
    if (error) {
      callback(error, port)
    } else if (foundPort) {
      callback(null, port)
    } else {
      callback(null, false)
    }
  })
}

/**
 * @exports portscanner
 */

module.exports = {
  findAPortInUse: findAPortInUse,
  findAPortNotInUse: findAPortNotInUse,
  checkPortStatus: checkPortStatus
}
<commit_msg>Improve arguments parsing<commit_after>var net = require('net')
var Socket = net.Socket
var async = require('async')

/**
 * Finds the first port with a status of 'open', implying the port is in use and
 * there is likely a service listening on it.
 */
/**
 * @param {Number} startPort - Port to begin status check on (inclusive).
 * @param {Number} [endPort=65535] - Last port to check status on (inclusive).
 * @param {String} [host='127.0.0.1'] - Host of where to scan.
 * @param {findPortCallback} callback - Function to call back with error or results.
 * @example
 * // scans through 3000 to 3002 (inclusive)
 * portscanner.findAPortInUse(3000, 3002, '127.0.0.1', console.log)
 * @example
 * // scans through 3000 to 65535 on '127.0.0.1'
 * portscanner.findAPortInUse(3000, console.log)
 */
/**
 * @param {Array} postList - Array of ports to check status on.
 * @param {String} [host='127.0.0.1'] - Host of where to scan.
 * @param {findPortCallback} callback - Function to call back with error or results.
 * @example
 * // scans 3000 and 3002 only, not 3001.
 * portscanner.findAPortInUse([3000, 3002], console.log)
 */
function findAPortInUse () {
  var params = [].slice.call(arguments)
  params.unshift('open')
  return findAPortWithStatus.apply(null, params)
}

/**
 * Finds the first port with a status of 'closed', implying the port is not in
 * use. Accepts identical parameters as {@link findAPortInUse}
 */
function findAPortNotInUse () {
  var params = [].slice.call(arguments)
  params.unshift('closed')
  return findAPortWithStatus.apply(null, params)
}

/**
 * Checks the status of an individual port.
 */
/**
 * @param {Number} port - Port to check status on.
 * @param {String} [host='127.0.0.1'] - Host of where to scan.
 * @param {checkPortCallback} callback - Function to call back with error or results.
 */
/**
 * @param {Number} port - Port to check status on.
 * @param {Object} [opts={}] - Options object.
 * @param {String} [opts.host='127.0.0.1'] - Host of where to scan.
 * @param {Number} [opts.timeout=400] - Connection timeout in ms.
 * @param {checkPortCallback} callback - Function to call back with error or results.
 */
function checkPortStatus (port) {
  var args, host, opts, callback

  args = [].slice.call(arguments, 1)

  if (typeof args[0] === 'string') {
    host = args[0]
  } else if (typeof args[0] === 'object') {
    opts = args[0]
  } else if (typeof args[0] === 'function') {
    callback = args[0]
  }

  if (typeof args[1] === 'object') {
    opts = args[1]
  } else if (typeof args[1] === 'function') {
    callback = args[1]
  }

  if (typeof args[2] === 'function') {
    callback = args[2]
  }
  opts = opts || {}

  host = host || opts.host || '127.0.0.1'

  var timeout = opts.timeout || 400
  var connectionRefused = false

  var socket = new Socket()
  var status = null
  var error = null

  // Socket connection established, port is open
  socket.on('connect', function () {
    status = 'open'
    socket.destroy()
  })

  // If no response, assume port is not listening
  socket.setTimeout(timeout)
  socket.on('timeout', function () {
    status = 'closed'
    error = new Error('Timeout (' + timeout + 'ms) occurred waiting for ' + host + ':' + port + ' to be available')
    socket.destroy()
  })

  // Assuming the port is not open if an error. May need to refine based on
  // exception
  socket.on('error', function (exception) {
    if (exception.code !== 'ECONNREFUSED') {
      error = exception
    } else {
      connectionRefused = true
    }
    status = 'closed'
  })

  // Return after the socket has closed
  socket.on('close', function (exception) {
    if (exception && !connectionRefused) { error = error || exception } else { error = null }
    callback(error, status)
  })

  socket.connect(port, host)
}
/**
 * Callback for {@link checkPortStatus}
 * @callback checkPortCallback
 * @param {Error|null} error - Any error that occurred while port scanning, or null.
 * @param {String} status - Status: 'open' if the port is in use, 'closed' if the port is available.
 */

/**
 * Internal helper function used by {@link findAPortInUse} and {@link findAPortNotInUse}
 * to find a port from a range or a list with a specific status.
 */
/**
 * @param {String} status - Status to check.
 * @param {...params} params - Params as passed exactly to {@link findAPortInUse} and {@link findAPortNotInUse}.
 */
function findAPortWithStatus (status) {
  var params, startPort, endPort, portList, host, callback

  params = [].slice.call(arguments, 1)

  if (typeof params[0] === 'number') {
    startPort = params[0]
  } else if (params[0] instanceof Array) {
    portList = params[0]
  }

  if (typeof params[1] === 'number') {
    endPort = params[1]
  } else if (typeof params[1] === 'string') {
    host = params[1]
  } else if (typeof params[1] === 'function') {
    callback = params[1]
  }

  if (typeof params[2] === 'string') {
    host = params[2]
  } else if (typeof params[2] === 'function') {
    callback = params[2]
  }

  if (typeof params[3] === 'function') {
    callback = params[3]
  }

  endPort = endPort || 65535

  var foundPort = false
  var numberOfPortsChecked = 0
  var port = portList ? portList[0] : startPort

  // Returns true if a port with matching status has been found or if checked
  // the entire range of ports
  var hasFoundPort = function () {
    return foundPort || numberOfPortsChecked === (portList ? portList.length : endPort - startPort + 1)
  }

  // Checks the status of the port
  var checkNextPort = function (callback) {
    checkPortStatus(port, host, function (error, statusOfPort) {
      numberOfPortsChecked++
      if (statusOfPort === status) {
        foundPort = true
        callback(error)
      } else {
        port = portList ? portList[numberOfPortsChecked] : port + 1
        callback(null)
      }
    })
  }

  // Check the status of each port until one with a matching status has been
  // found or the range of ports has been exhausted
  async.until(hasFoundPort, checkNextPort, function (error) {
    if (error) {
      callback(error, port)
    } else if (foundPort) {
      callback(null, port)
    } else {
      callback(null, false)
    }
  })
}
/**
 * Callback for {@link findAPortWithStatus}, and by that extension, for {@link findAPortInUse} and {@link findAPortNotInUse}.
 * @callback findPortCallback
 * @param {Error|null} error - Any error that occurred while port scanning, or null.
 * @param {Number|Boolean} port - The first open port found. Note, this is the first port that returns status as 'open', not necessarily the first open port checked. If no open port is found, the value is false.
 */

/**
 * @exports portscanner
 */

module.exports = {
  findAPortInUse: findAPortInUse,
  findAPortNotInUse: findAPortNotInUse,
  checkPortStatus: checkPortStatus
}
<|endoftext|>


<commit_before>'use strict';

const _             = require('lodash');
const EventEmitter  = require('events');
const process       = require('process');
const childProcess  = require('child_process');

const moment        = require('moment');
const linuxBattery  = require('linux-battery');
const mpdCmd        = require('mpd').cmd;

const util          = require('./util');
const config        = require('./config');
const clients       = require('./clients');

// Allow more listeners
process.setMaxListeners(0);

// Abstract block
// Emits 'update' events
// Output should be stored in this._output
// Updates on SIGUSR1 if class name is in blocks to be updated
class Block extends EventEmitter {
  constructor() {
    super();
    this._output = ` ${config.get('strLoading')} `;

    // Update block on SIGUSR1
    process.on('SIGUSR1', () => {
      util.getUpdateBlocks((err, blocks) => {
        if (err) {
          this.emit('error', err);
          return;
        }

        if (blocks.indexOf(this.constructor.name) > -1)
          this.update();
      });
    });
  }

  // Should update block output state and emit an 'update' event
  // abstract update();

  query() {
    return this._output;
  }
}

// Static block
class StaticBlock extends Block {
  constructor(text) {
    super();
    this._output = text;
  }

  update() {
    this.emit('update');
  }
}

// Abstract block which updates at intervals
class IntervalBlock extends Block {
  constructor(interval, delay) {
    super();

    // Default for delay
    delay = delay || 0;

    // Wait until the delay
    setTimeout(() => {
      this.update();

      // Set an interval to update on the interval
      setInterval(this.update.bind(this), interval);
    }, delay);

    // Update once initially
    this.update();
  }
}

// Abstract block which updates via an event emitter
class EventBlock extends Block {
  constructor(emitter) {
    super();
    this.emitter = emitter;
    this._do_registration();
  }

  // Here is where all callback registration should be done
  // abstract _do_registration();

  // Registers a this.update to the emitter for each event
  _register(events) {
    for (let e of events)
      this.emitter.on(e, this.update.bind(this));

    // Update once initially - needs to be here in case of a
    // ready callback
    this.update();
  }
}

// Abstract block which updates via an i3 ipc connection
class I3Block extends EventBlock {
  constructor() {
    super(clients.i3);
  }
}

// Abstract block which updates via an acpi connection
class AcpiBlock extends EventBlock {
  constructor() {
    super(clients.acpi);
  }
}

// Abstract block which updates via an mpd connection
class MpdBlock extends EventBlock {
  constructor() {
    super(clients.mpd);
  }
}

// Updates time once a minute, on the minute
class DatetimeBlock extends IntervalBlock {
  constructor() {
    let m = moment();
    let delay =(60 * 1000) -
      (m.millisecond() + m.second() * 1000) +
      config.get('fudgeTimeout');
    super(60 * 1000, delay);
  }

  update() {
    this._output = ` ${
      moment().locale(config.get('dtLocale')).format(config.get('dtFmt'))
    } `;
    this.emit('update');
  }
}

// Updates once an hour
class YumUpdateBlock extends IntervalBlock {
  constructor() {
    super(config.get('yumUpdateFreq'));
  }

  update() {
    childProcess.exec('yum check-update | sed \'1,/^$/d\' | wc -l', (err, out) => {
      if (err) {
        this.emit('error', err);
        return;
      }

      let updates = Number.parseInt(out.trim());
      let output = ` ${updates} `;

      // Accent if updates
      if (updates)
        output = util.addBG(output, 'cAccent');

      output = util.addAction(output,
          `${config.get('termExec')} "sudo yum update"`);

      this._output = output;
      this.emit('update');
    });
  }
}

class WorkspaceBlock extends I3Block {
  _do_registration() {
    this._register(['workspace']);
  }

  update() {
    this.emitter.workspaces((err, data) => {
      if (err) {
        this.emit('error', err);
        return;
      }

      this._output = data.map(function(space) {
        let current = ` ${
          space.name.split(':').slice(1).join('') || space.name
        } `;

        current = util.addAction(current, `i3-msg workspace "${space.name}"`);

        if (space.focused)
          return util.addBG(current, 'cAccent');
        else if (space.urgent)
          return util.addBG(current, 'cUrgent');
        else
          return current;
      }).join('');

      this.emit('update');
    });
  }
}

class TitleBlock extends I3Block {
  _do_registration() {
    this._register(['window', 'workspace::focus']);
  }

  update() {
    this.emitter.tree((err, data) => {
      if (err) {
        this.emit('error', err);
        return;
      }

      this._output = ` ${_.trunc(util.findFocused(data).name, {
        length:     config.get('maxlen'),
        omission:   config.get('trunc')
      })} `;

      this.emit('update');
    });
  }
}

class BatteryBlock extends AcpiBlock {
  constructor() {
    super();

    // Update status periodically
    setInterval(this.update.bind(this), config.get('batInterval'));
  }

  _do_registration() {
    this._register(['ac_adapter']);
  }

  update() {
    // Set a fudge timeout
    if (this.fudge)
      clearTimeout(this.fudge);
    this.fudge = setTimeout(() => {
      linuxBattery().then((batteries) => {
        let bat = batteries[0]; // Grab the first battery
        let stats = [];

        // Time until...
        let time = bat.timeToEmpty || bat.timeToFull;
        if (time)
          stats.push(time.replace(/\s*([a-z])[a-z]*/, '$1'));

        // Charging status
        let state;
        switch (bat.state) {
          case 'fully-charged':
            state = '✓';
            break;
          case 'charging':
            state = '↑';
            break;
          case 'discharging':
            state = '↓';
            break;
          default:
            // Do nothing
        }
        if (state)
          stats.push(state);

        // Percent
        let percent = Number.parseInt(bat.percentage.replace(/[^\d]/, ''));
        stats.push(percent);

        let output = ` ${stats.join(' ')} `;

        // Critical
        if (percent <= config.get('batCritical') && bat.state !== 'charging')
          output = util.addBG(output, 'cUrgent');

        this._output = output;
        this.emit('update');
      });
    }, config.get('fudgeTimeout'));
  }
}

class VolumeBlock extends AcpiBlock {
  _do_registration() {
    this._register([
        'button/volumeup',
        'button/volumedown',
        'button/mute',
        'jack/headphone',
    ]);
  }

  update() {
    // Set a fudge timeout
    if (this.fudge)
      clearTimeout(this.fudge);
    this.fudge = setTimeout(() => {
      childProcess.exec('amixer get Master', (err, out) => {
        if (err) {
          this.emit('error', err);
          return;
        }

        let matches = out.match(/\[(\d{1,3})%\] \[(on|off)\]\n/);
        let output = ` ${matches[1]} `;
        if (matches[2] === 'off')
          output = util.addBG(output, 'cUrgent');

        // Commands
        // Toggle mute
        output = util.addAction(output, 'amixer set Master toggle', 1,
            [this.constructor.name]);
        // Volume up
        output = util.addAction(output,
            `amixer set Master ${config.get('volPercent')}%+`, 4,
            [this.constructor.name]);
        // Volume down
        output = util.addAction(output,
            `amixer set Master ${config.get('volPercent')}%-`, 5,
            [this.constructor.name]);

        this._output = output;
        this.emit('update');
      });
    }, config.get('fudgeTimeout'));
  }
}

class SsidBlock extends EventBlock {
  constructor() {
    super(clients.iwevent);
  }

  _do_registration() {
    this._register(['New Access Point']);
  }

  // TODO: detect if airplane mode is on or not
  update() {
    // Set a fudge timout
    if (this.fudge)
      clearTimeout(this.fudge);
    this.fudge = setTimeout(() => {
      childProcess.exec('iwgetid', (err, out) => {
        // err means no ssid
        let output = ` ${
          err ? 'disconnected' : out.match(/ESSID:"(.*)"\n/)[1]
        } `;

        // Disconnected -> critical
        if (err)
          output = util.addBG(output, 'cUrgent');

        output = util.addAction(output, `${config.get('termExec')} "nmtui"`);

        this._output = output;
        this.emit('update');
      });
    }, config.get('netFudgeTimeout'));
  }
}

class CurrentSongBlock extends MpdBlock {
  _do_registration() {
    this.emitter.on('ready', () => {
      this._register(['system-player', 'system-playlist']);
    });
  }

  update() {
    this.emitter.sendCommand(mpdCmd('currentsong', []), (err, data) => {
      if (err) {
        this.emit('error', err);
        return;
      }

      if (data) {
        let stats = [];

        let matches  = [
          data.match(/\nTitle: (.*)\n/),
          data.match(/\nArtist: (.*)\n/)
        ];

        matches.forEach((match) => {
          if (match)
            stats.push(match[1]);
        });

        this._output = ` ${_.trunc(stats.join(' - '), {
          length:     config.get('maxlen'),
          omission:   config.get('trunc')
        })} `;
      } else {
        // Nothing playing
        this._output = ' no tunes ';
      }

      this.emit('update');
    });
  }
}

class PlayStatusBlock extends MpdBlock {
  _do_registration() {
    this.emitter.on('ready', () => {
      this._register(['system-player', 'system-playlist', 'system-options']);
    });
  }

  update() {
    if (this.fudge)
      clearTimeout(this.fudge);
    this.fudge = setTimeout(() => {
      this.emitter.sendCommand(mpdCmd('status', []), (err, data) => {
        if (err) {
          this.emit('error', err);
          return;
        }

        if (data) {
          let stats = '';

          // Binary flags
          let binaries  = [
            {
              label: 'r',
              action: 'mpc repeat',
              match: data.match(/\nrepeat: ([01])\n/)
            },
            {
              label: 'z',
              action: 'mpc random',
              match: data.match(/\nrandom: ([01])\n/)
            }
          ];

          binaries.forEach((status) => {
            stats += util.addAction(
                (status.match && status.match[1] !== '0') ? status.label : '-',
                status.action);
          });

          // Xfade handled separately
          let xfadeMatch = data.match(/\nxfade: (\d+)\n/);
          this.lastXfade = xfadeMatch ? Number.parseInt(xfadeMatch[1]) : 0;
          stats += util.addAction(xfadeMatch ? 'x' : '-',
              `mpc crossfade ${this.lastXfade ? 0 : config.get('mpdXfade')}`);

          // Playing status
          let playing = '♪';
          let playingMatch = data.match(/\nstate: (.*)\n/);
          if (playingMatch) {
            switch (playingMatch[1]) {
              case 'play':
                playing = '▶';
                break;
              case 'pause':
                playing = '‖';
                break;
              case 'stop':
                playing = '■';
                break;
              default:
                // Do nothing
            }
          }

          playing = util.addAction(playing, 'mpc toggle');

          this._output = ` ${stats} ${playing} `;
        } else {
          // Nothing playing
          this._output = ' ♪ ';
        }

        this.emit('update');
      });
    }, config.get('mpdFudgeTimeout'));
  }
}

module.exports = {
  Block:              Block,
  StaticBlock:        StaticBlock,
  IntervalBlock:      IntervalBlock,
  EventBlock:         EventBlock,
  I3Block:            I3Block,
  AcpiBlock:          AcpiBlock,
  DatetimeBlock:      DatetimeBlock,
  YumUpdateBlock:     YumUpdateBlock,
  WorkspaceBlock:     WorkspaceBlock,
  TitleBlock:         TitleBlock,
  BatteryBlock:       BatteryBlock,
  VolumeBlock:        VolumeBlock,
  SsidBlock:          SsidBlock,
  CurrentSongBlock:   CurrentSongBlock,
  PlayStatusBlock:    PlayStatusBlock,
};

<commit_msg>Revert "surround term commands in quotes"<commit_after>'use strict';

const _             = require('lodash');
const EventEmitter  = require('events');
const process       = require('process');
const childProcess  = require('child_process');

const moment        = require('moment');
const linuxBattery  = require('linux-battery');
const mpdCmd        = require('mpd').cmd;

const util          = require('./util');
const config        = require('./config');
const clients       = require('./clients');

// Allow more listeners
process.setMaxListeners(0);

// Abstract block
// Emits 'update' events
// Output should be stored in this._output
// Updates on SIGUSR1 if class name is in blocks to be updated
class Block extends EventEmitter {
  constructor() {
    super();
    this._output = ` ${config.get('strLoading')} `;

    // Update block on SIGUSR1
    process.on('SIGUSR1', () => {
      util.getUpdateBlocks((err, blocks) => {
        if (err) {
          this.emit('error', err);
          return;
        }

        if (blocks.indexOf(this.constructor.name) > -1)
          this.update();
      });
    });
  }

  // Should update block output state and emit an 'update' event
  // abstract update();

  query() {
    return this._output;
  }
}

// Static block
class StaticBlock extends Block {
  constructor(text) {
    super();
    this._output = text;
  }

  update() {
    this.emit('update');
  }
}

// Abstract block which updates at intervals
class IntervalBlock extends Block {
  constructor(interval, delay) {
    super();

    // Default for delay
    delay = delay || 0;

    // Wait until the delay
    setTimeout(() => {
      this.update();

      // Set an interval to update on the interval
      setInterval(this.update.bind(this), interval);
    }, delay);

    // Update once initially
    this.update();
  }
}

// Abstract block which updates via an event emitter
class EventBlock extends Block {
  constructor(emitter) {
    super();
    this.emitter = emitter;
    this._do_registration();
  }

  // Here is where all callback registration should be done
  // abstract _do_registration();

  // Registers a this.update to the emitter for each event
  _register(events) {
    for (let e of events)
      this.emitter.on(e, this.update.bind(this));

    // Update once initially - needs to be here in case of a
    // ready callback
    this.update();
  }
}

// Abstract block which updates via an i3 ipc connection
class I3Block extends EventBlock {
  constructor() {
    super(clients.i3);
  }
}

// Abstract block which updates via an acpi connection
class AcpiBlock extends EventBlock {
  constructor() {
    super(clients.acpi);
  }
}

// Abstract block which updates via an mpd connection
class MpdBlock extends EventBlock {
  constructor() {
    super(clients.mpd);
  }
}

// Updates time once a minute, on the minute
class DatetimeBlock extends IntervalBlock {
  constructor() {
    let m = moment();
    let delay =(60 * 1000) -
      (m.millisecond() + m.second() * 1000) +
      config.get('fudgeTimeout');
    super(60 * 1000, delay);
  }

  update() {
    this._output = ` ${
      moment().locale(config.get('dtLocale')).format(config.get('dtFmt'))
    } `;
    this.emit('update');
  }
}

// Updates once an hour
class YumUpdateBlock extends IntervalBlock {
  constructor() {
    super(config.get('yumUpdateFreq'));
  }

  update() {
    childProcess.exec('yum check-update | sed \'1,/^$/d\' | wc -l', (err, out) => {
      if (err) {
        this.emit('error', err);
        return;
      }

      let updates = Number.parseInt(out.trim());
      let output = ` ${updates} `;

      // Accent if updates
      if (updates)
        output = util.addBG(output, 'cAccent');

      output = util.addAction(output,
          `${config.get('termExec')} sudo yum update`);

      this._output = output;
      this.emit('update');
    });
  }
}

class WorkspaceBlock extends I3Block {
  _do_registration() {
    this._register(['workspace']);
  }

  update() {
    this.emitter.workspaces((err, data) => {
      if (err) {
        this.emit('error', err);
        return;
      }

      this._output = data.map(function(space) {
        let current = ` ${
          space.name.split(':').slice(1).join('') || space.name
        } `;

        current = util.addAction(current, `i3-msg workspace "${space.name}"`);

        if (space.focused)
          return util.addBG(current, 'cAccent');
        else if (space.urgent)
          return util.addBG(current, 'cUrgent');
        else
          return current;
      }).join('');

      this.emit('update');
    });
  }
}

class TitleBlock extends I3Block {
  _do_registration() {
    this._register(['window', 'workspace::focus']);
  }

  update() {
    this.emitter.tree((err, data) => {
      if (err) {
        this.emit('error', err);
        return;
      }

      this._output = ` ${_.trunc(util.findFocused(data).name, {
        length:     config.get('maxlen'),
        omission:   config.get('trunc')
      })} `;

      this.emit('update');
    });
  }
}

class BatteryBlock extends AcpiBlock {
  constructor() {
    super();

    // Update status periodically
    setInterval(this.update.bind(this), config.get('batInterval'));
  }

  _do_registration() {
    this._register(['ac_adapter']);
  }

  update() {
    // Set a fudge timeout
    if (this.fudge)
      clearTimeout(this.fudge);
    this.fudge = setTimeout(() => {
      linuxBattery().then((batteries) => {
        let bat = batteries[0]; // Grab the first battery
        let stats = [];

        // Time until...
        let time = bat.timeToEmpty || bat.timeToFull;
        if (time)
          stats.push(time.replace(/\s*([a-z])[a-z]*/, '$1'));

        // Charging status
        let state;
        switch (bat.state) {
          case 'fully-charged':
            state = '✓';
            break;
          case 'charging':
            state = '↑';
            break;
          case 'discharging':
            state = '↓';
            break;
          default:
            // Do nothing
        }
        if (state)
          stats.push(state);

        // Percent
        let percent = Number.parseInt(bat.percentage.replace(/[^\d]/, ''));
        stats.push(percent);

        let output = ` ${stats.join(' ')} `;

        // Critical
        if (percent <= config.get('batCritical') && bat.state !== 'charging')
          output = util.addBG(output, 'cUrgent');

        this._output = output;
        this.emit('update');
      });
    }, config.get('fudgeTimeout'));
  }
}

class VolumeBlock extends AcpiBlock {
  _do_registration() {
    this._register([
        'button/volumeup',
        'button/volumedown',
        'button/mute',
        'jack/headphone',
    ]);
  }

  update() {
    // Set a fudge timeout
    if (this.fudge)
      clearTimeout(this.fudge);
    this.fudge = setTimeout(() => {
      childProcess.exec('amixer get Master', (err, out) => {
        if (err) {
          this.emit('error', err);
          return;
        }

        let matches = out.match(/\[(\d{1,3})%\] \[(on|off)\]\n/);
        let output = ` ${matches[1]} `;
        if (matches[2] === 'off')
          output = util.addBG(output, 'cUrgent');

        // Commands
        // Toggle mute
        output = util.addAction(output, 'amixer set Master toggle', 1,
            [this.constructor.name]);
        // Volume up
        output = util.addAction(output,
            `amixer set Master ${config.get('volPercent')}%+`, 4,
            [this.constructor.name]);
        // Volume down
        output = util.addAction(output,
            `amixer set Master ${config.get('volPercent')}%-`, 5,
            [this.constructor.name]);

        this._output = output;
        this.emit('update');
      });
    }, config.get('fudgeTimeout'));
  }
}

class SsidBlock extends EventBlock {
  constructor() {
    super(clients.iwevent);
  }

  _do_registration() {
    this._register(['New Access Point']);
  }

  // TODO: detect if airplane mode is on or not
  update() {
    // Set a fudge timout
    if (this.fudge)
      clearTimeout(this.fudge);
    this.fudge = setTimeout(() => {
      childProcess.exec('iwgetid', (err, out) => {
        // err means no ssid
        let output = ` ${
          err ? 'disconnected' : out.match(/ESSID:"(.*)"\n/)[1]
        } `;

        // Disconnected -> critical
        if (err)
          output = util.addBG(output, 'cUrgent');

        output = util.addAction(output, `${config.get('termExec')} nmtui`);

        this._output = output;
        this.emit('update');
      });
    }, config.get('netFudgeTimeout'));
  }
}

class CurrentSongBlock extends MpdBlock {
  _do_registration() {
    this.emitter.on('ready', () => {
      this._register(['system-player', 'system-playlist']);
    });
  }

  update() {
    this.emitter.sendCommand(mpdCmd('currentsong', []), (err, data) => {
      if (err) {
        this.emit('error', err);
        return;
      }

      if (data) {
        let stats = [];

        let matches  = [
          data.match(/\nTitle: (.*)\n/),
          data.match(/\nArtist: (.*)\n/)
        ];

        matches.forEach((match) => {
          if (match)
            stats.push(match[1]);
        });

        this._output = ` ${_.trunc(stats.join(' - '), {
          length:     config.get('maxlen'),
          omission:   config.get('trunc')
        })} `;
      } else {
        // Nothing playing
        this._output = ' no tunes ';
      }

      this.emit('update');
    });
  }
}

class PlayStatusBlock extends MpdBlock {
  _do_registration() {
    this.emitter.on('ready', () => {
      this._register(['system-player', 'system-playlist', 'system-options']);
    });
  }

  update() {
    if (this.fudge)
      clearTimeout(this.fudge);
    this.fudge = setTimeout(() => {
      this.emitter.sendCommand(mpdCmd('status', []), (err, data) => {
        if (err) {
          this.emit('error', err);
          return;
        }

        if (data) {
          let stats = '';

          // Binary flags
          let binaries  = [
            {
              label: 'r',
              action: 'mpc repeat',
              match: data.match(/\nrepeat: ([01])\n/)
            },
            {
              label: 'z',
              action: 'mpc random',
              match: data.match(/\nrandom: ([01])\n/)
            }
          ];

          binaries.forEach((status) => {
            stats += util.addAction(
                (status.match && status.match[1] !== '0') ? status.label : '-',
                status.action);
          });

          // Xfade handled separately
          let xfadeMatch = data.match(/\nxfade: (\d+)\n/);
          this.lastXfade = xfadeMatch ? Number.parseInt(xfadeMatch[1]) : 0;
          stats += util.addAction(xfadeMatch ? 'x' : '-',
              `mpc crossfade ${this.lastXfade ? 0 : config.get('mpdXfade')}`);

          // Playing status
          let playing = '♪';
          let playingMatch = data.match(/\nstate: (.*)\n/);
          if (playingMatch) {
            switch (playingMatch[1]) {
              case 'play':
                playing = '▶';
                break;
              case 'pause':
                playing = '‖';
                break;
              case 'stop':
                playing = '■';
                break;
              default:
                // Do nothing
            }
          }

          playing = util.addAction(playing, 'mpc toggle');

          this._output = ` ${stats} ${playing} `;
        } else {
          // Nothing playing
          this._output = ' ♪ ';
        }

        this.emit('update');
      });
    }, config.get('mpdFudgeTimeout'));
  }
}

module.exports = {
  Block:              Block,
  StaticBlock:        StaticBlock,
  IntervalBlock:      IntervalBlock,
  EventBlock:         EventBlock,
  I3Block:            I3Block,
  AcpiBlock:          AcpiBlock,
  DatetimeBlock:      DatetimeBlock,
  YumUpdateBlock:     YumUpdateBlock,
  WorkspaceBlock:     WorkspaceBlock,
  TitleBlock:         TitleBlock,
  BatteryBlock:       BatteryBlock,
  VolumeBlock:        VolumeBlock,
  SsidBlock:          SsidBlock,
  CurrentSongBlock:   CurrentSongBlock,
  PlayStatusBlock:    PlayStatusBlock,
};

<|endoftext|>


<commit_before>/**
  * @file the main file the makes everything work
  * @author Capuccino
  * @author Ovyerus
  * @copyright Copyright (c) 2017 Capuccino, Ovyerus and the repository contributors.
  * @license MIT
  */

// Imports
const Clara = require(`${__dirname}/lib/Clara`);
const fs = require('fs');
const config = require(`${__dirname}/config.json`);

// Globals
global.mainDir = __dirname;
global.utils = require(`${__dirname}/lib/modules/utils`);
global.logger = require(`${__dirname}/lib/modules/Logger`);
global.Promise = require('bluebird');
global.got = require('got');

//bot stuff
const bot = new Clara(config, {
    seedVoiceConnections: true,
    maxShards: config.maxShards || 1,
    latencyThreshold: 420000000,
    defaultImageFormat: 'webp',
    defaultImageSize: 512,
    latencyThreshold: 42000000,
    disableEvents: {
        TYPING_START: true
    }
});

bot.commandsDir = `${__dirname}/cmd`;
bot.unloadedPath = `${__dirname}/data/unloadedCommands.json`;

//Promise configuration
Promise.config({
    warnings: {wForgottenReturn: config.promiseWarnings || false},
    longStackTraces: config.promiseWarnings || false
});

if (!fs.existsSync(`${__dirname}/cache`)) fs.mkdirSync(`${__dirname}/cache/`);

require(`${__dirname}/lib/events`)(bot);
bot.connect();

exports.bot = bot;<commit_msg>[RELEASE-PATCH] Fix duplicate key issue<commit_after>/**
  * @file the main file the makes everything work
  * @author Capuccino
  * @author Ovyerus
  * @copyright Copyright (c) 2017 Capuccino, Ovyerus and the repository contributors.
  * @license MIT
  */

// Imports
const Clara = require(`${__dirname}/lib/Clara`);
const fs = require('fs');
const config = require(`${__dirname}/config.json`);

// Globals
global.mainDir = __dirname;
global.utils = require(`${__dirname}/lib/modules/utils`);
global.logger = require(`${__dirname}/lib/modules/Logger`);
global.Promise = require('bluebird');
global.got = require('got');

//bot stuff
const bot = new Clara(config, {
    seedVoiceConnections: true,
    maxShards: config.maxShards || 1,
    latencyThreshold: 420000000,
    defaultImageFormat: 'webp',
    defaultImageSize: 512,
    disableEvents: {
        TYPING_START: true
    }
});

bot.commandsDir = `${__dirname}/cmd`;
bot.unloadedPath = `${__dirname}/data/unloadedCommands.json`;

//Promise configuration
Promise.config({
    warnings: {wForgottenReturn: config.promiseWarnings || false},
    longStackTraces: config.promiseWarnings || false
});

if (!fs.existsSync(`${__dirname}/cache`)) fs.mkdirSync(`${__dirname}/cache/`);

require(`${__dirname}/lib/events`)(bot);
bot.connect();

exports.bot = bot;<|endoftext|>


<commit_before>import React from 'react';
import { Pagination, Table, FormGroup, FormControl, ControlLabel} from 'react-bootstrap';

import UIStore from './stores/UIStore';
import UIActions from './actions/UIActions';
import ElementActions from './actions/ElementActions';

import ElementStore from './stores/ElementStore';
import ElementAllCheckbox from './ElementAllCheckbox';
import ElementsTableEntries from './ElementsTableEntries';
import ElementsTableSampleEntries from './ElementsTableSampleEntries'
import ElementsSvgCheckbox from './ElementsSvgCheckbox';
import deepEqual from 'deep-equal';

export default class ElementsTable extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      elements: [],
      currentElement: null,
      ui: {}
    }
    this.onChange = this.onChange.bind(this)
    this.onChangeUI = this.onChangeUI.bind(this)
  }

  componentDidMount() {
    UIStore.getState();
    ElementStore.listen(this.onChange);
    UIStore.listen(this.onChangeUI);
    this.initializePagination();
    this.initState();
  }

  componentWillUnmount() {
    ElementStore.unlisten(this.onChange);
    UIStore.unlisten(this.onChangeUI);
  }

  initializePagination() {
    const {page, pages, perPage, totalElements} = this.state;
    this.setState({
      page, pages, perPage, totalElements
    });
  }

  initState(){
    this.onChange(ElementStore.getState());
  }

  onChangeUI(state) {
    let {checkedIds, uncheckedIds, checkedAll} = state[this.props.type];

    // check if element details of any type are open at the moment
    let currentId = state.sample.currentId || state.reaction.currentId ||
                    state.wellplate.currentId;

    if (checkedIds || uncheckedIds || checkedAll || currentId ||
        state.showPreviews) {
      this.setState({
        ui: {
          checkedIds: checkedIds,
          uncheckedIds: uncheckedIds,
          checkedAll: checkedAll,
          currentId: currentId,
          showPreviews: state.showPreviews,
          number_of_results: state.number_of_results
        }
      });
    }

  }

  onChange(state) {
    let type = this.props.type + 's';
    let elementsState = state.elements[type];

    const {elements, page, pages, perPage, totalElements} = elementsState;

    let currentElement;
    if(!state.currentElement || state.currentElement.type == this.props.type) {
      currentElement = state.currentElement
    }

    let elementsDidChange = elements && ! deepEqual(elements, this.state.elements);
    let currentElementDidChange = !deepEqual(currentElement, this.state.currentElement);

    if (elementsDidChange) {
      this.setState({
        elements, page, pages, perPage, totalElements, currentElement
      }),
      () => this.initializePagination()
    }
    else if (currentElementDidChange) {
      this.setState({
        page, pages, perPage, totalElements, currentElement
      }),
      () => this.initializePagination()
    }
  }

  handlePaginationSelect(event, selectedEvent) {
    const {pages} = this.state;
    const {type} = this.props;
    if(selectedEvent.eventKey > 0 && selectedEvent.eventKey <= pages) {
      this.setState({
        page: selectedEvent.eventKey
      }, () => UIActions.setPagination({type, page: this.state.page}));
    }
  }

  pagination() {
    const {page, pages} = this.state;
    if(pages > 1) {
      return <Pagination
        prev
        next
        first
        last
        maxButtons={3}
        activePage={page}
        items={pages}
        bsSize="small"
        onSelect={(event, selectedEvent) => this.handlePaginationSelect(event, selectedEvent)}/>
    }
  }

  previewCheckbox() {
    const {ui} = this.state;
    const {type} = this.props;
    if(type == 'reaction' ) {
      return (

          <ElementsSvgCheckbox checked={ui.showPreviews}/>

      )
    }
  }

  handleNumberOfResultsChange(event) {
    const value = event.target.value;
    const {type} = this.props;
    UIActions.changeNumberOfResultsShown(value);
    ElementActions.refreshElements(type)
  }

  numberOfResultsInput() {
    let {ui} = this.state
    return (
      <FormGroup >
        <ControlLabel>Show </ControlLabel>
        <FormControl
          className="number-shown-select"
          onChange={event => this.handleNumberOfResultsChange(event)}
          type="text"
          value={ui.number_of_results ? ui.number_of_results : 0} />
      </FormGroup>

    );
  }

  renderEntries() {
    const {elements, ui, currentElement} = this.state
    const {overview, showReport, type} = this.props
    if(type == 'sample') {
      return (

                <ElementAllCheckbox type={this.props.type}
                  checked={ui.checkedAll}
                  showReport={showReport}/>

                All {type}s

          <ElementsTableSampleEntries
            elements={elements}
            currentElement={currentElement}
            showDragColumn={!overview}
            ui={ui}
          />

      )
    } else {
      return (

              <ElementAllCheckbox type={this.props.type}
                checked={ui.checkedAll}
                showReport={showReport}/>

              All {type}s

          <ElementsTableEntries
            elements={elements}
            currentElement={currentElement}
            showDragColumn={!overview}
            ui={ui}
          />

      )
    }
  }

  render() {
    return (

        {this.renderEntries()}
        {this.pagination()}

          {this.numberOfResultsInput()}
          {this.previewCheckbox()}

    );
  }
}
<commit_msg>Fix pagination bug<commit_after>import React from 'react';
import { Pagination, Table, FormGroup, FormControl, ControlLabel} from 'react-bootstrap';

import UIStore from './stores/UIStore';
import UIActions from './actions/UIActions';
import ElementActions from './actions/ElementActions';

import ElementStore from './stores/ElementStore';
import ElementAllCheckbox from './ElementAllCheckbox';
import ElementsTableEntries from './ElementsTableEntries';
import ElementsTableSampleEntries from './ElementsTableSampleEntries'
import ElementsSvgCheckbox from './ElementsSvgCheckbox';
import deepEqual from 'deep-equal';

export default class ElementsTable extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      elements: [],
      currentElement: null,
      ui: {}
    }
    this.onChange = this.onChange.bind(this)
    this.onChangeUI = this.onChangeUI.bind(this)
  }

  componentDidMount() {
    UIStore.getState();
    ElementStore.listen(this.onChange);
    UIStore.listen(this.onChangeUI);
    this.initializePagination();
    this.initState();
  }

  componentWillUnmount() {
    ElementStore.unlisten(this.onChange);
    UIStore.unlisten(this.onChangeUI);
  }

  initializePagination() {
    const {page, pages, perPage, totalElements} = this.state;
    this.setState({
      page, pages, perPage, totalElements
    });
  }

  initState(){
    this.onChange(ElementStore.getState());
  }

  onChangeUI(state) {
    let {checkedIds, uncheckedIds, checkedAll} = state[this.props.type];

    // check if element details of any type are open at the moment
    let currentId = state.sample.currentId || state.reaction.currentId ||
                    state.wellplate.currentId;

    if (checkedIds || uncheckedIds || checkedAll || currentId ||
        state.showPreviews) {
      this.setState({
        ui: {
          checkedIds: checkedIds,
          uncheckedIds: uncheckedIds,
          checkedAll: checkedAll,
          currentId: currentId,
          showPreviews: state.showPreviews,
          number_of_results: state.number_of_results
        }
      });
    }

  }

  onChange(state) {
    let type = this.props.type + 's';
    let elementsState = state.elements[type];

    const {elements, page, pages, perPage, totalElements} = elementsState;

    let currentElement;
    if(!state.currentElement || state.currentElement.type == this.props.type) {
      currentElement = state.currentElement
    }

    let elementsDidChange = elements && ! deepEqual(elements, this.state.elements);
    let currentElementDidChange = !deepEqual(currentElement, this.state.currentElement);

    if (elementsDidChange) {
      this.setState({
        elements, page, pages, perPage, totalElements, currentElement
      }),
      () => this.initializePagination()
    }
    else if (currentElementDidChange) {
      this.setState({
        page, pages, perPage, totalElements, currentElement
      }),
      () => this.initializePagination()
    }
  }

  handlePaginationSelect(eventKey) {
    const {pages} = this.state;
    const {type} = this.props;

    if(eventKey > 0 && eventKey <= pages) {
      this.setState({
        page: eventKey
      }, () => UIActions.setPagination({type, page: this.state.page}));
    }
  }

  pagination() {
    const {page, pages} = this.state;
    if(pages > 1) {
      return <Pagination
        prev
        next
        first
        last
        maxButtons={3}
        activePage={page}
        items={pages}
        bsSize="small"
        onSelect={(eventKey) => this.handlePaginationSelect(eventKey)}/>
    }
  }

  previewCheckbox() {
    const {ui} = this.state;
    const {type} = this.props;
    if(type == 'reaction' ) {
      return (

          <ElementsSvgCheckbox checked={ui.showPreviews}/>

      )
    }
  }

  handleNumberOfResultsChange(event) {
    const value = event.target.value;
    const {type} = this.props;
    UIActions.changeNumberOfResultsShown(value);
    ElementActions.refreshElements(type)
  }

  numberOfResultsInput() {
    let {ui} = this.state
    return (
      <FormGroup >
        <ControlLabel>Show </ControlLabel>
        <FormControl
          className="number-shown-select"
          onChange={event => this.handleNumberOfResultsChange(event)}
          type="text"
          value={ui.number_of_results ? ui.number_of_results : 0} />
      </FormGroup>

    );
  }

  renderEntries() {
    const {elements, ui, currentElement} = this.state
    const {overview, showReport, type} = this.props
    if(type == 'sample') {
      return (

                <ElementAllCheckbox type={this.props.type}
                  checked={ui.checkedAll}
                  showReport={showReport}/>

                All {type}s

          <ElementsTableSampleEntries
            elements={elements}
            currentElement={currentElement}
            showDragColumn={!overview}
            ui={ui}
          />

      )
    } else {
      return (

              <ElementAllCheckbox type={this.props.type}
                checked={ui.checkedAll}
                showReport={showReport}/>

              All {type}s

          <ElementsTableEntries
            elements={elements}
            currentElement={currentElement}
            showDragColumn={!overview}
            ui={ui}
          />

      )
    }
  }

  render() {
    return (

        {this.renderEntries()}
        {this.pagination()}

          {this.numberOfResultsInput()}
          {this.previewCheckbox()}

    );
  }
}
<|endoftext|>


<commit_before>(function () {

    new SliderBarr({
        el    : $('#slider'),
        value : 15,
        step  : 1
    });

    new SliderBarr({
        el    : $('#sliderTwo'),
        value : 75,
        step  : 10
    });

    new SliderBarr({
        el     : $('#sliderThree'),
        value  : 50,
        step   : 1,
        labels : true
    });

    new SliderBarr({
        el     : $('#sliderFour'),
        value  : 50,
        step   : 0.1,
        labels : true
    });

}).call(this);<commit_msg>Added examples using jquery selectors or just a string indicating slider ID<commit_after>(function () {

    new SliderBarr({
        el    : 'slider',
        value : 15,
        step  : 1
    });

    new SliderBarr({
        el    : $('#sliderTwo'),
        value : 75,
        step  : 10
    });

    new SliderBarr({
        el     : $('#sliderThree'),
        value  : 50,
        step   : 1,
        labels : true
    });

    new SliderBarr({
        el     : 'sliderFour',
        value  : 50,
        step   : 0.1,
        labels : true
    });

}).call(this);<|endoftext|>


<commit_before>'use strict'
const mongoose = require('mongoose')

var tweetSchema = new mongoose.Schema({
  embed_id: String
}, {_id: false})

var articleSchema = new mongoose.Schema({
  title: String,
  description: String,
  source: String,
  link: String,
  timestamp: Number,
  media: String
}, {_id: false})

var trendSchema = new mongoose.Schema({
  name: String,
  sentiment_score: Number,
  sentiment_description: String,
  locations: [String],
  tweet_volume: Number,
  tweets: [tweetSchema],
  articles: [articleSchema]
})

var Trend = mongoose.model('Trend', trendSchema)

module.exports = Trend
<commit_msg>Add tweets_analyzed property to trend model<commit_after>'use strict'
const mongoose = require('mongoose')

var tweetSchema = new mongoose.Schema({
  embed_id: String
}, {_id: false})

var articleSchema = new mongoose.Schema({
  title: String,
  description: String,
  source: String,
  link: String,
  timestamp: Number,
  media: String
}, {_id: false})

var trendSchema = new mongoose.Schema({
  name: String,
  tweets_analyzed: Number,
  sentiment_score: Number,
  sentiment_description: String,
  locations: [String],
  tweet_volume: Number,
  tweets: [tweetSchema],
  articles: [articleSchema]
})

var Trend = mongoose.model('Trend', trendSchema)

module.exports = Trend
<|endoftext|>


<commit_before>/** @babel */

import Insertion from '../lib/insertion';
import { Range } from 'atom';

const range = new Range(0, 0);

describe('Insertion', () => {

  it('returns what it was given when it has no substitution', () => {
    let insertion = new Insertion({
      range,
      substitution: undefined
    });
    let transformed = insertion.transform('foo!')

    expect(transformed).toEqual('foo!');
  });

  it('transforms what it was given when it has a regex transformation', () => {
    let insertion = new Insertion({
      range,
      substitution: {
        find: /foo/g,
        replace: ['bar']
      }
    });
    let transformed = insertion.transform('foo!')

    expect(transformed).toEqual('bar!');

  });

  it('transforms the case of the next character when encountering a \\u or \\l flag', () => {
    let uInsertion = new Insertion({
      range,
      substitution: {
        find: /(.)(.)(.*)/g,
        replace: [
          { backreference: 1 },
          { escape: 'u' },
          { backreference: 2 },
          { backreference: 3 }
        ]
      }
    });

    expect(uInsertion.transform('foo!')).toEqual('fOo!');
    expect(uInsertion.transform('fOo!')).toEqual('fOo!');
    expect(uInsertion.transform('FOO!')).toEqual('FOO!');

    let lInsertion = new Insertion({
      range,
      substitution: {
        find: /(.{2})(.)(.*)/g,
        replace: [
          { backreference: 1 },
          { escape: 'l' },
          { backreference: 2 },
          { backreference: 3 }
        ]
      }
    });

    expect(lInsertion.transform('FOO!')).toEqual('FOo!');
    expect(lInsertion.transform('FOo!')).toEqual('FOo!');
    expect(lInsertion.transform('FoO!')).toEqual('Foo!');
    expect(lInsertion.transform('foo!')).toEqual('foo!');

  });

  it('transforms the case of all remaining characters when encountering a \\U or \\L flag, up until it sees a \\E flag', () => {
    let uInsertion = new Insertion({
      range,
      substitution: {
        find: /(.)(.*)/,
        replace: [
          { backreference: 1 },
          { escape: 'U' },
          { backreference: 2 }
        ]
      }
    });

    expect(uInsertion.transform('lorem ipsum!')).toEqual('lOREM IPSUM!');
    expect(uInsertion.transform('lOREM IPSUM!')).toEqual('lOREM IPSUM!');
    expect(uInsertion.transform('LOREM IPSUM!')).toEqual('LOREM IPSUM!');

    let ueInsertion = new Insertion({
      range,
      substitution: {
        find: /(.)(.{3})(.*)/,
        replace: [
          { backreference: 1 },
          { escape: 'U' },
          { backreference: 2 },
          { escape: 'E' },
          { backreference: 3 }
        ]
      }
    });

    expect(ueInsertion.transform('lorem ipsum!')).toEqual('lOREm ipsum!');
    expect(ueInsertion.transform('lOREm ipsum!')).toEqual('lOREm ipsum!');
    expect(ueInsertion.transform('LOREM IPSUM!')).toEqual('LOREM IPSUM!');

    let lInsertion = new Insertion({
      range,
      substitution: {
        find: /(.{4})(.)(.*)/,
        replace: [
          { backreference: 1 },
          { escape: 'L' },
          { backreference: 2 },
          'WHAT'
        ]
      }
    });

    expect(lInsertion.transform('LOREM IPSUM!')).toEqual('LOREmwhat');

    let leInsertion = new Insertion({
      range,
      substitution: {
        find: /^([A-Fa-f])(.*)(.)$/,
        replace: [
          { backreference: 1 },
          { escape: 'L' },
          { backreference: 2 },
          { escape: 'E' },
          { backreference: 3 }
        ]
      }
    });

    expect(leInsertion.transform('LOREM IPSUM!')).toEqual('LOREM IPSUM!');
    expect(leInsertion.transform('CONSECUETUR')).toEqual('ConsecuetuR');
  });

});
<commit_msg>Remove Babel dep from insertion-spec and convert to standard style<commit_after>const Insertion = require('../lib/insertion')
const { Range } = require('atom')

const range = new Range(0, 0)

describe('Insertion', () => {
  it('returns what it was given when it has no substitution', () => {
    let insertion = new Insertion({
      range,
      substitution: undefined
    })
    let transformed = insertion.transform('foo!')

    expect(transformed).toEqual('foo!')
  })

  it('transforms what it was given when it has a regex transformation', () => {
    let insertion = new Insertion({
      range,
      substitution: {
        find: /foo/g,
        replace: ['bar']
      }
    })
    let transformed = insertion.transform('foo!')

    expect(transformed).toEqual('bar!')
  })

  it('transforms the case of the next character when encountering a \\u or \\l flag', () => {
    let uInsertion = new Insertion({
      range,
      substitution: {
        find: /(.)(.)(.*)/g,
        replace: [
          { backreference: 1 },
          { escape: 'u' },
          { backreference: 2 },
          { backreference: 3 }
        ]
      }
    })

    expect(uInsertion.transform('foo!')).toEqual('fOo!')
    expect(uInsertion.transform('fOo!')).toEqual('fOo!')
    expect(uInsertion.transform('FOO!')).toEqual('FOO!')

    let lInsertion = new Insertion({
      range,
      substitution: {
        find: /(.{2})(.)(.*)/g,
        replace: [
          { backreference: 1 },
          { escape: 'l' },
          { backreference: 2 },
          { backreference: 3 }
        ]
      }
    })

    expect(lInsertion.transform('FOO!')).toEqual('FOo!')
    expect(lInsertion.transform('FOo!')).toEqual('FOo!')
    expect(lInsertion.transform('FoO!')).toEqual('Foo!')
    expect(lInsertion.transform('foo!')).toEqual('foo!')
  })

  it('transforms the case of all remaining characters when encountering a \\U or \\L flag, up until it sees a \\E flag', () => {
    let uInsertion = new Insertion({
      range,
      substitution: {
        find: /(.)(.*)/,
        replace: [
          { backreference: 1 },
          { escape: 'U' },
          { backreference: 2 }
        ]
      }
    })

    expect(uInsertion.transform('lorem ipsum!')).toEqual('lOREM IPSUM!')
    expect(uInsertion.transform('lOREM IPSUM!')).toEqual('lOREM IPSUM!')
    expect(uInsertion.transform('LOREM IPSUM!')).toEqual('LOREM IPSUM!')

    let ueInsertion = new Insertion({
      range,
      substitution: {
        find: /(.)(.{3})(.*)/,
        replace: [
          { backreference: 1 },
          { escape: 'U' },
          { backreference: 2 },
          { escape: 'E' },
          { backreference: 3 }
        ]
      }
    })

    expect(ueInsertion.transform('lorem ipsum!')).toEqual('lOREm ipsum!')
    expect(ueInsertion.transform('lOREm ipsum!')).toEqual('lOREm ipsum!')
    expect(ueInsertion.transform('LOREM IPSUM!')).toEqual('LOREM IPSUM!')

    let lInsertion = new Insertion({
      range,
      substitution: {
        find: /(.{4})(.)(.*)/,
        replace: [
          { backreference: 1 },
          { escape: 'L' },
          { backreference: 2 },
          'WHAT'
        ]
      }
    })

    expect(lInsertion.transform('LOREM IPSUM!')).toEqual('LOREmwhat')

    let leInsertion = new Insertion({
      range,
      substitution: {
        find: /^([A-Fa-f])(.*)(.)$/,
        replace: [
          { backreference: 1 },
          { escape: 'L' },
          { backreference: 2 },
          { escape: 'E' },
          { backreference: 3 }
        ]
      }
    })

    expect(leInsertion.transform('LOREM IPSUM!')).toEqual('LOREM IPSUM!')
    expect(leInsertion.transform('CONSECUETUR')).toEqual('ConsecuetuR')
  })
})
<|endoftext|>


<commit_before>Application.Directives.directive('provenanceWizardSteps', provenanceWizardStepsDirective);

function provenanceWizardStepsDirective() {
    return {
        scope: {
            template: "=",
            showOverview: "="
        },
        controller: "provenanceWizardStepsDirectiveController",
        restrict: "EA",
        templateUrl: "application/core/projects/directives/provenance/provenance-wizard-steps.html"
    };
}

Application.Controllers.controller('provenanceWizardStepsDirectiveController',
                                   ["$scope", provenanceWizardStepsDirectiveController]);
function provenanceWizardStepsDirectiveController($scope) {
    function templateStepsCount() {
        if (!$scope.template) {
            return 0;
        }

        console.dir($scope.template);
        var count = $scope.template.input_templates.length;
        count += ($scope.template.required_input_files ? 1 : 0);
        count += $scope.template.output_templates.length;
        count += ($scope.template.required_output_files ? 1 : 0);
        console.log("count = " + count);
        return count;
    }

    $scope.offsetSteps = function() {
        return templateStepsCount() == 4;
    };
}
<commit_msg>Remove console statements.<commit_after>Application.Directives.directive('provenanceWizardSteps', provenanceWizardStepsDirective);

function provenanceWizardStepsDirective() {
    return {
        scope: {
            template: "=",
            showOverview: "="
        },
        controller: "provenanceWizardStepsDirectiveController",
        restrict: "EA",
        templateUrl: "application/core/projects/directives/provenance/provenance-wizard-steps.html"
    };
}

Application.Controllers.controller('provenanceWizardStepsDirectiveController',
                                   ["$scope", provenanceWizardStepsDirectiveController]);
function provenanceWizardStepsDirectiveController($scope) {
    function templateStepsCount() {
        if (!$scope.template) {
            return 0;
        }

        var count = $scope.template.input_templates.length;
        count += ($scope.template.required_input_files ? 1 : 0);
        count += $scope.template.output_templates.length;
        count += ($scope.template.required_output_files ? 1 : 0);
        return count;
    }

    $scope.offsetSteps = function() {
        return templateStepsCount() == 4;
    };
}
<|endoftext|>


<commit_before>/*global describe, it, beforeEach, expect, xit, jasmine */

describe("AttrList", function () {
    "use strict";
    var AttrList = window.multigraph.ModelTool.AttrList,
    al;

    beforeEach(function () {
        al = new AttrList("friends");
    });

    it("should be an Attr object", function () {
        expect(al instanceof window.multigraph.ModelTool.Attr).toBe(true);
    });

    it("should have a pop function", function () {
        expect(al.pop).not.toBeUndefined();
    });

    describe("size method", function () {
        it("should be initialized to 0", function () {
            expect(al.size()).toEqual(0);
        });

        it("should increase when an object is added", function () {
            var size = al.size();
            al.add("john");
            expect(al.size()).toEqual(size+1);
        });

        xit("should decrease when an object is removed", function () {

        });
    });

    describe("at method", function () {
        it("should return the element at a given index", function () {
            al.add("john");
            expect(al.at(0)).toEqual("john");
            al.add("semmy");
            expect(al.at(0)).toEqual("john");
            expect(al.at(1)).toEqual("semmy");
            al.add("mark");
            expect(al.at(0)).toEqual("john");
            expect(al.at(1)).toEqual("semmy");
            expect(al.at(2)).toEqual("mark");
        });

        it("should throw an exception if the parameter is out of bounds", function () {
            al.add("john");
            al.add("semmy");

            expect(function() {
                al.at(-1);
            }).toThrow(new Error("AttrList: Index out of bounds"));

            expect(function() {
                al.at(1);
            }).not.toThrow(new Error("AttrList: Index out of bounds"));

            expect(function() {
                al.at(2);
            }).toThrow(new Error("AttrList: Index out of bounds"));
        });

    });

    describe("add method", function () {
        it("should add an element to the end of the list", function () {
            al.add("john");
            expect(al.at(al.size()-1)).toEqual("john");
            al.add("semmy");
            expect(al.at(al.size()-2)).toEqual("john");
            expect(al.at(al.size()-1)).toEqual("semmy");
        });

        it("should call the validator function", function () {
            var v = jasmine.createSpy();
            var t = function (friend) {
                v();
                return true;
            };

            al.validatesWith(t);
            al.add("john");
            expect(v).toHaveBeenCalled();

        });

        it("should throw an error when the object does not pass validation", function () {
            expect(function () {
                al.errorsWith("Invalid").validatesWith(function (friend) {
                    return typeof(friend) === 'string';
                }).add(1);
            }).toThrow(new Error("Invalid"));
        });
    });

    describe("addTo method", function () {
        var Person = {};

        it("should add the AttrList to the specified object", function () {
            al.addTo(Person);
            expect(Person.friends).not.toBeUndefined();
            expect(Person.friends().add).not.toBeUndefined();
            expect(Person.friends().at).not.toBeUndefined();
            expect(Person.friends().size).not.toBeUndefined();
        });

        it("should not add any additional AttrList functions to the specified object", function () {
            al.addTo(Person);
            expect(Person.friends().validatesWith).toBeUndefined();
        });

        it("should accept the creation of two lists on the same object", function() {
            var al2 = new AttrList("cats");
            al.addTo(Person);
            al2.addTo(Person);
            expect(Person.friends).not.toBeUndefined();
            expect(Person.cats).not.toBeUndefined();
        });

        //test for the inheritance bug
        it("should allow for multiple attr_lists to be created", function () {
            var al2 = new AttrList("suit");

            al.validatesWith(function (suit) {
                return (suit === "diamonds");
            });

            expect(al.validator() !== al2.validator()).toBe(true);
        });

        it("should throw an error if the parameter is not an object", function () {
            expect(function () {
                al.addTo(5);
            }).toThrow(new Error("AttrList: addTo method requires an object parameter"));
        });

    });
});<commit_msg>changed attr_list tests to reflect our better understanding<commit_after>/*global describe, it, beforeEach, expect, xit, jasmine */

describe("AttrList", function () {
    "use strict";
    var AttrList = window.multigraph.ModelTool.AttrList,
    al,
    obj;

    beforeEach(function () {
        al = new AttrList("friends");
        obj = {};
        al.addTo(obj);
    });

    it("should be an Attr object", function () {
        expect(al instanceof window.multigraph.ModelTool.Attr).toBe(true);
    });

    it("should have a pop function", function () {
        expect(obj.friends().pop).not.toBeUndefined();
    });

    describe("size method", function () {
        it("should be initialized to 0", function () {
            expect(obj.friends().size()).toEqual(0);
        });

        it("should increase when an object is added", function () {
            var size = al.size();
            obj.friends().add("john");
            expect(al.size()).toEqual(size+1);
        });

        xit("should decrease when an object is removed", function () {

        });
    });

    describe("at method", function () {
        it("should return the element at a given index", function () {
            obj.friends().add("john");
            expect(obj.friends().at(0)).toEqual("john");
            obj.friends().add("semmy");
            expect(obj.friends().at(0)).toEqual("john");
            expect(obj.friends().at(1)).toEqual("semmy");
            obj.friends().add("mark");
            expect(obj.friends().at(0)).toEqual("john");
            expect(obj.friends().at(1)).toEqual("semmy");
            expect(obj.friends().at(2)).toEqual("mark");
        });

        it("should throw an exception if the parameter is out of bounds", function () {
            obj.friends().add("john");
            obj.friends().add("semmy");

            expect(function() {
                obj.friends().at(-1);
            }).toThrow(new Error("AttrList: Index out of bounds"));

            expect(function() {
                obj.friends().at(1);
            }).not.toThrow(new Error("AttrList: Index out of bounds"));

            expect(function() {
                obj.friends().at(2);
            }).toThrow(new Error("AttrList: Index out of bounds"));
        });

    });

    describe("add method", function () {
        it("should add an element to the end of the list", function () {
            obj.friends().add("john");
            expect(obj.friends().at(obj.friends().size()-1)).toEqual("john");
            obj.friends().add("semmy");
            expect(obj.friends().at(obj.friends().size()-2)).toEqual("john");
            expect(obj.friends().at(obj.friends().size()-1)).toEqual("semmy");
        });

        it("should call the validator function", function () {
            var v = jasmine.createSpy();
            var t = function (friend) {
                v();
                return true;
            };

            al.validatesWith(t);
            al.addTo(obj);
            obj.friends().add("john");
            expect(v).toHaveBeenCalled();

        });

        it("should throw an error when the object does not pass validation", function () {
            expect(function () {
                al.errorsWith("Invalid").validatesWith(function (friend) {
                    return typeof(friend) === 'string';
                });
                al.addTo(obj);
                obj.friends().add(1);
            }).toThrow(new Error("Invalid"));
        });
    });

    describe("addTo method", function () {
        var Person = {};

        it("should add the AttrList to the specified object", function () {
            al.addTo(Person);
            expect(Person.friends).not.toBeUndefined();
            expect(Person.friends().add).not.toBeUndefined();
            expect(Person.friends().at).not.toBeUndefined();
            expect(Person.friends().size).not.toBeUndefined();
        });

        it("should not add any additional AttrList functions to the specified object", function () {
            al.addTo(Person);
            expect(Person.friends().validatesWith).toBeUndefined();
        });

        it("should accept the creation of two lists on the same object", function() {
            var al2 = new AttrList("cats");
            al.addTo(Person);
            al2.addTo(Person);
            expect(Person.friends).not.toBeUndefined();
            expect(Person.cats).not.toBeUndefined();
        });

        //test for the inheritance bug
        it("should allow for multiple attr_lists to be created", function () {
            var al2 = new AttrList("suit");

            al.validatesWith(function (suit) {
                return (suit === "diamonds");
            });

            expect(al.validator() !== al2.validator()).toBe(true);
        });

        it("should throw an error if the parameter is not an object", function () {
            expect(function () {
                al.addTo(5);
            }).toThrow(new Error("AttrList: addTo method requires an object parameter"));
        });

    });
});<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';
const updateNotifier = require('update-notifier');
const meow = require('meow');
const moment = require('moment-timezone');
const devTime = require('dev-time');
const logSymbols = require('log-symbols');
const chalk = require('chalk');
const elegantSpinner = require('elegant-spinner');
const logUpdate = require('log-update');

const cli = meow(`
	Usage
	  $ dev-time <user> <user2> ...

	Options
	  -v, --verbose  Show UTC offset.
	  --format       The moment format of the output. [Default: HH:mm - D MMM. YYYY]
	  --token        The GitHub authentication token.

	Examples
	  $ dev-time SamVerschueren
	  19:47 - 8 Dec. 2015

	  $ dev-time SamVerschueren sindresorhus
	  SamVerschueren
	    19:47 - 8 Dec. 2015
	  sindresorhus
	    18:47 - 8 Dec. 2015

	  $ dev-time SamVerschueren -v
	  19:47 - 8 Dec. 2015 - UTC+1

	  $ dev-time SamVerschueren --format DD-MM-YYYY
	  07-12-2015
`, {
	string: ['_'],
	boolean: ['verbose'],
	alias: {
		v: 'verbose'
	},
	default: {
		format: 'HH:mm - D MMM. YYYY'
	}
});

updateNotifier({pkg: cli.pkg}).notify();

if (cli.input.length === 0) {
	console.error('Provide a GitHub user');
	process.exit(1);
}

const result = {};
const frames = {};

cli.input.forEach(user => frames[user] = elegantSpinner());

function parseError(err) {
	if (/no contributions/.test(err.message) || /Rate limit exceeded/.test(err.message)) {
		return `  ${logSymbols.error} ${chalk.red('error')} ${err.message.toLowerCase()}`;
	}

	return err.stack;
}

function render() {
	const output = [];

	cli.input.forEach(user => {
		if (cli.input.length === 1) {
			output.push(result[user].stack ? parseError(result[user]) : result[user]);
			return;
		}

		output.push(user);

		if (result[user]) {
			if (result[user] instanceof Error) {
				output.push(parseError(result[user]));
			} else {
				output.push(`  ${result[user]}`);
			}
		} else {
			output.push(`  ${chalk.gray.dim(frames[user]())}`);
		}
	});

	logUpdate(output.join('\n'));
}

if (cli.input.length > 1) {
	setInterval(render, 50);
}

Promise.all(cli.input.map(user =>
	devTime(user, cli.flags)
		.then(time => {
			const date = moment.utc(time).utcOffset(time);
			result[user] = date.format(cli.flags.format);

			if (cli.flags.verbose) {
				const sign = date.utcOffset() >= 0 ? '+' : '';
				result[user] += ` - UTC${sign}${date.utcOffset() / 60}`;
			}
		})
		.catch(err => result[user] = err)
)).then(() => {
	render();
	process.exit();
});
<commit_msg>fix linting issues<commit_after>#!/usr/bin/env node
'use strict';
const updateNotifier = require('update-notifier');
const meow = require('meow');
const moment = require('moment-timezone');
const devTime = require('dev-time');
const logSymbols = require('log-symbols');
const chalk = require('chalk');
const elegantSpinner = require('elegant-spinner');
const logUpdate = require('log-update');

const cli = meow(`
	Usage
	  $ dev-time <user> <user2> ...

	Options
	  -v, --verbose  Show UTC offset.
	  --format       The moment format of the output. [Default: HH:mm - D MMM. YYYY]
	  --token        The GitHub authentication token.

	Examples
	  $ dev-time SamVerschueren
	  19:47 - 8 Dec. 2015

	  $ dev-time SamVerschueren sindresorhus
	  SamVerschueren
	    19:47 - 8 Dec. 2015
	  sindresorhus
	    18:47 - 8 Dec. 2015

	  $ dev-time SamVerschueren -v
	  19:47 - 8 Dec. 2015 - UTC+1

	  $ dev-time SamVerschueren --format DD-MM-YYYY
	  07-12-2015
`, {
	string: ['_'],
	boolean: ['verbose'],
	alias: {
		v: 'verbose'
	},
	default: {
		format: 'HH:mm - D MMM. YYYY'
	}
});

updateNotifier({pkg: cli.pkg}).notify();

if (cli.input.length === 0) {
	console.error('Provide a GitHub user');
	process.exit(1);
}

const result = {};
const frames = {};

cli.input.forEach(user => {
	frames[user] = elegantSpinner();
});

function parseError(err) {
	if (/no contributions/.test(err.message) || /Rate limit exceeded/.test(err.message)) {
		return `  ${logSymbols.error} ${chalk.red('error')} ${err.message.toLowerCase()}`;
	}

	return err.stack;
}

function render() {
	const output = [];

	cli.input.forEach(user => {
		if (cli.input.length === 1) {
			output.push(result[user].stack ? parseError(result[user]) : result[user]);
			return;
		}

		output.push(user);

		if (result[user]) {
			if (result[user] instanceof Error) {
				output.push(parseError(result[user]));
			} else {
				output.push(`  ${result[user]}`);
			}
		} else {
			output.push(`  ${chalk.gray.dim(frames[user]())}`);
		}
	});

	logUpdate(output.join('\n'));
}

if (cli.input.length > 1) {
	setInterval(render, 50);
}

Promise.all(cli.input.map(user =>
	devTime(user, cli.flags)
		.then(time => {
			const date = moment.utc(time).utcOffset(time);
			result[user] = date.format(cli.flags.format);

			if (cli.flags.verbose) {
				const sign = date.utcOffset() >= 0 ? '+' : '';
				result[user] += ` - UTC${sign}${date.utcOffset() / 60}`;
			}
		})
		.catch(err => {
			result[user] = err;
		})
)).then(() => {
	render();
	process.exit();
});
<|endoftext|>


<commit_before>//Debug = Log all the things!
var d = false;

$(function() {
	//When document is ready with loading
	registerSideMenuEvents();

	$(window).resize(function(event) {
		onResize(event.currentTarget.innerWidth, event.currentTarget.innerHeight);;
	});
	onResize(window.innerWidth, window.innerHeight);

});

function registerSideMenuEvents() {
	$('.sidebar li.active').children('ul').show();
	$('.sidebar li.has-sub>a').on('click', function() {
		$(this).removeAttr('href');
		element = $(this).parent('li');
		if (element.hasClass('open')) {
			element.removeClass('open');
			element.find('li').removeClass('open');
			element.find('ul').slideUp(200);
		} else {
			element.addClass('open');
			element.children('ul').slideDown(200);
			element.siblings('li').children('ul').slideUp(200);
			element.siblings('li').removeClass('open');
			element.siblings('li').find('li').removeClass('open');
			element.siblings('li').find('ul').slideUp(200);
		}
	});
}

function onResize(width, height) {
	if(d) {
		console.log(width, height);
	}
	$(".Pagina").width(width*0.8);
	resizeBanner(width, height);
	resizeMenu(width, height);
	resizeContent(width, height);
	resizeFooter(width, height);
	resizeSidebar(width, height);
}

var canvas;
function resizeBanner(width, height) {
	canvas = $("#Banner");
}

function resizeMenu(width, height) {

}

function resizeContent(width, height) {

}

function resizeFooter(width, height) {

}

function resizeSidebar(width, height) {

}<commit_msg>Made stuff responsive<commit_after>//Debug = Log all the things!
var d = false;

$(function() {
	//When document is ready with loading
	registerSideMenuEvents();

	$(window).resize(function(event) {
		onResize(event.currentTarget.innerWidth, event.currentTarget.innerHeight);;
	});
	onResize(window.innerWidth, window.innerHeight);

});

function registerSideMenuEvents() {
	$('.sidebar li.active').children('ul').show();
	$('.sidebar li.has-sub>a').on('click', function() {
		$(this).removeAttr('href');
		element = $(this).parent('li');
		if (element.hasClass('open')) {
			element.removeClass('open');
			element.find('li').removeClass('open');
			element.find('ul').slideUp(200);
		} else {
			element.addClass('open');
			element.children('ul').slideDown(200);
			element.siblings('li').children('ul').slideUp(200);
			element.siblings('li').removeClass('open');
			element.siblings('li').find('li').removeClass('open');
			element.siblings('li').find('ul').slideUp(200);
		}
	});
}

function onResize(width, height) {
	if(d) {
		console.log(width, height);
	}
	$(".Pagina").width(width * 0.8);
	resizeBanner(width, height);
	resizeMenu(width, height);
	resizeContent(width, height);
	resizeFooter(width, height);
	resizeSidebar(width, height);
}

var canvas;
function resizeBanner(width, height) {
	canvas = $("#Banner");
}

function resizeMenu(width, height) {
	$(".Menu").width(width * 0.8 - 2);
}

function resizeContent(width, height) {

}

function resizeFooter(width, height) {
	$(".Footer").width(width * 0.8 - 2);
}

function resizeSidebar(width, height) {

}<|endoftext|>