Instruction:
Write a Python 3 script for
computing and logs the difference in memory utilization between the given old and new memory data.

Response:
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 _process_mem_percent(memory_data):
            return memory_data['process_data']['memory_percent']

        def _process_rss(memory_data):
            return memory_data['process_data']['memory_info'].rss

        def _process_vms(memory_data):
            return memory_data['process_data']['memory_info'].vms

        if new_memory_data and old_memory_data:
            log.info(
                u"%s Diff Vmem used: %s, Diff percent memory: %s, Diff rss: %s, Diff vms: %s",
                prefix,
                _vmem_used(new_memory_data) - _vmem_used(old_memory_data),
                _process_mem_percent(new_memory_data) - _process_mem_percent(old_memory_data),
                _process_rss(new_memory_data) - _process_rss(old_memory_data),
                _process_vms(new_memory_data) - _process_vms(old_memory_data),
            )


Instruction:
Write a Python 3 script to
return the thread. local data dict for a given namespace.

Response:
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:
            return self._data[namespace]

        new_data = {}
        self._data[namespace] = new_data
        return new_data


Instruction:
Create a Python 3 function to
retrieve a CachedResponse for the provided key.

Response:
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_value is not _CACHE_MISS
        return CachedResponse(is_found, key, cached_value)


Instruction:
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)
            cls._set_request_cache_if_django_cache_hit(key, django_cached_response)
            return django_cached_response

        return request_cached_response

Response: Returns a CachedResponse for the provided key.


Instruction:
Create a Python 3 function to
set the value for the provided key in both the request cache and the django cache.

Response:
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 determine
                if and for how long to cache in the django cache. A timeout of
                0 will skip the django cache. If timeout is provided, use that
                timeout for the key; otherwise use the default cache timeout.

        """
        DEFAULT_REQUEST_CACHE.set(key, value)
        django_cache.set(key, value, django_cache_timeout)


Instruction:
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 = cached_value is not _CACHE_MISS
        return CachedResponse(is_found, key, cached_value)

Response: Returns a CachedResponse for the given key from the django cache.


Instruction:
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)

Response: Sets the value in the request cache if the django cached response was a hit.


Instruction:
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').lower() == 'true'
        DEFAULT_REQUEST_CACHE.set(SHOULD_FORCE_CACHE_MISS_KEY, force_cache_miss)

Response:
Gets value for request query parameter FORCE_CACHE_MISS
        and sets it in the default request cache.


Instruction:
Create a Python 3 function for
returning True if the tiered cache should force a cache miss for the django cache and False otherwise.

Response:
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_response.is_found else cached_response.value


Instruction:
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.

Response:
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)
        elif guid is None and allow_none:
            return None
        else:
            raise ValueError('guid must be a string')


Instruction:
Create a Python 3 function to
accept one tag as string or multiple tags in list of strings or raises ValueError

Response:
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):
            return [cls.__tag_check_convert(tags)]
        elif isinstance(tags, Sequence):
            if not tags:
                raise ValueError("Tag list is empty")
            return [cls.__tag_check_convert(tag) for tag in tags]
        else:
            raise ValueError("tags must be a single string or list of sequence of strings")


Instruction:
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))

Response: Checks if the given URL is a valid URL.


Instruction:
Write a Python 3 function for
checking that the latitude and longitude are valid.

Response:
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 ValueError("Longitude: '{longitude}' invalid".format(longitude=lon))


Instruction:
Write a Python 3 function for
coring Client. request_search location parameter should be a dictionary that contains lat lon and radius floats

Response:
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 should be mapping with keys: %s' % _LOCATION_SEARCH_ARGS)

        cls.location_check(location['lat'], location['long'])
        radius = location['radius']
        if not (isinstance(radius, number_types) and 0 < radius <= 20038):  # half circumference
            raise ValueError("Radius: '{radius}' is invalid".format(radius=radius))


Instruction:
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" % VALIDATION_META_SEARCH_TEXT)
        text = ' '.join(_PATTERN_WORDS.findall(text))
        if not text:
            raise ValueError('Search text must contain at least one non-whitespace term (word)')
        return text

Response: Converts and keeps only words in text deemed to be valid


Instruction:
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.

Response:
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('callable cannot be None')
        elif not arg_checker(func, *[arg_value for _ in range(arg_count)]):
            raise ValueError('callable %s invalid (for %d arguments)' % (func, arg_count))


Instruction:
Write a Python 3 function that can
list all the feeds on this Thing.

Response:
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 [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
        if there is a communications problem between you and the infrastructure

        `limit` (optional) (integer) Return this many Point details

        `offset` (optional) (integer) Return Point details starting at this offset
        """
        return self.__list(R_FEED, limit=limit, offset=offset)['feeds']


Instruction:
How would you code a function in Python 3 to
list all the controls on this Thing.

Response:
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 [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
        if there is a communications problem between you and the infrastructure

        `limit` (optional) (integer) Return this many Point details

        `offset` (optional) (integer) Return Point details starting at this offset
        """
        return self.__list(R_CONTROL, limit=limit, offset=offset)['controls']


Instruction:
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 = new_lid
        self._client._notify_thing_lid_change(self.__lid, new_lid)

Response:
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.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 between you and the infrastructure

        `new_lid` (required) (string) the new local identifier of your Thing


Instruction:
Write a Python 3 script to
reassign the Thing from one agent to another.

Response:
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.

        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 between you and the infrastructure

        `new_epid` (required) (string) the new agent id to which your Thing should be assigned. If None,
        current agent will be chosen. If False, existing agent will be unassigned.
        """
        logger.info("reassign(new_epid=\"%s\") [lid=%s]", new_epid, self.__lid)
        evt = self._client._request_entity_reassign(self.__lid, new_epid)
        self._client._wait_and_except_if_failed(evt)


Instruction:
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)

Response: Create tags for a Thing in the language you specify.


Instruction:
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.

Response:
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 detects a problem

        Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
        if there is a communications problem between you and the infrastructure

        `tags` (mandatory) (list) - the list of tags you want to delete from your Thing, e.g.
        `["garden", "soil"]`
        """
        if isinstance(tags, str):
            tags = [tags]

        evt = self._client._request_entity_tag_update(self.__lid, tags, delete=True)
        self._client._wait_and_except_if_failed(evt)


Instruction:
Write a Python 3 script for
listing all the tags for this Thing

Response:
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 [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 between you and the infrastructure

        `limit` (optional) (integer) Return at most this many tags

        `offset` (optional) (integer) Return tags starting at this offset
        """
        evt = self._client._request_entity_tag_list(self.__lid, limit=limit, offset=offset)

        self._client._wait_and_except_if_failed(evt)
        return evt.payload['tags']


Instruction:
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')

Response: Get the metadata object for this Thing


Instruction:
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']

Response: Get the metadata for this Thing in rdf fmt


Instruction:
How would you code a function in Python 3 to
set the metadata for this Thing in RDF fmt

Response:
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.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 between you and the infrastructure

        `fmt` (optional) (string) The format of RDF you have sent.
        Valid formats are: "xml", "n3", "turtle"
        """
        evt = self._client._request_entity_meta_set(self.__lid, rdf, fmt=fmt)
        self._client._wait_and_except_if_failed(evt)


Instruction:
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)

Response: Get the details of a newly created feed.


Instruction:
Can you implement a function in Python 3 that
gets the details of a newly created control.

Response:
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`

        Returns a [Control](Point.m.html#IoticAgent.IOT.Point.Control) object,
        which corresponds to the cached entry for this local control id

        `pid` (required) (string) local identifier of your control.

        Raises `KeyError` if the control has not been newly created (or has already been retrieved by a previous call)
        """
        with self.__new_controls:
            try:
                return self.__new_controls.pop(pid)
            except KeyError as ex:
                raise_from(KeyError('Control %s not know as new' % pid), ex)


Instruction:
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)

Response: Create a new Feed for this Thing with a local point id pid.


Instruction:
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(callback_parsed, callback)
        return self.__create_point(R_CONTROL, pid, control_cb=callback)

Response: Create a new control for this Thing with a local point id and a control request.


Instruction:
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)

Response: Delete a feed identified by its local id.


Instruction:
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)

Response: Delete a control identified by its local id.


Instruction:
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('subscription for given args pending: %s' % str(key))
            new_subs[key] = None
        try:
            yield
        except:
            # don't preserve reference if request creation failed
            with new_subs:
                new_subs.pop(key, None)
            raise

Response: Used by __sub_make_request to save reference for pending sub request


Instruction:
Can you write a function in Python 3 where it
makes right subscription request depending on whether local or global - used by __sub*

Response:
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(ref):
                req = self._client._request_sub_create(self.__lid, foc, gpid, callback=callback)
        # local
        elif isinstance(gpid, Sequence) and len(gpid) == 2:
            ref = (foc, tuple(gpid))
            with self.__sub_add_reference(ref):
                req = self._client._request_sub_create_local(self.__lid, foc, *gpid, callback=callback)
        else:
            raise ValueError('gpid must be string or two-element tuple')

        req._run_on_completion(self.__sub_del_reference, ref)
        return req


Instruction:
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)

Response: 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.


Instruction:
Can you create a Python 3 function that
lists all the Points following this Thing and controls it s attached to the infrastructure.

Response:
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>": {
                    "id": "<Control GUID>",
                    "entityId":  "<Control's Thing GUID>",
                    "type": 3  # R_CONTROL from IoticAgent.Core.Const
                },
                "<Subscription GUID 2>": {
                    "id": "<Feed GUID>",
                    "entityId":  "<Feed's Thing GUID>",
                    "type": 2  # R_FEED from IoticAgent.Core.Const
            }

        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 between you and the infrastructure

        Note: For Things following a Point see
        [list_followers](./Point.m.html#IoticAgent.IOT.Point.Point.list_followers)
        """
        evt = self._client._request_sub_list(self.__lid, limit=limit, offset=offset)

        self._client._wait_and_except_if_failed(evt)
        return evt.payload['subs']


Instruction:
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]]
            with store:
                store[payload[P_LID]] = cls(self._client, payload[P_ENTITY_LID], payload[P_LID], payload[P_ID])
            logger.debug('Added %s: %s (for %s)', foc_to_str(payload[P_RESOURCE]), payload[P_LID],
                         payload[P_ENTITY_LID])

        elif payload[P_RESOURCE] == R_SUB:
            # local
            if P_POINT_ENTITY_LID in payload:
                key = (payload[P_POINT_TYPE], (payload[P_POINT_ENTITY_LID], payload[P_POINT_LID]))
            # global
            else:
                key = (payload[P_POINT_TYPE], payload[P_POINT_ID])

            new_subs = self.__new_subs
            with new_subs:
                if key in new_subs:
                    cls = RemoteFeed if payload[P_POINT_TYPE] == R_FEED else RemoteControl
                    new_subs[key] = cls(self._client, payload[P_ID], payload[P_POINT_ID], payload[P_ENTITY_LID])
                else:
                    logger.warning('Ignoring subscription creation for unexpected %s: %s',
                                   foc_to_str(payload[P_POINT_TYPE]), key[1])

        else:
            logger.error('Resource creation of type %d unhandled', payload[P_RESOURCE])

Response: Indirect callback for point & subscription creation responses


Instruction:
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)

Response: Wait for a method that matches our allowed_methods parameter and dispatch it.


Instruction:
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:
                if evt.is_set() or monotonic() >= timeout_time:
                    break
        self._client._except_if_failed(evt)

Response: Get the most recent items from the feed. Useful for testing purposes.


Instruction:
Write a Python 3 function that can
get the most recent entries for this entry.

Response:
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 (as described above) to the
        given function which must accept a single argument. Nothing is returned.
        """
        validate_nonnegative_int(count, 'count')
        Validation.callable_check(callback, allow_none=True)
        evt = self._client._request_sub_recent(self.subid, count=count)
        self._client._add_recent_cb_for(evt, callback)
        return evt


Instruction:
Implement a Python 3 function for
simulating the arrival of remote feeddata into the feed.

Response:
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 type of your data.  See:
        [share()](./Point.m.html#IoticAgent.IOT.Point.Feed.share)
        """
        self._client.simulate_feeddata(self.__pointid, data, mime)


Instruction:
Implement a function in Python 3 to
request a remote control to do something.

Response:
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)
        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 between you and the infrastructure

        `data` (mandatory) (as applicable) The data you want to share

        `mime` (optional) (string) The mime type of the data you're sharing.  See:
        [share()](./Point.m.html#IoticAgent.IOT.Point.Feed.share)
        """
        evt = self.ask_async(data, mime=mime)
        self._client._wait_and_except_if_failed(evt)


Instruction:
Can you create a Python 3 function that
orders a remote control to do something.

Response:
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}
            retval = r_thermostat.tell(data, timeout=10, mime=None)
            if retval is not True:
                print("Thermostat not reset - reason: {reason}".format(reason=retval))

        Returns True on success or else returns the reason (string) one of:

            #!python
            "timeout"     # The request-specified timeout has been reached.
            "unreachable" # The remote control is not associated with an agent
                          #     or is not reachable in some other way.
            "failed"      # The remote control indicates it did not perform
                          #     the request.

        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 between you and the infrastructure

        `data` (mandatory) (as applicable) The data you want to share

        `timeout` (optional) (int) Default 10.  The delay in seconds before your tell request times out.

        `mime` (optional) (string) See:
        [share()](./Point.m.html#IoticAgent.IOT.Point.Feed.share)
        """
        evt = self.tell_async(data, timeout=timeout, mime=mime)
        # No point in waiting longer than supplied timeout (as opposed to waiting for sync timeout)
        try:
            self._client._wait_and_except_if_failed(evt, timeout=timeout)
        except IOTSyncTimeout:
            return 'timeout'
        return True if evt.payload['success'] else evt.payload['reason']


Instruction:
Create a Python 3 function for
sending a request to the remote point to tell it.

Response:
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(timeout=%s) [subid=%s]", timeout, self.subid)
        if mime is None and isinstance(data, PointDataObject):
            data = data.to_dict()
        return self._client._request_sub_tell(self.subid, data, timeout, mime=mime)


Instruction:
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_failed(evt)
        self.__pid = new_pid

Response:
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 between you and the infrastructure

        `new_pid` (required) (string) the new local identifier of your Point


Instruction:
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)

        self._client._wait_and_except_if_failed(evt)
        return evt.payload['values']

Response: List all the values on this Point.


Instruction:
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']

Response: list followers for this point


Instruction:
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')

Response: Get the metadata object for this Point


Instruction:
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']

Response: Get the metadata for this Point in rdf fmt


Instruction:
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)

Response: Set the metadata for this Point in rdf fmt


Instruction:
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)

Response: Create tags for a Point in the language you specify.


Instruction:
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.

Response:
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 detects a problem

        Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
        if there is a communications problem between you and the infrastructure

        `tags` (mandatory) (list) - the list of tags you want to delete from your Point, e.g.
        ["garden", "soil"]
        """
        if isinstance(tags, str):
            tags = [tags]

        evt = self._client._request_point_tag_update(self._type, self.__lid, self.__pid, tags, delete=True)
        self._client._wait_and_except_if_failed(evt)


Instruction:
Implement a function in Python 3 to
list all the tags for this Point.

Response:
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 [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 between you and the infrastructure

        `limit` (optional) (integer) Return at most this many tags

        `offset` (optional) (integer) Return tags starting at this offset
        """
        evt = self._client._request_point_tag_list(self._type, self.__lid, self.__pid, limit=limit, offset=offset)

        self._client._wait_and_except_if_failed(evt)
        return evt.payload['tags']


Instruction:
Write a Python 3 function for
creating a value on this Point.

Response:
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
        your feed or control. If a value with the given label (and language) already exists, its fields are updated
        with the provided ones (or unset, if None).

        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 between you and the infrastructure

        `label` (mandatory) (string) the label for this value e.g. "Temperature".  The label must be unique for this
        Point.  E.g. You can't have two data values called "Volts" but you can have "volts1" and "volts2".

        `lang` (optional) (string) The two-character ISO 639-1 language code to use for the description. None means use
        the default language for your agent.
        See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__)

        `vtype` (mandatory) (xsd:datatype) the datatype of the data you are describing, e.g. dateTime
        We recommend you use a Iotic Labs-defined constant from
        [Datatypes](../Datatypes.m.html#IoticAgent.Datatypes.Datatypes) such as:
        [DECIMAL](../Datatypes.m.html#IoticAgent.Datatypes.DECIMAL)

        `description` (optional) (string) The longer descriptive text for this value.

        `unit` (optional) (ontology url) The url of the ontological description of the unit of your value
        We recommend you use a constant from  [Units](../Units.m.html#IoticAgent.Units.Units), such as:
        [CELSIUS](../Units.m.html#IoticAgent.Units.Units.CELSIUS)

            #!python
            # example with no units as time is unit-less
            my_feed.create_value("timestamp",
                                 Datatypes.DATETIME,
                                 "en",
                                 "time of reading")

            # example with a unit from the Units class
            my_feed.create_value("temperature",
                                 Datatypes.DECIMAL,
                                 "en",
                                 "Fish-tank temperature in celsius",
                                 Units.CELSIUS)
        """
        evt = self._client._request_point_value_create(self.__lid, self.__pid, self._type, label, vtype, lang,
                                                       description, unit)
        self._client._wait_and_except_if_failed(evt)


Instruction:
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)

Response: Delete the labelled value on this Point


Instruction:
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)

Response: Share some data from this Feed and return the ID of the new entry in the Feed.


Instruction:
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']

Response: Retrieves statistics and configuration about recent storage for this Feed.


Instruction:
How would you implement a function in Python 3 that
updates or configure recent data settings for this Feed.

Response:
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 retrieval. If not supported by container, this
        argument will be ignored. A value of zero disables this feature whilst a negative value requests the maximum
        sample store amount.

        Returns QAPI recent config function payload

            #!python
            {
                "maxSamples": 0
            }

        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 between you and the infrastructure
        """
        evt = self._client._request_point_recent_config(self._type, self.lid, self.pid, max_samples)

        self._client._wait_and_except_if_failed(evt)
        return evt.payload


Instruction:
Write a Python 3 script for
returning subset of values which match the given text types and or units.

Response:
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 a sequence of strings. If `include_unset` is set, unset values will also be considered."""
        if not (isinstance(text, Sequence) and all(isinstance(phrase, string_types) for phrase in text)):
            raise TypeError('text should be sequence of strings')
        values = ([self.__values[name] for name in self.__filter.filter_by(types=types, units=units)
                   if include_unset or not self.__values[name].unset]
                  if types or units else self.__values)
        if text:
            # avoid unexpected search by individual characters if a single string was specified
            if isinstance(text, string_types):
                text = (ensure_unicode(text),)
            text = [phrase.lower() for phrase in text]
            new_values = []
            for value in values:
                label = value.label.lower()
                description = value.description.lower() if value.description else ''
                if any(phrase in label or (description and phrase in description) for phrase in text):
                    new_values.append(value)
            values = new_values

        return values


Instruction:
Create a Python 3 function to
convert the set of values into a dictionary. Unset values are excluded.

Response:
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}


Instruction:
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)

Response: Sets the infrastructure s metadata description back to the infrastructure.


Instruction:
Write a Python 3 function that can
get the latest version of your metadata from the infrastructure and updates your local copy

Response:
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 infrastructure detects a problem

        Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
        if there is a communications problem between you and the infrastructure
        """
        graph = Graph()
        graph.parse(data=self.__parent.get_meta_rdf(fmt=self.__fmt), format=self.__fmt)
        self._graph = graph


Instruction:
Implement a Python 3 function for
setting the label metadata property on your Thing / Point.

Response:
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

        `label` (mandatory) (string) the new text of the label

        `lang` (optional) (string) The two-character ISO 639-1 language code to use for your label.
        None means use the default language for your agent.
        See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__)
        """
        label = Validation.label_check_convert(label)
        lang = Validation.lang_check_convert(lang, default=self._default_lang)
        # remove any other labels with this language before adding
        self.delete_label(lang)
        subj = self._get_uuid_uriref()
        self._graph.add((subj, self._labelPredicate, Literal(label, lang)))


Instruction:
Create a Python 3 function for
deleting all the label metadata properties on your Thing / Point for this language

Response:
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.
        None means use the default language for your agent.
        See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__)
        """
        self._remove_properties_by_language(self._labelPredicate,
                                            Validation.lang_check_convert(lang, default=self._default_lang))


Instruction:
Create a Python 3 function for
setting the description metadata property on your Thing / Point.

Response:
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 parameters fail validation

        `description` (mandatory) (string) the new text of the description

        `lang` (optional) (string) The two-character ISO 639-1 language code to use for your label.
        None means use the default language for your agent.
        See [Config](./Config.m.html#IoticAgent.IOT.Config.Config.__init__)
        """
        description = Validation.description_check_convert(description)
        lang = Validation.lang_check_convert(lang, default=self._default_lang)
        # remove any other descriptions with this language before adding
        self.delete_description(lang)
        subj = self._get_uuid_uriref()
        self._graph.add((subj, self._commentPredicate, Literal(description, lang)))


Instruction:
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))

Response: Deletes all the label metadata properties on your Thing / Point for this language


Instruction:
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)

Response: Returns True if obj is not None and its string representation is not 0 or False ( case - insensitive.


Instruction:
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-merging-isinstance
        raise TypeError('cls not a class or string')
    if __PRIVATE_NAME_PATTERN.match(var_name):
        class_name = cls.__name__ if isinstance(cls, type) else cls
        return '_%s%s' % (class_name.lstrip('_'), var_name)
    else:
        return var_name

Response: Returns the private name for the given variable and class instance.


Instruction:
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)

Response: Returns iterable of private names using privateNameFor


Instruction:
Write a Python 3 script to
set launch data from a ToolConfig.

Response:
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)


Instruction:
Can you write a function in Python 3 where it
checks if required parameters for a tool launch are set.

Response:
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


Instruction:
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.

Response:
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 < send_time_before


Instruction:
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
            return True
        return False

Response: Returns True if the request has finished False if it is still pending.


Instruction:
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_)

Response: Called internally by Client to indicate that this request has finished


Instruction:
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():
            self._complete_func = partial(func, self, *args, **kwargs)
        else:
            self.__run_completion_func(partial(func, self, *args, **kwargs), self.id_)

Response: Function to call when the request has finished.


Instruction:
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-type
            return True
        return False

Response: Wait for the request to finish optionally timing out. Returns True if the request has finished False otherwise.


Instruction:
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 all the middleware except the ones we care about for ordering.
    matching_middleware = [mw for mw in declared_middleware if mw in required_middleware]
    if required_middleware != matching_middleware:
        raise AssertionError(
            "{} requires middleware order {} but matching middleware was {}".format(
                concerned_object, required_middleware, matching_middleware
            )
        )

Response: Checks that the required middleware dependencies exist and in the correct order.


Instruction:
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:
            # Set the parameters to be what we were passed earlier
            # if we didn't get any passed to us now
            if not parameters and hasattr(self, 'params'):
                parameters = self.params

            method, url, headers, parameters = self.parse_request(
                request, parameters, fake_method)

            oauth_request = oauth2.Request.from_request(
                method,
                url,
                headers=headers,
                parameters=parameters)

            self.oauth_server.verify_request(
                oauth_request, self.oauth_consumer, {})

        except oauth2.MissingSignature, e:
            if handle_error:
                return False
            else:
                raise e
        # Signature was valid
        return True

Response: Validates an OAuth request using the python - oauth2 library.


Instruction:
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,
                (dict(request.POST.iteritems())
                    if request.method == 'POST'
                    else parameters))

Response: Parse Django request and return a tuple of the method and parameters.


Instruction:
Create a Python 3 function to
parse a webob request and return a tuple of the HTTP method and HTTP parameters.

Response:
def parse_request(self, request, parameters=None, fake_method=None):
        '''
        Parse WebOb request
        '''
        return (request.method,
                request.url,
                request.headers,
                request.POST.mixed())


Instruction:
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_POXHeader.\
                imsx_POXResponseHeaderInfo.\
                imsx_messageIdentifier

            status_node = root.imsx_POXHeader.\
                imsx_POXResponseHeaderInfo.\
                imsx_statusInfo

            # Get status parameters from header info status
            self.code_major = status_node.imsx_codeMajor
            self.severity = status_node.imsx_severity
            self.description = status_node.imsx_description
            self.message_ref_identifier = str(
                status_node.imsx_messageRefIdentifier)
            self.operation = status_node.imsx_operationRefIdentifier

            try:
                # Try to get the score
                self.score = str(root.imsx_POXBody.readResultResponse.
                                 result.resultScore.textString)
            except AttributeError:
                # Not a readResult, just ignore!
                pass
        except:
            pass

Response: Parse OutcomeResponse XML data form XML.


Instruction:
How would you implement a function in Python 3 that
generates XML based on the current configuration.

Response:
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')
        header_info = etree.SubElement(header, 'imsx_POXResponseHeaderInfo')
        version = etree.SubElement(header_info, 'imsx_version')
        version.text = 'V1.0'
        message_identifier = etree.SubElement(header_info,
                                              'imsx_messageIdentifier')
        message_identifier.text = str(self.message_identifier)
        status_info = etree.SubElement(header_info, 'imsx_statusInfo')
        code_major = etree.SubElement(status_info, 'imsx_codeMajor')
        code_major.text = str(self.code_major)
        severity = etree.SubElement(status_info, 'imsx_severity')
        severity.text = str(self.severity)
        description = etree.SubElement(status_info, 'imsx_description')
        description.text = str(self.description)
        message_ref_identifier = etree.SubElement(
            status_info,
            'imsx_messageRefIdentifier')
        message_ref_identifier.text = str(self.message_ref_identifier)
        operation_ref_identifier = etree.SubElement(
            status_info,
            'imsx_operationRefIdentifier')
        operation_ref_identifier.text = str(self.operation)

        body = etree.SubElement(root, 'imsx_POXBody')
        response = etree.SubElement(body, '%s%s' % (self.operation,
                                                    'Response'))

        if self.score:
            result = etree.SubElement(response, 'result')
            result_score = etree.SubElement(result, 'resultScore')
            language = etree.SubElement(result_score, 'language')
            language.text = 'en'
            text_string = etree.SubElement(result_score, 'textString')
            text_string.text = str(self.score)

        return '<?xml version="1.0" encoding="UTF-8"?>' + etree.tostring(root)


Instruction:
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)

Response: Returns the value that can be used as a parameter value in a URL.


Instruction:
Implement a function in Python 3 to
set monitoring custom metrics related to a course key.

Response:
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))
    newrelic.agent.add_custom_parameter('org', six.text_type(course_key.org))


Instruction:
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)

Response: Sets the transaction name for monitoring.


Instruction:
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

Response: A generator that yields the code that we want to appear as a separate explicit segment in our monitoring tools.


Instruction:
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)

Response: Fetch a Channel object identified by the numeric channel_id or create it if it doesn t already exist.


Instruction:
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
                channel.auto_encode_decode and
                hasattr(content, 'content_encoding')):
            try:
                content.body = content.body.decode(content.content_encoding)
            except Exception:
                pass

        amqp_method = (self._method_override.get(method_sig) or
                       channel._METHOD_MAP.get(method_sig, None))

        if amqp_method is None:
            raise AMQPNotImplementedError(
                'Unknown AMQP method {0!r}'.format(method_sig))

        if content is None:
            return amqp_method(channel, args)
        else:
            return amqp_method(channel, args, content)

Response: Wait for an event on a channel.


Instruction:
Create a Python 3 function for
requesting a connection close to the broker.

Response:
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. an exception.  When a close is due to an
        exception, the sender provides the class and method id of the
        method which caused the exception.

        RULE:

            After sending this method any received method except the
            Close-OK method MUST be discarded.

        RULE:

            The peer sending this method MAY use a counter or timeout
            to detect failure of the other peer to respond correctly
            with the Close-OK method.

        RULE:

            When a server receives the Close method from a client it
            MUST delete all server-side resources associated with the
            client's context.  A client CANNOT reconnect to a context
            after sending or receiving a Close method.

        PARAMETERS:
            reply_code: short

                The reply code. The AMQ reply codes are defined in AMQ
                RFC 011.

            reply_text: shortstr

                The localised reply text.  This text can be logged as an
                aid to resolving issues.

            class_id: short

                failing method class

                When the close is provoked by a method exception, this
                is the class of the method.

            method_id: short

                failing method ID

                When the close is provoked by a method exception, this
                is the ID of the method.

        """
        if self.transport is None:
            # already closed
            return

        args = AMQPWriter()
        args.write_short(reply_code)
        args.write_shortstr(reply_text)
        args.write_short(method_sig[0])  # class_id
        args.write_short(method_sig[1])  # method_id
        try:
            self._send_method((10, 50), args)
            return self.wait(allowed_methods=[
                (10, 50),  # Connection.close
                (10, 51),  # Connection.close_ok
            ])
        except (socket.timeout, socket.error) as e:
            # no point in waiting anymore
            if isinstance(e, socket.timeout):
                try:
                    self.sock.settimeout(0.1)
                except:
                    pass
            # lack of communication should not prevent tidy-up
            self._do_close()


Instruction:
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()
            for type_ in types:
                type_names |= self.by_type.get(type_, empty)
            if not units:
                return type_names

        if units:
            unit_names = set()
            for unit in units:
                unit_names |= self.by_unit.get(unit, empty)
            if not types:
                return unit_names

        return (type_names & unit_names) if (types and units) else empty

Response:
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.


Instruction:
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:
                    # Point has no (useable) values - don't try to refetch again
                    self.__last_parse_ok = False
                    raise
            if self.__value_templates is None:
                raise ValueError('Point has no values')
            if data is None:
                template = PointDataObject(self.__value_templates, self.__filter)
            else:
                while True:
                    try:
                        template = PointDataObject._from_dict(self.__value_templates, self.__filter, data)
                    except:
                        # parsing has failed for first time since refresh so try again
                        if self.__last_parse_ok:
                            logger.debug('Failed to parse data from for point %s, refreshing', self.__point)
                            self.__last_parse_ok = False
                            try:
                                self.__refresh()
                            except RefreshException:
                                break
                        else:
                            raise
                    else:
                        self.__last_parse_ok = True
                        break
            return template

Response:
Get a new template which represents the values of this point in a
       .


Instruction:
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 value
        by_type = {}
        by_unit = {}

        for raw_value in raw_values:
            label = raw_value['label']
            if not valid_identifier(label) or label.startswith('__'):
                raise RefreshException('Value "%s" unsuitable for object wrapper' % label)
            value = Value(label, raw_value['type'], raw_value['unit'], raw_value['comment'])
            templates.append(value)
            try:
                by_type[value.type_].add(label)
            except KeyError:
                by_type[value.type_] = {label}
            if value.unit:
                try:
                    by_unit[value.unit].add(label)
                except KeyError:
                    by_unit[value.unit] = {label}

        self.__value_templates = templates
        self.__filter = _ValueFilter(by_type, by_unit)

Response: Updates the local knowledge of values.


Instruction:
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 Point' % self.__point)
                values = description['meta']['values']
        else:
            limit = 100
            offset = 0
            while True:
                new = self.__point.list(limit=limit, offset=offset)
                values += new
                if len(new) < limit:
                    break
                offset += limit

            # Unlike for describe, value comments are keyed by language here, so unwrap to have same layout as for
            # describe call (default language only, if available).
            lang = self.__client.default_lang
            for value in values:
                value['comment'] = value['comment'].get(lang, None) if value['comment'] else None

        return values

Response: Retrieve value information via describe or point value listing. MUST be called within lock.


Instruction:
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:
            div += 1
        return ((div + MiB - 1) // MiB) * MiB

Response: Returns the chunk size of the S3 multipart object given a file s size.


Instruction:
Write a Python 3 function that can
set the provided parameter in a set of extension parameters.

Response:
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


Instruction:
Implement a Python 3 function for
getting specific parameter in set of provided extension parameters.

Response:
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


Instruction:
Can you write a function in Python 3 where it
parses the Common Cartridge LTI link XML.

Response:
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.tag:
                self.title = child.text
            if 'description' in child.tag:
                self.description = child.text
            if 'secure_launch_url' in child.tag:
                self.secure_launch_url = child.text
            elif 'launch_url' in child.tag:
                self.launch_url = child.text
            if 'icon' in child.tag:
                self.icon = child.text
            if 'secure_icon' in child.tag:
                self.secure_icon = child.text
            if 'cartridge_bundle' in child.tag:
                self.cartridge_bundle = child.attrib['identifierref']
            if 'catridge_icon' in child.tag:
                self.cartridge_icon = child.atrib['identifierref']

            if 'vendor' in child.tag:
                # Parse vendor tag
                for v_child in child.getchildren():
                    if 'code' in v_child.tag:
                        self.vendor_code = v_child.text
                    if 'description' in v_child.tag:
                        self.vendor_description = v_child.text
                    if 'name' in v_child.tag:
                        self.vendor_name = v_child.text
                    if 'url' in v_child.tag:
                        self.vendor_url = v_child.text
                    if 'contact' in v_child.tag:
                        # Parse contact tag for email and name
                        for c_child in v_child:
                            if 'name' in c_child.tag:
                                self.vendor_contact_name = c_child.text
                            if 'email' in c_child.tag:
                                self.vendor_contact_email = c_child.text

            if 'custom' in child.tag:
                # Parse custom tags
                for custom_child in child.getchildren():
                    self.custom_params[custom_child.attrib['name']] =\
                            custom_child.text

            if 'extensions' in child.tag:
                platform = child.attrib['platform']
                properties = {}

                # Parse extension tags
                for ext_child in child.getchildren():
                    if 'property' in ext_child.tag:
                        properties[ext_child.attrib['name']] = ext_child.text
                    elif 'options' in ext_child.tag:
                        opt_name = ext_child.attrib['name']
                        options = {}
                        for option_child in ext_child.getchildren():
                            options[option_child.attrib['name']] =\
                                    option_child.text
                        properties[opt_name] = options

                self.set_ext_params(platform, properties)


Instruction:
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')

        root = etree.Element('cartridge_basiclti_link', attrib = {
                    '{%s}%s' %(NSMAP['xsi'], 'schemaLocation'): 'http://www.imsglobal.org/xsd/imslticc_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticc_v1p0.xsd http://www.imsglobal.org/xsd/imsbasiclti_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imsbasiclti_v1p0p1.xsd http://www.imsglobal.org/xsd/imslticm_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticm_v1p0.xsd http://www.imsglobal.org/xsd/imslticp_v1p0 http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticp_v1p0.xsd',
                    'xmlns': 'http://www.imsglobal.org/xsd/imslticc_v1p0'
                    }, nsmap = NSMAP)

        for key in ['title', 'description', 'launch_url', 'secure_launch_url']:
            option = etree.SubElement(root, '{%s}%s' %(NSMAP['blti'], key))
            option.text = getattr(self, key)

        vendor_keys = ['name', 'code', 'description', 'url']
        if any('vendor_' + key for key in vendor_keys) or\
                self.vendor_contact_email:
                    vendor_node = etree.SubElement(root, '{%s}%s'
                            %(NSMAP['blti'], 'vendor'))
                    for key in vendor_keys:
                        if getattr(self, 'vendor_' + key) != None:
                            v_node = etree.SubElement(vendor_node,
                                    '{%s}%s' %(NSMAP['lticp'], key))
                            v_node.text = getattr(self, 'vendor_' + key)
                    if getattr(self, 'vendor_contact_email'):
                        v_node = etree.SubElement(vendor_node,
                                '{%s}%s' %(NSMAP['lticp'], 'contact'))
                        c_name = etree.SubElement(v_node,
                                '{%s}%s' %(NSMAP['lticp'], 'name'))
                        c_name.text = self.vendor_contact_name
                        c_email = etree.SubElement(v_node,
                                '{%s}%s' %(NSMAP['lticp'], 'email'))
                        c_email.text = self.vendor_contact_email

        # Custom params
        if len(self.custom_params) != 0:
            custom_node = etree.SubElement(root, '{%s}%s' %(NSMAP['blti'],
                'custom'))
            for (key, val) in sorted(self.custom_params.items()):
                c_node = etree.SubElement(custom_node, '{%s}%s'
                        %(NSMAP['lticm'], 'property'))
                c_node.set('name', key)
                c_node.text = val

        # Extension params
        if len(self.extensions) != 0:
            for (key, params) in sorted(self.extensions.items()):
                extension_node = etree.SubElement(root, '{%s}%s' %(NSMAP['blti'],
                    'extensions'), platform = key)
                self.recursive_options(extension_node,params)

        if getattr(self, 'cartridge_bundle'):
            identifierref = etree.SubElement(root, 'cartridge_bundle',
                    identifierref = self.cartridge_bundle)

        if getattr(self, 'cartridge_icon'):
            identifierref = etree.SubElement(root, 'cartridge_icon',
                    identifierref = self.cartridge_icon)

        return '<?xml version="1.0" encoding="UTF-8"?>' + etree.tostring(root)

Response: Generate XML from the current settings.


Instruction:
Implement a Python 3 function for
creating the underlying widget.

Response:
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(),
                                               None, d.style)


Instruction:
How would you implement a function in Python 3 that
creates the underlying widget.

Response:
def create_widget(self):
        """ Create the underlying widget.

        """
        d = self.declaration
        self.widget = CalendarView(self.get_context(), None,
                                   d.style or "@attr/calendarViewStyle")


Instruction:
Write a Python 3 script to
initialize the underlying widget.

Response:
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)


Instruction:
Write a Python 3 script for
initializing the underlying widget.

Response:
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)


Instruction:
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)

Response: Initialize the layout of the toolkit widget.


Instruction:
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(
                 lambda: self.widget.addView(self.load_view(), 0))
        else:
            self.widget = self.load_view()
        return self.widget

Response: Get the page to display.


Instruction:
How would you code a function in Python 3 to
initialize the underlying widget.

Response:
def init_widget(self):
        """ Initialize the underlying widget.

        """
        super(AndroidPagerFragment, self).init_widget()
        d = self.declaration
        if d.title:
            self.set_title(d.title)
        if d.icon:
            self.set_icon(d.icon)


Instruction:
Explain what the following Python 3 code does
def engine(func):
    func = _make_coroutine_wrapper(func, replace_callback=False)

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        future = func(*args, **kwargs)

        def final_callback(future):
            if future.result() is not None:
                raise ReturnValueIgnoredError(
                    "@gen.engine functions cannot return values: %r" %
                    (future.result(),))
        # The engine interface doesn't give us any way to return
        # errors but to raise them into the stack context.
        # Save the stack context here to use when the Future has resolved.
        future.add_done_callback(stack_context.wrap(final_callback))
    return wrapper

Response: Decorator for asynchronous generators.


Instruction:
Can you generate the documentation for the following Python 3 function
def _make_coroutine_wrapper(func, replace_callback):
    # On Python 3.5, set the coroutine flag on our generator, to allow it
    # to be used with 'await'.
    wrapped = func
    if hasattr(types, 'coroutine'):
        func = types.coroutine(func)

    @functools.wraps(wrapped)
    def wrapper(*args, **kwargs):
        future = TracebackFuture()

        if replace_callback and 'callback' in kwargs:
            callback = kwargs.pop('callback')
            IOLoop.current().add_future(
                future, lambda future: callback(future.result()))

        try:
            result = func(*args, **kwargs)
        except (Return, StopIteration) as e:
            result = _value_from_stopiteration(e)
        except Exception:
            future.set_exc_info(sys.exc_info())
            return future
        else:
            if isinstance(result, GeneratorType):
                # Inline the first iteration of Runner.run.  This lets us
                # avoid the cost of creating a Runner when the coroutine
                # never actually yields, which in turn allows us to
                # use "optional" coroutines in critical path code without
                # performance penalty for the synchronous case.
                try:
                    orig_stack_contexts = stack_context._state.contexts
                    yielded = next(result)
                    if stack_context._state.contexts is not orig_stack_contexts:
                        yielded = TracebackFuture()
                        yielded.set_exception(
                            stack_context.StackContextInconsistentError(
                                'stack_context inconsistency (probably caused '
                                'by yield within a "with StackContext" block)'))
                except (StopIteration, Return) as e:
                    future.set_result(_value_from_stopiteration(e))
                except Exception:
                    future.set_exc_info(sys.exc_info())
                else:
                    _futures_to_runners[future] = Runner(result, future, yielded)
                yielded = None
                try:
                    return future
                finally:
                    # Subtle memory optimization: if next() raised an exception,
                    # the future's exc_info contains a traceback which
                    # includes this stack frame.  This creates a cycle,
                    # which will be collected at the next full GC but has
                    # been shown to greatly increase memory usage of
                    # benchmarks (relative to the refcount-based scheme
                    # used in the absence of cycles).  We can avoid the
                    # cycle by clearing the local variable after we return it.
                    future = None
        future.set_result(result)
        return future

    wrapper.__wrapped__ = wrapped
    wrapper.__tornado_coroutine__ = True
    return wrapper

Response: A function decorator that wraps a coroutine function.


Instruction:
Can you tell what is the following Python 3 function doing
def Task(func, *args, **kwargs):
    future = Future()

    def handle_exception(typ, value, tb):
        if future.done():
            return False
        future.set_exc_info((typ, value, tb))
        return True

    def set_result(result):
        if future.done():
            return
        future.set_result(result)
    with stack_context.ExceptionStackContext(handle_exception):
        func(*args, callback=_argument_adapter(set_result), **kwargs)
    return future

Response: Adapts a callback - based asynchronous function for use in coroutines.


Instruction:
How would you explain what the following Python 3 function does
def _contains_yieldpoint(children):
    if isinstance(children, dict):
        return any(isinstance(i, YieldPoint) for i in children.values())
    if isinstance(children, list):
        return any(isinstance(i, YieldPoint) for i in children)
    return False

Response: Returns True if children contains any YieldPoints.


Instruction:
How would you implement a function in Python 3 that
runs multiple asynchronous operations in parallel.

Response:
def multi(children, quiet_exceptions=()):
    """Runs multiple asynchronous operations in parallel.

    ``children`` may either be a list or a dict whose values are
    yieldable objects. ``multi()`` returns a new yieldable
    object that resolves to a parallel structure containing their
    results. If ``children`` is a list, the result is a list of
    results in the same order; if it is a dict, the result is a dict
    with the same keys.

    That is, ``results = yield multi(list_of_futures)`` is equivalent
    to::

        results = []
        for future in list_of_futures:
            results.append(yield future)

    If any children raise exceptions, ``multi()`` will raise the first
    one. All others will be logged, unless they are of types
    contained in the ``quiet_exceptions`` argument.

    If any of the inputs are `YieldPoints <YieldPoint>`, the returned
    yieldable object is a `YieldPoint`. Otherwise, returns a `.Future`.
    This means that the result of `multi` can be used in a native
    coroutine if and only if all of its children can be.

    In a ``yield``-based coroutine, it is not normally necessary to
    call this function directly, since the coroutine runner will
    do it automatically when a list or dict is yielded. However,
    it is necessary in ``await``-based coroutines, or to pass
    the ``quiet_exceptions`` argument.

    This function is available under the names ``multi()`` and ``Multi()``
    for historical reasons.

    .. versionchanged:: 4.2
       If multiple yieldables fail, any exceptions after the first
       (which is raised) will be logged. Added the ``quiet_exceptions``
       argument to suppress this logging for selected exception types.

    .. versionchanged:: 4.3
       Replaced the class ``Multi`` and the function ``multi_future``
       with a unified function ``multi``. Added support for yieldables
       other than `YieldPoint` and `.Future`.

    """
    if _contains_yieldpoint(children):
        return MultiYieldPoint(children, quiet_exceptions=quiet_exceptions)
    else:
        return multi_future(children, quiet_exceptions=quiet_exceptions)


Instruction:
Can you tell what is the following Python 3 function doing
def multi_future(children, quiet_exceptions=()):
    if isinstance(children, dict):
        keys = list(children.keys())
        children = children.values()
    else:
        keys = None
    children = list(map(convert_yielded, children))
    assert all(is_future(i) for i in children)
    unfinished_children = set(children)

    future = Future()
    if not children:
        future.set_result({} if keys is not None else [])

    def callback(f):
        unfinished_children.remove(f)
        if not unfinished_children:
            result_list = []
            for f in children:
                try:
                    result_list.append(f.result())
                except Exception as e:
                    if future.done():
                        if not isinstance(e, quiet_exceptions):
                            app_log.error("Multiple exceptions in yield list",
                                          exc_info=True)
                    else:
                        future.set_exc_info(sys.exc_info())
            if not future.done():
                if keys is not None:
                    future.set_result(dict(zip(keys, result_list)))
                else:
                    future.set_result(result_list)

    listening = set()
    for f in children:
        if f not in listening:
            listening.add(f)
            f.add_done_callback(callback)
    return future

Response: Wait for multiple asynchronous futures in parallel.


Instruction:
Create a Python 3 function for
converting x into a Future.

Response:
def maybe_future(x):
    """Converts ``x`` into a `.Future`.

    If ``x`` is already a `.Future`, it is simply returned; otherwise
    it is wrapped in a new `.Future`.  This is suitable for use as
    ``result = yield gen.maybe_future(f())`` when you don't know whether
    ``f()`` returns a `.Future` or not.

    .. deprecated:: 4.3
       This function only handles ``Futures``, not other yieldable objects.
       Instead of `maybe_future`, check for the non-future result types
       you expect (often just ``None``), and ``yield`` anything unknown.
    """
    if is_future(x):
        return x
    else:
        fut = Future()
        fut.set_result(x)
        return fut


Instruction:
Can you tell what is the following Python 3 function doing
def with_timeout(timeout, future, quiet_exceptions=()):
    # TODO: allow YieldPoints in addition to other yieldables?
    # Tricky to do with stack_context semantics.
    #
    # It's tempting to optimize this by cancelling the input future on timeout
    # instead of creating a new one, but A) we can't know if we are the only
    # one waiting on the input future, so cancelling it might disrupt other
    # callers and B) concurrent futures can only be cancelled while they are
    # in the queue, so cancellation cannot reliably bound our waiting time.
    future = convert_yielded(future)
    result = Future()
    chain_future(future, result)
    io_loop = IOLoop.current()

    def error_callback(future):
        try:
            future.result()
        except Exception as e:
            if not isinstance(e, quiet_exceptions):
                app_log.error("Exception in Future %r after timeout",
                              future, exc_info=True)

    def timeout_callback():
        result.set_exception(TimeoutError("Timeout"))
        # In case the wrapped future goes on to fail, log it.
        future.add_done_callback(error_callback)
    timeout_handle = io_loop.add_timeout(
        timeout, timeout_callback)
    if isinstance(future, Future):
        # We know this future will resolve on the IOLoop, so we don't
        # need the extra thread-safety of IOLoop.add_future (and we also
        # don't care about StackContext here.
        future.add_done_callback(
            lambda future: io_loop.remove_timeout(timeout_handle))
    else:
        # concurrent.futures.Futures may resolve on any thread, so we
        # need to route them back to the IOLoop.
        io_loop.add_future(
            future, lambda future: io_loop.remove_timeout(timeout_handle))
    return result

Response: Wraps a tornado. util. Future in a timeout.


Instruction:
Here you have a function in Python 3, explain what it does
def sleep(duration):
    f = Future()
    IOLoop.current().call_later(duration, lambda: f.set_result(None))
    return f

Response: Return a new Future that resolves after the given number of seconds.


Instruction:
How would you explain what the following Python 3 function does
def _argument_adapter(callback):
    def wrapper(*args, **kwargs):
        if kwargs or len(args) > 1:
            callback(Arguments(args, kwargs))
        elif args:
            callback(args[0])
        else:
            callback(None)
    return wrapper

Response: Returns a function that when invoked runs callback with one argument.


Instruction:
Write a Python 3 script to
convert a yielded object into a tornado. Future.

Response:
def convert_yielded(yielded):
    """Convert a yielded object into a `.Future`.

    The default implementation accepts lists, dictionaries, and Futures.

    If the `~functools.singledispatch` library is available, this function
    may be extended to support additional types. For example::

        @convert_yielded.register(asyncio.Future)
        def _(asyncio_future):
            return tornado.platform.asyncio.to_tornado_future(asyncio_future)

    .. versionadded:: 4.1
    """
    # Lists and dicts containing YieldPoints were handled earlier.
    if yielded is None:
        return moment
    elif isinstance(yielded, (list, dict)):
        return multi(yielded)
    elif is_future(yielded):
        return yielded
    elif isawaitable(yielded):
        return _wrap_awaitable(yielded)
    else:
        raise BadYieldError("yielded unknown object %r" % (yielded,))


Instruction:
Given the following Python 3 function, write the documentation
def done(self):
        if self._finished or self._unfinished:
            return False
        # Clear the 'current' values when iteration is done.
        self.current_index = self.current_future = None
        return True

Response: Returns True if this iterator has no more results.


Instruction:
Can you create a Python 3 function that
returns a. Future that will yield the next available result.

Response:
def next(self):
        """Returns a `.Future` that will yield the next available result.

        Note that this `.Future` will not be the same object as any of
        the inputs.
        """
        self._running_future = TracebackFuture()

        if self._finished:
            self._return_result(self._finished.popleft())

        return self._running_future


Instruction:
Given the following Python 3 function, write the documentation
def _return_result(self, done):
        chain_future(done, self._running_future)

        self.current_future = done
        self.current_index = self._unfinished.pop(done)

Response: Called when the result of the iteration is done.


Instruction:
Implement a function in Python 3 to
add a callback to the list of pending callbacks.

Response:
def register_callback(self, key):
        """Adds ``key`` to the list of callbacks."""
        if self.pending_callbacks is None:
            # Lazily initialize the old-style YieldPoint data structures.
            self.pending_callbacks = set()
            self.results = {}
        if key in self.pending_callbacks:
            raise KeyReuseError("key %r is already pending" % (key,))
        self.pending_callbacks.add(key)


Instruction:
Can you tell what is the following Python 3 function doing
def is_ready(self, key):
        if self.pending_callbacks is None or key not in self.pending_callbacks:
            raise UnknownKeyError("key %r is not pending" % (key,))
        return key in self.results

Response: Returns true if a result is available for key.


Instruction:
Given the following Python 3 function, write the documentation
def set_result(self, key, result):
        self.results[key] = result
        if self.yield_point is not None and self.yield_point.is_ready():
            try:
                self.future.set_result(self.yield_point.get_result())
            except:
                self.future.set_exc_info(sys.exc_info())
            self.yield_point = None
            self.run()

Response: Sets the result for key and attempts to resume the generator.


Instruction:
Write a Python 3 script to
return the result for the given key. Unregisters the callback for the given key.

Response:
def pop_result(self, key):
        """Returns the result for ``key`` and unregisters it."""
        self.pending_callbacks.remove(key)
        return self.results.pop(key)