Handle CONNECT command: Establishes a new connection and checks auth (if applicable).
512230
def connect(self, frame, response=None):
        
        self.engine.log.debug("CONNECT")

        if self.engine.authenticator:
            login = frame.headers.get('login')
            passcode = frame.headers.get('passcode')
            if not self.engine.authenticator.authenticate(login, passcode):
                raise AuthError("Authentication failed for %s" % login)

        self.engine.connected = True

        response = response or Frame(frames.CONNECTED)
        response.headers['session'] = uuid.uuid4()

        # TODO: Do we want to do anything special to track sessions?
        # (Actually, I don't think the spec actually does anything with this at all.)
        self.engine.connection.send_frame(response)
1004917
public function check_connection()
    {
        // Establish connection if it wasn't done yet
        if (!$this->connect_done && !empty($this->options['user'])) {
            return $this->connect(
                $this->options['host'],
                $this->options['user'],
                $this->options['password'],
                $this->options['port'],
                $this->options['ssl']
            );
        }

        return $this->is_connected();
    }
1348435
def _do_connect(self):
        
        self.load_system_host_keys()
        if self.username is None or self.port is None:
            self._configure()
        try:
            self.connect(hostname=self.hostname,
                         port=self.port,
                         username=self.username,
                         key_filename=self.key_filename,
                         sock=self.proxy)
        except socket.error as e:
            raise GerritError("Failed to connect to server: %s" % e)

        try:
            version_string = self._transport.remote_version
            pattern = re.compile(r'^.*GerritCodeReview_([a-z0-9-\.]*) .*$')
            self.remote_version = _extract_version(version_string, pattern)
        except AttributeError:
            self.remote_version = None
714056
function handleConnection(socket) { // server 'connect'
		socket.setEncoding('utf-8')
		socket.on('data', requestResponder)

		function requestResponder(data) {
			socket.end(String(process.pid))
			self.emit('data', data)
		}
	}
157028
def get_connection(self, command_name, *keys, **options):
        ""
        self._checkpid()
        try:
            connection = self._available_connections.pop()
        except IndexError:
            connection = self.make_connection()
        self._in_use_connections.add(connection)
        try:
            # ensure this connection is connected to Redis
            connection.connect()
            # connections that the pool provides should be ready to send
            # a command. if not, the connection was either returned to the
            # pool before all data has been read or the socket has been
            # closed. either way, reconnect and verify everything is good.
            if not connection.is_ready_for_command():
                connection.disconnect()
                connection.connect()
                if not connection.is_ready_for_command():
                    raise ConnectionError('Connection not ready')
        except:  # noqa: E722
            # release the connection back to the pool so that we don't leak it
            self.release(connection)
            raise

        return connection
523323
def connect(self, host, port):
        ''''''
        conn = connection.Connection(host, port,
            reconnection_backoff=self._reconnection_backoff,
            auth_secret=self._auth_secret,
            timeout=self._connect_timeout,
            **self._identify_options)
        if conn.alive():
            conn.setblocking(0)
        self.add(conn)
        return conn
885167
def handle(self, *args, **options):
        
        self.db = options.get("database", DEFAULT_DB_ALIAS)
        self.current_name = connections[self.db].settings_dict["NAME"]
        self.compare_name = options.get("db_name")
        self.lines = options.get("lines")
        self.ignore = int(options.get('ignore'))

        if not self.compare_name:
            self.compare_name = "%s_compare" % self.current_name
        
        command = NASHVEGAS.get("dumpdb", "pg_dump -s {dbname}")
        
        print "Getting schema for current database..."
        current_sql = Popen(
            command.format(dbname=self.current_name),
            shell=True,
            stdout=PIPE
        ).stdout.readlines()
        
        print "Getting schema for fresh database..."
        self.setup_database()
        connections[self.db].close()
        connections[self.db].settings_dict["NAME"] = self.compare_name
        try:
            call_command("syncdb", interactive=False, verbosity=0, migrations=False)
            new_sql = Popen(
                command.format(dbname=self.compare_name).split(),
                stdout=PIPE
            ).stdout.readlines()
        finally:
            connections[self.db].close()
            connections[self.db].settings_dict["NAME"] = self.current_name
            self.teardown_database()
        
        print "Outputing diff between the two..."
        print "".join(difflib.unified_diff(normalize_sql(current_sql, self.ignore),
                                           normalize_sql(new_sql, self.ignore),
                                           n=int(self.lines)))
398422
def connect(self, user=None):
        

        self.api._tcl_handler.connect()
        if user:
            self.session.login(user)
116224
async def connect(self):
        
        await self._sender.connect(self._connection(
            self.session.server_address,
            self.session.port,
            self.session.dc_id,
            loop=self._loop,
            loggers=self._log,
            proxy=self._proxy
        ))
        self.session.auth_key = self._sender.auth_key
        self.session.save()

        await self._sender.send(self._init_with(
            functions.help.GetConfigRequest()))

        self._updates_handle = self._loop.create_task(self._update_loop())
305575
async def handle_command(bot: NoneBot, ctx: Context_T) -> bool:
    
    cmd, current_arg = parse_command(bot, str(ctx['message']).lstrip())
    is_privileged_cmd = cmd and cmd.privileged
    if is_privileged_cmd and cmd.only_to_me and not ctx['to_me']:
        is_privileged_cmd = False
    disable_interaction = is_privileged_cmd

    if is_privileged_cmd:
        logger.debug(f'Command {cmd.name} is a privileged command')

    ctx_id = context_id(ctx)

    if not is_privileged_cmd:
        # wait for 1.5 seconds (at most) if the current session is running
        retry = 5
        while retry > 0 and \
                _sessions.get(ctx_id) and _sessions[ctx_id].running:
            retry -= 1
            await asyncio.sleep(0.3)

    check_perm = True
    session = _sessions.get(ctx_id) if not is_privileged_cmd else None
    if session:
        if session.running:
            logger.warning(f'There is a session of command '
                           f'{session.cmd.name} running, notify the user')
            asyncio.ensure_future(send(
                bot, ctx,
                render_expression(bot.config.SESSION_RUNNING_EXPRESSION)
            ))
            # pretend we are successful, so that NLP won't handle it
            return True

        if session.is_valid:
            logger.debug(f'Session of command {session.cmd.name} exists')
            # since it's in a session, the user must be talking to me
            ctx['to_me'] = True
            session.refresh(ctx, current_arg=str(ctx['message']))
            # there is no need to check permission for existing session
            check_perm = False
        else:
            # the session is expired, remove it
            logger.debug(f'Session of command {session.cmd.name} is expired')
            if ctx_id in _sessions:
                del _sessions[ctx_id]
            session = None

    if not session:
        if not cmd:
            logger.debug('Not a known command, ignored')
            return False
        if cmd.only_to_me and not ctx['to_me']:
            logger.debug('Not to me, ignored')
            return False
        session = CommandSession(bot, ctx, cmd, current_arg=current_arg)
        logger.debug(f'New session of command {session.cmd.name} created')

    return await _real_run_command(session, ctx_id, check_perm=check_perm,
                                   disable_interaction=disable_interaction)
114280
async def immediate_execute_command(self, *args, **options):
        
        command_name = args[0]
        conn = self.connection
        # if this is the first call, we need a connection
        if not conn:
            conn = self.connection_pool.get_connection()
            self.connection = conn
        try:
            await conn.send_command(*args)
            return await self.parse_response(conn, command_name, **options)
        except (ConnectionError, TimeoutError) as e:
            conn.disconnect()
            if not conn.retry_on_timeout and isinstance(e, TimeoutError):
                raise
            # if we're not already watching, we can safely retry the command
            try:
                if not self.watching:
                    await conn.send_command(*args)
                    return await self.parse_response(conn, command_name, **options)
            except ConnectionError:
                # the retry failed so cleanup.
                conn.disconnect()
                await self.reset()
                raise
1198483
function handleDisconnect() {
    _connection = _mysql.createConnection(_dbConfig);

    _connection.connect(function (err) {
        if (err) {
            console.log('error when connecting to db:', err);
            setTimeout(handleDisconnect, 2000);
        }
    });

    _connection.on('error', function (err) {
        console.log('db error', err);
        if (err.code === 'PROTOCOL_CONNECTION_LOST') {
            handleDisconnect();
        } else {
            throw err;
        }
    });
}
674053
def connect(self, username=None, passcode=None, wait=False, headers=None, **keyword_headers):
        
        self.transport.start()
857376
private function connect () {
    $connectionString = "host=".$this->server." port=".$this->port." dbname=".$this->db." user=".$this->user." password=".$this->password;
    $this->handler = pg_connect ($connectionString);
  }
624188
def connectionMade(self):
        
        cmd = stomper.connect(self.username, self.password)
        self.transport.write(cmd)
235892
private boolean executeConnect() 
        throws IOException, HttpException {

        this.connectMethod = new ConnectMethod(this.hostConfiguration);
        this.connectMethod.getParams().setDefaults(this.hostConfiguration.getParams());
        String agent = (String) getParams().getParameter(PARAM_DEFAULT_USER_AGENT_CONNECT_REQUESTS);
        if (agent != null) {
            this.connectMethod.setRequestHeader("User-Agent", agent);
        }
        
        int code;
        for (;;) {
            if (!this.conn.isOpen()) {
                this.conn.open();
            }
            if (this.params.isAuthenticationPreemptive()
                    || this.state.isAuthenticationPreemptive()) {
                LOG.debug("Preemptively sending default basic credentials");
                this.connectMethod.getProxyAuthState().setPreemptive();
                this.connectMethod.getProxyAuthState().setAuthAttempted(true);
            }
            try {
                authenticateProxy(this.connectMethod);
            } catch (AuthenticationException e) {
                LOG.error(e.getMessage(), e);
            }
            applyConnectionParams(this.connectMethod);                    
            this.connectMethod.execute(state, this.conn);
            code = this.connectMethod.getStatusCode();
            boolean retry = false;
            AuthState authstate = this.connectMethod.getProxyAuthState(); 
            authstate.setAuthRequested(code == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED);
            if (authstate.isAuthRequested()) {
                if (processAuthenticationResponse(this.connectMethod)) {
                    retry = true;
                }
            }
            if (!retry) {
                break;
            }
            if (this.connectMethod.getResponseBodyAsStream() != null) {
                this.connectMethod.getResponseBodyAsStream().close();
            }
        }
        if ((code >= 200) && (code < 300)) {
            this.conn.tunnelCreated();
            // Drop the connect method, as it is no longer needed
            this.connectMethod = null;
            return true;
        } else {
            return false;
        }
    }
282380
public void connect() {
        doConnect(() -> {
            return CommandContextFactory.getInstance().
                    newCommandContext(new CommandContextConfiguration.Builder()
                    .setErrorOnInteract(false)
                    .build());
        });
    }