JS based on API characteristics of the native zmq_proxy()
356304
function proxy (frontend, backend, capture){
  switch(frontend.type+'/'+backend.type){
    case 'push/pull':
    case 'pull/push':
    case 'xpub/xsub':
      if(capture){

        frontend.on('message',function (){
          backend.send([].slice.call(arguments));
        });

        backend.on('message',function (){
          frontend.send([].slice.call(arguments));

          //forwarding messages over capture socket
          capture.send([].slice.call(arguments));
        });

      } else {

        //no capture socket provided, just forwarding msgs to respective sockets
        frontend.on('message',function (){
          backend.send([].slice.call(arguments));
        });

        backend.on('message',function (){
          frontend.send([].slice.call(arguments));
        });

      }
      break;
    case 'router/dealer':
    case 'xrep/xreq':
      if(capture){

        //forwarding router/dealer pack signature: id, delimiter, msg
        frontend.on('message',function (id,delimiter,msg){
          backend.send([].slice.call(arguments));
        });

        backend.on('message',function (id,delimiter,msg){
          frontend.send([].slice.call(arguments));

          //forwarding message to the capture socket
          capture.send([].slice.call(arguments, 2));
        });

      } else {

        //forwarding router/dealer signatures without capture
        frontend.on('message',function (id,delimiter,msg){
          backend.send([].slice.call(arguments));
        });

        backend.on('message',function (id,delimiter,msg){
          frontend.send([].slice.call(arguments));
        });

      }
      break;
    default:
      throw new Error('wrong socket order to proxy');
  }
}
642219
def create_sockets(self):
        """"""

        ports = self.ports

        context = zmq.Context()
        poller = zmq.Poller()

        # Socket to handle init data
        rep = context.socket(zmq.REP)
        # this was inconsequent: here REQ is for the client, we reply with REP.
        # PULL and PUB is seen from here, not from the client.
        # Is now renamed to PUSH and SUB: everything is seen from outside.
        if "REQ" in ports:
            rep.bind(
                "tcp://*:{port}".format(port=ports["REQ"])
            )
        else:
            ports["REQ"] = rep.bind_to_random_port(
                "tcp://*"
            )

        pull = context.socket(zmq.PULL)
        if "PUSH" in ports:
            pull.bind(
                "tcp://*:{port}".format(port=ports["PUSH"])
            )
        else:
            ports["PUSH"] = pull.bind_to_random_port(
                "tcp://*"
            )

        # for sending model messages
        pub = context.socket(zmq.PUB)
        if "SUB" in ports:
            pub.bind(
                "tcp://*:{port}".format(port=ports["SUB"])
            )
        else:
            ports["SUB"] = pub.bind_to_random_port(
                "tcp://*"
            )

        poller.register(rep, zmq.POLLIN)
        poller.register(pull, zmq.POLLIN)

        sockets = dict(
            poller=poller,
            rep=rep,
            pull=pull,
            pub=pub
        )
        return sockets
964855
function proxyReq (proxyObj, callback) {
  let proxyError = proxyObjErrors(proxyObj);
  if (proxyError) { return callback(new Error(proxyError)); }

  if (proxyObj.options.log) { logReqOpts(proxyObj.reqOpts); }

  // TESTING HELPER ONLY
  if (proxyObj.options.shortCircuit) { return callback(null, proxyObj); }

  // unless explicitly set, ignore encoding
  // THIS IS A HACK THAT MAY CAUSE ISSUES. I DON'T
  // KNOW OF AN IMMEDIATE WORKAROUND TO FIX IT.
  if (!proxyObj.options['accept-encoding']) {
    delete proxyObj.reqOpts.headers['accept-encoding'];
  }

  // Check for Form Post Parameters
  if (proxyObj.req.body && (proxyObj.reqOpts.method === 'POST' || proxyObj.reqOpts.method === 'PUT')) {
    proxyObj.reqOpts.form = proxyObj.req.body;
  }

  // make request
  request(proxyObj.reqOpts, function (error, response, body) {
    if (proxyObj.options.log) { logResponse(response, body); }

    // transfer result to resulting o
    proxyObj.res.set(helpers.defaultHeaders(proxyObj.options.response.headers, response ? response.headers : {}));

    proxyObj.result = {
      response : response,
      body     : body
    };

    return callback(error, proxyObj);
  });
}
108958
function Hermes (opts, socketOpts) {
  // mutates opts
  assertOpts(opts);
  if (!socketOpts) { socketOpts = {}; }
  defaults(socketOpts, {
    heartbeat: 0
  });
  var _this = this;
  this._channel = null;
  this._connection = null;
  this._consumerTags = {};
  this._opts = opts;
  this._opts.queues = Hermes._normalizeQueues(this._opts.queues)
  this._opts.publishedEvents = Hermes._normalizeQueues(this._opts.publishedEvents)
  this._opts.subscribedEvents = Hermes._normalizeQueues(this._opts.subscribedEvents)
  this._publishQueue = [];
  this._socketOpts = socketOpts;
  this._subscribeQueue = [];

  this._eventJobs = new EventJobs({
    publishedEvents: this._opts.publishedEvents,
    subscribedEvents: this._opts.subscribedEvents,
    name: this._opts.name
  });

  this.on('ready', function () {
    debug('hermes ready');
    var args;
    while(args = _this._publishQueue.pop()) {
      publish.apply(_this, args);
    }
    while(args = _this._subscribeQueue.pop()) {
      subscribe.apply(_this, args);
    }
  });
  this.on('publish', function (queueName, data) {
    debug('hermes publish event', queueName, data);
    if (_this._channel) {
      publish(queueName, data);
    }
    else {
      _this._publishQueue.push(Array.prototype.slice.call(arguments));
    }
  });
  this.on('subscribe', function (queueName, cb) {
    debug('hermes subscribe event', queueName);
    if (_this._channel) {
      subscribe(queueName, cb);
    }
    else {
      _this._subscribeQueue.push(Array.prototype.slice.call(arguments));
    }
  });
  this.on('unsubscribe', function (queueName, handler, cb) {
    debug('hermes unsubscribe event', queueName);
    if (_this._channel) {
      unsubscribe(queueName, handler, cb);
    }
    else {
      _this._subscribeQueue.forEach(function (args) {
        /* args: [queueName, cb] */
        if (handler) {
          if (args[0] === queueName && args[1] === handler) {
            _this._subscribeQueue.splice(_this._subscribeQueue.indexOf(args), 1);
          }
        }
        else if (args[0] === queueName) {
          _this._subscribeQueue.splice(_this._subscribeQueue.indexOf(args), 1);
        }
      });
      cb();
    }
  });
  /**
   * @param {String} queueName
   * @param {Object} data
   * @return null
   */
  function publish (queueName, data) {
    debug('channel.sendToQueue', queueName, data);

    if (_this._eventJobs.isPublishEvent(queueName)) {
      return _this._eventJobs.publish(queueName, data);
    }

    _this._channel.sendToQueue(
      queueName, data, { persistent: _this._opts.persistent });
  }
  /**
   * @param {String} queueName
   * @param {Function} cb
   * @return null
   */
  function subscribe (queueName, cb) {
    debug('channel.consume', queueName);
    var consumerTag = [
      uuid.v4(),
      queueName,
      cb.name
    ].join('-');
    _this._consumerTags[consumerTag] = Array.prototype.slice.call(arguments);

    if (_this._eventJobs.isSubscribeEvent(queueName)) {
      return _this._eventJobs.subscribe(queueName,  _this._subscribeCallback(cb));
    }

    _this._channel.consume(queueName, _this._subscribeCallback(cb), {
      consumerTag: consumerTag
    });
  }
  /**
   * @param {String} queueName
   * @param {Function|null} handler
   * @param {Function} cb
   * @return null
   */
  function unsubscribe (queueName, handler, cb) {
    debug('channel.cancel', queueName);
    var cancelTags = [];
    var tagVal;
    Object.keys(_this._consumerTags).forEach(function (consumerTag) {
      tagVal = _this._consumerTags[consumerTag];
      if (handler) {
        if (tagVal[0] === queueName && tagVal[1] === handler) {
          cancelTags.push(consumerTag);
        }
      }
      else if (tagVal[0] === queueName) {
        cancelTags.push(consumerTag);
      }
    });
    async.eachSeries(cancelTags, _this._channel.cancel.bind(_this._channel), function () {
      cancelTags.forEach(function (cancelTag) {
        delete _this._consumerTags[cancelTag];
      });
      if (isFunction(cb)) {
        cb.apply(_this, arguments);
      }
    });
  }
  return this;
}
411170
def init(opts):
    '''
    
    '''
    log.debug('Initting esxi proxy module in process %s', os.getpid())
    log.debug('Validating esxi proxy input')
    schema = EsxiProxySchema.serialize()
    log.trace('esxi_proxy_schema = %s', schema)
    proxy_conf = merge(opts.get('proxy', {}), __pillar__.get('proxy', {}))
    log.trace('proxy_conf = %s', proxy_conf)
    try:
        jsonschema.validate(proxy_conf, schema)
    except jsonschema.exceptions.ValidationError as exc:
        raise InvalidConfigError(exc)

    DETAILS['proxytype'] = proxy_conf['proxytype']
    if ('host' not in proxy_conf) and ('vcenter' not in proxy_conf):
        log.critical('Neither \'host\' nor \'vcenter\' keys found in pillar '
                     'for this proxy.')
        return False
    if 'host' in proxy_conf:
        # We have started the proxy by connecting directly to the host
        if 'username' not in proxy_conf:
            log.critical('No \'username\' key found in pillar for this proxy.')
            return False
        if 'passwords' not in proxy_conf:
            log.critical('No \'passwords\' key found in pillar for this proxy.')
            return False
        host = proxy_conf['host']

        # Get the correct login details
        try:
            username, password = find_credentials(host)
        except SaltSystemExit as err:
            log.critical('Error: %s', err)
            return False

        # Set configuration details
        DETAILS['host'] = host
        DETAILS['username'] = username
        DETAILS['password'] = password
        DETAILS['protocol'] = proxy_conf.get('protocol')
        DETAILS['port'] = proxy_conf.get('port')
        return True

    if 'vcenter' in proxy_conf:
        vcenter = proxy_conf['vcenter']
        if not proxy_conf.get('esxi_host'):
            log.critical('No \'esxi_host\' key found in pillar for this proxy.')
        DETAILS['esxi_host'] = proxy_conf['esxi_host']
        # We have started the proxy by connecting via the vCenter
        if 'mechanism' not in proxy_conf:
            log.critical('No \'mechanism\' key found in pillar for this proxy.')
            return False
        mechanism = proxy_conf['mechanism']
        # Save mandatory fields in cache
        for key in ('vcenter', 'mechanism'):
            DETAILS[key] = proxy_conf[key]

        if mechanism == 'userpass':
            if 'username' not in proxy_conf:
                log.critical('No \'username\' key found in pillar for this '
                             'proxy.')
                return False
            if 'passwords' not in proxy_conf and proxy_conf['passwords']:
                log.critical('Mechanism is set to \'userpass\' , but no '
                             '\'passwords\' key found in pillar for this '
                             'proxy.')
                return False
            for key in ('username', 'passwords'):
                DETAILS[key] = proxy_conf[key]
        elif mechanism == 'sspi':
            if 'domain' not in proxy_conf:
                log.critical('Mechanism is set to \'sspi\' , but no '
                             '\'domain\' key found in pillar for this proxy.')
                return False
            if 'principal' not in proxy_conf:
                log.critical('Mechanism is set to \'sspi\' , but no '
                             '\'principal\' key found in pillar for this '
                             'proxy.')
                return False
            for key in ('domain', 'principal'):
                DETAILS[key] = proxy_conf[key]

        if mechanism == 'userpass':
            # Get the correct login details
            log.debug('Retrieving credentials and testing vCenter connection'
                      ' for mehchanism \'userpass\'')
            try:
                username, password = find_credentials(DETAILS['vcenter'])
                DETAILS['password'] = password
            except SaltSystemExit as err:
                log.critical('Error: %s', err)
                return False

    # Save optional
    DETAILS['protocol'] = proxy_conf.get('protocol', 'https')
    DETAILS['port'] = proxy_conf.get('port', '443')
    DETAILS['credstore'] = proxy_conf.get('credstore')
1235409
def bind(endpoint)
      rc = ffi_delegate.bind("%s", :string, endpoint)
      raise_zmq_err("unable to bind to %p" % endpoint) if rc == -1
      @last_tcp_port = rc if rc > 0
    end
689312
function morganMiddleware(req, res, next) {
    const { ignoreRouteUrls, includeReqHeaders, omitReqProperties } = getConfig('logger');
    const { format } = getConfig('logger.morgan');
    // define custom tokens
    morgan.token('operation-hash', request => get(request, 'body.extensions.persistentQuery.sha256Hash'));
    morgan.token('operation-name', request => get(request, 'body.operationName'));
    morgan.token('user-id', request => get(request, 'locals.user.id'));
    morgan.token('company-id', request => get(request, 'locals.user.companyId'));
    morgan.token('message', request => request.name || '-');
    morgan.token('request-id', request => request.id);
    morgan.token('request-headers', (request) => {
        const headers = includeReqHeaders === true
            ? omit(request.headers, omitReqProperties) : {};
        return JSON.stringify(headers);
    });

    const logger = getContainer('logger');
    const formatFormat = json(format);
    const options = {
        stream: asStream(logger),
        skip: skip(ignoreRouteUrls),
    };
    return morgan(formatFormat, options)(req, res, next);
}
847558
def run(host,
        node,
        port,
        endpoint,
        tls,
        username,
        password,
        keyring,
        search_from,
        search_to,
        mode,
        output,
        follow,
        interval,
        limit,
        latency,
        stream,
        field,
        template_option,
        sort,
        asc,
        proxy,
        query):
    

    cfg = get_config()

    # Configure the graylog API object
    if node is not None:
        # The user specified a preconfigured node, take the config from there
        gl_api = api_from_config(cfg, node_name=node)
    else:
        if host is not None:
            # A manual host configuration is used
            if username is None:
                username = click.prompt("Enter username for {host}:{port}".format(host=host, port=port),
                                        default=getpass.getuser())
            if tls:
                scheme = "https"
            else:
                scheme = "http"

            if proxy:
                proxies = {scheme: proxy}
            else:
                proxies = None

            gl_api = api_from_host(host=host, port=port, endpoint=endpoint, username=username, scheme=scheme,
                                   proxies=proxies)
        else:
            if cfg.has_section("node:default"):
                gl_api = api_from_config(cfg)
            else:
                cli_error("Error: No host or node configuration specified and no default found.")

    if username is not None:
        gl_api.username = username

    if keyring and password is None:
        password = get_password_from_keyring(gl_api.host, gl_api.username)

    if password is None:
        password = click.prompt("Enter password for {username}@{api}".format(
            username=gl_api.username, api=gl_api), hide_input=True)

    gl_api.password = password

    if keyring:
        store_password_in_keyring(gl_api.host, gl_api.username, password)

    username = gl_api.username

    # Check if the query should be retrieved from the configuration
    if query[0] == ":":
        section_name = "query" + query
        template_options = dict(map(lambda t: tuple(str(t).split("=", 1)), template_option))
        query = get_templated_option(cfg, section_name, "query", template_options)

        if cfg.has_option(section_name, "limit"):
            limit = get_templated_option(cfg, section_name, "limit", template_options)

        if cfg.has_option(section_name, "from"):
            search_from = get_templated_option(cfg, section_name, "from", template_options)

        if cfg.has_option(section_name, "to"):
            search_to = get_templated_option(cfg, section_name, "to", template_options)

        if cfg.has_option(section_name, "sort"):
            sort = get_templated_option(cfg, section_name, "sort", template_options)

        if cfg.has_option(section_name, "asc"):
            asc = get_templated_option(cfg, section_name, "asc", template_options)

        if cfg.has_option(section_name, "fields"):
            field = get_templated_option(cfg, section_name, "fields", template_options).split(",")

        if cfg.has_option(section_name, "stream"):
            stream = get_templated_option(cfg, section_name, "stream", template_options)

    # Configure the base query
    sr = SearchRange(from_time=search_from, to_time=search_to)

    # Pass none if the list of fields is empty
    fields = None
    if field:
        fields = list(field)

    if limit <= 0:
        limit = None

    # Set limit to None, sort to none and start time to now, if follow is active
    if follow:
        limit = None
        sort = None
        sr.from_time = arrow.now('local').replace(seconds=-latency - 1)
        sr.to_time = arrow.now('local').replace(seconds=-latency)

    # Get the user permissions
    userinfo = gl_api.user_info(username)

    # If the permissions are not set or a stream is specified
    stream_filter = None
    if stream or (userinfo["permissions"] != ["*"] and gl_api.default_stream is None):
        if not stream:
            streams = gl_api.streams()["streams"]
            click.echo("Please select a stream to query:")
            for i, stream in enumerate(streams):
                click.echo("{}: Stream '{}' (id: {})".format(i, stream["title"], stream["id"]))
            i = click.prompt("Enter stream number:", type=int, default=0)
            stream = streams[i]["id"]
        stream_filter = "streams:{}".format(stream)

    # Create the initial query object
    q = SearchQuery(search_range=sr, query=query, limit=limit, filter=stream_filter, fields=fields, sort=sort,
                    ascending=asc)

    # Check the mode in which the program should run (dump, tail or interactive mode)
    if mode == "tail":
        if fields:
            formatter = tail_format(fields)
        else:
            formatter = tail_format()
    elif mode == "dump":
        formatter = dump_format()

    run_logprint(gl_api, q, formatter, follow, interval, latency, output)
206001
async function main() {

  // Retrieve the name of the network being used.
  const network = process.argv[process.argv.length - 1];
  console.log(`Running script with the ${network} network...`);

  // Delete any previous ZeppelinOS files.
  console.log(`Deleting previous zos files...`);
  if(fs.existsSync('zos.json')) fs.unlinkSync('zos.json');
  if(fs.existsSync(`zos.${network}.json`)) fs.unlinkSync(`zos.${network}.json`);

  // Enable command logging in ZeppelinOS.
  const Logger = lib.Logger;
  Logger.silent(false);
  Logger.verbose(true);

  // Retrieve ZeppelinOS scripts.
  // These are analogous to `zos` CLI commands.
  const { init, add, push, create, publish } = zos.scripts;

  // Initialize ZeppelinOS with Truffle's Web3 provider.
  console.log(`Initializing ZeppelinOS...`);
  const ZWeb3 = lib.ZWeb3;
  ZWeb3.initialize(web3.currentProvider);

  // Set the default parameters to be used in future transactions.
  const Contracts = lib.Contracts;
  Contracts.setArtifactsDefaults({
    gas: 6721975,
    gasPrice: 100000000000
  });

  // Retrieve the default transaction params.
  // This will include a default `from` address.
  const txParams = await Contracts.getDefaultTxParams();
  console.log(`Default params to be used in transactions:`, txParams);

  // Initialize the ZeppelinOS project.
  // Notice that publish is set to true, so that the project uses an App contract.
  // This App contract will be used from within Factory.sol to dynamically create
  // proxy instances from the contract itself.
  await init({name: 'creating-instances-from-solidity', version: '0.1.0', publish: true});

  // Add the Factory.sol and Instance.sol contracts to the ZeppelinOS project.
  console.log(`Adding contracts...`);
  await add({contractsData: [
    {alias: 'Factory', name: 'Factory'},
    {alias: 'Instance', name: 'Instance'}
  ]});

  // Push the contracts implementations to the network.
  console.log(`Pushing contract implementations...`);
  await push({force: true, network });

  // Retrieve the address of the project's App contract.
  // This address will be passed to an instance of the Factory contract,
  // so that it can call the App contract's create function.
  const zosLocalData = require(`./zos.${network}.json`);
  const appAddress = zosLocalData.app.address;
  console.log(`App deployed at ${appAddress}.`);

  // Create and initialize a proxy instance of the Factory contract.
  console.log(`Creating proxy instance of Factory.sol...`);
  const factoryProxy = await create({
    packageName: 'creating-instances-from-solidity',
    contractAlias: 'Factory',
    methodName: 'initialize',
    methodArgs: [appAddress],
    network
  });
  console.log(`Factory proxy created at ${factoryProxy.address}`);

  // Use the Factory proxy address to create a javascript Factory contract object.
  const factoryContract = Contracts.getFromLocal('Factory').at(factoryProxy.address);

  // Construct the call data for the initialize method of Instance.sol.
  // This call data consists of the contract's `initialize` method with the value of `42`.
  const encodeCall = lib.encodeCall;
  const data = encodeCall('initialize', ['uint256'], [42]);
  console.log(`Call data for Instance.sol's initialize: ${data}`);

  // TODO: Ideally, we'd want to retrieve the ProxyAdmin and forward that address
  // to the Factory's createInstance method. The problem is that the ProxyAdmin is created
  // lazily, and is not available at this time. Once this is changed,
  // we can also remove the reference to the transparent proxy problem 
  // from a few lines below.

  // Create and initialize a proxy instance of the Instance contract,
  // but do so via the Factory contract instead of using the create script.
  // This is the main concept of this example: proxies can be created from deployed contracts.
  console.log(`Creating proxy instance of Instance.sol (via Factory.sol)...`);
  const transactionReceipt = await factoryContract.methods.createInstance(data).send(txParams);
  const uint256ToAddress = require('zos-lib/lib/utils/Addresses.js').uint256ToAddress;
  const instanceAddress = uint256ToAddress(transactionReceipt.events['0'].raw.data);
  console.log(`Instance proxy created at ${instanceAddress}`);

  // Use the Instance proxy address to create a javascript Instance contract object.
  const instanceContract = Contracts.getFromLocal('Instance').at(instanceAddress);

  // Retrieve the value stored in the instance contract.
  // Note that we cannot make the call using the same address that created the proxy
  // because of the transparent proxy problem. See: https://docs.zeppelinos.org/docs/faq.html#why-are-my-getting-the-error-cannot-call-fallback-function-from-the-proxy-admin
  const anotherAccount = (await ZWeb3.accounts())[1];
  const value = await instanceContract.methods.value().call({ ...txParams, from: anotherAccount });
  console.log(`Retrieved value from the created Instance contract: ${value}`);

  return value;
}
496278
def zmq_send_data(socket, data, flags=0, copy=True, track=False):
    """"""

    header, payload = [], []

    for key in sorted(data.keys()):
        arr = data[key]

        if not isinstance(arr, np.ndarray):
            raise DataError('Only ndarray types can be serialized')

        header.append(dict(dtype=str(arr.dtype),
                           shape=arr.shape,
                           key=key,
                           aligned=arr.flags['ALIGNED']))
        # Force contiguity
        payload.append(arr)

    # Send the header
    msg = [json.dumps(header).encode('ascii')]
    msg.extend(payload)

    return socket.send_multipart(msg, flags, copy=copy, track=track)
1258508
def prepare(self):
        '''
        
        '''
        super(ProxyMinion, self).prepare()

        if not self.values.proxyid:
            self.error('salt-proxy requires --proxyid')

        # Proxies get their ID from the command line.  This may need to change in
        # the future.
        # We used to set this here.  Now it is set in ProxyMinionOptionParser
        # by passing it via setup_config to config.minion_config
        # self.config['id'] = self.values.proxyid

        try:
            if self.config['verify_env']:
                confd = self.config.get('default_include')
                if confd:
                    # If 'default_include' is specified in config, then use it
                    if '*' in confd:
                        # Value is of the form "minion.d/*.conf"
                        confd = os.path.dirname(confd)
                    if not os.path.isabs(confd):
                        # If configured 'default_include' is not an absolute
                        # path, consider it relative to folder of 'conf_file'
                        # (/etc/salt by default)
                        confd = os.path.join(
                            os.path.dirname(self.config['conf_file']), confd
                        )
                else:
                    confd = os.path.join(
                        os.path.dirname(self.config['conf_file']), 'proxy.d'
                    )

                v_dirs = [
                    self.config['pki_dir'],
                    self.config['cachedir'],
                    self.config['sock_dir'],
                    self.config['extension_modules'],
                    confd,
                ]

                verify_env(
                    v_dirs,
                    self.config['user'],
                    permissive=self.config['permissive_pki_access'],
                    root_dir=self.config['root_dir'],
                    pki_dir=self.config['pki_dir'],
                )
        except OSError as error:
            self.environment_failure(error)

        self.setup_logfile_logger()
        verify_log(self.config)
        self.action_log_info('Setting up "{0}"'.format(self.config['id']))

        migrations.migrate_paths(self.config)

        # Bail out if we find a process running and it matches out pidfile
        if self.check_running():
            self.action_log_info('An instance is already running. Exiting')
            self.shutdown(1)

        # TODO: AIO core is separate from transport
        # Late import so logging works correctly
        import salt.minion
        # If the minion key has not been accepted, then Salt enters a loop
        # waiting for it, if we daemonize later then the minion could halt
        # the boot process waiting for a key to be accepted on the master.
        # This is the latest safe place to daemonize
        self.daemonize_if_required()
        self.set_pidfile()
        if self.config.get('master_type') == 'func':
            salt.minion.eval_master_func(self.config)
        self.minion = salt.minion.ProxyMinionManager(self.config)
414325
function proxyServerMidleware(req, res, next) {
    // Check if static resource exist
    var sfile = path.join(req.app.get('static resource'), req.path);
    if(fs.existsSync(sfile)) {
        return next();
    }
    // Proxy request
    // --------------
    // buffer so that it won't be lost,
    // !!This is confilced with `methodOverride()`
    var buffer = httpProxy.buffer(req);
    var proxySetting = req.app.get('proxy setting');
    // Do process
    ProxyInstance.proxyRequest(req, res, {
        host: proxySetting.remote.host,
        port: proxySetting.remote.port,
        buffer: buffer
    });
}
670851
function EmulatedWebSocketServerFactory() {
        this.createServer = function (connectCallback) {
            var server = {
                _connect: function (socket) {
                    var conn = {
                        _client: socket,
                        _listeners: { "text": [], "close": [] },
                        on: function (type, listener) {
                            conn._listeners[type].push(listener);
                        },
                        _fire: function (type, args) {
                            conn._listeners[type].forEach(function (listener) {
                                listener.apply(null, args);
                            });
                        },

                        _text: function (msg) {
                            conn._fire("text", [msg]);
                        },
                        sendText: function (msg) {
                            setTimeout(function () {
                                conn._client._text(msg);
                            }, 0);
                        },
                        close: function (code, reason) {
                            setTimeout(function () {
                                conn._client._disconnect(code, reason);
                            }, 0);
                        },
                        _disconnect: function (code, reason) {
                            conn._fire("close", [code, reason]);
                        }
                    };
                    connectCallback(conn);
                    return conn;
                },
                listen: function (port) {
                    EmulatedWebSocketServerFactory.listeners[port] = this;
                    return this;
                }
            }
            return server;
        }
    }
354098
def _setup_ipc(self):
        '''
        
        '''
        log.debug('Setting up the internal IPC proxy')
        self.ctx = zmq.Context()
        # Frontend
        self.sub = self.ctx.socket(zmq.SUB)
        self.sub.bind(PUB_PX_IPC_URL)
        self.sub.setsockopt(zmq.SUBSCRIBE, b'')
        log.debug('Setting HWM for the proxy frontend: %d', self.hwm)
        try:
            self.sub.setsockopt(zmq.HWM, self.hwm)
            # zmq 2
        except AttributeError:
            # zmq 3
            self.sub.setsockopt(zmq.SNDHWM, self.hwm)
        # Backend
        self.pub = self.ctx.socket(zmq.PUB)
        self.pub.bind(PUB_IPC_URL)
        log.debug('Setting HWM for the proxy backend: %d', self.hwm)
        try:
            self.pub.setsockopt(zmq.HWM, self.hwm)
            # zmq 2
        except AttributeError:
            # zmq 3
            self.pub.setsockopt(zmq.SNDHWM, self.hwm)
986052
function(callback){
        if(source['brokerId']!='null'){
            db.db(dbName).collection(collectionName).find({brokerId:source['brokerId']}).toArray(function(err,result){
                mqttHost = result[0]['ipAddress'];
                mqttPort = result[0]['port'];
                console.log(result);
            });
        }else{
            mqttHost = mqttPort = null;
        }
    }
1252464
function() {
      var waitForLoaded = this.waitForLoaded;

      /** Index page. */
      app.get("/", function(request, response) {
        response.render("index", { hostname: hostname, port: port });
      });

      /** Send an open request, url is provided via query parameter url. */
      app.get("/open/*", function(request, response) {
        var url     = request.query.url,
            timeout = parseInt(request.query.timeout, 10) || TIMEOUT,
            id, entry, waitCallback;

        if (url) {
          if ( !connections) {
            console.log("   error -".red, "No browsers connected to open".yellow, url);
            return response.json({ success: false, error: "No browsers connected to open " + url });
          }

          // broadcast clear request for the first time
          if ( !clear && !Object.keys(urlData).length) {
            io.sockets.emit("clear");
            clear = true;
          }

          id    = crypto.createHash("md5").update(url).digest("hex");
          entry = { type: "open", success: true, id: id, url: url, timeout: timeout };
          io.sockets.emit("open", entry);
          urlData[id]  = { id: id, timeout: timeout, url: url, counter: connections };

          setTimeout(waitForLoaded(id, url, entry, response), WAIT_TIMEOUT);
          console.log("   info  -".cyan, "open".yellow, JSON.stringify(entry));
        } else {
          response.json({ success: false, error: "Invalid url" });
        }
      });

      /** Send a close request, url is provided via query parameter url. */
      app.get("/close/*", function(request, response) {
        var url = request.query.url, id, entry;

        if (url) {
          id    = crypto.createHash("md5").update(url).digest("hex");
          if (urlData[id]) {
            entry = { type: "close", id: id, url: url };
            io.sockets.emit("close", entry);
            console.log("   info  -".cyan, "close".yellow, JSON.stringify(entry));
            delete urlData[id];
          }
        } else {
          entry = {};
        }
        response.json(entry);
      });

      /** Send clear request to all browsers - close all open urls. */
      app.get("/clear/*", function(request, response) {
        io.sockets.emit("clear");
        console.log("   info  -".cyan, "clear".yellow);
        response.json({ success: true });
      });

      /** Return number of connections connecting to InsFrame */
      app.get("/connections", function(request, response) {
        response.json({ connections: connections });
      });
    }
3508
function ( options, callback ) {
    
    if ( typeof options == 'function' && typeof callback != 'function' ) {
        callback = options;
    }
    var callback = callback || function (){};

    // Validate arguments
    if ( typeof options != 'object' || options.constructor != Object ) {
        callback( Error( 'AmqpStream requires the first argument to an options object.' ) );
        return false;
    }

    // If module was called as a function, return a new AmqpStream object
    if ( !(this instanceof AmqpStream) ) 
        return new AmqpStream( options, callback );

    // Variables / Properties
    var stream          = this;
    var err             = null;

    // Make sure we have a valid connection
    if ( !(amqpObjectType(options.connection)=='Connection') && !(amqpObjectType(options.exchange)=='Exchange') && !(amqpObjectType(options.queue)=='Queue') ) {
        callback( Error( 'AmqpStream requires at least one amqp object (Connection, Exchange, or Queue).' ) );
        return false;
    }

    // Determine connection bearing object
    var connection = amqpObjectType(options.connection)=='Connection' ? options.connection : 
        amqpObjectType(options.exchange)=='Exchange' ? options.exchange.connection :
        amqpObjectType(options.queue)=='Queue' ? options.queue.connection : null;

    // AMQP related configuration properties
    this.connection     = null;
    this.exchange       = null;
    this.queue          = null;
    this.routingKey     = options.routingKey || '#';
    this.ctag           = null;
    this.originId       = uniqueIdentifier();
    this.autoBind       = typeof options.autoBind != 'undefined' ? options.autoBind : true;

    this.correlations   = [];
    //this.correlationId  = (options.correlationId && options.correlationId === true) ? uniqueIdentifier() : (options.correlationId || null);

    this.publishOptions         = options.publishOptions || {};
    this.publishOptions.headers = this.publishOptions.headers || {};
    this.publishOptions.headers['x-stream-origin'] = this.originId;

    // Stream interface properties
    this.writable       = false;    // Enabled once exchange is set
    this.readable       = false;
    this.paused         = false;    // Start in an un-paused state
    this.ended          = false;
    this.destroyed      = false;
    this.buffer         = [];

    this.initializing   = true;

    var connectionReady = false;
    var exchangeReady   = false;
    var queueReady      = false;
    var onReady = function () {
        if ( stream.initializing && connectionReady && (exchangeReady || !options.exchange) && (queueReady || (typeof options.queue != 'undefined' && options.queue === false) ) ) {
            stream.initializing = false;
            callback( err, stream );
            process.nextTick( function () { stream.emit( 'ready' ); } );
        }
    }

    var configureStream = function ( connection, options ) {
        var connectionReady = function () {
            setConnection( connection );

            if ( amqpObjectType(options.exchange) == 'Exchange' ) setExchange( options.exchange );
            else if ( options.exchange && typeof options.exchange == 'string' ) {
                connection.exchange( options.exchange, options.exchangeOptions||{durable:false,autoDelete:true}, function (exchange) {
                    setExchange( exchange );
                });
            } 

            if ( amqpObjectType(options.queue) == 'Queue' ) { 
                if ( !options.exchange && options.queue.exchange ) {
                    options.exchange = options.queue.exchange;
                    setExchange( options.exchange );
                }
                setQueue( options.queue );
            }
            else if ( options.queue && typeof options.queue == 'string' ) {
                connection.queue( options.queue, options.queueOptions||{durable:false,autoDelete:true}, function (queue) {
                    setQueue( queue );
                });
            }
            // Skip binding to a queue if queue:false, will create write-only stream 
            else if ( typeof options.queue != 'undefined' && options.queue === false ) {
                options.queue = null;
            }
            else {
                options.queue = buildQueue();
            }

        }
        if ( !connection._connecting && connection.channels && Object.keys(connection.channels).length > 0 ) {
            connectionReady();
        }
        else {
            connection.on( 'ready', connectionReady );
        }
    }

    var setConnection = function ( connection ) {
        stream.connection = connection;
        stream.emit( 'connectionReady' );

        connectionReady = true;
        onReady();
    }
    var setExchange = function ( exchange ) {
        if ( stream.exchange )
            return;
        assert.equal( amqpObjectType(exchange), 'Exchange', 'setExchange expected an Exchange object' );
        stream.exchange = exchange;
        stream.writable = true;
        stream.emit( 'exchangeReady' );
        stream.exchange.on( 'error', function (err) { stream.emit( 'error', err); });

        exchangeReady = true;
        onReady();
    }
    var setQueue = function ( queue ) {
        if ( stream.queue ) 
            return;
        assert.equal( amqpObjectType(queue), 'Queue', 'setQueue expected a Queue object' );
        stream.queue = queue;
        stream.readable = true;
        stream.emit( 'queueReady' );
        queue.on( 'error', function (err) { stream.emit( 'error', err); });
        queue.subscribe( messageHandler ).addCallback( function(ok) { 
            stream.ctag = ok.consumerTag;
        });

        // if ( stream.correlationId ) {
        //     stream.publishOptions.replyTo = queue.name;
        //     stream.publishOptions.correlationId = stream.correlationId;
        // }

        queueReady = true;
        onReady();
    }
    var buildQueue = function ( ) {
        var queue = stream.connection.queue( '', {durable: false, exclusive: true, autoDelete: true}, function () {
            if ( stream.autoBind )
                queue.bind( stream.exchange, stream.routingKey );
            queue.bind( stream.exchange, queue.name );
            queue.on( 'queueBindOk', function () { setQueue(queue); });
        });
        return queue;
    }
    var onEnd = function () {
        stream.writable = stream.readable  = false;
        stream.ended = true;
        stream.emit( 'end' );
    }
    var messageHandler = function ( message, headers, deliveryInfo ) {
        if ( 'x-stream-origin' in headers && headers['x-stream-origin'] == stream.originId )
            return; // Do not emit our own writes ( this is for duplex streams )
        if ( deliveryInfo.correlationId ) {
            if ( deliveryInfo.correlationId in stream.correlations ) {
                var emitter = stream.correlations[ deliveryInfo.correlationId ];
            }
            else {
                var emitter = stream.createCorrelatedResponse( deliveryInfo.replyTo, deliveryInfo.correlationId, function ( err, emitter ) {
                    stream.emit( 'correlatedRequest', emitter );
                });
            }
            if ( 'x-stream-event' in headers && headers['x-stream-event'] == 'end') {
                if ( message.data && message.data.toString().trim() != '' )
                    emitter.emit( 'data', message.data );
                emitter.emit( 'end' );
                process.nextTick( function () { delete stream.correlations[deliveryInfo.correlationId] } );
            }
        }
        else {
            var emitter = stream;
            if ( 'x-stream-event' in headers && headers['x-stream-event'] == 'end' ) {

                if ( message.data && message.data.toString().trim() != '' )
                    emitter.emit( 'data', message.data );

                if( !( emitter.paused || emitter.buffer.length ) )
                    return onEnd();
                else
                    emitter.once( 'drain', onEnd );
                emitter.drain();
            }
        }
        
        if ( 'x-stream-event' in headers && headers['x-stream-event'] == 'error') {
            if ( message.data && message.data.toString().trim() != '' )
                emitter.emit( 'data', message.data );
            emitter.emit( 'error' );
        }
        else if ( ( !('x-stream-event' in headers) || ('x-stream-event' in headers && headers['x-stream-event'] == 'data') ) && 
            message.data && message.data.toString().trim() != '' 
        ) {
            if ( emitter.paused ) {
                emitter.buffer.push( message.data );
            }
            else {
                emitter.emit( 'data', message.data );
            }
        }
    }
    
    // Configure the stream
    configureStream( connection, options );
}