/*

an abstraction for either a multiplex socket (dealer)
or a failover socket - always one of a few active

options:

wire
router
route
mode
973272
function Mesh(options){
	var self = this;
	EventEmitter.call(this);
	options = options || {};

	if(!options.wire){
		throw new Error('a mesh needs a wire')
	}
	this.wire = options.wire;
	this.router = options.router;
	this.route = options.route;
	this.mode = options.mode;

	this.wiresend = _.bind(this.wire.send, this.wire);
	this.wire.setup();

	this.connected = {};
	this.available = {};

	var initial = this.router.search(this.route || '');

	_.each(initial.workers, function(worker){
		self.addworker(worker);
	})

	
	this.router.on('added.' + this.route, function(route, worker){
		self.addworker(worker);
		self.emit('added', route, worker);
	})

	this.router.on('removed.' + this.route, function(route, worker){
		self.removeworker(worker);
		self.emit('removed', route, worker);
	})
}
735308
function(ip, options) {
    var modbus = this;
    modbus.ip = ip;
    modbus.openFlag = false;
    modbus.callback = null;
    modbus._transactionIdWrite = 1;

    // options
    if (typeof options === "undefined") options = {};
    modbus.port = options.port || MODBUS_PORT;

    // internal buffer
    modbus._buffer = Buffer.alloc(0);

    // handle callback - call a callback function only once, for the first event
    // it will triger
    var handleCallback = function(had_error) {
        if (modbus.callback) {
            modbus.callback(had_error);
            modbus.callback = null;
        }
    };

    // create a socket
    modbus._client = new net.Socket();
    if (options.timeout) this._client.setTimeout(options.timeout);

    // register the port data event
    modbus._client.on("data", function onData(data) {
        // add data to buffer
        modbus._buffer = Buffer.concat([modbus._buffer, data]);

        modbusSerialDebug({
            action: "receive tcp rtu buffered port",
            data: data,
            buffer: modbus._buffer
        });

        // check if buffer include a complete modbus answer
        var bufferLength = modbus._buffer.length;

        // check data length
        if (bufferLength < MIN_MBAP_LENGTH) return;

        // check buffer size for MAX_BUFFER_SIZE
        if (bufferLength > MAX_BUFFER_LENGTH) {
            modbus._buffer = modbus._buffer.slice(-MAX_BUFFER_LENGTH);
            bufferLength = MAX_BUFFER_LENGTH;
        }

        // check data length
        if (bufferLength < MIN_MBAP_LENGTH + EXCEPTION_LENGTH) return;

        // loop and check length-sized buffer chunks
        var maxOffset = bufferLength - MIN_MBAP_LENGTH;
        for (var i = 0; i <= maxOffset; i++) {
            modbus._transactionIdRead = modbus._buffer.readUInt16BE(i);
            var protocolID = modbus._buffer.readUInt16BE(i + 2);
            var msgLength = modbus._buffer.readUInt16BE(i + 4);
            var cmd = modbus._buffer[i + 7];

            modbusSerialDebug({
                protocolID: protocolID,
                msgLength: msgLength,
                bufferLength: bufferLength,
                cmd: cmd
            });

            if (
                protocolID === 0 &&
                cmd !== 0 &&
                msgLength >= EXCEPTION_LENGTH &&
                i + MIN_MBAP_LENGTH + msgLength <= bufferLength
            ) {
                // add crc and emit
                modbus._emitData(i + MIN_MBAP_LENGTH, msgLength);
                return;
            }
        }
    });

    this._client.on("connect", function() {
        modbus.openFlag = true;
        handleCallback();
    });

    this._client.on("close", function(had_error) {
        modbus.openFlag = false;
        handleCallback(had_error);
    });

    this._client.on("error", function(had_error) {
        modbus.openFlag = false;
        handleCallback(had_error);
    });

    this._client.on("timeout", function() {
        // modbus.openFlag is left in its current state as it reflects two types of timeouts,
        // i.e. 'false' for "TCP connection timeout" and 'true' for "Modbus response timeout"
        // (this allows to continue Modbus request re-tries without reconnecting TCP).
        modbusSerialDebug("TcpRTUBufferedPort port: TimedOut");
        handleCallback(new Error("TcpRTUBufferedPort Connection Timed Out"));
    });

    /**
     * Check if port is open.
     *
     * @returns {boolean}
     */
    Object.defineProperty(this, "isOpen", {
        enumerable: true,
        get: function() {
            return this.openFlag;
        }
    });

    EventEmitter.call(this);
}
1217376
function Router() {

  // Routes with all verbs
  var routes = {};
  methods.forEach(function (method) {
    routes[method] = [];
  });

  this.routes = routes;
  this.commonHandlers = [];
  this.routers = [];
}
66044
public Router options(@NotNull final String pattern, @NotNull final IMiddleware... handlers) {
        addPattern("OPTIONS", pattern, handlers, optionsBindings);
        return this;
    }
1202383
function(router, pathname, handler, msg_, preMsg, msg2) {

const msg = (msg2 && ` ${msg2}`) || (msg_ && `@${msg_}`) || '';

if (msg) {
  console.log(`${pad(preMsg, 35)} ${lpad(pathname,55)} ${msg}`);
}

  router.addRoute(pathname, function(req, res, params) {

    if (getDumpReqVerbosity() > 0) {
      dumpReq(req, res, `--------vvvvv\n${msg2} handling`, {skipBody:true, verbosity:getDumpReqVerbosity(), postMsg: '------^^^^^'});
    }

    return handler.apply(this, arguments);
  });
}
1299123
function Wire(options) {
  if (!(this instanceof Wire)) return new Wire(options);

  var opts = options || {};

  this.__co = opts.co || require('co');
  this.__p = opts.p || Promise;

  this.__hooks          = {};
  this.__handlers       = [];
  this.__sortedCache    = [];
  this.__knownChannels  = {};
  this.__skips          = {};
}
793104
function Router(env) {

    this.name = 'Router';
    var self = this
        , local = {
            conf    : config.getInstance(),
            bundle  : null
        };

    /**
     * Router Constructor
     * @constructor
     * */
    var init = function(){
        if ( typeof(Router.initialized) != "undefined" ) {
            return self.getInstance()
        } else {
            Router.initialized = true
        }
    }

    this.setMiddlewareInstance = function(instance) {
        self.middlewareInstance = instance
    }

    this.getInstance = function() {
        return self
    }


    /**
     * Compare urls
     *
     * @param {object} request
     * @param {object} params - Route params
     * @param {string} urlRouting
     *
     * @return {object|false} routes
     * */
    this.compareUrls = function(request, params, urlRouting) {

        if ( Array.isArray(urlRouting) ) {
            var i       = 0
                , res   = {
                    past    : false,
                    request : request
                };

            while (i < urlRouting.length && !res.past) {
                res = parseRouting(request, params, urlRouting[i]);
                ++i
            }

            return res
        } else {
            return parseRouting(request, params, urlRouting)
        }
    }

    /**
     * Check if rule has params
     *
     * @param {string} pathname
     * @return {boolean} found
     *
     * @private
     * */
    var hasParams = function(pathname) {
        return ( /:/.test(pathname) ) ? true : false
    }

    /**
     * Parse routing for mathcing url
     *
     * @param {object} request
     * @param {object} params
     * @param {string} route
     *
     * @return
     *
     * */
    var parseRouting = function(request, params, route) {
        var uRe         = params.url.split(/\//)
            , uRo       = route.split(/\//)
            , maxLen    = uRo.length
            , score     = 0
            , r         = {}
            , i         = 0;

        //attaching routing description for this request
        request.routing = params; // can be retried in controller with: req.routing

        if (uRe.length === uRo.length) {
            for (; i<maxLen; ++i) {
                if (uRe[i] === uRo[i]) {
                    ++score
                } else if (score == i && hasParams(uRo[i]) && fitsWithRequirements(request, uRo[i], uRe[i], params)) {
                    ++score
                }
            }
        }

        r.past = (score === maxLen) ? true : false;
        r.request = request;

        return r
    }

    /**
     * Fits with requiremements
     * http://en.wikipedia.org/wiki/Regular_expression
     *
     * @param {string} urlVar
     * @param {string} urlVal
     * @param {object} params
     *
     * @return {boolean} true|false - True if fits
     *
     * @private
     * */
    var fitsWithRequirements = function(request, urlVar, urlVal, params) {

        var matched     = -1
            , _param    = urlVar.match(/\:\w+/g)
            , regex     = null
            , tested    = false;

        if (!_param.length) return false;

        //  if custom path, path rewrite
        if (request.routing.param.path) {
            regex = new RegExp(urlVar, 'g')
            if ( regex.test(request.routing.param.path) ) {
                request.routing.param.path = request.routing.param.path.replace(regex, urlVal);
            }
        }

        //  if custom file, file rewrite
        if (request.routing.param.file) {
            regex = new RegExp(urlVar, 'g')
            if ( regex.test(request.routing.param.file) ) {
                request.routing.param.file = request.routing.param.file.replace(regex, urlVal);
            }
        }

        if (_param.length == 1) {// fast one
            matched =  ( _param.indexOf(urlVar) > -1 ) ? _param.indexOf(urlVar) : false;

            if (matched === false) return matched;
            // filter on method
            if (params.method !== request.method) return false;

            var key = _param[matched].substr(1);
            regex   = params.requirements[key];

            if ( /^\//.test(regex) ) {
                var re      = regex.match(/\/(.*)\//).pop()
                    , flags = regex.replace('/'+ re +'/', '');

                tested = new RegExp(re, flags).test( urlVal )

            } else {
                tested = new RegExp(params.requirements[key]).test( urlVal )
            }

            if (
                typeof(params.param[key]) != 'undefined' &&
                typeof(params.requirements) != 'undefined' &&
                typeof(params.requirements[key]) != 'undefined' &&
                tested
            ) {
                request.params[key] = urlVal;
                return true
            }

        } else { // slow one

            // In order to support rules defined like :
            //      { params.url }  => `/section/:name/page:number`
            //      { request.url } => `/section/plante/page4`
            //
            //      with keys = [ ":name", ":number" ]

            var keys        = _param
                , tplUrl    = params.url
                , url       = request.url
                , values    = {}
                , strVal    = ''
                , started   = false
                , i         = 0;

            for (var c = 0, posLen = url.length; c < posLen; ++c) {
                if (url.charAt(c) == tplUrl.charAt(i) && !started) {
                    ++i
                    continue
                } else if (strVal == '') { // start

                    started = true;
                    strVal += url.charAt(c);
                } else if ( c > (tplUrl.indexOf(keys[0]) + keys[0].length) ) {

                    regex   = params.requirements[keys[0]];
                    urlVal  = strVal.substr(0, strVal.length);

                    if ( /^\//.test(regex) ) {
                        var re      = regex.match(/\/(.*)\//).pop()
                            , flags = regex.replace('/'+ re +'/', '');

                        tested = new RegExp(re, flags).test( urlVal )

                    } else {
                        tested = new RegExp(params.requirements[key]).test( urlVal )
                    }

                    if (tested) {
                        values[ keys[0].substr(1) ] = urlVal
                    } else {
                        return false
                    }

                    strVal =  '';
                    started = false;
                    i = (tplUrl.indexOf(keys[0]) + keys[0].length);
                    c -= 1;

                    keys.splice(0,1)
                } else {
                    strVal += url.charAt(c);
                    ++i
                }

                if (c == posLen - 1 ) {

                    regex   = params.requirements[keys[0]];
                    urlVal  = strVal.substr(0, strVal.length);

                    if ( /^\//.test(regex) ) {
                        var re      = regex.match(/\/(.*)\//).pop()
                            , flags = regex.replace('/'+ re +'/', '');

                        tested = new RegExp(re, flags).test( urlVal )

                    } else {
                        tested = new RegExp(params.requirements[key]).test( urlVal )
                    }

                    if (tested) {
                        values[ keys[0].substr(1) ] = urlVal
                    } else {
                        return false
                    }

                }

            }

            if (values.count() == keys.length) {
                for (var key in values) {
                    request.params[key] = values[key];
                }
                return true
            }

        }

        return false
    }

    var refreshCore = function() {
        //var corePath = getPath('gina.core');
        var corePath = getPath('gina').core;
        var core = new RegExp( corePath );
        var excluded = [
            _(corePath + '/gna.js', true)
        ];

        for (var c in require.cache) {
            if ( (core).test(c) && excluded.indexOf(c) < 0 ) {
                require.cache[c].exports = require( _(c, true) )
            }
        }

        //update utils
        delete require.cache[_(corePath +'/utils/index.js', true)];
        require.cache[_(corePath +'/utils/index.js', true)] = require( _(corePath +'/utils/index.js', true) );
        require.cache[_(corePath + '/gna.js', true)].exports.utils = require.cache[_(corePath +'/utils/index.js', true)];

        //update plugins
        delete require.cache[_(corePath +'/plugins/index.js', true)];
        require.cache[_(corePath +'/plugins/index.js', true)] = require( _(corePath +'/plugins/index.js', true) );
        require.cache[_(corePath + '/gna.js', true)].exports.plugins = require.cache[_(corePath +'/plugins/index.js', true)];

        // Super controller
        delete require.cache[_(corePath +'/controller/index.js', true)];
        require.cache[_(corePath +'/controller/index.js', true)] = require( _(corePath +'/controller/index.js', true) );
        SuperController = require.cache[_(corePath +'/controller/index.js', true)];

    }

    /**
     * Route on the fly
     *
     * @param {object} request
     * @param {object} response
     * @param {object} params - Route params
     *
     * @callback next
     * */
    this.route = function(request, response, next, params) {

        //Routing.
        var pathname        = url.parse(request.url).pathname;
        var bundle          = local.bundle = params.bundle;
        var conf            = config.Env.getConf( bundle, env );
        var bundles         = conf.bundles;
        local.request       = request;
        local.conf          = conf;
        local.isStandalone  = config.Host.isStandalone();

        // for libs/context etc..
        var routerObj = {
            response        : response,
            next            : next,
            hasViews        : ( typeof(conf.content.views) != 'undefined' ) ? true : false,
            isUsingTemplate : conf.template,
            isProcessingXMLRequest : params.isXMLRequest
        };

        setContext('router', routerObj);

        var action          = request.action = params.param.action;
        // more can be added ... but it will always start by `on`Something.
        var reservedActions = [
            "onReady",
            "setup"
        ];
        if (reservedActions.indexOf(action) > -1) throwError(response, 500, '[ '+action+' ] is reserved for the framework');
        var middleware      = params.middleware || [];
        var actionFile      = params.param.file; // matches rule name
        var namespace       = params.namespace;
        var routeHasViews   = ( typeof(conf.content.views) != 'undefined' ) ? true : false;
        var isUsingTemplate = conf.template;
        var hasSetup        = false;
        var hasNamespace    = false;

        local.routeHasViews     = routeHasViews;
        local.isUsingTemplate   = isUsingTemplate;
        local.next              = next;
        local.isXMLRequest      = params.isXMLRequest;

        var cacheless = (process.env.IS_CACHELESS == 'false') ? false : true;
        local.cacheless = cacheless;

        if (cacheless) refreshCore();

        //Middleware Filters when declared.
        var resHeaders = conf.server.response.header;
        //TODO - to test
        if ( resHeaders.count() > 0 ) {
            for (var h in resHeaders) {
                if (!response.headersSent)
                    response.setHeader(h, resHeaders[h])
            }
        }

        //console.debug('ACTION ON  ROUTING IS : ' + action);

        //Getting superCleasses & extending it with super Models.
        var controllerFile         = {}
            , setupFile            = {}
            , Controller           = {};

        // TODO -  ?? merge all controllers into a single file while building for other env than `dev`

        setupFile     = conf.bundlesPath +'/'+ bundle + '/controllers/setup.js';
        var filename = '';
        if (namespace) {
            filename = conf.bundlesPath +'/'+ bundle + '/controllers/controller.'+ namespace +'.js';
            if ( !fs.existsSync(filename) ) {
                filename = conf.bundlesPath +'/'+ bundle + '/controllers/controller.js';
                console.warn('namespace found, but no `'+filename+'` to load: just ignore this message if this is ok with you')
            }
        } else {
            filename = conf.bundlesPath +'/'+ bundle + '/controllers/controller.js';
        }
        controllerFile = filename


        // default param setting
        var options = {
            file            : actionFile,
            namespace       : namespace,
            bundle          : bundle,//module
            bundlePath      : conf.bundlesPath +'/'+ bundle,
            rootPath        : self.executionPath,
            conf            : conf,
            instance        : self.middlewareInstance,
            views           : ( routeHasViews ) ? conf.content.views : undefined,
            isUsingTemplate : local.isUsingTemplate,
            cacheless       : cacheless,
            rule            : params.rule,
            path            : params.param.path || null, // user custom path : namespace should be ignored | left blank
            isXMLRequest    : params.isXMLRequest,
            withCredentials : false
        };

        for (var p in params.param) {
            options[p] = params.param[p]
        }

        try {

            if ( fs.existsSync(_(setupFile, true)) )
                hasSetup = true;

            if (cacheless) {

                delete require.cache[_(controllerFile, true)];

                if ( hasSetup )
                    delete require.cache[_(setupFile, true)];
            }

            Controller = require(_(controllerFile, true));

        } catch (err) {
            // means that you have a syntax errors in you controller file
            // TODO - increase `stack-trace` from 10 (default value) to 500 or more to get the exact error --stack-trace-limit=1000
            // TODO - also check `stack-size` why not set it to at the same time => --stack-size=1024
            throwError(response, 500, new Error('syntax error(s) found in `'+ controllerFile +'` \nTrace: ') + (err.stack || err.message) );
        }

        // about to contact Controller ...
        try {

            Controller      = inherits(Controller, SuperController);

            var controller  = new Controller(options);

            controller.setOptions(request, response, next, options);

            if (hasSetup) { // adding setup
                controller.setup = function(request, response, next) {
                    if (!this._setupDone) {
                        this._setupDone = true;
                        return function (request, response, next) { // getting rid of the controller context
                            var Setup = require(_(setupFile, true));

                            // TODO - loop on a defiend SuperController property like SuperController._allowedForExport
                            // inheriting SuperController functions & objects

                            // exporting config & common methods
                            Setup.engine                = controller.engine;
                            Setup.getConfig             = controller.getConfig;
                            Setup.getLocales            = controller.getLocales;
                            Setup.getFormsRules         = controller.getFormsRules;
                            Setup.throwError            = controller.throwError;
                            Setup.redirect              = controller.redirect;
                            Setup.render                = controller.render;
                            Setup.renderJSON            = controller.renderJSON;
                            Setup.renderWithoutLayout   = controller.renderWithoutLayout
                            Setup.isXMLRequest          = controller.isXMLRequest;
                            Setup.isWithCredentials     = controller.isWithCredentials,
                            Setup.isCacheless           = controller.isCacheless;

                            Setup.apply(Setup, arguments);

                            return Setup;
                        }(request, response, next)
                    }
                }
            }

            // allowing another controller (public methods) to be required inside the current controller
            /**
             * requireController
             * Allowing another controller (public methods) to be required inside the current controller
             *
             * @param {string} namespace - Controller namespace
             * @param {object} [options] - Controller options
             *
             * @return {object} controllerInstance
             * */
            controller.requireController = function (namespace, options) {

                var cacheless   = (process.env.IS_CACHELESS == 'false') ? false : true;
                var corePath    = getPath('gina').core;
                var config      = getContext('gina').Config.instance;
                var bundle      = config.bundle;
                var env         = config.env;
                var bundleConf  = config.Env.getConf(bundle, env);

                var filename    = _(bundleConf.bundlesPath +'/'+ bundle + '/controllers/' + namespace + '.js', true);

                try {

                    if (cacheless) {
                        // Super controller
                        delete require.cache[_(corePath +'/controller/index.js', true)];
                        require.cache[_(corePath +'/controller/index.js', true)] = require( _(corePath +'/controller/index.js', true) );

                        delete require.cache[filename];
                    }

                    var SuperController     = require.cache[_(corePath +'/controller/index.js', true)];
                    var RequiredController  = require(filename);

                    var RequiredController = inherits(RequiredController, SuperController)

                    if ( typeof(options) != 'undefined' ) {

                        var controller = new RequiredController( options );
                        controller.setOptions(request, response, next, options);

                        return controller

                    } else {
                        return new RequiredController();
                    }

                } catch (err) {
                    throwError(response, 500, err );
                }
            }

            if (middleware.length > 0) {
                processMiddlewares(middleware, controller, action, request, response, next,
                    function onDone(action, request, response, next){
                        // handle superController events
                        for (var e=0; e<reservedActions.length; ++e) {
                            if ( typeof(controller[reservedActions[e]]) == 'function' ) {
                                controller[reservedActions[e]](request, response, next)
                            }
                        }
                        controller[action](request, response, next)
                    })
            } else {
                // handle superController events
                // e.g.: inside your controller, you can defined: `this.onReady = function(){...}` which will always be called before the main action
                for (var e=0; e<reservedActions.length; ++e) {
                    if ( typeof(controller[reservedActions[e]]) == 'function' ) {
                        controller[reservedActions[e]](request, response, next)
                    }
                }
                controller[action](request, response, next)
            }

        } catch (err) {
            var superController = new SuperController(options);
            superController.setOptions(request, response, next, options);
            if ( typeof(controller) != 'undefined' && typeof(controller[action]) == 'undefined') {
                superController.throwError(response, 500, (new Error('action not found: `'+ action+'`. Please, check your routing.json or the related control in your `'+controllerFile+'`.')).stack);
            } else {
                superController.throwError(response, 500, err.stack);
            }
        }

        action = null
    };//EO route()

    var processMiddlewares = function(middlewares, controller, action, req, res, next, cb){

        var filename        = _(local.conf.bundlePath)
            , middleware    = null
            , constructor   = null
            , re            = new RegExp('^'+filename);

        if ( middlewares.length > 0 ) {
            for (var m=0; m<middlewares.length; ++m) {
                constructor = middlewares[m].split(/\./g);
                constructor = constructor
                    .splice(constructor.length-1,1)
                    .toString();
                middleware = middlewares[m].split(/\./g);
                middleware.splice(middleware.length-1);
                middleware = middleware.join('/');
                filename = _(filename +'/'+ middleware + '/index.js');
                if ( !fs.existsSync( filename ) ) {
                    // no middleware found with this alias
                    throwError(res, 501, new Error('middleware not found '+ middleware).stack);
                }

                if (local.cacheless) delete require.cache[_(filename, true)];

                var MiddlewareClass = function() {

                    return function () { // getting rid of the middleware context

                        var Middleware = require(_(filename, true));
                        // TODO - loop on a defiend SuperController property like SuperController._allowedForExport


                        // exporting config & common methods
                        //Middleware.engine             = controller.engine;
                        Middleware.prototype.getConfig              = controller.getConfig;
                        Middleware.prototype.getLocales             = controller.getLocales;
                        Middleware.prototype.getFormsRules          = controller.getFormsRules;
                        Middleware.prototype.throwError             = controller.throwError;
                        Middleware.prototype.redirect               = controller.redirect;
                        Middleware.prototype.render                 = controller.render;
                        Middleware.prototype.renderJSON             = controller.renderJSON;
                        Middleware.prototype.renderWithoutLayout    = controller.renderWithoutLayout
                        Middleware.prototype.isXMLRequest           = controller.isXMLRequest;
                        Middleware.prototype.isWithCredentials      = controller.isWithCredentials;
                        Middleware.prototype.isCacheless            = controller.isCacheless;

                        return Middleware;
                    }()
                }();

                middleware = new MiddlewareClass();


                if ( !middleware[constructor] ) {
                    throwError(res, 501, new Error('contructor [ '+constructor+' ] not found @'+ middlewares[m]).stack);
                }

                if ( typeof(middleware[constructor]) != 'undefined') {

                    middleware[constructor](req, res, next,
                        function onMiddlewareProcessed(req, res, next){
                            middlewares.splice(m, 1);
                            if (middlewares.length > 0) {
                                processMiddlewares(middlewares, controller, action,  req, res, next, cb)
                            } else {
                                cb(action, req, res, next)
                            }
                        }
                    );

                    break
                }
            }

        } else {
            cb(action, req, res, next)
        }
    };

    var hasViews = function() {
        return local.routeHasViews;
    };

    var throwError = function(res, code, msg) {
        if (arguments.length < 3) {
            var msg     = code || null
                , code  = res || 500
                , res   = local.res;
        }

        if (!res.headersSent) {
            if (local.isXMLRequest || !hasViews() || !local.isUsingTemplate) {
                // Internet Explorer override
                if ( /msie/i.test(local.request.headers['user-agent']) ) {
                    res.writeHead(code, "Content-Type", "text/plain")
                } else {
                    res.writeHead(code, { 'Content-Type': 'application/json'} )
                }

                console.error(res.req.method +' [ '+code+' ] '+ res.req.url)

                var e = {
                    status: code,
                    error: msg
                };

                if ( typeof(msg) == 'object' && typeof(msg.stack) != 'undefined' ) {
                    e.error.stack   = msg.stack;
                    e.error.message = msg.message;
                }

                res.end(JSON.stringify(err))
            } else {
                res.writeHead(code, { 'Content-Type': 'text/html'} );
                console.error(res.req.method +' [ '+code+' ] '+ res.req.url);
                res.end('<h1>Error '+ code +'.</h1><pre>'+ msg + '</pre>', local.next);
            }
        } else {
            local.next()
        }
    };

    init()
}
661936
function router(vertices, opt, linkView) {

        var sourceBBox = getSourceBBox(linkView, opt);
        var targetBBox = getTargetBBox(linkView, opt);

        var sourceAnchor = getSourceAnchor(linkView, opt);
        var targetAnchor = getTargetAnchor(linkView, opt);

        // if anchor lies outside of bbox, the bbox expands to include it
        sourceBBox = sourceBBox.union(getPointBox(sourceAnchor));
        targetBBox = targetBBox.union(getPointBox(targetAnchor));

        vertices = util.toArray(vertices).map(g.Point);
        vertices.unshift(sourceAnchor);
        vertices.push(targetAnchor);

        var bearing; // bearing of previous route segment

        var orthogonalVertices = []; // the array of found orthogonal vertices to be returned
        for (var i = 0, max = vertices.length - 1; i < max; i++) {

            var route = null;

            var from = vertices[i];
            var to = vertices[i + 1];

            var isOrthogonal = !!getBearing(from, to);

            if (i === 0) { // source

                if (i + 1 === max) { // route source -> target

                    // Expand one of the elements by 1px to detect situations when the two
                    // elements are positioned next to each other with no gap in between.
                    if (sourceBBox.intersect(targetBBox.clone().inflate(1))) {
                        route = insideElement(from, to, sourceBBox, targetBBox);

                    } else if (!isOrthogonal) {
                        route = elementElement(from, to, sourceBBox, targetBBox);
                    }

                } else { // route source -> vertex

                    if (sourceBBox.containsPoint(to)) {
                        route = insideElement(from, to, sourceBBox, getPointBox(to).moveAndExpand(getPaddingBox(opt)));

                    } else if (!isOrthogonal) {
                        route = elementVertex(from, to, sourceBBox);
                    }
                }

            } else if (i + 1 === max) { // route vertex -> target

                // prevent overlaps with previous line segment
                var isOrthogonalLoop = isOrthogonal && getBearing(to, from) === bearing;

                if (targetBBox.containsPoint(from) || isOrthogonalLoop) {
                    route = insideElement(from, to, getPointBox(from).moveAndExpand(getPaddingBox(opt)), targetBBox, bearing);

                } else if (!isOrthogonal) {
                    route = vertexElement(from, to, targetBBox, bearing);
                }

            } else if (!isOrthogonal) { // route vertex -> vertex
                route = vertexVertex(from, to, bearing);
            }

            // applicable to all routes:

            // set bearing for next iteration
            if (route) {
                Array.prototype.push.apply(orthogonalVertices, route.points);
                bearing = route.direction;

            } else {
                // orthogonal route and not looped
                bearing = getBearing(from, to);
            }

            // push `to` point to identified orthogonal vertices array
            if (i + 1 < max) {
                orthogonalVertices.push(to);
            }
        }

        return orthogonalVertices;
    }
336414
function ProxySocket(proxy_port, proxy_addr, meta, proxy_opts) {
    stream.Duplex.call(this);

    this.connected_fn = null;
    this.proxy_addr   = proxy_addr;
    this.proxy_port   = proxy_port;
    this.proxy_opts   = proxy_opts || {};

    this.setMeta(meta || {});

    this.state = 'disconnected';
}
663282
function Routing() {

    var self        = {};

    /**
     * @function getRoute
     *
     * @param {string} rule e.g.: <name>[@<bundle>]
     * @param {object} params
     *
     * @return {object} route
     * */
    self.getRoute = function(rule, params) {

        var config      = getContext('gina').config
            , bundle    = null;

        if ( /\@/.test(rule) ) {
            bundle = rule.split(/\@/)[1];
        } else {
            bundle    = config.bundle
        }

        var env     = config.env
        , routing   = config.getRouting(bundle, env);

        if ( typeof(routing[rule]) == 'undefined' ) {
            throw new Error('[ RoutingHelper::getRouting(rule, params) ] : `' +rule + '` not found !')
        }

        var route = JSON.parse(JSON.stringify(routing[rule]));
        var variable = null
        for (var p in route.param) {
            if ( /^:/.test(route.param[p]) ) {
                variable = route.param[p].substr(1);
                if ( typeof(params[variable]) != 'undefined') {
                    route.url = route.url.replace( new RegExp('(/:'+variable+'|/:'+variable+'$)', 'g'), '/'+ params[variable] );

                    if ( typeof(route.param.path) != 'undefined' && /:/.test(route.param.path) ) {
                        route.param.path = route.param.path.replace( new RegExp('(:'+variable+'/|:'+variable+'$)', 'g'), params[variable]);
                    }
                }
            }
        }

        if ( Array.isArray(route.url) ) {
            route.url = route.url[0]
        }

        return route

    };

    /**
     * Get route by url
     * N.B.: this will only work with rules declared with `GET` method property
     *
     * @function getRouteByUrl
     *
     * @param {string} url e.g.: /bundle/some/url/path or http
     * @param {string} [bundle] targeted bundle
     *
     * @return {object} route
     * */
    self.getRouteByUrl = function (url, bundle) {

        var matched         = false
            , pathname      = null
            , gnaCtx        = getContext('gina')
            , config        = gnaCtx.config
            , bundle        = ( typeof(bundle) != 'undefined' ) ? bundle : config.bundle
            , env           = config.env
            , router        = new gnaCtx.Router(env)
            , routing       = config.getRouting(bundle, env)
            , isRoute       = null
            , route         = null
            , isXMLRequest  = getContext().router.isProcessingXMLRequest
        ;

        var hostname    = config.envConf[bundle][env].hostname
            , uri       = config.envConf[bundle][env].server.webroot
            , prefix    = hostname + uri;

        pathname = url.replace( new RegExp('^'+ hostname), '');

        var request = {
            routing: {
                path: unescape(pathname)
            },
            method: 'GET',
            params: {}

        };

        out:
            for (var rule in routing) {
                if (typeof(routing[rule]['param']) == 'undefined')
                    break;

                if (routing[rule].bundle != bundle) continue;

                // this will only work with rules declared with `GET` method property
                if ( typeof(routing[rule].method) != 'undefined' && !/^get$/i.test(routing[rule].method) ) continue;

                //Preparing params to relay to the router.
                params = {
                    method              : routing[rule].method || 'GET',
                    requirements        : routing[rule].requirements,
                    namespace           : routing[rule].namespace || undefined,
                    url                 : unescape(pathname), /// avoid %20
                    rule                : routing[rule].originalRule || rule,
                    param               : routing[rule].param,
                    middleware          : routing[rule].middleware,
                    bundle              : routing[rule].bundle,
                    isXMLRequest        : isXMLRequest
                };

                //Parsing for the right url.
                try {
                    isRoute = router.compareUrls(request, params, routing[rule].url);
                } catch (err) {
                    throw new Error('Rule [ '+rule+' ] needs your attention.\n' + err.stack);
                    break;
                }

                if (isRoute.past) {

                    route = JSON.parse(JSON.stringify(routing[rule]));

                    matched = true;
                    isRoute = {};
                    break out;

                }
            }

        if (!matched) {
            throw new Error('[ RoutingHelper::getRouteByUrl(rule[, bundle]) ] : route not found for url: `' + url + '` !')
        } else {
            return route
        }

    }

    return self
}
633002
function chooseViewForRoute() {
            var allParams = addExtraParamsTo(params,
                layoutDelegate,
                clientRequest,
                clientResponse
            );

            return promisify(originalHandler).apply(router, allParams)
                .then(function(view) {
                    validateView(view);

                    return {
                        view: view,
                        reason: null
                    };
                })
                .catch(function(reason) {
                    return {
                        view: null,
                        reason: reason
                    };
                });
        }
245741
function get_wiring( req, res, next) {
		req.wiring_collection.findOne({
					user_id: req.current_user._id, 
					_id: ObjectID.createFromHexString(req.param('id')) 
			}, function(error, wiring) {
				if(error) { throw error; }
				req.wiring = wiring;
				next();
			});
	}
869641
function canRoute(url) {
	for (let i=ROUTERS.length; i--; ) {
		if (ROUTERS[i].canRoute(url)) return true;
	}
	return false;
}
1206575
function failover(keyword) {
  return (source, replace=source) => {
    if(is(keyword)(source)) {
      return source;
    }
    return replace;
  };
}
1022943
function web(){
  this.router = routers
  this.data = {}
  this.data.portStruct = this.data.portStruct || {}
  this.data.routers = {}

  this.data.isClearRequires = this.data.isClearRequires || this.isProductionMode
  this.data.consoleAll = this.data.consoleAll
  this.data.consoleNonProductionErrors = true

  return this
}
142570
def make_crossroad_router(source, drain=False):
    ''' 
    '''
    sink_observer = None

    def on_sink_subscribe(observer):
        nonlocal sink_observer
        sink_observer = observer

        def dispose():
            nonlocal sink_observer
            sink_observer = None

        return dispose

    def route_crossroad(request):
        def on_response_subscribe(observer):
            def on_next_source(i):
                if type(i) is cyclotron.Drain:
                    observer.on_completed()
                else:
                    observer.on_next(i)

            source_disposable = source.subscribe(
                on_next=on_next_source,
                on_error=lambda e: observer.on_error(e),
                on_completed=lambda: observer.on_completed()
            )

            def on_next_request(i):
                if sink_observer is not None:
                    sink_observer.on_next(i)

            def on_request_completed():
                if sink_observer is not None:
                    if drain is True:
                        sink_observer.on_next(cyclotron.Drain())
                    else:
                        sink_observer.on_completed()

            request_disposable = request.subscribe(
                on_next=on_next_request,
                on_error=observer.on_error,
                on_completed=on_request_completed
            )

            def dispose():
                source_disposable.dispose()
                request_disposable.dispose()

            return dispose

        return Observable.create(on_response_subscribe)

    return Observable.create(on_sink_subscribe), route_crossroad
186947
@Override
  public void channelInactive(ChannelHandlerContext ctx) {
    Status status = Status.UNAVAILABLE.withDescription(
        "Connection closed while performing protocol negotiation for " + ctx.pipeline().names());
    failWrites(status.asRuntimeException());
  }