tries to connect to the same app on differnet host from dist-info
11752
def reelect_app(self, request, app):
        """"""

        # disconnect app explicitly to break possibly existing connection
        app.disconnect()
        endpoints_size = len(app.locator.endpoints)

        # try x times, where x is the number of different endpoints in app locator.
        for _ in xrange(0, endpoints_size + 1):
            # last chance to take app from common pool
            if len(app.locator.endpoints) == 0:
                request.logger.info(
                    "giving up on connecting to dist-info hosts, falling back to common pool processing")
                app = yield self.proxy.reelect_app(request, app)
                raise gen.Return(app)

            try:
                # always create new locator to prevent locking as we do connect with timeout
                # however lock can be still held during TCP timeout
                locator = Locator(endpoints=app.locator.endpoints)
                request.logger.info("connecting to locator %s", locator.endpoints[0])

                # first try to connect to locator only on remote host with timeout
                yield gen.with_timeout(self.service_connect_timeout, locator.connect())
                request.logger.debug("connected to locator %s for %s", locator.endpoints[0], app.name)
                app = Service(app.name, locator=locator, timeout=RESOLVE_TIMEOUT)

                # try to resolve and connect to application itself
                yield gen.with_timeout(self.service_connect_timeout, app.connect())
                request.logger.debug("connected to application %s via %s", app.name, app.endpoints)
            except gen.TimeoutError:
                # on timeout try next endpoint first
                request.logger.warning("timed out while connecting to application")
                continue
            except ServiceError as err:
                request.logger.warning("got error while resolving app - %s", err)
                if err.category in LOCATORCATEGORY and err.code == ESERVICENOTAVAILABLE:
                    # if the application is down - also try next endpoint
                    continue
                else:
                    raise err
            finally:
                # drop first endpoint to start next connection from different endpoint
                # we do this, as default logic of connection attempts in locator do not fit here
                app.locator.endpoints = app.locator.endpoints[1:]
            # return connected app
            raise gen.Return(app)
        raise PluginApplicationError(42, 42, "could not connect to application")
28901
def connect(self, addr):
        '''
        
        '''
        if addr.find(':') == -1:
            addr += ':5555'
        output = self.run_cmd('connect', addr)
        return 'unable to connect' not in output
644343
def _connect(self):
        """"""
        if self._socketFile is not None:
            if not os.path.exists(self._socketFile):
                raise Exception("Socket file (%s) for Memcached Instance not found."
                                % self._socketFile)
        try:
            if self._timeout is not None:
                self._conn = util.Telnet(self._host, self._port, self._socketFile, 
                                         timeout)
            else:
                self._conn = util.Telnet(self._host, self._port, self._socketFile)
        except:     
            raise Exception("Connection to %s failed." % self._instanceName)
652097
def connect(self, host=HOST, port=GPSD_PORT):
        
        for alotta_stuff in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
            family, socktype, proto, _canonname, host_port = alotta_stuff
            try:
                self.streamSock = socket.socket(family, socktype, proto)
                self.streamSock.connect(host_port)
                self.streamSock.setblocking(False)
            except (OSError, IOError) as error:
                sys.stderr.write('\r\nGPSDSocket.connect exception is--> {}'.format(error))
                sys.stderr.write('\r\nGPS3 gpsd connection at \'{0}\' on port \'{1}\' failed\r\n'.format(host, port))
673533
def _connect(self):
        """"""
        if sys.version_info[:2] < (2,6):
            self._conn = httplib.HTTPConnection(self._host, self._port)
        else:
            self._conn = httplib.HTTPConnection(self._host, self._port, 
                                                False, defaultTimeout)
594029
def init(port=8813, numRetries=10, host="localhost", label="default"):
    
    _connections[label] = connect(port, numRetries, host)
    switch(label)
    return getVersion()
1204818
function resolveHostAndPort() {
  const connectionOptions = this.connection_options;
  return connectionOptions ? [connectionOptions.host, connectionOptions.port] :
    this.options ? [this.options.host, this.options.port] : [defaultHost, defaultPort];
}
862986
def connect(self):
        """"""
        try:
            _, self.transport = yield from open_connection(
                self.hostname, self.port, loop=self.parent.app.loop)
        except OSError:
            if self.parent.cfg.fail_silently:
                return False
            raise
        return self
578922
def get_distroinfo(distro=None):
    """"""
    if not distro:
        distro = cfg['DISTRO']
    _info_file = info_file(distro)
    # prefer git fetcher if available
    git_info_url_conf = distro.upper() + 'INFO_REPO'
    try:
        remote_git_info = cfg[git_info_url_conf]
        return DistroInfo(_info_file, remote_git_info=remote_git_info)
    except KeyError:
        pass
    # try raw remote fetcher
    remote_info_url_conf = distro.upper() + 'INFO_RAW_URL'
    try:
        remote_info = cfg[remote_info_url_conf]
        return DistroInfo(_info_file, remote_info=remote_info)
    except KeyError:
        raise exception.InvalidUsage(
            why="Couldn't find config option %s or %s for distro: %s"
                % (git_info_url_conf, remote_info_url_conf, distro))
1278199
async def connect(self, server_info, proto_code=None, *,
                            use_tor=False, disable_cert_verify=False,
                            proxy=None, short_term=False):
        '''
            
        '''
        self.server_info = server_info
        if not proto_code:
             proto_code,*_ = server_info.protocols
        self.proto_code = proto_code

        logger.debug("Connecting to: %r" % server_info)

        if proto_code == 'g':       # websocket
            # to do this, we'll need a websockets implementation that
            # operates more like a asyncio.Transport
            # maybe: `asyncws` or `aiohttp` 
            raise NotImplementedError('sorry no WebSocket transport yet')

        hostname, port, use_ssl = server_info.get_port(proto_code)

        if use_tor:
            if have_aiosocks:
                # Connect via Tor proxy proxy, assumed to be on localhost:9050
                # unless a tuple is given with another host/port combo.
                try:
                    socks_host, socks_port = use_tor
                except TypeError:
                    socks_host, socks_port = 'localhost', 9050

                # basically no-one has .onion SSL certificates, and
                # pointless anyway.
                disable_cert_verify = True

                assert not proxy, "Sorry not yet supporting proxy->tor->dest"

                logger.debug(" .. using TOR")

                proxy = aiosocks.Socks5Addr(socks_host, int(socks_port))
            else:
                logger.debug("Error: want to use tor, but no aiosocks module.")

        if use_ssl == True and disable_cert_verify:
            # Create a more liberal SSL context that won't
            # object to self-signed certicates. This is 
            # very bad on public Internet, but probably ok
            # over Tor
            use_ssl = ssl.create_default_context()
            use_ssl.check_hostname = False
            use_ssl.verify_mode = ssl.CERT_NONE

            logger.debug(" .. SSL cert check disabled")

        async def _reconnect():
            if self.protocol: return        # race/duplicate work

            if proxy:
                if have_aiosocks:
                    transport, protocol = await aiosocks.create_connection(
                                            StratumProtocol, proxy=proxy,
                                            proxy_auth=None,
                                            remote_resolve=True, ssl=use_ssl,
                                            dst=(hostname, port))
                else:
                    logger.debug("Error: want to use proxy, but no aiosocks module.")
            else:
                transport, protocol = await self.loop.create_connection(
                                                        StratumProtocol, host=hostname,
                                                        port=port, ssl=use_ssl)

            self.protocol = protocol
            protocol.client = self

            # capture actual values used
            self.actual_connection = dict(hostname=hostname, port=int(port),
                                            ssl=bool(use_ssl), tor=bool(proxy))
            self.actual_connection['ip_addr'] = transport.get_extra_info('peername',
                                                        default=['unknown'])[0]

            if not short_term:
                self.ka_task = self.loop.create_task(self._keepalive())

            logger.debug("Connected to: %r" % server_info)

        # close whatever we had
        if self.protocol:
            self.protocol.close()
            self.protocol = None

        self.reconnect = _reconnect
        await self.reconnect()
577726
function tlsConnect(options) {
  options.path = undefined;
  options.servername = options.servername || options.host;
  return tls.connect(options);
}
470031
def connect(self):
        """"""
        device = None
        # logger.debug("Connecting to: {}".format(str(self)))
        for device in self.devices:
            if not device.connected:
                self.connection.emit_message("Connecting {}".format(str(device)), log_level=logging.INFO)
                protocol_name = device.get_protocol_name()
                device.protocol = make_protocol(protocol_name, device)
                command = device.protocol.get_command()
                self.ctrl.spawn_session(command=command)
                try:
                    result = device.connect(self.ctrl)
                except CommandSyntaxError as exc:
                    # all commands during discovery provides itself in exception except
                    # spawn session which is handled differently. If command syntax error is detected during spawning
                    # a new session then the problem is either on jumphost or csm server.
                    # The problem with spawning session is detected in connect FSM for telnet and ssh.
                    if exc.command:
                        cmd = exc.command
                        host = device.hostname
                    else:
                        cmd = command
                        host = "Jumphost/CSM"

                    self.connection.log(
                        "Command not supported or not authorized on {}: '{}'".format(host, cmd))
                    raise CommandError(message="Command not supported or not authorized",
                                       command=cmd,
                                       host=host)

                if result:
                    # logger.info("Connected to {}".format(device))
                    self.connection.emit_message("Connected {}".format(device), log_level=logging.INFO)
                else:
                    if device.last_error_msg:
                        message = device.last_error_msg
                        device.last_error_msg = None
                    else:
                        message = "Connection error"

                    self.connection.log(message)
                    raise ConnectionError(message)  # , host=str(device))

        if device is None:
            raise ConnectionError("No devices")

        return True
549991
def connect_to_ipykernel(self, service_name, timeout=10):
        """"""
        kernel_json_file = self.wait_for_ipykernel(service_name, timeout=10)
        self.start_interactive_mode()
        subprocess.check_call([
            sys.executable, "-m", "IPython", "console", "--existing", kernel_json_file
        ])
        self.stop_interactive_mode()
222132
function tryConnect() {
    if (!seleniumIP) {
        process.nextTick(buildDriver);
        return;
    }
    const sock = net.connect({
        host: seleniumIP,
        port: +seleniumPort,
    });
    sock.on("connect", function() {
        sock.end();
        attempts = 0;
        process.nextTick(buildDriver);
    }).on("error", function() {
        if (++attempts > 50) {
            throw new Error("Failed to connect selenium server.");
        }
        setTimeout(tryConnect, 200);
    });
}
695122
function (cb) {
					if (argv.env === 'saucelabs-travis' || (argv.env === 'saucelabs-local' && argv['sauce-username'] && argv['sauce-access-key'])) {
						startSauceConnect(cb);
					} else {
						if (argv.env === 'saucelabs-local') {
							console.error([moment().format('HH:mm:ss:SSS')] + ' kne: You must specify --sauce-username and --sauce-access-key when using: --' + argv.env);
							cb(new Error('kne: You must specify --sauce-username and --sauce-access-key when using: --' + argv.env));
						} else {
							cb();
						}
					}
				}
88928
def connect_telnet(name, ip_address=None, user='micro', password='python'):
    """"""
    if ip_address is None:
        try:
            ip_address = socket.gethostbyname(name)
        except socket.gaierror:
            ip_address = name
    if not QUIET:
        if name == ip_address:
            print('Connecting to (%s) ...' % ip_address)
        else:
            print('Connecting to %s (%s) ...' % (name, ip_address))
    dev = DeviceNet(name, ip_address, user, password)
    add_device(dev)
826914
async function connect() {
  
  let esConfig
  let client

  // use local client
  if (!process.env.ES_HOST) {
    client = new elasticsearch.Client({host: 'localhost:9200'})
  } else {
    await new Promise((resolve, reject) => AWS.config.getCredentials((err) => {
      if (err) return reject(err)
      resolve()
    }))

    esConfig = {
      host: process.env.ES_HOST,
      connectionClass: httpAwsEs,
      amazonES: {
        region: process.env.AWS_DEFAULT_REGION || 'us-east-1',
        credentials: AWS.config.credentials
      },
      // Note that this doesn't abort the query.
      requestTimeout: 120000  // milliseconds
    }
    client = new elasticsearch.Client(esConfig)
  }

  await new Promise((resolve, reject) => client.ping({requestTimeout: 1000}, (err) => {
    if (err) {
      console.log('unable to connect to elasticsearch')
      reject('unable to connect to elasticsearch')
    } else {
      resolve()
    }
  }))
  return client
}