<commit_before>var Utils = {
    loaded: true,
    enabled: true,

    config: {
        enableAjaxFilter: false,
        minDuration: 50
    },

    adapters: {},

    log: function (msg) {
        //console.log('### LOG');
        //console.log(msg);
    },

    warn: function (msg) {
        console.log('### WARN');
        console.log(msg);
    },

    error: function (msg) {
        console.log('### ERROR');
        console.log(msg);
    },

    send: function (events, metrics) {
        console.log('### SEND');
        console.log(events.toString(), metrics);
    },

    slice: function (a) {
        return Array.prototype.slice.call(a);
    },

    aliasMethodChain: function ($, method, label, wrapper) {
        var e = $[method];
        if ('function' == typeof e) {
            var f = '__' + method + '_without_' + label + '__',
                g = '__' + method + '_with_' + label + '__';

            $[f] = e;
            $[g] = $[method] = wrapper;
        }
        return $;
    },

    __super__: function () {
        throw new Error('Cannot call __super__ outside of a wrapped function');
    },
    __empty__: function () {
    }
};

Utils.wrap = function (originalFunction, wrapper) {
    return function () {
        var currentSuper = Utils.__super__,
            self = this,
            args = Utils.slice(arguments);

        try {
            if ('function' == typeof originalFunction) {
                Utils.__super__ = function () {
                    return this === Utils ?
                        0 === arguments.length ?
                            originalFunction.apply(self, args) :
                            originalFunction.apply(self, arguments) :
                        originalFunction.apply(this, arguments);
                }
            } else {
                Utils.__super__ = Utils.__empty__();
            }

            return wrapper.apply(this, arguments);
        } finally {
            Utils.__super__ = currentSuper;
        }
    }
};

var WeppyEmber = function (Utils, Ember, $) {
    'use strict';
    var EmberAdapter = {
        VERSION: '0.0.10'
    };

    if (Utils.plugins && Utils.plugins.Ember) {
        Utils.plugins.Ember.VERSION === EmberAdapter.VERSION ?
            Utils.warn('Already loaded weppy-ember v' + EmberAdapter.VERSION) :
            Utils.error('Failed to load weppy-ember v' + EmberAdapter.VERSION + ': ' +
            'another version of weppy-ember (v' + Utils.plugins.Ember.VERSION + ') was already loaded');
    } else if (void 0 === Ember) {
        Utils.error('Failed to load weppy-ember: Ember could not be found');
    } else if (void 0 === $) {
        Utils.error('Failed to load weppy-ember: $ could not be found');
    } else {
        Utils.log('Initializing weppy-ember v' + EmberAdapter.VERSION);
        Utils.config.enableAjaxFilter = Utils.config.enableAjaxFilter || false;
        Utils.config.minDuration = Utils.config.minDuration || 50;

        var traceStack = [],
            getLastTraceItem = function () {
                return traceStack[traceStack.length - 1];
            },
            traceAjaxRequest = function (method, url) {
                this.method = method;
                this.url = url;
                this.pending = true;
                this.trace = getLastTraceItem();

                this.trace && this.trace.events.push(this);
                this.startTime = Date.now();
            };

        traceAjaxRequest.prototype.stop = function () {
            if (this.pending) {
                this.stopTime = Date.now();
                this.pending = false;
            } else {
                Utils.warn('[BUG] Attempted to stop an AJAX request twice.');
            }
        };

        traceAjaxRequest.prototype.serialize = function (time) {
            if (this.pending === false) {
                time = time || 0;
                return ['a', this.method, this.url, this.startTime - time, this.stopTime - this.startTime];
            }
        };

        var traceViewRender = function (viewName) {
            this.viewName = viewName;
            this.pending = true;
            this.trace = getLastTraceItem();

            this.trace && this.trace.events.push(this);
            this.startTime = Date.now();
        };

        traceViewRender.prototype.stop = function () {
            if (this.pending) {
                this.stopTime = Date.now();
                this.pending = false;
            } else {
                Utils.warn('[BUG] Attempted to stop a view render twice.')
            }
        };

        traceViewRender.prototype.serialize = function (time) {
            if (this.pending === false) {
                time = time || 0;
                return ['r', this.viewName, this.startTime - time, this.stopTime - this.startTime];
            }
        };

        var trace = function (klass, method, pattern) {
            this.klass = klass;
            this.method = method;
            this.pattern = pattern;
            this.events = [];
            this.finalized = false;

            traceStack.push(this);
            this.startTime = Date.now();
        };

        trace.prototype.pause = function () {
            for (var i = 1; i <= traceStack.length; i++) {
                traceStack[traceStack.length - i] === this &&
                traceStack.splice(traceStack.length - i, 1);
            }
        };

        trace.prototype.resume = function () {
            this.pause();
            traceStack.push(this);
        };

        trace.prototype.finalize = function () {
            if (this.finalized === !0) {
                Utils.warn('[BUG] Attempted to finalize a trace twice.');
                return;
            }

            this.pause();

            for (var i = 0; i < this.events.length; i++) {
                if (this.events[i].pending) return;
            }

            this.stopTime = Date.now();
            this.finalized = !0;
            this.duration = this.stopTime - this.startTime;

            if (this.duration < (Utils.config.minDuration || 1)) {
                Utils.log('Dropped: ' + this.klass + '.' + this.method + ' (' + this.pattern + '), took ' +
                this.duration + 'ms. (minDuration is ' + Utils.config.minDuration + 'ms)');
                return;
            }

            if (Utils.config.enableAjaxFilter === true) {
                var ajaxRequestToTrace = false;

                for (i = 0; i < this.events.length; i++)
                    if (this.events[i] instanceof traceAjaxRequest) {
                        ajaxRequestToTrace = true;
                        break
                    }

                if (!ajaxRequestToTrace) {
                    Utils.log('Dropped: ' + this.klass + '.' + this.method + ' (' + this.pattern + '), took ' +
                    this.duration + 'ms. (enableAjaxFilter is true)');
                    return;
                }
            }

            Utils.log('Sending: ' + this.klass + '.' + this.method + ' (' + this.pattern + '), took ' + this.duration +
            'ms.');

            this.url = window.location.hash || window.location.pathname;

            var metrics = {
                startTime: this.startTime,
                duration: this.duration,
                url: this.url
            };

            this.klass && this.klass.length && (metrics.klass = this.klass);
            this.method && this.method.length && (metrics.method = this.method);
            this.pattern && this.pattern.length && (metrics.pattern = this.pattern);

            var events = [];
            for (i = 0; i < this.events.length; i++) {
                events.push(this.events[i].serialize(this.startTime));
            }

            Utils.send(events, metrics)
        };

        var getRoutePattern = function (EmberRoute) {
                try {
                    var routeName = EmberRoute.get('routeName'),
                        segments = EmberRoute.get('router.router.recognizer.names')[routeName].segments,
                        listOfSegments = [];

                    for (var i = 0; i < segments.length; i++) {
                        var segment = null;
                        try {
                            segment = segments[i].generate();
                        } catch (err) {
                            segment = ':' + segments[i].name;
                        }
                        segment && listOfSegments.push(segment);
                    }
                    return '/' + listOfSegments.join('/');
                } catch (err) {
                    return '/';
                }
            },
            traceRouteEvent = function () {
                var pattern = getRoutePattern(this),
                    lastTrace = getLastTraceItem();

                if (lastTrace) {
                    lastTrace.klass = this.constructor.toString();
                    lastTrace.method = void 0;
                    return lastTrace.pattern = pattern;
                } else {
                    new trace(this.constructor.toString(), void 0, pattern);
                    return this._super.apply(this, Utils.slice(arguments));
                }
            };

        Ember.Route.reopen({
            beforeModel: traceRouteEvent,
            afterModel: traceRouteEvent,
            enter: traceRouteEvent
            // TODO this currently causes 'TypeError: Cannot set property '_qpDelegate' of undefined'
            //setup: traceRouteEvent
        });

        Ember.CoreView.reopen({
            /**
             * Triggers a named event for the object. Any additional arguments
             * will be passed as parameters to the functions that are subscribed to the
             * event.
             *
             * @method trigger
             * @param {String} eventName The name of the event
             * @param {Object...} args Optional arguments to pass on
             */
            trigger: function (eventName) {
                var className = this.constructor.toString(),
                    isNotEmberClass = (
                    'Ember' !== className.substr(0, 5) &&
                        //(subclass of Ember...)
                    'Ember' !== className.substr(13, 5)),

                    // TODO this caused logging only for route transitions for me. why?
                    //isEvent = this.constructor.prototype.hasOwnProperty(eventName),
                    isEvent = true,

                    shouldTrace = !getLastTraceItem() &&
                        isNotEmberClass &&
                        isEvent;

                if (shouldTrace) {
                    new trace(this.constructor.toString(), eventName);
                }

                return this._super.apply(this, Utils.slice(arguments));
            }
        });

        var wrap = function (method) {
                var traceItem = getLastTraceItem();

                if (traceItem) {
                    'undefined' == typeof traceItem.pattern && (traceItem.klass = this.constructor.toString());
                    traceItem.method = method;
                } else {
                    new trace(this.constructor.toString(), method);
                }
            },
            wrapEvent = function (eventName, callback) {
                if ('function' == typeof callback) {
                    return Utils.wrap(callback, function () {
                        wrap.call(this, eventName);
                        return Utils.__super__();
                    });
                } else {
                    return callback;
                }
            };

        Ember.ActionHandler.reopen({
            willMergeMixin: function (props) {
                var eventName,
                    parent = this._super(props);

                if (props._actions) {
                    for (eventName in props._actions) {
                        props._actions.hasOwnProperty(eventName) &&
                        (props._actions[eventName] = wrapEvent(eventName, props._actions[eventName]));
                    }
                } else if (props.events) {
                    for (eventName in props.events) {
                        props.events.hasOwnProperty(eventName) &&
                        (props.events[eventName] = wrapEvent(eventName, props.events[eventName]));
                    }
                }
                return parent;
            }
        });

        var subclassPattern = new RegExp('<(?:\\(subclass of )?(.*?)\\)?:.*>');
        Ember.subscribe('render.view', {
            before: function (eventName, time, container) {
                if (getLastTraceItem()) {
                    var parentClass = container.object.match(subclassPattern)[1];
                    if ('Ember' !== parentClass.substr(0, 5) && 'LinkView' !== parentClass) {
                        return new traceViewRender(parentClass);
                    }
                }
            },
            after: function (eventName, time, container, tracer) {
                tracer && tracer.stop();
            }
        });

        Ember.run.backburner.options.onEnd = Utils.wrap(Ember.run.backburner.options.onEnd, function (current, next) {
            if (!next && traceStack.length) {
                for (var d = 0; d < traceStack.length; d++) {
                    traceStack[d].finalize();
                }
            }
            return Utils.__super__();
        });

        Utils.aliasMethodChain($, 'ajax', 'instrumentation', Utils.wrap($.ajax, function () {
            if (getLastTraceItem()) {
                var request = arguments[1] || arguments[0],
                    type = request.type || 'GET',
                    url = request.url || arguments[0];

                'string' == typeof request && (request = {});
                var tracer = new traceAjaxRequest(type, url);

                request.success = Utils.wrap(request.success, function () {
                    tracer.trace.resume();
                    tracer.stop();
                    return Utils.__super__();
                });

                request.error = Utils.wrap(request.error, function () {
                    tracer.trace.resume();
                    tracer.stop();
                    return Utils.__super__();
                });

                request.url = url;

                return Utils.__super__(request);
            }
            return Utils.__super__();
        }));

        Utils.adapters.Ember = EmberAdapter;
        Utils.log('Sucessfully loaded weppy-ember v' + EmberAdapter.VERSION);
    }
}(Utils, Ember, $);
<commit_msg>remove old file<commit_after><|endoftext|>


<commit_before>// test.js
// Hello, World<commit_msg>added alert to test<commit_after>// test.js
alert('Hello, World');<|endoftext|>


<commit_before>(function (module) {
    module.factory('Events', ['$filter', EventsService]);

    function EventsService($filter) {
        var service = {
            date: '',

            addConvertedTime: function (project) {
                project.reviews = service.update(project.reviews);
                project.samples = service.update(project.samples);
                project.processes = service.update(project.processes);
                project.notes = service.update(project.notes);
                project.drafts = service.update(project.drafts);
                return project;
            },

            update: function (items) {
                items.forEach(function (item) {
                    var item_date = new Date(item.mtime.epoch_time * 1000);
                    item.converted_mtime = Date.UTC(item_date.getUTCFullYear(), item_date.getUTCMonth(), item_date.getUTCDate());
                });
                return items;
            },

            prepareCalendarEvent: function (items, title) {
                var calendar_event = [];
                if (items.length !== 0) {
                    var grouped_by_convertedtime = $filter('groupBy')(items, 'converted_mtime');
                    Object.keys(grouped_by_convertedtime).forEach(function (key) {
                        var d = new Date(0);
                        var value = grouped_by_convertedtime[key][0];
                        d.setUTCSeconds(value.mtime.epoch_time);
                        calendar_event.push({
                            title: grouped_by_convertedtime[key].length + " " + title,
                            start: d,
                            description: '',
                            tooltip: "This is a cool event"
                        });
                    });
                }
                return calendar_event;
            },

            updateDate: function (project, currentdate, nextdate) {
                var today = new Date();
                var today_utc = Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
                if (today_utc === currentdate) {
                    project.date = '';
                    project.nextdate = '';
                } else {
                    project.date = currentdate;
                    project.nextdate = nextdate;
                }
                return project;
            }
        };
        return service;
    }
}(angular.module('materialscommons')));
<commit_msg>Fix the tooltip for calendar entries to show the names of all the entries that were created. Rework the code a bit by pulling out methods that are only used internally from the global service and hiding them in the closure.<commit_after>(function (module) {
    module.factory('Events', ['$filter', EventsService]);

    function EventsService($filter) {
        function update(items) {
            items.forEach(function (item) {
                var item_date = new Date(item.mtime.epoch_time * 1000);
                item.converted_mtime = Date.UTC(item_date.getUTCFullYear(), item_date.getUTCMonth(), item_date.getUTCDate());
            });
            return items;
        }

        return {
            addConvertedTime: function (project) {
                project.reviews = update(project.reviews);
                project.samples = update(project.samples);
                project.processes = update(project.processes);
                project.notes = update(project.notes);
                project.drafts = update(project.drafts);
                return project;
            },

            prepareCalendarEvent: function (items, title) {
                var calendar_event = [];
                if (items.length !== 0) {
                    var groupedByConvertedTime = $filter('groupBy')(items, 'converted_mtime');
                    Object.keys(groupedByConvertedTime).forEach(function (key) {
                        var d = new Date(0);
                        var value = groupedByConvertedTime[key][0];
                        d.setUTCSeconds(value.mtime.epoch_time);
                        var tooltip = groupedByConvertedTime[key].map(function (e) {return e.name;}).join('\n');
                        calendar_event.push({
                            title: groupedByConvertedTime[key].length + " " + title,
                            start: d,
                            description: '',
                            tooltip: tooltip
                        });
                    });
                }
                return calendar_event;
            },

            updateDate: function (project, currentdate, nextdate) {
                var today = new Date();
                var today_utc = Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
                if (today_utc === currentdate) {
                    project.date = '';
                    project.nextdate = '';
                } else {
                    project.date = currentdate;
                    project.nextdate = nextdate;
                }
                return project;
            }
        }
    }
}(angular.module('materialscommons')));
<|endoftext|>


<commit_before>// require koa and its modules
const Koa = require('koa')
const session = require('koa-session')
const bodyparser = require('koa-bodyparser')
const hbs = require('koa-hbs')
const json = require('koa-json')

// require other modules
const path = require('path')
require('dotenv').config()

// require user modules
const passport = require('./lib/passport')
const router = require('./lib/router')
const variables = require('./lib/middlewares/variables')

const debug = process.env.NODE_ENV !== 'production'
const port = process.env.PORT || 5121

const app = new Koa()

app.use(bodyparser())
app.keys = [debug ? 'oasis' : process.env.KEY]
app.use(session(app))

hbs.registerHelper('json', JSON.stringify)
app.use(hbs.middleware({
  viewPath: path.join(__dirname, 'views'),
  defaultLayout: 'layout',
  disableCache: debug
}))
app.use(json())
app.use(variables)
passport(app)
router(app)

if(debug) {
  const webpackMiddleware = require('koa-webpack')
  app.use(webpackMiddleware())
}

app.listen(port, () => {
  console.log(`listening on http://localhost:${port}`)
})<commit_msg>Add some middlewares<commit_after>// require koa and its modules
const Koa = require('koa')
const session = require('koa-session')
const bodyparser = require('koa-bodyparser')
const ejs = require('koa-ejs')
const json = require('koa-json')

// require other modules
const path = require('path')
require('dotenv').config()
const fs = require('fs')

// require user modules
const passport = require('./lib/passport')
const router = require('./lib/router')
const variables = require('./lib/middlewares/variables')

const debug = process.env.NODE_ENV !== 'production'
const port = process.env.PORT || 5121

const app = new Koa()
app.use(bodyparser({
  detectJSON: ctx => /\.json$/i.test(ctx.path)
}))
app.keys = [debug ? 'oasis' : process.env.KEY]
app.use(session(app))

ejs(app, {
  root: path.join(__dirname, 'views'),
  layout: 'layout',
  viewExt: 'ejs',
  cache: !debug,
  debug
})
app.use(json())
app.use(variables)
passport(app)
router(app)

if(debug) {
  const webpackMiddleware = require('koa-webpack')
  const DashboardPlugin = require('webpack-dashboard/plugin')
  const webpack = require('webpack')
  const webpackConfig = require('./webpack.config')
  const compiler = webpack(webpackConfig)
  compiler.apply(new DashboardPlugin())
  app.use(webpackMiddleware({
    compiler
  }))
}

// create repos dir
fs.mkdir(path.join(__dirname, 'repos'), () => null)

app.listen(port, () => {
  console.log(`listening on http://localhost:${port}`) // eslint-disable-line
})
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/* jshint forin: false */
var util = require('util');
var Transport = require('winston-uber').Transport;
var NodeSol = require('nodesol-write').NodeSol;
var KafkaRestClient = require('kafka-rest-client');
var hostName = require('os').hostname();
var extend = require('xtend');

function KafkaLogger(options) {
    if (!(this instanceof KafkaLogger)) {
        return new KafkaLogger(options);
    }

    var self = this;

    function onConnect(err) {
        if (!err) {
            if (self.logger) {
                self.logger.info('KafkaClient connected to kafka');
            }
            self.connected = true;
            self._flush();
        } else {
            if (self.logger) {
                self.logger.warn('KafkaClient could not connect to kafka');
            }
            // connection failed, purge queue.
            self.initQueue.length = 0;
        }
    }

    function onKafkaRestClientConnect(err) {
        if (!err) {
            if (self.logger) {
                self.logger.info('KafkaRestClient connected to kafka');
            }
            self.kafkaRestClientConnected = true;
            self._flush();
        } else {
            if (self.logger) {
                self.logger.warn('KafkaRestClient could not connect to kafka');
            }
        }
    }

    options = options || {};

    Transport.call(this, options);
    this.topic = options.topic || 'unknown';
    this.leafHost = options.leafHost || 'localhost';
    this.leafPort = options.leafPort || 9093;
    this.proxyHost = options.proxyHost || 'localhost';
    if ('proxyPort' in options && options.proxyPort) {
        this.proxyPort = options.proxyPort;
    }
    this.logger = options.logger;
    this.properties = options.properties || {};
    this.dateFormats = options.dateFormats || { isodate: 'iso' };
    this.peerId = options.hasOwnProperty('peerId') ? options.peerId : -1;
    this.workerId = options.hasOwnProperty('workerId') ? options.workerId : -1;
    this.logTemplate = {
        host: hostName,
        level: "LOGLEVELHERE",
        msg: "MESSAGEHERE"
    };
    for (var dateFormat in this.dateFormats) {
        this.logTemplate[dateFormat] = this.dateFormats[dateFormat];
    }
    for (var property in this.properties) {
        this.logTemplate[property] = this.properties[property];
    }

    this.kafkaProber = options.kafkaProber || null;
    this.failureHandler = options.failureHandler || null;
    this.kafkaClient = options.kafkaClient || null;
    this.isDisabled = options.isDisabled || null;

    this.connected = true;
    this.kafkaRestClientConnected = false;
    this.initQueue = [];
    this.initTime = null;
    this.statsd = options.statsd || null;
    if (!this.kafkaRestClient) {
        if (this.proxyPort) {
            var kafkaRestClientOptions = {
                proxyHost: this.proxyHost,
                proxyPort: this.proxyPort,
                statsd: this.statsd
            };
            if ('maxRetries' in options) {
                kafkaRestClientOptions['maxRetries'] = options.maxRetries;
            }
            if ('blacklistMigrator' in options && 'blacklistMigratorUrl' in options) {
                if (options.blacklistMigrator) {
                    kafkaRestClientOptions['blacklistMigrator'] = options.blacklistMigrator;
                    kafkaRestClientOptions['blacklistMigratorUrl'] = options.blacklistMigratorUrl;
                }
            }
            if ('statsd' in options) {
                kafkaRestClientOptions['statsd'] = options.statsd;
            }
            this.kafkaRestClient = new KafkaRestClient(kafkaRestClientOptions);
            this.kafkaRestClient.connect(onKafkaRestClientConnect);
        }
    } else {
        this.kafkaRestClientConnected = true;
    }

    if (!this.kafkaClient) {
        this.connected = false;
        this.initTime = Date.now();
        this.kafkaClient = new NodeSol({
            leafHost: this.leafHost, leafPort: this.leafPort
        });
        this.kafkaClient.connect(onConnect);
    }
}

util.inherits(KafkaLogger, Transport);

KafkaLogger.prototype.name = 'KafkaLogger';

KafkaLogger.prototype.destroy = function destroy() {
    var producer = this.kafkaClient.get_producer(this.topic);

    if (producer && producer.connection &&
        producer.connection.connection &&
        producer.connection.connection._connection
    ) {
        producer.connection.connection._connection.destroy();
    }

    if (this.kafkaRestClient) {
        this.kafkaRestClient.close();
    }
};

KafkaLogger.prototype._flush = function _flush() {
    while (this.initQueue.length > 0) {
        var tuple = this.initQueue.shift();
        produceMessage(this, tuple[0], tuple[1]);
    }
};

KafkaLogger.prototype.log = function(level, msg, meta, callback) {
    var logMessage = extend(this.logTemplate);
    meta = meta || {};

    var d = new Date();
    var timestamp = d.getTime();
    for (var dateFormat in this.dateFormats) {
        switch(this.dateFormats[dateFormat]) {
        case 'epoch':
            logMessage[dateFormat] = Math.floor(timestamp / 1000);
            break;
        case 'jsepoch':
            logMessage[dateFormat] = timestamp;
            break;
        case 'pyepoch':
            logMessage[dateFormat] = timestamp / 1000;
            break;
        case 'iso':
            /* falls through */
        default:
            logMessage[dateFormat] = d.toISOString();
            break;
        }
    }
    if (!logMessage.ts) {
        logMessage.ts = timestamp;
    }
    logMessage.level = level;
    logMessage.msg = msg;
    logMessage.fields = meta;

    if ((!this.connected || (this.kafkaRestClient && !this.kafkaRestClientConnected))  && Date.now() < this.initTime + 5000) {
        return this.initQueue.push([logMessage, callback]);
    } else if (this.connected && this.initQueue.length) {
        this._flush();
    }

    produceMessage(this, logMessage, callback)
};

function produceMessage(self, logMessage, callback) {
    if (self.isDisabled && self.isDisabled()) {
        if (callback) {
            process.nextTick(callback);
        }
        return;
    }

    var failureHandler = self.failureHandler

    if (self.kafkaProber) {
        var thunk = self.kafkaClient.produce.bind(self.kafkaClient,
            self.topic, logMessage);
        self.kafkaProber.probe(thunk, onFailure);
    } else {
        self.kafkaClient.produce(self.topic, logMessage, callback);
    }

    if (self.kafkaRestClientConnected) {
        self.kafkaRestClient.produce(self.topic, JSON.stringify(logMessage), logMessage.ts);
    }

    function onFailure(err) {
        if (failureHandler) {
            failureHandler(err, logMessage);
        }

        if (callback && typeof callback === 'function') {
            callback(err);
        }
    }
}

module.exports = KafkaLogger;
<commit_msg>default leafHost/leafPort to null<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

/* jshint forin: false */
var util = require('util');
var Transport = require('winston-uber').Transport;
var NodeSol = require('nodesol-write').NodeSol;
var KafkaRestClient = require('kafka-rest-client');
var hostName = require('os').hostname();
var extend = require('xtend');

function KafkaLogger(options) {
    if (!(this instanceof KafkaLogger)) {
        return new KafkaLogger(options);
    }

    var self = this;

    function onConnect(err) {
        if (!err) {
            if (self.logger) {
                self.logger.info('KafkaClient connected to kafka');
            }
            self.connected = true;
            self._flush();
        } else {
            if (self.logger) {
                self.logger.warn('KafkaClient could not connect to kafka');
            }
            // connection failed, purge queue.
            self.initQueue.length = 0;
        }
    }

    function onKafkaRestClientConnect(err) {
        if (!err) {
            if (self.logger) {
                self.logger.info('KafkaRestClient connected to kafka');
            }
            self.kafkaRestClientConnected = true;
            self._flush();
        } else {
            if (self.logger) {
                self.logger.warn('KafkaRestClient could not connect to kafka');
            }
        }
    }

    options = options || {};

    Transport.call(this, options);
    this.topic = options.topic || 'unknown';
    this.leafHost = options.leafHost;
    this.leafPort = options.leafPort;
    this.proxyHost = options.proxyHost || 'localhost';
    if ('proxyPort' in options && options.proxyPort) {
        this.proxyPort = options.proxyPort;
    }
    this.logger = options.logger;
    this.properties = options.properties || {};
    this.dateFormats = options.dateFormats || { isodate: 'iso' };
    this.peerId = options.hasOwnProperty('peerId') ? options.peerId : -1;
    this.workerId = options.hasOwnProperty('workerId') ? options.workerId : -1;
    this.logTemplate = {
        host: hostName,
        level: "LOGLEVELHERE",
        msg: "MESSAGEHERE"
    };
    for (var dateFormat in this.dateFormats) {
        this.logTemplate[dateFormat] = this.dateFormats[dateFormat];
    }
    for (var property in this.properties) {
        this.logTemplate[property] = this.properties[property];
    }

    this.kafkaProber = options.kafkaProber || null;
    this.failureHandler = options.failureHandler || null;
    this.kafkaClient = options.kafkaClient || null;
    this.isDisabled = options.isDisabled || null;

    this.connected = true;
    this.kafkaRestClientConnected = false;
    this.initQueue = [];
    this.initTime = null;
    this.statsd = options.statsd || null;
    if (!this.kafkaRestClient) {
        if (this.proxyPort) {
            var kafkaRestClientOptions = {
                proxyHost: this.proxyHost,
                proxyPort: this.proxyPort,
                statsd: this.statsd
            };
            if ('maxRetries' in options) {
                kafkaRestClientOptions['maxRetries'] = options.maxRetries;
            }
            if ('blacklistMigrator' in options && 'blacklistMigratorUrl' in options) {
                if (options.blacklistMigrator) {
                    kafkaRestClientOptions['blacklistMigrator'] = options.blacklistMigrator;
                    kafkaRestClientOptions['blacklistMigratorUrl'] = options.blacklistMigratorUrl;
                }
            }
            if ('statsd' in options) {
                kafkaRestClientOptions['statsd'] = options.statsd;
            }
            this.kafkaRestClient = new KafkaRestClient(kafkaRestClientOptions);
            this.kafkaRestClient.connect(onKafkaRestClientConnect);
        }
    } else {
        this.kafkaRestClientConnected = true;
    }

    if (!this.kafkaClient && this.leafHost && this.leafPort) {
        this.connected = false;
        this.initTime = Date.now();
        this.kafkaClient = new NodeSol({
            leafHost: this.leafHost, leafPort: this.leafPort
        });
        this.kafkaClient.connect(onConnect);
    }
}

util.inherits(KafkaLogger, Transport);

KafkaLogger.prototype.name = 'KafkaLogger';

KafkaLogger.prototype.destroy = function destroy() {
    if (this.kafkaClient) {
        var producer = this.kafkaClient.get_producer(this.topic);

        if (producer && producer.connection &&
            producer.connection.connection &&
            producer.connection.connection._connection
        ) {
            producer.connection.connection._connection.destroy();
        }
    }

    if (this.kafkaRestClient) {
        this.kafkaRestClient.close();
    }
};

KafkaLogger.prototype._flush = function _flush() {
    while (this.initQueue.length > 0) {
        var tuple = this.initQueue.shift();
        produceMessage(this, tuple[0], tuple[1]);
    }
};

KafkaLogger.prototype.log = function(level, msg, meta, callback) {
    var logMessage = extend(this.logTemplate);
    meta = meta || {};

    var d = new Date();
    var timestamp = d.getTime();
    for (var dateFormat in this.dateFormats) {
        switch(this.dateFormats[dateFormat]) {
        case 'epoch':
            logMessage[dateFormat] = Math.floor(timestamp / 1000);
            break;
        case 'jsepoch':
            logMessage[dateFormat] = timestamp;
            break;
        case 'pyepoch':
            logMessage[dateFormat] = timestamp / 1000;
            break;
        case 'iso':
            /* falls through */
        default:
            logMessage[dateFormat] = d.toISOString();
            break;
        }
    }
    if (!logMessage.ts) {
        logMessage.ts = timestamp;
    }
    logMessage.level = level;
    logMessage.msg = msg;
    logMessage.fields = meta;

    if ((!this.connected || (this.kafkaRestClient && !this.kafkaRestClientConnected))  && Date.now() < this.initTime + 5000) {
        return this.initQueue.push([logMessage, callback]);
    } else if (this.connected && this.initQueue.length) {
        this._flush();
    }

    produceMessage(this, logMessage, callback)
};

function produceMessage(self, logMessage, callback) {
    if (self.isDisabled && self.isDisabled()) {
        if (callback) {
            process.nextTick(callback);
        }
        return;
    }

    var failureHandler = self.failureHandler

    if (self.kafkaClient) {
        if (self.kafkaProber) {
            var thunk = self.kafkaClient.produce.bind(self.kafkaClient,
                self.topic, logMessage);
            self.kafkaProber.probe(thunk, onFailure);
        } else {
            self.kafkaClient.produce(self.topic, logMessage, callback);
        }
    }

    if (self.kafkaRestClientConnected) {
        self.kafkaRestClient.produce(self.topic, JSON.stringify(logMessage), logMessage.ts);
    }

    function onFailure(err) {
        if (failureHandler) {
            failureHandler(err, logMessage);
        }

        if (callback && typeof callback === 'function') {
            callback(err);
        }
    }
}

module.exports = KafkaLogger;
<|endoftext|>


<commit_before>var _ = require('lodash');
var common = require('./common');

module.exports = {
    personne_de_reference: {
        fn: function(situation) {
            return _.find(situation.individus, { role: 'demandeur' }).id;
        },
        copyTo3PreviousMonths: false,
    },
    conjoint: {
        fn: function(situation) {
            var conjoint = _.find(situation.individus, { role: 'conjoint' });
            return conjoint ? conjoint.id : null;
        },
        copyTo3PreviousMonths: false,
    },
    enfants: {
        fn: common.getEnfants,
        copyTo3PreviousMonths: false,
    },
    statut_occupation_logement: {
        fn: function(situation) {
            var statusOccupationMap = {
                'proprietaireprimoaccedant': 1,
                'proprietaire': 2,
                'locatairenonmeuble': 4,
                'locatairemeublehotel': 5,
                'heberge': 6,
                'locatairefoyer': 7,
                'sansDomicile' : 8
            };
            var logement = situation.logement;
            var type = logement.type;
            if (type) {
                var statusOccupationId = type;
                if (type == 'proprietaire' && logement.primoAccedant) {
                    statusOccupationId = 'proprietaireprimoaccedant';
                }
                if (type == 'locataire' && logement.locationType) {
                    statusOccupationId += logement.locationType;
                }
                return statusOccupationMap[statusOccupationId];
            }
        }
    },
    loyer: {
        fn: function (situation) { return situation.logement.loyer; }
    },
    charges_locatives: {
        fn: function (situation) { return situation.logement.charges; }
    },
    depcom: {
        fn: function (situation) { return situation.logement.adresse.codeInsee || null; }
    },
    participation_frais: {
        fn: function (situation) { return situation.logement.participationFrais; }
    },
    coloc: {
        fn: function (situation) {
            return (situation.logement.type == 'locataire' && situation.logement.colocation) || situation.logement.colocation;
        }
    },
    logement_chambre: {
        fn: function (situation) {
            return (situation.logement.type == 'locataire' && situation.logement.isChambre) || situation.logement.isChambre;
        }
    },
};
<commit_msg>Rely on string for statut_occupation_logement Enum<commit_after>var _ = require('lodash');
var common = require('./common');

module.exports = {
    personne_de_reference: {
        fn: function(situation) {
            return _.find(situation.individus, { role: 'demandeur' }).id;
        },
        copyTo3PreviousMonths: false,
    },
    conjoint: {
        fn: function(situation) {
            var conjoint = _.find(situation.individus, { role: 'conjoint' });
            return conjoint ? conjoint.id : null;
        },
        copyTo3PreviousMonths: false,
    },
    enfants: {
        fn: common.getEnfants,
        copyTo3PreviousMonths: false,
    },
    statut_occupation_logement: {
        fn: function(situation) {
            var statusOccupationMap = {
                'proprietaireprimoaccedant': 'Accédant à la propriété',
                'proprietaire': 'Propriétaire (non accédant) du logement',
                'locatairenonmeuble': 'Locataire ou sous-locataire d‘un logement loué vide non-HLM',
                'locatairemeublehotel': 'Locataire ou sous-locataire d‘un logement loué meublé ou d‘une chambre d‘hôtel',
                'heberge': 'Logé gratuitement par des parents, des amis ou l‘employeur',
                'locatairefoyer': 'Locataire d‘un foyer (résidence universitaire, maison de retraite, foyer de jeune travailleur, résidence sociale...)',
                'sansDomicile' : 'Sans domicile stable'
            };
            var logement = situation.logement;
            var type = logement.type;
            if (type) {
                var statusOccupationId = type;
                if (type == 'proprietaire' && logement.primoAccedant) {
                    statusOccupationId = 'proprietaireprimoaccedant';
                }
                if (type == 'locataire' && logement.locationType) {
                    statusOccupationId += logement.locationType;
                }
                return statusOccupationMap[statusOccupationId];
            }
        }
    },
    loyer: {
        fn: function (situation) { return situation.logement.loyer; }
    },
    charges_locatives: {
        fn: function (situation) { return situation.logement.charges; }
    },
    depcom: {
        fn: function (situation) { return situation.logement.adresse.codeInsee || null; }
    },
    participation_frais: {
        fn: function (situation) { return situation.logement.participationFrais; }
    },
    coloc: {
        fn: function (situation) {
            return (situation.logement.type == 'locataire' && situation.logement.colocation) || situation.logement.colocation;
        }
    },
    logement_chambre: {
        fn: function (situation) {
            return (situation.logement.type == 'locataire' && situation.logement.isChambre) || situation.logement.isChambre;
        }
    },
};
<|endoftext|>


<commit_before>/*jslint indent: 2, node: true, stupid: true, nomen: true */
/*global */

var argv = process.argv,
  argc = argv.length,

  main = function (argc, argv) {
    'use strict';

    var player = [
      { name: 'Virat' },
      { name: 'MESSI' },
      { name: 'CR7' }
    ];

    var quals = [
      { qualification: 'B.E' },
      { Salary: '$100' }
    ];

    var qual = quals.reduce(function (acc, val) {
      Object.getOwnPropertyNames(val).forEach(function (name) {
        acc[name] = val[name];
      });
      return acc;
    });
    console.log(qual);

    var result = player.map(function (val) {
      Object.getOwnPropertyNames(qual).forEach(function (name) {
        val[name] = qual[name];
      });
      return val;
    });

    console.log(result);
  };

main(argc, argv);
<commit_msg>add comment<commit_after>/*jslint indent: 2, node: true, stupid: true, nomen: true */
/*global */

var argv = process.argv,
  argc = argv.length,

  main = function (argc, argv) {
    'use strict';

    var player = [
      { name: 'Virat' },
      { name: 'MESSI' },
      { name: 'CR7' }
    ];

    var quals = [
      { qualification: 'B.E' },
      { Salary: '$100' }
    ];

    var qual = quals.reduce(function (acc, val) {
      Object.getOwnPropertyNames(val).forEach(function (name) {
        acc[name] = val[name];
      });
      return acc;
    });
    console.log(qual);

    var result = player.map(function (val) {
      Object.getOwnPropertyNames(qual).forEach(function (name) {
        val[name] = qual[name];
      });
      return val;
    });

    console.log(result);
    // Expect:
    // [
    //   { name: 'Virat', qualification: 'B.E', Salary: '$100' },
    //   { name: 'MESSI', qualification: 'B.E', Salary: '$100' },
    //   { name: 'CR7', qualification: 'B.E', Salary: '$100' }
    // ]
  };

main(argc, argv);
<|endoftext|>


<commit_before>(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['leaflet'], factory);
    } else if (typeof module !== 'undefined') {
        // Node/CommonJS
        module.exports = factory(require('leaflet'));
    } else {
        // Browser globals
        if (typeof window.L === 'undefined') {
            throw new Error('Leaflet must be loaded first');
        }
        factory(window.L);
    }
}(function (L) {
    L.Control.EasyControl = L.Control.extend({
        options: {
            position: 'topleft'
        },

        onAdd: function (map) {
            var container = L.DomUtil.create('div', 'leaflet-control-easycontrol-bar leaflet-bar leaflet-control');

            this.link = L.DomUtil.create('a', 'leaflet-control-easycontrol leaflet-bar-part', container);
            this.link.innerText = this.options.label;
            this.link.href = '#';

            this._map = map;

            L.DomEvent.on(this.link, 'click', this._clickHandler, this);

            return container;
        },

        _clickHandler: function (e) {
            e.preventDefault();
            e.stopPropagation();
            this.options.onClick(this._map);
        }
    });

    L.Control.easyControl = function (options) {
        return new L.Control.EasyControl(options);
    };
}));<commit_msg>Add customClass option<commit_after>(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['leaflet'], factory);
    } else if (typeof module !== 'undefined') {
        // Node/CommonJS
        module.exports = factory(require('leaflet'));
    } else {
        // Browser globals
        if (typeof window.L === 'undefined') {
            throw new Error('Leaflet must be loaded first');
        }
        factory(window.L);
    }
}(function (L) {
    L.Control.EasyControl = L.Control.extend({
        options: {
            position: 'topleft'
        },

        onAdd: function (map) {
            var container = L.DomUtil.create('div', 'leaflet-control-easycontrol-bar leaflet-bar leaflet-control');

            this.link = L.DomUtil.create('a', 'leaflet-control-easycontrol leaflet-bar-part ' + this.options.customClass, container);
            this.link.innerText = this.options.label;
            this.link.href = '#';

            this._map = map;

            L.DomEvent.on(this.link, 'click', this._clickHandler, this);

            return container;
        },

        _clickHandler: function (e) {
            e.preventDefault();
            e.stopPropagation();
            this.options.onClick(this._map);
        }
    });

    L.Control.easyControl = function (options) {
        return new L.Control.EasyControl(options);
    };
}));<|endoftext|>


<commit_before>const
    express = require('express'),
    app = express(),
    port = 3001

app.use(express.static('public'))
app.set('view engine', 'pug')
app.get('/', (req, res) => res.render('index'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
<commit_msg>changed index.js code to be more in line with what heroku expects<commit_after>const
    express = require('express'),
    app = express()

app.set('port', (process.env.PORT || 5000))
app.use(express.static('public'))
app.set('view engine', 'pug')
app.get('/', (req, res) => res.render('index'))
app.listen(app.get('port'), () => console.log(`Example app listening on port ${app.get('port')}!`))
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-6-13 20:52:07<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var tape = require('tape')
var choppa = require('choppa')
var protocol = require('./')

var KEY = new Buffer('01234567890123456789012345678901')
var OTHER_KEY = new Buffer('12345678901234567890123456789012')

tape('basic', function (t) {
  t.plan(2)

  var a = protocol()
  var b = protocol()

  a.feed(KEY)
  b.feed(KEY)

  a.once('handshake', function () {
    t.pass('a got handshake')
  })

  b.once('handshake', function () {
    t.pass('b got handshake')
  })

  a.pipe(b).pipe(a)
})

tape('basic with handshake options', function (t) {
  t.plan(8)

  var a = protocol({id: new Buffer('a'), live: true})
  var b = protocol({id: new Buffer('b'), live: false})

  a.feed(KEY)
  b.feed(KEY)

  a.once('handshake', function () {
    t.same(a.id, new Buffer('a'))
    t.same(a.live, true)
    t.same(a.remoteId, new Buffer('b'))
    t.same(a.remoteLive, false)
  })

  b.once('handshake', function () {
    t.same(b.id, new Buffer('b'))
    t.same(b.live, false)
    t.same(b.remoteId, new Buffer('a'))
    t.same(b.remoteLive, true)
  })

  a.pipe(b).pipe(a)
})

tape('send messages', function (t) {
  t.plan(10)

  var a = protocol()
  var b = protocol()

  var ch1 = a.feed(KEY)
  var ch2 = b.feed(KEY)

  b.on('feed', function (discoveryKey) {
    t.same(discoveryKey, ch1.discoveryKey)
  })

  a.on('feed', function (discoveryKey) {
    t.same(discoveryKey, ch2.discoveryKey)
  })

  ch2.on('data', function (data) {
    t.same(data, {index: 42, signature: null, value: new Buffer('hi'), nodes: []})
  })

  ch1.data({index: 42, value: new Buffer('hi')})

  ch2.on('request', function (request) {
    t.same(request, {index: 10, hash: false, bytes: 0, nodes: 0})
  })

  ch1.request({index: 10})

  ch2.on('cancel', function (cancel) {
    t.same(cancel, {index: 100, hash: false, bytes: 0})
  })

  ch1.cancel({index: 100})

  ch1.on('want', function (want) {
    t.same(want, {start: 10, length: 100})
  })

  ch2.want({start: 10, length: 100})

  ch1.on('info', function (info) {
    t.same(info, {uploading: false, downloading: true})
  })

  ch2.info({uploading: false, downloading: true})

  ch1.on('unwant', function (unwant) {
    t.same(unwant, {start: 11, length: 100})
  })

  ch2.unwant({start: 11, length: 100})

  ch1.on('unhave', function (unhave) {
    t.same(unhave, {start: 18, length: 100})
  })

  ch2.unhave({start: 18, length: 100})

  ch1.on('have', function (have) {
    t.same(have, {start: 10, length: 10, bitfield: null})
  })

  ch2.have({start: 10, length: 10})

  a.pipe(b).pipe(a)
})

tape('send messages (chunked)', function (t) {
  t.plan(10)

  var a = protocol()
  var b = protocol()

  var ch1 = a.feed(KEY)
  var ch2 = b.feed(KEY)

  b.on('feed', function (discoveryKey) {
    t.same(discoveryKey, ch1.discoveryKey)
  })

  a.on('feed', function (discoveryKey) {
    t.same(discoveryKey, ch2.discoveryKey)
  })

  ch2.on('data', function (data) {
    t.same(data, {index: 42, signature: null, value: new Buffer('hi'), nodes: []})
  })

  ch1.data({index: 42, value: new Buffer('hi')})

  ch2.on('request', function (request) {
    t.same(request, {index: 10, hash: false, bytes: 0, nodes: 0})
  })

  ch1.request({index: 10})

  ch2.on('cancel', function (cancel) {
    t.same(cancel, {index: 100, hash: false, bytes: 0})
  })

  ch1.cancel({index: 100})

  ch1.on('want', function (want) {
    t.same(want, {start: 10, length: 100})
  })

  ch2.want({start: 10, length: 100})

  ch1.on('info', function (info) {
    t.same(info, {uploading: false, downloading: true})
  })

  ch2.info({uploading: false, downloading: true})

  ch1.on('unwant', function (unwant) {
    t.same(unwant, {start: 11, length: 100})
  })

  ch2.unwant({start: 11, length: 100})

  ch1.on('unhave', function (unhave) {
    t.same(unhave, {start: 18, length: 100})
  })

  ch2.unhave({start: 18, length: 100})

  ch1.on('have', function (have) {
    t.same(have, {start: 10, length: 10, bitfield: null})
  })

  ch2.have({start: 10, length: 10})

  a.pipe(choppa()).pipe(b).pipe(choppa()).pipe(a)
})

tape('send messages (concat)', function (t) {
  t.plan(10)

  var a = protocol()
  var b = protocol()

  var ch1 = a.feed(KEY)
  var ch2 = b.feed(KEY)

  b.on('feed', function (discoveryKey) {
    t.same(discoveryKey, ch1.discoveryKey)
  })

  a.on('feed', function (discoveryKey) {
    t.same(discoveryKey, ch2.discoveryKey)
  })

  ch2.on('data', function (data) {
    t.same(data, {index: 42, signature: null, value: new Buffer('hi'), nodes: []})
  })

  ch1.data({index: 42, value: new Buffer('hi')})

  ch2.on('request', function (request) {
    t.same(request, {index: 10, hash: false, bytes: 0, nodes: 0})
  })

  ch1.request({index: 10})

  ch2.on('cancel', function (cancel) {
    t.same(cancel, {index: 100, hash: false, bytes: 0})
  })

  ch1.cancel({index: 100})

  ch1.on('want', function (want) {
    t.same(want, {start: 10, length: 100})
  })

  ch2.want({start: 10, length: 100})

  ch1.on('info', function (info) {
    t.same(info, {uploading: false, downloading: true})
  })

  ch2.info({uploading: false, downloading: true})

  ch1.on('unwant', function (unwant) {
    t.same(unwant, {start: 11, length: 100})
  })

  ch2.unwant({start: 11, length: 100})

  ch1.on('unhave', function (unhave) {
    t.same(unhave, {start: 18, length: 100})
  })

  ch2.unhave({start: 18, length: 100})

  ch1.on('have', function (have) {
    t.same(have, {start: 10, length: 10, bitfield: null})
  })

  ch2.have({start: 10, length: 10})

  b.write(toBuffer(a))
  a.write(toBuffer(b))
  a.pipe(b).pipe(a)

  function toBuffer (stream) {
    var bufs = []
    while (true) {
      var next = stream.read()
      if (!next) return Buffer.concat(bufs)
      bufs.push(next)
    }
  }
})

tape('destroy', function (t) {
  var a = protocol()
  var ch1 = a.feed(KEY)

  ch1.on('close', function () {
    t.pass('closed')
    t.end()
  })

  a.destroy()
})

tape('first feed should be the same', function (t) {
  t.plan(2)

  var a = protocol()
  var b = protocol()

  a.feed(KEY)
  b.feed(OTHER_KEY)

  a.once('error', function () {
    t.pass('a should error')
  })

  b.once('error', function () {
    t.pass('b should error')
  })

  a.pipe(b).pipe(a)
})

tape('multiple feeds', function (t) {
  var a = protocol()
  var b = protocol()

  a.feed(KEY)
  b.feed(KEY)

  var ch1 = a.feed(OTHER_KEY)
  var ch2 = b.feed(OTHER_KEY)

  ch1.have({
    start: 10,
    length: 100
  })

  ch2.on('have', function () {
    t.pass('got message on second channel')
    t.end()
  })

  a.pipe(b).pipe(a)
})

tape('async feed', function (t) {
  var a = protocol()
  var b = protocol()

  var ch1 = a.feed(KEY)

  ch1.request({index: 42})

  b.once('feed', function () {
    setTimeout(function () {
      var ch2 = b.feed(KEY)
      ch2.on('request', function (request) {
        t.same(request.index, 42)
        t.end()
      })
    }, 100)
  })

  a.pipe(b).pipe(a)
})

tape('stream is encrypted', function (t) {
  var a = protocol()
  var b = protocol()

  var ch1 = a.feed(KEY)
  var ch2 = b.feed(KEY)

  ch2.on('data', function (data) {
    t.same(data.value, new Buffer('i am secret'))
    t.end()
  })

  a.on('data', function (data) {
    t.ok(data.toString().indexOf('secret') === -1)
  })

  a.pipe(b).pipe(a)

  ch1.data({index: 42, value: new Buffer('i am secret')})
})

tape('stream can be unencrypted', function (t) {
  var a = protocol({encrypt: false})
  var b = protocol({encrypt: false})

  var ch1 = a.feed(KEY)
  var ch2 = b.feed(KEY)
  var sawSecret = false

  ch2.on('data', function (data) {
    t.ok(sawSecret, 'saw secret')
    t.same(data.value, new Buffer('i am secret'))
    t.end()
  })

  a.on('data', function (data) {
    if (data.toString().indexOf('secret') > -1) {
      sawSecret = true
    }
  })

  a.pipe(b).pipe(a)

  ch1.data({index: 42, value: new Buffer('i am secret')})
})

tape('keep alives', function (t) {
  var a = protocol({timeout: 100})
  var b = protocol({timeout: 100})

  a.feed(KEY)
  b.feed(KEY)

  var timeout = setTimeout(function () {
    t.pass('should not time out')
    t.end()
  }, 1000)

  b.on('error', function () {
    clearTimeout(timeout)
    t.fail('timed out')
    t.end()
  })

  a.pipe(b).pipe(a)
})

tape('timeouts', function (t) {
  var a = protocol({timeout: false})
  var b = protocol({timeout: 100})

  var timeout = setTimeout(function () {
    t.fail('should time out')
  }, 1000)

  b.on('error', function () {
    clearTimeout(timeout)
    t.pass('timed out')
    t.end()
  })

  a.pipe(b).pipe(a)
})

tape('expected feeds', function (t) {
  var a = protocol({expectedFeeds: 1})

  a.resume()
  a.on('end', function () {
    t.pass('should end')
    t.end()
  })

  var ch = a.feed(KEY)

  ch.close()
})

tape('2 expected feeds', function (t) {
  var a = protocol({expectedFeeds: 2})
  var created = 0

  a.resume()
  a.on('end', function () {
    t.same(created, 2, 'created two feeds')
    t.pass('should end')
    t.end()
  })

  created++
  var ch = a.feed(KEY)
  ch.close()

  setTimeout(function () {
    created++
    var ch = a.feed(OTHER_KEY)
    ch.close()
  }, 100)
})
<commit_msg>add failing test case<commit_after>var tape = require('tape')
var choppa = require('choppa')
var protocol = require('./')

var KEY = new Buffer('01234567890123456789012345678901')
var OTHER_KEY = new Buffer('12345678901234567890123456789012')

tape('basic', function (t) {
  t.plan(2)

  var a = protocol()
  var b = protocol()

  a.feed(KEY)
  b.feed(KEY)

  a.once('handshake', function () {
    t.pass('a got handshake')
  })

  b.once('handshake', function () {
    t.pass('b got handshake')
  })

  a.pipe(b).pipe(a)
})

tape('basic with handshake options', function (t) {
  t.plan(8)

  var a = protocol({id: new Buffer('a'), live: true})
  var b = protocol({id: new Buffer('b'), live: false})

  a.feed(KEY)
  b.feed(KEY)

  a.once('handshake', function () {
    t.same(a.id, new Buffer('a'))
    t.same(a.live, true)
    t.same(a.remoteId, new Buffer('b'))
    t.same(a.remoteLive, false)
  })

  b.once('handshake', function () {
    t.same(b.id, new Buffer('b'))
    t.same(b.live, false)
    t.same(b.remoteId, new Buffer('a'))
    t.same(b.remoteLive, true)
  })

  a.pipe(b).pipe(a)
})

tape('send messages', function (t) {
  t.plan(10)

  var a = protocol()
  var b = protocol()

  var ch1 = a.feed(KEY)
  var ch2 = b.feed(KEY)

  b.on('feed', function (discoveryKey) {
    t.same(discoveryKey, ch1.discoveryKey)
  })

  a.on('feed', function (discoveryKey) {
    t.same(discoveryKey, ch2.discoveryKey)
  })

  ch2.on('data', function (data) {
    t.same(data, {index: 42, signature: null, value: new Buffer('hi'), nodes: []})
  })

  ch1.data({index: 42, value: new Buffer('hi')})

  ch2.on('request', function (request) {
    t.same(request, {index: 10, hash: false, bytes: 0, nodes: 0})
  })

  ch1.request({index: 10})

  ch2.on('cancel', function (cancel) {
    t.same(cancel, {index: 100, hash: false, bytes: 0})
  })

  ch1.cancel({index: 100})

  ch1.on('want', function (want) {
    t.same(want, {start: 10, length: 100})
  })

  ch2.want({start: 10, length: 100})

  ch1.on('info', function (info) {
    t.same(info, {uploading: false, downloading: true})
  })

  ch2.info({uploading: false, downloading: true})

  ch1.on('unwant', function (unwant) {
    t.same(unwant, {start: 11, length: 100})
  })

  ch2.unwant({start: 11, length: 100})

  ch1.on('unhave', function (unhave) {
    t.same(unhave, {start: 18, length: 100})
  })

  ch2.unhave({start: 18, length: 100})

  ch1.on('have', function (have) {
    t.same(have, {start: 10, length: 10, bitfield: null})
  })

  ch2.have({start: 10, length: 10})

  a.pipe(b).pipe(a)
})

tape('send messages (chunked)', function (t) {
  t.plan(10)

  var a = protocol()
  var b = protocol()

  var ch1 = a.feed(KEY)
  var ch2 = b.feed(KEY)

  b.on('feed', function (discoveryKey) {
    t.same(discoveryKey, ch1.discoveryKey)
  })

  a.on('feed', function (discoveryKey) {
    t.same(discoveryKey, ch2.discoveryKey)
  })

  ch2.on('data', function (data) {
    t.same(data, {index: 42, signature: null, value: new Buffer('hi'), nodes: []})
  })

  ch1.data({index: 42, value: new Buffer('hi')})

  ch2.on('request', function (request) {
    t.same(request, {index: 10, hash: false, bytes: 0, nodes: 0})
  })

  ch1.request({index: 10})

  ch2.on('cancel', function (cancel) {
    t.same(cancel, {index: 100, hash: false, bytes: 0})
  })

  ch1.cancel({index: 100})

  ch1.on('want', function (want) {
    t.same(want, {start: 10, length: 100})
  })

  ch2.want({start: 10, length: 100})

  ch1.on('info', function (info) {
    t.same(info, {uploading: false, downloading: true})
  })

  ch2.info({uploading: false, downloading: true})

  ch1.on('unwant', function (unwant) {
    t.same(unwant, {start: 11, length: 100})
  })

  ch2.unwant({start: 11, length: 100})

  ch1.on('unhave', function (unhave) {
    t.same(unhave, {start: 18, length: 100})
  })

  ch2.unhave({start: 18, length: 100})

  ch1.on('have', function (have) {
    t.same(have, {start: 10, length: 10, bitfield: null})
  })

  ch2.have({start: 10, length: 10})

  a.pipe(choppa()).pipe(b).pipe(choppa()).pipe(a)
})

tape('send messages (concat)', function (t) {
  t.plan(10)

  var a = protocol()
  var b = protocol()

  var ch1 = a.feed(KEY)
  var ch2 = b.feed(KEY)

  b.on('feed', function (discoveryKey) {
    t.same(discoveryKey, ch1.discoveryKey)
  })

  a.on('feed', function (discoveryKey) {
    t.same(discoveryKey, ch2.discoveryKey)
  })

  ch2.on('data', function (data) {
    t.same(data, {index: 42, signature: null, value: new Buffer('hi'), nodes: []})
  })

  ch1.data({index: 42, value: new Buffer('hi')})

  ch2.on('request', function (request) {
    t.same(request, {index: 10, hash: false, bytes: 0, nodes: 0})
  })

  ch1.request({index: 10})

  ch2.on('cancel', function (cancel) {
    t.same(cancel, {index: 100, hash: false, bytes: 0})
  })

  ch1.cancel({index: 100})

  ch1.on('want', function (want) {
    t.same(want, {start: 10, length: 100})
  })

  ch2.want({start: 10, length: 100})

  ch1.on('info', function (info) {
    t.same(info, {uploading: false, downloading: true})
  })

  ch2.info({uploading: false, downloading: true})

  ch1.on('unwant', function (unwant) {
    t.same(unwant, {start: 11, length: 100})
  })

  ch2.unwant({start: 11, length: 100})

  ch1.on('unhave', function (unhave) {
    t.same(unhave, {start: 18, length: 100})
  })

  ch2.unhave({start: 18, length: 100})

  ch1.on('have', function (have) {
    t.same(have, {start: 10, length: 10, bitfield: null})
  })

  ch2.have({start: 10, length: 10})

  b.write(toBuffer(a))
  a.write(toBuffer(b))
  a.pipe(b).pipe(a)

  function toBuffer (stream) {
    var bufs = []
    while (true) {
      var next = stream.read()
      if (!next) return Buffer.concat(bufs)
      bufs.push(next)
    }
  }
})

tape('destroy', function (t) {
  var a = protocol()
  var ch1 = a.feed(KEY)

  ch1.on('close', function () {
    t.pass('closed')
    t.end()
  })

  a.destroy()
})

tape('first feed should be the same', function (t) {
  t.plan(2)

  var a = protocol()
  var b = protocol()

  a.feed(KEY)
  b.feed(OTHER_KEY)

  a.once('error', function () {
    t.pass('a should error')
  })

  b.once('error', function () {
    t.pass('b should error')
  })

  a.pipe(b).pipe(a)
})

tape('multiple feeds', function (t) {
  var a = protocol()
  var b = protocol()

  a.feed(KEY)
  b.feed(KEY)

  var ch1 = a.feed(OTHER_KEY)
  var ch2 = b.feed(OTHER_KEY)

  ch1.have({
    start: 10,
    length: 100
  })

  ch2.on('have', function () {
    t.pass('got message on second channel')
    t.end()
  })

  a.pipe(b).pipe(a)
})

tape('async feed', function (t) {
  var a = protocol()
  var b = protocol()

  var ch1 = a.feed(KEY)

  ch1.request({index: 42})

  b.once('feed', function () {
    setTimeout(function () {
      var ch2 = b.feed(KEY)
      ch2.on('request', function (request) {
        t.same(request.index, 42)
        t.end()
      })
    }, 100)
  })

  a.pipe(b).pipe(a)
})

tape('stream is encrypted', function (t) {
  var a = protocol()
  var b = protocol()

  var ch1 = a.feed(KEY)
  var ch2 = b.feed(KEY)

  ch2.on('data', function (data) {
    t.same(data.value, new Buffer('i am secret'))
    t.end()
  })

  a.on('data', function (data) {
    t.ok(data.toString().indexOf('secret') === -1)
  })

  a.pipe(b).pipe(a)

  ch1.data({index: 42, value: new Buffer('i am secret')})
})

tape('stream can be unencrypted', function (t) {
  var a = protocol({encrypt: false})
  var b = protocol({encrypt: false})

  var ch1 = a.feed(KEY)
  var ch2 = b.feed(KEY)
  var sawSecret = false

  ch2.on('data', function (data) {
    t.ok(sawSecret, 'saw secret')
    t.same(data.value, new Buffer('i am secret'))
    t.end()
  })

  a.on('data', function (data) {
    if (data.toString().indexOf('secret') > -1) {
      sawSecret = true
    }
  })

  a.pipe(b).pipe(a)

  ch1.data({index: 42, value: new Buffer('i am secret')})
})

tape('keep alives', function (t) {
  var a = protocol({timeout: 100})
  var b = protocol({timeout: 100})

  a.feed(KEY)
  b.feed(KEY)

  var timeout = setTimeout(function () {
    t.pass('should not time out')
    t.end()
  }, 1000)

  b.on('error', function () {
    clearTimeout(timeout)
    t.fail('timed out')
    t.end()
  })

  a.pipe(b).pipe(a)
})

tape('timeouts', function (t) {
  var a = protocol({timeout: false})
  var b = protocol({timeout: 100})

  var timeout = setTimeout(function () {
    t.fail('should time out')
  }, 1000)

  b.on('error', function () {
    clearTimeout(timeout)
    t.pass('timed out')
    t.end()
  })

  a.pipe(b).pipe(a)
})

tape('expected feeds', function (t) {
  var a = protocol({expectedFeeds: 1})

  a.resume()
  a.on('end', function () {
    t.pass('should end')
    t.end()
  })

  var ch = a.feed(KEY)

  ch.close()
})

tape('2 expected feeds', function (t) {
  var a = protocol({expectedFeeds: 2})
  var created = 0

  a.resume()
  a.on('end', function () {
    t.same(created, 2, 'created two feeds')
    t.pass('should end')
    t.end()
  })

  created++
  var ch = a.feed(KEY)
  ch.close()

  setTimeout(function () {
    created++
    var ch = a.feed(OTHER_KEY)
    ch.close()
  }, 100)
})

tape('message after ping', function (t) {
  t.plan(2)

  var a = protocol()
  var b = protocol()

  var ch1 = a.feed(KEY)
  var ch2 = b.feed(KEY)

  ch2.on('have', function (have) {
    t.pass('got have')
  })

  ch1.have({start: 1})
  a.ping()
  ch1.have({start: 2})

  a.pipe(b).pipe(a)
})
<|endoftext|>


<commit_before>var Cyclist = function(size) {
	if (!(this instanceof Cyclist)) return new Cyclist(size);
	this.mask = 0;
	this.values = [];
	this.indexes = [];
	if (size) this.fit(size);
};

Cyclist.prototype.__defineGetter__('size', function() {
	return this.mask + 1;
});

Cyclist.prototype.put = function(index, val) {
	var pos = index & this.mask;
	this.indexes[pos] = index;
	this.values[pos] = val;
};

Cyclist.prototype.get = function(index) {
	return this.values[index & this.mask];
};

Cyclist.prototype.del = function(index) {
	var pos = index & this.mask;
	var val = this.values[pos];
	this.indexes[pos] = this.values[pos] = undefined;
	return val;
};

Cyclist.prototype.fit = function(size) {
	if (size <= this.size) return;
	while (this.size < size) this.mask = 2 * (this.mask + 1) - 1;

	var values = this.values;
	var indexes = this.indexes;
	this.values = [];
	this.indexes = [];

	for (var i = 0; i < indexes.length; i++) {
		if (indexes[i] !== undefined) this.put(indexes[i], values[i]);
	}
};

module.exports = Cyclist;<commit_msg>some perf tuning based on benches<commit_after>var Cyclist = function(size) {
	if (!(this instanceof Cyclist)) return new Cyclist(size);
	this.mask = 0;
	this.values = [];
	this.indexes = [];
	if (size) this.fit(size);
};

Cyclist.prototype.__defineGetter__('size', function() {
	return this.mask + 1;
});

Cyclist.prototype.put = function(index, val) {
	var pos = index & this.mask;
	this.indexes[pos] = index;
	this.values[pos] = val;
};

Cyclist.prototype.get = function(index) {
	return this.values[index & this.mask];
};

Cyclist.prototype.del = function(index) {
	var pos = index & this.mask;
	var val = this.values[pos];
	this.indexes[pos] = this.values[pos] = undefined;
	return val;
};

Cyclist.prototype.fit = function(size) {
	if (size <= this.size) return;
	while (this.size < size) this.mask = 2 * (this.mask + 1) - 1;

	var values = this.values;
	var indexes = this.indexes;
	this.values = new Array(this.size);
	this.indexes = new Array(this.size);

	for (var i = 0; i < indexes.length; i++) {
		if (indexes[i] !== undefined) this.put(indexes[i], values[i]);
	}
};

module.exports = Cyclist;<|endoftext|>


<commit_before>'use strict';

var exec = require('child_process').exec,
    nconf = require('nconf'),
    sprintf = require('sprintf-js').sprintf,
    q = require('q'),
    winston = require('winston');

module.exports = function() {

    // Load configuration
    nconf.file('./gebo.json');
    var _config = nconf.get('textConverter');
    var _logLevel = nconf.get('logLevel');
    var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ colorize: true }) ] });

    /**
     * Take a file and return plain text
     *
     * @param string
     *
     * @return promise
     */
    function _convert(path, options) {
        var deferred = q.defer();

        if (!options) {
          options = {};
        }

        _getFileType(path).
          then(function(type) {
                var command = sprintf(_config[type], path);
                if (!command) {
                  command = sprintf(_config.default, path);
                }

                exec(command, options, function(err, stdout, stderr) {
                    if (err) {
                      if (logLevel === 'trace') logger.error('gebo-text-converter', err);
                      deferred.reject(err);
                    }
                    if (stderr) {
                      if (logLevel === 'trace') logger.warn('gebo-text-converter', stderr);
                    }
                    deferred.resolve(stdout);
                  });
            }).
          catch(function(err) {

            });
        return deferred.promise;
      };
    exports.convert = _convert;

    /**
     * Determine this file's type so as to know which
     * text conversion software to run
     *
     * @param string
     *
     * @return promise
     */
    function _getFileType(path) {
        var deferred = q.defer();
        exec('file --mime-type ' + path, function(err, stdout, stderr) {
            if (err) {
              deferred.reject(err);
            }
            else {
              var type = stdout.split(' ').pop().trim();
              switch(type) {
                case 'application/msword':
                    deferred.resolve('doc');
                    break;
                case 'application/zip':
                case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
                    deferred.resolve('docx');
                    break;
                case 'application/vnd.oasis.opendocument.text':
                    deferred.resolve('odt');
                    break;
                case 'application/pdf':
                    deferred.resolve('pdf');
                    break;
                case 'text/rtf':
                case 'application/rtf':
                    deferred.resolve('rtf');
                    break;
                case 'text/plain':
                    deferred.resolve('txt');
                    break;
                default:
                    deferred.resolve(null);
              }
            }
          });
        return deferred.promise;
      };
    exports.getFileType = _getFileType;

    return exports;
  }();
<commit_msg>Add logging<commit_after>'use strict';

var exec = require('child_process').exec,
    nconf = require('nconf'),
    sprintf = require('sprintf-js').sprintf,
    q = require('q'),
    winston = require('winston');

module.exports = function() {

    // Load configuration
    nconf.file('./gebo.json');
    var _config = nconf.get('textConverter');
    var _logLevel = nconf.get('logLevel');
    var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ colorize: true }) ] });

    /**
     * Take a file and return plain text
     *
     * @param string
     *
     * @return promise
     */
    function _convert(path, options) {
        var deferred = q.defer();

        if (!options) {
          options = {};
        }

        _getFileType(path).
          then(function(type) {
                var command = sprintf(_config[type], path);
                if (!command) {
                  command = sprintf(_config.default, path);
                }

                if (logLevel === 'trace') logger.info('gebo-text-converter command:', command);

                exec(command, options, function(err, stdout, stderr) {
                    if (err) {
                      if (logLevel === 'trace') logger.error('gebo-text-converter', err);
                      deferred.reject(err);
                    }
                    else {
                      if (stderr && logLevel === 'trace') logger.warn('gebo-text-converter', stderr);
                      deferred.resolve(stdout);
                    }
                  });
            }).
          catch(function(err) {
                if (logLevel === 'trace') logger.error('gebo-text-converter _getFileType:', err);
                deferred.reject(err);
            });
        return deferred.promise;
      };
    exports.convert = _convert;

    /**
     * Determine this file's type so as to know which
     * text conversion software to run
     *
     * @param string
     *
     * @return promise
     */
    function _getFileType(path) {
        var deferred = q.defer();
        exec('file --mime-type ' + path, function(err, stdout, stderr) {
            if (err) {
              deferred.reject(err);
            }
            else {
              var type = stdout.split(' ').pop().trim();
              switch(type) {
                case 'application/msword':
                    deferred.resolve('doc');
                    break;
                case 'application/zip':
                case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
                    deferred.resolve('docx');
                    break;
                case 'application/vnd.oasis.opendocument.text':
                    deferred.resolve('odt');
                    break;
                case 'application/pdf':
                    deferred.resolve('pdf');
                    break;
                case 'text/rtf':
                case 'application/rtf':
                    deferred.resolve('rtf');
                    break;
                case 'text/plain':
                    deferred.resolve('txt');
                    break;
                default:
                    deferred.resolve(null);
              }
            }
          });
        return deferred.promise;
      };
    exports.getFileType = _getFileType;

    return exports;
  }();
<|endoftext|>


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

module.exports = function(schema, config) {

    // handle optional api
    var prop, steps;
    if (typeof config === "object") {
        prop = config.prop;
        steps = config.steps;
    } else if (typeof config === "string") {
        prop = config;
        steps = 12;
    }

    if (!prop) throw new Error('prop must be specified');

    // token virtual references
    var key = '_' + prop;
    var hash_prop = 'hash' + key;

    // extend the schema
    var extension = {};
    extension[hash_prop] = String;
    schema.add(extension);

    // setup access methods
    schema.virtual(prop)
        .set(function(value) {
            this[key] = value;
            // encrypt value
            // TODO: # of steps should be config driven
            var salt = bcrypt.genSaltSync(steps);
            this[hash_prop] = bcrypt.hashSync(value, salt);
        })
        .get(function() { return this[key]; });

    // abstract authentication function generator
    schema.methods['verify_' + prop] = function(value, cb) {
        if (!this[hash_prop]) return false;
        if (typeof cb !== "function")
            return bcrypt.compareSync(value, this[hash_prop]);
        bcrypt.compare(value, this[hash_prop], cb);
    };

    // hide these properties when calling toJSON
    if (!schema.options.toJSON) schema.options.toJSON = {};
    var fn = schema.options.toJSON.transform;
    schema.options.toJSON.transform = function (doc, ret, options) {
      // remove the _id of every document before returning the result
      delete ret[hash_prop];
      if (typeof fn === "function") fn(doc, ret, options);
    }

}<commit_msg>cleanup docs, mark csv : false on the schema properties<commit_after>var bcrypt = require('bcrypt');

module.exports = function(schema, config) {

    // handle optional api
    var prop, steps;
    if (typeof config === "object") {
        prop = config.prop;
        steps = config.steps;
    } else if (typeof config === "string") {
        prop = config;
        steps = 12;
    }

    if (!prop) throw new Error('prop must be specified');

    // token virtual references
    var key = '_' + prop;
    var hash_prop = 'hash' + key;

    // extend the schema
    var extension = {};
    extension[hash_prop] = { type: String, csv: false };
    schema.add(extension);

    // setup access methods
    schema.virtual(prop, { csv : false })
        .set(function(value) {
            this[key] = value;
            // encrypt value
            // TODO: # of steps should be config driven
            var salt = bcrypt.genSaltSync(steps);
            this[hash_prop] = bcrypt.hashSync(value, salt);
        })
        .get(function() { return this[key]; });

    // abstract authentication function generator
    schema.methods['verify_' + prop] = function(value, cb) {
        if (!this[hash_prop]) return false;
        if (typeof cb !== "function")
            return bcrypt.compareSync(value, this[hash_prop]);
        bcrypt.compare(value, this[hash_prop], cb);
    };

    // hide these properties when calling toJSON
    if (!schema.options.toJSON) schema.options.toJSON = {};
    var fn = schema.options.toJSON.transform;
    schema.options.toJSON.transform = function (doc, ret, options) {
      // remove the hash_prop before returning the result
      delete ret[hash_prop];
      if (typeof fn === "function") fn(doc, ret, options);
    }

}<|endoftext|>


<commit_before>var assert = require('assert')

var route = require('./')

var called = 0

var handler = route(/^\/hello\/(\w+)/, function (req, res) {
  res.end('hello ' + req.params[0])
})

handler({url: '/hello/world'}, {end: function (data) {
  called ++
  console.log(data)
  assert.equal(data, 'hello world')
}})

var handler2 = route.get(/^\/hello\/(\w+)/, function (req, res) {
  res.end('hello ' + req.params[0])
})

handler({url: '/hello/world', method: 'GET'}, {end: function (data) {
  called ++
  console.log('GET', data)
  assert.equal(data, 'hello world')
}})

assert(called)
<commit_msg>test for string route<commit_after>var assert = require('assert')

var route = require('./')

var called = 0

var handler = route(/^\/hello\/(\w+)/, function (req, res) {
  res.end('hello ' + req.params[0])
})

handler({url: '/hello/world'}, {end: function (data) {
  called ++
  console.log('1:', data)
  assert.equal(data, 'hello world')
}})

var handler2 = route.get(/^\/hello\/(\w+)/, function (req, res) {
  res.end('hello ' + req.params[0])
})

handler2({url: '/hello/world', method: 'GET'}, {end: function (data) {
  called ++
  console.log('2: GET', data)
  assert.equal(data, 'hello world')
}})

var handler3 = route.get('/test', function (req, res) {
  res.end('test!')
  console.log('3:', req.url)
})

handler3({url: '/test', method: 'GET'}, {end: function (data) {
  console.log(data)
  assert.equal(data, 'test!')
  called ++
}})

assert.equal(called, 3)
<|endoftext|>


<commit_before>/*!
 * npm-base <https://github.com/doowb/npm-base>
 *
 * Copyright (c) 2015, Brian Woodward.
 * Licensed under the MIT License.
 */

'use strict';

module.exports = function () {
  // do stuff
};
<commit_msg>implementation of the main file<commit_after>/*!
 * npm-base <https://github.com/doowb/npm-base>
 *
 * Copyright (c) 2015, Brian Woodward.
 * Licensed under the MIT License.
 */

'use strict';

var Base = require('base').namespace('cache');
var plugin = require('base-plugins');
var option = require('base-options');

var List = require('./lib/list');
var View = require('./lib/view');
var Repo = require('./lib/models/Repo');
var Maintainer = require('./lib/models/maintainer');

/**
 * NpmBase constructor. Create an instance to work with maintainer and repository information.
 *
 * ```js
 * var npm = new NpmBase();
 * ```
 * @api public
 */

function NpmBase() {
  if (!(this instanceof NpmBase)) {
    return new NpmBase();
  }
  Base.call(this);
  this.options = this.options || {};
  this.cache = this.cache || {};
  this.use(plugin());
  this.use(option());

  this.define('List', List);
  this.define('View', View);
  this.define('Repo', Repo);
  this.define('Maintainer', Maintainer);
}

/**
 * Extend `Base`
 */

Base.extend(NpmBase);

/**
 * Create a new instance of `View` or get an existing instance to work
 * with npm couchdb views.
 *
 * ```js
 * var view = npm.view('byUser');
 * ```
 *
 * @param  {String} `name` Name of the couchdb view to work with.
 * @return {Object} `View` instance
 * @api public
 */

NpmBase.prototype.view = function(name) {
  if (this.has(['views', name])) {
    return this.get(['views', name]);
  }
  var view = new View(name);
  this.set(['views', name], view);
  return view;
};

/**
 * Create a new instance of `List` or get an existing instance to work
 * with npm couchdb list.
 *
 * ```js
 * var list = npm.list('sortCount', 'byUser');
 * ```
 *
 * @param  {String} `name` Name of the couchdb list to work with.
 * @param  {String|Object} `view` Name or instance of a `view` to work with.
 * @return {Object} `List` instance
 * @api public
 */

NpmBase.prototype.list = function(name, view) {
  var viewName = view;
  if (typeof view === 'object') {
    viewName = view.name;
  }

  if (this.has(['lists', viewName, name])) {
    return this.get(['lists', viewName, name]);
  }

  if (typeof view === 'string') {
    view = this.view(view);
  }

  var list = new List(name, view);
  this.set(['lists', viewName, name], list);
  return list;
};

/**
 * Create an instance of a `repo` to work with.
 *
 * ```js
 * var repo =  npm.repo('micromatch');
 * ```
 *
 * @param  {String} `name` Name of the repo as it's published to npm.
 * @return {Object} Instance of a `Repo` model to work with.
 * @api public
 */

NpmBase.prototype.repo = function(name) {
  if (this.has(['repos', name])) {
    return this.get(['repos', name]);
  }
  var repo = new Repo(name);
  this.set(['repos', name], repo);
  return repo;
};

/**
 * Create an instance of a `maintainer` to work with.
 *
 * ```js
 * var maintainer =  npm.maintainer('doowb');
 * ```
 *
 * @param  {String} `name` Npm username of the maintainer.
 * @return {Object} Instance of a `Maintainer` model to work with.
 * @api public
 */

NpmBase.prototype.maintainer = function(name) {
  if (this.has(['maintainers', name])) {
    return this.get(['maintainers', name]);
  }
  var maintainer = new Maintainer(name);
  this.set(['maintainers', name], maintainer);
  return maintainer;
};

/**
 * Exposes `NpmBase`
 */

module.exports = NpmBase;
<|endoftext|>