Client connected to the server

        :param client: Connected Paho client
        :param userdata: User data (unused)
        :param flags: Response flags sent by the broker
        :param result_code: Connection result code (0: success, others: error)
427589
def __on_connect(self, client, userdata, flags, result_code):
        # pylint: disable=W0613
        
        if result_code:
            # result_code != 0: something wrong happened
            _logger.error(
                "Error connecting the MQTT server: %s (%d)",
                paho.connack_string(result_code),
                result_code,
            )
        else:
            # Connection is OK: stop the reconnection timer
            self.__stop_timer()

        # Notify the caller, if any
        if self.on_connect is not None:
            try:
                self.on_connect(self, result_code)
            except Exception as ex:
                _logger.exception("Error notifying MQTT listener: %s", ex)
1315014
def hello_user(api_client):
    

    try:
        response = api_client.get_user_profile()

    except (ClientError, ServerError) as error:
        fail_print(error)
        return

    else:
        profile = response.json
        user_id = profile.get('id')
        message = 'Hello. Successfully granted access token to User ID {}.'.format(user_id)
        success_print(message)
1330163
def who(self, *args):
        """"""
        if len(self._users) == 0:
            self.log('No users connected')
            if len(self._clients) == 0:
                self.log('No clients connected')
                return

        Row = namedtuple("Row", ['User', 'Client', 'IP'])
        rows = []

        for user in self._users.values():
            for key, client in self._clients.items():
                if client.useruuid == user.uuid:
                    row = Row(user.account.name, key, client.ip)
                    rows.append(row)

        for key, client in self._clients.items():
            if client.useruuid is None:
                row = Row('ANON', key, client.ip)
                rows.append(row)

        self.log("\n" + std_table(rows))
572170
def add_client(self, user_id=None):
        
        if user_id is None:
            # generate a random uuid if it's an unauthenticated client
            self.channel = 'public'
            user_id = uuid.uuid1().hex
        else:
            self.channel = 'private'
        
        self.id = user_id
        self.channels[self.channel][self.id] = self
        print 'Client connected to the %s channel.' % self.channel
604238
def _client_data(self, client):
        
        data = {}
        if client:
            data['obj'] = client
            data['id'] = client.id
            data['url'] = client.absolute_url()
            data['name'] = to_utf8(client.getName())
        return data
736044
def watch(
        self,
        username,
        watch={
            "friend":True,
            "deviations":True,
            "journals":True,
            "forum_threads":True,
            "critiques":True,
            "scraps":True,
            "activity":True,
            "collections":True
        }
    ):

        

        if self.standard_grant_type is not "authorization_code":
            raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.")

        response = self._req('/user/friends/watch/{}'.format(username), post_data={
            "watch[friend]": watch['friend'],
            "watch[deviations]": watch['deviations'],
            "watch[journals]": watch['journals'],
            "watch[forum_threads]": watch['forum_threads'],
            "watch[critiques]": watch['critiques'],
            "watch[scraps]": watch['scraps'],
            "watch[activity]": watch['activity'],
            "watch[collections]": watch['collections'],
        })

        return response['success']
816031
def get_user_id_by_user(self, username):
        '''  '''
        response, status_code = self.__pod__.Users.get_v2_user(
            sessionToken=self.__session__,
            username=username
        ).result()
        self.logger.debug('%s: %s' % (status_code, response))
        return status_code, response
564633
def _get_client(self, server):
        
        return Client(
            server=server[0],
            authport=server[1],
            secret=server[2],
            dict=self._get_dictionary(),
        )
1060986
def hello_user(api_client):
    

    try:
        response = api_client.get_driver_profile()

    except (ClientError, ServerError) as error:
        fail_print(error)
        return

    else:
        profile = response.json
        first_name = profile.get('first_name')
        last_name = profile.get('last_name')
        email = profile.get('email')
        message = 'Hello, {} {}. Successfully granted access token to {}.'
        message = message.format(first_name, last_name, email)
        success_print(message)
        success_print(profile)

        success_print('---')
        response = api_client.get_driver_trips()
        trips = response.json
        success_print(trips)

        success_print('---')
        response = api_client.get_driver_payments()
        payments = response.json
        success_print(payments)
855028
function runClient(client) {
  var ws = client.ws;

  function invalidMessage() {
    var message = SyncMessage.error.format;
    message.content = {error: 'Unable to parse/handle message, invalid message format.'};
    client.sendMessage(message);
  }

  ws.onmessage = function(msg, flags) {
    var data;
    var message;
    var info;

    if(!flags || !flags.binary) {
      try {
        // Keep track of how much data we receive
        info = client.info();
        if(info) {
          info.bytesReceived += Buffer.byteLength(msg.data, 'utf8');
        }

        data = JSON.parse(msg.data);
        message = SyncMessage.parse(data);
      } catch(error) {
        log.error({client: client, err: error}, 'Unable to parse/handle client message. Data was `%s`', msg.data);
        return invalidMessage();
      }

      // Delegate ws messages to the sync protocol handler at this point
      client.handler.handleMessage(message);
    } else {
      log.warn({client: client}, 'Expected string but got binary data over web socket.');
      invalidMessage();
    }
  };

  // Send an AUTHZ response to let client know normal sync'ing can begin.
  client.state = States.LISTENING;
  client.sendMessage(SyncMessage.response.authz);
  log.debug({client: client}, 'Starting authorized client session');
}
1347730
def _send_user_message(self, data):
        
        start = time.time()
        while True:
            self.clear_to_send.wait(0.1)
            if not self.active:
                self._log(DEBUG, 'Dropping user packet because connection is dead.')
                return
            self.clear_to_send_lock.acquire()
            if self.clear_to_send.isSet():
                break
            self.clear_to_send_lock.release()
            if time.time() > start + self.clear_to_send_timeout:
              raise SSHException('Key-exchange timed out waiting for key negotiation')
        try:
            self._send_message(data)
        finally:
            self.clear_to_send_lock.release()
800778
def run

      @client = JsonApiClient.new(uri)
      @client.log = log
      @client.header = header
      @client.param = parameters
      if param[:concurrency]
       @client.concurrency = param[:concurrency].to_i
      end

      if param[:slice]
       @client.slice = param[:slice].to_i
      end

      if uri =~ /\w+[:]\w+[@]/
        username, password = URI.parse(uri).userinfo.split(":")
        @client.username = username
        @client.password = password
      end
      
      if param[:auth]
        # Force authorization
        @client.authorization = true
      end

      method = param[:method].upcase

      response = nil

      case method
        when "DELETE"
          response = delete
        when "GET"
          response = get
        when "HEAD"
          response = head
        when "PATCH"
          response = patch
        when "POST"
          if data.is_a? Dir
            raise "Not implemented"
          else
            response = post(data)
          end
          
          
          
        when "PUT"
          response = put(data)
        else
          raise ArgumentError, "Unsupported HTTP method: #{param[:method]}"
      end

      #Loop dirs?
      if not response.nil? and (response.respond_to? :body or response.is_a? Array)
        if response.is_a? Array
          responses = response
        else
          responses = [response]
        end

        i = 0
        responses.each do | response |
          i += 1
          log.debug "#{method} #{response.uri.path} [#{i}] Total time: #{response.total_time}"+
            " DNS time: #{response.namelookup_time}"+
            " Connect time: #{response.connect_time}"+
            " Pre-transer time: #{response.pretransfer_time}"
            
          if "HEAD" == method or headers?
            puts response.response_headers
          end
          unless param[:join]
            puts response.body
          end
        end
        
        statuses = responses.map {|r| r.code }.uniq
        status = statuses.map {|code| { code => responses.select {|r| code == r.code }.size } }.to_json.gsub(/["{}\[\]]/, "")
        real_responses_size = responses.select {|r| r.code >= 100 }.size

        log.info "Status(es): #{status}, request(s): #{responses.size}, response(s): #{real_responses_size}"

      else
        raise "Invalid response: #{response}"
      end
      
      if param[:join]
        joined = responses.map {|r|
          JSON.parse(r.body)
        }
        puts joined.to_json
      end

    end
895376
def process(self, message, user):
        
        if not self._socket:
            self.connect()
            self.lhlo()
        else:
            self.rset()

        if not self.dlmtp:
            raise DspamClientError('DLMTP mode not available')

        self.mailfrom(client_args='--process --deliver=summary')
        self.rcptto((user,))
        self.data(message)

        # check for valid result format
        if 'class' not in self.results[user]:
            raise DspamClientError(
                'Unexpected response format from server at END-OF-DATA, '
                'an error occured')

        return self.results[user]
630140
def clientConnected(self, proto):
        
        proto.uniqueName = ':1.%d' % (self.next_id,)
        self.next_id += 1
        self.clients[proto.uniqueName] = proto
1056485
def process(self, request, response, environ):
        
        token_data = self.create_token(
            client_id=self.client.identifier,
            data=self.data,
            grant_type=AuthorizationCodeGrant.grant_type,
            scopes=self.scopes,
            user_id=self.user_id)

        self.auth_code_store.delete_code(self.code)

        if self.scopes:
            token_data["scope"] = encode_scopes(self.scopes)

        json_success_response(data=token_data, response=response)

        return response
339553
function initClient(client) {
  var ws = client.ws;

  client.state = States.CONNECTING;

  // Wait until we get the user's token so we can finish authorizing
  ws.onmessage = function(msg) {
    var data;
    var info;

    try {
      // Keep track of how much data we receive
      info = client.info();
      if(info) {
        info.bytesReceived += Buffer.byteLength(msg.data, 'utf8');
      }

      data = JSON.parse(msg.data);
    } catch(err) {
      log.error({client: client, err: err}, 'Error parsing client token. Data was `%s`', msg.data);
      ClientInfo.remove(token);
      client.close({
        code: 1011,
        message: 'Error: token could not be parsed.'
      });
      return;
    }

    // Authorize user
    var token = data.token;
    var username = WebsocketAuth.getAuthorizedUsername(token);
    if (!username) {
      log.warn({client: client}, 'Client sent an invalid or expired token (could not get username): token=%s', token);
      ClientInfo.remove(token);
      client.close({
        code: 1008,
        message: 'Error: invalid token.'
      });
      return;
    }

    // Update client details now that he/she is authenticated
    client.id = token;
    client.username = username;
    client.fs = filesystem.create(username);
    ClientInfo.update(client);

    log.info({client: client}, 'Client connected');

    runClient(client);
  };
}
831410
def _get_data(self, func):
        
        def wrapper(*args, **kwargs):
            timeout = kwargs.pop('timeout', None)

            uri, params, method, body, headers, singleobject = func(*args, **kwargs)

            if headers is None:
                headers = {}

            # Use the JSON API by default, but remember we might request a PDF (application/pdf)
            # so don't force the Accept header.
            if 'Accept' not in headers:
                headers['Accept'] = 'application/json'

            # Set a user-agent so Xero knows the traffic is coming from pyxero
            # or individual user/partner
            headers['User-Agent'] = self.user_agent

            response = getattr(requests, method)(
                    uri, data=body, headers=headers, auth=self.credentials.oauth,
                    params=params, timeout=timeout)

            if response.status_code == 200:
                # If we haven't got XML or JSON, assume we're being returned a binary file
                if not response.headers['content-type'].startswith('application/json'):
                    return response.content

                return self._parse_api_response(response, self.name)

            elif response.status_code == 204:
                return response.content

            elif response.status_code == 400:
                raise XeroBadRequest(response)

            elif response.status_code == 401:
                raise XeroUnauthorized(response)

            elif response.status_code == 403:
                raise XeroForbidden(response)

            elif response.status_code == 404:
                raise XeroNotFound(response)

            elif response.status_code == 500:
                raise XeroInternalError(response)

            elif response.status_code == 501:
                raise XeroNotImplemented(response)

            elif response.status_code == 503:
                # Two 503 responses are possible. Rate limit errors
                # return encoded content; offline errors don't.
                # If you parse the response text and there's nothing
                # encoded, it must be a not-available error.
                payload = parse_qs(response.text)
                if payload:
                    raise XeroRateLimitExceeded(response, payload)
                else:
                    raise XeroNotAvailable(response)
            else:
                raise XeroExceptionUnknown(response)

        return wrapper