Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:async def async_send(self, request, **kwargs): kwargs.setdefault('stream', True) # In the current backward compatible implementation, return the HTTP response # and plug context inside. Could be remove if we modify Autorest, # but we ...
[ "Prepare and send request object according to configuration.\n\n :param ClientRequest request: The request object to be sent.\n :param dict headers: Any headers to add to the request.\n :param content: Any body data to add to the request.\n :param config: Any specific config overrides\n ...
Please provide a description of the function:async def send(self, request: ClientRequest, **config: Any) -> AsyncClientResponse: result = await self._session.request( request.method, request.url, **config ) response = AioHttpClientResponse(request, re...
[ "Send the request using this HTTP sender.\n\n Will pre-load the body into memory to be available with a sync method.\n pass stream=True to avoid this behavior.\n " ]
Please provide a description of the function:def stream_download(self, chunk_size: Optional[int] = None, callback: Optional[Callable] = None) -> AsyncIterator[bytes]: chunk_size = chunk_size or CONTENT_CHUNK_SIZE async def async_gen(resp): while True: chunk = await r...
[ "Generator for streaming request body data.\n " ]
Please provide a description of the function:def deserialize_from_text(cls, data, content_type=None): # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any if hasattr(data, 'read'): # Assume a stream data = cast(IO, data).read() if isinstance(data, bytes):...
[ "Decode data according to content-type.\n\n Accept a stream of data as well, but will be load at once in memory for now.\n\n If no content-type, will return the string version (not bytes, not stream)\n\n :param data: Input, could be bytes or stream (will be decoded with UTF8) or text\n :...
Please provide a description of the function:def deserialize_from_http_generics(cls, body_bytes, headers): # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any # Try to use content-type from headers if available content_type = None if 'content-type' in headers: cont...
[ "Deserialize from HTTP response.\n\n Use bytes and headers to NOT use any requests/aiohttp or whatever\n specific implementation.\n Headers will tested for \"content-type\"\n " ]
Please provide a description of the function:def on_response(self, request, response, **kwargs): # type: (Request, Response, Any) -> None # If response was asked as stream, do NOT read anything and quit now if kwargs.get("stream", True): return http_response = respo...
[ "Extract data from the body of a REST response object.\n\n This will load the entire payload in memory.\n\n Will follow Content-Type to parse.\n We assume everything is UTF8 (BOM acceptable).\n\n :param raw_data: Data to be processed.\n :param content_type: How to parse if raw_dat...
Please provide a description of the function:async def send(self, request: Request, **config: Any) -> Response: return Response( request, await self.driver.send(request.http_request) )
[ "Send the request using this HTTP sender.\n " ]
Please provide a description of the function:def add_headers(self, header_dict): # type: (Dict[str, str]) -> None if not self.response: return for name, data_type in header_dict.items(): value = self.response.headers.get(name) value = self._deserializ...
[ "Deserialize a specific header.\n\n :param dict header_dict: A dictionary containing the name of the\n header and the type to deserialize to.\n " ]
Please provide a description of the function:async def send(self, request: ClientRequest, **kwargs: Any) -> AsyncClientResponse: # type: ignore # It's not recommended to provide its own session, and is mostly # to enable some legacy code to plug correctly session = kwargs.pop('session'...
[ "Send the request using this HTTP sender.\n " ]
Please provide a description of the function:async def send(self, request: ClientRequest, **kwargs: Any) -> AsyncClientResponse: # type: ignore requests_kwargs = self._configure_send(request, **kwargs) return await super(AsyncRequestsHTTPSender, self).send(request, **requests_kwargs)
[ "Send the request using this HTTP sender.\n " ]
Please provide a description of the function:def stream_download(self, chunk_size: Optional[int] = None, callback: Optional[Callable] = None) -> AsyncIteratorType[bytes]: return StreamDownloadGenerator( self.internal_response, callback, chunk_size )
[ "Generator for streaming request body data.\n\n :param callback: Custom callback for monitoring progress.\n :param int chunk_size:\n " ]
Please provide a description of the function:async def async_get(self, url): self.reset() self.next_link = url return await self.async_advance_page()
[ "Get an arbitrary page.\n\n This resets the iterator and then fully consumes it to return the\n specific page **only**.\n\n :param str url: URL to arbitrary page results.\n " ]
Please provide a description of the function:def _start(self): try: self._polling_method.run() except Exception as err: self._exception = err finally: self._done.set() callbacks, self._callbacks = self._callbacks, [] while callbacks:...
[ "Start the long running operation.\n On completion, runs any callbacks.\n\n :param callable update_cmd: The API reuqest to check the status of\n the operation.\n " ]
Please provide a description of the function:def wait(self, timeout=None): # type: (Optional[int]) -> None if self._thread is None: return self._thread.join(timeout=timeout) try: # Let's handle possible None in forgiveness here raise self._exc...
[ "Wait on the long running operation for a specified length\n of time. You can check if this call as ended with timeout with the\n \"done()\" method.\n\n :param int timeout: Period of time to wait for the long running\n operation to complete (in seconds).\n :raises CloudError: Ser...
Please provide a description of the function:def add_done_callback(self, func): # type: (Callable) -> None # Still use "_done" and not "done", since CBs are executed inside the thread. if self._done is None or self._done.is_set(): func(self._polling_method) # Let's a...
[ "Add callback function to be run once the long running operation\n has completed - regardless of the status of the operation.\n\n :param callable func: Callback function that takes at least one\n argument, a completed LongRunningOperation.\n " ]
Please provide a description of the function:def log_request(_, request, *_args, **_kwargs): # type: (Any, ClientRequest, str, str) -> None if not _LOGGER.isEnabledFor(logging.DEBUG): return try: _LOGGER.debug("Request URL: %r", request.url) _LOGGER.debug("Request method: %r", ...
[ "Log a client request.\n\n :param _: Unused in current version (will be None)\n :param requests.Request request: The request object.\n " ]
Please provide a description of the function:def log_response(_, _request, response, *_args, **kwargs): # type: (Any, ClientRequest, ClientResponse, str, Any) -> Optional[ClientResponse] if not _LOGGER.isEnabledFor(logging.DEBUG): return None try: _LOGGER.debug("Response status: %r", r...
[ "Log a server response.\n\n :param _: Unused in current version (will be None)\n :param requests.Request request: The request object.\n :param requests.Response response: The response object.\n " ]
Please provide a description of the function:def _clear_config(self): # type: () -> None for section in self._config.sections(): self._config.remove_section(section)
[ "Clearout config object in memory." ]
Please provide a description of the function:def save(self, filepath): # type: (str) -> None sections = [ "Connection", "Proxies", "RedirectPolicy"] for section in sections: self._config.add_section(section) self._config.set("Conn...
[ "Save current configuration to file.\n\n :param str filepath: Path to file where settings will be saved.\n :raises: ValueError if supplied filepath cannot be written to.\n " ]
Please provide a description of the function:def load(self, filepath): # type: (str) -> None try: self._config.read(filepath) import ast self.connection.timeout = \ self._config.getint("Connection", "timeout") self.connection.verif...
[ "Load configuration from existing file.\n\n :param str filepath: Path to existing config file.\n :raises: ValueError if supplied config file is invalid.\n " ]
Please provide a description of the function:def format_parameters(self, params): # type: (Dict[str, str]) -> None query = urlparse(self.url).query if query: self.url = self.url.partition('?')[0] existing_params = { p[0]: p[-1] for...
[ "Format parameters into a valid query string.\n It's assumed all parameters have already been quoted as\n valid URL strings.\n\n :param dict params: A dictionary of parameters.\n " ]
Please provide a description of the function:def add_content(self, data): # type: (Optional[Union[Dict[str, Any], ET.Element]]) -> None if data is None: return if isinstance(data, ET.Element): bytes_data = ET.tostring(data, encoding="utf8") self.head...
[ "Add a body to the request.\n\n :param data: Request body data, can be a json serializable\n object (e.g. dictionary) or a generator (e.g. file data).\n " ]
Please provide a description of the function:def _format_data(data): # type: (Union[str, IO]) -> Union[Tuple[None, str], Tuple[Optional[str], IO, str]] if hasattr(data, 'read'): data = cast(IO, data) data_name = None try: if data.name[0] != '<...
[ "Format field data according to whether it is a stream or\n a string for a form-data request.\n\n :param data: The request field data.\n :type data: str or file-like object.\n " ]
Please provide a description of the function:def add_formdata(self, content=None): # type: (Optional[Dict[str, str]]) -> None if content is None: content = {} content_type = self.headers.pop('Content-Type', None) if self.headers else None if content_type and content...
[ "Add data as a multipart form-data request to the request.\n\n We only deal with file-like objects or strings at this point.\n The requests is not yet streamed.\n\n :param dict headers: Any headers to add to the request.\n :param dict content: Dictionary of the fields of the formdata.\n ...
Please provide a description of the function:def raise_with_traceback(exception, message="", *args, **kwargs): # type: (Callable, str, Any, Any) -> None exc_type, exc_value, exc_traceback = sys.exc_info() # If not called inside a "except", exc_type will be None. Assume it will not happen exc_msg = ...
[ "Raise exception with a specified traceback.\n\n This MUST be called inside a \"except\" clause.\n\n :param Exception exception: Error type to be raised.\n :param str message: Message to include with error, empty by default.\n :param args: Any additional args to be included with exception.\n " ]
Please provide a description of the function:def stream_download(self, chunk_size: Optional[int] = None, callback: Optional[Callable] = None) -> AsyncIterator[bytes]: pass
[ "Generator for streaming request body data.\n\n Should be implemented by sub-classes if streaming download\n is supported.\n\n :param callback: Custom callback for monitoring progress.\n :param int chunk_size:\n " ]
Please provide a description of the function:def _patch_redirect(session): # type: (requests.Session) -> None def enforce_http_spec(resp, request): if resp.status_code in (301, 302) and \ request.method not in ['GET', 'HEAD']: return False return True redire...
[ "Whether redirect policy should be applied based on status code.\n\n HTTP spec says that on 301/302 not HEAD/GET, should NOT redirect.\n But requests does, to follow browser more than spec\n https://github.com/requests/requests/blob/f6e13ccfc4b50dc458ee374e5dba347205b9a2da/requests/sessions.py#L305-L314\n\...
Please provide a description of the function:def stream_download(self, chunk_size=None, callback=None): # type: (Optional[int], Optional[Callable]) -> Iterator[bytes] chunk_size = chunk_size or CONTENT_CHUNK_SIZE with contextlib.closing(self.internal_response) as response: #...
[ "Generator for streaming request body data.\n\n :param callback: Custom callback for monitoring progress.\n :param int chunk_size:\n " ]
Please provide a description of the function:def send(self, request, **kwargs): # type: (ClientRequest, Any) -> ClientResponse # It's not recommended to provide its own session, and is mostly # to enable some legacy code to plug correctly session = kwargs.pop('session', self.ses...
[ "Send request object according to configuration.\n\n Allowed kwargs are:\n - session : will override the driver session and use yours. Should NOT be done unless really required.\n - anything else is sent straight to requests.\n\n :param ClientRequest request: The request object to be sen...
Please provide a description of the function:def _init_session(self, session): # type: (requests.Session) -> None _patch_redirect(session) # Change max_retries in current all installed adapters max_retries = self.config.retry_policy() for protocol in self._protocols: ...
[ "Init session level configuration of requests.\n\n This is initialization I want to do once only on a session.\n " ]
Please provide a description of the function:def _configure_send(self, request, **kwargs): # type: (ClientRequest, Any) -> Dict[str, str] requests_kwargs = {} # type: Any session = kwargs.pop('session', self.session) # If custom session was not create here if session i...
[ "Configure the kwargs to use with requests.\n\n See \"send\" for kwargs details.\n\n :param ClientRequest request: The request object to be sent.\n :returns: The requests.Session.request kwargs\n :rtype: dict[str,str]\n " ]
Please provide a description of the function:def send(self, request, **kwargs): # type: (ClientRequest, Any) -> ClientResponse requests_kwargs = self._configure_send(request, **kwargs) return super(RequestsHTTPSender, self).send(request, **requests_kwargs)
[ "Send request object according to configuration.\n\n Available kwargs:\n - session : will override the driver session and use yours. Should NOT be done unless really required.\n - A subset of what requests.Session.request can receive:\n\n - cookies\n - verify\n ...
Please provide a description of the function:def save(self, filepath): self._config.add_section("RetryPolicy") self._config.set("RetryPolicy", "retries", str(self.retry_policy.retries)) self._config.set("RetryPolicy", "backoff_factor", str(self.retry_policy.back...
[ "Save current configuration to file.\n\n :param str filepath: Path to file where settings will be saved.\n :raises: ValueError if supplied filepath cannot be written to.\n " ]
Please provide a description of the function:def full_restapi_key_transformer(key, attr_desc, value): keys = _FLATTEN.split(attr_desc['key']) return ([_decode_attribute_map_key(k) for k in keys], value)
[ "A key transformer that returns the full RestAPI key path.\n\n :param str _: The attribute name\n :param dict attr_desc: The attribute metadata\n :param object value: The value\n :returns: A list of keys using RestAPI syntax.\n " ]
Please provide a description of the function:def last_restapi_key_transformer(key, attr_desc, value): key, value = full_restapi_key_transformer(key, attr_desc, value) return (key[-1], value)
[ "A key transformer that returns the last RestAPI key.\n\n :param str key: The attribute name\n :param dict attr_desc: The attribute metadata\n :param object value: The value\n :returns: The last RestAPI key.\n " ]
Please provide a description of the function:def _create_xml_node(tag, prefix=None, ns=None): if prefix and ns: ET.register_namespace(prefix, ns) if ns: return ET.Element("{"+ns+"}"+tag) else: return ET.Element(tag)
[ "Create a XML node." ]
Please provide a description of the function:def _create_xml_node(cls): try: xml_map = cls._xml_map except AttributeError: raise ValueError("This model has no XML definition") return _create_xml_node( xml_map.get('name', cls.__name__), xm...
[ "Create XML node from \"_xml_map\".\n " ]
Please provide a description of the function:def validate(self): validation_result = [] for attr_name, value in [(attr, getattr(self, attr)) for attr in self._attribute_map]: attr_desc = self._attribute_map[attr_name] if attr_name == "additional_properties" and attr_desc...
[ "Validate this model recursively and return a list of ValidationError.\n\n :returns: A list of validation error\n :rtype: list\n " ]
Please provide a description of the function:def serialize(self, keep_readonly=False): serializer = Serializer(self._infer_class_models()) return serializer._serialize(self, keep_readonly=keep_readonly)
[ "Return the JSON that would be sent to azure from this model.\n\n This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`.\n\n :param bool keep_readonly: If you want to serialize the readonly attributes\n :returns: A dict JSON compatible object\n :rtype: dict\n ...
Please provide a description of the function:def as_dict(self, keep_readonly=True, key_transformer=attribute_transformer): serializer = Serializer(self._infer_class_models()) return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly)
[ "Return a dict that can be JSONify using json.dump.\n\n Advanced usage might optionaly use a callback as parameter:\n\n .. code::python\n\n def my_key_transformer(key, attr_desc, value):\n return key\n\n Key is the attribute name used in Python. Attr_desc\n is a...
Please provide a description of the function:def deserialize(cls, data, content_type=None): deserializer = Deserializer(cls._infer_class_models()) return deserializer(cls.__name__, data, content_type=content_type)
[ "Parse a str using the RestAPI syntax and return a model.\n\n :param str data: A str using RestAPI structure. JSON by default.\n :param str content_type: JSON by default, set application/xml if XML.\n :returns: An instance of this model\n :raises: DeserializationError if something went w...
Please provide a description of the function:def from_dict(cls, data, key_extractors=None, content_type=None): deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = [ rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extra...
[ "Parse a dict using given key extractor return a model.\n\n By default consider key\n extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor\n and last_rest_key_case_insensitive_extractor)\n\n :param dict data: A dict using RestAPI structure\n :p...
Please provide a description of the function:def _classify(cls, response, objects): for subtype_key in cls.__dict__.get('_subtype_map', {}).keys(): subtype_value = None rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] subtype_value = response.pop(res...
[ "Check the class _subtype_map for any child classes.\n We want to ignore any inherited _subtype_maps.\n Remove the polymorphic key from the initial data.\n " ]
Please provide a description of the function:def _get_rest_key_parts(cls, attr_key): rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]['key']) return [_decode_attribute_map_key(key_part) for key_part in rest_split_key]
[ "Get the RestAPI key of this attr, split it and decode part\n :param str attr_key: Attribute key must be in attribute_map.\n :returns: A list of RestAPI part\n :rtype: list\n " ]
Please provide a description of the function:def _serialize(self, target_obj, data_type=None, **kwargs): key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) if target_obj is None: return None attr_...
[ "Serialize data into a string according to type.\n\n :param target_obj: The data to be serialized.\n :param str data_type: The type to be serialized from.\n :rtype: str, dict\n :raises: SerializationError if serialization fails.\n " ]
Please provide a description of the function:def body(self, data, data_type, **kwargs): if data is None: raise ValidationError("required", "body", True) # Just in case this is a dict internal_data_type = data_type.strip('[]{}') internal_data_type = self.dependencies...
[ "Serialize data intended for a request body.\n\n :param data: The data to be serialized.\n :param str data_type: The type to be serialized from.\n :rtype: dict\n :raises: SerializationError if serialization fails.\n :raises: ValueError if data is None\n " ]
Please provide a description of the function:def url(self, name, data, data_type, **kwargs): if self.client_side_validation: data = self.validate(data, name, required=True, **kwargs) try: output = self.serialize_data(data, data_type, **kwargs) if data_type ==...
[ "Serialize data intended for a URL path.\n\n :param data: The data to be serialized.\n :param str data_type: The type to be serialized from.\n :rtype: str\n :raises: TypeError if serialization fails.\n :raises: ValueError if data is None\n " ]
Please provide a description of the function:def header(self, name, data, data_type, **kwargs): if self.client_side_validation: data = self.validate(data, name, required=True, **kwargs) try: if data_type in ['[str]']: data = ["" if d is None else d for d ...
[ "Serialize data intended for a request header.\n\n :param data: The data to be serialized.\n :param str data_type: The type to be serialized from.\n :rtype: str\n :raises: TypeError if serialization fails.\n :raises: ValueError if data is None\n " ]
Please provide a description of the function:def validate(cls, data, name, **kwargs): required = kwargs.get('required', False) if required and data is None: raise ValidationError("required", name, True) elif data is None: return elif kwargs.get('readonly'...
[ "Validate that a piece of data meets certain conditions" ]
Please provide a description of the function:def serialize_data(self, data, data_type, **kwargs): if data is None: raise ValueError("No value for given attribute") try: if data_type in self.basic_types.values(): return self.serialize_basic(data, data_typ...
[ "Serialize generic data according to supplied data type.\n\n :param data: The data to be serialized.\n :param str data_type: The type to be serialized from.\n :param bool required: Whether it's essential that the data not be\n empty or None\n :raises: AttributeError if required d...
Please provide a description of the function:def serialize_basic(self, data, data_type, **kwargs): custom_serializer = self._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == 'str': return self.serial...
[ "Serialize basic builting data type.\n Serializes objects to str, int, float or bool.\n\n Possible kwargs:\n - is_xml bool : If set, adapt basic serializers without the need for basic_types_serializers\n - basic_types_serializers dict[str, callable] : If set, use the callable as serializ...
Please provide a description of the function:def serialize_unicode(self, data): try: return data.value except AttributeError: pass try: if isinstance(data, unicode): return data.encode(encoding='utf-8') except NameError: ...
[ "Special handling for serializing unicode strings in Py2.\n Encode to UTF-8 if unicode, otherwise handle as a str.\n\n :param data: Object to be serialized.\n :rtype: str\n " ]
Please provide a description of the function:def serialize_iter(self, data, iter_type, div=None, **kwargs): if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") serialization_ctxt = kwargs.get("serialization_ctxt", {}) serialized = []...
[ "Serialize iterable.\n\n Supported kwargs:\n serialization_ctxt dict : The current entry of _attribute_map, or same format. serialization_ctxt['type'] should be same as data_type.\n\n :param list attr: Object to be serialized.\n :param str iter_type: Type of object in the iterable.\n ...
Please provide a description of the function:def serialize_dict(self, attr, dict_type, **kwargs): serialization_ctxt = kwargs.get("serialization_ctxt", {}) serialized = {} for key, value in attr.items(): try: serialized[self.serialize_unicode(key)] = self.ser...
[ "Serialize a dictionary of objects.\n\n :param dict attr: Object to be serialized.\n :param str dict_type: Type of object in the dictionary.\n :param bool required: Whether the objects in the dictionary must\n not be None or empty.\n :rtype: dict\n " ]
Please provide a description of the function:def serialize_object(self, attr, **kwargs): if attr is None: return None if isinstance(attr, ET.Element): return attr obj_type = type(attr) if obj_type in self.basic_types: return self.serialize_bas...
[ "Serialize a generic object.\n This will be handled as a dictionary. If object passed in is not\n a basic type (str, int, float, dict, list) it will simply be\n cast to str.\n\n :param dict attr: Object to be serialized.\n :rtype: dict or str\n " ]
Please provide a description of the function:def serialize_base64(attr, **kwargs): encoded = b64encode(attr).decode('ascii') return encoded.strip('=').replace('+', '-').replace('/', '_')
[ "Serialize str into base-64 string.\n\n :param attr: Object to be serialized.\n :rtype: str\n " ]
Please provide a description of the function:def serialize_date(attr, **kwargs): if isinstance(attr, str): attr = isodate.parse_date(attr) t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) return t
[ "Serialize Date object into ISO-8601 formatted string.\n\n :param Date attr: Object to be serialized.\n :rtype: str\n " ]
Please provide a description of the function:def serialize_duration(attr, **kwargs): if isinstance(attr, str): attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr)
[ "Serialize TimeDelta object into ISO-8601 formatted string.\n\n :param TimeDelta attr: Object to be serialized.\n :rtype: str\n " ]
Please provide a description of the function:def serialize_rfc(attr, **kwargs): try: if not attr.tzinfo: _LOGGER.warning( "Datetime with no tzinfo will be considered UTC.") utc = attr.utctimetuple() except AttributeError: r...
[ "Serialize Datetime object into RFC-1123 formatted string.\n\n :param Datetime attr: Object to be serialized.\n :rtype: str\n :raises: TypeError if format invalid.\n " ]
Please provide a description of the function:def serialize_iso(attr, **kwargs): if isinstance(attr, str): attr = isodate.parse_datetime(attr) try: if not attr.tzinfo: _LOGGER.warning( "Datetime with no tzinfo will be considered UTC.") ...
[ "Serialize Datetime object into ISO-8601 formatted string.\n\n :param Datetime attr: Object to be serialized.\n :rtype: str\n :raises: SerializationError if format invalid.\n " ]
Please provide a description of the function:def serialize_unix(attr, **kwargs): if isinstance(attr, int): return attr try: if not attr.tzinfo: _LOGGER.warning( "Datetime with no tzinfo will be considered UTC.") return int(...
[ "Serialize Datetime object into IntTime format.\n This is represented as seconds.\n\n :param Datetime attr: Object to be serialized.\n :rtype: int\n :raises: SerializationError if format invalid\n " ]
Please provide a description of the function:def _deserialize(self, target_obj, data): # This is already a model, go recursive just in case if hasattr(data, "_attribute_map"): constants = [name for name, config in getattr(data, '_validation', {}).items() if ...
[ "Call the deserializer on a model.\n\n Data needs to be already deserialized as JSON or XML ElementTree\n\n :param str target_obj: Target data type to deserialize to.\n :param object data: Object to deserialize.\n :raises: DeserializationError if deserialization fails.\n :return: ...
Please provide a description of the function:def _classify_target(self, target, data): if target is None: return None, None if isinstance(target, basestring): try: target = self.dependencies[target] except KeyError: return tar...
[ "Check to see whether the deserialization target object can\n be classified into a subclass.\n Once classification has been determined, initialize object.\n\n :param str target: The target object type to deserialize to.\n :param str/dict data: The response data to deseralize.\n " ...
Please provide a description of the function:def _unpack_content(raw_data, content_type=None): # This avoids a circular dependency. We might want to consider RawDesializer is more generic # than the pipeline concept, and put it in a toolbox, used both here and in pipeline. TBD. from .pi...
[ "Extract the correct structure for deserialization.\n\n If raw_data is a PipelineResponse, try to extract the result of RawDeserializer.\n if we can't, raise. Your Pipeline should have a RawDeserializer.\n\n If not a pipeline response and raw_data is bytes or string, use content-type\n t...
Please provide a description of the function:def _instantiate_model(self, response, attrs, additional_properties=None): if callable(response): subtype = getattr(response, '_subtype_map', {}) try: readonly = [k for k, v in response._validation.items() ...
[ "Instantiate a response model passing in deserialized args.\n\n :param response: The response model class.\n :param d_attrs: The deserialized response attributes.\n " ]
Please provide a description of the function:def deserialize_data(self, data, data_type): if data is None: return data try: if not data_type: return data if data_type in self.basic_types.values(): return self.deserialize_basic...
[ "Process data for deserialization according to data type.\n\n :param str data: The response string to be deserialized.\n :param str data_type: The type to deserialize to.\n :raises: DeserializationError if deserialization fails.\n :return: Deserialized object.\n " ]
Please provide a description of the function:def deserialize_iter(self, attr, iter_type): if attr is None: return None if isinstance(attr, ET.Element): # If I receive an element here, get the children attr = list(attr) if not isinstance(attr, (list, set)): ...
[ "Deserialize an iterable.\n\n :param list attr: Iterable to be deserialized.\n :param str iter_type: The type of object in the iterable.\n :rtype: list\n " ]
Please provide a description of the function:def deserialize_dict(self, attr, dict_type): if isinstance(attr, list): return {x['key']: self.deserialize_data(x['value'], dict_type) for x in attr} if isinstance(attr, ET.Element): # Transform <Key>value</Key> into {"Key": ...
[ "Deserialize a dictionary.\n\n :param dict/list attr: Dictionary to be deserialized. Also accepts\n a list of key, value pairs.\n :param str dict_type: The object type of the items in the dictionary.\n :rtype: dict\n " ]
Please provide a description of the function:def deserialize_object(self, attr, **kwargs): if attr is None: return None if isinstance(attr, ET.Element): # Do no recurse on XML, just return the tree as-is return attr if isinstance(attr, basestring): ...
[ "Deserialize a generic object.\n This will be handled as a dictionary.\n\n :param dict attr: Dictionary to be deserialized.\n :rtype: dict\n :raises: TypeError if non-builtin datatype encountered.\n " ]
Please provide a description of the function:def deserialize_basic(self, attr, data_type): # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text if isinstance(attr, ET.Element): attr = attr.text if not attr: ...
[ "Deserialize baisc builtin data type from string.\n Will attempt to convert to str, int, float and bool.\n This function will also accept '1', '0', 'true' and 'false' as\n valid bool values.\n\n :param str attr: response string to be deserialized.\n :param str data_type: deseriali...
Please provide a description of the function:def deserialize_unicode(data): # We might be here because we have an enum modeled as string, # and we try to deserialize a partial dict with enum inside if isinstance(data, Enum): return data # Consider this is real strin...
[ "Preserve unicode objects in Python 2, otherwise return data\n as a string.\n\n :param str data: response string to be deserialized.\n :rtype: str or unicode\n " ]
Please provide a description of the function:def deserialize_enum(data, enum_obj): if isinstance(data, enum_obj): return data if isinstance(data, Enum): data = data.value if isinstance(data, int): # Workaround. We might consider remove it in the futur...
[ "Deserialize string into enum object.\n\n :param str data: response string to be deserialized.\n :param Enum enum_obj: Enum object to deserialize to.\n :rtype: Enum\n :raises: DeserializationError if string is not valid enum value.\n " ]
Please provide a description of the function:def deserialize_bytearray(attr): if isinstance(attr, ET.Element): attr = attr.text return bytearray(b64decode(attr))
[ "Deserialize string into bytearray.\n\n :param str attr: response string to be deserialized.\n :rtype: bytearray\n :raises: TypeError if string format invalid.\n " ]
Please provide a description of the function:def deserialize_base64(attr): if isinstance(attr, ET.Element): attr = attr.text padding = '=' * (3 - (len(attr) + 3) % 4) attr = attr + padding encoded = attr.replace('-', '+').replace('_', '/') return b64decode(en...
[ "Deserialize base64 encoded string into string.\n\n :param str attr: response string to be deserialized.\n :rtype: bytearray\n :raises: TypeError if string format invalid.\n " ]
Please provide a description of the function:def deserialize_decimal(attr): if isinstance(attr, ET.Element): attr = attr.text try: return decimal.Decimal(attr) except decimal.DecimalException as err: msg = "Invalid decimal {}".format(attr) ...
[ "Deserialize string into Decimal object.\n\n :param str attr: response string to be deserialized.\n :rtype: Decimal\n :raises: DeserializationError if string format invalid.\n " ]
Please provide a description of the function:def deserialize_long(attr): if isinstance(attr, ET.Element): attr = attr.text return _long_type(attr)
[ "Deserialize string into long (Py2) or int (Py3).\n\n :param str attr: response string to be deserialized.\n :rtype: long or int\n :raises: ValueError if string format invalid.\n " ]
Please provide a description of the function:def deserialize_duration(attr): if isinstance(attr, ET.Element): attr = attr.text try: duration = isodate.parse_duration(attr) except(ValueError, OverflowError, AttributeError) as err: msg = "Cannot deseria...
[ "Deserialize ISO-8601 formatted string into TimeDelta object.\n\n :param str attr: response string to be deserialized.\n :rtype: TimeDelta\n :raises: DeserializationError if string format invalid.\n " ]
Please provide a description of the function:def deserialize_date(attr): if isinstance(attr, ET.Element): attr = attr.text if re.search(r"[^\W\d_]", attr, re.I + re.U): raise DeserializationError("Date must have only digits and -. Received: %s" % attr) # This mus...
[ "Deserialize ISO-8601 formatted string into Date object.\n\n :param str attr: response string to be deserialized.\n :rtype: Date\n :raises: DeserializationError if string format invalid.\n " ]
Please provide a description of the function:def deserialize_rfc(attr): if isinstance(attr, ET.Element): attr = attr.text try: date_obj = datetime.datetime.strptime( attr, "%a, %d %b %Y %H:%M:%S %Z") if not date_obj.tzinfo: dat...
[ "Deserialize RFC-1123 formatted string into Datetime object.\n\n :param str attr: response string to be deserialized.\n :rtype: Datetime\n :raises: DeserializationError if string format invalid.\n " ]
Please provide a description of the function:def deserialize_iso(attr): if isinstance(attr, ET.Element): attr = attr.text try: attr = attr.upper() match = Deserializer.valid_date.match(attr) if not match: raise ValueError("Invalid ...
[ "Deserialize ISO-8601 formatted string into Datetime object.\n\n :param str attr: response string to be deserialized.\n :rtype: Datetime\n :raises: DeserializationError if string format invalid.\n " ]
Please provide a description of the function:def deserialize_unix(attr): if isinstance(attr, ET.Element): attr = int(attr.text) try: date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) except ValueError as err: msg = "Cannot deserialize to unix d...
[ "Serialize Datetime object into IntTime format.\n This is represented as seconds.\n\n :param int attr: Object to be serialized.\n :rtype: Datetime\n :raises: DeserializationError if format invalid\n " ]
Please provide a description of the function:def raw(self): # type: () -> ClientRawResponse raw = ClientRawResponse(self.current_page, self._response) if self._raw_headers: raw.add_headers(self._raw_headers) return raw
[ "Get current page as ClientRawResponse.\n\n :rtype: ClientRawResponse\n " ]
Please provide a description of the function:def get(self, url): # type: (str) -> List[Model] self.reset() self.next_link = url return self.advance_page()
[ "Get an arbitrary page.\n\n This resets the iterator and then fully consumes it to return the\n specific page **only**.\n\n :param str url: URL to arbitrary page results.\n " ]
Please provide a description of the function:def advance_page(self): # type: () -> List[Model] if self.next_link is None: raise StopIteration("End of paging") self._current_page_iter_index = 0 self._response = self._get_next(self.next_link) self._derserialize...
[ "Force moving the cursor to the next azure call.\n\n This method is for advanced usage, iterator protocol is prefered.\n\n :raises: StopIteration if no further page\n :return: The current page list\n :rtype: list\n " ]
Please provide a description of the function:async def send(self, request: Request, **kwargs) -> Response: if request.context is None: # Should not happen, but make mypy happy and does not hurt request.context = self.build_context() if request.context.session is not self.driver.se...
[ "Send request object according to configuration.\n\n :param Request request: The request object to be sent.\n " ]
Please provide a description of the function:def _ensureAtomicity(fn): @ensureScoopStartedProperly def wrapper(*args, **kwargs): # Note that the docstring is the one of setConst. # This is because of the documentation framework (sphinx) limitations. from . import _control ...
[ "Ensure atomicity of passed elements on the whole worker pool", "setConst(**kwargs)\n Set a constant that will be shared to every workers.\n This call blocks until the constant has propagated to at least one\n worker.\n\n :param \\*\\*kwargs: One or more combination(s) key=value. Key b...
Please provide a description of the function:def setConst(**kwargs): from . import _control sendVariable = _control.execQueue.socket.sendVariable for key, value in kwargs.items(): # Propagate the constant # for file-like objects, see encapsulation.py where copyreg was # us...
[ "setConst(**kwargs)\n Set a constant that will be shared to every workers.\n\n :param **kwargs: One or more combination(s) key=value. Key being the\n variable name and value the object to share.\n\n :returns: None.\n\n Usage: setConst(name=value)\n " ]
Please provide a description of the function:def getConst(name, timeout=0.1): from . import _control import time timeStamp = time.time() while True: # Enforce retrieval of currently awaiting constants _control.execQueue.socket.pumpInfoSocket() # Constants concatenation ...
[ "Get a shared constant.\n\n :param name: The name of the shared variable to retrieve.\n :param timeout: The maximum time to wait in seconds for the propagation of\n the constant.\n\n :returns: The shared object.\n\n Usage: value = getConst('name')\n " ]
Please provide a description of the function:def getArgs(): try: nb_to_launch = int(sys.argv[1]) except: nb_to_launch = 0 if nb_to_launch == 0: nb_to_launch = getCPUcount() try: verbosity = int(sys.argv[2]) except: verbosity = 3 return nb_to_launch...
[ "Gets the arguments of the program.\n Returns a tuple containting:\n (qty to launch, arguments to pass to the bootstrap module)." ]
Please provide a description of the function:def launchBootstraps(): global processes worker_amount, verbosity, args = getArgs() was_origin = False if verbosity >= 1: sys.stderr.write("Launching {0} worker(s) using {1}.\n".format( worker_amount, os.environ['...
[ "Launch the bootstrap instances in separate subprocesses" ]
Please provide a description of the function:def resolve(self, s): name = s.split('.') used = name.pop(0) try: found = self.importer(used) for frag in name: used += '.' + frag try: found = getattr(found, frag) ...
[ "\n Resolve strings to objects using standard import and attribute\n syntax.\n " ]
Please provide a description of the function:def as_tuple(self, value): if isinstance(value, list): value = tuple(value) return value
[ "Utility function which converts lists to tuples." ]
Please provide a description of the function:def configure(self): config = self.config if 'version' not in config: raise ValueError("dictionary doesn't specify a version") if config['version'] != 1: raise ValueError("Unsupported version: %s" % config['version'])...
[ "Do the configuration." ]
Please provide a description of the function:def configure_formatter(self, config): if '()' in config: factory = config['()'] # for use in exception handler try: result = self.configure_custom(config) except TypeError, te: if "'format'...
[ "Configure a formatter from a dictionary." ]
Please provide a description of the function:def configure_filter(self, config): if '()' in config: result = self.configure_custom(config) else: name = config.get('name', '') result = logging.Filter(name) return result
[ "Configure a filter from a dictionary." ]
Please provide a description of the function:def configure_logger(self, name, config, incremental=False): logger = logging.getLogger(name) self.common_logger_config(logger, config, incremental) propagate = config.get('propagate', None) if propagate is not None: logge...
[ "Configure a non-root logger from a dictionary." ]
Please provide a description of the function:def configure_root(self, config, incremental=False): root = logging.getLogger() self.common_logger_config(root, config, incremental)
[ "Configure a root logger from a dictionary." ]
Please provide a description of the function:def sliceImage(image, divWidth, divHeight): w, h = image.size tiles = [] for y in range(0, h - 1 , h/divHeight): my = min(y + h/divHeight, h) for x in range(0, w - 1, w/divWidth): mx = min(x + w/divWidth, w) tiles.appe...
[ "Divide the received image in multiple tiles" ]
Please provide a description of the function:def resizeTile(index, size): resized = tiles[index].resize(size, Image.ANTIALIAS) return sImage(resized.tostring(), resized.size, resized.mode)
[ "Apply Antialiasing resizing to tile" ]
Please provide a description of the function:def initLogging(verbosity=0, name="SCOOP"): global loggingConfig verbose_levels = { -2: "CRITICAL", -1: "ERROR", 0: "WARNING", 1: "INFO", 2: "DEBUG", 3: "DEBUG", 4: ...
[ "Creates a logger." ]