<commit_before>/*!
 * datastructures-js
 * index (main module object)
 * Copyright(c) 2015 Eyas Ranjous <eyas@eyasranjous.info>
 * MIT Licensed
 */

'use strict';

module.exports = (function() {

    var self = {};

    var getObject = function(ds, args) {
        return require('./lib/' + ds).apply(this, args).export();
    };

    self.stack = function() {
        return getObject('stack');
    };

    self.queue = function() {
        return getObject('queue');
    };

    self.priorityQueue = function() {
        return getObject('priorityQueue');
    };

    self.set = function() {
        return getObject('set');
    };

    self.linkedList = function() {
        return getObject('linkedList');
    };

    self.doublyLinkedList = function() {
        return getObject('doublyLinkedList');
    };

    self.hashtable = function() {
        return getObject('hashtable');
    };

    self.binarySearchTree = function() {
        return getObject('binarySearchTree');
    };

    self.directedGraph = function() {
        return getObject('directedGraph');
    };

    return self;

}());<commit_msg>use dependency container in the main module<commit_after>/*!
 * datastructures-js
 * index (main module object)
 * Copyright(c) 2015 Eyas Ranjous <eyas@eyasranjous.info>
 * MIT Licensed
 */

'use strict';

var di = require('./di');

module.exports = (function() {

    var self = {};

    self.stack = function() {
        var stack = di.getFactory('ds', 'stack')();
        return di.exportObject(stack);
    };

    self.queue = function() {
        var queue = di.getFactory('ds', 'queue')();
        return di.exportObject(queue);
    };

    self.priorityQueue = function() {
        var priorityQueue = di.getPriorityQueueFactory()();
        return di.exportObject(priorityQueue);
    };

    self.set = function() {
        var set = di.getSetFactory()();
        return di.exportObject(set);
    };

    self.linkedList = function() {
        var linkedList = di.getLinkedListFactory()();
        return di.exportObject(linkedList);
    };

    self.doublyLinkedList = function() {
        var doublyLinkedList = di.getDoublyLinkedListFactory()();
        return di.exportObject(doublyLinkedList);
    };

    self.hashtable = function() {
        var hashtable = di.getHashtableFactory()();
        return di.exportObject(hashtable);
    };

    self.binarySearchTree = function() {
        var binarySearchTree = di.getBinarySearchTreeFactory()();
        return di.exportObject(binarySearchTree);
    };

    self.directedGraph = function() {
       var directedGraph = di.getFactory('ds', 'directedGraph')();
        return di.exportObject(directedGraph);
    };

    return self;

}());<|endoftext|>


<commit_before>var http = require('http');
var fs = require('fs');
var concat = require('concat-stream');
var voicebox = require('voicebox-karaoke');
var ecstatic = require('ecstatic')({ root: __dirname + '/public' });

http.createServer(function (req, res) {
  console.log('%s', req.url);

  if (req.url === '/bump') {
    req.pipe(concat(function (data) {
      var parts = /roomId=([\w]+)\&song=([\d]+)/.exec('' + data);
      console.log('%s | %s @ %s', req.url, parts[1], parts[2]);
      var client = voicebox(parts[1]);
      client.bump(parts[2]);

      res.writeHead(200);
      res.end();
    }));
    return;
  }

  if (req.url === '/queue') {
    req.pipe(concat(function (data) {
      var client = voicebox(data.roomId);
      client.addSong(data.song);
      res.writeHead(200);
      res.end();
    }));
    return;
  }

  ecstatic(req, res);

}).listen(3000);<commit_msg>[fix] wtf<commit_after>var http = require('http');
var fs = require('fs');
var concat = require('concat-stream');
var voicebox = require('voicebox-karaoke');
var ecstatic = require('ecstatic')({ root: __dirname + '/public' });

var server = http.createServer(function (req, res) {
  console.log('%s', req.url);

  if (req.url === '/bump') {
    req.pipe(concat(function (data) {
      var parts = /roomId=([\w]+)\&song=([\d]+)/.exec('' + data);
      console.log('%s | %s @ %s', req.url, parts[1], parts[2]);
      var client = voicebox(parts[1]);
      client.bump(parts[2]);

      res.writeHead(200);
      res.end();
    }));
    return;
  }

  if (req.url === '/queue') {
    req.pipe(concat(function (data) {
      var client = voicebox(data.roomId);
      client.addSong(data.song);
      res.writeHead(200);
      res.end();
    }));
    return;
  }

  ecstatic(req, res);

});

setTimeout(function () {
  server.listen(3000);
}, 2000)
<|endoftext|>


<commit_before>'use strict'

import amqp from 'amqplib'

export default class AMQPExchange {

  constructor({ channel, name }) {
    this._channel = channel
    this._name = name
    const _this = this
    this._channel.on('close', () => _this.onClose())
    this._channel.on('error', err => _this.onError(err))
    this._channel.on('return', msg => _this.onReturn(msg))
    this._channel.on('drain', () => _this.onDrain())
  }

/**
  * @method url
  * @description This method must be overriden to specify the url connection
  * @throws Error by default if it's not implemented
  * @returns String containing the url of AMQP server
  * @author Antonio Saad
*/
  static get url() {
    throw new Error('You must implement the `static get url()` getter method, returning a string with the url to connect to AMQP server')
  }

/**
  * @method socketOptions
  * @description This method can be overriden to specify options for the socket connection.
  * For more info, check: http://www.squaremobius.net/amqp.node/channel_api.html#connect
  * @returns undefined by default, otherwise it must return a JSON with the options
  * @author Antonio Saad
*/
  static get socketOptions() {
    return undefined
  }

/**
  * @method type
  * @description This method must be overriden to specify a valid type of exchange (direct, fanout, topic)
  * @throws Error by default if it's not implemented
  * @returns String specifying a valid type of exchange
  * @author Antonio Saad
*/
  get type() {
    throw new Error('You must implement the `get type()` getter method, returning a valid type of exchange')
  }

/**
  * @method bindings
  * @description This method can be overriden to specify bindings to another exchanges
  * @returns Array of JSON objects with the following structure:
  * [
  *   {
  *      routingKey: "routing key pattern"
  *      source: "exchange name which wants to join",
  *      args: { OPTIONAL }
  *   },
  *   ...
  * ]
  * @author Antonio Saad
*/
  get bindings() {
    return []
  }

/**
  * @method options
  * @description This method can be overriden to specify a JSON with options for creating the channel.
  * For more info, check: http://www.squaremobius.net/amqp.node/channel_api.html#channel_assertExchange
  * @returns undefined by default, otherwise it must return a JSON
  * @author Antonio Saad
*/
  get options() {
    return undefined
  }

/**
  * @method FANOUT
  * @description returns a valid type of exchange, it can be used as return value
  * when overriding `static get type()` method
  * @returns String 'fanout'
  * @author Antonio Saad
*/
  static get FANOUT() {
    return 'fanout'
  }

/**
  * @method DIRECT
  * @description returns a valid type of exchange, it can be used as return value
  * when overriding `static get type()` method
  * @returns String 'direct'
  * @author Antonio Saad
*/
  static get DIRECT() {
    return 'direct'
  }

/**
  * @method TOPIC
  * @description returns a valid type of exchange, it can be used as return value
  * when overriding `static get type()` method
  * @returns String 'topic'
  * @author Antonio Saad
*/
  static get TOPIC() {
    return 'topic'
  }

/**
  * @method channel
  * @description AMQP native channel
  * @returns Object to handle the underlying channel provided by the API.
  * For more info, check: http://www.squaremobius.net/amqp.node/channel_api.html#channel
  * @author Antonio Saad
*/
  get channel() {
    return this._channel
  }

/**
  * @method name
  * @description Exchange's name. It'll be the name of the child class
  * @returns string containing the exchange's name
  * @author Antonio Saad
*/
  get name() {
    return this._name
  }

/**
  * @method closeChannel
  * @description Closes the channel
  * @param cb Callback to execute after the channel is closed.
  * It has the following format: function(err) {...}
  * @returns Promise if no callback specified
  * @author Antonio Saad
*/
  closeChannel(cb) {
    return this._channel.close(cb)
  }

/**
  * @method destroy
  * @description Delete an exchange from the AMQP server
  * @param opts The only meaningful field is:
              - ifUnused (boolean): if true and the exchange has bindings,
                it will not be deleted and the channel will be closed.
  * @returns Promise
  * @author Antonio Saad
*/
  destroy(opts) {
    return this._channel.deleteExchange(this._name, opts)
  }

/**
  * @method unbindFrom
  * @description Remove a binding to another exchange
  * @param exchangeName String source exchange name
  * @param pattern String Routing key pattern
  * @param args Object arguments extension
  * @param cb Callback to execute after exchange binding has been removed
  * It has the following format: function(err, ok) {...}
  * @returns Promise if no cb specified
  * @author Antonio Saad
*/
  unbindFrom(exchangeName, pattern, args, cb) {
    return this._channel.unbindExchange(this._name, exchangeName, pattern, args, cb)
  }

/**
  * @method publish
  * @description Publish a message
  * @param routingKey String Pattern to route the message to the appropiate queues
  * @param content Buffer Message to publish
  * @param opts JSON special parameters.
  For more info, check: http://www.squaremobius.net/amqp.node/channel_api.html#channel_publish
  * @returns Promise
  * @author Antonio Saad
*/
  publish(routingKey, content, opts) {
    return this._channel.publish(this._name, routingKey, content, opts)
  }

/**
  * @method onClose
  * @description Invoked when channel has  been clossed
  * @author Antonio Saad
*/
  onClose() {

  }

/**
  * @method onError
  * @description Invoked when the server closes the channel for any reason
  * @param err Object containing the error
  * @author Antonio Saad
*/
  onError(err) {

  }

/**
  * @method onReturn
  * @description Invoked when the published message cannot be routed
  * @param msg Buffer the returned message
  * @author Antonio Saad
*/
  onReturn(msg) {

  }
/**
  * @method onDrain
  * @description Invoked once the write buffer has been emptied (i.e., once it is
  * ready for writes again)
  * @author Antonio Saad
  */
  onDrain() {

  }

/**
  * @method beforeCreateChannel
  * @description Invoked before creating the channel for this exchange
  * @param conn Object Connection to the AMQP server.
  * WARNING: This connection is the underlying socket shared between all the
  * created channels, so any change will affect all channels
  * @author Antonio Saad
*/
  static *beforeCreateChannel(conn) {

  }

}
<commit_msg>Solved syntax issues<commit_after>'use strict'

module.exports = class AMQPExchange {

  constructor(channel, name) {
    this._channel = channel
    this._name = name
    const _this = this
    this._channel.on('close', () => _this.onClose())
    this._channel.on('error', err => _this.onError(err))
    this._channel.on('return', msg => _this.onReturn(msg))
    this._channel.on('drain', () => _this.onDrain())
  }

/**
  * @method url
  * @description This method must be overriden to specify the url connection
  * @throws Error by default if it's not implemented
  * @returns String containing the url of AMQP server
  * @author Antonio Saad
*/
  static get url() {
    throw new Error('You must implement the `static get url()` getter method, returning a string with the url to connect to AMQP server')
  }

/**
  * @method socketOptions
  * @description This method can be overriden to specify options for the socket connection.
  * For more info, check: http://www.squaremobius.net/amqp.node/channel_api.html#connect
  * @returns undefined by default, otherwise it must return a JSON with the options
  * @author Antonio Saad
*/
  static get socketOptions() {
    return undefined
  }

/**
  * @method type
  * @description This method must be overriden to specify a valid type of exchange (direct, fanout, topic)
  * @throws Error by default if it's not implemented
  * @returns String specifying a valid type of exchange
  * @author Antonio Saad
*/
  get type() {
    throw new Error('You must implement the `get type()` getter method, returning a valid type of exchange')
  }

/**
  * @method bindings
  * @description This method can be overriden to specify bindings to another exchanges
  * @returns Array of JSON objects with the following structure:
  * [
  *   {
  *      routingKey: "routing key pattern"
  *      source: "exchange name which wants to join",
  *      args: { OPTIONAL }
  *   },
  *   ...
  * ]
  * @author Antonio Saad
*/
  get bindings() {
    return []
  }

/**
  * @method options
  * @description This method can be overriden to specify a JSON with options for creating the channel.
  * For more info, check: http://www.squaremobius.net/amqp.node/channel_api.html#channel_assertExchange
  * @returns undefined by default, otherwise it must return a JSON
  * @author Antonio Saad
*/
  get options() {
    return undefined
  }

/**
  * @method FANOUT
  * @description returns a valid type of exchange, it can be used as return value
  * when overriding `static get type()` method
  * @returns String 'fanout'
  * @author Antonio Saad
*/
  static get FANOUT() {
    return 'fanout'
  }

/**
  * @method DIRECT
  * @description returns a valid type of exchange, it can be used as return value
  * when overriding `static get type()` method
  * @returns String 'direct'
  * @author Antonio Saad
*/
  static get DIRECT() {
    return 'direct'
  }

/**
  * @method TOPIC
  * @description returns a valid type of exchange, it can be used as return value
  * when overriding `static get type()` method
  * @returns String 'topic'
  * @author Antonio Saad
*/
  static get TOPIC() {
    return 'topic'
  }

/**
  * @method channel
  * @description AMQP native channel
  * @returns Object to handle the underlying channel provided by the API.
  * For more info, check: http://www.squaremobius.net/amqp.node/channel_api.html#channel
  * @author Antonio Saad
*/
  get channel() {
    return this._channel
  }

/**
  * @method name
  * @description Exchange's name. It'll be the name of the child class
  * @returns string containing the exchange's name
  * @author Antonio Saad
*/
  get name() {
    return this._name
  }

/**
  * @method closeChannel
  * @description Closes the channel
  * @param cb Callback to execute after the channel is closed.
  * It has the following format: function(err) {...}
  * @returns Promise if no callback specified
  * @author Antonio Saad
*/
  closeChannel(cb) {
    return this._channel.close(cb)
  }

/**
  * @method destroy
  * @description Delete an exchange from the AMQP server
  * @param opts The only meaningful field is:
              - ifUnused (boolean): if true and the exchange has bindings,
                it will not be deleted and the channel will be closed.
  * @returns Promise
  * @author Antonio Saad
*/
  destroy(opts) {
    return this._channel.deleteExchange(this._name, opts)
  }

/**
  * @method unbindFrom
  * @description Remove a binding to another exchange
  * @param exchangeName String source exchange name
  * @param pattern String Routing key pattern
  * @param args Object arguments extension
  * @param cb Callback to execute after exchange binding has been removed
  * It has the following format: function(err, ok) {...}
  * @returns Promise if no cb specified
  * @author Antonio Saad
*/
  unbindFrom(exchangeName, pattern, args, cb) {
    return this._channel.unbindExchange(this._name, exchangeName, pattern, args, cb)
  }

/**
  * @method publish
  * @description Publish a message
  * @param routingKey String Pattern to route the message to the appropiate queues
  * @param content Buffer Message to publish
  * @param opts JSON special parameters.
  For more info, check: http://www.squaremobius.net/amqp.node/channel_api.html#channel_publish
  * @returns Promise
  * @author Antonio Saad
*/
  publish(routingKey, content, opts) {
    return this._channel.publish(this._name, routingKey, content, opts)
  }

/**
  * @method onClose
  * @description Invoked when channel has  been clossed
  * @author Antonio Saad
*/
  onClose() {

  }

/**
  * @method onError
  * @description Invoked when the server closes the channel for any reason
  * @param err Object containing the error
  * @author Antonio Saad
*/
  onError(err) {

  }

/**
  * @method onReturn
  * @description Invoked when the published message cannot be routed
  * @param msg Buffer the returned message
  * @author Antonio Saad
*/
  onReturn(msg) {

  }
/**
  * @method onDrain
  * @description Invoked once the write buffer has been emptied (i.e., once it is
  * ready for writes again)
  * @author Antonio Saad
  */
  onDrain() {

  }

/**
  * @method beforeCreateChannel
  * @description Invoked before creating the channel for this exchange
  * @param conn Object Connection to the AMQP server.
  * WARNING: This connection is the underlying socket shared between all the
  * created channels, so any change will affect all channels
  * @author Antonio Saad
*/
  static *beforeCreateChannel(conn) {

  }

}
<|endoftext|>


<commit_before>/*jshint -W097 */
'use strict';

var LOG_ID = 'find-npm-assets';
var NODE_MODULES_DIR = 'node_modules';
var PACKAGE_INFO = 'package.json';

var path = require('path');
var gutil = require('gulp-util');

var verbose = false;
var assets = [];

module.exports = {
    load: load
};

if (require.main === module) {
    if (process.argv[2] === '-v') {
        verbose = true;
    }

    load();
}

if (verbose) {
    gutil.log(LOG_ID, gutil.colors.green('assets'), assets);
}

function load(config) {

    if (config && config.debug) {
        verbose = true;
    }

    var cwd = process.cwd();
    processPkg(cwd);

    return assets;
}

function processPkg(curDir) {

    var meta;
    var metaPath = path.join(curDir, PACKAGE_INFO);

    try {
        if (verbose) {
            gutil.log(LOG_ID, gutil.colors.blue('reading', metaPath));
        }
        meta = require(metaPath);
        grabAssets(curDir, meta.assets);
    } catch (err) {
        if (verbose) {
            gutil.log(LOG_ID, gutil.colors.yellow('not found', metaPath, 'skipping...'));
        }
    }

    if (!meta || !meta.dependencies) {
        return;
    }

    /*jshint -W089 */
    for (var pkg in meta.dependencies) {
        processPkg(path.join(curDir, NODE_MODULES_DIR, pkg));
    }

}

function grabAssets(basePath, pkgAssets) {

    if (!pkgAssets || !basePath) {
        return;
    }

    if (verbose) {
        gutil.log(LOG_ID, gutil.colors.green('found', pkgAssets));
    }

    if (Array.isArray(pkgAssets)) {
        pkgAssets.forEach(assetPush);
    } else {
        assetPush(pkgAssets);
    }

    function assetPush(asset) {
        assets.push(path.join(basePath, asset));
    }

}
<commit_msg>added debug message when assets not found in package<commit_after>/*jshint -W097 */
'use strict';

var LOG_ID = 'find-npm-assets';
var NODE_MODULES_DIR = 'node_modules';
var PACKAGE_INFO = 'package.json';

var path = require('path');
var gutil = require('gulp-util');

var verbose = false;
var assets = [];

module.exports = {
    load: load
};

if (require.main === module) {
    if (process.argv[2] === '-v') {
        verbose = true;
    }

    load();
}

if (verbose) {
    gutil.log(LOG_ID, gutil.colors.green('assets'), assets);
}

function load(config) {

    if (config && config.debug) {
        verbose = true;
    }

    var cwd = process.cwd();
    processPkg(cwd);

    return assets;
}

function processPkg(curDir) {

    var meta;
    var metaPath = path.join(curDir, PACKAGE_INFO);

    try {
        if (verbose) {
            gutil.log(LOG_ID, gutil.colors.blue('reading', metaPath));
        }
        meta = require(metaPath);
        grabAssets(curDir, meta.assets);
    } catch (err) {
        if (verbose) {
            gutil.log(LOG_ID, gutil.colors.yellow('not found', metaPath, 'skipping...'));
        }
    }

    if (!meta || !meta.dependencies) {
        return;
    }

    /*jshint -W089 */
    for (var pkg in meta.dependencies) {
        processPkg(path.join(curDir, NODE_MODULES_DIR, pkg));
    }

}

function grabAssets(basePath, pkgAssets) {

    if (!pkgAssets || !basePath) {
        gutil.log(LOG_ID, gutil.colors.yellow('no assets found in ', basePath));
        return;
    }

    if (verbose) {
        gutil.log(LOG_ID, gutil.colors.green('found', pkgAssets));
    }

    if (Array.isArray(pkgAssets)) {
        pkgAssets.forEach(assetPush);
    } else {
        assetPush(pkgAssets);
    }

    function assetPush(asset) {
        assets.push(path.join(basePath, asset));
    }

}
<|endoftext|>


<commit_before>/**
 * escallmatch:
 *   ECMAScript CallExpression matcher made from function/method signature
 *
 * https://github.com/twada/escallmatch
 *
 * Copyright (c) 2014 Takuto Wada
 * Licensed under the MIT license.
 *   http://twada.mit-license.org/
 */
'use strict';
/* jshint -W024 */

var esprima = require('esprima'),
    estraverse = require('estraverse'),
    espurify = require('espurify'),
    syntax = estraverse.Syntax,
    hasOwn = Object.prototype.hasOwnProperty,
    deepEqual = require('deep-equal'),
    notCallExprMessage = 'Argument should be in the form of CallExpression',
    duplicatedArgMessage = 'Duplicate argument name: ',
    invalidFormMessage = 'Argument should be in the form of `name` or `[name]`';

function createMatcher (signatureStr) {
    var ast = extractExpressionFrom(esprima.parse(signatureStr));
    return new Matcher(ast);
}

function Matcher (signatureAst) {
    this.signatureAst = signatureAst;
    this.numMaxArgs = this.signatureAst.arguments.length;
    this.numMinArgs = this.signatureAst.arguments.filter(identifiers).length;
}

Matcher.prototype.test = function (currentNode) {
    var calleeMatched = isCalleeMatched(this.signatureAst, currentNode),
        numArgs;
    if (calleeMatched) {
        numArgs = currentNode.arguments.length;
        return this.numMinArgs <= numArgs && numArgs <= this.numMaxArgs;
    }
    return false;
};

Matcher.prototype.matchArgument = function (currentNode, parentNode) {
    var indexOfCurrentArg;
    if (isCalleeOfParent(currentNode, parentNode)) {
        return null;
    }
    if (this.test(parentNode)) {
        indexOfCurrentArg = parentNode.arguments.indexOf(currentNode);
        return toArgumentSigniture(this.signatureAst.arguments[indexOfCurrentArg]);
    }
    return null;
};

Matcher.prototype.calleeAst = function () {
    return espurify(this.signatureAst.callee);
};

Matcher.prototype.argumentSignitures = function () {
    return this.signatureAst.arguments.map(toArgumentSigniture);
};

function toArgumentSigniture (argSignatureNode) {
    switch(argSignatureNode.type) {
    case syntax.Identifier:
        return {
            name: argSignatureNode.name,
            kind: 'mandatory'
        };
    case syntax.ArrayExpression:
        return {
            name: argSignatureNode.elements[0].name,
            kind: 'optional'
        };
    default:
        return null;
    }
}

function isCalleeMatched(callExp1, callExp2) {
    if (!isCallExpression(callExp1) || !isCallExpression(callExp2)) {
        return false;
    }
    if (astDepth(callExp1.callee) !== astDepth(callExp2.callee)) {
        return false;
    }
    return deepEqual(espurify(callExp1.callee), espurify(callExp2.callee));
}

function astDepth (ast) {
    var maxDepth = 0;
    estraverse.traverse(ast, {
        enter: function (currentNode, parentNode) {
            var path = this.path(),
                currentDepth = path ? path.length : 0;
            if (maxDepth < currentDepth) {
                maxDepth = currentDepth;
            }
        }
    });
    return maxDepth;
}

function isCallExpression (node) {
    return node && node.type === syntax.CallExpression;
}

function isCalleeOfParent(currentNode, parentNode) {
    return parentNode && currentNode &&
        parentNode.type === syntax.CallExpression &&
        parentNode.callee === currentNode;
}

function identifiers (node) {
    return node.type === syntax.Identifier;
}

function validateApiExpression (callExpression) {
    if (callExpression.type !== syntax.CallExpression) {
        throw new Error(notCallExprMessage);
    }
    var names = {};
    callExpression.arguments.forEach(function (arg) {
        var name = validateArg(arg);
        if (hasOwn.call(names, name)) {
            throw new Error(duplicatedArgMessage + name);
        } else {
            names[name] = name;
        }
    });
}

function validateArg (arg) {
    var inner;
    switch(arg.type) {
    case syntax.Identifier:
        return arg.name;
    case syntax.ArrayExpression:
        if (arg.elements.length !== 1) {
            throw new Error(invalidFormMessage);
        }
        inner = arg.elements[0];
        if (inner.type !== syntax.Identifier) {
            throw new Error(invalidFormMessage);
        }
        return inner.name;
    default:
        throw new Error(invalidFormMessage);
    }
}

function extractExpressionFrom (tree) {
    var statement, expression;
    statement = tree.body[0];
    if (statement.type !== syntax.ExpressionStatement) {
        throw new Error(notCallExprMessage);
    }
    expression = statement.expression;
    validateApiExpression(expression);
    return expression;
}

module.exports = createMatcher;
<commit_msg>refactor(escallmatch): extract variable<commit_after>/**
 * escallmatch:
 *   ECMAScript CallExpression matcher made from function/method signature
 *
 * https://github.com/twada/escallmatch
 *
 * Copyright (c) 2014 Takuto Wada
 * Licensed under the MIT license.
 *   http://twada.mit-license.org/
 */
'use strict';
/* jshint -W024 */

var esprima = require('esprima'),
    estraverse = require('estraverse'),
    espurify = require('espurify'),
    syntax = estraverse.Syntax,
    hasOwn = Object.prototype.hasOwnProperty,
    deepEqual = require('deep-equal'),
    notCallExprMessage = 'Argument should be in the form of CallExpression',
    duplicatedArgMessage = 'Duplicate argument name: ',
    invalidFormMessage = 'Argument should be in the form of `name` or `[name]`';

function createMatcher (signatureStr) {
    var ast = extractExpressionFrom(esprima.parse(signatureStr));
    return new Matcher(ast);
}

function Matcher (signatureAst) {
    this.signatureAst = signatureAst;
    this.numMaxArgs = this.signatureAst.arguments.length;
    this.numMinArgs = this.signatureAst.arguments.filter(identifiers).length;
}

Matcher.prototype.test = function (currentNode) {
    var calleeMatched = isCalleeMatched(this.signatureAst, currentNode),
        numArgs;
    if (calleeMatched) {
        numArgs = currentNode.arguments.length;
        return this.numMinArgs <= numArgs && numArgs <= this.numMaxArgs;
    }
    return false;
};

Matcher.prototype.matchArgument = function (currentNode, parentNode) {
    var indexOfCurrentArg, argNode;
    if (isCalleeOfParent(currentNode, parentNode)) {
        return null;
    }
    if (this.test(parentNode)) {
        indexOfCurrentArg = parentNode.arguments.indexOf(currentNode);
        argNode = this.signatureAst.arguments[indexOfCurrentArg];
        return toArgumentSigniture(argNode);
    }
    return null;
};

Matcher.prototype.calleeAst = function () {
    return espurify(this.signatureAst.callee);
};

Matcher.prototype.argumentSignitures = function () {
    return this.signatureAst.arguments.map(toArgumentSigniture);
};

function toArgumentSigniture (argSignatureNode) {
    switch(argSignatureNode.type) {
    case syntax.Identifier:
        return {
            name: argSignatureNode.name,
            kind: 'mandatory'
        };
    case syntax.ArrayExpression:
        return {
            name: argSignatureNode.elements[0].name,
            kind: 'optional'
        };
    default:
        return null;
    }
}

function isCalleeMatched(callExp1, callExp2) {
    if (!isCallExpression(callExp1) || !isCallExpression(callExp2)) {
        return false;
    }
    if (astDepth(callExp1.callee) !== astDepth(callExp2.callee)) {
        return false;
    }
    return deepEqual(espurify(callExp1.callee), espurify(callExp2.callee));
}

function astDepth (ast) {
    var maxDepth = 0;
    estraverse.traverse(ast, {
        enter: function (currentNode, parentNode) {
            var path = this.path(),
                currentDepth = path ? path.length : 0;
            if (maxDepth < currentDepth) {
                maxDepth = currentDepth;
            }
        }
    });
    return maxDepth;
}

function isCallExpression (node) {
    return node && node.type === syntax.CallExpression;
}

function isCalleeOfParent(currentNode, parentNode) {
    return parentNode && currentNode &&
        parentNode.type === syntax.CallExpression &&
        parentNode.callee === currentNode;
}

function identifiers (node) {
    return node.type === syntax.Identifier;
}

function validateApiExpression (callExpression) {
    if (callExpression.type !== syntax.CallExpression) {
        throw new Error(notCallExprMessage);
    }
    var names = {};
    callExpression.arguments.forEach(function (arg) {
        var name = validateArg(arg);
        if (hasOwn.call(names, name)) {
            throw new Error(duplicatedArgMessage + name);
        } else {
            names[name] = name;
        }
    });
}

function validateArg (arg) {
    var inner;
    switch(arg.type) {
    case syntax.Identifier:
        return arg.name;
    case syntax.ArrayExpression:
        if (arg.elements.length !== 1) {
            throw new Error(invalidFormMessage);
        }
        inner = arg.elements[0];
        if (inner.type !== syntax.Identifier) {
            throw new Error(invalidFormMessage);
        }
        return inner.name;
    default:
        throw new Error(invalidFormMessage);
    }
}

function extractExpressionFrom (tree) {
    var statement, expression;
    statement = tree.body[0];
    if (statement.type !== syntax.ExpressionStatement) {
        throw new Error(notCallExprMessage);
    }
    expression = statement.expression;
    validateApiExpression(expression);
    return expression;
}

module.exports = createMatcher;
<|endoftext|>


<commit_before>// index.js
module.exports = require('./pg-error.js')<commit_msg>missing ;<commit_after>// index.js
module.exports = require('./pg-error.js');<|endoftext|>


<commit_before>var time = require('time');
exports.handler = (event, context, callback) => {
    var currentTime = new time.Date();
    currentTime.setTimezone("America/Los_Angeles");
    callback(null, {
        statusCode: '200',
        body: 'The time in Los Angeles is: ' + currentTime.toString(),
    });
};
<commit_msg>Change timezone to New York<commit_after>var time = require('time');
exports.handler = (event, context, callback) => {
    var currentTime = new time.Date();
    currentTime.setTimezone("America/New_York");
    callback(null, {
        statusCode: '200',
        body: 'The time in New York is: ' + currentTime.toString(),
    });
};
<|endoftext|>


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

/*!
 * statmap
 * Output recursive directory stats as JSON for visualization and analysis.
 * Dan Motzenbecker <dan@oxism.com>
 * MIT Licensed
 */

"use strict";

var fs    = require('fs'),
    path  = require('path'),
    async = require('async'),
    scan;

module.exports = scan = function(dir, cb, tree) {
  var baseName = path.basename(dir);

  tree = tree || {};
  tree[baseName] = {};

  fs.stat(dir, function(err, stats) {
    if (err) return cb(err);

    tree[baseName].stats = stats;

    if (stats.isDirectory()) {
      fs.readdir(dir, function(err, files) {
        if (err) return cb(err);
        if (files.length) {
          tree[baseName].sum      = 0;
          tree[baseName].children = {};
          async.each(files, function(file, cb) {
            scan(dir + '/' + file, function(err, branch){
              if (err) return cb(err);
              tree[baseName].sum += branch[file].sum || branch[file].stats.size;
            }, tree[baseName].children);
          }, function(err) {
            cb(err, tree)
          });
        } else {
          cb(null, tree);
        }
      });
    } else {
      cb(null, tree);
    }
  });
}

if (!module.parent) {
  if (process.argv[2]) {
    process.chdir(process.argv[2]);
  }
  scan(process.cwd(), function(err, stats) {
    console.log(JSON.stringify(stats, null, 2));
  });
}

<commit_msg>use path.join<commit_after>#!/usr/bin/env node

/*!
 * statmap
 * Output recursive directory stats as JSON for visualization and analysis.
 * Dan Motzenbecker <dan@oxism.com>
 * MIT Licensed
 */

"use strict";

var fs    = require('fs'),
    path  = require('path'),
    async = require('async'),
    scan;

module.exports = scan = function(dir, cb, tree) {
  var baseName = path.basename(dir);

  tree = tree || {};
  tree[baseName] = {};

  fs.stat(dir, function(err, stats) {
    if (err) return cb(err);
    tree[baseName].stats = stats;

    if (stats.isDirectory()) {
      fs.readdir(dir, function(err, files) {
        if (err) return cb(err);
        if (files.length) {
          tree[baseName].sum      = 0;
          tree[baseName].children = {};
          async.each(files, function(file, cb) {
            scan(path.join(dir, file), function(err, branch) {
              if (err) return cb(err);
              tree[baseName].sum += branch[file].sum || branch[file].stats.size;
              cb();
            }, tree[baseName].children);
          }, function(err) {
            cb(err, tree)
          });
        } else {
          cb(null, tree);
        }
      });
    } else {
      cb(null, tree);
    }
  });
}

if (!module.parent) {
  if (process.argv[2]) {
    process.chdir(process.argv[2]);
  }
  scan(process.cwd(), function(err, stats) {
    console.log(JSON.stringify(stats, null, 2));
  });
}

<|endoftext|>


<commit_before>/**
  Created By: Anthony Datu
  Purpose: Modular Analog Clock
  Date: 07/16/2014
  Notes: This works in conjunction with moment.js and moment-timezone.js
  How to use:
    1) In html create
<svg></svg>

    2) Set div's height and width equal to each other(e.g 400px by 400px)
    3) Call new Clock() to instantiate object
    4) Call method generate('#clock','Manila') <--- City is optional, if no city
    time will default to Local time.

  Clock Description:
    Between 6 am - 5pm, clock color is orange, otherwise gray.
**/
var moment = require('moment-timezone'),
  extend = require('util')._extend,
  format = require('util').format,
  components = require('./lib/components'),
  parse = require('angular-expressions').compile,
  defaults = {
    autoStart: true,
    colors: {
      'day': '#FF760D',
      'night': '#005753'
    }
  };

function Clock(el, options) {
  var ns = 'http://www.w3.org/2000/svg';

  if (!el) {
    throw new Error('No element given when instantiating clocked.');
  }

  Object.defineProperties(this, {
    el: {
      value: el instanceof Node ? el : document.querySelector(el),
      writable: true
    },
    options: {
      value: options && extend(defaults, options) || defaults
    },
    svgNs: {
      value: ns
    },
    reqFrame: {
      writable: true
    },
    svg: {
      enumerable: true,
      configurable: true,
      value: document.createElementNS(ns, 'svg'),
      writable: true
    }
  });

  this.generate();

  if (this.options.autoStart) {
    this.start();
  }
}

Clock.prototype.getTime = function() {
  var city = this.options.city,
    fn = city && moment.tz || moment;
  return {
    hour: (parseInt(fn(city).format('h'), 10) * 30) + (parseInt(fn(city).format('mm'), 10) * 0.5),
    minute: parseInt(fn(city).format('mm'), 10) * 6,
    second: parseInt(fn(city).format('ss'), 10) * 6
  };
};

Clock.prototype.dayOrNight = function() {
  var city = this.options.city,
    fn = city && moment.tz || moment;
  return parseInt(fn(city).format('HH'), 10) > 17 || parseInt(fn(city).format('HH'), 10) < 6 ? 'night' : 'day';
};

Clock.prototype.dateTicker = function() {
  var city = this.options.city,
    format = arguments.length ? 'HH:mm' : 'ddd D',
    fn = city && moment.tz || moment;
  return fn(city).format(format);
};

Clock.prototype.formatCity = function() {
  var city = this.options.city || 'local',
    formatted = city.replace(/^(\w+\/)*/gi, '');
  return formatted.replace('_', ' ');
};

Clock.prototype.generate = function() {
  var el = this.el,
    height = el.clientHeight,
    ns = this.svgNs,
    position = height / 2,
    /** Get Clock hands angles **/
    time = this.getTime(),
    colors = this.options.colors,
    color = colors[this.dayOrNight()],
    svg = this.svg,
    compMap = {
      circle: document.createElementNS(ns, 'circle'),
      city: document.createElementNS(ns, 'text'),
      date: document.createElementNS(ns, 'text'),
      dot: document.createElementNS(ns, 'circle'),
      hour: document.createElementNS(ns, 'line'),
      minute: document.createElementNS(ns, 'line'),
      second: document.createElementNS(ns, 'line'),
      svg: svg,
      time: document.createElementNS(ns, 'text')
    },
    context = {
      height: height,
      width: height,
      color: color,
      format: format,
      position: position,
      time: time
    },
    component, attr;

  compMap.date.appendChild(document.createTextNode(this.dateTicker()));
  compMap.time.appendChild(document.createTextNode(this.dateTicker(true)));
  compMap.city.appendChild(document.createTextNode(this.formatCity()));

  for (component in components) {
    for(attr in components[component]) {
      compMap[component].setAttribute(attr, parse(components[component][attr])(context));
    }
  }

  delete compMap.svg;

  for (component in compMap) {
    svg.appendChild(compMap[component]);
  }
  el.appendChild(svg);
};

Clock.prototype.tick = function() {
  var div = this.el,
    cir = div.querySelectorAll('circle'),
    hands = div.querySelectorAll('line'), //Get SVG child nodes (clock hands)
    text = div.querySelectorAll('text'),
    position = div.clientHeight / 2,
    time = this.getTime(),
    hour = time.hour,
    minute = time.minute,
    second = time.second,
    fmt = 'rotate(%s %s %s)';

  [hour, minute, second].forEach(function(time, idx) {
    hands[idx].setAttribute('transform', format(fmt, time, position, position));
  });

  text[0].innerHTML = this.dateTicker();
  text[1].innerHTML = this.dateTicker(true);

  var colors = this.options.colors,
    color = colors[this.dayOrNight()];

  hands.forEach(function(hand) {
    hand.setAttribute('stroke', color);
  });

  text.forEach(function(txt) {
    txt.setAttribute('fill', color);
  });

  cir[0].setAttribute('stroke', color);
  cir[1].setAttribute('fill', color);

  this.reqFrame = window.requestAnimationFrame(this.tick.bind(this));
};

Clock.prototype.start = function() {
  this.reqFrame = window.requestAnimationFrame(this.tick.bind(this));
};

module.exports = Clock;<commit_msg>fix step function<commit_after>/**
  Created By: Anthony Datu
  Purpose: Modular Analog Clock
  Date: 07/16/2014
  Notes: This works in conjunction with moment.js and moment-timezone.js
  How to use:
    1) In html create
<svg></svg>

    2) Set div's height and width equal to each other(e.g 400px by 400px)
    3) Call new Clock() to instantiate object
    4) Call method generate('#clock','Manila') <--- City is optional, if no city
    time will default to Local time.

  Clock Description:
    Between 6 am - 5pm, clock color is orange, otherwise gray.
**/
var moment = require('moment-timezone'),
  extend = require('util')._extend,
  format = require('util').format,
  components = require('./lib/components'),
  parse = require('angular-expressions').compile,
  defaults = {
    autoStart: true,
    colors: {
      'day': '#FF760D',
      'night': '#005753'
    }
  };

function Clock(el, options) {
  var ns = 'http://www.w3.org/2000/svg';

  if (!el) {
    throw new Error('No element given when instantiating clocked.');
  }

  Object.defineProperties(this, {
    el: {
      value: el instanceof Node ? el : document.querySelector(el),
      writable: true
    },
    options: {
      value: options && extend(defaults, options) || defaults
    },
    svgNs: {
      value: ns
    },
    reqFrame: {
      writable: true
    },
    svg: {
      enumerable: true,
      configurable: true,
      value: document.createElementNS(ns, 'svg'),
      writable: true
    }
  });

  this.generate();

  if (this.options.autoStart) {
    this.start();
  }
}

Clock.prototype.getTime = function() {
  var city = this.options.city,
    fn = city && moment.tz || moment;
  return {
    hour: (parseInt(fn(city).format('h'), 10) * 30) + (parseInt(fn(city).format('mm'), 10) * 0.5),
    minute: parseInt(fn(city).format('mm'), 10) * 6,
    second: parseInt(fn(city).format('ss'), 10) * 6
  };
};

Clock.prototype.dayOrNight = function() {
  var city = this.options.city,
    fn = city && moment.tz || moment;
  return parseInt(fn(city).format('HH'), 10) > 17 || parseInt(fn(city).format('HH'), 10) < 6 ? 'night' : 'day';
};

Clock.prototype.dateTicker = function() {
  var city = this.options.city,
    format = arguments.length ? 'HH:mm' : 'ddd D',
    fn = city && moment.tz || moment;
  return fn(city).format(format);
};

Clock.prototype.formatCity = function() {
  var city = this.options.city || 'local',
    formatted = city.replace(/^(\w+\/)*/gi, '');
  return formatted.replace('_', ' ');
};

Clock.prototype.generate = function() {
  var el = this.el,
    height = el.clientHeight,
    ns = this.svgNs,
    position = height / 2,
    /** Get Clock hands angles **/
    time = this.getTime(),
    colors = this.options.colors,
    color = colors[this.dayOrNight()],
    svg = this.svg,
    compMap = {
      circle: document.createElementNS(ns, 'circle'),
      city: document.createElementNS(ns, 'text'),
      date: document.createElementNS(ns, 'text'),
      dot: document.createElementNS(ns, 'circle'),
      hour: document.createElementNS(ns, 'line'),
      minute: document.createElementNS(ns, 'line'),
      second: document.createElementNS(ns, 'line'),
      svg: svg,
      time: document.createElementNS(ns, 'text')
    },
    context = {
      height: height,
      width: height,
      color: color,
      format: format,
      position: position,
      time: time
    },
    component, attr;

  compMap.date.appendChild(document.createTextNode(this.dateTicker()));
  compMap.time.appendChild(document.createTextNode(this.dateTicker(true)));
  compMap.city.appendChild(document.createTextNode(this.formatCity()));

  for (component in components) {
    for(attr in components[component]) {
      compMap[component].setAttribute(attr, parse(components[component][attr])(context));
    }
  }

  delete compMap.svg;

  for (component in compMap) {
    svg.appendChild(compMap[component]);
  }
  el.appendChild(svg);
};

Clock.prototype.tick = function() {
  var div = this.el,
    cir = div.querySelectorAll('circle'),
    hands = div.querySelectorAll('line'), //Get SVG child nodes (clock hands)
    text = div.querySelectorAll('text'),
    position = div.clientHeight / 2,
    time = this.getTime(),
    hour = time.hour,
    minute = time.minute,
    second = time.second,
    fmt = 'rotate(%s %s %s)';

  [hour, minute, second].forEach(function(time, idx) {
    hands[idx].setAttribute('transform', format(fmt, time, position, position));
  });

  text[0].innerHTML = this.dateTicker();
  text[1].innerHTML = this.dateTicker(true);

  var colors = this.options.colors,
    color = colors[this.dayOrNight()];

  Array.prototype.forEach.apply(hands, function(hand) {
    hand.setAttribute('stroke', color);
  });

  Array.prototype.forEach.apply(text, function(txt) {
    txt.setAttribute('fill', color);
  });

  cir[0].setAttribute('stroke', color);
  cir[1].setAttribute('fill', color);

  this.reqFrame = window.requestAnimationFrame(this.tick.bind(this));
};

Clock.prototype.start = function() {
  this.reqFrame = window.requestAnimationFrame(this.tick.bind(this));
};

module.exports = Clock;<|endoftext|>


<commit_before>hexo.extend.filter.register('after_post_render', function(data) {
    var re = /(\|{2}?)((.|\n)+?)(\|{2}?)/gm;
    data.content = data.content.replace(re,'$2');
    return data;
});
<commit_msg>change to after_render<commit_after>hexo.extend.filter.register('after_render:html', function(data) {
    var re = /(\|{2}?)((.|\n)+?)(\|{2}?)/gm;
    var result = str.replace(re,'$2');
    return result;
    //data.content = data.content.replace(re,'$2');
    //return data;
});
<|endoftext|>


<commit_before>"use strict";

module.exports = {
  name: require("./package").name,

  included: function(app) {
    this._super.included.apply(this, arguments);

    app.import("node_modules/popper.js/dist/umd/popper.js", {
      using: [
        {
          transformation: "amd",
          as: "popper.js"
        }
      ]
    });
    app.import("node_modules/tooltip.js/dist/umd/tooltip.js", {
      using: [
        {
          transformation: "amd",
          as: "tooltip.js"
        }
      ]
    });
  },

  treeForAddonTestSupport(tree) {
    const writeFile = require('broccoli-file-creator');
    const optionalFeatures = this.addons.find(a => a.name === '@ember/optional-features');
    const testType = optionalFeatures.isFeatureEnabled('jquery-integration')
      ? 'jquery'
      : 'dom';

    const reexportTree = writeFile(
      'index.js',
      `export * from '${this.moduleName()}/test-support/${testType}';`
    );

    const MergedTrees = require('broccoli-merge-trees');
    const mergedTree = new MergedTrees([tree, reexportTree]);

    return this._super(mergedTree);
  }
};
<commit_msg>Import {popper,tooltip}.js.map to fix sourcemap generation<commit_after>"use strict";

module.exports = {
  name: require("./package").name,

  included: function(app) {
    this._super.included.apply(this, arguments);

    app.import("node_modules/popper.js/dist/umd/popper.js", {
      using: [
        {
          transformation: "amd",
          as: "popper.js"
        }
      ]
    });
    app.import("node_modules/popper.js/dist/umd/popper.js.map", { destDir: 'assets' });
    app.import("node_modules/tooltip.js/dist/umd/tooltip.js", {
      using: [
        {
          transformation: "amd",
          as: "tooltip.js"
        }
      ]
    });
    app.import("node_modules/tooltip.js/dist/umd/tooltip.js.map", { destDir: 'assets' });
  },

  treeForAddonTestSupport(tree) {
    const writeFile = require('broccoli-file-creator');
    const optionalFeatures = this.addons.find(a => a.name === '@ember/optional-features');
    const testType = optionalFeatures.isFeatureEnabled('jquery-integration')
      ? 'jquery'
      : 'dom';

    const reexportTree = writeFile(
      'index.js',
      `export * from '${this.moduleName()}/test-support/${testType}';`
    );

    const MergedTrees = require('broccoli-merge-trees');
    const mergedTree = new MergedTrees([tree, reexportTree]);

    return this._super(mergedTree);
  }
};
<|endoftext|>


<commit_before>'use strict';
const reqAll = require('req-all');

module.exports = {
	rules: reqAll('rules', {camelize: false}),
	configs: {
		recommended: {
			env: {
				es6: true
			},
			parserOptions: {
				ecmaVersion: 2017,
				sourceType: 'module'
			},
			rules: {
				'ava/assertion-arguments': 'error',
				'ava/assertion-message': ['off', 'always'],
				'ava/max-asserts': ['off', 5],
				'ava/no-async-fn-without-await': 'off',
				'ava/no-cb-test': 'off',
				'ava/no-duplicate-modifiers': 'off',
				'ava/no-identical-title': 'error',
				'ava/no-ignored-test-files': 'error',
				'ava/no-invalid-end': 'error',
				'ava/no-nested-tests': 'error',
				'ava/no-only-test': 'error',
				'ava/no-skip-assert': 'error',
				'ava/no-skip-test': 'error',
				'ava/no-statement-after-end': 'error',
				'ava/no-todo-implementation': 'error',
				'ava/no-todo-test': 'warn',
				'ava/no-unknown-modifiers': 'error',
				'ava/prefer-async-await': 'error',
				'ava/prefer-power-assert': 'off',
				'ava/test-ended': 'error',
				'ava/test-title': ['error', 'if-multiple'],
				'ava/use-t-well': 'error',
				'ava/use-t': 'error',
				'ava/use-test': 'error',
				'ava/use-true-false': 'error'
			}
		}
	}
};
<commit_msg>enable two rules in the recommended preset<commit_after>'use strict';
const reqAll = require('req-all');

module.exports = {
	rules: reqAll('rules', {camelize: false}),
	configs: {
		recommended: {
			env: {
				es6: true
			},
			parserOptions: {
				ecmaVersion: 2017,
				sourceType: 'module'
			},
			rules: {
				'ava/assertion-arguments': 'error',
				'ava/assertion-message': ['off', 'always'],
				'ava/max-asserts': ['off', 5],
				'ava/no-async-fn-without-await': 'error',
				'ava/no-cb-test': 'off',
				'ava/no-duplicate-modifiers': 'error',
				'ava/no-identical-title': 'error',
				'ava/no-ignored-test-files': 'error',
				'ava/no-invalid-end': 'error',
				'ava/no-nested-tests': 'error',
				'ava/no-only-test': 'error',
				'ava/no-skip-assert': 'error',
				'ava/no-skip-test': 'error',
				'ava/no-statement-after-end': 'error',
				'ava/no-todo-implementation': 'error',
				'ava/no-todo-test': 'warn',
				'ava/no-unknown-modifiers': 'error',
				'ava/prefer-async-await': 'error',
				'ava/prefer-power-assert': 'off',
				'ava/test-ended': 'error',
				'ava/test-title': ['error', 'if-multiple'],
				'ava/use-t-well': 'error',
				'ava/use-t': 'error',
				'ava/use-test': 'error',
				'ava/use-true-false': 'error'
			}
		}
	}
};
<|endoftext|>


<commit_before>// Dependencies
var Url = require("url")
  , Fs  = require("fs")
  , Path = require("path")
  , Events = require("events")
  , Debug = require("bug-killer")
  , RegexpParser = function (str) {
        return new RegExp(str);
    }
  ;

// MIME types
const MIME_TYPES = {
    "html": "text/html"
  , "jpeg": "image/jpeg"
  , "jpg":  "image/jpeg"
  , "png":  "image/png"
  , "js":   "text/javascript"
  , "css":  "text/css"
};

/**
 * Le Statique
 * -----------
 * A node-static minimalist alternative.
 * Licensed under the MIT license. See the LICENSE file.
 *
 * Documentation can be found in README and on GitHub:
 * http://github.com/IonicaBizau/node-statique
 */
var Statique = module.exports = {};

/**
 * Sets the root of the public folder.
 *
 * @param {Object} options an object containing the following fields:
 *  - root: string representing the absolute path to the public folder.
 *  - cache: the number of seconds of cache
 * @return {Object} Statique object
 */
Statique.server = function (options) {
    if (typeof options === "string") {
        options = {
            root: options
        }
    }
    if (options.root.slice(-1) !== "/") {
        options.root += "/";
    }

    Statique._root = options.root;
    Statique._cache = options.cache || 3600;

    return Statique;
};

/**
 * Sets the routes of the website.
 *
 * @param {Object} routes an object containing fields and values in the
 * following format:
 *  {
 *      "/":       "/html/index.html"
 *    , "/foo/":   { url: "/html/foo.html" }
 *    , "/another-foo": "/html/myfoo.html"
 *    , "/some/api": function (req, res) {
 *          res.end("Hello World!");
 *      }
 *  }
 *
 *  See test file for more examples.
 * @return {Object} Statique object
 */
Statique.setRoutes = function (routes) {
    Statique._routes = routes;
    Statique._regexpRoutes = [];
    for (var r in routes) {
        var cRoute = routes[r];
        if ((cRoute.type || "").toLowerCase() === "regexp") {
            if ((cRoute.regexp || {}).constructor.name !== "RegExp") {
                cRoute.regexp = RegexpParser(r);
            }
            Statique._regexpRoutes.push(cRoute);
            delete cRoute[r];
        }
    }
    return Statique;
};

/**
 * setErrors
 * Sets the error pages
 *
 * @name setErrors
 * @function
 * @param {Object} errorRoutes An object with the error codes and their paths to the HTML files
 * @return {Object} Statique object
 */
Statique.setErrors = function (errorRoutes) {
    Statique._errors = errorRoutes;
    return Statique;
};

/**
 * Gets the route by providing an @url
 *
 * @param {String} url a string representing the url of the page that
 * must be served
 * @return {Object} the route object that contains the following fields:
 *  - url
 *  - handler
 */
Statique.getRoute = function (url) {

    var route = {};

    // remove slash at the end of the string
    if (url.slice (-1) === "/") {
        url = url.substring(0, url.length - 1);
    }

    // get the route that was set in the configuration
    var routeObj = Statique._routes[url] || Statique._routes[url + "/"] || null;
    route.url = (routeObj || {}).url || routeObj;
    route.reqUrl = route.url || url;
    route._data = routeObj;

    // Handle regexp routes
    for (var i = 0, cRegexpRoute; i < Statique._regexpRoutes.length; ++i) {
        cRegexpRoute = Statique._regexpRoutes[i];
        if (cRegexpRoute.regexp.test(url)) {
            for (var k in cRegexpRoute) {
                route[k] = cRegexpRoute[k];
            }
            break;
        }
    }

    // handle url as function
    if (typeof route.url === "function") {
        route.handler = route.url;
        delete route.url;
    }

    if (routeObj && typeof routeObj.handler === "function") {
        routeObj.handler = routeObj.handler;
    }

    return route;
};

/**
 * Checks if a route exists.
 *
 * @param {Object} req the request object
 * @return {Boolean} true, if the route was found, else false
 */
Statique.exists = function (req) {
    return Boolean(Statique.getRoute(Url.parse(req.url).pathname));
};

/**
 * Reads the file and callbacks the content.
 *
 * @param {String} file the relative path to the file
 * @param {Function} callback the callback function that will be called with an
 * err (first argument) and the content of the file (second argument)
 * @return {Buffer} the raw buffer
 */
Statique.readFile = function (file, callback) {
    return Fs.readFile(Statique._root + file, function (err, buffer) {
        if (err) { return callback(err); }
        callback(null, buffer.toString())
    });
};

/**
 * Serves the HTML file according by providing the @req and @res parameters
 *
 * @param {Object} req the request object
 * @param {Object} res the response object
 * @return {Object} the Statique instance
 */
Statique.serve = function (req, res) {
    return Statique.serveRoute(undefined, req, res);
};

/**
 * This function is used for sending custom status messages and content
 * If the @content parameter is not provided or is not a string, the response
 * will not be ended. The status code and the headers will be set
 *
 * @param {Object} res the response object
 * @param {Number} statusCode the response status code
 * @param {String} mimeType the response mime type
 * @param {String} content the content that you want to send via response
 * @param {Object} otherHeaders Aditional headers that will be merged with
 * the basic ones. They have greater priority than basic headers.
 * @return {Object} the Statique instance
 */
Statique.sendRes = function (res, statusCode, mimeType, content, otherHeaders) {

    var headers = {
        "Content-Type": mimeType || "plain/text"
      , "Server": "Statique Server"
    };

    for (var h in otherHeaders) {
        headers[h] = otherHeaders[h] || headers[h];
    }

    res.writeHead(statusCode, headers);

    if (typeof content === "string") {
        res.end(content);
    }

    return Statique;
};

/**
 * serveFile
 * Serves a file
 *
 * @name serveFile
 * @function
 * @param {String|Object} path The path to the file that should be served or the route object
 * @param {Number} statusCode The response status code (default: 200)
 * @param {Object} res The response object
 * @param {Object} req The request object
 * @param {Object} additionalheaders Additional headers that should be sent
 * @return {Object} Statique object
 */
Statique.serveFile = function (path, statusCode, res, req, additionalHeaders) {

    res = Object(res);
    req = Object(req);
    req.headers = req.headers || {};

    if (typeof path === "string") {
        path = {
            reqUrl: path
        };
    }

    var fullPath = Statique._root + (path.url || path.reqUrl);

    try {
        stats = Fs.lstatSync(fullPath);
    } catch (e) {
        Statique.error(req, res, 404, "Not found");
        return Statique;
    }

    // no file, no fun
    if (!stats.isFile()) { return Statique; }

    // cache stuff
    var mtime = Date.parse(stats.mtime)
      , clientETag = req.headers['if-none-match']
      , clientMTime = Date.parse(req.headers['if-modified-since'])
      , contentType = MIME_TYPES[
            Path.extname(path.reqUrl).substring(1)
        ]
      , headers = {
            "Etag": JSON.stringify([stats.ino, stats.size, mtime].join('-'))
          , "Date": (new Date()).toUTCString()
          , "Last-Modified": (new Date(stats.mtime)).toUTCString()
          , "Content-Type": contentType
          , "Content-Length": stats.size
        }
      ;

    // file is cached
    if ((clientMTime  || clientETag) &&
        (!clientETag  || clientETag === headers['Etag']) &&
        (!clientMTime || clientMTime >= mtime)) {
        // 304 response should not contain entity headers
        ['Content-Encoding',
         'Content-Language',
         'Content-Length',
         'Content-Location',
         'Content-MD5',
         'Content-Range',
         'Content-Type',
         'Expires',
         'Last-Modified'].forEach(function(entityHeader) {
            delete headers[entityHeader];
        });

        for (var aH in additionalHeaders) {
            headers[aH] = additionalHeaders[aH] || headers[aH];
        }

        Statique.sendRes(res, 304, contentType, null, headers);
        res.end();
        return Statique;
    }

    // Set cache-control  header
    headers["cache-control"] = "max-age=" + Statique._cache;
    for (var aH in additionalHeaders) {
        headers[aH] = additionalHeaders[aH] || headers[aH];
    }

    // file should cached
    Statique.sendRes(res, statusCode || 200, contentType, null, headers)

    var fileStream = Fs.createReadStream(fullPath);
    fileStream.pipe(res);

    return Statique;
};

/**
 * serveRoute
 * Serves a provided route.
 *
 * @name serveRoute
 * @function
 * @param {String} route The route that should be served
 * @param {Object} req The request object
 * @param {Object} res The response object
 * @return {Object} The Statique instance
 */
Statique.serveRoute = function (route, req, res) {

    var parsedUrl = Url.parse(req.url)
      , routeToServe = Statique.getRoute(
            route || parsedUrl.pathname
        ) || parsedUrl.pathname
      , stats = null
      , method = req.method.toLowerCase()
      , form = {
            data: ""
          , error: ""
          , _emitter: new Events.EventEmitter()
        }
      ;

    req.on("data", function (chunk) {
        form.data += chunk;
    });

    req.on("error", function (err) {
        form.error += err;
    });

    req.on("end", function () {
        form._emitter.emit("done", form);
    });

    if (routeToServe.url && typeof routeToServe.url[method] === "function") {
        try {
            routeToServe.url[method](req, res, form._emitter);
        } catch (e) {
            Statique.error(req, res, 500, "Internal Server Error");
            Debug.log(e.stack, "error");
        }
        return Statique;
    }

    if (typeof routeToServe.handler === "function") {
        try {
            routeToServe.handler(req, res, form._emitter);
        } catch (e) {
            Statique.error(req, res, 500, "Internal Server Error");
            Debug.log(e.stack, "error");
        }
        return Statique;
    }

    return Statique.serveFile(routeToServe, null, res, req);
};

/**
 * redirect
 * Redirects the user to the new url passed in the second argument.
 *
 * @name redirect
 * @function
 * @param {String} res The response object
 * @param {String} newUrl The new url where the user should be redirected
 * @return {Object} Statique object
 */
Statique.redirect = function (res, newUrl) {
    return Statique.sendRes(res, 301, "text", "Redirecting", {
        "location": newUrl
    });
};

/**
 * error
 * Sends an error to client
 *
 * @name error
 * @function
 * @param {Object} req The request object
 * @param {Object} res The response object
 * @param {Number} errCode The error code
 * @param {String} errMessage The error message
 * @return {Object} Statique object
 */
Statique.error = function (req, res, errCode, errMessage) {
    var configErrors = Object(Statique._errors)
      , errPage = configErrors[errCode]
      ;

    if (errPage) {
        return Statique.serveFile(errPage, errCode, res, req, {
            "cache-control": "no-cache"
        });
    }

    return Statique.sendRes(res, errCode, "text", errMessage);
};
<commit_msg>regex-parser as depenendcy<commit_after>// Dependencies
var Url = require("url")
  , Fs  = require("fs")
  , Path = require("path")
  , Events = require("events")
  , Debug = require("bug-killer")
  , RegexpParser = require("regex-parser")
  ;

// MIME types
const MIME_TYPES = {
    "html": "text/html"
  , "jpeg": "image/jpeg"
  , "jpg":  "image/jpeg"
  , "png":  "image/png"
  , "js":   "text/javascript"
  , "css":  "text/css"
};

/**
 * Le Statique
 * -----------
 * A node-static minimalist alternative.
 * Licensed under the MIT license. See the LICENSE file.
 *
 * Documentation can be found in README and on GitHub:
 * http://github.com/IonicaBizau/node-statique
 */
var Statique = module.exports = {};

/**
 * Sets the root of the public folder.
 *
 * @param {Object} options an object containing the following fields:
 *  - root: string representing the absolute path to the public folder.
 *  - cache: the number of seconds of cache
 * @return {Object} Statique object
 */
Statique.server = function (options) {
    if (typeof options === "string") {
        options = {
            root: options
        }
    }
    if (options.root.slice(-1) !== "/") {
        options.root += "/";
    }

    Statique._root = options.root;
    Statique._cache = options.cache || 3600;

    return Statique;
};

/**
 * Sets the routes of the website.
 *
 * @param {Object} routes an object containing fields and values in the
 * following format:
 *  {
 *      "/":       "/html/index.html"
 *    , "/foo/":   { url: "/html/foo.html" }
 *    , "/another-foo": "/html/myfoo.html"
 *    , "/some/api": function (req, res) {
 *          res.end("Hello World!");
 *      }
 *  }
 *
 *  See test file for more examples.
 * @return {Object} Statique object
 */
Statique.setRoutes = function (routes) {
    Statique._routes = routes;
    Statique._regexpRoutes = [];
    for (var r in routes) {
        var cRoute = routes[r];
        if ((cRoute.type || "").toLowerCase() === "regexp") {
            if ((cRoute.regexp || {}).constructor.name !== "RegExp") {
                cRoute.regexp = RegexpParser.parse(r);
            }
            Statique._regexpRoutes.push(cRoute);
            delete cRoute[r];
        }
    }
    return Statique;
};

/**
 * setErrors
 * Sets the error pages
 *
 * @name setErrors
 * @function
 * @param {Object} errorRoutes An object with the error codes and their paths to the HTML files
 * @return {Object} Statique object
 */
Statique.setErrors = function (errorRoutes) {
    Statique._errors = errorRoutes;
    return Statique;
};

/**
 * Gets the route by providing an @url
 *
 * @param {String} url a string representing the url of the page that
 * must be served
 * @return {Object} the route object that contains the following fields:
 *  - url
 *  - handler
 */
Statique.getRoute = function (url) {

    var route = {};

    // remove slash at the end of the string
    if (url.slice (-1) === "/") {
        url = url.substring(0, url.length - 1);
    }

    // get the route that was set in the configuration
    var routeObj = Statique._routes[url] || Statique._routes[url + "/"] || null;
    route.url = (routeObj || {}).url || routeObj;
    route.reqUrl = route.url || url;
    route._data = routeObj;

    // Handle regexp routes
    for (var i = 0, cRegexpRoute; i < Statique._regexpRoutes.length; ++i) {
        cRegexpRoute = Statique._regexpRoutes[i];
        if (cRegexpRoute.regexp.test(url)) {
            for (var k in cRegexpRoute) {
                route[k] = cRegexpRoute[k];
            }
            break;
        }
    }

    // handle url as function
    if (typeof route.url === "function") {
        route.handler = route.url;
        delete route.url;
    }

    if (routeObj && typeof routeObj.handler === "function") {
        routeObj.handler = routeObj.handler;
    }

    return route;
};

/**
 * Checks if a route exists.
 *
 * @param {Object} req the request object
 * @return {Boolean} true, if the route was found, else false
 */
Statique.exists = function (req) {
    return Boolean(Statique.getRoute(Url.parse(req.url).pathname));
};

/**
 * Reads the file and callbacks the content.
 *
 * @param {String} file the relative path to the file
 * @param {Function} callback the callback function that will be called with an
 * err (first argument) and the content of the file (second argument)
 * @return {Buffer} the raw buffer
 */
Statique.readFile = function (file, callback) {
    return Fs.readFile(Statique._root + file, function (err, buffer) {
        if (err) { return callback(err); }
        callback(null, buffer.toString())
    });
};

/**
 * Serves the HTML file according by providing the @req and @res parameters
 *
 * @param {Object} req the request object
 * @param {Object} res the response object
 * @return {Object} the Statique instance
 */
Statique.serve = function (req, res) {
    return Statique.serveRoute(undefined, req, res);
};

/**
 * This function is used for sending custom status messages and content
 * If the @content parameter is not provided or is not a string, the response
 * will not be ended. The status code and the headers will be set
 *
 * @param {Object} res the response object
 * @param {Number} statusCode the response status code
 * @param {String} mimeType the response mime type
 * @param {String} content the content that you want to send via response
 * @param {Object} otherHeaders Aditional headers that will be merged with
 * the basic ones. They have greater priority than basic headers.
 * @return {Object} the Statique instance
 */
Statique.sendRes = function (res, statusCode, mimeType, content, otherHeaders) {

    var headers = {
        "Content-Type": mimeType || "plain/text"
      , "Server": "Statique Server"
    };

    for (var h in otherHeaders) {
        headers[h] = otherHeaders[h] || headers[h];
    }

    res.writeHead(statusCode, headers);

    if (typeof content === "string") {
        res.end(content);
    }

    return Statique;
};

/**
 * serveFile
 * Serves a file
 *
 * @name serveFile
 * @function
 * @param {String|Object} path The path to the file that should be served or the route object
 * @param {Number} statusCode The response status code (default: 200)
 * @param {Object} res The response object
 * @param {Object} req The request object
 * @param {Object} additionalheaders Additional headers that should be sent
 * @return {Object} Statique object
 */
Statique.serveFile = function (path, statusCode, res, req, additionalHeaders) {

    res = Object(res);
    req = Object(req);
    req.headers = req.headers || {};

    if (typeof path === "string") {
        path = {
            reqUrl: path
        };
    }

    var fullPath = Statique._root + (path.url || path.reqUrl);

    try {
        stats = Fs.lstatSync(fullPath);
    } catch (e) {
        Statique.error(req, res, 404, "Not found");
        return Statique;
    }

    // no file, no fun
    if (!stats.isFile()) { return Statique; }

    // cache stuff
    var mtime = Date.parse(stats.mtime)
      , clientETag = req.headers['if-none-match']
      , clientMTime = Date.parse(req.headers['if-modified-since'])
      , contentType = MIME_TYPES[
            Path.extname(path.reqUrl).substring(1)
        ]
      , headers = {
            "Etag": JSON.stringify([stats.ino, stats.size, mtime].join('-'))
          , "Date": (new Date()).toUTCString()
          , "Last-Modified": (new Date(stats.mtime)).toUTCString()
          , "Content-Type": contentType
          , "Content-Length": stats.size
        }
      ;

    // file is cached
    if ((clientMTime  || clientETag) &&
        (!clientETag  || clientETag === headers['Etag']) &&
        (!clientMTime || clientMTime >= mtime)) {
        // 304 response should not contain entity headers
        ['Content-Encoding',
         'Content-Language',
         'Content-Length',
         'Content-Location',
         'Content-MD5',
         'Content-Range',
         'Content-Type',
         'Expires',
         'Last-Modified'].forEach(function(entityHeader) {
            delete headers[entityHeader];
        });

        for (var aH in additionalHeaders) {
            headers[aH] = additionalHeaders[aH] || headers[aH];
        }

        Statique.sendRes(res, 304, contentType, null, headers);
        res.end();
        return Statique;
    }

    // Set cache-control  header
    headers["cache-control"] = "max-age=" + Statique._cache;
    for (var aH in additionalHeaders) {
        headers[aH] = additionalHeaders[aH] || headers[aH];
    }

    // file should cached
    Statique.sendRes(res, statusCode || 200, contentType, null, headers)

    var fileStream = Fs.createReadStream(fullPath);
    fileStream.pipe(res);

    return Statique;
};

/**
 * serveRoute
 * Serves a provided route.
 *
 * @name serveRoute
 * @function
 * @param {String} route The route that should be served
 * @param {Object} req The request object
 * @param {Object} res The response object
 * @return {Object} The Statique instance
 */
Statique.serveRoute = function (route, req, res) {

    var parsedUrl = Url.parse(req.url)
      , routeToServe = Statique.getRoute(
            route || parsedUrl.pathname
        ) || parsedUrl.pathname
      , stats = null
      , method = req.method.toLowerCase()
      , form = {
            data: ""
          , error: ""
          , _emitter: new Events.EventEmitter()
        }
      ;

    req.on("data", function (chunk) {
        form.data += chunk;
    });

    req.on("error", function (err) {
        form.error += err;
    });

    req.on("end", function () {
        form._emitter.emit("done", form);
    });

    if (routeToServe.url && typeof routeToServe.url[method] === "function") {
        try {
            routeToServe.url[method](req, res, form._emitter);
        } catch (e) {
            Statique.error(req, res, 500, "Internal Server Error");
            Debug.log(e.stack, "error");
        }
        return Statique;
    }

    if (typeof routeToServe.handler === "function") {
        try {
            routeToServe.handler(req, res, form._emitter);
        } catch (e) {
            Statique.error(req, res, 500, "Internal Server Error");
            Debug.log(e.stack, "error");
        }
        return Statique;
    }

    return Statique.serveFile(routeToServe, null, res, req);
};

/**
 * redirect
 * Redirects the user to the new url passed in the second argument.
 *
 * @name redirect
 * @function
 * @param {String} res The response object
 * @param {String} newUrl The new url where the user should be redirected
 * @return {Object} Statique object
 */
Statique.redirect = function (res, newUrl) {
    return Statique.sendRes(res, 301, "text", "Redirecting", {
        "location": newUrl
    });
};

/**
 * error
 * Sends an error to client
 *
 * @name error
 * @function
 * @param {Object} req The request object
 * @param {Object} res The response object
 * @param {Number} errCode The error code
 * @param {String} errMessage The error message
 * @return {Object} Statique object
 */
Statique.error = function (req, res, errCode, errMessage) {
    var configErrors = Object(Statique._errors)
      , errPage = configErrors[errCode]
      ;

    if (errPage) {
        return Statique.serveFile(errPage, errCode, res, req, {
            "cache-control": "no-cache"
        });
    }

    return Statique.sendRes(res, errCode, "text", errMessage);
};
<|endoftext|>


<commit_before>var ejs = require("ejs");
var fs = require("fs");
var template = null;
fs.readFile("template.ejs","utf-8",function (err,data) {
    if (err) throw new Error(err);
    template = ejs.compile(data);
});

module.exports = function (options) {
    return function (options) {
        var snippet = template(options).replace("\n","").replace(/\s+/g," ");
        return function (req,res,next) {
            req.locals.piwik = function () {
                return snippet;
            }
        };
    }(options);
};
<commit_msg>Fix template path for use in a module<commit_after>var ejs = require("ejs");
var fs = require("fs");
var path = require("path");

var template = null;
fs.readFile(path.join(__dirname,"template.ejs"),"utf-8",function (err,data) {
    if (err) throw new Error(err);
    template = ejs.compile(data);
});

module.exports = function (options) {
    return function (options) {
        var snippet = template(options).replace("\n","").replace(/\s+/g," ");
        return function (req,res,next) {
            req.locals.piwik = function () {
                return snippet;
            }
        };
    }(options);
};
<|endoftext|>


<commit_before>/*!
 * fill-range <https://github.com/jonschlinkert/fill-range>
 *
 * Copyright (c) 2014 Jon Schlinkert, contributors.
 * Licensed under the MIT license.
 */

'use strict';

var repeat = require('repeat-string');
var isNumber = require('is-number');

/**
 * Expose `fillRange`
 */

module.exports = fillRange;

function fillRange(a, b, increment, fn) {
  if (typeof increment === 'function') {
    fn = increment;
    increment = undefined;
  }

  var invalid = (/\./.test(a) || /\./.test(b))
    || (increment && !isNumber(increment))
    || (!isNumber(Math.abs(a)) && isNumber(Math.abs(b)))
    || (isNumber(Math.abs(a)) && !isNumber(Math.abs(b)));

  if (invalid) {
    return {invalid: [a, b, increment].filter(Boolean).join('..')};
  }

  var astr = a.toString();
  var bstr = b.toString();
  var padding;

  // Was an increment (step) passed?
  increment = typeof increment !== 'undefined'
    ? Math.abs(increment)
    : 1;

  // is the range alphabetical? or numeric?
  var isLetter = !isNumber(a);
  a = isLetter ? a.charCodeAt(0) : +a;
  b = isLetter ? b.charCodeAt(0) : +b;

  if (!isLetter) {
    padding = isPadded(a, b);
  }

  function positiveRange(a, b, increment, fn, isLetter) {
    var arr = [];
    var pad = '';
    var i = 0;
    var res;

    while (a <= b) {
      // var pad = !isLetter ? String(repeat('0', padding)) : '';
      // if (padding && !res && !isLetter) {
      //   a = pad + a;
      // }

      if (typeof fn === 'function') {
        res = fn(a, isLetter, pad, i++);
      } else if (isLetter) {
        res = String.fromCharCode(a);
      } else {
        res = String(a);
      }

      arr.push(res);
      a += increment;
    }
    return arr;
  }

  function negativeRange(a, b, increment, fn, isLetter) {
    var arr = [];
    var pad = '';
    var i = 0;
    var res;

    while (a >= b) {
      // var pad = !isLetter ? String(repeat('0', padding)) : '';
      // if (padding && !res && !isLetter) {
      //   a = pad + a;
      // }

      if (typeof fn === 'function') {
        res = fn(a, isLetter, pad, i++);
      } else if (isLetter) {
        res = String.fromCharCode(a);
      } else {
        res = String(a);
      }

      arr.push(res);
      a -= increment;
    }
    return arr;
  }

  function isPadded(a, b, isLetter) {
    var res = /^-*(0*)[0-9]/.exec(astr);
    var len = res && res[1].length;
    if (!!(res && len > 0)) {
      return len;
    }

    return false;
  }

  function expand(a, b, increment, fn) {
    if (b < a) {
      return negativeRange(a, b, increment, fn, isLetter, padding);
    }
    return positiveRange(a, b, increment, fn, isLetter, padding);
  }

  return expand(a, b, increment, fn)
}<commit_msg>refactored:<commit_after>/*!
 * fill-range <https://github.com/jonschlinkert/fill-range>
 *
 * Copyright (c) 2014 Jon Schlinkert, contributors.
 * Licensed under the MIT license.
 */

'use strict';

var repeat = require('repeat-string');
var isNumber = require('is-number');

/**
 * Expose `fillRange`
 */

module.exports = fillRange;

function fillRange(a, b, increment, fn) {
  if (typeof increment === 'function') {
    fn = increment;
    increment = undefined;
  }

  validateRange(a, b, increment);

  // Was an increment (step) passed?
  increment = typeof increment !== 'undefined'
    ? Math.abs(increment)
    : 1;

  var strA = a.toString();

  // is the range alphabetical? or numeric?
  var isLetter = !isNumber(a);
  a = isLetter ? a.charCodeAt(0) : +a;
  b = isLetter ? b.charCodeAt(0) : +b;

  var padding = isPadded(strA, isLetter);
  var res, pad, arr = [];
  var reverse = b < a;
  var i = 0;

  while (reverse ? (a >= b) : (a <= b)) {
    if (padding && !isLetter) {
      pad = padding(a);
    }

    if (typeof fn === 'function') {
      res = fn(a, isLetter, pad, i++);
    } else if (isLetter) {
      res = String.fromCharCode(a);
    } else {
      res = String(pad ? pad + a : a);
    }

    arr.push(res);

    if (reverse) {
      a -= increment
    } else {
      a += increment;
    }
  }
  return arr;
}

function isPadded(strA, isLetter) {
  return !isLetter && /^-*0+[1-9]/.test(strA)
    ? function (a) {
      var num = strA.length - a.toString().length;
      return repeat('0', num);
    } : false;
}

function validateRange(a, b, increment) {
  if (!/[\w\d]/.test(a) || !/[\w\d]/.test(b)) {
    throw new Error('fill-range: invalid range arguments.');
  }
  if (!isNumber(a) && isNumber(b)) {
    throw new TypeError('fill-range: incompatible range arguments.');
  }
  if (isNumber(a) && !isNumber(b)) {
    throw new TypeError('fill-range: incompatible range arguments.');
  }
  if (increment && !isNumber(increment)) {
    throw new TypeError('fill-range: invalid increment.');
  }
}<|endoftext|>


<commit_before>'use strict';

const plugins = require('./lib/input-plugins');

module.exports.plugins = plugins;
<commit_msg>:new: export fixtures tooooo<commit_after>'use strict';

const plugins = require('./lib/input-plugins');
const fixtures = require('./tests/fixtures');

module.exports = {
  fixtures,
  plugins
};
<|endoftext|>


<commit_before>/* INCLUDES */

var exports = module.exports = {};
var express = require('express');
var body_parser = require('body-parser');
var queries = require('./db/queries.js');
var store = require('./db/store.js');
var config = require('./config.json')
var Q = require("q");
var app = express();

const get = require('simple-get');
var jsdom = require("jsdom");
const guardian = require('guardian-js');

var NYT_KEY = config["NYT_KEY"];
var GUAR_KEY = config["GUAR_KEY"];
var guardApi = new guardian(GUAR_KEY, false);

/* CONFIG */

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/bower_components'));
// app.use(body_parser.json());

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', (request, response) => {
  response.render('pages/index');
});

/* ROUTES */

app.get('/api/topics', (request, response) => {
  queries.topics().then((data) => {
    response.json(data);
  })
});

app.get('/api/topic/:topic/articles', (request, response) => {
  queries.articlesFor(request.params.topic).then((data) => {
    response.json(data);
  })
});

app.get('/api/topic/:topic/name', (request, response) => {
  queries.topicName(request.params.topic).then((data) => {
    response.json(data);
  })
});

app.get('/api/article/:article', (request, response) => {
  queries.articleBias(request.params.article).then((data) => {
    response.json(data);
  })
});

app.post('/api/topic', (request, response) => {
  console.log("hello");
  crawlArticlesForTopic("wind power");
  response.sendStatus(200);
});

/* CONFIG */

app.use((req, res) => {
  // support ui router
  res.render('pages/index');
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

/* HELPER FUNCTIONS */

function crawlArticlesForTopic(topic) {
  var TopicDBObj = store.newTopic(topic);
  var NYTSource = store.newSource("New York Times", getSourceURLFromSourceName("New York Times"));
  var GUARSource = store.newSource("The Guardian", getSourceURLFromSourceName("The Guardian"));

  var NYT_data = getNYTArticles(topic);

  getGuardianArticles(topic).then(function(GUAR_data){

      var NYT_bodies = pullBodyFromURLSet(NYT_data, "new york times")
      var GUAR_bodies = pullBodyFromURLSet(GUAR_data, "guardian")
      var NYT_objs = createArticleJSObjects(NYT_data, NYT_bodies, "New York Times");
      var GUAR_objs = createArticleJSObjects(GUAR_data, GUAR_bodies, "The Guardian");

      var allObjs = NYT_objs.concat(GUAR_objs);
      allObjs.forEach(function(value, index) {
          var source = value.source;

          store.newArticle(value).then(function(ArticleDBObj) {
              queries.sourceByName(source).then(function(result){
                  ArticleDBObj.updateAttributes({
                      "topic;id": TopicDBObj.id,
                      "sourceId": result.id
                  });
              });
          });

      });
 });

}

function getNYTArticles(topic) {
   var urlString = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
   urlString = urlString + "?q=" + topic.replace(' ', '+') + "&fq=document_type:(\"article\")" + "&api-key=" + NYT_KEY + "&response-format=jsonp" + "&callback=svc_search_v2_articlesearch";

   var NYT_data = [];

   get.concat(urlString, function (err, res, data) {
     if (err) throw err

     var docs = JSON.parse(data.toString()).response.docs;

     docs.forEach(function(value, index) {
       var article_data = {
         url: value["web_url"],
         headline: value.headline.main
       }
       NYT_data.push(article_data);

     });

   });

   return NYT_data;
}

function getGuardianArticles(topic) {
    var header = {
      "type": "article"
    };

    var GUAR_data = [];

    return guardApi.content.search(topic, header).then(function(response){

          var docs = JSON.parse(response.body.toString()).response.results;

          docs.forEach(function(value, index) {
            var article_data = {
              url: value["webUrl"],
              headline: value["webTitle"]
            }

            GUAR_data.push(article_data);
          });

          return GUAR_data;
     });

}

function pullBodyFromURLSet(data, source) {
  bodyList = [];

  data.forEach(function(value, index) {
      pullBodyOfURL(value.url, source, function(body) {
          bodyList.push(body);
      });
    });

    return bodyList;
}

function pullBodyOfURL(url, source) {
  return jsdom.env({
    url: url,
    scripts: ["http://code.jquery.com/jquery.js"],
    done: function (err, window) {
        var $ = window.$;

        var bodyStrings = [];
        var storyblocks = $(divClassTagFromSource(source));
        console.log("HELLOOooooooooooooooooooooo");
        console.log(storyblocks);
        storyblocks.forEach(function(value, index) {
            bodyStrings.push(value.text());
        });

        var storyText = bodyStrings.join(" ");
        return storyText;
    }
  });

}

function divClassTagFromSource(source) {
    if (source === "new york times")
      return '.story-body-text.story-content';
    else if (source === "guardian")
      return 'content__article-body.from-content-api.js-article__body p';

}

function createArticleJSObjects(data, bodies, source) {
  var objs = [];
  for (var i = 0; i < data.length; i++) {
    var urlVal = data[i].url;
    var headline = data[i].headline;
    var bodyVal = bodies[i];

    var obj = {
      url: urlVal,
      body: bodyVal,
      source: source,
      headline: headline
    }

    objs.push(obj);
  }

  return objs;
}

function getSourceURLFromSourceName(sourceName) {
  if (sourceName === "New York Times") {
    return "https://www.nytimes.com";
  } else if (sourceName === "The Guardian") {
    return "https://www.theguardian.com";
  }
}<commit_msg>fix sebi forgetting a . :)<commit_after>/* INCLUDES */

var exports = module.exports = {};
var express = require('express');
var body_parser = require('body-parser');
var queries = require('./db/queries.js');
var store = require('./db/store.js');
var config = require('./config.json')
var Q = require("q");
var app = express();

const get = require('simple-get');
var jsdom = require("jsdom");
const guardian = require('guardian-js');

var NYT_KEY = config["NYT_KEY"];
var GUAR_KEY = config["GUAR_KEY"];
var guardApi = new guardian(GUAR_KEY, false);

/* CONFIG */

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/bower_components'));
// app.use(body_parser.json());

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', (request, response) => {
  response.render('pages/index');
});

/* ROUTES */

app.get('/api/topics', (request, response) => {
  queries.topics().then((data) => {
    response.json(data);
  })
});

app.get('/api/topic/:topic/articles', (request, response) => {
  queries.articlesFor(request.params.topic).then((data) => {
    response.json(data);
  })
});

app.get('/api/topic/:topic/name', (request, response) => {
  queries.topicName(request.params.topic).then((data) => {
    response.json(data);
  })
});

app.get('/api/article/:article', (request, response) => {
  queries.articleBias(request.params.article).then((data) => {
    response.json(data);
  })
});

app.post('/api/topic', (request, response) => {
  console.log("hello");
  crawlArticlesForTopic("wind power");
  response.sendStatus(200);
});

/* CONFIG */

app.use((req, res) => {
  // support ui router
  res.render('pages/index');
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

/* HELPER FUNCTIONS */

function crawlArticlesForTopic(topic) {
  var TopicDBObj = store.newTopic(topic);
  var NYTSource = store.newSource("New York Times", getSourceURLFromSourceName("New York Times"));
  var GUARSource = store.newSource("The Guardian", getSourceURLFromSourceName("The Guardian"));

  var NYT_data = getNYTArticles(topic);

  getGuardianArticles(topic).then(function(GUAR_data){

      var NYT_bodies = pullBodyFromURLSet(NYT_data, "new york times")
      var GUAR_bodies = pullBodyFromURLSet(GUAR_data, "guardian")
      var NYT_objs = createArticleJSObjects(NYT_data, NYT_bodies, "New York Times");
      var GUAR_objs = createArticleJSObjects(GUAR_data, GUAR_bodies, "The Guardian");

      var allObjs = NYT_objs.concat(GUAR_objs);
      allObjs.forEach(function(value, index) {
          var source = value.source;

          store.newArticle(value).then(function(ArticleDBObj) {
              queries.sourceByName(source).then(function(result){
                  ArticleDBObj.updateAttributes({
                      "topic;id": TopicDBObj.id,
                      "sourceId": result.id
                  });
              });
          });

      });
 });

}

function getNYTArticles(topic) {
   var urlString = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
   urlString = urlString + "?q=" + topic.replace(' ', '+') + "&fq=document_type:(\"article\")" + "&api-key=" + NYT_KEY + "&response-format=jsonp" + "&callback=svc_search_v2_articlesearch";

   var NYT_data = [];

   get.concat(urlString, function (err, res, data) {
     if (err) throw err

     var docs = JSON.parse(data.toString()).response.docs;

     docs.forEach(function(value, index) {
       var article_data = {
         url: value["web_url"],
         headline: value.headline.main
       }
       NYT_data.push(article_data);

     });

   });

   return NYT_data;
}

function getGuardianArticles(topic) {
    var header = {
      "type": "article"
    };

    var GUAR_data = [];

    return guardApi.content.search(topic, header).then(function(response){

          var docs = JSON.parse(response.body.toString()).response.results;

          docs.forEach(function(value, index) {
            var article_data = {
              url: value["webUrl"],
              headline: value["webTitle"]
            }

            GUAR_data.push(article_data);
          });

          return GUAR_data;
     });

}

function pullBodyFromURLSet(data, source) {
  bodyList = [];
  data.forEach(function(value, index) {
    pullBodyOfURL(value.url, source, function(body) {
      bodyList.push(body);
    });
  });
  return bodyList;
}

function pullBodyOfURL(url, source, callback) {
  return jsdom.env({
    url: url,
    scripts: ["http://code.jquery.com/jquery.js"],
    done: function (err, window) {
        var $ = window.$;

        var bodyStrings = [];
        var storyblocks = $(divClassTagFromSource(source));
        console.log("at: " + url);
        console.log("found: " + storyblocks.length);
        storyblocks.each(function(idx, val) {
            bodyStrings.push($(val).text());
        });

        var storyText = bodyStrings.join(" ");
        callback(storyText);
    }
  });

}

function divClassTagFromSource(source) {
    if (source === "new york times")
      return '.story-body-text.story-content';
    else if (source === "guardian")
      return '.content__article-body.from-content-api.js-article__body p';

}

function createArticleJSObjects(data, bodies, source) {
  var objs = [];
  for (var i = 0; i < data.length; i++) {
    var urlVal = data[i].url;
    var headline = data[i].headline;
    var bodyVal = bodies[i];

    var obj = {
      url: urlVal,
      body: bodyVal,
      source: source,
      headline: headline
    }

    objs.push(obj);
  }

  return objs;
}

function getSourceURLFromSourceName(sourceName) {
  if (sourceName === "New York Times") {
    return "https://www.nytimes.com";
  } else if (sourceName === "The Guardian") {
    return "https://www.theguardian.com";
  }
}<|endoftext|>


<commit_before>var WebSocket = require('ws');
var debug = require('debug')('signalk:client');

var Promise = require('bluebird');
var agent = require('superagent-promise')(require('superagent'), Promise);

function Client(host, port) {
  this.host = host;
  this.port = port;
}

Client.prototype.get = function(path) {
  return agent('GET', 'http://' + this.host + ':' + this.port + path).then(function(result) {
    return result.res.body;
  });
}

Client.prototype.connect = function(options) {
  debug('connect');
  var host = this.host;
  var port = this.port;
  if (options) {
    host = options.host || host;
    port = options.port || port;
  }
  if (host && port) {
    return connectDelta(options.host + ":" + options.port, options.onData, options.onConnect, options.onDisconnect, options.onError)
  }
  return discoverAndConnect(options);
}

function discoverAndConnect(options) {
  debug('discoverAndConnect');
  try {
    var mdns = require('mdns');
  } catch(ex) {
    console.log("Discovery requires mdns, please install it with 'npm install mdns' or specify host and port");
    return
  }
  return new Promise(function(resolve, reject) {
    var browser = mdns.createBrowser(mdns.tcp('signalk-ws'));
    browser.on('serviceUp', function(service) {
      debug("Discovered signalk-ws with txtRecord:" + JSON.stringify(service.txtRecord, null, 2));
      //TODO handle multiple discoveries
      resolve(service);
    });
    debug("Starting mdns discovery");
    browser.start();
  }).then(function(service) {
    return connectDelta(service.host + ":" + service.port, options.onData, options.onConnect, options.onDisconnect, options.onError);
  });
}

Client.prototype.connectDelta = function(hostname, callback, onConnect, onDisconnect, onError) {
  debug("Connecting to " + hostname);
  var url = "ws://" + hostname + "/signalk/v1/stream?stream=delta&context=self";
  if (typeof Primus != 'undefined') {
    debug("Using Primus");
    var signalKStream = Primus.connect(url, {
      reconnect: {
        maxDelay: 15000,
        minDelay: 500,
        retries: Infinity
      }
    });
    signalKStream.on('data', callback);
    return {
      disconnect: function() {
        signalKStream.destroy();
        debug('Disconnected');
      }
    }
  } else {
    debug("Using ws");
    var connection = new WebSocket(url);
    connection.onopen = function(msg) {
      debug("open");
      var sub = '{"context":"vessels.self","subscribe":[{"path":"*"}]}';
      connection.send(sub);
      if (onConnect) onConnect();
    };
    connection.onerror = function(error) {
      debug("error:" + error);
      if (onError) {
        onError(error)
      }
    };
    connection.onmessage = function(msg) {
      callback(JSON.parse(msg.data));
    };
    return {
      disconnect: function() {
        connection.close();
        debug('Disconnected');
      }
    }
  }
}

function getSelf(host) {
  return agent('GET', "http://" + (host || this.host + ":" + this.port) + "/signalk/v1/api/vessels/self");
}

Client.prototype.getSelfMatcher = function(host) {
  return getSelf(host || this.host + ":" + this.port).then(function(result) {
    var selfData = result.body;
    var selfId = selfData.mmsi || selfData.uuid;
    if (selfId) {
      var selfContext = 'vessels.' + selfId;
      return function(delta) {
        return delta.context === 'self' || delta.context === 'vessels.self' || delta.context === selfContext;
      }
    } else {
      return function(delta) {
        return true;
      }
    }
  });
}

module.exports = {
  Client: Client
}<commit_msg>Add this, closes #1<commit_after>var WebSocket = require('ws');
var debug = require('debug')('signalk:client');

var Promise = require('bluebird');
var agent = require('superagent-promise')(require('superagent'), Promise);

function Client(host, port) {
  this.host = host;
  this.port = port;
}

Client.prototype.get = function(path) {
  return agent('GET', 'http://' + this.host + ':' + this.port + path).then(function(result) {
    return result.res.body;
  });
}

Client.prototype.connect = function(options) {
  debug('connect');
  var host = this.host;
  var port = this.port;
  if (options) {
    host = options.host || host;
    port = options.port || port;
  }
  if (host && port) {
    return this.connectDelta(options.host + ":" + options.port, options.onData, options.onConnect, options.onDisconnect, options.onError)
  }
  return discoverAndConnect(options);
}

function discoverAndConnect(options) {
  debug('discoverAndConnect');
  try {
    var mdns = require('mdns');
  } catch(ex) {
    console.log("Discovery requires mdns, please install it with 'npm install mdns' or specify host and port");
    return
  }
  return new Promise(function(resolve, reject) {
    var browser = mdns.createBrowser(mdns.tcp('signalk-ws'));
    browser.on('serviceUp', function(service) {
      debug("Discovered signalk-ws with txtRecord:" + JSON.stringify(service.txtRecord, null, 2));
      //TODO handle multiple discoveries
      resolve(service);
    });
    debug("Starting mdns discovery");
    browser.start();
  }).then(function(service) {
    return connectDelta(service.host + ":" + service.port, options.onData, options.onConnect, options.onDisconnect, options.onError);
  });
}

Client.prototype.connectDelta = function(hostname, callback, onConnect, onDisconnect, onError) {
  debug("Connecting to " + hostname);
  var url = "ws://" + hostname + "/signalk/v1/stream?stream=delta&context=self";
  if (typeof Primus != 'undefined') {
    debug("Using Primus");
    var signalKStream = Primus.connect(url, {
      reconnect: {
        maxDelay: 15000,
        minDelay: 500,
        retries: Infinity
      }
    });
    signalKStream.on('data', callback);
    return {
      disconnect: function() {
        signalKStream.destroy();
        debug('Disconnected');
      }
    }
  } else {
    debug("Using ws");
    var connection = new WebSocket(url);
    connection.onopen = function(msg) {
      debug("open");
      var sub = '{"context":"vessels.self","subscribe":[{"path":"*"}]}';
      connection.send(sub);
      if (onConnect) onConnect();
    };
    connection.onerror = function(error) {
      debug("error:" + error);
      if (onError) {
        onError(error)
      }
    };
    connection.onmessage = function(msg) {
      callback(JSON.parse(msg.data));
    };
    return {
      disconnect: function() {
        connection.close();
        debug('Disconnected');
      }
    }
  }
}

function getSelf(host) {
  return agent('GET', "http://" + (host || this.host + ":" + this.port) + "/signalk/v1/api/vessels/self");
}

Client.prototype.getSelfMatcher = function(host) {
  return getSelf(host || this.host + ":" + this.port).then(function(result) {
    var selfData = result.body;
    var selfId = selfData.mmsi || selfData.uuid;
    if (selfId) {
      var selfContext = 'vessels.' + selfId;
      return function(delta) {
        return delta.context === 'self' || delta.context === 'vessels.self' || delta.context === selfContext;
      }
    } else {
      return function(delta) {
        return true;
      }
    }
  });
}

module.exports = {
  Client: Client
}<|endoftext|>