<commit_before>angular.module("leaflet-directive").directive('layers', function ($log, $q, leafletData, leafletHelpers, leafletMapDefaults, leafletLayerHelpers) {
    var _leafletLayers;

    return {
        restrict: "A",
        scope: false,
        replace: false,
        require: 'leaflet',
        controller: function () {
            _leafletLayers = $q.defer();
            this.getLayers = function() {
                return _leafletLayers.promise;
            };
        },
        link: function(scope, element, attrs, controller) {
            var isDefined = leafletHelpers.isDefined,
                leafletLayers = {},
                leafletScope  = controller.getLeafletScope(),
                layers = leafletScope.layers,
                createLayer = leafletLayerHelpers.createLayer;

            controller.getMap().then(function(map) {
                var defaults = leafletMapDefaults.getDefaults(attrs.id);

                // Do we have a baselayers property?
                if (!isDefined(layers) || !isDefined(layers.baselayers) || Object.keys(layers.baselayers).length === 0) {
                    // No baselayers property
                    $log.error('[AngularJS - Leaflet] At least one baselayer has to be defined');
                    return;
                }

                // We have baselayers to add to the map
                _leafletLayers.resolve(leafletLayers);
                leafletData.setLayers(leafletLayers, attrs.id);

                leafletLayers.baselayers = {};
                leafletLayers.controls = {};
                leafletLayers.controls.layers = new L.control.layers();
                leafletLayers.controls.layers.setPosition(defaults.controlLayersPosition);

                // Setup all baselayers definitions
                var top = false;
                for (var layerName in layers.baselayers) {
                    var newBaseLayer = createLayer(layers.baselayers[layerName]);
                    if (!isDefined(newBaseLayer)) {
                        delete layers.baselayers[layerName];
                        continue;
                    }
                    leafletLayers.baselayers[layerName] = newBaseLayer;
                    // Only add the visible layer to the map, layer control manages the addition to the map
                    // of layers in its control
                    if (layers.baselayers[layerName].top === true) {
                        map.addLayer(leafletLayers.baselayers[layerName]);
                        top = true;
                    }

                    leafletLayers.controls.layers.addBaseLayer(leafletLayers.baselayers[layerName], layers.baselayers[layerName].name);
                }

                // Only add the layers switch selector control if we have more than one baselayer
                if (Object.keys(layers.baselayers).length > 1) {
                    leafletLayers.controls.layers.addTo(map);
                }

                // If there is no visible layer add first to the map
                if (!top && Object.keys(leafletLayers.baselayers).length > 0) {
                    map.addLayer(leafletLayers.baselayers[Object.keys(layers.baselayers)[0]]);
                }

                // Setup the Overlays
                leafletLayers.overlays = {};
                for (layerName in layers.overlays) {
                    var newOverlayLayer = createLayer(layers.overlays[layerName]);
                    if (isDefined(newOverlayLayer)) {
                        leafletLayers.overlays[layerName] = newOverlayLayer;
                        // Only add the visible layer to the map, layer control manages the addition to the map
                        // of layers in its control
                        if (layers.overlays[layerName].visible === true) {
                            map.addLayer(leafletLayers.overlays[layerName]);
                        }
                        leafletLayers.controls.layers.addOverlay(leafletLayers.overlays[layerName], layers.overlays[layerName].name);
                    }
                }

                // Watch for the base layers
                leafletScope.$watch('layers.baselayers', function(newBaseLayers) {
                    // Delete layers from the array
                    for (var name in leafletLayers.baselayers) {
                        if (!isDefined(newBaseLayers[name])) {
                            // Remove the layer from the control
                            leafletLayers.controls.layers.removeLayer(leafletLayers.baselayers[name]);
                            // Remove from the map if it's on it
                            if (map.hasLayer(leafletLayers.baselayers[name])) {
                                map.removeLayer(leafletLayers.baselayers[name]);
                            }
                            delete leafletLayers.baselayers[name];
                        }
                    }
                    // add new layers
                    for (var new_name in newBaseLayers) {
                        if (!isDefined(leafletLayers.baselayers[new_name])) {
                            var testBaseLayer = createLayer(newBaseLayers[new_name]);
                            if (isDefined(testBaseLayer)) {
                                leafletLayers.baselayers[new_name] = testBaseLayer;
                                // Only add the visible layer to the map, layer control manages the addition to the map
                                // of layers in its control
                                if (newBaseLayers[new_name].top === true) {
                                    map.addLayer(leafletLayers.baselayers[new_name]);
                                }
                                leafletLayers.controls.layers.addBaseLayer(leafletLayers.baselayers[new_name], newBaseLayers[new_name].name);
                            }
                        }
                    }
                    if (Object.keys(leafletLayers.baselayers).length === 0) {
                        $log.error('[AngularJS - Leaflet] At least one baselayer has to be defined');
                        return;
                    }

                    //we have layers, so we need to make, at least, one active
                    var found = false;
                    // search for an active layer
                    for (var key in leafletLayers.baselayers) {
                        if (map.hasLayer(leafletLayers.baselayers[key])) {
                            found = true;
                            break;
                        }
                    }
                    // If there is no active layer make one active
                    if (!found) {
                        map.addLayer(leafletLayers.baselayers[Object.keys(layers.baselayers)[0]]);
                    }
                }, true);

                var overLayersNotVisible = {};

                // Watch for the overlay layers
                leafletScope.$watch('layers.overlays', function(newOverlayLayers) {
                    // Delete layers from the array
                    for (var name in leafletLayers.overlays) {
                        if (!isDefined(newOverlayLayers[name])) {
                            // Remove the layer from the control
                            leafletLayers.controls.layers.removeLayer(leafletLayers.overlays[name]);
                            // Remove from the map if it's on it
                            if (map.hasLayer(leafletLayers.overlays[name])) {
                                map.removeLayer(leafletLayers.overlays[name]);
                            }
                            // TODO: Depending on the layer type we will have to delete what's included on it
                            delete leafletLayers.overlays[name];
                        }
                    }

                    // add new layers
                    for (var new_name in newOverlayLayers) {
                        if (!isDefined(leafletLayers.overlays[new_name])) {
                            var testOverlayLayer = createLayer(newOverlayLayers[new_name]);
                            if (isDefined(testOverlayLayer)) {
                                leafletLayers.overlays[new_name] = testOverlayLayer;
                                leafletLayers.controls.layers.addOverlay(leafletLayers.overlays[new_name], newOverlayLayers[new_name].name);
                                if (newOverlayLayers[new_name].visible === true) {
                                    map.addLayer(leafletLayers.overlays[new_name]);
                                }
                            }
                        }

                        // watch for the .visible property to hide/show overLayers
                        if (overLayersNotVisible[new_name] && newOverlayLayers[new_name].visible && !map.hasLayer(leafletLayers.overlays[new_name])) {
                            map.addLayer(overLayersNotVisible[new_name]);
                        } else if (newOverlayLayers[new_name].visible == false && map.hasLayer(leafletLayers.overlays[new_name])) {
                            overLayersNotVisible[new_name] = leafletLayers.overlays[new_name];
                            map.removeLayer(leafletLayers.overlays[new_name]);
                        }
                    }
                }, true);
            });
        }
    };
});
<commit_msg>Fixed jsHint warning.<commit_after>angular.module("leaflet-directive").directive('layers', function ($log, $q, leafletData, leafletHelpers, leafletMapDefaults, leafletLayerHelpers) {
    var _leafletLayers;

    return {
        restrict: "A",
        scope: false,
        replace: false,
        require: 'leaflet',
        controller: function () {
            _leafletLayers = $q.defer();
            this.getLayers = function() {
                return _leafletLayers.promise;
            };
        },
        link: function(scope, element, attrs, controller) {
            var isDefined = leafletHelpers.isDefined,
                leafletLayers = {},
                leafletScope  = controller.getLeafletScope(),
                layers = leafletScope.layers,
                createLayer = leafletLayerHelpers.createLayer;

            controller.getMap().then(function(map) {
                var defaults = leafletMapDefaults.getDefaults(attrs.id);

                // Do we have a baselayers property?
                if (!isDefined(layers) || !isDefined(layers.baselayers) || Object.keys(layers.baselayers).length === 0) {
                    // No baselayers property
                    $log.error('[AngularJS - Leaflet] At least one baselayer has to be defined');
                    return;
                }

                // We have baselayers to add to the map
                _leafletLayers.resolve(leafletLayers);
                leafletData.setLayers(leafletLayers, attrs.id);

                leafletLayers.baselayers = {};
                leafletLayers.controls = {};
                leafletLayers.controls.layers = new L.control.layers();
                leafletLayers.controls.layers.setPosition(defaults.controlLayersPosition);

                // Setup all baselayers definitions
                var top = false;
                for (var layerName in layers.baselayers) {
                    var newBaseLayer = createLayer(layers.baselayers[layerName]);
                    if (!isDefined(newBaseLayer)) {
                        delete layers.baselayers[layerName];
                        continue;
                    }
                    leafletLayers.baselayers[layerName] = newBaseLayer;
                    // Only add the visible layer to the map, layer control manages the addition to the map
                    // of layers in its control
                    if (layers.baselayers[layerName].top === true) {
                        map.addLayer(leafletLayers.baselayers[layerName]);
                        top = true;
                    }

                    leafletLayers.controls.layers.addBaseLayer(leafletLayers.baselayers[layerName], layers.baselayers[layerName].name);
                }

                // Only add the layers switch selector control if we have more than one baselayer
                if (Object.keys(layers.baselayers).length > 1) {
                    leafletLayers.controls.layers.addTo(map);
                }

                // If there is no visible layer add first to the map
                if (!top && Object.keys(leafletLayers.baselayers).length > 0) {
                    map.addLayer(leafletLayers.baselayers[Object.keys(layers.baselayers)[0]]);
                }

                // Setup the Overlays
                leafletLayers.overlays = {};
                for (layerName in layers.overlays) {
                    var newOverlayLayer = createLayer(layers.overlays[layerName]);
                    if (isDefined(newOverlayLayer)) {
                        leafletLayers.overlays[layerName] = newOverlayLayer;
                        // Only add the visible layer to the map, layer control manages the addition to the map
                        // of layers in its control
                        if (layers.overlays[layerName].visible === true) {
                            map.addLayer(leafletLayers.overlays[layerName]);
                        }
                        leafletLayers.controls.layers.addOverlay(leafletLayers.overlays[layerName], layers.overlays[layerName].name);
                    }
                }

                // Watch for the base layers
                leafletScope.$watch('layers.baselayers', function(newBaseLayers) {
                    // Delete layers from the array
                    for (var name in leafletLayers.baselayers) {
                        if (!isDefined(newBaseLayers[name])) {
                            // Remove the layer from the control
                            leafletLayers.controls.layers.removeLayer(leafletLayers.baselayers[name]);
                            // Remove from the map if it's on it
                            if (map.hasLayer(leafletLayers.baselayers[name])) {
                                map.removeLayer(leafletLayers.baselayers[name]);
                            }
                            delete leafletLayers.baselayers[name];
                        }
                    }
                    // add new layers
                    for (var new_name in newBaseLayers) {
                        if (!isDefined(leafletLayers.baselayers[new_name])) {
                            var testBaseLayer = createLayer(newBaseLayers[new_name]);
                            if (isDefined(testBaseLayer)) {
                                leafletLayers.baselayers[new_name] = testBaseLayer;
                                // Only add the visible layer to the map, layer control manages the addition to the map
                                // of layers in its control
                                if (newBaseLayers[new_name].top === true) {
                                    map.addLayer(leafletLayers.baselayers[new_name]);
                                }
                                leafletLayers.controls.layers.addBaseLayer(leafletLayers.baselayers[new_name], newBaseLayers[new_name].name);
                            }
                        }
                    }
                    if (Object.keys(leafletLayers.baselayers).length === 0) {
                        $log.error('[AngularJS - Leaflet] At least one baselayer has to be defined');
                        return;
                    }

                    //we have layers, so we need to make, at least, one active
                    var found = false;
                    // search for an active layer
                    for (var key in leafletLayers.baselayers) {
                        if (map.hasLayer(leafletLayers.baselayers[key])) {
                            found = true;
                            break;
                        }
                    }
                    // If there is no active layer make one active
                    if (!found) {
                        map.addLayer(leafletLayers.baselayers[Object.keys(layers.baselayers)[0]]);
                    }
                }, true);

                var overLayersNotVisible = {};

                // Watch for the overlay layers
                leafletScope.$watch('layers.overlays', function(newOverlayLayers) {
                    // Delete layers from the array
                    for (var name in leafletLayers.overlays) {
                        if (!isDefined(newOverlayLayers[name])) {
                            // Remove the layer from the control
                            leafletLayers.controls.layers.removeLayer(leafletLayers.overlays[name]);
                            // Remove from the map if it's on it
                            if (map.hasLayer(leafletLayers.overlays[name])) {
                                map.removeLayer(leafletLayers.overlays[name]);
                            }
                            // TODO: Depending on the layer type we will have to delete what's included on it
                            delete leafletLayers.overlays[name];
                        }
                    }

                    // add new layers
                    for (var new_name in newOverlayLayers) {
                        if (!isDefined(leafletLayers.overlays[new_name])) {
                            var testOverlayLayer = createLayer(newOverlayLayers[new_name]);
                            if (isDefined(testOverlayLayer)) {
                                leafletLayers.overlays[new_name] = testOverlayLayer;
                                leafletLayers.controls.layers.addOverlay(leafletLayers.overlays[new_name], newOverlayLayers[new_name].name);
                                if (newOverlayLayers[new_name].visible === true) {
                                    map.addLayer(leafletLayers.overlays[new_name]);
                                }
                            }
                        }

                        // watch for the .visible property to hide/show overLayers
                        if (overLayersNotVisible[new_name] && newOverlayLayers[new_name].visible && !map.hasLayer(leafletLayers.overlays[new_name])) {
                            map.addLayer(overLayersNotVisible[new_name]);
                        } else if (newOverlayLayers[new_name].visible === false && map.hasLayer(leafletLayers.overlays[new_name])) {
                            overLayersNotVisible[new_name] = leafletLayers.overlays[new_name];
                            map.removeLayer(leafletLayers.overlays[new_name]);
                        }
                    }
                }, true);
            });
        }
    };
});
<|endoftext|>


<commit_before>exports.add = add
exports.has = has
exports.remove = remove
exports.swap = swap

function add (list, item) {
  if (has(list, item)) return item
  item._index = list.length
  list.push(item)
  return item
}

function has (list, item) {
  return list[item._index] === item
}

function remove (list, item) {
  if (!has(list, item)) return item

  var last = list.pop()
  if (last !== item) {
    list[item._index] = last
    last._index = item._index
  }

  return item
}

function swap (list, a, b) {
  if (!has(list, a) || !has(list, b)) return
  var tmp = a._index
  a._index = b._index
  list[a._index] = a
  b._index = tmp
  list[b._index] = b
}
<commit_msg>fix return value from remove<commit_after>exports.add = add
exports.has = has
exports.remove = remove
exports.swap = swap

function add (list, item) {
  if (has(list, item)) return item
  item._index = list.length
  list.push(item)
  return item
}

function has (list, item) {
  return list[item._index] === item
}

function remove (list, item) {
  if (!has(list, item)) return null

  var last = list.pop()
  if (last !== item) {
    list[item._index] = last
    last._index = item._index
  }

  return item
}

function swap (list, a, b) {
  if (!has(list, a) || !has(list, b)) return
  var tmp = a._index
  a._index = b._index
  list[a._index] = a
  b._index = tmp
  list[b._index] = b
}
<|endoftext|>


<commit_before>var mocha = require('mocha')
var describe = mocha.describe
var before = mocha.beforeEach
var it = mocha.it
var chai = require('chai')
chai.should()
var expect = chai.expect

var createBus = function() {
  var me = {}

  var _handlers = {}
  var _events = []

  me.space = function(name) {
    return {
      on: function(address) {
        return {
          then: function(transform) {
            _handlers[address] = _handlers[address] || []
            _handlers[address].push(transform)
          }
        }
      }
    }
  }
  me.send = function(receivedAddress, receivedMessage) {
    var deliveries = {}
    deliveries[receivedAddress] = receivedMessage

    if(!_handlers[receivedAddress]) {
      _events.push({
        unhandled: [receivedAddress, receivedMessage]
      })
      return;
    }
    _handlers[receivedAddress].forEach(function(handler) {
      var event = {}
      event.received = [receivedAddress, receivedMessage]
      _events.push(event)

      var sender = function(sendAddress, sendMessage) {
        event.sent     = [sendAddress, sendMessage]
        me.send          (sendAddress, sendMessage)
      }
      handler(sender, deliveries)
    })
  }
  me.all = function() {
    return _events;
  }
  return me
}

var run = function(spec) {
  var bus = spec.go()

  var wasOk = false
  bus.all().forEach(function(event) {
    if (event.unhandled && event.unhandled[0] === 'expectation-ok') {
      wasOk = true
    }

  })
  if (wasOk)
    console.log("OK:", spec.name)
  else
    console.warn("FAIL:", spec.name)

}

var spec = function(bus, name) {
  return {
    when: function(whenAddress, whenMessage) {
      return {
        willSend: function(willSendAddress, willSendMessage) {
          bus.space().on(willSendAddress).then(function(s,d) {
            if (d[willSendAddress] === willSendMessage)
              s('expectation-ok', name)
          })
          return {
            name: name,
            go: function() {
              bus.send(whenAddress, whenMessage)
              return bus
            }
          }
        }
      }
    }
  }
}

var bus = createBus()

bus
  .space('app')
  .on('start')
  .then(function(s, d) {
    s('greeting', 'hello')
  })

run(spec(bus, 'it sends start')
  .when('start')
    .willSend('greeting', 'hello'))

<commit_msg>Deleted prototype<commit_after><|endoftext|>


<commit_before>'use strict';

var fs = require("fs")
var path = require('path')
var loaderUtils = require('loader-utils');
var elmCompiler = require('node-elm-compiler');
var yargs = require('yargs');

var runningInstances = 0;
var alreadyCompiledFiles = [];

var defaultOptions = {
  cache: false,
  forceWatch: false,
  yes: true
};

var getInput = function() {
  return this.resourcePath;
};

var getOptions = function() {
  var globalOptions = this.options.elm || {};
  var loaderOptions = loaderUtils.getOptions(this) || {};
  return Object.assign({
    emitWarning: this.emitWarning
  }, defaultOptions, globalOptions, loaderOptions);
};

var _addDependencies = function(dependency) {
  this.addDependency(dependency);
};

var _addDirDependency = function(dirs){
  dirs.forEach(this.addContextDependency.bind(this));
};

/* Figures out if webpack has been run in watch mode
    This currently means either that the `watch` command was used
    Or it was run via `webpack-dev-server`
*/
var isInWatchMode = function(){
  // parse the argv given to run this webpack instance
  var argv = yargs(process.argv)
      .alias('w', 'watch')
      .argv;

  var hasWatchArg = typeof argv.watch !== "undefined" && argv.watch;

  var hasWebpackDevServer = Array.prototype.filter.call(process.argv, function (arg) {
    return arg.indexOf('webpack-dev-server') !== -1;
  }).length > 0;

  return hasWebpackDevServer || hasWatchArg;
};

/* Takes a working dir, tries to read elm-package.json, then grabs all the modules from in there
*/
var filesToWatch = function(cwd){
  var readFile = fs.readFileSync(path.join(cwd, "elm-package.json"), 'utf8');
  var elmPackage = JSON.parse(readFile);

  var paths = elmPackage["source-directories"].map(function(dir){
    return path.join(cwd, dir);
  });

  return paths;
};

module.exports = function() {
  this.cacheable && this.cacheable();

  var callback = this.async();
  if (!callback) {
    throw 'elm-webpack-loader currently only supports async mode.';
  }

  // bind helper functions to `this`
  var addDependencies = _addDependencies.bind(this);
  var addDirDependency = _addDirDependency.bind(this);
  var emitError = this.emitError.bind(this);

  var input = getInput.call(this);
  var options = getOptions.call(this);

  var promises = [];

  // we only need to track deps if we are in watch mode
  // otherwise, we trust elm to do it's job
  if (options.forceWatch || isInWatchMode()){
    // we can do a glob to track deps we care about if cwd is set
    if (typeof options.cwd !== "undefined" && options.cwd !== null){
      // watch elm-package.json
      var elmPackage = path.join(options.cwd, "elm-package.json");
      addDependencies(elmPackage);
      var dirs = filesToWatch(options.cwd);
      // watch all the dirs in elm-package.json
      addDirDependency.bind(this)(dirs);
    }

    // find all the deps, adding them to the watch list if we successfully parsed everything
    // otherwise return an error which is currently ignored
    var dependencies = elmCompiler.findAllDependencies(input).then(function(dependencies){
      // add each dependency to the tree
      dependencies.map(addDependencies);
      return { kind: 'success', result: true };
    }).catch(function(v){
      emitError(v);
      return { kind: 'error', error: v };
    })

    promises.push(dependencies);
  }

  delete options.forceWatch

  var maxInstances = options.maxInstances;

  if (typeof maxInstances === "undefined"){
    maxInstances = 1;
  } else {
    delete options.maxInstances;
  }

  var intervalId = setInterval(function(){
    if (runningInstances > maxInstances) return;
    runningInstances += 1;
    clearInterval(intervalId);

    // If we are running in watch mode, and we have previously compiled
    // the current file, then let the user know that elm-make is running
    // and can be slow
    if (alreadyCompiledFiles.indexOf(input) > -1){
      console.log('Started compiling Elm..');
    }

    var compilation = elmCompiler.compileToString(input, options)
      .then(function(v) { runningInstances -= 1; return { kind: 'success', result: v }; })
      .catch(function(v) { runningInstances -= 1; return { kind: 'error', error: v }; });

    promises.push(compilation);

    Promise.all(promises)
      .then(function(results) {
        var output = results[results.length - 1]; // compilation output is always last

        if (output.kind == 'success') {
          alreadyCompiledFiles.push(input);
          callback(null, output.result);
        } else {
          output.error.message = 'Compiler process exited with error ' + output.error.message;
          callback(output.error);
        }
      }).catch(function(err){
        callback(err);
      });

  }, 200);
}
<commit_msg>Fix off-by-one bug in maxInstances<commit_after>'use strict';

var fs = require("fs")
var path = require('path')
var loaderUtils = require('loader-utils');
var elmCompiler = require('node-elm-compiler');
var yargs = require('yargs');

var runningInstances = 0;
var alreadyCompiledFiles = [];

var defaultOptions = {
  cache: false,
  forceWatch: false,
  yes: true
};

var getInput = function() {
  return this.resourcePath;
};

var getOptions = function() {
  var globalOptions = this.options.elm || {};
  var loaderOptions = loaderUtils.getOptions(this) || {};
  return Object.assign({
    emitWarning: this.emitWarning
  }, defaultOptions, globalOptions, loaderOptions);
};

var _addDependencies = function(dependency) {
  this.addDependency(dependency);
};

var _addDirDependency = function(dirs){
  dirs.forEach(this.addContextDependency.bind(this));
};

/* Figures out if webpack has been run in watch mode
    This currently means either that the `watch` command was used
    Or it was run via `webpack-dev-server`
*/
var isInWatchMode = function(){
  // parse the argv given to run this webpack instance
  var argv = yargs(process.argv)
      .alias('w', 'watch')
      .argv;

  var hasWatchArg = typeof argv.watch !== "undefined" && argv.watch;

  var hasWebpackDevServer = Array.prototype.filter.call(process.argv, function (arg) {
    return arg.indexOf('webpack-dev-server') !== -1;
  }).length > 0;

  return hasWebpackDevServer || hasWatchArg;
};

/* Takes a working dir, tries to read elm-package.json, then grabs all the modules from in there
*/
var filesToWatch = function(cwd){
  var readFile = fs.readFileSync(path.join(cwd, "elm-package.json"), 'utf8');
  var elmPackage = JSON.parse(readFile);

  var paths = elmPackage["source-directories"].map(function(dir){
    return path.join(cwd, dir);
  });

  return paths;
};

module.exports = function() {
  this.cacheable && this.cacheable();

  var callback = this.async();
  if (!callback) {
    throw 'elm-webpack-loader currently only supports async mode.';
  }

  // bind helper functions to `this`
  var addDependencies = _addDependencies.bind(this);
  var addDirDependency = _addDirDependency.bind(this);
  var emitError = this.emitError.bind(this);

  var input = getInput.call(this);
  var options = getOptions.call(this);

  var promises = [];

  // we only need to track deps if we are in watch mode
  // otherwise, we trust elm to do it's job
  if (options.forceWatch || isInWatchMode()){
    // we can do a glob to track deps we care about if cwd is set
    if (typeof options.cwd !== "undefined" && options.cwd !== null){
      // watch elm-package.json
      var elmPackage = path.join(options.cwd, "elm-package.json");
      addDependencies(elmPackage);
      var dirs = filesToWatch(options.cwd);
      // watch all the dirs in elm-package.json
      addDirDependency.bind(this)(dirs);
    }

    // find all the deps, adding them to the watch list if we successfully parsed everything
    // otherwise return an error which is currently ignored
    var dependencies = elmCompiler.findAllDependencies(input).then(function(dependencies){
      // add each dependency to the tree
      dependencies.map(addDependencies);
      return { kind: 'success', result: true };
    }).catch(function(v){
      emitError(v);
      return { kind: 'error', error: v };
    })

    promises.push(dependencies);
  }

  delete options.forceWatch

  var maxInstances = options.maxInstances;

  if (typeof maxInstances === "undefined"){
    maxInstances = 1;
  } else {
    delete options.maxInstances;
  }

  var intervalId = setInterval(function(){
    if (runningInstances >= maxInstances) return;
    runningInstances += 1;
    clearInterval(intervalId);

    // If we are running in watch mode, and we have previously compiled
    // the current file, then let the user know that elm-make is running
    // and can be slow
    if (alreadyCompiledFiles.indexOf(input) > -1){
      console.log('Started compiling Elm..');
    }

    var compilation = elmCompiler.compileToString(input, options)
      .then(function(v) { runningInstances -= 1; return { kind: 'success', result: v }; })
      .catch(function(v) { runningInstances -= 1; return { kind: 'error', error: v }; });

    promises.push(compilation);

    Promise.all(promises)
      .then(function(results) {
        var output = results[results.length - 1]; // compilation output is always last

        if (output.kind == 'success') {
          alreadyCompiledFiles.push(input);
          callback(null, output.result);
        } else {
          output.error.message = 'Compiler process exited with error ' + output.error.message;
          callback(output.error);
        }
      }).catch(function(err){
        callback(err);
      });

  }, 200);
}
<|endoftext|>


<commit_before>/*
* Check that the monthly payments data matches both
* my google calendar and shifts in tenrox.
*
*/

var cfg           = require('config'),
    log4js        = require('log4js'),
    calendarModel = require('calendar-model'),
    pd            = require('./lib/paymentData.js'),
    compare       = require('./lib/compare.js'),
    cs            = require('./lib/calendarShifts.js'),
    mailer        = require('./lib/emailNotification.js');
    timesheet     = require('./lib/tenrox.js');

/*
* Initialize
*/

// logs

log4js.configure(cfg.get('log.log4jsConfigs'));

var log = log4js.getLogger(cfg.get('log.appName'));
log.setLevel(cfg.get('log.level'));

/*
* Main program
*/

log.info('Begin script');
log.info('============');

function handleError (errMsg) {

  var emailContent = "Error running support payment check on " + emailMonth.toDateString();
     emailContent += '
'+errMsg;

  mailer.sendEmail({
    content: emailContent
  }, function(err) {

    if (err) {
      var errMsg = 'handleError: Error sending email: ' + err;
      log.error(errMsg)
      return null;
    }
  });

}

/*
 * Set up search times and go for it
 */

// Expect the email this month
var emailMonth = new Date()

try {

  // Get the payment data sent by email
  pd.get({emailMonth: emailMonth},function (err,paymentsData,isEmailAlreadyProcessed) {

    if (err) {
      var errMsg = 'index.js Error getting payment data: ' + err;
      log.error(errMsg)
      handleError(errMsg)
      return null;
    }

    // No messages found? No need to go on
    if (isEmailAlreadyProcessed) {
      log.info("Payments email already processed. Ending program.")
      return null;
    }

    log.info("Retrieved data from payments email:\n%s", JSON.stringify(paymentsData))
    // Get the calendar shifts
    var timeMin = new Date(emailMonth.getFullYear(), emailMonth.getMonth()-1);
    var timeMax = new Date(emailMonth.getFullYear(), emailMonth.getMonth(), 0, 23, 59, 59);

    cs.get({
      timeMin: timeMin,
      timeMax: timeMax
    },function (calendarData) {

      log.info("Retrieved data from calendar:\n%s", JSON.stringify(calendarData))

      timesheet.get({
        timeMin: timeMin,
        timeMax: timeMax
      }, function (err, oohShifts) {

        if (err) {
          var errMsg = 'index.js Error getting timesheet ooh shifts: ' + err;
          log.error(errMsg)
          handleError(errMsg)
          return null;
        }

        log.info("Retrieved data from timesheet:\n%s", JSON.stringify(oohShifts))

        compare.getDiffs({
         email: paymentsData,
         calendar: calendarData,
         timesheet: oohShifts
        }, function(err, syncChart, unSyncedCount) {

          if (err) {
            var errMsg = 'Error while comparing: ' + err;
            log.error(errMsg)
            handleError(errMsg)
            return null;
          }

          var emailContent = "Support payment check complete on " + emailMonth.toDateString();

          if (unSyncedCount == 0) {
            emailContent += '
All in sync.';
          } else {
            emailContent += '
'+unSyncedCount+' items not synced:'
          }

          emailContent += '
';

          emailContent += compare.formatSyncChartInTable({syncChart : syncChart});

          // Send out the email with the sync report
          mailer.sendEmail({
            content: emailContent
          }, function(err) {

            if (err) {
              var errMsg = 'Error sending email: ' + err;
              log.error(errMsg)
              handleError(errMsg)
              return null;
            }
          });

	  pd.updateLabels (function (err,message) {
            if (err) {
              var errMsg = 'Error updating labels: ' + err;
              log.error(errMsg)
              handleError(errMsg)
              return null;
            }
          });
        });
      });
    });

  });

} catch (err) {

  var errMsg = 'Error in main body:\n ' + err;
  log.error(errMsg)
  handleError(errMsg)
  return null;
}

return;

<commit_msg>Minor spacing<commit_after>/*
* Check that the monthly payments data matches both
* my google calendar and shifts in tenrox.
*
*/

var cfg           = require('config'),
    log4js        = require('log4js'),
    calendarModel = require('calendar-model'),
    pd            = require('./lib/paymentData.js'),
    compare       = require('./lib/compare.js'),
    cs            = require('./lib/calendarShifts.js'),
    mailer        = require('./lib/emailNotification.js');
    timesheet     = require('./lib/tenrox.js');

/*
* Initialize
*/

// logs

log4js.configure(cfg.get('log.log4jsConfigs'));

var log = log4js.getLogger(cfg.get('log.appName'));
log.setLevel(cfg.get('log.level'));

/*
* Main program
*/

log.info('Begin script');
log.info('============');

function handleError (errMsg) {

  var emailContent = "Error running support payment check on " + emailMonth.toDateString();
     emailContent += '
'+errMsg;

  mailer.sendEmail({
    content: emailContent
  }, function(err) {

    if (err) {
      var errMsg = 'handleError: Error sending email: ' + err;
      log.error(errMsg)
      return null;
    }
  });

}

/*
 * Set up search times and go for it
 */

// Expect the email this month
var emailMonth = new Date()

try {

  // Get the payment data sent by email
  pd.get({
    emailMonth: emailMonth
  },function (err,paymentsData,isEmailAlreadyProcessed) {

    if (err) {
      var errMsg = 'index.js Error getting payment data: ' + err;
      log.error(errMsg)
      handleError(errMsg)
      return null;
    }

    // No messages found? No need to go on
    if (isEmailAlreadyProcessed) {
      log.info("Payments email already processed. Ending program.")
      return null;
    }

    log.info("Retrieved data from payments email:\n%s", JSON.stringify(paymentsData))
    // Get the calendar shifts
    var timeMin = new Date(emailMonth.getFullYear(), emailMonth.getMonth()-1);
    var timeMax = new Date(emailMonth.getFullYear(), emailMonth.getMonth(), 0, 23, 59, 59);

    cs.get({
      timeMin: timeMin,
      timeMax: timeMax
    },function (calendarData) {

      log.info("Retrieved data from calendar:\n%s", JSON.stringify(calendarData))

      timesheet.get({
        timeMin: timeMin,
        timeMax: timeMax
      }, function (err, oohShifts) {

        if (err) {
          var errMsg = 'index.js Error getting timesheet ooh shifts: ' + err;
          log.error(errMsg)
          handleError(errMsg)
          return null;
        }

        log.info("Retrieved data from timesheet:\n%s", JSON.stringify(oohShifts))

        compare.getDiffs({
         email: paymentsData,
         calendar: calendarData,
         timesheet: oohShifts
        }, function(err, syncChart, unSyncedCount) {

          if (err) {
            var errMsg = 'Error while comparing: ' + err;
            log.error(errMsg)
            handleError(errMsg)
            return null;
          }

          var emailContent = "Support payment check complete on " + emailMonth.toDateString();

          if (unSyncedCount == 0) {
            emailContent += '
All in sync.';
          } else {
            emailContent += '
'+unSyncedCount+' items not synced:'
          }

          emailContent += '
';

          emailContent += compare.formatSyncChartInTable({syncChart : syncChart});

          // Send out the email with the sync report
          mailer.sendEmail({
            content: emailContent
          }, function(err) {

            if (err) {
              var errMsg = 'Error sending email: ' + err;
              log.error(errMsg)
              handleError(errMsg)
              return null;
            }
          });

	  pd.updateLabels (function (err,message) {
            if (err) {
              var errMsg = 'Error updating labels: ' + err;
              log.error(errMsg)
              handleError(errMsg)
              return null;
            }
          });
        });
      });
    });

  });

} catch (err) {

  var errMsg = 'Error in main body:\n ' + err;
  log.error(errMsg)
  handleError(errMsg)
  return null;
}

return;

<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

var config = require('../config')
var dbServer = require('fxa-auth-db-server')
var error = dbServer.errors
var log = require('../log')(config.logLevel, 'db-api')
var DB = require('../db')(log, error)

module.exports = function () {
  return DB.connect(config)
    .then(function (db) {
      return dbServer.createServer(db)
    })
}
<commit_msg>Fix relative import paths in index.js<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

var config = require('./config')
var dbServer = require('fxa-auth-db-server')
var error = dbServer.errors
var log = require('./log')(config.logLevel, 'db-api')
var DB = require('./db')(log, error)

module.exports = function () {
  return DB.connect(config)
    .then(function (db) {
      return dbServer.createServer(db)
    })
}
<|endoftext|>


<commit_before>module.exports = require('sails-generate-entities')({
  module: 'sails-auth',
  id: 'auth-api',
  statics: [
    'api/models/Passport.js',
    'api/models/User.js',
    'api/controllers/AuthController.js',
    'api/controllers/UserController.js',
    'api/services/protocols/index.js',
    'config/routes/sails-auth.js',
    'config/policies/sails-auth.js',
    'config/passport.js'
  ],
  classes: [
    'api/services/passport.js',
    'api/services/protocols/local.js',
    'api/services/protocols/basic.js',
    'api/services/protocols/oauth.js',
    'api/services/protocols/oauth2.js',
    'api/services/protocols/openid.js'
  ],
  functions: [
    'api/policies/passport.js',
    'api/policies/basicAuth.js',
    'api/policies/sessionAuth.js',
    'api/services/protocols/basic.js',
    'api/hooks/sails-auth.js'
  ]
});
<commit_msg>remove phantom policies config; resolves #14<commit_after>module.exports = require('sails-generate-entities')({
  module: 'sails-auth',
  id: 'auth-api',
  statics: [
    'api/models/Passport.js',
    'api/models/User.js',
    'api/controllers/AuthController.js',
    'api/controllers/UserController.js',
    'api/services/protocols/index.js',
    'config/routes/sails-auth.js',
    'config/passport.js'
  ],
  classes: [
    'api/services/passport.js',
    'api/services/protocols/local.js',
    'api/services/protocols/basic.js',
    'api/services/protocols/oauth.js',
    'api/services/protocols/oauth2.js',
    'api/services/protocols/openid.js'
  ],
  functions: [
    'api/policies/passport.js',
    'api/policies/basicAuth.js',
    'api/policies/sessionAuth.js',
    'api/services/protocols/basic.js',
    'api/hooks/sails-auth.js'
  ]
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
const SMTPServer = require('smtp-server').SMTPServer;
const simpleParser = require('mailparser').simpleParser;
const express = require("express");
const basicAuth = require('express-basic-auth');
const path = require("path");
const _ = require("lodash");
const moment = require("moment");
const cli = require('cli').enable('catchall');

const config = cli.parse({
  'smtp-port': ['s', 'SMTP port to listen on', 'number', 1025],
  'http-port': ['h', 'HTTP port to listen on', 'number', 1080],
  whitelist: ['w', 'Only accept e-mails from these adresses. Accepts multiple e-mails comma-separated', 'string'],
  max: ['m', 'Max number of e-mails to keep', 'number', 100],
  auth: ['a', 'Enable Authentication', 'string']
});

const whitelist = config.whitelist ? config.whitelist.split(',') : [];

let users = null;
if (config.auth && !/.+:.+/.test(config.auth)) {
    cli.error("Please provide authentication details in USERNAME:PASSWORD format");
    console.log(process.exit(1))
}
if (config.auth) {
  let authConfig = config.auth.split(":");
  users = {};
  users[authConfig[0]] = authConfig[1];
}

const mails = [];

const server = new SMTPServer({
  authOptional: true,
  onMailFrom(address, session, cb) {
    if (whitelist.length == 0 || whitelist.indexOf(address.address) !== -1) {
      cb();
    } else {
      cb(new Error('Invalid email from: ' + address.address));
    }
  },
  onData(stream, session, callback) {
    simpleParser(stream).then(
      mail => {
        cli.debug(JSON.stringify(mail));

        mails.unshift(mail);

        //trim list of emails if necessary
        while (mails.length > config.max) {
          mails.pop();
        }

        callback();
      },
      callback
    );
  }
});

server.on('error', err => {
  cli.error(err);
});

server.listen(config['smtp-port']);

const app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

if (users) {
    app.use(basicAuth({
        users: users,
        challenge: true
    }));
}

const buildDir = path.join(__dirname, 'build');

app.use(express.static(buildDir));

function emailFilter(filter) {
  return email => {
    if (filter.since || filter.until) {
      const date = moment(email.date);
      if (filter.since && date.isBefore(filter.since)) {
        return false;
      }
      if (filter.until && date.isAfter(filter.until)) {
        return false;
      }
    }

    if (filter.to && _.every(email.to.value, to => to.address !== filter.to)) {
      return false;
    }

    if (filter.from && _.every(email.from.value, from => from.address !== filter.from)) {
      return false;
    }

    return true;
  }
}

app.get('/api/emails', (req, res) => {
  res.json(mails.filter(emailFilter(req.query)));
});

app.delete('/api/emails', (req, res) => {
    mails.length = 0;
    res.send();
});

app.listen(config['http-port'], () => {
  cli.info("HTTP server listening on port " + config['http-port']);
});

cli.info("SMTP server listening on port " + config['smtp-port']);
<commit_msg>add cli status plugin<commit_after>#!/usr/bin/env node
const SMTPServer = require('smtp-server').SMTPServer;
const simpleParser = require('mailparser').simpleParser;
const express = require("express");
const basicAuth = require('express-basic-auth');
const path = require("path");
const _ = require("lodash");
const moment = require("moment");
const cli = require('cli').enable('catchall').enable('status');

const config = cli.parse({
  'smtp-port': ['s', 'SMTP port to listen on', 'number', 1025],
  'http-port': ['h', 'HTTP port to listen on', 'number', 1080],
  whitelist: ['w', 'Only accept e-mails from these adresses. Accepts multiple e-mails comma-separated', 'string'],
  max: ['m', 'Max number of e-mails to keep', 'number', 100],
  auth: ['a', 'Enable Authentication', 'string']
});

const whitelist = config.whitelist ? config.whitelist.split(',') : [];

let users = null;
if (config.auth && !/.+:.+/.test(config.auth)) {
    cli.error("Please provide authentication details in USERNAME:PASSWORD format");
    console.log(process.exit(1))
}
if (config.auth) {
  let authConfig = config.auth.split(":");
  users = {};
  users[authConfig[0]] = authConfig[1];
}

const mails = [];

const server = new SMTPServer({
  authOptional: true,
  onMailFrom(address, session, cb) {
    if (whitelist.length == 0 || whitelist.indexOf(address.address) !== -1) {
      cb();
    } else {
      cb(new Error('Invalid email from: ' + address.address));
    }
  },
  onData(stream, session, callback) {
    simpleParser(stream).then(
      mail => {
        cli.debug(JSON.stringify(mail));

        mails.unshift(mail);

        //trim list of emails if necessary
        while (mails.length > config.max) {
          mails.pop();
        }

        callback();
      },
      callback
    );
  }
});

server.on('error', err => {
  cli.error(err);
});

server.listen(config['smtp-port']);

const app = express();

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

if (users) {
    app.use(basicAuth({
        users: users,
        challenge: true
    }));
}

const buildDir = path.join(__dirname, 'build');

app.use(express.static(buildDir));

function emailFilter(filter) {
  return email => {
    if (filter.since || filter.until) {
      const date = moment(email.date);
      if (filter.since && date.isBefore(filter.since)) {
        return false;
      }
      if (filter.until && date.isAfter(filter.until)) {
        return false;
      }
    }

    if (filter.to && _.every(email.to.value, to => to.address !== filter.to)) {
      return false;
    }

    if (filter.from && _.every(email.from.value, from => from.address !== filter.from)) {
      return false;
    }

    return true;
  }
}

app.get('/api/emails', (req, res) => {
  res.json(mails.filter(emailFilter(req.query)));
});

app.delete('/api/emails', (req, res) => {
    mails.length = 0;
    res.send();
});

app.listen(config['http-port'], () => {
  cli.info("HTTP server listening on port " + config['http-port']);
});

cli.info("SMTP server listening on port " + config['smtp-port']);
<|endoftext|>


<commit_before>var winston = require('winston');
var moment = require('moment');
var extend = require('extend');
var util = require('util');
var path = require('path');
var fs = require('fs');

var DEFAULT_CONFIG = {
    consoleLevel: 'debug',
    fileLevel: 'none',
    logDir: 'logs',
    dateFormat: 'YYYY-MM-DD HH:mm:ss',
    prefix: false
};

function createLogger(config) {
    var username = config.username;
    var filePath = path.join('.', config.logDir, username + '.log');

    var logOptions = {
        levels: {
            debug: 0,
            info: 1,
            warn: 2,
            error: 3
        },
        colors: {
            debug: 'grey',
            info: 'green',
            warn: 'yellow',
            error: 'red'
        },
        transports: []
    };

    // Add transports if possible
    if(config.consoleLevel !== 'none') {
        logOptions.transports.push(new (winston.transports.Console)({
            timestamp: function() { return moment().format(config.dateFormat); },
            level: config.consoleLevel,
            colorize: true
        }));
    }

    if(config.fileLevel !== 'none') {
        var dirPath = path.join('.', config.logDir);
        if (!fs.existsSync(dirPath)){
            fs.mkdirSync(dirPath);
        }

        logOptions.transports.push(new (winston.transports.File)({
            filename: filePath,
            timestamp: function() { return moment().format(config.dateFormat); },
            level: config.fileLevel,
            json: false
        }));
    }

    // Create logger instance
    var logger = new (winston.Logger)({
        levels: logOptions.levels,
        colors: logOptions.colors,
        transports: logOptions.transports
    });

    // Add prefix if necessary
    if(config.prefix === true) {
        logger.addFilter(function(msg) {
            return util.format('[%s] %s', username, msg);
        });
    }

    return logger;
}

exports.name = 'winston-logger';

exports.plugin = function(VaporAPI) {
    var config = extend(true, {}, DEFAULT_CONFIG, VaporAPI.data);
    config.username = VaporAPI.getConfig().username;

    var logger = createLogger(config);

    VaporAPI.registerHandler({emitter: '*', event: 'message:debug'}, logger.debug);
    VaporAPI.registerHandler({emitter: '*', event: 'message:info'}, logger.info);
    VaporAPI.registerHandler({emitter: '*', event: 'message:warn'}, logger.warn);
    VaporAPI.registerHandler({emitter: '*', event: 'message:error'}, logger.error);
};
<commit_msg>fix indentation<commit_after>var winston = require('winston');
var moment = require('moment');
var extend = require('extend');
var util = require('util');
var path = require('path');
var fs = require('fs');

var DEFAULT_CONFIG = {
  consoleLevel: 'debug',
  fileLevel: 'none',
  logDir: 'logs',
  dateFormat: 'YYYY-MM-DD HH:mm:ss',
  prefix: false
};

function createLogger(config) {
  var username = config.username;
  var filePath = path.join('.', config.logDir, username + '.log');

  var logOptions = {
    levels: {
      debug: 0,
      info: 1,
      warn: 2,
      error: 3
    },
    colors: {
      debug: 'grey',
      info: 'green',
      warn: 'yellow',
      error: 'red'
    },
    transports: []
  };

  // Add transports if possible
  if(config.consoleLevel !== 'none') {
    logOptions.transports.push(new (winston.transports.Console)({
      timestamp: function() { return moment().format(config.dateFormat); },
      level: config.consoleLevel,
      colorize: true
    }));
  }

  if(config.fileLevel !== 'none') {
    var dirPath = path.join('.', config.logDir);
    if (!fs.existsSync(dirPath)){
      fs.mkdirSync(dirPath);
    }

    logOptions.transports.push(new (winston.transports.File)({
      filename: filePath,
      timestamp: function() { return moment().format(config.dateFormat); },
      level: config.fileLevel,
      json: false
    }));
  }

  // Create logger instance
  var logger = new (winston.Logger)({
    levels: logOptions.levels,
    colors: logOptions.colors,
    transports: logOptions.transports
  });

  // Add prefix if necessary
  if(config.prefix === true) {
    logger.addFilter(function(msg) {
      return util.format('[%s] %s', username, msg);
    });
  }

  return logger;
}

exports.name = 'winston-logger';

exports.plugin = function(VaporAPI) {
  var config = extend(true, {}, DEFAULT_CONFIG, VaporAPI.data);
  config.username = VaporAPI.getConfig().username;

  var logger = createLogger(config);

  VaporAPI.registerHandler({emitter: '*', event: 'message:debug'}, logger.debug);
  VaporAPI.registerHandler({emitter: '*', event: 'message:info'}, logger.info);
  VaporAPI.registerHandler({emitter: '*', event: 'message:warn'}, logger.warn);
  VaporAPI.registerHandler({emitter: '*', event: 'message:error'}, logger.error);
};
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const BST = require('../classes/BST.js');
const Util = require('../classes/Util.js');

module.exports.name = 'emoteLeaderboard';

module.exports.alias = [
  'emotes',
  'emojis',
  'emlb'
];

module.exports.isAllowed = () => {
  return true;
};

module.exports.help = '`,emlb [-s]` Emote leaderboard for this server. Put `-s` to show only the server emotes.';

module.exports.command = async (message, content, bot, server) => {
  let channel = message.channel;
  let onlyServer = /-l?s/.test(content) ? server.guild.emojis.map((v) => {return v.toString();}) : null;
  let longList = /-s?l/g.test(content);
  content = content.replace(/-[sl]+/g, '').trim();

  let users = server.users;
  let emDict = {};
  for (let user in users) {
    let reactions = users[user].totalReactions();
    if (reactions) {
      for (let r in reactions) {
        if (onlyServer && !onlyServer.includes(r)) continue;
        if (!emDict[r]) emDict[r] = 0;
        emDict[r] +=  reactions[r];
      }
    }
  }
  let result = new BST();
  for (let e in emDict) result.add(e, emDict[e]);
  result = result.toMap();
  let count = 1;

  if (longList) {
    let list = '';
    let nameRegex = /<a?(:[\S]+:)\d+>/;
    for (let emote in result) {
      let regMatch = emote.match(nameRegex);
      let temp = `${count++}) ${regMatch && !bot.usableEmotes.includes(emote) ? regMatch[1] : emote} : ${result[emote]}\n`;
      if (list.length + temp.length < 2000) list += temp;
      else {
        channel.send(list);
        return;
      }
    }
    if (onlyServer) {
      for (let emote of onlyServer) {
        if (!result[emote]) {
          let temp = count++ + ') ' + emote + ' : ' + 0 + '\n';
          if (list.length + temp.length < 2000) list += temp;
          else {
            channel.send(list);
            return;
          }
        }
      }
    }
    channel.send(list);
  } else {
    let embed = new Discord.RichEmbed();
    embed.title = `Emote Leaderboard${onlyServer ? ' for server emotes' : ''}`;
    embed.description = 'For the last 30 days (UTC time)';
    embed.color = Number('0x3A8EDB');
    let found = false;
    if (!result[content]) found = true; // If no such emote exists.
    for (let emote in result) {
      if (count >= 25) { // the 25th person is either the 25th one or the user
        if (!found && emote != content) {
          count++;
          continue;
        }
        embed.addField(count + ') ' + emote, result[emote], true);
        break;
      }
      if (emote == content) found = true;
      embed.addField(count++ + ') ' + emote, result[emote], true);
    }
    embed.setFooter('Current UTC time: ' + new Date().toUTCString());
    channel.send({embed});
  }
};
<commit_msg>em count bool<commit_after>const Discord = require('discord.js');
const BST = require('../classes/BST.js');
const Util = require('../classes/Util.js');

module.exports.name = 'emoteLeaderboard';

module.exports.alias = [
  'emotes',
  'emojis',
  'emlb',
  'el'
];

module.exports.isAllowed = () => {
  return true;
};

module.exports.help = '`,emlb [-s]` Emote leaderboard for this server. Put `-s` to show only the server emotes.';

module.exports.command = async (message, content, bot, server) => {
  let channel = message.channel;
  let onlyServer = /-l?c?s/g.test(content) ? server.guild.emojis.map((v) => {return v.toString();}) : null;
  let longList = /-s?c?l/g.test(content);
  let c = /-s?l?c/g.test(content);
  content = content.replace(/-[slc]+/g, '').trim();

  let users = server.users;
  let emDict = {};
  for (let user in users) {
    let reactions = users[user].totalReactions();
    if (reactions) {
      for (let r in reactions) {
        if (onlyServer && !onlyServer.includes(r)) continue;
        if (!emDict[r]) emDict[r] = 0;
        emDict[r] +=  reactions[r];
      }
    }
  }
  let result = new BST();
  for (let e in emDict) result.add(e, emDict[e]);
  result = result.toMap();
  let count = 1;

  if (longList) {
    let list = '';
    let nameRegex = /<a?(:[\S]+:)\d+>/;
    for (let emote in result) {
      let regMatch = emote.match(nameRegex);
      let temp = `${c ? count + ') ' : ''}${regMatch && !bot.usableEmotes.includes(emote) ? regMatch[1] : emote} : ${result[emote]}\n`;
      count++;
      if (list.length + temp.length < 2000) list += temp;
      else {
        channel.send(list);
        return;
      }
    }
    if (onlyServer) {
      for (let emote of onlyServer) {
        if (!result[emote]) {
          let temp = count++ + ') ' + emote + ' : ' + 0 + '\n';
          if (list.length + temp.length < 2000) list += temp;
          else {
            channel.send(list);
            return;
          }
        }
      }
    }
    channel.send(list);
  } else {
    let embed = new Discord.RichEmbed();
    embed.title = `Emote Leaderboard${onlyServer ? ' for server emotes' : ''}`;
    embed.description = 'For the last 30 days (UTC time)';
    embed.color = Number('0x3A8EDB');
    let found = false;
    if (!result[content]) found = true; // If no such emote exists.
    for (let emote in result) {
      if (count >= 25) { // the 25th person is either the 25th one or the user
        if (!found && emote != content) {
          count++;
          continue;
        }
        embed.addField(count + ') ' + emote, result[emote], true);
        break;
      }
      if (emote == content) found = true;
      embed.addField(count++ + ') ' + emote, result[emote], true);
    }
    embed.setFooter('Current UTC time: ' + new Date().toUTCString());
    channel.send({embed});
  }
};
<|endoftext|>


<commit_before>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2012 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Image field.  Used for pictures, icons, etc.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.FieldImage');

goog.require('Blockly.Field');
goog.require('goog.dom');
goog.require('goog.math.Size');
goog.require('goog.userAgent');

/**
 * Class for an image on a block.
 * @param {string} src The URL of the image.
 * @param {number} width Width of the image.
 * @param {number} height Height of the image.
 * @param {string=} opt_alt Optional alt text for when block is collapsed.
 * @param {Function=} opt_onClick Optional function to be called when the image
 *     is clicked.  If opt_onClick is defined, opt_alt must also be defined.
 * @extends {Blockly.Field}
 * @constructor
 */
Blockly.FieldImage = function(src, width, height, opt_alt, opt_onClick) {
  this.sourceBlock_ = null;

  // Ensure height and width are numbers.  Strings are bad at math.
  this.height_ = Number(height);
  this.width_ = Number(width);
  this.size_ = new goog.math.Size(this.width_,
      this.height_ + 2 * Blockly.BlockSvg.INLINE_PADDING_Y);
  this.text_ = opt_alt || '';
  this.setValue(src);

  if (typeof opt_onClick == 'function') {
    this.clickHandler_ = opt_onClick;
  }
};
goog.inherits(Blockly.FieldImage, Blockly.Field);

/**
 * Editable fields are saved by the XML renderer, non-editable fields are not.
 */
Blockly.FieldImage.prototype.EDITABLE = false;

/**
 * Install this image on a block.
 */
Blockly.FieldImage.prototype.init = function() {
  if (this.fieldGroup_) {
    // Image has already been initialized once.
    return;
  }
  // Build the DOM.
  /** @type {SVGElement} */
  this.fieldGroup_ = Blockly.utils.createSvgElement('g', {}, null);
  if (!this.visible_) {
    this.fieldGroup_.style.display = 'none';
  }
  /** @type {SVGElement} */
  this.imageElement_ = Blockly.utils.createSvgElement(
    'image',
    {
      'height': this.height_ + 'px',
      'width': this.width_ + 'px'
    },
    this.fieldGroup_);
  this.setValue(this.src_);
  this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_);

  // Configure the field to be transparent with respect to tooltips.
  this.setTooltip(this.sourceBlock_);
  Blockly.Tooltip.bindMouseEvents(this.imageElement_);

  this.maybeAddClickHandler_();
};

/**
 * Dispose of all DOM objects belonging to this text.
 */
Blockly.FieldImage.prototype.dispose = function() {
  goog.dom.removeNode(this.fieldGroup_);
  this.fieldGroup_ = null;
  this.imageElement_ = null;
};

/**
 * Bind events for a mouse down on the image, but only if a click handler has
 * been defined.
 * @private
 */
Blockly.FieldImage.prototype.maybeAddClickHandler_ = function() {
  if (this.clickHandler_) {
    this.mouseDownWrapper_ =
        Blockly.bindEventWithChecks_(this.fieldGroup_, 'mousedown', this,
        this.onMouseDown_);
  }
};

/**
 * Change the tooltip text for this field.
 * @param {string|!Element} newTip Text for tooltip or a parent element to
 *     link to for its tooltip.
 */
Blockly.FieldImage.prototype.setTooltip = function(newTip) {
  this.imageElement_.tooltip = newTip;
};

/**
 * Get the source URL of this image.
 * @return {string} Current text.
 * @override
 */
Blockly.FieldImage.prototype.getValue = function() {
  return this.src_;
};

/**
 * Set the source URL of this image.
 * @param {?string} src New source.
 * @override
 */
Blockly.FieldImage.prototype.setValue = function(src) {
  if (src === null) {
    // No change if null.
    return;
  }
  this.src_ = src;
  if (this.imageElement_) {
    this.imageElement_.setAttributeNS('http://www.w3.org/1999/xlink',
        'xlink:href', src || '');
  }
};

/**
 * Set the alt text of this image.
 * @param {?string} alt New alt text.
 * @override
 */
Blockly.FieldImage.prototype.setText = function(alt) {
  if (alt === null) {
    // No change if null.
    return;
  }
  this.text_ = alt;
};

/**
 * Images are fixed width, no need to render.
 * @private
 */
Blockly.FieldImage.prototype.render_ = function() {
  // NOP
};

/**
 * Images are fixed width, no need to update.
 * @private
 */
Blockly.FieldImage.prototype.updateWidth = function() {
 // NOP
};

/**
 * If field click is called, and click handler defined,
 * call the handler.
 */
Blockly.FieldImage.prototype.showEditor_ = function() {
  if (this.clickHandler_) {
    this.clickHandler_(this);
  }
};
<commit_msg>Fix #1467<commit_after>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2012 Google Inc.
 * https://developers.google.com/blockly/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Image field.  Used for pictures, icons, etc.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Blockly.FieldImage');

goog.require('Blockly.Field');
goog.require('goog.dom');
goog.require('goog.math.Size');
goog.require('goog.userAgent');

/**
 * Class for an image on a block.
 * @param {string} src The URL of the image.
 * @param {number} width Width of the image.
 * @param {number} height Height of the image.
 * @param {string=} opt_alt Optional alt text for when block is collapsed.
 * @param {Function=} opt_onClick Optional function to be called when the image
 *     is clicked.  If opt_onClick is defined, opt_alt must also be defined.
 * @extends {Blockly.Field}
 * @constructor
 */
Blockly.FieldImage = function(src, width, height, opt_alt, opt_onClick) {
  this.sourceBlock_ = null;

  // Ensure height and width are numbers.  Strings are bad at math.
  this.height_ = Number(height);
  this.width_ = Number(width);
  this.size_ = new goog.math.Size(this.width_,
      this.height_ + 2 * Blockly.BlockSvg.INLINE_PADDING_Y);
  this.text_ = opt_alt || '';
  this.setValue(src);

  if (typeof opt_onClick == 'function') {
    this.clickHandler_ = opt_onClick;
  }
};
goog.inherits(Blockly.FieldImage, Blockly.Field);

/**
 * Editable fields are saved by the XML renderer, non-editable fields are not.
 */
Blockly.FieldImage.prototype.EDITABLE = false;

/**
 * Install this image on a block.
 */
Blockly.FieldImage.prototype.init = function() {
  if (this.fieldGroup_) {
    // Image has already been initialized once.
    return;
  }
  // Build the DOM.
  /** @type {SVGElement} */
  this.fieldGroup_ = Blockly.utils.createSvgElement('g', {}, null);
  if (!this.visible_) {
    this.fieldGroup_.style.display = 'none';
  }
  /** @type {SVGElement} */
  this.imageElement_ = Blockly.utils.createSvgElement(
    'image',
    {
      'height': this.height_ + 'px',
      'width': this.width_ + 'px'
    },
    this.fieldGroup_);
  this.setValue(this.src_);
  this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_);

  // Configure the field to be transparent with respect to tooltips.
  this.setTooltip(this.sourceBlock_);
  Blockly.Tooltip.bindMouseEvents(this.imageElement_);

  this.maybeAddClickHandler_();
};

/**
 * Dispose of all DOM objects belonging to this text.
 */
Blockly.FieldImage.prototype.dispose = function() {
  goog.dom.removeNode(this.fieldGroup_);
  this.fieldGroup_ = null;
  this.imageElement_ = null;
};

/**
 * Bind events for a mouse down on the image, but only if a click handler has
 * been defined.
 * @private
 */
Blockly.FieldImage.prototype.maybeAddClickHandler_ = function() {
  if (this.clickHandler_) {
    this.mouseDownWrapper_ =
        Blockly.bindEventWithChecks_(this.fieldGroup_, 'mousedown', this,
        this.onMouseDown_);
  }
};

/**
 * Change the tooltip text for this field.
 * @param {string|!Element} newTip Text for tooltip or a parent element to
 *     link to for its tooltip.
 */
Blockly.FieldImage.prototype.setTooltip = function(newTip) {
  this.imageElement_.tooltip = newTip;
};

/**
 * Get the source URL of this image.
 * @return {string} Current text.
 * @override
 */
Blockly.FieldImage.prototype.getValue = function() {
  return this.src_;
};

/**
 * Set the source URL of this image.
 * @param {?string} src New source.
 * @override
 */
Blockly.FieldImage.prototype.setValue = function(src) {
  if (src === null) {
    // No change if null.
    return;
  }
  this.src_ = src;
  if (this.imageElement_) {
    this.imageElement_.setAttributeNS('http://www.w3.org/1999/xlink',
        'xlink:href', src || '');
  }
};

/**
 * Set the alt text of this image.
 * @param {?string} alt New alt text.
 * @override
 */
Blockly.FieldImage.prototype.setText = function(alt) {
  if (alt === null) {
    // No change if null.
    return;
  }
  this.text_ = alt;
};

/**
 * Images are fixed width, no need to render.
 * @private
 */
Blockly.FieldImage.prototype.render_ = function() {
  // NOP
};

/**
 * Images are fixed width, no need to render even if forced.
 */
Blockly.FieldImage.prototype.forceRerender = function() {
  // NOP
};

/**
 * Images are fixed width, no need to update.
 * @private
 */
Blockly.FieldImage.prototype.updateWidth = function() {
 // NOP
};

/**
 * If field click is called, and click handler defined,
 * call the handler.
 */
Blockly.FieldImage.prototype.showEditor_ = function() {
  if (this.clickHandler_) {
    this.clickHandler_(this);
  }
};
<|endoftext|>


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

/**
 * This script gathers dates and payload names from the subreddit launch manifest,
 * fuzzy checks them against existing upcoming payload id's and updates the date if a
 * change is made in the wiki. The proper time zone is calculated from the launch site
 * id of the launch.
 */

const MongoClient = require('mongodb');
const moment = require('moment-timezone');
const cheerio = require('cheerio');
const request = require('request-promise-native');
const fuzz = require('fuzzball');

moment.suppressDeprecationWarnings = true;

let client;
let location;
let calculatedTimes;
let localTime;
let date;

const sites = [];
const payloads = [];
const promises = [];

(async () => {
  try {
    client = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true });

    const db = client.db('spacex-api');
    const col = db.collection('launch');

    const launches = await col.find({ upcoming: true }).toArray();

    // Collect site names for time zone and payload name for fuzzy check
    launches.forEach(launch => {
      // Add temp fix for last Iridium NEXT launch because we need fuzzy
      // search to return 100% substring match, else we get SSO-A and SSO-B changing
      // because of a slight difference.
      // NOTE: Will be removed after launch
      if (launch.rocket.second_stage.payloads[0].payload_id === 'Iridium NEXT 8') {
        payloads.push('Iridium 8');
      } else {
        payloads.push(launch.rocket.second_stage.payloads[0].payload_id);
      }
      sites.push(launch.launch_site.site_id);
    });

    // Grab subreddit wiki manifest
    const result = await request('https://www.reddit.com/r/spacex/wiki/launches/manifest');
    const $ = cheerio.load(result);

    // Grab entire row, clean date, and convert to valid UTC moment date
    const manifest = $('body > div.content > div > div > table:nth-child(6) > tbody').text();
    const manifest_row = manifest.split('\n').filter(v => v !== '');

    // Filter to collect manaifest dates
    const manifest_dates = manifest_row.filter((value, index) => {
      return index % 8 === 0;
    });

    // Filter to collect payload names
    const manifest_payloads = manifest_row.filter((value, index) => {
      return (index + 3) % 8 === 0;
    });

    payloads.forEach((payload, p_index) => {
      manifest_payloads.forEach((manifest_payload, m_index) => {
        if (fuzz.partial_ratio(payload, manifest_payload) === 100) {
          location = sites[p_index];
          date = manifest_dates[m_index];

          console.log(date);
          console.log(`${payload} : ${manifest_payload}`);

          const stripped_time = `${date.replace('[', '').replace(']', '')} UTC`;
          const time = moment(stripped_time);
          const zone = moment.tz(time, 'UTC');

          // Set timezone based on launch location
          if (location === 'ccafs_slc_40' || location === 'ksc_lc_39a' || location === 'ccafs_lc_13') {
            localTime = time.tz('America/New_York').format();
          } else if (location === 'vafb_slc_4e' || location === 'vafb_slc_4w') {
            localTime = time.tz('America/Los_Angeles').format();
          } else {
            localTime = time.tz('America/Chicago').format();
          }

          // Build launch time objects to update
          calculatedTimes = {
            launch_date_unix: zone.unix(),
            launch_date_utc: zone.toISOString(),
            launch_date_local: localTime,
          };
          console.log(calculatedTimes);
          console.log('');

          // Another special case added for last Iridium launch
          // NOTE: Will be removed after launch
          if (payload === 'Iridium 8') {
            payload = 'Iridium NEXT 8';
          }

          promises.push(col.updateOne({ 'rocket.second_stage.payloads.payload_id': payload }, { $set: calculatedTimes }));
        }
      });
    });
    const output = await Promise.all(promises);
    output.forEach(doc => {
      console.log(`N: ${doc.result.n}`);
      console.log(`Modified: ${doc.result.nModified}`);
    });
  } catch (err) {
    console.log(err.stack);
  }

  if (client) {
    client.close();
  }
})();
<commit_msg>Added support for quarter and half year dates in upcoming launch updater<commit_after>#!/usr/bin/env node

/**
 * This script gathers dates and payload names from the subreddit launch manifest,
 * fuzzy checks them against existing upcoming payload id's and updates the date if a
 * change is made in the wiki. The proper time zone is calculated from the launch site
 * id of the launch.
 */

const MongoClient = require('mongodb');
const moment = require('moment-timezone');
const cheerio = require('cheerio');
const request = require('request-promise-native');
const fuzz = require('fuzzball');

moment.suppressDeprecationWarnings = true;

let client;
let location;
let calculatedTimes;
let localTime;
let date;

const sites = [];
const payloads = [];
const promises = [];

(async () => {
  try {
    client = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true });

    const db = client.db('spacex-api');
    const col = db.collection('launch');

    const launches = await col.find({ upcoming: true }).toArray();

    // Collect site names for time zone and payload name for fuzzy check
    launches.forEach(launch => {
      // Add temp fix for last Iridium NEXT launch because we need fuzzy
      // search to return 100% substring match, else we get SSO-A and SSO-B changing
      // because of a slight difference.
      // NOTE: Will be removed after launch
      if (launch.rocket.second_stage.payloads[0].payload_id === 'Iridium NEXT 8') {
        payloads.push('Iridium 8');
      } else {
        payloads.push(launch.rocket.second_stage.payloads[0].payload_id);
      }
      sites.push(launch.launch_site.site_id);
    });

    // Grab subreddit wiki manifest
    const result = await request('https://www.reddit.com/r/spacex/wiki/launches/manifest');
    const $ = cheerio.load(result);

    // Grab entire row, clean date, and convert to valid UTC moment date
    const manifest = $('body > div.content > div > div > table:nth-child(6) > tbody').text();
    const manifest_row = manifest.split('\n').filter(v => v !== '');

    // Filter to collect manaifest dates
    const manifest_dates = manifest_row.filter((value, index) => {
      return index % 8 === 0;
    });

    manifest_dates.forEach((elem, index) => {
      if (elem.includes('Q')) {
        manifest_dates[index] = manifest_dates[index].replace('Q', '');
      } else if (elem.includes('H1')) {
        manifest_dates[index] = manifest_dates[index].replace('H1', '1');
      } else if (elem.includes('H2')) {
        manifest_dates[index] = manifest_dates[index].replace('H2', '3');
      }
    });

    // Filter to collect payload names
    const manifest_payloads = manifest_row.filter((value, index) => {
      return (index + 3) % 8 === 0;
    });

    payloads.forEach((payload, p_index) => {
      manifest_payloads.forEach((manifest_payload, m_index) => {
        if (fuzz.partial_ratio(payload, manifest_payload) === 100) {
          location = sites[p_index];
          date = manifest_dates[m_index];

          console.log(date);
          console.log(`${payload} : ${manifest_payload}`);

          const stripped_time = `${date.replace('[', '').replace(']', '')} +0000`;
          const time = moment(stripped_time, ['YYYY MMM D HH:mm Z', 'YYYY MMM D Z', 'YYYY MMM Z', 'YYYY Q Z', 'YYYY Z']);
          const zone = moment.tz(time, 'UTC');

          // Set timezone based on launch location
          if (location === 'ccafs_slc_40' || location === 'ksc_lc_39a' || location === 'ccafs_lc_13') {
            localTime = time.tz('America/New_York').format();
          } else if (location === 'vafb_slc_4e' || location === 'vafb_slc_4w') {
            localTime = time.tz('America/Los_Angeles').format();
          } else {
            localTime = time.tz('America/Chicago').format();
          }

          // Build launch time objects to update
          calculatedTimes = {
            launch_date_unix: zone.unix(),
            launch_date_utc: zone.toISOString(),
            launch_date_local: localTime,
          };
          console.log(calculatedTimes);
          console.log('');

          // Another special case added for last Iridium launch
          // NOTE: Will be removed after launch
          if (payload === 'Iridium 8') {
            payload = 'Iridium NEXT 8';
          }

          promises.push(col.updateOne({ 'rocket.second_stage.payloads.payload_id': payload }, { $set: calculatedTimes }));
        }
      });
    });
    const output = await Promise.all(promises);
    output.forEach(doc => {
      console.log(`N: ${doc.result.n}`);
      console.log(`Modified: ${doc.result.nModified}`);
    });
  } catch (err) {
    console.log(err.stack);
  }

  if (client) {
    client.close();
  }
})();
<|endoftext|>


<commit_before>$(document).ready(function(){
    /*var box = document.getElementsByTagName('a-box');

    var changeColor = function() {
        this.setAttribute('color', 'green');
    };
    var returnColor = function() {
        this.setAttribute('color', '#4CC3D9');
    };

    for (var i = 0; i < box.length; i++) {
        box[i].addEventListener('mouseenter', changeColor, false);
        box[i].addEventListener('mouseleave', returnColor, false);
    }*/

    $( "a-box" ).hover(
        function(){
            $(this).setAttribute('color', 'green');
        },
        function(){
            $(this).setAttribute('color', '#4CC3D9');
        }
    );
});<commit_msg>Revert to old JS, TODO improve performance<commit_after>$(document).ready(function(){
    var box = document.getElementsByTagName('a-box');

    var changeColor = function() {
        this.setAttribute('color', 'green');
    };
    var returnColor = function() {
        this.setAttribute('color', '#4CC3D9');
    };

    for (var i = 0; i < box.length; i++) {
        box[i].addEventListener('mouseenter', changeColor, false);
        box[i].addEventListener('mouseleave', returnColor, false);
    }
});<|endoftext|>


<commit_before>import React from 'react'
import App, {Container} from 'next/app'
import {MDXProvider} from '@mdx-js/tag'
import Head from 'next/head'
import {withMDXLive} from 'mdx-live'
import {BaseStyles, Box, Flex, Link, theme} from '@primer/components'
import {SideNav, Header, IndexHero} from '../src/components'
import {rootPage} from '../src/utils'

import 'primer/build/build.css'
import 'prism-github/prism-github.css'

export default class MyApp extends App {
  static async getInitialProps({Component, ctx}) {
    let page = {}

    if (Component.getInitialProps) {
      page = await Component.getInitialProps(ctx)
    }

    return {page}
  }

  render() {
    // strip the trailing slash
    const pathname = this.props.router.pathname.replace(/\/$/, '')
    const {Component, page} = this.props

    const node = rootPage.first(node => node.path === pathname)
    const {meta = {}, outline: getOutline = () => []} = node || {}

    const components = {
      // render links with our component
      a: Link,
      p: ({children, ...rest}) => {
        if (children === '{:toc}') {
          return <TableOfContents outline={getOutline()} {...rest} />
        } else {
          return
{children}

        }
      },
      code: withMDXLive('pre'),
      pre: props => props.children
    }

    return (
      <BaseStyles style={{fontFamily: theme.fonts.normal}}>
        <Container>

            <title>Primer CSS{meta.title ? ` / ${meta.title}` : null}</title>

          <Flex display={['block', 'block', 'flex', 'flex']} flexDirection="row-reverse">
            <Box width="100%">
              {meta.hero ? <IndexHero /> : null}
              <Box color="gray.9" maxWidth={1012} width="100%" my={6} mx="auto" px={6}>

                  {meta.title ?
{meta.title}
 : null}
                  <MDXProvider components={components}>
                    <Component {...page} />
                  </MDXProvider>

meta: {JSON.stringify(meta, null, 2)}

                {/* TODO: bring back edit link! */}
              </Box>
            </Box>
            <SideNav />
          </Flex>
        </Container>
      </BaseStyles>
    )
  }
}

function TableOfContents({outline, ...rest}) {
  if (outline && outline.length) {
    return (
      <Box is="details" mb={4}>
        Table of contents
        <List items={outline} {...rest} />
      </Box>
    )
  }
  return null
}

function List({items, ...rest}) {
  if (items && items.length) {
    return (

        {items.map(item => (

            <a href={`#${item.id}`}>{item.title}
            <List items={item.children} />

        ))}

    )
  }
  return null
}
<commit_msg>use primer/index.scss<commit_after>import React from 'react'
import App, {Container} from 'next/app'
import {MDXProvider} from '@mdx-js/tag'
import Head from 'next/head'
import {withMDXLive} from 'mdx-live'
import {BaseStyles, Box, Flex, Link, theme} from '@primer/components'
import {SideNav, Header, IndexHero} from '../src/components'
import {rootPage} from '../src/utils'

import 'primer/index.scss'
import 'prism-github/prism-github.css'

export default class MyApp extends App {
  static async getInitialProps({Component, ctx}) {
    let page = {}

    if (Component.getInitialProps) {
      page = await Component.getInitialProps(ctx)
    }

    return {page}
  }

  render() {
    // strip the trailing slash
    const pathname = this.props.router.pathname.replace(/\/$/, '')
    const {Component, page} = this.props

    const node = rootPage.first(node => node.path === pathname)
    const {meta = {}, outline: getOutline = () => []} = node || {}

    const components = {
      // render links with our component
      a: Link,
      p: ({children, ...rest}) => {
        if (children === '{:toc}') {
          return <TableOfContents outline={getOutline()} {...rest} />
        } else {
          return
{children}

        }
      },
      code: withMDXLive('pre'),
      pre: props => props.children
    }

    return (
      <BaseStyles style={{fontFamily: theme.fonts.normal}}>
        <Container>

            <title>Primer CSS{meta.title ? ` / ${meta.title}` : null}</title>

          <Flex display={['block', 'block', 'flex', 'flex']} flexDirection="row-reverse">
            <Box width="100%">
              {meta.hero ? <IndexHero /> : null}
              <Box color="gray.9" maxWidth={1012} width="100%" my={6} mx="auto" px={6}>

                  {meta.title ?
{meta.title}
 : null}
                  <MDXProvider components={components}>
                    <Component {...page} />
                  </MDXProvider>

meta: {JSON.stringify(meta, null, 2)}

                {/* TODO: bring back edit link! */}
              </Box>
            </Box>
            <SideNav />
          </Flex>
        </Container>
      </BaseStyles>
    )
  }
}

function TableOfContents({outline, ...rest}) {
  if (outline && outline.length) {
    return (
      <Box is="details" mb={4}>
        Table of contents
        <List items={outline} {...rest} />
      </Box>
    )
  }
  return null
}

function List({items, ...rest}) {
  if (items && items.length) {
    return (

        {items.map(item => (

            <a href={`#${item.id}`}>{item.title}
            <List items={item.children} />

        ))}

    )
  }
  return null
}
<|endoftext|>


<commit_before>import path from 'path';
import mkdirp from 'mkdirp';
import { cloneOrFetchRepo, cloneRepo, checkoutSha, getWorkdirForRepoUrl,
  getTempdirForRepoUrl, getOriginForRepo, getHeadForRepo, resetOriginUrl } from './git-api';
import { getSanitizedRepoUrl, getNwoFromRepoUrl, postCommitStatus, createGist,
  findPRForCommit } from './github-api';
import { determineBuildCommands, runAllBuildCommands, uploadBuildArtifacts } from './build-api';
import { fs, rimraf } from './promisify';
import { retryPromise } from './promise-array';

import {Observable} from 'rxjs';
import ON_DEATH from 'death';

const DeathPromise = new Promise((res,rej) => {
  ON_DEATH((sig) => rej(new Error(`Signal ${sig} thrown`)));
});

const d = require('debug')('surf:surf-build');

function getRootAppDir() {
  let ret = null;
  let tmp = process.env.TMPDIR || process.env.TEMP || '/tmp';

  switch (process.platform) {
  case 'win32':
    ret = path.join(process.env.LOCALAPPDATA, 'surf');
    break;
  case 'darwin':
    ret = process.env.HOME ?
      path.join(process.env.HOME, 'Library', 'Application Support', 'surf') :
      path.join(tmp, 'surf-repos');
    break;
  default:
    ret = process.env.HOME ?
      path.join(process.env.HOME, '.config', 'surf') :
      path.join(tmp, 'surf-repos');
    break;
  }

  mkdirp.sync(ret);
  return ret;
}

function getRepoCloneDir() {
  return path.join(getRootAppDir(), 'repos');
}

function truncateErrorMessage(errorMessage) {
  return (errorMessage.split('\n')[0]).substr(0, 256);
}

export default function main(argv, showHelp) {
  let doIt = Observable.merge(
    Observable.fromPromise(realMain(argv, showHelp)),
    Observable.fromPromise(DeathPromise)
  ).take(1).toPromise();

  return doIt
    .then(() => Promise.resolve(true), (e) => {
      d("Build being taken down!");
      if (argv.name) {
        let repo = argv.repo || process.env.SURF_REPO;
        let sha = argv.sha || process.env.SURF_SHA1;
        let nwo = getNwoFromRepoUrl(repo);

        d(`Attempting to post error status!`);
        return retryPromise(() =>
            postCommitStatus(nwo, sha, 'error', `Build Errored: ${truncateErrorMessage(e.message)}`, null, argv.name))
          .catch(() => true)
          .then(() => d(`We did it!`))
          .then(() => Promise.reject(e));
      } else {
        return Promise.reject(e);
      }
    });
}

async function configureEnvironmentVariablesForChild(nwo, sha, name, repo) {
  process.env.SURF_NWO = nwo;
  process.env.SURF_REPO = repo;
  if (name) process.env.SURF_BUILD_NAME = name;

  // If the current PR number isn't set, try to recreate it
  try {
    if (!process.env.SURF_PR_NUM) {
      let pr = await findPRForCommit(nwo, sha);

      if (pr) {
        process.env.SURF_PR_NUM = pr.number;
        process.env.SURF_REF = pr.head.ref;
      }
    }
  } catch (e) {
    d(`Couldn't fetch PR for commit: ${e.message}`);
  }
}

async function realMain(argv, showHelp) {
  let sha = argv.sha || process.env.SURF_SHA1;
  let repo = argv.repo || process.env.SURF_REPO;
  let name = argv.name;

  if (argv.help) {
    showHelp();
    process.exit(0);
  }

  if (name === '__test__') {
    // NB: Don't end up setting statuses in unit tests, even if argv.name is set
    name = null;
  }

  if (!repo) {
    try {
      repo = getSanitizedRepoUrl(await getOriginForRepo('.'));
      argv.repo = repo;
    } catch (e) {
      console.error("Repository not specified and current directory is not a Git repo");
      d(e.stack);

      showHelp();
      process.exit(-1);
    }
  }

  if (!repo) {
    showHelp();
    process.exit(-1);
  }

  let repoDir = getRepoCloneDir();

  d(`Running initial cloneOrFetchRepo: ${repo} => ${repoDir}`);
  let bareRepoDir = await retryPromise(() => cloneOrFetchRepo(repo, repoDir));

  if (!sha) {
    d(`SHA1 not specified, trying to retrieve default branch`);
    try {
      sha = await getHeadForRepo(bareRepoDir);
      argv.sha = sha;
      d(`Default branch is ${sha}`);
    } catch (e) {
      console.error(`Failed to find the current commit for repo ${repo}: ${e.message}`);
      d(e.stack);

      showHelp();
      process.exit(-1);
    }
  }

  let nwo = getNwoFromRepoUrl(repo);
  await configureEnvironmentVariablesForChild(nwo, sha, name, repo);

  d(`repo: ${repo}, sha: ${sha}`);

  if (name) {
    d(`Posting 'pending' to GitHub status`);

    let nwo = getNwoFromRepoUrl(repo);
    await retryPromise(() =>
      postCommitStatus(nwo, sha, 'pending', 'Surf Build Server', null, name));
  }

  let workDir = getWorkdirForRepoUrl(repo, sha);
  let tempDir = getTempdirForRepoUrl(repo, sha);

  d(`Cloning to work directory: ${workDir}`);
  let r = await retryPromise(() => cloneRepo(bareRepoDir, workDir, null, false));
  r.free();

  d(`Checking out to given SHA1: ${sha}`);
  await checkoutSha(workDir, sha);

  d(`Resetting remote origin to URL`);
  await resetOriginUrl(workDir, repo);

  d(`Determining command to build`);
  let { cmd, cmds, args, artifactDirs } = await determineBuildCommands(workDir);

  if (!cmds) {
    cmds = [{cmd, args}];
  }

  let buildPassed = false;
  let buildOutput = null;

  try {
    let buildStream = runAllBuildCommands(cmds, workDir, sha, tempDir);

    buildOutput = '';
    buildStream.subscribe((x) => {
      buildOutput += x;
      console.log(x.replace(/[\r\n]+$/, ''));
    }, () => {});

    await buildStream
      .reduce(() => null)
      .toPromise();

    buildPassed = true;
  } catch (e) {
    buildOutput += `\n${e.message}`;
    d(e.stack);
  }

  await fs.writeFile(path.join(workDir, 'build-output.log'), buildOutput);

  if (name) {
    d(`Posting 'success' to GitHub status`);
    let nwo = getNwoFromRepoUrl(repo);

    let gistInfo = await retryPromise(() => createGist(`Build completed: ${nwo}#${sha}, ${new Date()}`, {
      "build-output.txt": {
        content: buildOutput
      }
    }));

    d(`Gist result: ${gistInfo.result.html_url}`);
    d(`Gist clone URL: ${gistInfo.result.git_pull_url}`);
    if (buildPassed) {
      let token = process.env.GIST_TOKEN || process.env.GITHUB_TOKEN;

      try {
        d(`Uploading build artifacts using token: ${token}`);
        let targetDir = await retryPromise(() => uploadBuildArtifacts(gistInfo.result.id, gistInfo.result.git_pull_url, artifactDirs, token));
        await rimraf(targetDir);
      } catch (e) {
        console.error(`Failed to upload build artifacts: ${e.message}`);
        d(e.stack);
      }
    }

    await postCommitStatus(nwo, sha,
      buildPassed ? 'success' : 'failure', 'Surf Build Server', gistInfo.result.html_url, name);
  }

  if (buildPassed && !process.env.DEBUG) {
    await rimraf(tempDir);
  }

  if (!buildPassed) {
    throw new Error(buildOutput);
  }
}
<commit_msg>Print the full error message to console<commit_after>import path from 'path';
import mkdirp from 'mkdirp';
import { cloneOrFetchRepo, cloneRepo, checkoutSha, getWorkdirForRepoUrl,
  getTempdirForRepoUrl, getOriginForRepo, getHeadForRepo, resetOriginUrl } from './git-api';
import { getSanitizedRepoUrl, getNwoFromRepoUrl, postCommitStatus, createGist,
  findPRForCommit } from './github-api';
import { determineBuildCommands, runAllBuildCommands, uploadBuildArtifacts } from './build-api';
import { fs, rimraf } from './promisify';
import { retryPromise } from './promise-array';

import {Observable} from 'rxjs';
import ON_DEATH from 'death';

const DeathPromise = new Promise((res,rej) => {
  ON_DEATH((sig) => rej(new Error(`Signal ${sig} thrown`)));
});

const d = require('debug')('surf:surf-build');

function getRootAppDir() {
  let ret = null;
  let tmp = process.env.TMPDIR || process.env.TEMP || '/tmp';

  switch (process.platform) {
  case 'win32':
    ret = path.join(process.env.LOCALAPPDATA, 'surf');
    break;
  case 'darwin':
    ret = process.env.HOME ?
      path.join(process.env.HOME, 'Library', 'Application Support', 'surf') :
      path.join(tmp, 'surf-repos');
    break;
  default:
    ret = process.env.HOME ?
      path.join(process.env.HOME, '.config', 'surf') :
      path.join(tmp, 'surf-repos');
    break;
  }

  mkdirp.sync(ret);
  return ret;
}

function getRepoCloneDir() {
  return path.join(getRootAppDir(), 'repos');
}

function truncateErrorMessage(errorMessage) {
  return (errorMessage.split('\n')[0]).substr(0, 256);
}

export default function main(argv, showHelp) {
  let doIt = Observable.merge(
    Observable.fromPromise(realMain(argv, showHelp)),
    Observable.fromPromise(DeathPromise)
  ).take(1).toPromise();

  return doIt
    .then(() => Promise.resolve(true), (e) => {
      d("Build being taken down!");
      if (argv.name) {
        let repo = argv.repo || process.env.SURF_REPO;
        let sha = argv.sha || process.env.SURF_SHA1;
        let nwo = getNwoFromRepoUrl(repo);

        console.error(`Build Errored: ${e.message}`);

        d(`Attempting to post error status!`);
        return retryPromise(() => {
          return postCommitStatus(nwo, sha, 'error', `Build Errored: ${truncateErrorMessage(e.message)}`, null, argv.name);
        })
          .catch(() => true)
          .then(() => d(`We did it!`))
          .then(() => Promise.reject(e));
      } else {
        return Promise.reject(e);
      }
    });
}

async function configureEnvironmentVariablesForChild(nwo, sha, name, repo) {
  process.env.SURF_NWO = nwo;
  process.env.SURF_REPO = repo;
  if (name) process.env.SURF_BUILD_NAME = name;

  // If the current PR number isn't set, try to recreate it
  try {
    if (!process.env.SURF_PR_NUM) {
      let pr = await findPRForCommit(nwo, sha);

      if (pr) {
        process.env.SURF_PR_NUM = pr.number;
        process.env.SURF_REF = pr.head.ref;
      }
    }
  } catch (e) {
    d(`Couldn't fetch PR for commit: ${e.message}`);
  }
}

async function realMain(argv, showHelp) {
  let sha = argv.sha || process.env.SURF_SHA1;
  let repo = argv.repo || process.env.SURF_REPO;
  let name = argv.name;

  if (argv.help) {
    showHelp();
    process.exit(0);
  }

  if (name === '__test__') {
    // NB: Don't end up setting statuses in unit tests, even if argv.name is set
    name = null;
  }

  if (!repo) {
    try {
      repo = getSanitizedRepoUrl(await getOriginForRepo('.'));
      argv.repo = repo;
    } catch (e) {
      console.error("Repository not specified and current directory is not a Git repo");
      d(e.stack);

      showHelp();
      process.exit(-1);
    }
  }

  if (!repo) {
    showHelp();
    process.exit(-1);
  }

  let repoDir = getRepoCloneDir();

  d(`Running initial cloneOrFetchRepo: ${repo} => ${repoDir}`);
  let bareRepoDir = await retryPromise(() => cloneOrFetchRepo(repo, repoDir));

  if (!sha) {
    d(`SHA1 not specified, trying to retrieve default branch`);
    try {
      sha = await getHeadForRepo(bareRepoDir);
      argv.sha = sha;
      d(`Default branch is ${sha}`);
    } catch (e) {
      console.error(`Failed to find the current commit for repo ${repo}: ${e.message}`);
      d(e.stack);

      showHelp();
      process.exit(-1);
    }
  }

  let nwo = getNwoFromRepoUrl(repo);
  await configureEnvironmentVariablesForChild(nwo, sha, name, repo);

  d(`repo: ${repo}, sha: ${sha}`);

  if (name) {
    d(`Posting 'pending' to GitHub status`);

    let nwo = getNwoFromRepoUrl(repo);
    await retryPromise(() =>
      postCommitStatus(nwo, sha, 'pending', 'Surf Build Server', null, name));
  }

  let workDir = getWorkdirForRepoUrl(repo, sha);
  let tempDir = getTempdirForRepoUrl(repo, sha);

  d(`Cloning to work directory: ${workDir}`);
  let r = await retryPromise(() => cloneRepo(bareRepoDir, workDir, null, false));
  r.free();

  d(`Checking out to given SHA1: ${sha}`);
  await checkoutSha(workDir, sha);

  d(`Resetting remote origin to URL`);
  await resetOriginUrl(workDir, repo);

  d(`Determining command to build`);
  let { cmd, cmds, args, artifactDirs } = await determineBuildCommands(workDir);

  if (!cmds) {
    cmds = [{cmd, args}];
  }

  let buildPassed = false;
  let buildOutput = null;

  try {
    let buildStream = runAllBuildCommands(cmds, workDir, sha, tempDir);

    buildOutput = '';
    buildStream.subscribe((x) => {
      buildOutput += x;
      console.log(x.replace(/[\r\n]+$/, ''));
    }, () => {});

    await buildStream
      .reduce(() => null)
      .toPromise();

    buildPassed = true;
  } catch (e) {
    buildOutput += `\n${e.message}`;
    d(e.stack);
  }

  await fs.writeFile(path.join(workDir, 'build-output.log'), buildOutput);

  if (name) {
    d(`Posting 'success' to GitHub status`);
    let nwo = getNwoFromRepoUrl(repo);

    let gistInfo = await retryPromise(() => createGist(`Build completed: ${nwo}#${sha}, ${new Date()}`, {
      "build-output.txt": {
        content: buildOutput
      }
    }));

    d(`Gist result: ${gistInfo.result.html_url}`);
    d(`Gist clone URL: ${gistInfo.result.git_pull_url}`);
    if (buildPassed) {
      let token = process.env.GIST_TOKEN || process.env.GITHUB_TOKEN;

      try {
        d(`Uploading build artifacts using token: ${token}`);
        let targetDir = await retryPromise(() => uploadBuildArtifacts(gistInfo.result.id, gistInfo.result.git_pull_url, artifactDirs, token));
        await rimraf(targetDir);
      } catch (e) {
        console.error(`Failed to upload build artifacts: ${e.message}`);
        d(e.stack);
      }
    }

    await postCommitStatus(nwo, sha,
      buildPassed ? 'success' : 'failure', 'Surf Build Server', gistInfo.result.html_url, name);
  }

  if (buildPassed && !process.env.DEBUG) {
    await rimraf(tempDir);
  }

  if (!buildPassed) {
    throw new Error(buildOutput);
  }
}
<|endoftext|>