Convert from PLS response to user response
513296
def unpack_rsp(cls, rsp_pb):
        """"""
        if rsp_pb.retType != RET_OK:
            return RET_ERROR, rsp_pb.retMsg, None

        raw_funds = rsp_pb.s2c.funds
        accinfo_list = [{
            'power': raw_funds.power,
            'total_assets': raw_funds.totalAssets,
            'cash': raw_funds.cash,
            'market_val': raw_funds.marketVal,
            'frozen_cash': raw_funds.frozenCash,
            'avl_withdrawal_cash': raw_funds.avlWithdrawalCash,
        }]
        return RET_OK, "", accinfo_list
278979
def from_response(response, url):
    
    # noinspection PyBroadException
    try:
        data = response.json()
        if not isinstance(data, dict):
            return from_status(
                response.status_code, response.text,
                extra=dict(url=url, response=response.text)
            )

        code = data.get('code', response.status_code)
        if code in HTTP_STATUS_CODES:
            return HTTP_STATUS_CODES[code](**ErrorSchema().load(data))
        else:
            return Error(**ErrorSchema().load(data))
    except Exception:
        return from_status(
            response.status_code, response.text,
            extra=dict(url=url, response=response.text)
        )
114559
def _parse_response(self, resp):
        """"""
        access = resp["access"]
        token = access.get("token")
        self.token = token["id"]
        self.tenant_id = token["tenant"]["id"]
        self.tenant_name = token["tenant"]["name"]
        self.expires = self._parse_api_time(token["expires"])
        self.service_catalog = access.get("serviceCatalog")
        self._parse_service_catalog()
        user = access["user"]
        self.user = {}
        self.user["id"] = user["id"]
        self.username = self.user["name"] = user["name"]
        self.user["roles"] = user["roles"]
886458
def res_to_str(res):
    
    if 'Authorization' in res.request.headers:
        res.request.headers['Authorization'] = "*****"
    return """
####################################
url = %s
headers = %s
-------- data sent -----------------
%s
------------------------------------
@@@@@ response @@@@@@@@@@@@@@@@
headers = %s
code = %d
reason = %s
--------- data received ------------
%s
------------------------------------
####################################
""" % (res.url,
       str(res.request.headers),
       OLD_REQ and res.request.data or res.request.body,
       res.headers,
       res.status_code,
       res.reason,
       res.text)
505456
def convert_response(self):
        
        if hasattr(self.response, 'body_raw'):
            if self.response.body_raw is not None:
                to_type = re.sub('[^a-zA-Z_]', '_', self.type)
                to_type_method = 'to_' + to_type
                if hasattr(self, to_type_method):
                    self.response.body = getattr(self, to_type_method)(
                        self.response.body_raw)
            del self.response.body_raw
672641
def parse_response(object)
      LOG.debug("response is #{object}")
      case object
        when ::Net::HTTPUnauthorized
          ::File.delete(ACCESS_TOKEN)
          raise 'user revoked oauth connection'
        when ::Net::HTTPOK then
          object.body
      end
    end
1041437
def _from_json_array_nested(cls, response_raw):
        

        json = response_raw.body_bytes.decode()
        obj = converter.json_to_class(dict, json)
        value = converter.deserialize(cls, obj[cls._FIELD_RESPONSE])

        return client.BunqResponse(value, response_raw.headers)
599274
def _json_to_subscription_post_response(response_body):
    
    data = json.loads(response_body)
    response_list = []
    for response_data in data.get("responseList", []):
        response_list.append(SubscriptionPostResponse().from_json(
            data.get('uwNetID'), response_data))

    return response_list
821541
def _parse_response(response, clazz, is_list=False, resource_name=None):
        """"""
        target = response.json()[
            resource_name] if resource_name else response.json()
        if is_list:
            return [clazz.from_json(resource) for resource in target]
        else:
            return clazz.from_json(target)
415469
def from_response_data(cls, response_data):
        

        response_json = response_data.json()

        return cls(
            response_data.url,
            response_json["number_of_page_results"],
            response_json["number_of_total_results"],
            response_json["results"],
        )
1214907
def webob_to_django_response(webob_response):
    """"""
    from django.http import HttpResponse
    django_response = HttpResponse(
        webob_response.app_iter,
        content_type=webob_response.content_type,
        status=webob_response.status_code,
    )
    for name, value in webob_response.headerlist:
        django_response[name] = value
    return django_response
1039782
def _makeResponse(self, urllib2_response):
        '''
        
        '''
        resp = HTTPResponse()
        resp.body = urllib2_response.read(MAX_RESPONSE_KB * 1024)
        resp.final_url = urllib2_response.geturl()
        resp.headers = self._lowerCaseKeys(
            dict(list(urllib2_response.info().items())))

        if hasattr(urllib2_response, 'code'):
            resp.status = urllib2_response.code
        else:
            resp.status = 200

        _, extra_dict = self._parseHeaderValue(
            resp.headers.get("content-type", ""))
        # Try to decode the response body to a string, if there's a
        # charset known; fall back to ISO-8859-1 otherwise, since that's
        # what's suggested in HTTP/1.1
        charset = extra_dict.get('charset', 'latin1')
        try:
            resp.body = resp.body.decode(charset)
        except Exception:
            pass

        return resp
414500
def render_to_response(self, obj, **response_kwargs):
        
        return HttpResponse(self.serialize(obj), content_type='application/json', **response_kwargs)
71711
def from_response(cls, response, attrs):
        
        proj = response['Projection']
        hash_key = attrs.get(response['KeySchema'][0]['AttributeName'])
        range_key = None
        if len(response['KeySchema']) > 1:
            range_key = attrs[response['KeySchema'][1]['AttributeName']]
        throughput = Throughput.from_response(
            response['ProvisionedThroughput'])
        index = cls(proj['ProjectionType'], response['IndexName'], hash_key,
                    range_key, proj.get('NonKeyAttributes'), throughput)
        index.response = response
        return index
142466
def _parse_single_response(cls, response_data):
        

        if not isinstance(response_data, dict):
            raise errors.RPCInvalidRequest("No valid RPC-package.")

        if "id" not in response_data:
            raise errors.RPCInvalidRequest("""Invalid Response, "id" missing.""")

        request_id = response_data['id']

        if "jsonrpc" not in response_data:
            raise errors.RPCInvalidRequest("""Invalid Response, "jsonrpc" missing.""", request_id)
        if not isinstance(response_data["jsonrpc"], (str, unicode)):
            raise errors.RPCInvalidRequest("""Invalid Response, "jsonrpc" must be a string.""")
        if response_data["jsonrpc"] != "2.0":
            raise errors.RPCInvalidRequest("""Invalid jsonrpc version.""", request_id)

        error = response_data.get('error', None)
        result = response_data.get('result', None)

        if error and result:
            raise errors.RPCInvalidRequest("""Invalid Response, only "result" OR "error" allowed.""", request_id)

        if error:
            if not isinstance(error, dict):
                raise errors.RPCInvalidRequest("Invalid Response, invalid error-object.", request_id)

            if not ("code" in error and "message" in error):
                raise errors.RPCInvalidRequest("Invalid Response, invalid error-object.", request_id)

            error_data = error.get("data", None)

            if error['code'] in errors.ERROR_CODE_CLASS_MAP:
                raise errors.ERROR_CODE_CLASS_MAP[error['code']](error_data, request_id)
            else:
                error_object = errors.RPCFault(error_data, request_id)
                error_object.error_code = error['code']
                error_object.message = error['message']
                raise error_object

        return result, request_id
261042
def _from_json_list(cls, response_raw, wrapper=None):
        

        json = response_raw.body_bytes.decode()
        obj = converter.json_to_class(dict, json)
        array = obj[cls._FIELD_RESPONSE]
        array_deserialized = []

        for item in array:
            item_unwrapped = item if wrapper is None else item[wrapper]
            item_deserialized = converter.deserialize(cls, item_unwrapped)
            array_deserialized.append(item_deserialized)

        pagination = converter.deserialize(client.Pagination,
                                           obj[cls._FIELD_PAGINATION])

        return client.BunqResponse(array_deserialized, response_raw.headers,
                                   pagination)
205735
def _read_response(self, response):
        
        self.name = response['name']
        self.includesPattern = response['includesPattern']
        self.excludesPattern = response['excludesPattern']
        self._repositories = response.get('repositories', [])
        if 'principals' in response:
            if 'users' in response['principals']:
                self._users = response['principals']['users']
            if 'groups' in response['principals']:
                self._groups = response['principals']['groups']