/*
Initiates a connection to a Coinfloor API server and returns the new
WebSocket object. A websocket URL may be given to override the default.
If a callback function is provided, it will be invoked after the
connection is established.
5930
function (url, callback) {
		if (_websocket) {
			_websocket.close();
			_websocket = null;
		}
		var ws = _websocket = new WebSocket(url || DEFAULT_URL);
		ws.onopen = function (event) {
			trigger("open", event);
		};
		ws.onerror = function (event) {
			trigger("error", event);
		};
		ws.onclose = function (event) {
			trigger("close", event);
		};
		var handler = function (event) {
			reset_idle_ping_timer();
			var msg = JSON.parse(event.data);
			console.log("Coinfloor >>", msg);
			if ("tag" in msg) {
				var handler = _result_handlers[msg.tag];
				delete _result_handlers[msg.tag];
				if (handler) {
					handler(msg);
				}
				else if (handler === undefined) {
					console.error("Coinfloor:", msg);
				}
			}
			else if ("notice" in msg) {
				trigger(msg.notice, msg);
			}
		};
		ws.onmessage = function (event) {
			var msg = JSON.parse(event.data);
			_server_nonce = atob(msg.nonce);
			this.onmessage = handler;
			handler(event);
			if (callback) {
				callback(msg);
			}
		};
	}
663336
function (options, callback) {
            /// <summary>Starts the connection</summary>
            /// <param name="options" type="Object">Options map</param>
            /// <param name="callback" type="Function">A callback function to execute when the connection has started</param>
            var connection = this,
                config = {
                    pingInterval: 300000,
                    waitForPageLoad: true,
                    transport: "auto",
                    jsonp: false
                },
                initialize,
                deferred = connection._deferral || $.Deferred(), // Check to see if there is a pre-existing deferral that's being built on, if so we want to keep using it
                parser = window.document.createElement("a");

            connection.lastError = null;

            // Persist the deferral so that if start is called multiple times the same deferral is used.
            connection._deferral = deferred;

            if (!connection.json) {
                // no JSON!
                throw new Error("SignalR: No JSON parser found. Please ensure json2.js is referenced before the SignalR.js file if you need to support clients without native JSON parsing support, e.g. IE<8.");
            }

            if ($.type(options) === "function") {
                // Support calling with single callback parameter
                callback = options;
            } else if ($.type(options) === "object") {
                $.extend(config, options);
                if ($.type(config.callback) === "function") {
                    callback = config.callback;
                }
            }

            config.transport = validateTransport(config.transport, connection);

            // If the transport is invalid throw an error and abort start
            if (!config.transport) {
                throw new Error("SignalR: Invalid transport(s) specified, aborting start.");
            }

            connection._.config = config;

            // Check to see if start is being called prior to page load
            // If waitForPageLoad is true we then want to re-direct function call to the window load event
            if (!_pageLoaded && config.waitForPageLoad === true) {
                connection._.deferredStartHandler = function () {
                    connection.start(options, callback);
                };
                _pageWindow.bind("load", connection._.deferredStartHandler);

                return deferred.promise();
            }

            // If we're already connecting just return the same deferral as the original connection start
            if (connection.state === signalR.connectionState.connecting) {
                return deferred.promise();
            } else if (changeState(connection,
                            signalR.connectionState.disconnected,
                            signalR.connectionState.connecting) === false) {
                // We're not connecting so try and transition into connecting.
                // If we fail to transition then we're either in connected or reconnecting.

                deferred.resolve(connection);
                return deferred.promise();
            }

            configureStopReconnectingTimeout(connection);

            // Resolve the full url
            parser.href = connection.url;
            if (!parser.protocol || parser.protocol === ":") {
                connection.protocol = window.document.location.protocol;
                connection.host = parser.host || window.document.location.host;
            } else {
                connection.protocol = parser.protocol;
                connection.host = parser.host;
            }

            connection.baseUrl = connection.protocol + "//" + connection.host;

            // Set the websocket protocol
            connection.wsProtocol = connection.protocol === "https:" ? "wss://" : "ws://";

            // If jsonp with no/auto transport is specified, then set the transport to long polling
            // since that is the only transport for which jsonp really makes sense.
            // Some developers might actually choose to specify jsonp for same origin requests
            // as demonstrated by Issue #623.
            if (config.transport === "auto" && config.jsonp === true) {
                config.transport = "longPolling";
            }

            // If the url is protocol relative, prepend the current windows protocol to the url. 
            if (connection.url.indexOf("//") === 0) {
                connection.url = window.location.protocol + connection.url;
                connection.log("Protocol relative URL detected, normalizing it to '" + connection.url + "'.");
            }

            if (this.isCrossDomain(connection.url)) {
                connection.log("Auto detected cross domain url.");

                if (config.transport === "auto") {
                    // TODO: Support XDM with foreverFrame
                    config.transport = ["webSockets", "serverSentEvents", "longPolling"];
                }

                if (typeof (config.withCredentials) === "undefined") {
                    config.withCredentials = true;
                }

                // Determine if jsonp is the only choice for negotiation, ajaxSend and ajaxAbort.
                // i.e. if the browser doesn't supports CORS
                // If it is, ignore any preference to the contrary, and switch to jsonp.
                if (!config.jsonp) {
                    config.jsonp = !$.support.cors;

                    if (config.jsonp) {
                        connection.log("Using jsonp because this browser doesn't support CORS.");
                    }
                }

                connection.contentType = signalR._.defaultContentType;
            }

            connection.withCredentials = config.withCredentials;

            connection.ajaxDataType = config.jsonp ? "jsonp" : "text";

            $(connection).bind(events.onStart, function (e, data) {
                if ($.type(callback) === "function") {
                    callback.call(connection);
                }
                deferred.resolve(connection);
            });

            connection._.initHandler = signalR.transports._logic.initHandler(connection);

            initialize = function (transports, index) {
                var noTransportError = signalR._.error(resources.noTransportOnInit);

                index = index || 0;
                if (index >= transports.length) {
                    if (index === 0) {
                        connection.log("No transports supported by the server were selected.");
                    } else if (index === 1) {
                        connection.log("No fallback transports were selected.");
                    } else {
                        connection.log("Fallback transports exhausted.");
                    }

                    // No transport initialized successfully
                    $(connection).triggerHandler(events.onError, [noTransportError]);
                    deferred.reject(noTransportError);
                    // Stop the connection if it has connected and move it into the disconnected state
                    connection.stop();
                    return;
                }

                // The connection was aborted
                if (connection.state === signalR.connectionState.disconnected) {
                    return;
                }

                var transportName = transports[index],
                    transport = signalR.transports[transportName],
                    onFallback = function () {
                        initialize(transports, index + 1);
                    };

                connection.transport = transport;

                try {
                    connection._.initHandler.start(transport, function () { // success
                        // Firefox 11+ doesn't allow sync XHR withCredentials: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#withCredentials
                        var isFirefox11OrGreater = signalR._.firefoxMajorVersion(window.navigator.userAgent) >= 11,
                            asyncAbort = !!connection.withCredentials && isFirefox11OrGreater;

                        connection.log("The start request succeeded. Transitioning to the connected state.");

                        if (supportsKeepAlive(connection)) {
                            signalR.transports._logic.monitorKeepAlive(connection);
                        }

                        signalR.transports._logic.startHeartbeat(connection);

                        // Used to ensure low activity clients maintain their authentication.
                        // Must be configured once a transport has been decided to perform valid ping requests.
                        signalR._.configurePingInterval(connection);

                        if (!changeState(connection,
                                            signalR.connectionState.connecting,
                                            signalR.connectionState.connected)) {
                            connection.log("WARNING! The connection was not in the connecting state.");
                        }

                        // Drain any incoming buffered messages (messages that came in prior to connect)
                        connection._.connectingMessageBuffer.drain();

                        $(connection).triggerHandler(events.onStart);

                        // wire the stop handler for when the user leaves the page
                        _pageWindow.bind("unload", function () {
                            connection.log("Window unloading, stopping the connection.");

                            connection.stop(asyncAbort);
                        });

                        if (isFirefox11OrGreater) {
                            // Firefox does not fire cross-domain XHRs in the normal unload handler on tab close.
                            // #2400
                            _pageWindow.bind("beforeunload", function () {
                                // If connection.stop() runs runs in beforeunload and fails, it will also fail
                                // in unload unless connection.stop() runs after a timeout.
                                window.setTimeout(function () {
                                    connection.stop(asyncAbort);
                                }, 0);
                            });
                        }
                    }, onFallback);
                }
                catch (error) {
                    connection.log(transport.name + " transport threw '" + error.message + "' when attempting to start.");
                    onFallback();
                }
            };

            var url = connection.url + "/negotiate",
                onFailed = function (error, connection) {
                    var err = signalR._.error(resources.errorOnNegotiate, error, connection._.negotiateRequest);

                    $(connection).triggerHandler(events.onError, err);
                    deferred.reject(err);
                    // Stop the connection if negotiate failed
                    connection.stop();
                };

            $(connection).triggerHandler(events.onStarting);

            url = signalR.transports._logic.prepareQueryString(connection, url);

            connection.log("Negotiating with '" + url + "'.");

            // Save the ajax negotiate request object so we can abort it if stop is called while the request is in flight.
            connection._.negotiateRequest = signalR.transports._logic.ajax(connection, {
                url: url,
                error: function (error, statusText) {
                    // We don't want to cause any errors if we're aborting our own negotiate request.
                    if (statusText !== _negotiateAbortText) {
                        onFailed(error, connection);
                    } else {
                        // This rejection will noop if the deferred has already been resolved or rejected.
                        deferred.reject(signalR._.error(resources.stoppedWhileNegotiating, null /* error */, connection._.negotiateRequest));
                    }
                },
                success: function (result) {
                    var res,
                        keepAliveData,
                        protocolError,
                        transports = [],
                        supportedTransports = [];

                    try {
                        res = connection._parseResponse(result);
                    } catch (error) {
                        onFailed(signalR._.error(resources.errorParsingNegotiateResponse, error), connection);
                        return;
                    }

                    keepAliveData = connection._.keepAliveData;
                    connection.appRelativeUrl = res.Url;
                    connection.id = res.ConnectionId;
                    connection.token = res.ConnectionToken;
                    connection.webSocketServerUrl = res.WebSocketServerUrl;

                    // The long poll timeout is the ConnectionTimeout plus 10 seconds
                    connection._.pollTimeout = res.ConnectionTimeout * 1000 + 10000; // in ms

                    // Once the server has labeled the PersistentConnection as Disconnected, we should stop attempting to reconnect
                    // after res.DisconnectTimeout seconds.
                    connection.disconnectTimeout = res.DisconnectTimeout * 1000; // in ms

                    // Add the TransportConnectTimeout from the response to the transportConnectTimeout from the client to calculate the total timeout
                    connection._.totalTransportConnectTimeout = connection.transportConnectTimeout + res.TransportConnectTimeout * 1000;

                    // If we have a keep alive
                    if (res.KeepAliveTimeout) {
                        // Register the keep alive data as activated
                        keepAliveData.activated = true;

                        // Timeout to designate when to force the connection into reconnecting converted to milliseconds
                        keepAliveData.timeout = res.KeepAliveTimeout * 1000;

                        // Timeout to designate when to warn the developer that the connection may be dead or is not responding.
                        keepAliveData.timeoutWarning = keepAliveData.timeout * connection.keepAliveWarnAt;

                        // Instantiate the frequency in which we check the keep alive.  It must be short in order to not miss/pick up any changes
                        connection._.beatInterval = (keepAliveData.timeout - keepAliveData.timeoutWarning) / 3;
                    } else {
                        keepAliveData.activated = false;
                    }

                    connection.reconnectWindow = connection.disconnectTimeout + (keepAliveData.timeout || 0);

                    if (!res.ProtocolVersion || res.ProtocolVersion !== connection.clientProtocol) {
                        protocolError = signalR._.error(signalR._.format(resources.protocolIncompatible, connection.clientProtocol, res.ProtocolVersion));
                        $(connection).triggerHandler(events.onError, [protocolError]);
                        deferred.reject(protocolError);

                        return;
                    }

                    $.each(signalR.transports, function (key) {
                        if ((key.indexOf("_") === 0) || (key === "webSockets" && !res.TryWebSockets)) {
                            return true;
                        }
                        supportedTransports.push(key);
                    });

                    if ($.isArray(config.transport)) {
                        $.each(config.transport, function (_, transport) {
                            if ($.inArray(transport, supportedTransports) >= 0) {
                                transports.push(transport);
                            }
                        });
                    } else if (config.transport === "auto") {
                        transports = supportedTransports;
                    } else if ($.inArray(config.transport, supportedTransports) >= 0) {
                        transports.push(config.transport);
                    }

                    initialize(transports);
                }
            });

            return deferred.promise();
        }
1208858
function _poolCreate() {
      // implementation is copy-pasted from https://github.com/tediousjs/node-mssql/pull/614
      return new base.Promise((resolve, reject) => {
        const cfg = {
          userName: this.config.user,
          password: this.config.password,
          server: this.config.server,
          options: Object.assign({}, this.config.options),
          domain: this.config.domain,
        };

        cfg.options.database = this.config.database;
        cfg.options.port = this.config.port;
        cfg.options.connectTimeout =
          this.config.connectionTimeout || this.config.timeout || 15000;
        cfg.options.requestTimeout =
          this.config.requestTimeout != null
            ? this.config.requestTimeout
            : 15000;
        cfg.options.tdsVersion = cfg.options.tdsVersion || '7_4';
        cfg.options.rowCollectionOnDone = false;
        cfg.options.rowCollectionOnRequestCompletion = false;
        cfg.options.useColumnNames = false;
        cfg.options.appName = cfg.options.appName || 'node-mssql';

        // tedious always connect via tcp when port is specified
        if (cfg.options.instanceName) delete cfg.options.port;

        if (isNaN(cfg.options.requestTimeout))
          cfg.options.requestTimeout = 15000;
        if (cfg.options.requestTimeout === Infinity)
          cfg.options.requestTimeout = 0;
        if (cfg.options.requestTimeout < 0) cfg.options.requestTimeout = 0;

        if (this.config.debug) {
          cfg.options.debug = {
            packet: true,
            token: true,
            data: true,
            payload: true,
          };
        }

        const tedious = new tds.Connection(cfg);

        // prevent calling resolve again on end event
        let alreadyResolved = false;
        function safeResolve(err) {
          if (!alreadyResolved) {
            alreadyResolved = true;
            resolve(err);
          }
        }

        function safeReject(err) {
          if (!alreadyResolved) {
            alreadyResolved = true;
            reject(err);
          }
        }

        tedious.once('end', (evt) => {
          safeReject(
            new base.ConnectionError(
              'Connection ended unexpectedly during connecting'
            )
          );
        });

        tedious.once('connect', (err) => {
          if (err) {
            err = new base.ConnectionError(err);
            return safeReject(err);
          }
          safeResolve(tedious);
        });

        tedious.on('error', (err) => {
          if (err.code === 'ESOCKET') {
            tedious.hasError = true;
            return;
          }

          this.emit('error', err);
        });

        if (this.config.debug) {
          tedious.on('debug', this.emit.bind(this, 'debug', tedious));
        }
      });
    }
1056160
function HybridConnectionsWebSocketServer(options, callback) {
  if (this instanceof HybridConnectionsWebSocketServer === false) {
    return new HybridConnectionsWebSocketServer(options, callback);
  }

  EventEmitter.call(this);

  options = Object.assign({
    server: null,
    token: null,
    id: null,
    verifyClient: null,
    handleProtocols: null,
    disableHixie: false,
    clientTracking: true,
    perMessageDeflate: true,
    maxPayload: 100 * 1024 * 1024,
    backlog: null // use default (511 as implemented in net.js)
  }, options);

  if (!isDefinedAndNonNull(options, 'server')) {
    throw new TypeError('\'server\' must be provided');
  }

  if (!isDefinedAndNonNull(options, 'token')) {
    throw new TypeError('A \'token\' string or function must be provided');
  }

  var self = this;

  this.listenUri = options.server;
  if (isDefinedAndNonNull(options, 'id')) {
    this.listenUri = listenUri + '&id=' + options.id;
  }

  this.closeRequested = false;
  this.options = options;
  this.path = options.path;
  this.clients = [];

  connectControlChannel(this);
}
417089
function _openClientConnection() {
  _openClientConnection = _asyncToGenerator(
  /*#__PURE__*/
  _regeneratorRuntime.mark(function _callee12(channelName, readerUuid) {
    var pathToSocket, client;
    return _regeneratorRuntime.wrap(function _callee12$(_context12) {
      while (1) {
        switch (_context12.prev = _context12.next) {
          case 0:
            pathToSocket = socketPath(channelName, readerUuid);
            client = new net.Socket();
            return _context12.abrupt("return", new Promise(function (res, rej) {
              client.connect(pathToSocket, function () {
                return res(client);
              });
              client.on('error', function (err) {
                return rej(err);
              });
            }));

          case 3:
          case "end":
            return _context12.stop();
        }
      }
    }, _callee12);
  }));
  return _openClientConnection.apply(this, arguments);
}
1235845
def new_conn(self):
        
        """
        :return:
        """
        logger.debug("Opening new connection to rethinkdb with args=%s" % self._conn_args)
        return ConnectionWrapper(self._pool, **self._conn_args)
717970
function initialize(url) {
    this.socket = Requests[Requests.method](this);

    //
    // Open the socket BEFORE adding any properties to the instance as this might
    // trigger a thrown `InvalidStateError: An attempt was made to use an object
    // that is not, or is no longer, usable` error in FireFox:
    //
    // @see https://bugzilla.mozilla.org/show_bug.cgi?id=707484
    //
    this.socket.open(this.method.toUpperCase(), url, true);

    //
    // Register this as an active HTTP request.
    //
    Requests.active[this.id] = this;
  }
733965
function createClient(wsdlUrl, options, cb) {
  if (!cb) {
    cb = options;
    options = {};
  }

  if (this.errOnCreateClient) {
    return setTimeout(cb.bind(null, new Error('forced error on createClient')));
  }

  var client = getStub(wsdlUrl);

  if (client) {
    resetStubbedMethods(client);
    setTimeout(cb.bind(null, null, client));
  } else {
    setTimeout(cb.bind(null, new Error('no client stubbed for ' + wsdlUrl)));
  }
}
492977
async function () {
    const oThis = this
      , web3Provider = web3ProviderFactory.getProvider(oThis.chain, 'ws')
      , abi = coreAddresses.getAbiForContract(oThis.contractName)
      , contractObj = new web3Provider.eth.Contract(abi)
      , bufferGasLimit = 10000
    ;

    contractObj.options.address = oThis.contractAddress;
    //contractObj.setProvider(web3Provider.currentProvider);

    const transactionOptions = {
      from: oThis.senderAddress,
      gasPrice: (oThis.chain === 'value') ? VC_GAS_PRICE : UC_GAS_PRICE,
      gas: (oThis.chain === 'value') ? VC_GAS_LIMIT : UC_GAS_LIMIT
    };

    const scope = contractObj.methods
      , gasToUse = await (scope[oThis.methodName].apply(scope,
      (oThis.methodArguments || []))).estimateGas(transactionOptions);

    return responseHelper.successWithData({gas_to_use: gasToUse + bufferGasLimit});
  }
347101
function InterchangeConnection(connectionManager, interchangeUrl) {
  var self = {};

  var socket;

  self.interchangeUrl = interchangeUrl;
  self.connected = false;
  self.sessionId = undefined;
  self.serverVersion = 'unknown';
  self.serverAgent = 'unknown';

  var pendingCommands = [];

  /**
   * Opens a socket connection to the interchange server.
   */
  self._open = function() {
    debug('Connecting to %s', interchangeUrl);

    socket = io.connect(interchangeUrl, {
        forceNew: true,
        transports: ['websocket']
    });

    ///////////////////
    // Socket Events //
    ///////////////////

    socket.on('connect', function() {
      debug('Connected to %s', interchangeUrl);
      self.connected = true;
      connectionManager.emit('connect', {
          interchangeUrl: interchangeUrl
      });
      _nextCommand();
    });

    socket.on('error', function(err) {
      console.error('Connection error %s', interchangeUrl);
      connectionManager.emit('error', {
          interchangeUrl: interchangeUrl,
          error: err
      });
    });

    socket.on('reconnect', function() {
      debug('Reconnecting %s', interchangeUrl);
      // If our client has previously set the session, then reissue it on
      // reconnection.
      if (self.sessionId) {
        self.SESSION(self.sessionId);
      }
      connectionManager.emit('reconnect', {
          interchangeUrl: interchangeUrl
      });
    });

    socket.on('disconnect', function() {
      debug('Disconnected %s', interchangeUrl);
      self.connected = false;
      connectionManager.emit('disconnect', {
          interchangeUrl: interchangeUrl
      });
    });

    socket.on('reconnect_failed', function() {
      debug('Reconnection failed %s', interchangeUrl);
      connectionManager.emit('reconnect_failed', {
          interchangeUrl: interchangeUrl
      });
    });

    ///////////////////////////////
    // Interchange Push Messages //
    ///////////////////////////////

    socket.on('STANZA', function(stanza) {
      debug('STANZA', stanza);
      connectionManager.emit('STANZA', stanza);
    });

    return self;
  }

  //////////////////////////
  // Interchange Commands //
  //////////////////////////

  self.SESSION = function(sessionId) {
    self.sessionId = sessionId;
    var url = 'vox:__session__' + (sessionId ? ('/session/' + sessionId) : '/session');
    return sendCommand('POST', url, {
          version: connectionManager.version,
          agent: connectionManager.agent,
       }, true)
      .then(function(reply) {
        var newSessionId = reply ? reply.newSessionId : 0;
        // If the server replies with a new session ID, then it has created a
        // new session for us.  Update our internal record.
        if (newSessionId) {
          self.sessionId = newSessionId;
        }
        reply = reply ? reply : {};
        reply.version = (reply.version ? reply.version : 'unknown').substr(0, 64);
        reply.agent = (reply.agent ? reply.agent : 'unknown').substr(0, 64);
        self.serverVersion = reply.version;
        self.serverAgent = reply.agent;
        reply.interchangeUrl = interchangeUrl;
        connectionManager.emit('SESSION', reply);
        _nextCommand();
        return reply;
      });
  }

  self.GET = function(url, payload) {
    return sendCommand('GET', url, payload);
  }

  self.POST = function(url, payload) {
    return sendCommand('POST', url, payload);
  }

  self.SUBSCRIBE = function(url, payload) {
    return sendCommand('SUBSCRIBE', url, payload);
  }

  self.UNSUBSCRIBE = function(url, payload) {
    return sendCommand('UNSUBSCRIBE', url, payload);
  }

  self.close = function() {
    socket.close();
    connectionManager._removeConnection(self);
  }

  /**
   * Helper function to send a command to the server.
   *
   * Returns a Promise for the server's response.  Rejects the Promise if the
   * reply's status is not 200.
   *
   * If this connection is not ready to receive commands, the command is queued
   * for later execution.
   */
  function sendCommand(method, url, payload, skipQueue) {
    if (!self.connected) {
      debug('Queueing %s %s', method, url);
      return new P(function(resolve, reject) {
        var p = P.method(function() {
          debug('Dequeueing %s %s', method, url);
          return _sendCommand(method, url, payload)
            .then(resolve)
            .catch(reject);
        });
        if (skipQueue) {
          pendingCommands.splice(0, 0, p);
        } else {
          pendingCommands.push(p);
        }
      });
    }
    return _sendCommand(method, url, payload);
  }

  function _sendCommand(method, url, payload) {
    return new P(function(resolve, reject) {
      var data = {
          url: url,
          payload: payload
      };
      debug('REQUEST %s %s %s\n', interchangeUrl, method, url, data);
      socket.emit(method, data, function(reply) {
        debug('REPLY %s %s %s\n', interchangeUrl, method, url, reply);
        if (reply && reply.status && reply.status != 200) {
          reject(new errors.HttpError(reply.status, reply.message));
        } else {
          resolve(reply);
        }
      });
    });
  }

  /**
   * Executes the next command on the queue.
   */
  function _nextCommand() {
    var fn = pendingCommands.shift();
    if (!fn) {
      return;
    }
    fn().then(_nextCommand);
  }

  return self;
}
83935
function init(ctx) {
        var server = ctx.server;

        return registerCookieJar(server)
            .then(function () {
                registerJwtCookie(server);
                server.ext('onPreAuth', getJwtFromCookie);

                return new Q(ctx);
            });
    }
1292303
private Socket createConnectedSocket(final String url) {
		try {
			final Socket initSocket = IO.socket(url);

			final Callback callback = new Callback();
			
			initSocket.on(Socket.EVENT_CONNECT, callback);
			initSocket.on(Socket.EVENT_CONNECT_ERROR, callback);
			initSocket.on(Socket.EVENT_CONNECT_TIMEOUT, callback);
			initSocket.on(Socket.EVENT_CONNECT_ERROR, callback);
			initSocket.on(Socket.EVENT_DISCONNECT, callback);
			initSocket.on(Socket.EVENT_ERROR, callback);
			
			// Be sure that the emit/ack is synchronous to get the filters before the test are run
			LOGGER.finest("Connection to Probe Dock RT"); // Unable to use the logger into the run method
			new Thread(new Runnable() {
				@Override
				public void run() {
					initSocket.connect();
				}
			}).start();
			
			synchronized (callback) {
				callback.wait();
			}

			if (!initSocket.connected()) {
				LOGGER.warning("Probe Dock RT is not available");
				return null;
			}
			
			return initSocket;
		}
		catch (URISyntaxException | InterruptedException e) {
			LOGGER.log(Level.WARNING, "Unknown error", e);
		}
		
		return null;
	}
495485
async function () {
    const oThis = this
    ;

    const web3Provider = web3ProviderFactory.getProvider(oThis.chain, web3ProviderFactory.typeWS);
    if (!web3Provider) {
      let errObj = responseHelper.error({
        internal_error_identifier: 's_u_ga_1',
        api_error_identifier: 'invalid_chain',
        error_config: basicHelper.fetchErrorConfig()
      });
      return Promise.resolve(errObj);
    }

    var eth_address = await web3Provider.eth.personal.newAccount(oThis.passphrase);

    // returns a promise which resolves to an address which was created.
    return Promise.resolve(responseHelper.successWithData({address: eth_address}));
  }
1029543
function createConnectionObject(context) {
  const { req } = context.bindings;
  const xForwardedFor = req.headers ? req.headers["x-forwarded-for"] : undefined;

  return {
    encrypted     : req.originalUrl && req.originalUrl.toLowerCase().startsWith("https"),
    remoteAddress : removePortFromAddress(xForwardedFor)
  };
}
943812
function TransportClient() {
        log.info("instantiate websocket");
        // get non-ambiguous this
        var self = this;
        // Call parent constructor
        TransportClient.super_.call(self);
        // Internal structures
        self._ws = undefined;
        self._id = _.uniqueId(); // debugging tool only
        self._state = "NOT_OPENED";
        // state listeners
        self.once("open", function handleOpened() {
            self._state = "OPEN";
        }).once("close", function handleClosed() {
            self._state = "CLOSED";
        });
        // constructor - return undefined
        return undefined;
    }
1208684
function createHttpsServer(options, requestHandler, keys) {
  net
    .createServer(function(socket){
      socket.once('data', function(buffer){
        // Pause the socket
        socket.pause();

        // Determine if this is an HTTP(s) request
        var byte = buffer[0];
        var proxy;

        if (byte === 22)
          proxy = server.https;
        else if (32 < byte && byte < 127)
          proxy = server.http;

        if (proxy)
        {
          // Push the buffer back onto the front of the data stream
          socket.unshift(buffer);

          // Emit the socket to the HTTP(s) server
          proxy.emit('connection', socket);
        }

        // Resume the socket data stream
        socket.resume();
      });
    })
    .on('error', function(error){
      onError(error, options);
    })
    .listen(options.port, function(){
      onListen(this, options);
    });

  var server = {
    http: http.createServer(requestHandler),
    https: https.createServer(keys, requestHandler)
  };

  return server;
}
1280799
function connectBrowser (subscriptions, backlog, host, done_cb, secure) {

    // Associate the right port
    var websocket_uri;
    if(secure == true) {
        websocket_uri ='wss://' + host + ':1885/mqtt';
    }
    else {
        websocket_uri ='ws://' + host + ':1884/mqtt';
    }

    // Create client
    var client = new mqtt_lib.Client(websocket_uri, generateRandomClientId());
    // Register callback for connection lost
    client.onConnectionLost = function() {
        // TODO try to reconnect
    };
    // Register callback for received message
    client.onMessageArrived = function (message) {
        // Execute all the appropriate callbacks:
        // the ones specific to this channel with a single parameter (message)
        // the ones associated to a wildcard channel, with two parameters (message and channel)
        var cbs = findCallbacks(subscriptions, message.destinationName);
        if (cbs!==undefined) {
            cbs.forEach(function(cb) {
                if (Object.keys(subscriptions).indexOf(message.destinationName)!==-1)
                    cb(message.payloadString);
                else
                    cb(message.payloadString, message.destinationName);
            });
        }
    };
    // Connect
    client.connect({onSuccess: function() {
        // Execute optional done callback passing true
        if (done_cb!==undefined)
            done_cb(true);
        // Execute the backlog of operations performed while the client wasn't connected
        backlog.forEach(function(e) {
            e.op.apply(this, e.params);
        });
    },
        onFailure: function() {
            // Execute optional done callback passing false
            if (done_cb!==undefined)
                done_cb(false);
            else
                console.error('There was a problem initializing nutella.');
        }});
    return client;
}