output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def set_all_tiers(key, value, django_cache_timeout=DEFAULT_TIMEOUT): """ Caches the value for the provided key in both the request cache and the django cache. Args: key (string) value (object) django_cache_timeout (int): (Optional) Timeout used to det...
Create a Python 3 function to set the value for the provided key in both the request cache and the django cache.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a CachedResponse for the given key from the django cache.
Can you tell what is the following Python 3 function doing def _get_cached_response_from_django_cache(key): if TieredCache._should_force_django_cache_miss(): return CachedResponse(is_found=False, key=key, value=None) cached_value = django_cache.get(key, _CACHE_MISS) is_found = cache...
As a python code expert, you are capable of creating scripts from specifications.
Sets the value in the request cache if the django cached response was a hit.
Can you generate a brief explanation for the following Python 3 code def _set_request_cache_if_django_cache_hit(key, django_cached_response): if django_cached_response.is_found: DEFAULT_REQUEST_CACHE.set(key, django_cached_response.value)
As a python code expert, you are capable of creating scripts from specifications.
Gets value for request query parameter FORCE_CACHE_MISS and sets it in the default request cache.
How would you explain what the following Python 3 function does def _get_and_set_force_cache_miss(request): if not (request.user and request.user.is_active and request.user.is_staff): force_cache_miss = False else: force_cache_miss = request.GET.get(FORCE_CACHE_MISS_PARAM, 'false...
As a Python code analyst, you investigate and solve complex coding mysteries
def _should_force_django_cache_miss(cls): """ Returns True if the tiered cache should force a cache miss for the django cache, and False otherwise. """ cached_response = DEFAULT_REQUEST_CACHE.get_cached_response(SHOULD_FORCE_CACHE_MISS_KEY) return False if not cached_res...
Create a Python 3 function for returning True if the tiered cache should force a cache miss for the django cache and False otherwise.
You are a Python code architect, reviewing and designing scalable and efficient code
def guid_check_convert(guid, allow_none=False): """Take a GUID in the form of hex string "32" or "8-4-4-4-12". Returns hex string "32" or raises ValueError: badly formed hexadecimal UUID string """ if isinstance(guid, string_types): return ensure_unicode(UUID(guid).hex) ...
Can you create a Python 3 function that takes a GUID in the form of hex string 32 or 8 - 4 - 4 - 12. Returns None if the GUID is None.
As a Python code composer, you craft elegant and concise scripts.
def tags_check_convert(cls, tags): """Accept one tag as string or multiple tags in list of strings. Returns list (with tags in unicode form) or raises ValueError """ # single string check comes first since string is also a Sequence if isinstance(tags, string_types): r...
Create a Python 3 function to accept one tag as string or multiple tags in list of strings or raises ValueError
You are a Python code architect, reviewing and designing scalable and efficient code
Checks if the given URL is a valid URL.
Explain what the following Python 3 code does def __valid_url(cls, url): bits = urlparse(url) return ((bits.scheme == "http" or bits.scheme == "https") and _PATTERN_URL_PART.match(bits.netloc) and _PATTERN_URL_PART.match(bits.path))
You are a Python code generator, capable of creating scripts from specifications.
def location_check(lat, lon): """For use by Core client wrappers""" if not (isinstance(lat, number_types) and -90 <= lat <= 90): raise ValueError("Latitude: '{latitude}' invalid".format(latitude=lat)) if not (isinstance(lon, number_types) and -180 <= lon <= 180): raise V...
Write a Python 3 function for checking that the latitude and longitude are valid.
You are a Python code analyst, evaluating scripts for potential improvements.
def search_location_check(cls, location): """Core.Client.request_search location parameter should be a dictionary that contains lat, lon and radius floats """ if not (isinstance(location, Mapping) and set(location.keys()) == _LOCATION_SEARCH_ARGS): raise ValueError('Search location s...
Write a Python 3 function for coring Client. request_search location parameter should be a dictionary that contains lat lon and radius floats
You are a Python code architect, reviewing and designing scalable and efficient code
Converts and keeps only words in text deemed to be valid
Make a summary of the following Python 3 code def __search_text_check_convert(cls, text): text = cls.check_convert_string(text, name='text', no_leading_trailing_whitespace=False) if len(text) > VALIDATION_META_SEARCH_TEXT: raise ValueError("Search text can contain at most %d characters" % VA...
As a Python code analyst, you investigate and solve complex coding mysteries
def callable_check(func, arg_count=1, arg_value=None, allow_none=False): """Check whether func is callable, with the given number of positional arguments. Returns True if check succeeded, False otherwise.""" if func is None: if not allow_none: raise ValueError('cal...
Write a Python 3 script to check whether func is callable with the given number of positional arguments. Returns True if check succeeded False otherwise.
As a Python code composer, you craft elegant and concise scripts.
def list_feeds(self, limit=500, offset=0): """List `all` the feeds on this Thing. Returns QAPI list function payload Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkExcep...
Write a Python 3 function that can list all the feeds on this Thing.
You are a Python code architect, reviewing and designing scalable and efficient code
def list_controls(self, limit=500, offset=0): """List `all` the controls on this Thing. Returns QAPI list function payload Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [Lin...
How would you code a function in Python 3 to list all the controls on this Thing.
As a Python code translator, you convert algorithms and pseudocode into Python.
Rename the Thing. `ADVANCED USERS ONLY` This can be confusing. You are changing the local id of a Thing to `new_lid`. If you create another Thing using the "old_lid", the system will oblige, but it will be a completely _new_ Thing. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Ex...
Can you generate the documentation for the following Python 3 function def rename(self, new_lid): logger.info("rename(new_lid=\"%s\") [lid=%s]", new_lid, self.__lid) evt = self._client._request_entity_rename(self.__lid, new_lid) self._client._wait_and_except_if_failed(evt) self.__lid = n...
As a Python code translator, you convert algorithms and pseudocode into Python.
def reassign(self, new_epid): """Reassign the Thing from one agent to another. `ADVANCED USERS ONLY` This will lead to any local instances of a Thing being rendered useless. They won't be able to receive control requests, feed data or to share any feeds as they won't be in this agent. ...
Write a Python 3 script to reassign the Thing from one agent to another.
As a Python code composer, you craft elegant and concise scripts.
Create tags for a Thing in the language you specify.
Make a summary of the following Python 3 code def create_tag(self, tags): if isinstance(tags, str): tags = [tags] evt = self._client._request_entity_tag_update(self.__lid, tags, delete=False) self._client._wait_and_except_if_failed(evt)
As a Python code composer, you craft elegant and concise scripts.
def delete_tag(self, tags): """Delete tags for a Thing in the language you specify. Case will be ignored and any tags matching lower-cased will be deleted. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detect...
How would you code a function in Python 3 to delete tags for a Thing in the language you specify. Case will be ignored and any tags matching the lower - cased will be deleted.
You are a Python code architect, reviewing and designing scalable and efficient code
def list_tag(self, limit=500, offset=0): """List `all` the tags for this Thing Returns lists of tags, as below #!python [ "mytag1", "mytag2" "ein_name", "nochein_name" ] - OR... Raises...
Write a Python 3 script for listing all the tags for this Thing
As a python code expert, you are capable of creating scripts from specifications.
Get the metadata object for this Thing
Explain what the following Python 3 code does def get_meta(self): rdf = self.get_meta_rdf(fmt='n3') return ThingMeta(self, rdf, self._client.default_lang, fmt='n3')
You are a Python code analyst, evaluating scripts for potential improvements.
Get the metadata for this Thing in rdf fmt
Given the following Python 3 function, write the documentation def get_meta_rdf(self, fmt='n3'): evt = self._client._request_entity_meta_get(self.__lid, fmt=fmt) self._client._wait_and_except_if_failed(evt) return evt.payload['meta']
You are a Python code architect, reviewing and designing scalable and efficient code
def set_meta_rdf(self, rdf, fmt='n3'): """Set the metadata for this Thing in RDF fmt Advanced users who want to manipulate the RDF for this Thing directly without the [ThingMeta](ThingMeta.m.html#IoticAgent.IOT.ThingMeta.ThingMeta) helper object Raises [IOTException](./Exceptions.m.htm...
How would you code a function in Python 3 to set the metadata for this Thing in RDF fmt
As a python code expert, you are capable of creating scripts from specifications.
Get the details of a newly created feed.
Given the following Python 3 function, write the documentation def get_feed(self, pid): with self.__new_feeds: try: return self.__new_feeds.pop(pid) except KeyError as ex: raise_from(KeyError('Feed %s not know as new' % pid), ex)
As a python code expert, you are capable of creating scripts from specifications.
def get_control(self, pid): """Get the details of a newly created control. This only applies to asynchronous creation of feeds and the new control instance can only be retrieved once. `NOTE` - Destructive Read. Once you've called get_control once, any further calls will raise a `KeyError` ...
Can you implement a function in Python 3 that gets the details of a newly created control.
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a new Feed for this Thing with a local point id pid.
How would you explain what the following Python 3 function does def create_feed(self, pid, save_recent=0): logger.info("create_feed(pid=\"%s\") [lid=%s]", pid, self.__lid) return self.__create_point(R_FEED, pid, save_recent=save_recent)
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a new control for this Thing with a local point id and a control request.
How would you explain what the following Python 3 function does def create_control(self, pid, callback, callback_parsed=None): logger.info("create_control(pid=\"%s\", control_cb=%s) [lid=%s]", pid, callback, self.__lid) if callback_parsed: callback = self._client._get_parsed_control_callback...
As a python code expert, you are capable of creating scripts from specifications.
Delete a feed identified by its local id.
Explain what the following Python 3 code does def delete_feed(self, pid): logger.info("delete_feed(pid=\"%s\") [lid=%s]", pid, self.__lid) return self.__delete_point(R_FEED, pid)
As a Python code composer, you craft elegant and concise scripts.
Delete a control identified by its local id.
Make a summary of the following Python 3 code def delete_control(self, pid): logger.info("delete_control(pid=\"%s\") [lid=%s]", pid, self.__lid) return self.__delete_point(R_CONTROL, pid)
As a Python code translator, you convert algorithms and pseudocode into Python.
Used by __sub_make_request to save reference for pending sub request
Can you generate a brief explanation for the following Python 3 code def __sub_add_reference(self, key): new_subs = self.__new_subs with new_subs: # don't allow multiple subscription requests to overwrite internal reference if key in new_subs: raise ValueError('su...
You are a Python code analyst, evaluating scripts for potential improvements.
def __sub_make_request(self, foc, gpid, callback): """Make right subscription request depending on whether local or global - used by __sub*""" # global if isinstance(gpid, string_types): gpid = uuid_to_hex(gpid) ref = (foc, gpid) with self.__sub_add_reference(...
Can you write a function in Python 3 where it makes right subscription request depending on whether local or global - used by __sub*
As a python code expert, you are capable of creating scripts from specifications.
Create a new subscription with a global point id and a feed data callback Returns a new RemoteFeed instance with the new data and a callback_parsed dictionary that will be called when the subscription is created.
Here you have a function in Python 3, explain what it does def follow(self, gpid, callback=None, callback_parsed=None): if callback_parsed: callback = self._client._get_parsed_feed_callback(callback_parsed, callback) return self.__sub(R_FEED, gpid, callback=callback)
You are a Python code generator, capable of creating scripts from specifications.
def list_connections(self, limit=500, offset=0): """List Points to which this Things is subscribed. I.e. list all the Points this Thing is following and controls it's attached to Returns subscription list e.g. #!python { "<Subscription GUID 1>": { ...
Can you create a Python 3 function that lists all the Points following this Thing and controls it s attached to the infrastructure.
As a python code expert, you are capable of creating scripts from specifications.
Indirect callback for point & subscription creation responses
How would you explain what the following Python 3 function does def _cb_created(self, payload, duplicated): if payload[P_RESOURCE] in _POINT_TYPE_TO_CLASS: store = self.__new_feeds if payload[P_RESOURCE] == R_FEED else self.__new_controls cls = _POINT_TYPE_TO_CLASS[payload[P_RESOURCE]] ...
You are a Python code analyst, evaluating scripts for potential improvements.
Wait for a method that matches our allowed_methods parameter and dispatch it.
Explain what the following Python 3 code does def wait(self, allowed_methods=None): method_sig, args, content = self.connection._wait_method( self.channel_id, allowed_methods) return self.dispatch_method(method_sig, args, content)
You are a Python code analyst, evaluating scripts for potential improvements.
Get the most recent items from the feed. Useful for testing purposes.
Explain what the following Python 3 code does def get_recent(self, count): queue = Queue() evt = self.get_recent_async(count, queue.put) timeout_time = monotonic() + self._client.sync_timeout while True: try: yield queue.get(True, .1) except Empty...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_recent_async(self, count, callback): """Similar to `get_recent` except instead of returning an iterable, passes each dict to the given function which must accept a single argument. Returns the request. `callback` (mandatory) (function) instead of returning an iterable, pass each dict (a...
Write a Python 3 function that can get the most recent entries for this entry.
As a Python code translator, you convert algorithms and pseudocode into Python.
def simulate(self, data, mime=None): """Simulate the arrival of feeddata into the feed. Useful if the remote Thing doesn't publish very often. `data` (mandatory) (as applicable) The data you want to use to simulate the arrival of remote feed data `mime` (optional) (string) The mime ty...
Implement a Python 3 function for simulating the arrival of remote feeddata into the feed.
As a Python code translator, you convert algorithms and pseudocode into Python.
def ask(self, data, mime=None): """Request a remote control to do something. Ask is "fire-and-forget" in that you won't receive any notification of the success or otherwise of the action at the far end. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) c...
Implement a function in Python 3 to request a remote control to do something.
You are a Python code architect, reviewing and designing scalable and efficient code
def tell(self, data, timeout=10, mime=None): """Order a remote control to do something. Tell is confirmed in that you will receive a notification of the success or otherwise of the action at the far end via a callback `Example` #!python data = {"thermostat":18.0} ...
Can you create a Python 3 function that orders a remote control to do something.
You are a Python code architect, reviewing and designing scalable and efficient code
def tell_async(self, data, timeout=10, mime=None): """Asyncronous version of [tell()](./RemotePoint.m.html#IoticAgent.IOT.RemotePoint.RemoteControl.tell) `Note` payload contains the success and reason keys they are not separated out as in the synchronous version """ logger.info("tell(ti...
Create a Python 3 function for sending a request to the remote point to tell it.
You are a Python code analyst, evaluating scripts for potential improvements.
Rename the Point. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) if there is a communications problem b...
Given the following Python 3 function, write the documentation def rename(self, new_pid): logger.info("rename(new_pid=\"%s\") [lid=%s, pid=%s]", new_pid, self.__lid, self.__pid) evt = self._client._request_point_rename(self._type, self.__lid, self.__pid, new_pid) self._client._wait_and_except_if...
As a Python code composer, you craft elegant and concise scripts.
List all the values on this Point.
How would you explain what the following Python 3 function does def list(self, limit=50, offset=0): logger.info("list(limit=%s, offset=%s) [lid=%s,pid=%s]", limit, offset, self.__lid, self.__pid) evt = self._client._request_point_value_list(self.__lid, self.__pid, self._type, limit=limit, offset=offset)...
As a Python code translator, you convert algorithms and pseudocode into Python.
list followers for this point
Explain what the following Python 3 code does def list_followers(self): evt = self._client._request_point_list_detailed(self._type, self.__lid, self.__pid) self._client._wait_and_except_if_failed(evt) return evt.payload['subs']
You are a Python code analyst, evaluating scripts for potential improvements.
Get the metadata object for this Point
Make a summary of the following Python 3 code def get_meta(self): rdf = self.get_meta_rdf(fmt='n3') return PointMeta(self, rdf, self._client.default_lang, fmt='n3')
As a python code expert, you are capable of creating scripts from specifications.
Get the metadata for this Point in rdf fmt
How would you explain what the following Python 3 function does def get_meta_rdf(self, fmt='n3'): evt = self._client._request_point_meta_get(self._type, self.__lid, self.__pid, fmt=fmt) self._client._wait_and_except_if_failed(evt) return evt.payload['meta']
You are a Python code analyst, evaluating scripts for potential improvements.
Set the metadata for this Point in rdf fmt
Can you tell what is the following Python 3 function doing def set_meta_rdf(self, rdf, fmt='n3'): evt = self._client._request_point_meta_set(self._type, self.__lid, self.__pid, rdf, fmt=fmt) self._client._wait_and_except_if_failed(evt)
You are a Python code architect, reviewing and designing scalable and efficient code
Create tags for a Point in the language you specify.
Can you generate a brief explanation for the following Python 3 code def create_tag(self, tags): if isinstance(tags, str): tags = [tags] evt = self._client._request_point_tag_update(self._type, self.__lid, self.__pid, tags, delete=False) self._client._wait_and_except_if_failed(evt)
You are a Python code generator, capable of creating scripts from specifications.
def delete_tag(self, tags): """Delete tags for a Point in the language you specify. Case will be ignored and any tags matching lower-cased will be deleted. Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detect...
Create a Python 3 function for deleting tags for a Point in the language you specify. Case will be ignored and any tags matching lower - cased will be deleted.
You are a Python code architect, reviewing and designing scalable and efficient code
def list_tag(self, limit=50, offset=0): """List `all` the tags for this Point Returns list of tags, as below #!python [ "mytag1", "mytag2" "ein_name", "nochein_name" ] - OR... Raises [...
Implement a function in Python 3 to list all the tags for this Point.
As a Python code analyst, you investigate and solve complex coding mysteries
def create_value(self, label, vtype, lang=None, description=None, unit=None): """Create a value on this Point. Values are descriptions in semantic metadata of the individual data items you are sharing (or expecting to receive, if this Point is a control). This will help others to search for yo...
Write a Python 3 function for creating a value on this Point.
You are a Python code architect, reviewing and designing scalable and efficient code
Delete the labelled value on this Point
Explain what the following Python 3 code does def delete_value(self, label=None): evt = self._client._request_point_value_delete(self.__lid, self.__pid, self._type, label=label) self._client._wait_and_except_if_failed(evt)
As a Python code composer, you craft elegant and concise scripts.
Share some data from this Feed and return the ID of the new entry in the Feed.
Explain what the following Python 3 code does def share(self, data, mime=None, time=None): evt = self.share_async(data, mime=mime, time=time) self._client._wait_and_except_if_failed(evt)
As a python code expert, you are capable of creating scripts from specifications.
Retrieves statistics and configuration about recent storage for this Feed.
How would you explain what the following Python 3 function does def get_recent_info(self): evt = self._client._request_point_recent_info(self._type, self.lid, self.pid) self._client._wait_and_except_if_failed(evt) return evt.payload['recent']
You are a Python code generator, capable of creating scripts from specifications.
def set_recent_config(self, max_samples=0): """Update/configure recent data settings for this Feed. If the container does not support recent storage or it is not enabled for this owner, this function will have no effect. `max_samples` (optional) (int) how many shares to store for later retrieva...
How would you implement a function in Python 3 that updates or configure recent data settings for this Feed.
As a Python code composer, you craft elegant and concise scripts.
def filter_by(self, text=(), types=(), units=(), include_unset=False): """Return subset of values which match the given text, types and/or units. For a value to be matched, at least one item from each specified filter category has to apply to a value. Each of the categories must be specified as ...
Write a Python 3 script for returning subset of values which match the given text types and or units.
You are a Python code generator, capable of creating scripts from specifications.
def to_dict(self): """Converts the set of values into a dictionary. Unset values are excluded.""" return {value.label: value.value for value in self.__values if not value.unset}
Create a Python 3 function to convert the set of values into a dictionary. Unset values are excluded.
You are a Python code generator, capable of creating scripts from specifications.
Sets the infrastructure s metadata description back to the infrastructure.
Here you have a function in Python 3, explain what it does def set(self): self.__parent.set_meta_rdf(self._graph.serialize(format=self.__fmt).decode('utf8'), fmt=self.__fmt)
As a Python code analyst, you investigate and solve complex coding mysteries
def update(self): """Gets the latest version of your metadata from the infrastructure and updates your local copy Returns `True` if successful, `False` otherwise - OR - Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrast...
Write a Python 3 function that can get the latest version of your metadata from the infrastructure and updates your local copy
As a Python code composer, you craft elegant and concise scripts.
def set_label(self, label, lang=None): """Sets the `label` metadata property on your Thing/Point. Only one label is allowed per language, so any other labels in this language are removed before adding this one Raises `ValueError` containing an error message if the parameters fail validation ...
Implement a Python 3 function for setting the label metadata property on your Thing / Point.
As a Python code translator, you convert algorithms and pseudocode into Python.
def delete_label(self, lang=None): """Deletes all the `label` metadata properties on your Thing/Point for this language Raises `ValueError` containing an error message if the parameters fail validation `lang` (optional) (string) The two-character ISO 639-1 language code to identify your label....
Create a Python 3 function for deleting all the label metadata properties on your Thing / Point for this language
As a Python code composer, you craft elegant and concise scripts.
def set_description(self, description, lang=None): """Sets the `description` metadata property on your Thing/Point. Only one description is allowed per language, so any other descriptions in this language are removed before adding this one Raises `ValueError` containing an error message if the...
Create a Python 3 function for setting the description metadata property on your Thing / Point.
As a Python code analyst, you investigate and solve complex coding mysteries
Deletes all the label metadata properties on your Thing / Point for this language
Explain what the following Python 3 code does def delete_description(self, lang=None): self._remove_properties_by_language(self._commentPredicate, Validation.lang_check_convert(lang, default=self._default_lang))
You are a Python code architect, reviewing and designing scalable and efficient code
Returns True if obj is not None and its string representation is not 0 or False ( case - insensitive.
Given the following Python 3 function, write the documentation def bool_from(obj, default=False): return str(obj).lower() not in ('0', 'false') if obj is not None else bool(default)
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the private name for the given variable and class instance.
Given the following Python 3 function, write the documentation def private_name_for(var_name, cls): if not (isinstance(var_name, string_types) and var_name): raise TypeError('var_name must be non-empty string') if not (isinstance(cls, type) or isinstance(cls, string_types)): # pylint: disable=consider-...
You are a Python code generator, capable of creating scripts from specifications.
Returns iterable of private names using privateNameFor
Here you have a function in Python 3, explain what it does def private_names_for(cls, names): if not isinstance(names, Iterable): raise TypeError('names must be an interable') return (private_name_for(item, cls) for item in names)
You are a Python code generator, capable of creating scripts from specifications.
def set_config(self, config): ''' Set launch data from a ToolConfig. ''' if self.launch_url == None: self.launch_url = config.launch_url self.custom_params.update(config.custom_params)
Write a Python 3 script to set launch data from a ToolConfig.
As a python code expert, you are capable of creating scripts from specifications.
def has_required_params(self): ''' Check if required parameters for a tool launch are set. ''' return self.consumer_key and\ self.consumer_secret and\ self.resource_link_id and\ self.launch_url
Can you write a function in Python 3 where it checks if required parameters for a tool launch are set.
As a python code expert, you are capable of creating scripts from specifications.
def _sent_without_response(self, send_time_before): """Used internally to determine whether the request has not received any response from the container and was send before the given time. Unsent requests are not considered.""" return not self._messages and self._send_time and self._send_time...
Create a Python 3 function to use internally to determine whether the request has not received any response from the container before the given time.
As a Python code composer, you craft elegant and concise scripts.
Returns True if the request has finished False if it is still pending.
Can you tell what is the following Python 3 function doing def is_set(self): if self.__event.is_set(): if self.exception is not None: # todo better way to raise errors on behalf of other Threads? raise self.exception # pylint: disable=raising-bad-type ret...
As a Python code translator, you convert algorithms and pseudocode into Python.
Called internally by Client to indicate that this request has finished
Given the following Python 3 function, write the documentation def _set(self): self.__event.set() if self._complete_func: self.__run_completion_func(self._complete_func, self.id_)
As a python code expert, you are capable of creating scripts from specifications.
Function to call when the request has finished.
Can you generate a brief explanation for the following Python 3 code def _run_on_completion(self, func, *args, **kwargs): if self._complete_func is not None: raise ValueError('Completion function already set for %s: %s' % (self.id_, self._complete_func)) if not self.__event.is_set(): ...
As a Python code composer, you craft elegant and concise scripts.
Wait for the request to finish optionally timing out. Returns True if the request has finished False otherwise.
Can you tell what is the following Python 3 function doing def wait(self, timeout=None): if self.__event.wait(timeout): if self.exception is not None: # todo better way to raise errors on behalf of other Threads? raise self.exception # pylint: disable=raising-bad-typ...
As a python code expert, you are capable of creating scripts from specifications.
Checks that the required middleware dependencies exist and in the correct order.
Explain what the following Python 3 code does def _check_middleware_dependencies(concerned_object, required_middleware): declared_middleware = getattr(settings, 'MIDDLEWARE', None) if declared_middleware is None: declared_middleware = settings.MIDDLEWARE_CLASSES # Django 1.8 support # Filter out a...
As a Python code analyst, you investigate and solve complex coding mysteries
Validates an OAuth request using the python - oauth2 library.
Explain what the following Python 3 code does def is_valid_request(self, request, parameters={}, fake_method=None, handle_error=True): ''' Validates an OAuth request using the python-oauth2 library: https://github.com/simplegeo/python-oauth2 ''' try:...
You are a Python code analyst, evaluating scripts for potential improvements.
Parse Django request and return a tuple of the method and parameters.
Can you generate the documentation for the following Python 3 function def parse_request(self, request, parameters, fake_method=None): ''' Parse Django request ''' return (fake_method or request.method, request.build_absolute_uri(), request.META, ...
You are a Python code generator, capable of creating scripts from specifications.
def parse_request(self, request, parameters=None, fake_method=None): ''' Parse WebOb request ''' return (request.method, request.url, request.headers, request.POST.mixed())
Create a Python 3 function to parse a webob request and return a tuple of the HTTP method and HTTP parameters.
You are a Python code analyst, evaluating scripts for potential improvements.
Parse OutcomeResponse XML data form XML.
Given the following Python 3 function, write the documentation def process_xml(self, xml): ''' Parse OutcomeResponse data form XML. ''' try: root = objectify.fromstring(xml) # Get message idenifier from header info self.message_identifier = root.imsx_P...
You are a Python code architect, reviewing and designing scalable and efficient code
def generate_response_xml(self): ''' Generate XML based on the current configuration. ''' root = etree.Element( 'imsx_POXEnvelopeResponse', xmlns='http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0') header = etree.SubElement(root, 'imsx_POXHeader'...
How would you implement a function in Python 3 that generates XML based on the current configuration.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the value that can be used as a parameter value in a URL.
Can you generate the documentation for the following Python 3 function def _minimally_quoted_parameter_value(value): if re.match("^[{charset}]*$".format(charset=MediaType.RFC7320_TOKEN_CHARSET), value): return value else: return MediaType._quote(value)
You are a Python code analyst, evaluating scripts for potential improvements.
def set_custom_metrics_for_course_key(course_key): """ Set monitoring custom metrics related to a course key. This is not cached, and only support reporting to New Relic Insights. """ if not newrelic: return newrelic.agent.add_custom_parameter('course_id', six.text_type(course_key)) ...
Implement a function in Python 3 to set monitoring custom metrics related to a course key.
You are a Python code architect, reviewing and designing scalable and efficient code
Sets the transaction name for monitoring.
Can you generate a brief explanation for the following Python 3 code def set_monitoring_transaction_name(name, group=None, priority=None): if not newrelic: return newrelic.agent.set_transaction_name(name, group, priority)
As a python code expert, you are capable of creating scripts from specifications.
A generator that yields the code that we want to appear as a separate explicit segment in our monitoring tools.
Can you generate a brief explanation for the following Python 3 code def function_trace(function_name): if newrelic: nr_transaction = newrelic.agent.current_transaction() with newrelic.agent.FunctionTrace(nr_transaction, function_name): yield else: yield
You are a Python code generator, capable of creating scripts from specifications.
Fetch a Channel object identified by the numeric channel_id or create it if it doesn t already exist.
Make a summary of the following Python 3 code def channel(self, channel_id=None, auto_encode_decode=True): try: return self.channels[channel_id] except KeyError: return self.Channel(self, channel_id, auto_encode_decode=auto_encode_decode)
You are a Python code architect, reviewing and designing scalable and efficient code
Wait for an event on a channel.
Here you have a function in Python 3, explain what it does def drain_events(self, timeout=None): chanmap = self.channels chanid, method_sig, args, content = self._wait_multiple( chanmap, None, timeout=timeout, ) channel = chanmap[chanid] if (content and ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def close(self, reply_code=0, reply_text='', method_sig=(0, 0)): """Request a connection close This method indicates that the sender wants to close the connection. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e...
Create a Python 3 function for requesting a connection close to the broker.
As a Python code analyst, you investigate and solve complex coding mysteries
Return list of value labels filtered by either or both type and unit. An empty sequence for either argument will match as long as the other argument matches any values. An empty sequence for either argument will match as long as the other argument matches any values.
How would you explain what the following Python 3 function does def filter_by(self, types=(), units=()): if not (isinstance(types, Sequence) and isinstance(units, Sequence)): raise TypeError('types/units must be a sequence') empty = frozenset() if types: type_names = set...
You are a Python code analyst, evaluating scripts for potential improvements.
Get a new template which represents the values of this point in a .
Here you have a function in Python 3, explain what it does def get_template(self, data=None): # noqa (complexity) with self.__lock: if self.__value_templates is None and self.__last_parse_ok: try: self.__refresh() except RefreshException: ...
As a python code expert, you are capable of creating scripts from specifications.
Updates the local knowledge of values.
Can you generate the documentation for the following Python 3 function def __refresh(self): raw_values = self.__get_values() if not raw_values: raise RefreshException('Point has no values') # individual templates templates = [] # lookup tables by type and unit of val...
You are a Python code generator, capable of creating scripts from specifications.
Retrieve value information via describe or point value listing. MUST be called within lock.
Explain what the following Python 3 code does def __get_values(self): values = [] if self.__remote: description = self.__client.describe(self.__point) if description is not None: if description['type'] != 'Point': raise IOTUnknown('%s is not a...
As a python code expert, you are capable of creating scripts from specifications.
Returns the chunk size of the S3 multipart object given a file s size.
Given the following Python 3 function, write the documentation def get_s3_multipart_chunk_size(filesize): if filesize <= AWS_MAX_MULTIPART_COUNT * AWS_MIN_CHUNK_SIZE: return AWS_MIN_CHUNK_SIZE else: div = filesize // AWS_MAX_MULTIPART_COUNT if div * AWS_MAX_MULTIPART_COUNT < filesize: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def set_ext_param(self, ext_key, param_key, val): ''' Set the provided parameter in a set of extension parameters. ''' if not self.extensions[ext_key]: self.extensions[ext_key] = defaultdict(lambda: None) self.extensions[ext_key][param_key] = val
Write a Python 3 function that can set the provided parameter in a set of extension parameters.
As a Python code analyst, you investigate and solve complex coding mysteries
def get_ext_param(self, ext_key, param_key): ''' Get specific param in set of provided extension parameters. ''' return self.extensions[ext_key][param_key] if self.extensions[ext_key]\ else None
Implement a Python 3 function for getting specific parameter in set of provided extension parameters.
You are a Python code analyst, evaluating scripts for potential improvements.
def process_xml(self, xml): ''' Parse tool configuration data out of the Common Cartridge LTI link XML. ''' root = objectify.fromstring(xml, parser = etree.XMLParser()) # Parse all children of the root node for child in root.getchildren(): if 'title' in child....
Can you write a function in Python 3 where it parses the Common Cartridge LTI link XML.
You are a Python code analyst, evaluating scripts for potential improvements.
Generate XML from the current settings.
Given the following Python 3 function, write the documentation def to_xml(self, opts = defaultdict(lambda: None)): ''' Generate XML from the current settings. ''' if not self.launch_url or not self.secure_launch_url: raise InvalidLTIConfigError('Invalid LTI configuration') ...
You are a Python code analyst, evaluating scripts for potential improvements.
def create_widget(self): """ Create the underlying widget. """ d = self.declaration if d.orientation == 'vertical': self.widget = ScrollView(self.get_context(), None, d.style) else: self.widget = HorizontalScrollView(self.get_context(), ...
Implement a Python 3 function for creating the underlying widget.
As a Python code analyst, you investigate and solve complex coding mysteries
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = CalendarView(self.get_context(), None, d.style or "@attr/calendarViewStyle")
How would you implement a function in Python 3 that creates the underlying widget.
You are a Python code analyst, evaluating scripts for potential improvements.
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidCalendarView, self).init_widget() #: Setup listener w = self.widget w.setOnDateChangeListener(w.getId()) w.onSelectedDayChange.connect(self.on_selected_day_change)
Write a Python 3 script to initialize the underlying widget.
As a Python code analyst, you investigate and solve complex coding mysteries
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidFragment, self).init_widget() f = self.fragment f.setFragmentListener(f.getId()) f.onCreateView.connect(self.on_create_view) f.onDestroyView.connect(self.on_destroy_view)
Write a Python 3 script for initializing the underlying widget.
You are a Python code analyst, evaluating scripts for potential improvements.
Initialize the layout of the toolkit widget.
Make a summary of the following Python 3 code def init_layout(self): parent = self.parent() if parent is not None: self.adapter = parent.adapter self.adapter.addFragment(self.fragment)
As a Python code analyst, you investigate and solve complex coding mysteries
Get the page to display.
Make a summary of the following Python 3 code def get_view(self): d = self.declaration if d.cached and self.widget: return self.widget if d.defer_loading: self.widget = FrameLayout(self.get_context()) app = self.get_context() app.deferred_call( ...
You are a Python code generator, capable of creating scripts from specifications.