<commit_before>'use strict';

var readline = require('readline');
var fs = require('fs');
var rfOptions = {encoding: 'utf-8'};
var _ = require('lodash');
var path = require('path');

/**
 *
 * @function SnowFrog is a static-site generating function that accepts a
 * directory and converts it into a directory with the new layout
 *
 * @param {string} path: a path for the file or file system that will be
 *                       the basis for the generated site.
 *
 * @param {string} indexFile A string naming the file to use as the template.
 *                           If no template file is specified, the program
 *                           assumes "layout.html"
 */
var SnowFrog = function (directory, indexFile, cb) {
  debugger;
  var obj = this._findDirectory(directory, indexFile);
  obj._cb = cb;
  this._webList(obj);
};

SnowFrog.prototype._startFrogging = function (obj, cb) {
  console.log("beginning frogging");
};

SnowFrog.prototype._finish = function (obj) {
  console.log("finishing");
  obj._cb(null, obj);
};

SnowFrog.prototype._findDirectory = function (directory, indexFile) {
  var template = indexFile;
  var dr = path.resolve(directory);
  if (!indexFile) {
    template = path.normalize(dr + "/layout.html");
  }
  console.log("Template file is: " + template);
  var obj = {path: dr, template: template};
  return obj;
};

SnowFrog.prototype._webList = function (obj) {
  console.log("beginning webList");
  fs.readdir(obj.path, function (err, files) {
    var webFiles = [];
    files.map(function (fileName) {
      if (fileName !== "layout.html") {
        if (fileName.slice(-5) === ".html") {
          webFiles.push(fileName);
        }
      }
      }.bind(this));
    obj.webFiles = webFiles;
    console.log(obj.webFiles);
    this._extractTemplate(obj);
    }.bind(this));
};

SnowFrog.prototype._extractTemplate = function (obj) {
  console.log("beginning template extraction");
  console.log(obj.template);
  fs.readFile(obj.template, "utf-8", function (err, content) {
    var layoutArray = content.split("{{CONTENT}}");
    obj.templateData = layoutArray;
    console.log(layoutArray);
    this._getOldContent(obj);
  }.bind(this));
};

SnowFrog.prototype._getOldContent = function (obj) {
  fs.readFile(obj.webFiles[0], "utf-8", function (err, data) {
    console.log("Extracting unique content from " + obj.webFiles[0]);
    obj.webContent = data;
    this._writeNewFiles(obj);
  }.bind(this));
};

SnowFrog.prototype._writeNewFiles = function (obj) {
  console.log("beginning to write new files");
  fs.writeFile(path.normalize(obj.path + '/' + 'new' + obj.webFiles[0]),
  (obj.templateData[0] + obj.webContent +
    obj.templateData[1]), "utf-8", function () {
      console.log("Created New File: new" + obj.webFiles[0]);
      this._finish(obj);
    }.bind(this));
};
  // obj.webFiles.forEach(function(file) {
  //   fs.readFile(file, "utf-8", function (err, data) {
  //     console.log("Cloning " + file);
  //     fs.writeFile(path.normalize(obj.path + 'new' + file),
  //       (obj.templateData[0].toString + data +
  //         obj.templateData[1]), "utf-8", function () {
  //         console.log("Created New File: new" + file);
  //       });
  //   }.bind(this));
  // }, this);

SnowFrog.prototype._eachFile = function (err, data, obj, count) {
  console.log("Cloning " + obj.webFiles[i]);
  fs.writeFile(path.normalize(obj.path + '/' + 'new' + obj.webFiles[count]),
    (obj.templateData[0].toString + data +
      obj.templateData[1]), "utf-8", function () {
        console.log("Created New File: new" + obj.webFiles[count]);
        count += 1;
        return count;
      });
};

module.exports = SnowFrog;
<commit_msg>Included iteration<commit_after>'use strict';

var readline = require('readline');
var fs = require('fs');
var rfOptions = {encoding: 'utf-8'};
var _ = require('lodash');
var path = require('path');

/**
 *
 * @function SnowFrog is a static-site generating function that accepts a
 * directory and converts it into a directory with the new layout
 *
 * @param {string} path: a path for the file or file system that will be
 *                       the basis for the generated site.
 *
 * @param {string} indexFile A string naming the file to use as the template.
 *                           If no template file is specified, the program
 *                           assumes "layout.html"
 */
var SnowFrog = function (directory, indexFile, cb) {
  //TODO Make error compatible
  debugger;
  var obj = this._findDirectory(directory, indexFile);
  obj._cb = cb;
  this._webList(obj);
};

SnowFrog.prototype._finish = function (obj) {
  console.log("finishing");
  obj._cb(null, obj);
};

SnowFrog.prototype._findDirectory = function (directory, indexFile) {
  var template = indexFile;
  var dr = path.resolve(directory);
  if (!indexFile) {
    template = path.normalize(dr + "/layout.html");
  }
  console.log("Template file is: " + template);
  var obj = {path: dr, template: template};
  return obj;
};

SnowFrog.prototype._webList = function (obj) {
  console.log("beginning webList");
  fs.readdir(obj.path, function (err, files) {
    var webFiles = [];
    files.map(function (fileName) {
      if (fileName !== "layout.html" && fileName.slice(-5) === ".html") {
          webFiles.push(fileName);
      }
      }.bind(this));
    obj.webFiles = webFiles;
    console.log(obj.webFiles);
    this._extractTemplate(obj);
    }.bind(this));
};

SnowFrog.prototype._extractTemplate = function (obj) {
  console.log("beginning template extraction");
  console.log(obj.template);
  fs.readFile(obj.template, "utf-8", function (err, content) {
    var layoutArray = content.split("{{CONTENT}}");
    obj.templateData = layoutArray;
    console.log(layoutArray);
    this._getOldContent(obj);
  }.bind(this));
};

SnowFrog.prototype._getOldContent = function (obj) {
  var counter = 0;
  obj.webContent = [];
  obj.webFiles.forEach(function (file, index) {
    fs.readFile(file, "utf-8", function (err, data) {
      console.log("Extracted unique content from " + file);
      obj.webContent[index] = data;
      counter += 1;
      if (counter === obj.webFiles.length) {
        this._writeNewFiles(obj);
      }
  }.bind(this));
  }, this);
};

SnowFrog.prototype._writeNewFiles = function (obj) {
  console.log("beginning to write new files");
  var counter = 0;
  obj.webFiles.forEach(function (file, index) {
    fs.writeFile(path.normalize(obj.path + '/' + 'new' + file),
    (obj.templateData[0] + obj.webContent[index] +
      obj.templateData[1]), "utf-8", function () {
        console.log("Created New File: new" + obj.webFiles[0]);
        counter += 1;
        if (counter === obj.webFiles.length) {
          this._finish(obj);
        }
    }.bind(this));
  }, this);
};

module.exports = SnowFrog;
<|endoftext|>


<commit_before>var inside = require('turf-inside');
var featureCollection = require('turf-featurecollection');

/**
 * Takes a {@link FeatureCollection} of {@link Point} features and a FeatureCollection of {@link Polygon} features and returns a FeatureCollection of Point features representing all points that fall within a collection of polygons.
 *
 * @module turf/within
 * @category joins
 * @param {FeatureCollection} points a FeatureCollection of {@link Point} features
 * @param {FeatureCollection} polygons a FeatureCollection of {@link Polygon} features
 * @return {FeatureCollection} a collection of all points that land
 * within at least one polygon
 * @example
 * var searchWithin = turf.featurecollection([
 *   turf.polygon([[
 *     [-46.653,-23.543],
 *     [-46.634,-23.5346],
 *     [-46.613,-23.543],
 *     [-46.614,-23.559],
 *     [-46.631,-23.567],
 *     [-46.653,-23.560],
 *     [-46.653,-23.543]
 *   ]])
 * ]);
 * var points = turf.featurecollection([
 *   turf.point([-46.6318, -23.5523]),
 *   turf.point([-46.6246, -23.5325]),
 *   turf.point([-46.6062, -23.5513]),
 *   turf.point([-46.663, -23.554]),
 *   turf.point([-46.643, -23.557])
 * ]);
 *
 * var ptsWithin = turf.within(points, searchWithin);
 *
 * //=points
 *
 * //=searchWithin
 *
 * //=ptsWithin
 */
module.exports = function(ptFC, polyFC){
  var pointsWithin = featureCollection([]);
  for (var i = 0; i < polyFC.features.length; i++) {
    for (var j = 0; j < ptFC.features.length; j++) {
      var isInside = inside(ptFC.features[j], polyFC.features[i]);
      if(isInside){
        pointsWithin.features.push(ptFC.features[j]);
      }
    }
  }
  return pointsWithin;
};
<commit_msg>Switch example to geojson primitives<commit_after>var inside = require('turf-inside');
var featureCollection = require('turf-featurecollection');

/**
 * Takes a {@link FeatureCollection} of {@link Point} features and a FeatureCollection of {@link Polygon} features and returns a FeatureCollection of Point features representing all points that fall within a collection of polygons.
 *
 * @module turf/within
 * @category joins
 * @param {FeatureCollection} points a FeatureCollection of {@link Point} features
 * @param {FeatureCollection} polygons a FeatureCollection of {@link Polygon} features
 * @return {FeatureCollection} a collection of all points that land
 * within at least one polygon
 * @example
 * var searchWithin = {
 *   "type": "FeatureCollection",
 *   "features": [
 *     {
 *       "type": "Feature",
 *       "properties": {},
 *       "geometry": {
 *         "type": "Polygon",
 *         "coordinates": [[
 *           [-46.653,-23.543],
 *           [-46.634,-23.5346],
 *           [-46.613,-23.543],
 *           [-46.614,-23.559],
 *           [-46.631,-23.567],
 *           [-46.653,-23.560],
 *           [-46.653,-23.543]
 *         ]]
 *       }
 *     }
 *   ]
 * };
 * var points = {
 *   "type": "FeatureCollection",
 *   "features": [
 *     {
 *       "type": "Feature",
 *       "properties": {},
 *       "geometry": {
 *         "type": "Point",
 *         "coordinates": [-46.6318, -23.5523]
 *       }
 *     }, {
 *       "type": "Feature",
 *       "properties": {},
 *       "geometry": {
 *         "type": "Point",
 *         "coordinates": [-46.6246, -23.5325]
 *       }
 *     }, {
 *       "type": "Feature",
 *       "properties": {},
 *       "geometry": {
 *         "type": "Point",
 *         "coordinates": [-46.6062, -23.5513]
 *       }
 *     }, {
 *       "type": "Feature",
 *       "properties": {},
 *       "geometry": {
 *         "type": "Point",
 *         "coordinates": [-46.663, -23.554]
 *       }
 *     }, {
 *       "type": "Feature",
 *       "properties": {},
 *       "geometry": {
 *         "type": "Point",
 *         "coordinates": [-46.643, -23.557]
 *       }
 *     }
 *   ]
 * };
 *
 * var ptsWithin = turf.within(points, searchWithin);
 *
 * //=points
 *
 * //=searchWithin
 *
 * //=ptsWithin
 */
module.exports = function(ptFC, polyFC){
  var pointsWithin = featureCollection([]);
  for (var i = 0; i < polyFC.features.length; i++) {
    for (var j = 0; j < ptFC.features.length; j++) {
      var isInside = inside(ptFC.features[j], polyFC.features[i]);
      if(isInside){
        pointsWithin.features.push(ptFC.features[j]);
      }
    }
  }
  return pointsWithin;
};
<|endoftext|>


<commit_before>var basicEventuate           = require('./basic'),
    EventuateUnconsumedError = require('./errors').EventuateUnconsumedError,
    EventuateEndedError      = require('./errors').EventuateEndedError

module.exports = function createEventuate (options) {
    options = typeof options === 'object' ? options : {}
    options.requireConsumption = options.requireConsumption === undefined ? false : options.requireConsumption

    var ended = false

    var eventuate = Object.defineProperties(basicEventuate(), {
        produce        : { value: produce, configurable: true, writable: true },
        consume        : { value: consume, configurable: true, writable: true },
        removeConsumer : { value: removeConsumer, configurable: true, writable: true },
        signalError    : { value: signalError, configurable: true, writable: true },
        signalEnd      : { value: signalEnd, configurable: true, writable: true },
        consumerAdded  : { value: basicEventuate(), configurable: true, writable: true },
        consumerRemoved: { value: basicEventuate(), configurable: true, writable: true },
        error          : { value: basicEventuate(), configurable: true, writable: true },
        end            : { value: basicEventuate(), configurable: true, writable: true },
        factory        : { value: createEventuate, configurable: true, writable: true }
    })

    return eventuate

    function produce (data) {
        if (ended)
            throw new EventuateEndedError('Cannot produce data on an ended eventuate')
        if (options.requireConsumption && eventuate._consumers.length === 0)
            throw ((data instanceof Error) ? data : new EventuateUnconsumedError('Unconsumed eventuate data', { data: data }))

        eventuate._consumers.forEach(function eventuateConsume (consume) {
            consume(data)
        })
    }

    function consume (consumer) {
        if (typeof consumer !== 'function') throw new TypeError('eventuate consumer must be a function')
        eventuate._consumers.push(consumer)
        eventuate.consumerAdded.produce(consumer)
    }

    function removeConsumer (consumer) {
        eventuate._consumers.splice(eventuate._consumers.indexOf(consumer), 1)
        eventuate.consumerRemoved.produce(consumer)
    }

    function signalError (err) {
        eventuate.error.produce(err)
    }

    function signalEnd () {
        ended = true
        eventuate.end.produce()
    }
}
<commit_msg>eventuate-core is too primitive for end/error<commit_after>var basicEventuate           = require('./basic'),
    EventuateUnconsumedError = require('./errors').EventuateUnconsumedError

module.exports = function createEventuate (options) {
    options = typeof options === 'object' ? options : {}
    options.requireConsumption = options.requireConsumption === undefined ? false : options.requireConsumption

    var eventuate = Object.defineProperties(basicEventuate(), {
        produce        : { value: produce, configurable: true, writable: true },
        consume        : { value: consume, configurable: true, writable: true },
        removeConsumer : { value: removeConsumer, configurable: true, writable: true },
        consumerAdded  : { value: basicEventuate(), configurable: true, writable: true },
        consumerRemoved: { value: basicEventuate(), configurable: true, writable: true },
        factory        : { value: createEventuate, configurable: true, writable: true }
    })

    return eventuate

    function produce (data) {
        if (options.requireConsumption && eventuate._consumers.length === 0)
            throw ((data instanceof Error) ? data : new EventuateUnconsumedError('Unconsumed eventuate data', { data: data }))

        eventuate._consumers.forEach(function eventuateConsume (consume) {
            consume(data)
        })
    }

    function consume (consumer) {
        if (typeof consumer !== 'function') throw new TypeError('eventuate consumer must be a function')
        eventuate._consumers.push(consumer)
        eventuate.consumerAdded.produce(consumer)
    }

    function removeConsumer (consumer) {
        eventuate._consumers.splice(eventuate._consumers.indexOf(consumer), 1)
        eventuate.consumerRemoved.produce(consumer)
    }
}
<|endoftext|>


<commit_before>var twitter = require('twitter')
  , env = process.env.NODE_ENV || "development"
  , request = require('request')
  , utils = require('./lib/utils')
  , settings = require('./settings.'+env+'.json');

var twit = new twitter(settings.twitter);

var sendTweetReply = function(in_reply_to_status_id, text, cb) {
    var form, r;
    var oauthKeys = {
      consumer_key: settings.twitter.consumer_key,
      consumer_secret: settings.twitter.consumer_secret,
      token: settings.twitter.access_token_key,
      token_secret: settings.twitter.access_token_secret
    };
    r = request.post("https://api.twitter.com/1.1/statuses/update.json", {oauth: oauthKeys}, cb);
    form = r.form();
    form.append('status', text);
    form.append('in_reply_to_status_id', in_reply_to_status_id);
    r.on('error', function(e) {
      console.error("Error while sending the tweet: ", e);
    });
  }

function processTweet(tweet) {

  if(!tweet.entities) return;
  if(!tweet.entities.urls || tweet.entities.urls.length == 0) return;
  if(tweet.user.screen_name == 'EmbeddedVideo') {
    console.log("tweet from EmbeddedVideo: ", tweet);
    return;
  }

  var url = tweet.entities.urls[0].expanded_url;

  console.log("Getting HTML page for ", url);
  utils.getHTML(url, function(e, html) {
    var videoUrl = utils.getVideoUrl(html);

    if(!videoUrl) {
      console.log("No video found in "+url);
      return;
    }

    utils.getHTML(videoUrl, function(e, html) {
      var title = utils.getTitle(html);

      title = title.replace(" - YouTube","");
      title = title.replace(" on Vimeo","");

      var via = "On @"+tweet.user.screen_name+":";
      var text = title.smart_truncate(119-via.length);

      text = via + " " + text + " " + videoUrl

      var hashtag = "#SavedYouAClick";

      if((text+hashtag).length < 119) text+= " " + hashtag;

      console.log("Sending tweet to ", tweet.id_str, text);
      sendTweetReply(tweet.id_str, text, function(err, result) {
        console.log("Tweet sent", err);
      });
    });
  });

};

twit.stream('user', function(stream) {

  stream.on('data', function(data) {

    // We don't process retweets, just interested in original tweets
    // var tweet = data.retweeted_status || data;
    if(data.retweeted_status) return;

    // We don't process tweets that mention @EmbeddedVideo
    if(data && data.text && data.text.match(/@EmbeddedVideo/i)) return;

    var tweet = data;

    console.log("\n-----------------------------------------------------------------------------\n");

    if(tweet.user) {
      console.log("Tweet from : "+tweet.user.screen_name, tweet.text);
      processTweet(tweet);
    }

  });

  stream.on('error', function(e) {
    console.error("Error in twitter stream", e);
    process.exit(1);
  });

  stream.on('end', function(e) {
    console.log("Twitter stream ended -- exiting");
    process.exit(1);
  });

});
<commit_msg>Revert "We don't process tweets that mention @EmbeddedVideo"<commit_after>var twitter = require('twitter')
  , env = process.env.NODE_ENV || "development"
  , request = require('request')
  , utils = require('./lib/utils')
  , settings = require('./settings.'+env+'.json');

var twit = new twitter(settings.twitter);

var sendTweetReply = function(in_reply_to_status_id, text, cb) {
    var form, r;
    var oauthKeys = {
      consumer_key: settings.twitter.consumer_key,
      consumer_secret: settings.twitter.consumer_secret,
      token: settings.twitter.access_token_key,
      token_secret: settings.twitter.access_token_secret
    };
    r = request.post("https://api.twitter.com/1.1/statuses/update.json", {oauth: oauthKeys}, cb);
    form = r.form();
    form.append('status', text);
    form.append('in_reply_to_status_id', in_reply_to_status_id);
    r.on('error', function(e) {
      console.error("Error while sending the tweet: ", e);
    });
  }

function processTweet(tweet) {

  if(!tweet.entities) return;
  if(!tweet.entities.urls || tweet.entities.urls.length == 0) return;
  if(tweet.user.screen_name == 'EmbeddedVideo') {
    console.log("tweet from EmbeddedVideo: ", tweet);
    return;
  }

  var url = tweet.entities.urls[0].expanded_url;

  console.log("Getting HTML page for ", url);
  utils.getHTML(url, function(e, html) {
    var videoUrl = utils.getVideoUrl(html);

    if(!videoUrl) {
      console.log("No video found in "+url);
      return;
    }

    utils.getHTML(videoUrl, function(e, html) {
      var title = utils.getTitle(html);

      title = title.replace(" - YouTube","");
      title = title.replace(" on Vimeo","");

      var via = "On @"+tweet.user.screen_name+":";
      var text = title.smart_truncate(119-via.length);

      text = via + " " + text + " " + videoUrl

      var hashtag = "#SavedYouAClick";

      if((text+hashtag).length < 119) text+= " " + hashtag;

      console.log("Sending tweet to ", tweet.id_str, text);
      sendTweetReply(tweet.id_str, text, function(err, result) {
        console.log("Tweet sent", err);
      });
    });
  });

};

twit.stream('user', function(stream) {

  stream.on('data', function(data) {

    // We don't process retweets, just interested in original tweets
    // var tweet = data.retweeted_status || data;
    if(data.retweeted_status) return;

    // We don't process tweets that mention @EmbeddedVideo
    if(data.text.match(/@EmbeddedVideo/i)) return;

    var tweet = data;

    console.log("\n-----------------------------------------------------------------------------\n");

    if(tweet.user) {
      console.log("Tweet from : "+tweet.user.screen_name, tweet.text);
      processTweet(tweet);
    }

  });

  stream.on('error', function(e) {
    console.error("Error in twitter stream", e);
    process.exit(1);
  });

  stream.on('end', function(e) {
    console.log("Twitter stream ended -- exiting");
    process.exit(1);
  });

});
<|endoftext|>


<commit_before>module.exports = ({ register, resolve }) => {
    const db = require('./lib/db')(resolve);
    register('db', () => db);

    const UserRepo = require('./lib/userRepo');
    const userRepo = new UserRepo(resolve);
    register('userRepo', () => userRepo);

    const LobbyRepo = require('./lib/lobbyRepo');
    const lobbyRepo = new LobbyRepo(resolve);
    register('lobbyRepo', () => lobbyRepo);

    const { Store } = require('repatch');
    const { lanName = 'l4n.at' } = resolve('settings');
    const publicStore = new Store({
        lanName,
        lobbies: [],
        providers: [],
        users: [],
    });
    register('publicStore', () => publicStore);

    require('./glue/lobbyRepoToStore')(resolve);
    require('./glue/userRepoToStore')(resolve);

    const privateStore = new Store({});
    register('privateStore', () => privateStore);

    const renderView = require('./lib/renderView')(resolve);
    register('renderView', () => renderView);

    const app = require('./lib/app')(resolve);
    register('app', () => app);

    const webSocketServer = require('./lib/webSocketServer')(resolve);
    register('webSocketServer', () => webSocketServer);

    require('./glue/storeToWebSocket')(resolve);
    require('./glue/webSocketToStore')(resolve);

    // TODO: refactor, needs to be last route
    app.get('*', renderView());
    // !!!

    const { httpServer: { port = 8080 } } = resolve('settings');
    app.listen(port);
};
<commit_msg>was solved via generated routes<commit_after>module.exports = ({ register, resolve }) => {
    const db = require('./lib/db')(resolve);
    register('db', () => db);

    const UserRepo = require('./lib/userRepo');
    const userRepo = new UserRepo(resolve);
    register('userRepo', () => userRepo);

    const LobbyRepo = require('./lib/lobbyRepo');
    const lobbyRepo = new LobbyRepo(resolve);
    register('lobbyRepo', () => lobbyRepo);

    const { Store } = require('repatch');
    const { lanName = 'l4n.at' } = resolve('settings');
    const publicStore = new Store({
        lanName,
        lobbies: [],
        providers: [],
        users: [],
    });
    register('publicStore', () => publicStore);

    require('./glue/lobbyRepoToStore')(resolve);
    require('./glue/userRepoToStore')(resolve);

    const privateStore = new Store({});
    register('privateStore', () => privateStore);

    const renderView = require('./lib/renderView')(resolve);
    register('renderView', () => renderView);

    const app = require('./lib/app')(resolve);
    register('app', () => app);

    const webSocketServer = require('./lib/webSocketServer')(resolve);
    register('webSocketServer', () => webSocketServer);

    require('./glue/storeToWebSocket')(resolve);
    require('./glue/webSocketToStore')(resolve);

    app.get('*', renderView());

    const { httpServer: { port = 8080 } } = resolve('settings');
    app.listen(port);
};
<|endoftext|>


<commit_before>'use strict';
const Koa = require('koa');
const MqttServer = require('./mqtt-server');
const server = new MqttServer();
const router = require('./router');
const data = {};
const jsonp = require('koa-jsonp');
const handlebars = require("koa-handlebars");

server.ready(() => {
  const app = new Koa();
  const redis = server.redisClient;
  app.server = server;
  app.use(function*(next) {
    this.set('Access-Control-Allow-Methods', '*');
    this.set('Access-Control-Allow-Origin', '*');
    this.set('Access-Control-Allow-Headers', 'Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With')
    if (this.method === 'OPTIONS') {
      this.status = 200;
    }
    yield next;
  });
  app.use(handlebars({
    defaultLayout: "main"
  }));
  app.use(router.routes());

  app.queryData = function(metric) {
    return redis.get(metric);
  }

  server.on('published', (message, client) => {
    if (message.topic === 'sensor') {
      try {
        const msg = JSON.parse(message.payload);
        const metric = msg.metric;
        const value = msg.value;
        if (!data[metric]) {
          data[metric] = [];
        }
        data[metric].push({
          time: Date.now(),
          value,
        });
        if (data[metric].length > 1000) {
          data[metric] = data[metric].slice(-1000);
        }
        redis.set(metric, JSON.stringify(data[metric]));
      } catch (err) {
        console.log(message.toString());
        console.error(err);
      }
    }
  });

  const port = 80;
  app.listen(port, () => {
    console.log(`app is listening on ${port}`);
  });
});<commit_msg>feat: add static<commit_after>'use strict';
const Koa = require('koa');
const MqttServer = require('./mqtt-server');
const server = new MqttServer();
const router = require('./router');
const data = {};
const jsonp = require('koa-jsonp');
const handlebars = require("koa-handlebars");

server.ready(() => {
  const app = new Koa();
  const redis = server.redisClient;
  app.server = server;
  app.use(function*(next) {
    this.set('Access-Control-Allow-Methods', '*');
    this.set('Access-Control-Allow-Origin', '*');
    this.set('Access-Control-Allow-Headers', 'Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With')
    if (this.method === 'OPTIONS') {
      this.status = 200;
    }
    yield next;
  });
  app.use(require('koa-static')(__dirname + '/views/public'));
  app.use(handlebars({
    defaultLayout: "main"
  }));
  app.use(router.routes());

  app.queryData = function(metric) {
    return redis.get(metric);
  }

  server.on('published', (message, client) => {
    if (message.topic === 'sensor') {
      try {
        const msg = JSON.parse(message.payload);
        const metric = msg.metric;
        const value = msg.value;
        if (!data[metric]) {
          data[metric] = [];
        }
        data[metric].push({
          time: Date.now(),
          value,
        });
        if (data[metric].length > 1000) {
          data[metric] = data[metric].slice(-1000);
        }
        redis.set(metric, JSON.stringify(data[metric]));
      } catch (err) {
        console.log(message.toString());
        console.error(err);
      }
    }
  });

  const port = 80;
  app.listen(port, () => {
    console.log(`app is listening on ${port}`);
  });
});<|endoftext|>


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

// TODO: package up as an NPM module so it can be -g installed and run from path with node

const fs = require('fs');
const path = require('path');
const args = require('args');

args
  .option('infile', 'Filename to read kindle quotes, default is quotes.txt', 'quotes.txt')
  .option('outfile', 'Filename to write JSON, default is quotes.json', 'quotes.json')
  .option('dirname', 'Path to write outfile to, default is pwd', __dirname)
  .option('no-reorder', 'Prevent re-ordering author names from "Surname, Name" to "Name Surname"');

const flags = args.parse(process.argv);

/////////////
// helpers //
/////////////

function stripBOM(str) { return str.replace(/[\u200B-\u200D\uFEFF]/g, ''); }
function parseTitle(str) { return str.match(/.+(?=\s\()/)[0]; }
function swapWords(w1, w2) { return `${w2} ${w1}`; }
function last(arr) { return arr[arr.length - 1]; }
function isEmpty(x) { return x === '' || x == null; }
function isDuplicate(a, b) { return a === b; }

/**
 * Reduce all occurrences of multiple spaces to a single space char.
 * So that '      ' becomes ' '
 * @param  {String} str
 * @return {String}
 */
function contractSpaces(str) { return str.replace(/\s{2,}/g, ' '); }

/**
 *  re-order names in the format of "surname, name" to "name surname"
 * @param  {String} str String containing more than one name
 * @return {String}     Re-ordered name
 */
function orderNames(str) { return /,/.test(str) ? swapWords(...str.split(/,\s?/)) : str; }

function parseAuthor(str) {
  // capture author names from string format: "Book title (maybe with parens) (AUTHOR NAMES)"
  const re = /(?:\((?!.*\())(.+)(?:\))/;

  // match names, and split any multiple authors delineated by ";" and format as Firstname Last
  let authors = str.match(re)[1].split(/;\s?/);
  if (!flags.n) authors = authors.map(orderNames);
  return authors.join(', ');
}

// TODO: use moment.js or roll-your-own date parsing into a proper JS Date() object.
function parseDate(str) {
  // kindle human readable dates follow 'on ' and end with ' HH:MM:SS'
  // NOTE: keep the time in string if parsing to a JS date
  const re = /\son\s(.*)(?=\s\d\d:)/;

  return str.match(re)[1];
}

function parseLine(prev, quote, index) {
  const [header, date, content] = quote.trim().split(/\s?\n\s?/);

  if (isEmpty(content) || prev.length && isDuplicate(content, last(prev).content)) return prev;

  return prev.concat({
    title: parseTitle(header),
    author: parseAuthor(header),
    date: parseDate(date),
    // Some of my quotes had huge chunks of spaces - probably from epub to mobi conversions?
    content: contractSpaces(content),
  });
}

function buildJSON(data) {
  // entries are separated with ============
  const kindleQuoteBreak = /={2,}/;
  const clippings = data.split(kindleQuoteBreak).reduce(parseLine, []);

  return JSON.stringify(clippings);
}

/////////////////////
// main logic here //
/////////////////////

fs.readFile(flags.infile, 'utf8', (err, data) => {
  if (err) throw err;

  const dest = path.join(flags.dirname, flags.outfile);
  const clippings = buildJSON(data);

  fs.writeFile(dest, clippings, (writeErr) => {
    if (writeErr) {
      throw writeErr;
    } else console.log(`Output quotes to ${dest}`);
  });
});
<commit_msg>fix comment about split chars<commit_after>#!/usr/bin/env node

// TODO: package up as an NPM module so it can be -g installed and run from path with node

const fs = require('fs');
const path = require('path');
const args = require('args');

args
  .option('infile', 'Filename to read kindle quotes, default is quotes.txt', 'quotes.txt')
  .option('outfile', 'Filename to write JSON, default is quotes.json', 'quotes.json')
  .option('dirname', 'Path to write outfile to, default is pwd', __dirname)
  .option('no-reorder', 'Prevent re-ordering author names from "Surname, Name" to "Name Surname"');

const flags = args.parse(process.argv);

/////////////
// helpers //
/////////////

function stripBOM(str) { return str.replace(/[\u200B-\u200D\uFEFF]/g, ''); }
function parseTitle(str) { return str.match(/.+(?=\s\()/)[0]; }
function swapWords(w1, w2) { return `${w2} ${w1}`; }
function last(arr) { return arr[arr.length - 1]; }
function isEmpty(x) { return x === '' || x == null; }
function isDuplicate(a, b) { return a === b; }

/**
 * Reduce all occurrences of multiple spaces to a single space char.
 * So that '      ' becomes ' '
 * @param  {String} str
 * @return {String}
 */
function contractSpaces(str) { return str.replace(/\s{2,}/g, ' '); }

/**
 *  re-order names in the format of "surname, name" to "name surname"
 * @param  {String} str String containing more than one name
 * @return {String}     Re-ordered name
 */
function orderNames(str) { return /,/.test(str) ? swapWords(...str.split(/,\s?/)) : str; }

function parseAuthor(str) {
  // capture author names from string format: "Book title (maybe with parens) (AUTHOR NAMES)"
  const re = /(?:\((?!.*\())(.+)(?:\))/;

  // match names, and split any multiple authors delineated by ";" and format as Firstname Last
  let authors = str.match(re)[1].split(/;\s?/);
  if (!flags.n) authors = authors.map(orderNames);
  return authors.join(', ');
}

// TODO: use moment.js or roll-your-own date parsing into a proper JS Date() object.
function parseDate(str) {
  // kindle human readable dates follow 'on ' and end with ' HH:MM:SS'
  // NOTE: keep the time in string if parsing to a JS date
  const re = /\son\s(.*)(?=\s\d\d:)/;

  return str.match(re)[1];
}

function parseLine(prev, quote, index) {
  const [header, date, content] = quote.trim().split(/\s?\n\s?/);

  if (isEmpty(content) || prev.length && isDuplicate(content, last(prev).content)) return prev;

  return prev.concat({
    title: parseTitle(header),
    author: parseAuthor(header),
    date: parseDate(date),
    // Some of my quotes had huge chunks of spaces - probably from epub to mobi conversions?
    content: contractSpaces(content),
  });
}

function buildJSON(data) {
  // entries are separated with ==========
  const kindleQuoteBreak = /={2,}/;
  const clippings = data.split(kindleQuoteBreak).reduce(parseLine, []);

  return JSON.stringify(clippings);
}

/////////////////////
// main logic here //
/////////////////////

fs.readFile(flags.infile, 'utf8', (err, data) => {
  if (err) throw err;

  const dest = path.join(flags.dirname, flags.outfile);
  const clippings = buildJSON(data);

  fs.writeFile(dest, clippings, (writeErr) => {
    if (writeErr) {
      throw writeErr;
    } else console.log(`Output quotes to ${dest}`);
  });
});
<|endoftext|>


<commit_before>// ControllerRouter class

'use strict';

var includes             = require('es5-ext/array/#/contains')
  , customError          = require('es5-ext/error/custom')
  , identity             = require('es5-ext/function/identity')
  , assign               = require('es5-ext/object/assign')
  , ensureCallable       = require('es5-ext/object/valid-callable')
  , ensureObject         = require('es5-ext/object/valid-object')
  , ensureStringifiable  = require('es5-ext/object/validate-stringifiable-value')
  , forEach              = require('es5-ext/object/for-each')
  , endsWith             = require('es5-ext/string/#/ends-with')
  , d                    = require('d')
  , lazy                 = require('d/lazy')
  , isPromise            = require('is-promise')
  , compareDynamicRoutes = require('./lib/compare-dynamic-routes')
  , isStatic             = require('./lib/is-token-static')
  , resolvePathMeta      = require('./lib/resolve-path-meta')
  , ensurePath           = require('./lib/ensure-path')

  , push = Array.prototype.push, slice = Array.prototype.slice, apply = Function.prototype.apply
  , create = Object.create, defineProperty = Object.defineProperty, stringify = JSON.stringify
  , routeCallIdIndex = 0;

var ControllerRouter = module.exports = Object.defineProperties(function (routes/*, options*/) {
	var options;
	// Validate initialization
	if (!(this instanceof ControllerRouter)) return new ControllerRouter(routes, arguments[1]);
	options = Object(arguments[1]);
	this.constructor.ensureRoutes(routes, options);

	if (options.eventProto != null) {
		// Override default event prototype
		defineProperty(this, '_eventProto', d(ensureObject(options.eventProto)));
	}

	defineProperty(this, 'routes', d(routes));

	// Configure internal routes map
	forEach(this.constructor.normalizeRoutes(routes, options), function (conf, path) {
		var pathData = resolvePathMeta(path);
		if (pathData.static) {
			this._staticRoutes[path] = conf;
			return;
		}
		if (!this._dynamicRoutes[pathData.tokens.length]) {
			this._dynamicRoutes[pathData.tokens.length] = [];
		}
		pathData.conf = conf;
		pathData.matchPositionsLength = pathData.matchPositions.length;
		this._dynamicRoutes[pathData.tokens.length].push(pathData);
	}, this);
	forEach(this._dynamicRoutes, function (data) { data.sort(compareDynamicRoutes); });

	// Whether route should resolve with promise or not
	if (options.promiseResultImplementation) {
		defineProperty(this, 'Promise', d(ensureCallable(options.promiseResultImplementation)));
	}
}, {
	// Validates provided routes map
	ensureRoutes: d(function (routes) {
		forEach(ensureObject(routes), function (conf, path) {
			var isDynamic;
			ensureObject(conf);
			ensurePath(path);
			if (path !== '/') isDynamic = !path.split('/').every(isStatic);
			if (typeof conf === 'function') {
				if (isDynamic) {
					throw customError("Missing match function for " + stringify(path), 'MISSING_MATCH');
				}
				return;
			}
			if (typeof conf.controller !== 'function') {
				throw customError("Invalid controller for " + stringify(path), 'INVALID_CONTROLLER');
			}
			if (typeof conf.match !== 'function') {
				if (isDynamic) {
					throw customError("Invalid match function for " + stringify(path), 'INVALID_MATCH');
				}
				return;
			}
			if (!isDynamic) {
				throw customError("Missing regular expression in path " + stringify(path),
					'MISSING_PATH_REGEX');
			}
		});
		return routes;
	}),
	// Normalizes routes to bare ControllerRouter format. If ControllerRouter extension
	// provides more sophisticated routes format, this should be a function which transforms it
	// directly to map as understood by ControllerRouter
	normalizeRoutes: d(identity)
});

Object.defineProperties(ControllerRouter.prototype, assign({
	_resolveResult: d(function (result) {
		return this.Promise ? this.Promise.resolve(result) : result;
	}),
	// Routes path to controller
	route: d(function (path/*, …controllerArgs*/) {
		var args = [create(this._eventProto)];
		push.apply(args, arguments);
		return this.routeEvent.apply(this, args);
	}),
	// Routes path to controller and provides an event to be used for controller invocation
	routeEvent: d(function (event, path/*, …controllerArgs*/) {
		var pathTokens, controllerArgs = slice.call(arguments, 2), conf, initConf, controller
		  , asyncResult, callId = ++routeCallIdIndex;

		ensureObject(event);
		path = ensureStringifiable(path);

		// Preprepare route data
		this.lastRouteData = { event: event };

		// Do not proceed for no path
		if (!path) return this._resolveResult(false);

		// Resolve path for route resolution
		if (path[0] === '/') path = path.slice(1);
		if (endsWith.call(path, '/')) path = path.slice(0, -1);
		event.path = path || '/';

		// Handle eventual static path
		conf = this._staticRoutes[path || '/'];
		if (conf) {
			initConf = this.routes[path || '/'];
			controller = conf.controller || conf;
			this.lastRouteData.conf =  initConf;
			this.lastRouteData.result = apply.call(controller, event, controllerArgs);
			return this._resolveResult(this.lastRouteData);
		}

		// Handle eventual dynamic paths
		pathTokens = path.split('/');
		if (!this._dynamicRoutes[pathTokens.length]) return this._resolveResult(false);
		this._dynamicRoutes[pathTokens.length].some(function (data) {
			var args = [], matchResult;

			// Check whether path matches
			if (!data.tokens.every(function (token, index) {
					var pathToken = pathTokens[index];
					if (includes.call(data.matchPositions, index)) {
						if (!token.test(pathToken)) return false;
						args.push(pathToken);
						return true;
					}
					return (token === pathToken);
				})) {
				return false;
			}

			// Path matches, now resolve with `match` function
			matchResult = data.conf.match.apply(event, args);
			if (isPromise(matchResult)) {
				asyncResult = matchResult.then(function (isMatch) {
					if (!isMatch) return false;
					this.lastRouteData = {
						event: event,
						conf: this.routes[data.path]
					};
					if (callId !== routeCallIdIndex) {
						// Cancel route (as promises are concerned we need to reject)
						throw customError("Route cancelled, as next one took action", 'OUTDATED_ROUTE_CALL');
					}
					this.lastRouteData.result = apply.call(data.conf.controller, event, controllerArgs);
					return this.lastRouteData;
				}.bind(this));
			} else if (matchResult) {
				conf = data.conf;
				initConf = this.routes[data.path];
			}
			return true;
		}, this);

		// If `match` is asynchronous return promise
		if (asyncResult) return asyncResult;
		if (!conf) return this._resolveResult(false);
		this.lastRouteData.conf = initConf;
		this.lastRouteData.result = apply.call(conf.controller, event, controllerArgs);
		return this._resolveResult(this.lastRouteData);
	}),
	// Default prototype for an route event
	_eventProto: d(Object.prototype)
}, lazy({
	// Internal map of dynamic routes (those that contain regexp tokens)
	_dynamicRoutes: d(function () { return create(null); }),
	// Internal map of static routes (no regexp tokens)
	_staticRoutes: d(function () { return create(null); })
})));
<commit_msg>feat: ensure wait for eventual promise resolution<commit_after>// ControllerRouter class

'use strict';

var includes             = require('es5-ext/array/#/contains')
  , customError          = require('es5-ext/error/custom')
  , identity             = require('es5-ext/function/identity')
  , constant             = require('es5-ext/function/constant')
  , assign               = require('es5-ext/object/assign')
  , ensureCallable       = require('es5-ext/object/valid-callable')
  , ensureObject         = require('es5-ext/object/valid-object')
  , ensureStringifiable  = require('es5-ext/object/validate-stringifiable-value')
  , forEach              = require('es5-ext/object/for-each')
  , endsWith             = require('es5-ext/string/#/ends-with')
  , d                    = require('d')
  , lazy                 = require('d/lazy')
  , isPromise            = require('is-promise')
  , compareDynamicRoutes = require('./lib/compare-dynamic-routes')
  , isStatic             = require('./lib/is-token-static')
  , resolvePathMeta      = require('./lib/resolve-path-meta')
  , ensurePath           = require('./lib/ensure-path')

  , push = Array.prototype.push, slice = Array.prototype.slice, apply = Function.prototype.apply
  , create = Object.create, defineProperty = Object.defineProperty, stringify = JSON.stringify
  , routeCallIdIndex = 0;

var ControllerRouter = module.exports = Object.defineProperties(function (routes/*, options*/) {
	var options;
	// Validate initialization
	if (!(this instanceof ControllerRouter)) return new ControllerRouter(routes, arguments[1]);
	options = Object(arguments[1]);
	this.constructor.ensureRoutes(routes, options);

	if (options.eventProto != null) {
		// Override default event prototype
		defineProperty(this, '_eventProto', d(ensureObject(options.eventProto)));
	}

	defineProperty(this, 'routes', d(routes));

	// Configure internal routes map
	forEach(this.constructor.normalizeRoutes(routes, options), function (conf, path) {
		var pathData = resolvePathMeta(path);
		if (pathData.static) {
			this._staticRoutes[path] = conf;
			return;
		}
		if (!this._dynamicRoutes[pathData.tokens.length]) {
			this._dynamicRoutes[pathData.tokens.length] = [];
		}
		pathData.conf = conf;
		pathData.matchPositionsLength = pathData.matchPositions.length;
		this._dynamicRoutes[pathData.tokens.length].push(pathData);
	}, this);
	forEach(this._dynamicRoutes, function (data) { data.sort(compareDynamicRoutes); });

	// Whether route should resolve with promise or not
	if (options.promiseResultImplementation) {
		defineProperty(this, 'Promise', d(ensureCallable(options.promiseResultImplementation)));
	}
}, {
	// Validates provided routes map
	ensureRoutes: d(function (routes) {
		forEach(ensureObject(routes), function (conf, path) {
			var isDynamic;
			ensureObject(conf);
			ensurePath(path);
			if (path !== '/') isDynamic = !path.split('/').every(isStatic);
			if (typeof conf === 'function') {
				if (isDynamic) {
					throw customError("Missing match function for " + stringify(path), 'MISSING_MATCH');
				}
				return;
			}
			if (typeof conf.controller !== 'function') {
				throw customError("Invalid controller for " + stringify(path), 'INVALID_CONTROLLER');
			}
			if (typeof conf.match !== 'function') {
				if (isDynamic) {
					throw customError("Invalid match function for " + stringify(path), 'INVALID_MATCH');
				}
				return;
			}
			if (!isDynamic) {
				throw customError("Missing regular expression in path " + stringify(path),
					'MISSING_PATH_REGEX');
			}
		});
		return routes;
	}),
	// Normalizes routes to bare ControllerRouter format. If ControllerRouter extension
	// provides more sophisticated routes format, this should be a function which transforms it
	// directly to map as understood by ControllerRouter
	normalizeRoutes: d(identity)
});

Object.defineProperties(ControllerRouter.prototype, assign({
	_resolveResult: d(function (result) {
		if (result && isPromise(result.result)) return result.result.then(constant(result));
		return this.Promise ? this.Promise.resolve(result) : result;
	}),
	// Routes path to controller
	route: d(function (path/*, …controllerArgs*/) {
		var args = [create(this._eventProto)];
		push.apply(args, arguments);
		return this.routeEvent.apply(this, args);
	}),
	// Routes path to controller and provides an event to be used for controller invocation
	routeEvent: d(function (event, path/*, …controllerArgs*/) {
		var pathTokens, controllerArgs = slice.call(arguments, 2), conf, initConf, controller
		  , asyncResult, callId = ++routeCallIdIndex;

		ensureObject(event);
		path = ensureStringifiable(path);

		// Preprepare route data
		this.lastRouteData = { event: event };

		// Do not proceed for no path
		if (!path) return this._resolveResult(false);

		// Resolve path for route resolution
		if (path[0] === '/') path = path.slice(1);
		if (endsWith.call(path, '/')) path = path.slice(0, -1);
		event.path = path || '/';

		// Handle eventual static path
		conf = this._staticRoutes[path || '/'];
		if (conf) {
			initConf = this.routes[path || '/'];
			controller = conf.controller || conf;
			this.lastRouteData.conf =  initConf;
			this.lastRouteData.result = apply.call(controller, event, controllerArgs);
			return this._resolveResult(this.lastRouteData);
		}

		// Handle eventual dynamic paths
		pathTokens = path.split('/');
		if (!this._dynamicRoutes[pathTokens.length]) return this._resolveResult(false);
		this._dynamicRoutes[pathTokens.length].some(function (data) {
			var args = [], matchResult;

			// Check whether path matches
			if (!data.tokens.every(function (token, index) {
					var pathToken = pathTokens[index];
					if (includes.call(data.matchPositions, index)) {
						if (!token.test(pathToken)) return false;
						args.push(pathToken);
						return true;
					}
					return (token === pathToken);
				})) {
				return false;
			}

			// Path matches, now resolve with `match` function
			matchResult = data.conf.match.apply(event, args);
			if (isPromise(matchResult)) {
				asyncResult = matchResult.then(function (isMatch) {
					if (!isMatch) return false;
					this.lastRouteData = {
						event: event,
						conf: this.routes[data.path]
					};
					if (callId !== routeCallIdIndex) {
						// Cancel route (as promises are concerned we need to reject)
						throw customError("Route cancelled, as next one took action", 'OUTDATED_ROUTE_CALL');
					}
					this.lastRouteData.result = apply.call(data.conf.controller, event, controllerArgs);
					return this._resolveResult(this.lastRouteData);
				}.bind(this));
			} else if (matchResult) {
				conf = data.conf;
				initConf = this.routes[data.path];
			}
			return true;
		}, this);

		// If `match` is asynchronous return promise
		if (asyncResult) return asyncResult;
		if (!conf) return this._resolveResult(false);
		this.lastRouteData.conf = initConf;
		this.lastRouteData.result = apply.call(conf.controller, event, controllerArgs);
		return this._resolveResult(this.lastRouteData);
	}),
	// Default prototype for an route event
	_eventProto: d(Object.prototype)
}, lazy({
	// Internal map of dynamic routes (those that contain regexp tokens)
	_dynamicRoutes: d(function () { return create(null); }),
	// Internal map of static routes (no regexp tokens)
	_staticRoutes: d(function () { return create(null); })
})));
<|endoftext|>


<commit_before>module.exports = {
    extends: [
        "plugin:react/recommended",
        "plugin:@typescript-eslint/recommended",
        "prettier/@typescript-eslint",
        'plugin:@typescript-eslint/eslint-recommended'
    ].map(require.resolve),
    rules: {
        indent: [
            2, 4,
            { SwitchCase: 1 },
        ],
        camelcase: 0,
        yoda: 'off',
        'no-plusplus': ['error', { 'allowForLoopAfterthoughts': true }],
        'padded-blocks': ['error', { 'classes': 'always', 'blocks': 'never', 'switches': 'never' }],
        'key-spacing': [2, {
            singleLine: {
                beforeColon: false,
                afterColon:  true
            },
            multiLine: {
                beforeColon: false,
                afterColon:  true,
                mode: 'minimum'
            }
        }],
        'max-len': [ 'error', 100, 2, {
            ignoreUrls: true,
            ignoreComments: true,
            ignoreRegExpLiterals: true,
            ignoreStrings: true,
            ignoreTemplateLiterals: true,
        }],
        'import/prefer-default-export': 'off',
        'default-case': 0,
        'function-paren-newline': ['error', 'consistent'],
        'class-methods-use-this': 0,
        'no-underscore-dangle': 0,
        'import/no-unresolved': 0,
        'import/extensions': 0,
        'react/jsx-uses-vars': [2],
        'react/jsx-indent': [2, 4],
        'react/jsx-indent-props': [0, 4],
        'react/forbid-prop-types': 0,
        'no-unused-vars': [2, {'varsIgnorePattern': '_+'}],
        'react/prefer-stateless-function': [2, { ignorePureComponents: true }],
        'import/no-extraneous-dependencies': [0, { devDependencies: true }],
        'no-param-reassign': ['error', { 'props': false }],
        'object-curly-newline': ['error', { 'consistent': true }],
        'no-multi-spaces': [2, {
            exceptions: {
                Identifier: true,
                ClassProperty: true,
                ImportDeclaration: true,
                VariableDeclarator: true,
                AssignmentExpression: true,
                JSXAttribute: true,
                JSXIdentifier: true,
                JSXOpeningElement: true,
                JSXClosingElement: true,
            },
        }],
        "import/prefer-default-export": "off",
        "default-case": 0,
        "func-names:": 0,
        "space-before-function-paren": 0,
        "react/prop-types": 0,
        "react/jsx-handler-names": 0,
        "react/jsx-fragments": 0,
        "react/no-unused-prop-types": 0,
        "import/export": 0,
        "@typescript-eslint/no-use-before-define": "off",
        "@typescript-eslint/no-unused-vars": ["error"],
        "@typescript-eslint/no-non-null-assertion": 'off',
        "@typescript-eslint/no-explicit-any": "off",
        "@typescript-eslint/explicit-function-return-type": "off",
        "comma-dangle": ["error", {
            "arrays": "always-multiline",
            "objects": "always-multiline",
            "imports": "always-multiline",
            "exports": "always-multiline",
            "functions": "always-multiline"
        }],
        "lines-between-class-members": ["error", "always", { "exceptAfterSingleLine": true }],
        "semi": ["error", "never"],
    },
    globals: {
        fetch: false
    },
    plugins: [
        'react',
        'jsx-a11y',
        'import',
    ],
    parser: 'babel-eslint',
    parserOptions: {
        ecmaFeatures: {
            'experimentalObjectRestSpread': true,
            'jsx': true
        },
        sourceType: 'module'
    },
    env: {
        browser: true,
        es6: true
    },
};
<commit_msg>don't require, remoe prettier<commit_after>module.exports = {
    extends: [
        "plugin:react/recommended",
        "plugin:@typescript-eslint/recommended",
        'plugin:@typescript-eslint/eslint-recommended',
    ],
    rules: {
        indent: [
            2, 4,
            { SwitchCase: 1 },
        ],
        camelcase: 0,
        yoda: 'off',
        'no-plusplus': ['error', { 'allowForLoopAfterthoughts': true }],
        'padded-blocks': ['error', { 'classes': 'always', 'blocks': 'never', 'switches': 'never' }],
        'key-spacing': [2, {
            singleLine: {
                beforeColon: false,
                afterColon:  true
            },
            multiLine: {
                beforeColon: false,
                afterColon:  true,
                mode: 'minimum'
            }
        }],
        'max-len': [ 'error', 100, 2, {
            ignoreUrls: true,
            ignoreComments: true,
            ignoreRegExpLiterals: true,
            ignoreStrings: true,
            ignoreTemplateLiterals: true,
        }],
        'import/prefer-default-export': 'off',
        'default-case': 0,
        'function-paren-newline': ['error', 'consistent'],
        'class-methods-use-this': 0,
        'no-underscore-dangle': 0,
        'import/no-unresolved': 0,
        'import/extensions': 0,
        'react/jsx-uses-vars': [2],
        'react/jsx-indent': [2, 4],
        'react/jsx-indent-props': [0, 4],
        'react/forbid-prop-types': 0,
        'no-unused-vars': [2, {'varsIgnorePattern': '_+'}],
        'react/prefer-stateless-function': [2, { ignorePureComponents: true }],
        'import/no-extraneous-dependencies': [0, { devDependencies: true }],
        'no-param-reassign': ['error', { 'props': false }],
        'object-curly-newline': ['error', { 'consistent': true }],
        'no-multi-spaces': [2, {
            exceptions: {
                Identifier: true,
                ClassProperty: true,
                ImportDeclaration: true,
                VariableDeclarator: true,
                AssignmentExpression: true,
                JSXAttribute: true,
                JSXIdentifier: true,
                JSXOpeningElement: true,
                JSXClosingElement: true,
            },
        }],
        "import/prefer-default-export": "off",
        "default-case": 0,
        "func-names:": 0,
        "space-before-function-paren": 0,
        "react/prop-types": 0,
        "react/jsx-handler-names": 0,
        "react/jsx-fragments": 0,
        "react/no-unused-prop-types": 0,
        "import/export": 0,
        "@typescript-eslint/no-use-before-define": "off",
        "@typescript-eslint/no-unused-vars": ["error"],
        "@typescript-eslint/no-non-null-assertion": 'off',
        "@typescript-eslint/no-explicit-any": "off",
        "@typescript-eslint/explicit-function-return-type": "off",
        "comma-dangle": ["error", {
            "arrays": "always-multiline",
            "objects": "always-multiline",
            "imports": "always-multiline",
            "exports": "always-multiline",
            "functions": "always-multiline"
        }],
        "lines-between-class-members": ["error", "always", { "exceptAfterSingleLine": true }],
        "semi": ["error", "never"],
    },
    globals: {
        fetch: false
    },
    plugins: [
        'react',
        'jsx-a11y',
        'import',
    ],
    parser: 'babel-eslint',
    parserOptions: {
        ecmaFeatures: {
            'experimentalObjectRestSpread': true,
            'jsx': true
        },
        sourceType: 'module'
    },
    env: {
        browser: true,
        es6: true
    },
};
<|endoftext|>


<commit_before>var pairs = require('./pairs')
var bytewise = require('./bytewise')
var pl    = require('pull-level')
var pull  = require('pull-stream')
var toStream = require('pull-stream-to-stream')
var safeRegex = require('safe-regex')

function isString (s) {
  return 'string' === typeof s
}

var encode = bytewise.encode
var decode = bytewise.decode

module.exports = function (db, indexDb) {

  function hasPath (obj, keys) {
    var _keys = keys.slice()
    while(_keys.length) {
      var k = _keys.shift()
      if(k === obj && !_keys.length)
        return true
      if (isRegExp(k)) {
        if (_keys.length === 0) return k.test(obj)
        if (typeof obj !== 'object') return false
        var okeys = Object.keys(obj)
        for(var i = 0, l = okeys.length; i < l; i++) {
          if (k.test(okeys[i])) break
        }
        if (i === l) return false
        obj = obj[okeys[i]]
        continue
      }
      if(k === true && Array.isArray(obj)) {
        for(var i = 0, l = obj.length; i < l; i++) {
          var el = obj[i]
          if(hasPath(el, _keys))
            return true
        }
      }
      if('undefined' === typeof obj[k])
        return false
      else
        obj = obj[k]
    }
    return true
  }

  if('string' === typeof indexDb)
    indexDb = db.sublevel(indexDb)

  function indexer (key, value) {
    return [[key, value]]
  }

  indexDb.indexer = indexer

  function createIndex (op, add) {
    var keys = pairs(op.value, indexer)
    keys.forEach(function (e) {
      var f = e.slice(), g = e.slice()
      e.push(op.key)
      add({key: encode(e), value: '0', type: 'put', prefix: indexDb})
    })
  }

  db.pre(createIndex)

  indexDb.rebuild = function (cb) {
    pull(
      pl.read(db),
      pull.map(function (op) {
        var batch = []
        createIndex(op, function (ch) {
          batch.push(ch)
        })
        return batch
      }),
      pull.flatten(),
      pl.write(indexDb, cb)
    )
  }

  indexDb.explain = function (keys) {
    var k = keys.slice().reverse()
//    .filter(function (e) { return e !== true })

    while(k.length > 1 && (!isString(k[0]) || !isString(k[1]))) {
      k.shift()
    }

    var query = k.slice(0, 2).reverse() //.reverse()

    var min = query.slice()
    var max = query.slice()

    min.push(null)      //minimum
    max.push(undefined) //maximum

    return {
      values: false,
      _min: min, _max: max,
      min: encode(min),
      max: encode(max)
    }
  }

  indexDb.createSearchStream = function (keys, opts) {
    return toStream(null, indexDb.search(keys, opts))
  }

  indexDb.search = function (keys, _opts) {
    //get the last two items that are usable as an index.
    // [string, string]
    // example... if pattern is ["dependencies", "optimist", true]
    // then retrive all modules that depend on optimist
    var opts = indexDb.explain(keys)
    opts.reverse = _opts && _opts.reverse
    opts.limit = _opts && _opts.limit

    for(var i = 0, l = keys.length; i < l; i++) {
      if (isRegExp(keys[i]) && !safeRegex(keys[i])) {
        return function (_, cb) {
          return cb(new Error('unsafe regular expression'))
        }
      }
    }
    return pull(
      pl.read(indexDb, opts),
      pull.map(function (key) {
        return decode(key)
      }),
      pull.map(function (data) {
        return data;
      }),
      pull.unique(function (key) {
        return key[key.length - 1];
      }),
      pull.asyncMap(function (key, cb) {
        var k = key.pop()
        db.get(k, function (err, val) {
          cb(err, {key: k, value: val, index: key})
        })
      }),
      pull.filter(function (data) {
        return hasPath(data.value, keys)
      }),
      pull.map(function (data) {
        if(_opts && _opts.keys == false)
          return data.value
        else if(_opts && _opts.values == false)
          return data.key
        return data
      })
    )
  }

  return indexDb
}

function isRegExp (x) { return {}.toString.call(x) === '[object RegExp]' }
<commit_msg>fixed the non-leaf regex case<commit_after>var pairs = require('./pairs')
var bytewise = require('./bytewise')
var pl    = require('pull-level')
var pull  = require('pull-stream')
var toStream = require('pull-stream-to-stream')
var safeRegex = require('safe-regex')

function isString (s) {
  return 'string' === typeof s
}

var encode = bytewise.encode
var decode = bytewise.decode

module.exports = function (db, indexDb) {

  function hasPath (obj, keys) {
    var _keys = keys.slice()
    while(_keys.length) {
      var k = _keys.shift()
      if(k === obj && !_keys.length)
        return true
      if (isRegExp(k)) {
        if (_keys.length === 0 && k.test(obj)) return true

        if (typeof obj !== 'object') return false
        var okeys = Object.keys(obj)
        for(var i = 0, l = okeys.length; i < l; i++) {
          if (k.test(okeys[i])) break
        }
        if (i === l) return false
        obj = obj[okeys[i]]
        continue
      }
      if(k === true && Array.isArray(obj)) {
        for(var i = 0, l = obj.length; i < l; i++) {
          var el = obj[i]
          if(hasPath(el, _keys))
            return true
        }
      }
      if('undefined' === typeof obj[k])
        return false
      else
        obj = obj[k]
    }
    return true
  }

  if('string' === typeof indexDb)
    indexDb = db.sublevel(indexDb)

  function indexer (key, value) {
    return [[key, value]]
  }

  indexDb.indexer = indexer

  function createIndex (op, add) {
    var keys = pairs(op.value, indexer)
    keys.forEach(function (e) {
      var f = e.slice(), g = e.slice()
      e.push(op.key)
      add({key: encode(e), value: '0', type: 'put', prefix: indexDb})
    })
  }

  db.pre(createIndex)

  indexDb.rebuild = function (cb) {
    pull(
      pl.read(db),
      pull.map(function (op) {
        var batch = []
        createIndex(op, function (ch) {
          batch.push(ch)
        })
        return batch
      }),
      pull.flatten(),
      pl.write(indexDb, cb)
    )
  }

  indexDb.explain = function (keys) {
    var k = keys.slice().reverse()
//    .filter(function (e) { return e !== true })

    while(k.length > 1 && (!isString(k[0]) || !isString(k[1]))) {
      k.shift()
    }

    var query = k.slice(0, 2).reverse() //.reverse()

    var min = query.slice()
    var max = query.slice()

    min.push(null)      //minimum
    max.push(undefined) //maximum

    return {
      values: false,
      _min: min, _max: max,
      min: encode(min),
      max: encode(max)
    }
  }

  indexDb.createSearchStream = function (keys, opts) {
    return toStream(null, indexDb.search(keys, opts))
  }

  indexDb.search = function (keys, _opts) {
    //get the last two items that are usable as an index.
    // [string, string]
    // example... if pattern is ["dependencies", "optimist", true]
    // then retrive all modules that depend on optimist
    var opts = indexDb.explain(keys)
    opts.reverse = _opts && _opts.reverse
    opts.limit = _opts && _opts.limit

    for(var i = 0, l = keys.length; i < l; i++) {
      if (isRegExp(keys[i]) && !safeRegex(keys[i])) {
        return function (_, cb) {
          return cb(new Error('unsafe regular expression'))
        }
      }
    }
    return pull(
      pl.read(indexDb, opts),
      pull.map(function (key) {
        return decode(key)
      }),
      pull.map(function (data) {
        return data;
      }),
      pull.unique(function (key) {
        return key[key.length - 1];
      }),
      pull.asyncMap(function (key, cb) {
        var k = key.pop()
        db.get(k, function (err, val) {
          cb(err, {key: k, value: val, index: key})
        })
      }),
      pull.filter(function (data) {
        return hasPath(data.value, keys)
      }),
      pull.map(function (data) {
        if(_opts && _opts.keys == false)
          return data.value
        else if(_opts && _opts.values == false)
          return data.key
        return data
      })
    )
  }

  return indexDb
}

function isRegExp (x) { return {}.toString.call(x) === '[object RegExp]' }
<|endoftext|>


<commit_before>$(document).ready(function () {
    var times = [
        {
            Section: 9,
            Day: "T",
            StartTime: 1600,
            Type: "Lab",
            TAs: ["Taz Thenell", "Lily Shellhammer", "Xiaomeng Li"]
        },
        {
            Section: 10,
            Day: "T",
            StartTime: 800,
            Type: "Lab",
            TAs: ["Aidan Carson", "Katherine Bajno", "Alex Niebur"]
        },
        {
            Section: 11,
            Day: "W",
            StartTime: 800,
            Type: "Lab",
            TAs: ["Shannon Ernst", "Austin Row", "Mason Sidebottom"]
        },
        {
            Section: 12,
            Day: "W",
            StartTime: 1200,
            Type: "Lab",
            TAs: ["Megan McCormick", "Daniel Grocki", "Xiaomeng Li"]
        },
        {
            Section: 13,
            Day: "R",
            StartTime: 1000,
            Type: "Lab",
            TAs: ["Austin Row", "Nathan Burnett", "Kyle Nichols"]
        },
        {
            Section: 14,
            Day: "R",
            StartTime: 1200,
            Type: "Lab",
            TAs: ["Jeff Wentz", "Zoe Steine-Hanson", "Austin Row"]
        },
        {
            Section: 15,
            Day: "R",
            StartTime: 800,
            Type: "Lab",
            TAs: ["Philip Carroll", "Katherine Bajno", "Steven Gloyd"]
},
        {
            Section: 16,
            Day: "W",
            StartTime: 1000,
            Type: "Lab",
            TAs: ["Jake Fenger", "Ernie Bodle","Cierra Shawe"]
        },
        {
            Section: 17,
            Day: "F",
            StartTime: 800,
            Type: "Lab",
            TAs: ["Billy Buffum", "Shannon Ernst", "Jia Chen"]
        },
        {
            Section: 18,
            Day: "F",
            StartTime: 1000,
            Type: "Lab",
            TAs: ["Connor Christensen", "Louis Duvoisin", "Lucas Campos-Davis"]
        },
        {
            Section: 19,
            Day: "M",
            StartTime: 800,
            Type: "Lab",
            TAs: ["Robert Rosenberger", "Courtney Miller", "Dan Van Horn"]
        },
        {
            Section: 20,
            Day: "M",
            StartTime: 1000,
            Type: "Lab",
            TAs: ["Kyle Nichols", "Courtney Miller", "Connor Christensen"]
        },
        {
            Section: 21,
            Day: "M",
            StartTime: 1200,
            Type: "Lab",
            TAs: ["Mikky Cecil", "Seth Gipe", "Daniel Grocki"]
        },
        {
            Section: 22,
            Day: "M",
            StartTime: 1400,
            Type: "Lab",
            TAs: ["Mikky Cecil", "Matthew Lohr", "Billy Buffum"]
        },
        {
            Section: 23,
            Day: "M",
            StartTime: 1600,
            Type: "Lab",
            TAs: ["Matthew Lohr", "Zoe Steine-Hanson", "Louis Duvoisin"]
        }
];

    function convert24to12hour(hour) {
        var twelveHour = hour;
        var ampm = "";
        if (hour > 1200) {
            twelveHour -= 1200;
            ampm = "pm";
        } else if (hour == 1200) {
            twelveHour = 1200;
            ampm = "pm";
        } else {
            ampm = "am";
        }
        var hours = Math.floor(twelveHour / 100)
        var minutes = twelveHour - (hours * 100);
        if (minutes === 0) {
            return (hours).toString() + ":00" + ampm;
        }
        return (hours).toString() + ":" + minutes + ampm;
    }

    var table = '
';
    table += "
Section	Day	Time	TA's
";

    for (var x = 0; x < times.length; x++) {
        table += "
";
        table += "" + times[x]["Section"] + "	";
        table += "" + times[x]["Day"] + "	";
        table += "" + convert24to12hour(times[x]["StartTime"]) + " - ";
        table += convert24to12hour(times[x]["StartTime"] + 150) + "	";
        table += '';
        for (var y = 0; y < (times[x]["TAs"].length); y++) {
            table += "
" + times[x]["TAs"][y] + "
";
        }
        table += "	";
        table += "
";
    }
    table += "
";
    $(".labs").append(table);
});<commit_msg>added the new TA list for labs and the jQuery code for making a hamburger list<commit_after>$(document).ready(function () {
    $(".hamburger").click(function(){
        $(this).toggleClass("is-active");
        $("nav").slideToggle();
    });

    var times = [
        {
            Section: 10,
            Day: "T",
            StartTime: 1600,
            Type: "Lab",
            TAs: ["Alex Niebur", "Natalie Suderman", "Xiaomeng Li"]
        },
        {
            Section: 11,
            Day: "W",
            StartTime: 1800,
            Type: "Lab",
            TAs: ["Louis Duvoisin", "Megan McCormick", "Josh Diedrich"]
        },
        {
            Section: 12,
            Day: "R",
            StartTime: 800,
            Type: "Lab",
            TAs: ["Zoe Steine-Hanson", "Daniel Grocki", "Lucas Campos-Davis"]
        },
        {
            Section: 13,
            Day: "R",
            StartTime: 1000,
            Type: "Lab",
            TAs: ["Courtney Miller", "Ernie Bodle", "Jia Chen"]
        },
        {
            Section: 14,
            Day: "T",
            StartTime: 1200,
            Type: "Lab",
			TAs: ["Carl Beery", "Aidan Carson", "Lucas Campos-Davis"]
        },
        {
            Section: 15,
            Day: "T",
            StartTime: 1000,
            Type: "Lab",
            TAs: ["Kyle Nichols", "Courtney Miller", "Zoe Steine-Hanson"]
        },
        {
            Section: 16,
            Day: "F",
            StartTime: 1400,
            Type: "Lab",
            TAs: ["Alex Niebur", "Katherine Bajno", "Aidan Carson"]
        },
        {
            Section: 17,
            Day: "W",
            StartTime: 1600,
            Type: "Lab",
            TAs: ["Jake Fenger", "Cierra Shawe", "Chongxian Chen"]
        },
        {
            Section: 18,
            Day: "W",
            StartTime: 1200,
            Type: "Lab",
            TAs: ["Kyle Nichols", "Ernie Bodle", "Cierra Shawe"]
        },
        {
            Section: 19,
            Day: "R",
            StartTime: 1600,
            Type: "Lab",
            TAs: ["Jake Fenger", "Natalie Suderman", "Xiaomeng Li"]
        },
        {
            Section: 20,
            Day: "R",
            StartTime: 1400,
            Type: "Lab",
            TAs: ["Megan McCormick", "Louis Duvoisin", "Dan Van Horn"]
        },
        {
            Section: 21,
            Day: "F",
            StartTime: 1100,
            Type: "Lab",
            TAs: ["Matthew Lohr", "Daniel Grocki", "Chongxian Chen"]
        }
];

    function convert24to12hour(hour) {
        var twelveHour = hour;
        var ampm = "";
        if (hour > 1200) {
            twelveHour -= 1200;
            ampm = "pm";
        } else if (hour == 1200) {
            twelveHour = 1200;
            ampm = "pm";
        } else {
            ampm = "am";
        }
        var hours = Math.floor(twelveHour / 100)
        var minutes = twelveHour - (hours * 100);
        if (minutes === 0) {
            return (hours).toString() + ":00" + ampm;
        }
        return (hours).toString() + ":" + minutes + ampm;
    }

    var table = '
';
    table += "
Section	Day	Time	TA's
";

    for (var x = 0; x < times.length; x++) {
        table += "
";
        table += "" + times[x]["Section"] + "	";
        table += "" + times[x]["Day"] + "	";
        table += "" + convert24to12hour(times[x]["StartTime"]) + " - ";
        table += convert24to12hour(times[x]["StartTime"] + 150) + "	";
        table += '';
        for (var y = 0; y < (times[x]["TAs"].length); y++) {
            table += "
" + times[x]["TAs"][y] + "
";
        }
        table += "	";
        table += "
";
    }
    table += "
";
    $(".labs").append(table);
});<|endoftext|>


<commit_before>/**
 * Parse a time string and return the number value of it.
 *
 * @param {String} ms Time string.
 * @returns {Number}
 * @api private
 */
module.exports = function millisecond(ms) {
  'use strict';

  if ('string' !== typeof ms || '0' === ms || +ms) return +ms;

  var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|wks?|w|years?|yrs?|y)?$/i.exec(ms)
    , second = 1000
    , minute = second * 60
    , hour = minute * 60
    , day = hour * 24
    , week = day * 7
    , year = day * 365
    , amount;

  if (!match) return 0;

  amount = parseFloat(match[1]);

  switch (match[2].toLowerCase()) {
    case 'years':
    case 'year':
    case 'yrs':
    case 'yr':
    case 'y':
      return amount * year;

    case 'weeks':
    case 'week':
    case 'wks':
    case 'wk':
    case 'w':
      return amount * week;

    case 'days':
    case 'day':
    case 'd':
      return amount * day;

    case 'hours':
    case 'hour':
    case 'hrs':
    case 'hr':
    case 'h':
      return amount * hour;

    case 'minutes':
    case 'minute':
    case 'mins':
    case 'min':
    case 'm':
      return amount * minute;

    case 'seconds':
    case 'second':
    case 'secs':
    case 'sec':
    case 's':
      return amount * second;

    default:
      return amount;
  }
};
<commit_msg>[minor] Compute the time units only once<commit_after>'use strict';

var regex = new RegExp('^((?:\\d+)?\\.?\\d+) *('+ [
  'milliseconds?',
  'msecs?',
  'ms',
  'seconds?',
  'secs?',
  's',
  'minutes?',
  'mins?',
  'm',
  'hours?',
  'hrs?',
  'h',
  'days?',
  'd',
  'weeks?',
  'wks?',
  'w',
  'years?',
  'yrs?',
  'y'
].join('|') +')?$', 'i');

var second = 1000
  , minute = second * 60
  , hour = minute * 60
  , day = hour * 24
  , week = day * 7
  , year = day * 365;

/**
 * Parse a time string and return the number value of it.
 *
 * @param {String} ms Time string.
 * @returns {Number}
 * @api private
 */
module.exports = function millisecond(ms) {
  if ('string' !== typeof ms || '0' === ms || +ms) return +ms;

  var match = regex.exec(ms)
    , amount;

  if (!match) return 0;

  amount = parseFloat(match[1]);

  switch (match[2].toLowerCase()) {
    case 'years':
    case 'year':
    case 'yrs':
    case 'yr':
    case 'y':
      return amount * year;

    case 'weeks':
    case 'week':
    case 'wks':
    case 'wk':
    case 'w':
      return amount * week;

    case 'days':
    case 'day':
    case 'd':
      return amount * day;

    case 'hours':
    case 'hour':
    case 'hrs':
    case 'hr':
    case 'h':
      return amount * hour;

    case 'minutes':
    case 'minute':
    case 'mins':
    case 'min':
    case 'm':
      return amount * minute;

    case 'seconds':
    case 'second':
    case 'secs':
    case 'sec':
    case 's':
      return amount * second;

    default:
      return amount;
  }
};
<|endoftext|>


<commit_before>'use strict'

var BezierEasing = require('bezier-easing')

var _ = exports.utils = {
    $: function (selector) {
        return document.querySelector(selector)
    },
    on: function (element, events, handler) {
        if (!(events instanceof Array)) {
            events = [events]
        }
        for (var i = 0; i < events.length; i++) {
            element.addEventListener(events[i], handler)
        }
    },
    off: function (element, events, handler) {
        if (!(events instanceof Array)) {
            events = [events]
        }
        for (var i = 0; i < events.length; i++) {
            element.removeEventListener(events[i], handler)
        }
    }
}

exports.install = function (Vue) {
    function handleClick(e) {
        e.preventDefault()

        if (typeof this.value === 'object') {
          exports.scrollTo(this.value.el || this.value.element , this.value.duration || 500, {
            easing: this.value.easing || exports.easing['ease'],
            offset: this.value.offset || 0
          })
        } else {
          exports.scrollTo(this.value, 500, {
            easing: exports.easing['ease']
          })
        }
    }

    Vue.directive('scroll-to', {
        bind: function (el, binding) {
            _.on(el, 'click', handleClick.bind(binding))
        },
        unbind: function (el) {
            _.off(el, 'click', handleClick)
        }
    })
}

exports.scrollTo = function (element, duration, options) {
    if(typeof element === 'string') {
        element = _.$(element)
    }

    var page = _.$('html, body')
    var events = ['scroll', 'mousedown', 'wheel', 'DOMMouseScroll', 'mousewheel', 'keyup', 'touchmove']
    var abort = false

    var abortFn = function () {
        abort = true
    }

    _.on(page, events, abortFn)

    var initialY = window.pageYOffset
    var elementY = initialY + element.getBoundingClientRect().top
    var targetY = document.body.scrollHeight - elementY < window.innerHeight ? document.body.scrollHeight - window.innerHeight : elementY

    if (options.offset) {
        targetY += options.offset
    }

    var diff = targetY - initialY
    var easing = BezierEasing.apply(BezierEasing, options.easing)
    var start

    var done = function () {
        _.off(page, events, abortFn)
    }

    if (!diff) return

    window.requestAnimationFrame(function step(timestamp) {
        if (abort) return done()
        if (!start) start = timestamp

        var time = timestamp - start
        var progress = Math.min(time / duration, 1)
        progress = easing(progress)

        window.scrollTo(0, initialY + diff * progress)

        if (time < duration) {
            window.requestAnimationFrame(step)
        } else {
            done()
        }
    })
}

exports.easing = {
    'ease': [0.25, 0.1, 0.25, 1.0],
    'linear': [0.00, 0.0, 1.00, 1.0],
    'ease-in': [0.42, 0.0, 1.00, 1.0],
    'ease-out': [0.00, 0.0, 0.58, 1.0],
    'ease-in-out': [0.42, 0.0, 0.58, 1.0]
}
<commit_msg>Allow using easing names too<commit_after>'use strict'

var BezierEasing = require('bezier-easing')

var _ = exports.utils = {
    $: function (selector) {
        return document.querySelector(selector)
    },
    on: function (element, events, handler) {
        if (!(events instanceof Array)) {
            events = [events]
        }
        for (var i = 0; i < events.length; i++) {
            element.addEventListener(events[i], handler)
        }
    },
    off: function (element, events, handler) {
        if (!(events instanceof Array)) {
            events = [events]
        }
        for (var i = 0; i < events.length; i++) {
            element.removeEventListener(events[i], handler)
        }
    }
}

exports.install = function (Vue) {
    function handleClick(e) {
        e.preventDefault()

        if (typeof this.value === 'object') {
          exports.scrollTo(this.value.el || this.value.element , this.value.duration || 500, {
            easing: (typeof this.value.easing === 'string' ? exports.easing[this.value.easing] : this.value.easing) || exports.easing['ease'],
            offset: this.value.offset || 0
          })
        } else {
          exports.scrollTo(this.value, 500, {
            easing: exports.easing['ease']
          })
        }
    }

    Vue.directive('scroll-to', {
        bind: function (el, binding) {
            _.on(el, 'click', handleClick.bind(binding))
        },
        unbind: function (el) {
            _.off(el, 'click', handleClick)
        }
    })
}

exports.scrollTo = function (element, duration, options) {
    if(typeof element === 'string') {
        element = _.$(element)
    }

    var page = _.$('html, body')
    var events = ['scroll', 'mousedown', 'wheel', 'DOMMouseScroll', 'mousewheel', 'keyup', 'touchmove']
    var abort = false

    var abortFn = function () {
        abort = true
    }

    _.on(page, events, abortFn)

    var initialY = window.pageYOffset
    var elementY = initialY + element.getBoundingClientRect().top
    var targetY = document.body.scrollHeight - elementY < window.innerHeight ? document.body.scrollHeight - window.innerHeight : elementY

    if (options.offset) {
        targetY += options.offset
    }

    var diff = targetY - initialY
    var easing = BezierEasing.apply(BezierEasing, options.easing)
    var start

    var done = function () {
        _.off(page, events, abortFn)
    }

    if (!diff) return

    window.requestAnimationFrame(function step(timestamp) {
        if (abort) return done()
        if (!start) start = timestamp

        var time = timestamp - start
        var progress = Math.min(time / duration, 1)
        progress = easing(progress)

        window.scrollTo(0, initialY + diff * progress)

        if (time < duration) {
            window.requestAnimationFrame(step)
        } else {
            done()
        }
    })
}

exports.easing = {
    'ease': [0.25, 0.1, 0.25, 1.0],
    'linear': [0.00, 0.0, 1.00, 1.0],
    'ease-in': [0.42, 0.0, 1.00, 1.0],
    'ease-out': [0.00, 0.0, 0.58, 1.0],
    'ease-in-out': [0.42, 0.0, 0.58, 1.0]
}
<|endoftext|>


<commit_before>var parser = require('js-yaml')
var optionalByteOrderMark = '\\ufeff?'
var pattern = '^(' +
  optionalByteOrderMark +
  '(= yaml =|---)' +
  '$([\\s\\S]*?)' +
  '^(?:\\2|\\.\\.\\.)\\s*' +
  '$' +
  (process.platform === 'win32' ? '\\r?' : '') +
  '(?:\\n)?)'
// NOTE: If this pattern uses the 'g' flag the `regex` variable definition will
// need to be moved down into the functions that use it.
var regex = new RegExp(pattern, 'm')

module.exports = extractor
module.exports.test = test

function extractor (string) {
  string = string || ''

  var lines = string.split(/(\r?\n)/)
  if (lines[0] && /= yaml =|---/.test(lines[0])) {
    return parse(string)
  } else {
    return { attributes: {}, body: string }
  }
}

function parse (string) {
  var match = regex.exec(string)

  if (!match) {
    return {
      attributes: {},
      body: string
    }
  }

  var yaml = match[match.length - 1].replace(/^\s+|\s+$/g, '')
  var attributes = parser.load(yaml) || {}
  var body = string.replace(match[0], '')

  return { attributes: attributes, body: body, frontmatter: yaml }
}

function test (string) {
  string = string || ''

  return regex.test(string)
}
<commit_msg>Fix for environments without process var<commit_after>var parser = require('js-yaml')
var optionalByteOrderMark = '\\ufeff?'
var platform = typeof process !== 'undefined' ? process.platform : ''
var pattern = '^(' +
  optionalByteOrderMark +
  '(= yaml =|---)' +
  '$([\\s\\S]*?)' +
  '^(?:\\2|\\.\\.\\.)\\s*' +
  '$' +
  (platform === 'win32' ? '\\r?' : '') +
  '(?:\\n)?)'
// NOTE: If this pattern uses the 'g' flag the `regex` variable definition will
// need to be moved down into the functions that use it.
var regex = new RegExp(pattern, 'm')

module.exports = extractor
module.exports.test = test

function extractor (string) {
  string = string || ''

  var lines = string.split(/(\r?\n)/)
  if (lines[0] && /= yaml =|---/.test(lines[0])) {
    return parse(string)
  } else {
    return { attributes: {}, body: string }
  }
}

function parse (string) {
  var match = regex.exec(string)

  if (!match) {
    return {
      attributes: {},
      body: string
    }
  }

  var yaml = match[match.length - 1].replace(/^\s+|\s+$/g, '')
  var attributes = parser.load(yaml) || {}
  var body = string.replace(match[0], '')

  return { attributes: attributes, body: body, frontmatter: yaml }
}

function test (string) {
  string = string || ''

  return regex.test(string)
}
<|endoftext|>


<commit_before>'use strict';
/* global browser, expect, element, by, EC */
/* eslint new-cap: 0 */ // --> OFF for Given, When, Then

/*
 * Created by marketionist on 13.11.2016
 */
// #############################################################################

// Use the external Chai As Promised to deal with resolving promises in
// expectations
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const fs = require('fs');
const protractor = require('protractor');
const censor = require('./utils/helpers.js').censor;
const util = require('util');
const errors = require('./utils/errors.js');

chai.use(chaiAsPromised);
let expect = chai.expect;
let EC = protractor.ExpectedConditions;
let defaultCustomTimeout = 5000;
let customTimeout = browser.params.customTimeout || defaultCustomTimeout;
let pageObjects = browser.params.pageObjects;
let timeToWaitMax = 300100; // Maximum time to wait for in 'I wait for (\d+) ms' step

module.exports = function () {
    /**
     * Waits for the element to be present and displayed on the page
     * @param {string} elementSelector
     */
    function waitForDisplayed(elementSelector) {
        browser.wait(EC.presenceOf(elementSelector), customTimeout,
            errors.PRESENT);
    }
    /**
     * Composes proper element locator for fuether actions
     * @param {string} page
     * @param {string} elem
     * @returns {object} elmnt
     */
    function composeLocator(page, elem) {
        let locator = pageObjects[page][elem];
        let elmnt;

        if (locator[0] + locator[1] === '//') {
            elmnt = element(by.xpath(locator));
        } else {
            elmnt = element(by.css(locator));
        }

        return elmnt;
    }

    // #### When steps #############################################################

    this.When(/^I go to URL "([^"]*)"$/, function (url, callback) {
        browser.get(url);
        callback();
    });

    this.When(/^I go to "([^"]*)"."([^"]*)"$/, function (page, elem, callback) {
        let url = pageObjects[page][elem];

        browser.get(url);
        callback();
    });

    this.When(/^I click "([^"]*)"."([^"]*)"$/, function (page, elem, callback) {
        let elmnt = composeLocator(page, elem);

        waitForDisplayed(elmnt);
        browser.wait(EC.elementToBeClickable(elmnt), customTimeout,
            `"${pageObjects[page][elem]}" ${errors.CLICKABLE}`);
        elmnt.click();
        callback();
    });

    this.When(/^I wait and click "([^"]*)"."([^"]*)"$/, function (page, elem, callback) {
        let elmnt = composeLocator(page, elem);
        let timeToWait = 300;

        waitForDisplayed(elmnt);
        browser.wait(EC.elementToBeClickable(elmnt), customTimeout,
            `"${pageObjects[page][elem]}" ${errors.CLICKABLE}`);
        setTimeout(function () {
            elmnt.click();
            callback();
        }, timeToWait);
    });

    this.When(/^I click "([^"]*)"."([^"]*)" if present$/, function (page, elem, callback) {
        let elmnt = composeLocator(page, elem);

        elmnt.isPresent().then(function (isPresent) {
            if (isPresent) {
                // Click only if element is present
                elmnt.click();
            }
            callback();
        });
    });

    this.When(/^I wait for (\d+) ms$/, { timeout: timeToWaitMax }, function (timeToWait, callback) {
        setTimeout(callback, timeToWait);
    });

    this.When(/^I type "([^"]*)" in the "([^"]*)"."([^"]*)"$/, function (
            text, page, elem, callback) {
        let inputField = composeLocator(page, elem);

        waitForDisplayed(inputField);
        browser.wait(EC.elementToBeClickable(inputField), customTimeout,
            `${pageObjects[page][elem]} ${errors.CLICKABLE}`);
        browser.actions().mouseMove(inputField).click().perform();
        inputField.sendKeys(text);
        callback();
    });

    this.When(/^I type "([^"]*)"."([^"]*)" in the "([^"]*)"."([^"]*)"$/, function (
            page1, element1, page2, element2, callback) {
        let inputField = composeLocator(page2, element2);

        waitForDisplayed(inputField);
        browser.wait(EC.elementToBeClickable(inputField), customTimeout,
            `${pageObjects[page2][element2]} ${errors.CLICKABLE}`);
        browser.actions().mouseMove(inputField).click().perform();
        inputField.sendKeys(pageObjects[page1][element1]);
        callback();
    });

    // #### Then steps #############################################################

    this.Then(/the title should equal to "([^"]*)"$/, function (text, callback) {
        expect(browser.getTitle()).to.eventually.equal(text).and.notify(callback);
    });

    this.Then(/^"([^"]*)"."([^"]*)" should be present$/, function (page, elem, callback) {
        let elmnt = composeLocator(page, elem);

        expect(elmnt.isPresent()).to.eventually.equal(true).and.notify(callback);
    });

    this.Then(/^"([^"]*)"."([^"]*)" has text "([^"]*)"$/, function (page, elem, text, callback) {
        let elmnt = composeLocator(page, elem);

        expect(elmnt.getText()).to.eventually.equal(text).and.notify(callback);
    });

    this.Then(/^"([^"]*)"."([^"]*)" has text "([^"]*)"."([^"]*)"$/, function (
            page1, element1, page2, element2, callback) {
        let elmnt = composeLocator(page1, element1);
        let text = pageObjects[page2][element2];

        expect(elmnt.getText()).to.eventually.equal(text).and.notify(callback);
    });

    // Take a callback as an additional argument to execute when the step is done
    this.Then(/^the file "([^"]*)" is empty$/, function (fileName, callback) {
        fs.readFile(fileName, 'utf8', function (error, contents) {
            if (error) {
                callback(error);
            } else {
                expect(contents).to.eventually.equal('').and.notify(callback);
            }
        });
    });

};
<commit_msg>Added '... should not be present' step<commit_after>'use strict';
/* global browser, expect, element, by, EC */
/* eslint new-cap: 0 */ // --> OFF for Given, When, Then

/*
 * Created by marketionist on 13.11.2016
 */
// #############################################################################

// Use the external Chai As Promised to deal with resolving promises in
// expectations
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const fs = require('fs');
const protractor = require('protractor');
const censor = require('./utils/helpers.js').censor;
const errors = require('./utils/errors.js');

chai.use(chaiAsPromised);
let expect = chai.expect;
let EC = protractor.ExpectedConditions;
let defaultCustomTimeout = 5000;
let customTimeout = browser.params.customTimeout || defaultCustomTimeout;
let pageObjects = browser.params.pageObjects;
let timeToWaitMax = 300100; // Maximum time to wait for in 'I wait for (\d+) ms' step

module.exports = function () {
    /**
     * Waits for the element to be present and displayed on the page
     * @param {string} elementSelector
     */
    function waitForDisplayed(elementSelector) {
        browser.wait(EC.presenceOf(elementSelector), customTimeout,
            errors.PRESENT);
    }
    /**
     * Composes proper element locator for fuether actions
     * @param {string} page
     * @param {string} elem
     * @returns {object} elmnt
     */
    function composeLocator(page, elem) {
        let locator = pageObjects[page][elem];
        let elmnt;

        if (locator[0] + locator[1] === '//') {
            elmnt = element(by.xpath(locator));
        } else {
            elmnt = element(by.css(locator));
        }

        return elmnt;
    }

    // #### When steps #############################################################

    this.When(/^I go to URL "([^"]*)"$/, function (url, callback) {
        browser.get(url);
        callback();
    });

    this.When(/^I go to "([^"]*)"."([^"]*)"$/, function (page, elem, callback) {
        let url = pageObjects[page][elem];

        browser.get(url);
        callback();
    });

    this.When(/^I click "([^"]*)"."([^"]*)"$/, function (page, elem, callback) {
        let elmnt = composeLocator(page, elem);

        waitForDisplayed(elmnt);
        browser.wait(EC.elementToBeClickable(elmnt), customTimeout,
            `"${pageObjects[page][elem]}" ${errors.CLICKABLE}`);
        elmnt.click();
        callback();
    });

    this.When(/^I wait and click "([^"]*)"."([^"]*)"$/, function (page, elem, callback) {
        let elmnt = composeLocator(page, elem);
        let timeToWait = 300;

        waitForDisplayed(elmnt);
        browser.wait(EC.elementToBeClickable(elmnt), customTimeout,
            `"${pageObjects[page][elem]}" ${errors.CLICKABLE}`);
        setTimeout(function () {
            elmnt.click();
            callback();
        }, timeToWait);
    });

    this.When(/^I click "([^"]*)"."([^"]*)" if present$/, function (page, elem, callback) {
        let elmnt = composeLocator(page, elem);

        elmnt.isPresent().then(function (isPresent) {
            if (isPresent) {
                // Click only if element is present
                elmnt.click();
            }
            callback();
        });
    });

    this.When(/^I wait for (\d+) ms$/, { timeout: timeToWaitMax }, function (timeToWait, callback) {
        setTimeout(callback, timeToWait);
    });

    this.When(/^I type "([^"]*)" in the "([^"]*)"."([^"]*)"$/, function (
            text, page, elem, callback) {
        let inputField = composeLocator(page, elem);

        waitForDisplayed(inputField);
        browser.wait(EC.elementToBeClickable(inputField), customTimeout,
            `${pageObjects[page][elem]} ${errors.CLICKABLE}`);
        browser.actions().mouseMove(inputField).click().perform();
        inputField.sendKeys(text);
        callback();
    });

    this.When(/^I type "([^"]*)"."([^"]*)" in the "([^"]*)"."([^"]*)"$/, function (
            page1, element1, page2, element2, callback) {
        let inputField = composeLocator(page2, element2);

        waitForDisplayed(inputField);
        browser.wait(EC.elementToBeClickable(inputField), customTimeout,
            `${pageObjects[page2][element2]} ${errors.CLICKABLE}`);
        browser.actions().mouseMove(inputField).click().perform();
        inputField.sendKeys(pageObjects[page1][element1]);
        callback();
    });

    // #### Then steps #############################################################

    this.Then(/the title should equal to "([^"]*)"$/, function (text, callback) {
        expect(browser.getTitle()).to.eventually.equal(text).and.notify(callback);
    });

    this.Then(/^"([^"]*)"."([^"]*)" should be present$/, function (page, elem, callback) {
        let elmnt = composeLocator(page, elem);

        expect(elmnt.isPresent()).to.eventually.equal(true).and.notify(callback);
    });

    this.Then(/^"([^"]*)"."([^"]*)" should not be present$/, function (page, elem, callback) {
        let elmnt = composeLocator(page, elem);

        expect(elmnt.isPresent()).to.eventually.equal(false).and.notify(callback);
    });

    this.Then(/^"([^"]*)"."([^"]*)" has text "([^"]*)"$/, function (page, elem, text, callback) {
        let elmnt = composeLocator(page, elem);

        expect(elmnt.getText()).to.eventually.equal(text).and.notify(callback);
    });

    this.Then(/^"([^"]*)"."([^"]*)" has text "([^"]*)"."([^"]*)"$/, function (
            page1, element1, page2, element2, callback) {
        let elmnt = composeLocator(page1, element1);
        let text = pageObjects[page2][element2];

        expect(elmnt.getText()).to.eventually.equal(text).and.notify(callback);
    });

    // Take a callback as an additional argument to execute when the step is done
    this.Then(/^the file "([^"]*)" is empty$/, function (fileName, callback) {
        fs.readFile(fileName, 'utf8', function (error, contents) {
            if (error) {
                callback(error);
            } else {
                expect(contents).to.eventually.equal('').and.notify(callback);
            }
        });
    });

};
<|endoftext|>