output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Used by Thing instances to indicate that a rename operation has happened
Can you tell what is the following Python 3 function doing def _notify_thing_lid_change(self, from_lid, to_lid): try: with self.__private_things: self.__private_things[to_lid] = self.__private_things.pop(from_lid) except KeyError: logger.warning('Thing %s renamed ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Registers a callback that is called for all feeddata your Thing receives.
Can you generate the documentation for the following Python 3 function def register_catchall_feeddata(self, callback, callback_parsed=None): if callback_parsed: callback = self._get_parsed_feed_callback(callback_parsed, callback) return self.__client.register_callback_feeddata(callback)
You are a Python code generator, capable of creating scripts from specifications.
Registers a callback that is called for all control requests received by your Thing.
Can you generate the documentation for the following Python 3 function def register_catchall_controlreq(self, callback, callback_parsed=None): if callback_parsed: callback = self._get_parsed_control_callback(callback_parsed, callback) return self.__client.register_callback_controlreq(callbac...
You are a Python code generator, capable of creating scripts from specifications.
Register a callback for resource creation.
Given the following Python 3 function, write the documentation def register_callback_created(self, func, serialised=True): self.__client.register_callback_created(partial(self.__callback_payload_only, func), serialised=serialised)
As a Python code analyst, you investigate and solve complex coding mysteries
Register a callback for resource creation but where the resource already exists in Iotic Space.
Can you tell what is the following Python 3 function doing def register_callback_duplicate(self, func, serialised=True): self.__client.register_callback_duplicate(partial(self.__callback_payload_only, func), serialised=serialised)
You are a Python code analyst, evaluating scripts for potential improvements.
def register_callback_renamed(self, func, serialised=True): """ Register a callback for resource rename. This will be called when any resource is renamed within your agent. If `serialised` is not set, the callbacks might arrive in a different order to they were requested. The p...
Create a Python 3 function for registering a callback for resource renaming.
As a Python code analyst, you investigate and solve complex coding mysteries
Register a callback for resource deletion.
Can you tell what is the following Python 3 function doing def register_callback_deleted(self, func, serialised=True): self.__client.register_callback_deleted(partial(self.__callback_payload_only, func), serialised=serialised)
As a python code expert, you are capable of creating scripts from specifications.
Register a callback for reassignment of a resource in the local system.
Make a summary of the following Python 3 code def register_callback_reassigned(self, func, serialised=True): self.__client.register_callback_reassigned(partial(self.__callback_payload_only, func), serialised)
As a python code expert, you are capable of creating scripts from specifications.
Register a callback for new subscription.
Can you tell what is the following Python 3 function doing def register_callback_subscribed(self, callback): return self.__client.register_callback_created(partial(self.__callback_subscribed_filter, callback), serialised=False)
As a Python code composer, you craft elegant and concise scripts.
def simulate_feeddata(self, feedid, data, mime=None, time=None): """Simulate the last feeddata received for given feedid Calls the registered callback for the feed with the last recieved feed data. Allows you to test your code without having to wait for the remote thing to share again. ...
Write a Python 3 function that can simulate the last recieved feeddata for given feedid
As a Python code analyst, you investigate and solve complex coding mysteries
Confirm that you ve done as you ve sent the data.
Make a summary of the following Python 3 code def confirm_tell(self, data, success): logger.info("confirm_tell(success=%s) [lid=\"%s\",pid=\"%s\"]", success, data[P_ENTITY_LID], data[P_LID]) evt = self._request_point_confirm_tell(R_CONTROL, data[P_ENTITY_LID], data[P_LID], success, data['requestId']) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def save_config(self): """Save the config, update the seqnum & default language """ self.__config.set('agent', 'seqnum', self.__client.get_seqnum()) self.__config.set('agent', 'lang', self.__client.default_lang) self.__config.save()
Create a Python 3 function for saving the config update the seqnum & default language
As a python code expert, you are capable of creating scripts from specifications.
def _get_point_data_handler_for(self, point): """Used by point instances and data callbacks""" with self.__point_data_handlers: try: return self.__point_data_handlers[point] except KeyError: return self.__point_data_handlers.setdefault(point, Point...
Can you write a function in Python 3 where it uses by point instances and data callbacks
You are a Python code architect, reviewing and designing scalable and efficient code
Wrapper for parsing data for a specific point.
Given the following Python 3 function, write the documentation def _parsed_callback_wrapper(self, callback_parsed, callback_plain, foc, data): # used by PointDataObjectHandler as reference if foc == R_FEED: point_ref = data['pid'] else: # R_CONTROL point_ref = Control(se...
As a python code expert, you are capable of creating scripts from specifications.
def _wait_and_except_if_failed(self, event, timeout=None): """Combines waiting for event and call to `_except_if_failed`. If timeout is not specified the configured sync_timeout is used. """ event.wait(timeout or self.__sync_timeout) self._except_if_failed(event)
Write a Python 3 function for combining waiting for event and call _except_if_failed.
You are a Python code generator, capable of creating scripts from specifications.
def _except_if_failed(cls, event): """Raises an IOTException from the given event if it was not successful. Assumes timeout success flag on event has not been set yet.""" if event.success is None: raise IOTSyncTimeout('Requested timed out', event) if not event.success: ...
Create a Python 3 function to raise an IOTException from the given event if it was not successful.
You are a Python code generator, capable of creating scripts from specifications.
List all the things created by this client on this or all your agents.
Can you generate a brief explanation for the following Python 3 code def list(self, all_my_agents=False, limit=500, offset=0): logger.info("list(all_my_agents=%s, limit=%s, offset=%s)", all_my_agents, limit, offset) if all_my_agents: evt = self._request_entity_list_all(limit=limit, offset=of...
You are a Python code analyst, evaluating scripts for potential improvements.
Get the details of a newly created Thing.
Can you generate a brief explanation for the following Python 3 code def get_thing(self, lid): with self.__new_things: try: return self.__new_things.pop(lid) except KeyError as ex: raise_from(KeyError('Thing %s not know as new' % lid), ex)
You are a Python code architect, reviewing and designing scalable and efficient code
Create a new Thing with a local id.
Explain what the following Python 3 code does def create_thing(self, lid): evt = self.create_thing_async(lid) self._wait_and_except_if_failed(evt) try: with self.__new_things: return self.__new_things.pop(lid) except KeyError as ex: raise raise_fro...
As a Python code translator, you convert algorithms and pseudocode into Python.
Delete a Thing from the Infrastructure
Can you generate a brief explanation for the following Python 3 code def delete_thing(self, lid): logger.info("delete_thing(lid=\"%s\")", lid) evt = self.delete_thing_async(lid) self._wait_and_except_if_failed(evt)
As a Python code composer, you craft elegant and concise scripts.
Search the Iotic Space for public Things with metadata matching the search parameters.
Given the following Python 3 function, write the documentation def search(self, text=None, lang=None, location=None, unit=None, limit=50, offset=0, reduced=False, local=None, scope=SearchScope.PUBLIC): """Search the Iotic Space for public Things with metadata matching the search parameters: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Search reduced Iotic Agent
Can you generate a brief explanation for the following Python 3 code def search_reduced(self, text=None, lang=None, location=None, unit=None, limit=100, offset=0, local=None, scope=SearchScope.PUBLIC): """Shorthand for [search()](#IoticAgent.IOT.Client.Client.search) with `reduced=True`""...
As a Python code translator, you convert algorithms and pseudocode into Python.
def search_located(self, text=None, lang=None, location=None, unit=None, limit=100, offset=0, local=None, scope=SearchScope.PUBLIC): """See [search()](#IoticAgent.IOT.Client.Client.search) for general documentation. Provides a thing-only result set comprised only of things which h...
How would you implement a function in Python 3 that searches for a specific language in a specific location.
As a Python code analyst, you investigate and solve complex coding mysteries
def describe(self, guid_or_resource, lang=None, local=None, scope=DescribeScope.AUTO): """Describe returns the public (or local) description of a Thing or Point Returns the description dict (see below for Thing example) if available, otherwise `None` #!python { ...
Can you implement a function in Python 3 that describes returns the public description of a Thing or Point.
As a Python code composer, you craft elegant and concise scripts.
Convenience method for creating a new OutcomeRequest from a Django HttpRequest object.
Explain what the following Python 3 code does def from_post_request(post_request): ''' Convenience method for creating a new OutcomeRequest from a request object. post_request is assumed to be a Django HttpRequest object ''' request = OutcomeRequest() request.pos...
As a Python code analyst, you investigate and solve complex coding mysteries
def post_replace_result(self, score, result_data=None): ''' POSTs the given score to the Tool Consumer with a replaceResult. OPTIONAL: result_data must be a dictionary Note: ONLY ONE of these values can be in the dict at a time, due to the Canvas specificatio...
How would you implement a function in Python 3 that posts the given score to the Tool Consumer with a replaceResult.
As a Python code translator, you convert algorithms and pseudocode into Python.
def post_outcome_request(self): ''' POST an OAuth signed request to the Tool Consumer. ''' if not self.has_required_attributes(): raise InvalidLTIConfigError( 'OutcomeRequest does not have all required attributes') consumer = oauth2.Consumer(key=self....
Can you implement a function in Python 3 that posts an OAuth signed request to the LTI - State Service.
As a python code expert, you are capable of creating scripts from specifications.
def process_xml(self, xml): ''' Parse Outcome Request data from XML. ''' root = objectify.fromstring(xml) self.message_identifier = str( root.imsx_POXHeader.imsx_POXRequestHeaderInfo. imsx_messageIdentifier) try: result = root.imsx_POXB...
Implement a function in Python 3 to parse Outcome Request XML.
As a Python code analyst, you investigate and solve complex coding mysteries
Wrap the socket in an SSL object.
Can you generate a brief explanation for the following Python 3 code def _setup_transport(self): if hasattr(self, 'sslopts'): self.sock = ssl.wrap_socket(self.sock, **self.sslopts) elif hasattr(self, 'sslctx'): self.sock = self.sslctx.wrap_socket(self.sock, ...
You are a Python code architect, reviewing and designing scalable and efficient code
def _shutdown_transport(self): """Unwrap a Python 2.6 SSL socket, so we can call shutdown()""" if self.sock is not None: try: unwrap = self.sock.unwrap except AttributeError: return try: self.sock = unwrap() ...
Can you create a Python 3 function that unwraps a Python 2. 6 SSL socket so we can call shutdown
You are a Python code analyst, evaluating scripts for potential improvements.
def save(self, filename=None): """Write config to file.""" if self.__fname is None and filename is None: raise ValueError('Config loaded from string, no filename specified') conf = self.__config cpa = dict_to_cp(conf) with open(self.__fname if filename is None else fi...
Implement a Python 3 function for writing config to file.
You are a Python code analyst, evaluating scripts for potential improvements.
Get a setting or the default value
Make a summary of the following Python 3 code def get(self, section, val): val = val.lower() if section in self.__config: if val in self.__config[section]: # logger.debug('get config %s %s = %s', section, val, self.__config[section][val]) return self.__config[...
You are a Python code generator, capable of creating scripts from specifications.
def set(self, section, val, data): """Add a setting to the config `section` (mandatory) (string) the section name in the config E.g. `"agent"` `val` (mandatory) (string) the section name in the config E.g. `"host"` `data` (mandatory) (as appropriate) the new value for the `val` ...
Create a Python 3 function to add a setting to the config file.
As a Python code translator, you convert algorithms and pseudocode into Python.
def update(self, section, val, data): """Add a setting to the config, but if same as default or None then no action. This saves the .save writing the defaults `section` (mandatory) (string) the section name in the config E.g. `"agent"` `val` (mandatory) (string) the section name in the...
Can you implement a function in Python 3 that updates the value of the key in the config
As a python code expert, you are capable of creating scripts from specifications.
Gets the current geo location of your Thing
Make a summary of the following Python 3 code def get_location(self): lat = None lon = None # note: always picks from first triple for _, _, o in self._graph.triples((None, GEO_NS.lat, None)): lat = float(o) break for _, _, o in self._graph.triples((None, ...
As a python code expert, you are capable of creating scripts from specifications.
Deletes all the geo : lat and geo : long metadata properties on your Thing
Here you have a function in Python 3, explain what it does def delete_location(self): # normally this should only remove one triple each for s, p, o in self._graph.triples((None, GEO_NS.lat, None)): self._graph.remove((s, p, o)) for s, p, o in self._graph.triples((None, GEO_NS.long, ...
You are a Python code generator, capable of creating scripts from specifications.
def start(self): """start connection threads, blocks until started """ if not (self.__recv_thread or self.__send_thread): self.__end.clear() self.__send_ready.clear() self.__recv_ready.clear() timeout = self.__socket_timeout + 1 ignore_...
Create a Python 3 function to start connection threads blocks until started is set
As a Python code composer, you craft elegant and concise scripts.
disconnect blocks until stopped
Given the following Python 3 function, write the documentation def stop(self): self.__end.set() if self.__recv_thread: self.__recv_thread.join() self.__recv_thread = None if self.__send_thread: self.__send_thread.join() self.__send_thread = None
As a Python code composer, you craft elegant and concise scripts.
def send(self, body, content_type='application/ubjson', timeout=5): """timeout indicates amount of time to wait for sending thread to be ready. set to larger than zero to wait (in seconds, fractional) or None to block. """ if self.__send_ready.wait(timeout): try: ...
Implement a Python 3 function for sending a message to the broker.
You are a Python code generator, capable of creating scripts from specifications.
Make an SSLConext for this Python version using public or sslca.
Can you generate the documentation for the following Python 3 function def __get_ssl_context(cls, sslca=None): if ((version_info[0] == 2 and (version_info[1] >= 7 and version_info[2] >= 5)) or (version_info[0] == 3 and version_info[1] >= 4)): logger.debug('SSL method for 2.7.5+ / 3.4...
You are a Python code generator, capable of creating scripts from specifications.
def __recv_cb(self, msg): """Calls user-provided callback and marks message for Ack regardless of success """ try: self.__msg_callback(msg) except: logger.exception("AmqpLink.__recv_cb exception calling msg_callback") finally: # only works if a...
How would you implement a function in Python 3 that calls user - provided callback and marks message for Ack regardless of success
You are a Python code analyst, evaluating scripts for potential improvements.
Set the exception of the receiver thread and wait for it to finish.
Given the following Python 3 function, write the documentation def __recv_log_set_exc_and_wait(self, msg, level=None, wait_seconds=CONN_RETRY_DELAY_SECONDS): logger.log( ((logging.DEBUG if self.__recv_exc else logging.ERROR) if level is None else level), msg, exc_info=DEBUG_E...
You are a Python code architect, reviewing and designing scalable and efficient code
To be called in exception context only.
Can you generate the documentation for the following Python 3 function def __send_log_set_exc_and_wait(self, msg, level=None, wait_seconds=CONN_RETRY_DELAY_SECONDS): logger.log( ((logging.DEBUG if self.__send_exc else logging.ERROR) if level is None else level), msg, exc_info...
As a python code expert, you are capable of creating scripts from specifications.
Clear send exception and time.
Explain what the following Python 3 code does def __send_exc_clear(self, log_if_exc_set=None): if not (log_if_exc_set is None or self.__send_exc is None): logger.info(log_if_exc_set) self.__send_exc_time = None self.__send_exc = None
As a python code expert, you are capable of creating scripts from specifications.
Checks for validity of given mimetype.
Can you tell what is the following Python 3 function doing def valid_mimetype(type_, allow_none=True): if isinstance(type_, unicode_type): match = __IDX_PATTERN.match(type_) if match: return match.group(1) in __IDX_MAPPING else: return __is_ascii(type_, 1, __MAX_LEN) ...
You are a Python code generator, capable of creating scripts from specifications.
def expand_idx_mimetype(type_): """Returns long equivalent of type_, if available, otherwise type_ itself. Does not raise exceptions""" if isinstance(type_, unicode_type): match = __IDX_PATTERN.match(type_) return __IDX_MAPPING.get(match.group(1), type_) if match else type_ else: ret...
Can you implement a function in Python 3 that returns long equivalent of type_ if available otherwise type_ itself. Does not raise exceptions
As a python code expert, you are capable of creating scripts from specifications.
Returns None if the rate limit is exceeded.
Here you have a function in Python 3, explain what it does def throttle(self): iterations = self.__iterations timestamp = monotonic() outdated_threshold = timestamp - self.__interval with self.__lock: # remove any iterations older than interval try: ...
You are a Python code analyst, evaluating scripts for potential improvements.
Decode a message into a string of the decoded message.
Make a summary of the following Python 3 code def decode_sent_msg(pref, message, pretty=False): newline = "\n" if pretty else " " indent = " " if pretty else "" start = newline + indent out = [] out.append("%s%s{%sSEQNUM: %d," % (pref, newline, start, message[Const.W_SEQ])) out.append("%sCOM...
As a Python code translator, you convert algorithms and pseudocode into Python.
def decode_rcvd_msg(pref, message, seqnum, pretty=False): """decode_rcvd_msg: Return string of received message expanding short codes, optionally with newlines and indent """ newline = "\n" if pretty else " " indent = " " if pretty else "" start = newline + indent out = [] out.append("%s...
Can you implement a function in Python 3 that decodes a received message into a string expanding short codes optionally with newlines and indent
As a python code expert, you are capable of creating scripts from specifications.
def _long_to_bytes(self, long_value): """ Turns a long value into its byte string equivalent. :param long_value: the long value to be returned as a byte string :return: a byte string equivalent of a long value """ _byte_string = b'' pack = struct.pack whil...
Implement a function in Python 3 to convert a long value into its byte string equivalent.
As a python code expert, you are capable of creating scripts from specifications.
restore an event based on the requestId
How would you explain what the following Python 3 function does def restore_event(self, requestId): with self.__requests: if requestId not in self.__requests: self.__requests[requestId] = RequestEvent(requestId) return True return False
As a Python code analyst, you investigate and solve complex coding mysteries
def __add_callback(self, type_, func, serialised_if_crud=True): """sync_if_crud indicates whether to serialise this callback (applies only to CRUD)""" Validation.callable_check(func) with self.__callbacks: self.__callbacks[type_].append((func, serialised_if_crud))
Can you create a Python 3 function that adds a callback to the list of callbacks for a specific type.
You are a Python code generator, capable of creating scripts from specifications.
Register a callback function to receive a QAPI Unsolicited ( resource ) CREATED.
Given the following Python 3 function, write the documentation def register_callback_created(self, func, serialised=True): self.__add_callback(_CB_CREATED, func, serialised_if_crud=serialised)
You are a Python code generator, capable of creating scripts from specifications.
Register a callback function to receive a duplicate message.
Here you have a function in Python 3, explain what it does def register_callback_duplicate(self, func, serialised=True): self.__add_callback(_CB_DUPLICATE, func, serialised_if_crud=serialised)
You are a Python code architect, reviewing and designing scalable and efficient code
def register_callback_renamed(self, func, serialised=True): """Register a callback function to receive QAPI Unsolicited (resource) RENAMED. The callback receives a single argument - the inner message. If `serialised` is not set, the callbacks might arrive out-of-order. """ self._...
Implement a function in Python 3 to register a callback function to receive a QAPI Unsolicited ( resource ) RENAMED.
As a python code expert, you are capable of creating scripts from specifications.
def register_callback_reassigned(self, func, serialised=True): """Register a callback function to receive QAPI Unsolicited (entity) REASSIGNED. The callback receives a single argument - the inner message. If `serialised` is not set, the callbacks might arrive out-of-order. """ se...
Can you create a Python 3 function that registers a callback function to receive a Unsolicited ( entity ) REASSIGNED.
As a Python code analyst, you investigate and solve complex coding mysteries
def start(self): # noqa (complexity) """Start the send & recv Threads. Start can be delayed to EG restore requestIds before attaching to the QAPI Note: This function waits for/blocks until amqplink connect(s) and the current sequence number has been obtained from the container (wi...
Write a Python 3 function that can start the send & receive threads.
You are a Python code analyst, evaluating scripts for potential improvements.
def stop(self): """Stop the Client, disconnect from queue """ if self.__end.is_set(): return self.__end.set() self.__send_retry_requests_timer.cancel() self.__threadpool.stop() self.__crud_threadpool.stop() self.__amqplink.stop() self._...
Can you implement a function in Python 3 that stops the Client disconnect from queue
You are a Python code analyst, evaluating scripts for potential improvements.
Override default compression method and threshold
Can you generate a brief explanation for the following Python 3 code def set_compression(self, comp=COMP_DEFAULT, size=COMP_SIZE): if comp not in COMPRESSORS: if comp == COMP_LZ4F: raise ValueError('lz4f compression not available, required lz4framed') else: ...
As a Python code analyst, you investigate and solve complex coding mysteries
def __send_retry_requests(self, last_send_failure_time): """Called via Timer from __send_ready to resend requests which might not have been sent due to transport failure. This can happen since the current transport implementation does not received acknowledgements for sent messages.""" ...
Write a Python 3 function that can call by the transport implementation to send all requests which have not been sent due to a transport failure. This function is called by the transport implementation to send all the requests that have not been sent due to a transport failure.
You are a Python code generator, capable of creating scripts from specifications.
def request_entity_create(self, lid, epId=None): """request entity create: lid = local name to user If epId=None (default), the current agent/EP is chosen If epId=False, no agent is assigned If epId=guid, said agent is chosen """ lid = Validation.lid_check_convert(lid) ...
How would you implement a function in Python 3 that requests entity create: lid = local name to user If epId=None (default), the current agent/EP is chosen If epId=False, no agent is assigned If epId=guid, said agent is chosen
As a Python code translator, you convert algorithms and pseudocode into Python.
def request_entity_reassign(self, lid, nepId=None): """request entity to be reassigned to given ep/agent If nepId=None (default), the current agent/EP is chosen If nepId=False, no agent is assigned If nepId=guid, said agent is chosen """ lid = Validation.lid_check_convert...
How would you code a function in Python 3 to request entity to be reassigned to given ep
As a python code expert, you are capable of creating scripts from specifications.
def request_point_create(self, foc, lid, pid, control_cb=None, save_recent=0): """request point create: feed or control, lid and pid point lid """ Validation.foc_check(foc) lid = Validation.lid_check_convert(lid) pid = Validation.pid_check_convert(pid) save_recent = valid...
Create a Python 3 function to request point create lid and pid point lid
As a Python code translator, you convert algorithms and pseudocode into Python.
def __point_data_to_bytes(self, data, mime=None): # pylint: disable=too-many-branches """Returns tuple of mime type & data. Auto encodes unicode strings (to utf8) and dictionaries (to ubjson) depending on client setting.""" if mime is None: if self.__auto_encode_decode: ...
Implement a Python 3 function for returning tuple of mime type & data. Auto encodes unicode strings to utf8 and unicode dictionaries depending on client setting.
As a Python code analyst, you investigate and solve complex coding mysteries
def __bytes_to_share_data(self, payload): """Attempt to auto-decode data""" rbytes = payload[P_DATA] mime = payload[P_MIME] if mime is None or not self.__auto_encode_decode: return rbytes, mime mime = expand_idx_mimetype(mime).lower() try: if mime...
Can you create a Python 3 function that attempts to auto - decode data
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a new request id for the current request.
Can you generate a brief explanation for the following Python 3 code def __new_request_id(self): while True: # Since seqnum wraps on 2^64 at most, this should always fit into 32 chars (QAPI request id limit) with self.__seqnum_lock: requestId = "%s%d" % (self.__reqpre, se...
As a Python code translator, you convert algorithms and pseudocode into Python.
def __make_hash(cls, innermsg, token, seqnum): """return the hash for this innermsg, token, seqnum return digest bytes """ hobj = hmacNew(token, digestmod=hashfunc) hobj.update(innermsg) hobj.update(cls.__byte_packer(seqnum)) return hobj.digest()
Can you implement a function in Python 3 that returns the hash for this innermsg token seqnum return digest bytes
You are a Python code analyst, evaluating scripts for potential improvements.
def __check_hash(self, message): """return true/false if hash is good message = dict """ return message[W_HASH] == self.__make_hash(message[W_MESSAGE], self.__token, message[W_SEQ])
Write a Python 3 script for checking if hash is good
You are a Python code analyst, evaluating scripts for potential improvements.
return innermsg chunk (dict)
Can you generate the documentation for the following Python 3 function def __make_innermsg(resource, rtype, ref, action=None, payload=None, limit=None): if action is not None and not isinstance(action, (tuple, list)): raise TypeError('action must be None/tuple/list') p = {M_RESOURCE: resourc...
You are a Python code architect, reviewing and designing scalable and efficient code
def __request_except(self, requestId, exc, set_and_forget=True): """Set exception (if not None) for the given request and (optionally) remove from internal cache & setting its event""" try: with self.__requests: if set_and_forget: req = self.__r...
Create a Python 3 function to set exception for the given request and remove from internal cache and set its event
As a Python code composer, you craft elegant and concise scripts.
Set send time & clear exception from request if set
Can you generate the documentation for the following Python 3 function def __request_mark_sent(self, requestId): with self.__requests: try: req = self.__requests[requestId] except KeyError: # request might have had a response already have been removed by r...
You are a Python code generator, capable of creating scripts from specifications.
Sends a message to the AMPL server. Returns True if the message was successfully sent False otherwise.
Can you generate a brief explanation for the following Python 3 code def __publish(self, qmsg): with self.__seqnum_lock: seqnum = self.__seqnum self.__seqnum = (self.__seqnum + 1) % _SEQ_WRAP_SIZE # innermsg = ubjdumpb(qmsg.inner_msg) clevel = COMP_NONE if...
You are a Python code architect, reviewing and designing scalable and efficient code
def __fire_callback(self, type_, *args, **kwargs): """Returns True if at least one callback was called""" called = False plain_submit = self.__threadpool.submit with self.__callbacks: submit = self.__crud_threadpool.submit if type_ in _CB_CRUD_TYPES else plain_submit ...
Write a Python 3 function for returning True if at least one callback was called
As a Python code analyst, you investigate and solve complex coding mysteries
def __validate_decode_msg(self, message): # noqa (complexity) pylint: disable=too-many-return-statements,too-many-branches """Decodes wrapper, check hash & seq, decodes body. Returns body or None, if validation / unpack failed""" try: if not _CONTENT_TYPE_PATTERN.match(message.content_type)...
Write a Python 3 script to validate the message and return the content of the message.
As a Python code analyst, you investigate and solve complex coding mysteries
def __dispatch_msg(self, message): """Verify the signature and update RequestEvents / perform callbacks Note messages with an invalid wrapper, invalid hash, invalid sequence number or unexpected clientRef will be sent to debug_bad callback. """ msg = self.__validate_decode_msg(m...
Write a Python 3 function that can dispatch a message to the appropriate handler.
You are a Python code analyst, evaluating scripts for potential improvements.
returns True if message has been handled as a solicited response False otherwise
How would you explain what the following Python 3 function does def __handle_known_solicited(self, msg): with self.__requests: try: req = self.__requests[msg[M_CLIENTREF]] except KeyError: return False if self.__handle_low_seq_resend(msg, req)...
You are a Python code generator, capable of creating scripts from specifications.
def __clear_references(self, request, remove_request=True): """Remove any internal references to the given request""" # remove request itself if remove_request: with self.__requests: self.__requests.pop(request.id_) # remove request type specific references ...
How would you code a function in Python 3 to remove any internal references to the given request.
You are a Python code analyst, evaluating scripts for potential improvements.
def __update_existing(self, msg, req): """Propagate changes based on type of message. MUST be called within self.__requests lock. Performs additional actions when solicited messages arrive.""" req._messages.append(msg) payload = msg[M_PAYLOAD] if msg[M_TYPE] in _RSP_TYPE_CREA...
Implement a function in Python 3 to propagate changes based on type of message. Performs additional information actions when solicited messages arrive.
You are a Python code generator, capable of creating scripts from specifications.
special error case - low sequence number resend
How would you explain what the following Python 3 function does def __handle_low_seq_resend(self, msg, req): if msg[M_TYPE] == E_FAILED and msg[M_PAYLOAD][P_CODE] == E_FAILED_CODE_LOWSEQNUM: with self.__seqnum_lock: self.__seqnum = int(msg[M_PAYLOAD][P_MESSAGE]) # return ...
As a python code expert, you are capable of creating scripts from specifications.
Extract time and decode payload based on mime type. Applies to E_FEEDDATA and E_RECENTDATA.
Explain what the following Python 3 code does def __decode_data_time(self, payload): data, mime = self.__bytes_to_share_data(payload) try: time = datetime.strptime(payload.get(P_TIME), self.__share_time_fmt) except (ValueError, TypeError): logger.warning('Share payload fr...
As a Python code composer, you craft elegant and concise scripts.
def __perform_unsolicited_callbacks(self, msg): """Callbacks for which a client reference is either optional or does not apply at all""" type_ = msg[M_TYPE] payload = msg[M_PAYLOAD] # callbacks for responses which might be unsolicited (e.g. created or deleted) if type_ in _RSP_P...
Can you implement a function in Python 3 that performs unsolicited callbacks for the given message.
You are a Python code analyst, evaluating scripts for potential improvements.
def roles(self, roles_list): ''' Set the roles for the current launch. Full list of roles can be found here: http://www.imsglobal.org/LTI/v1p1/ltiIMGv1p1.html#_Toc319560479 LIS roles include: * Student * Faculty * Member * Learner * Instr...
Implement a function in Python 3 to set the roles for the current launch.
As a Python code analyst, you investigate and solve complex coding mysteries
def process_params(self, params): ''' Populates the launch data from a dictionary. Only cares about keys in the LAUNCH_DATA_PARAMETERS list, or that start with 'custom_' or 'ext_'. ''' for key, val in params.items(): if key in LAUNCH_DATA_PARAMETERS and val !=...
Can you create a Python 3 function that populates the launch data from a dictionary. Only cares about keys custom_ or ext_.
As a Python code analyst, you investigate and solve complex coding mysteries
Createa a new dictionary with all launch data. Custom and Extension keys will be included. Roles are set as a comma separated string.
Can you generate a brief explanation for the following Python 3 code def to_params(self): ''' Createa a new dictionary with all launch data. Custom / Extension keys will be included. Roles are set as a ',' separated string. ''' params = {} custom_params = {} for k...
As a Python code analyst, you investigate and solve complex coding mysteries
def write_longstr(self, s): """Write a string up to 2**32 bytes long after encoding. If passed a unicode string, encode as UTF-8. """ self._flushbits() if isinstance(s, text_t): s = s.encode('utf-8') self.write_long(len(s)) self.out.write(s)
Can you create a Python 3 function that writes a string up to 2 ** 32 bytes long after encoding.
You are a Python code generator, capable of creating scripts from specifications.
Runs on_startup main and on_shutdown blocking until finished.
Can you generate the documentation for the following Python 3 function def run(self, background=False): if self.__bgthread: raise Exception('run has already been called (since last stop)') self.__shutdown.clear() if background: self.__bgthread = Thread(target=self.__run, ...
As a python code expert, you are capable of creating scripts from specifications.
def stop(self, timeout=None): """Requests device to stop running, waiting at most the given timout in seconds (fractional). Has no effect if `run()` was not called with background=True set. Returns True if successfully stopped (or already not running). """ stopped = True self.__s...
Write a Python 3 script to request device to stop running waiting at most the given timeout in seconds. Returns True if successfully stopped False otherwise.
As a Python code analyst, you investigate and solve complex coding mysteries
Given a payload and any optional message attributes add it to the queue.
Here you have a function in Python 3, explain what it does def add_message_to_queue(self, payload, **attributes): return self.queue.send_message(MessageBody=json.dumps(payload), MessageAttributes={k: {"StringValue": v} for k, v in attributes.items()})
You are a Python code analyst, evaluating scripts for potential improvements.
def receive_messages_from_queue(self, wait_time=15, num_messages=1): """ Returns the first (according to FIFO) element in the queue; if none, then returns None.""" return self.queue.receive_messages(MaxNumberOfMessages=num_messages, WaitTimeSeconds=wait_time)
Implement a Python 3 function for returning the first num_messages messages from the queue.
You are a Python code generator, capable of creating scripts from specifications.
Write a. json file with the units tree containing the units
Given the following Python 3 function, write the documentation def save_json(self, jsonfn=None, pretty=True): if jsonfn is None: jsonfn = os.path.join(os.getcwd(), 'units.json') # jsondump = None sort_keys = False indent = 0 if pretty: sort_keys = ...
You are a Python code architect, reviewing and designing scalable and efficient code
Accumulate a custom metric name and value in the metrics cache.
Explain what the following Python 3 code does def accumulate_metric(cls, name, value): metrics_cache = cls._get_metrics_cache() metrics_cache.setdefault(name, 0) metrics_cache.set(name, value)
You are a Python code generator, capable of creating scripts from specifications.
Report the collected custom metrics to New Relic.
Explain what the following Python 3 code does def _batch_report(cls, request): if not newrelic: return metrics_cache = cls._get_metrics_cache() try: newrelic.agent.add_custom_parameter('user_id', request.user.id) except AttributeError: pass for...
You are a Python code architect, reviewing and designing scalable and efficient code
def process_request(self, request): """ Store memory data to log later. """ if self._is_enabled(): self._cache.set(self.guid_key, six.text_type(uuid4())) log_prefix = self._log_prefix(u"Before", request) self._cache.set(self.memory_data_key, self._memo...
Implement a function in Python 3 to store memory data to log later.
You are a Python code analyst, evaluating scripts for potential improvements.
def process_response(self, request, response): """ Logs memory data after processing response. """ if self._is_enabled(): log_prefix = self._log_prefix(u"After", request) new_memory_data = self._memory_data(log_prefix) log_prefix = self._log_prefix(u"...
Write a Python 3 script for logging memory data after processing response.
You are a Python code architect, reviewing and designing scalable and efficient code
def _log_prefix(self, prefix, request): """ Returns a formatted prefix for logging for the given request. """ # After a celery task runs, the request cache is cleared. So if celery # tasks are running synchronously (CELERY_ALWAYS _EAGER), "guid_key" # will no longer be in...
Can you create a Python 3 function that returns a formatted prefix for logging for the given request.
As a Python code composer, you craft elegant and concise scripts.
def _memory_data(self, log_prefix): """ Returns a dict with information for current memory utilization. Uses log_prefix in log statements. """ machine_data = psutil.virtual_memory() process = psutil.Process() process_data = { 'memory_info': process.ge...
Write a Python 3 function for returning a dict with information for current memory utilization.
You are a Python code analyst, evaluating scripts for potential improvements.
def _log_diff_memory_data(self, prefix, new_memory_data, old_memory_data): """ Computes and logs the difference in memory utilization between the given old and new memory data. """ def _vmem_used(memory_data): return memory_data['machine_data'].used def _proc...
Write a Python 3 script for computing and logs the difference in memory utilization between the given old and new memory data.
As a python code expert, you are capable of creating scripts from specifications.
def data(self, namespace): """ Gets the thread.local data (dict) for a given namespace. Args: namespace (string): The namespace, or key, of the data dict. Returns: (dict) """ assert namespace if namespace in self._data: retu...
Write a Python 3 script to return the thread. local data dict for a given namespace.
As a Python code composer, you craft elegant and concise scripts.
def get_cached_response(self, key): """ Retrieves a CachedResponse for the provided key. Args: key (string) Returns: A CachedResponse with is_found status and value. """ cached_value = self.data.get(key, _CACHE_MISS) is_found = cached_va...
Create a Python 3 function to retrieve a CachedResponse for the provided key.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a CachedResponse for the provided key.
How would you explain what the following Python 3 function does def get_cached_response(cls, key): request_cached_response = DEFAULT_REQUEST_CACHE.get_cached_response(key) if not request_cached_response.is_found: django_cached_response = cls._get_cached_response_from_django_cache(key) ...
You are a Python code architect, reviewing and designing scalable and efficient code