Instruction:
Can you create a Python 3 function that
reports the total progress for the current stack optionally given the local fraction completed.

Response:
def report(self, fraction=None):
		"""report the total progress for the current stack, optionally given the local fraction completed.
		fraction=None: if given, used as the fraction of the local method so far completed.
		runtimes=None: if given, used as the expected runtimes for the current stack.
		"""
		r = Dict()
		local_key = self.stack_key
		if local_key is None: return {}
		runtimes = self.runtimes()
		for key in self.stack_keys:
			if self.current_times.get(key) is None:
				self.start(key=key)
			runtime = runtimes.get(key) or self.runtime(key)
			if key == local_key and fraction is not None:
				r[key] = fraction
			elif runtime is not None:
				r[key] = (time() - self.current_times[key]) / runtime
		return r


Instruction:
Can you generate a brief explanation for the following Python 3 code
def finish(self):
		self.report(fraction=1.0)
		key = self.stack_key
		if key is not None:
			if self.data.get(key) is None:
				self.data[key] = []
			start_time = self.current_times.get(key) or time()
			self.data[key].append(Dict(runtime=time()-start_time, **self.params))

Response: record the current stack process as finished


Instruction:
Can you generate the documentation for the following Python 3 function
def add_directive_header(self, sig):
        domain = getattr(self, 'domain', 'py')
        directive = getattr(self, 'directivetype', "module")
        name = self.format_name()
        self.add_line(u'.. %s:%s:: %s%s' % (domain, directive, name, sig),
                      '<autodoc>')
        if self.options.noindex:
            self.add_line(u'   :noindex:', '<autodoc>')
        if self.objpath:
            # Be explicit about the module, this is necessary since .. class::
            # etc. don't support a prepended module name
            self.add_line(u'   :module: %s' % self.modname, '<autodoc>')

Response: Add the directive header and options to the generated content.


Instruction:
Create a Python 3 function to
initiate the connection to a proxying hub

Response:
def connect(self):
        "Initiate the connection to a proxying hub"
        log.info("connecting")

        # don't have the connection attempt reconnects, because when it goes
        # down we are going to cycle to the next potential peer from the Client
        self._peer = connection.Peer(
                None, self._dispatcher, self._addrs.popleft(),
                backend.Socket(), reconnect=False)
        self._peer.start()


Instruction:
Implement a function in Python 3 to
wait for all the active connection and their handshakes to finish.

Response:
def wait_connected(self, timeout=None):
        '''Wait for connections to be made and their handshakes to finish

        :param timeout:
            maximum time to wait in seconds. with None, there is no timeout.
        :type timeout: float or None

        :returns:
            ``True`` if all connections were made, ``False`` if one or more
            failed.
        '''
        result = self._peer.wait_connected(timeout)
        if not result:
            if timeout is not None:
                log.warn("connect wait timed out after %.2f seconds" % timeout)
        return result


Instruction:
Implement a Python 3 function for
closing the current failed connection and prepare for a new one

Response:
def reset(self):
        "Close the current failed connection and prepare for a new one"
        log.info("resetting client")
        rpc_client = self._rpc_client
        self._addrs.append(self._peer.addr)
        self.__init__(self._addrs)
        self._rpc_client = rpc_client
        self._dispatcher.rpc_client = rpc_client
        rpc_client._client = weakref.ref(self)


Instruction:
Can you tell what is the following Python 3 function doing
def shutdown(self):
        'Close the hub connection'
        log.info("shutting down")
        self._peer.go_down(reconnect=False, expected=True)

Response: Close the hub connection


Instruction:
Can you implement a function in Python 3 that
sends a 1 - way message to the hub.

Response:
def publish(self, service, routing_id, method, args=None, kwargs=None,
            broadcast=False):
        '''Send a 1-way message

        :param service: the service name (the routing top level)
        :type service: anything hash-able
        :param routing_id:
            The id used for routing within the registered handlers of the
            service.
        :type routing_id: int
        :param method: the method name to call
        :type method: string
        :param args: the positional arguments to send along with the request
        :type args: tuple
        :param kwargs: keyword arguments to send along with the request
        :type kwargs: dict
        :param broadcast:
            if ``True``, send to every peer with a matching subscription
        :type broadcast: bool

        :returns: None. use 'rpc' methods for requests with responses.

        :raises:
            :class:`Unroutable <junction.errors.Unroutable>` if the client
            doesn't have a connection to a hub
        '''
        if not self._peer.up:
            raise errors.Unroutable()

        self._dispatcher.send_proxied_publish(service, routing_id, method,
                args or (), kwargs or {}, singular=not broadcast)


Instruction:
Write a Python 3 script for
getting the number of peers that would handle a particular publish

Response:
def publish_receiver_count(
            self, service, routing_id, method, timeout=None):
        '''Get the number of peers that would handle a particular publish

        This method will block until a response arrives

        :param service: the service name
        :type service: anything hash-able
        :param routing_id:
            the id used for narrowing within the service handlers
        :type routing_id: int
        :param method: the method name
        :type method: string
        :param timeout: maximum time to wait for the response
        :type timeout: int, float or None

        :raises:
            - :class:`Unroutable <junction.errors.Unroutable>` if no peers are
              registered to receive the message
            - :class:`WaitTimeout <junction.errors.WaitTimeout>` if a timeout
              was provided and it expires
        '''
        if not self._peer.up:
            raise errors.Unroutable()

        return self._rpc_client.recipient_count(self._peer,
                const.MSG_TYPE_PUBLISH, service, routing_id, method).wait(
                        timeout)[0]


Instruction:
Can you generate the documentation for the following Python 3 function
def send_rpc(self, service, routing_id, method, args=None, kwargs=None,
            broadcast=False):
        '''Send out an RPC request

        :param service: the service name (the routing top level)
        :type service: anything hash-able
        :param routing_id:
            The id used for routing within the registered handlers of the
            service.
        :type routing_id: int
        :param method: the method name to call
        :type method: string
        :param args: the positional arguments to send along with the request
        :type args: tuple
        :param kwargs: keyword arguments to send along with the request
        :type kwargs: dict
        :param broadcast:
            if ``True``, send to all peers with matching subscriptions
        :type broadcast: bool

        :returns:
            a :class:`RPC <junction.futures.RPC>` object representing the
            RPC and its future response.

        :raises:
            :class:`Unroutable <junction.errors.Unroutable>` if the client
            doesn't have a connection to a hub
        '''
        if not self._peer.up:
            raise errors.Unroutable()

        return self._dispatcher.send_proxied_rpc(service, routing_id, method,
                args or (), kwargs or {}, not broadcast)

Response: Send out an RPC request to all connected peers.


Instruction:
Can you generate the documentation for the following Python 3 function
def rpc_receiver_count(self, service, routing_id, method, timeout=None):
        '''Get the number of peers that would handle a particular RPC

        This method will block until a response arrives

        :param service: the service name
        :type service: anything hash-able
        :param routing_id:
            the id used for narrowing within the service handlers
        :type routing_id: int
        :param method: the method name
        :type method: string

        :returns:
            the integer number of peers that would receive the described RPC

        :raises:
            - :class:`Unroutable <junction.errors.Unroutable>` if no peers are
              registered to receive the message
            - :class:`WaitTimeout <junction.errors.WaitTimeout>` if a timeout
              was provided and it expires
        '''
        if not self._peer.up:
            raise errors.Unroutable()

        return self._rpc_client.recipient_count(self._peer,
                const.MSG_TYPE_RPC_REQUEST, service, routing_id, method).wait(
                        timeout)[0]

Response: Get the number of peers that would handle a particular RPC message. This method blocks until a response arrives.


Instruction:
Can you tell what is the following Python 3 function doing
def _headers(self, others={}):
        headers = {
            'Content-Type': 'application/json'
        }

        for p in others.keys():
            headers[p] = others[p]
        return headers

Response: Return the default headers and others as necessary


Instruction:
Make a summary of the following Python 3 code
def read(config_file, configspec, server_mode=False, default_section='default_settings', list_values=True):
    '''
    Read the config file with spec validation
    '''
#    configspec = ConfigObj(path.join(path.abspath(path.dirname(__file__)), configspec),
#                           encoding='UTF8',
#                           interpolation='Template',
#                           list_values=False,
#                           _inspec=True)
    config = ConfigObj(config_file,
                       configspec=path.join(path.abspath(path.dirname(__file__)),
                                            configspec),
                                            list_values=list_values)
    validation = config.validate(validate.Validator(), preserve_errors=True)

    if validation == True:
        config = dict(config)
        for section in config:
            if section != default_section:
                if server_mode: # When it's a servers config file, retrieve the correct fqdn
                    config[section]['availability'] = True
                    if config[section]['custom_fqdn'] == None:
                        config[section]['custom_fqdn'] = socket.getfqdn()
                for option in config[section]:  # retrieve default configuration for missing values
                    if config[section][option] == None:
                        config[section][option] = config[default_section][option]

        del(config[default_section])

        return config
    else:
        raise ConfiguratorException(config_file, validation)

Response: Read the config file with spec validation


Instruction:
Given the following Python 3 function, write the documentation
def pcolor(text, color, indent=0):
    esc_dict = {
        "black": 30,
        "red": 31,
        "green": 32,
        "yellow": 33,
        "blue": 34,
        "magenta": 35,
        "cyan": 36,
        "white": 37,
        "none": -1,
    }
    if not isinstance(text, str):
        raise RuntimeError("Argument `text` is not valid")
    if not isinstance(color, str):
        raise RuntimeError("Argument `color` is not valid")
    if not isinstance(indent, int):
        raise RuntimeError("Argument `indent` is not valid")
    color = color.lower()
    if color not in esc_dict:
        raise ValueError("Unknown color {color}".format(color=color))
    if esc_dict[color] != -1:
        return "\033[{color_code}m{indent}{text}\033[0m".format(
            color_code=esc_dict[color], indent=" " * indent, text=text
        )
    return "{indent}{text}".format(indent=" " * indent, text=text)

Response: r Colorize a string.


Instruction:
How would you code a function in Python 3 to
return a string with a frame record pretty - formatted.

Response:
def strframe(obj, extended=False):
    """
    Return a string with a frame record pretty-formatted.

    The record is typically an item in a list generated by `inspect.stack()
    <https://docs.python.org/3/library/inspect.html#inspect.stack>`_).

    :param obj: Frame record
    :type  obj: tuple

    :param extended: Flag that indicates whether contents of the frame object
                     are printed (True) or not (False)
    :type  extended: boolean

    :rtype:     string
    """
    # Stack frame -> (frame object [0], filename [1], line number of current
    # line [2], function name [3], list of lines of context from source
    # code [4], index of current line within list [5])
    fname = normalize_windows_fname(obj[1])
    ret = list()
    ret.append(pcolor("Frame object ID: {0}".format(hex(id(obj[0]))), "yellow"))
    ret.append("File name......: {0}".format(fname))
    ret.append("Line number....: {0}".format(obj[2]))
    ret.append("Function name..: {0}".format(obj[3]))
    ret.append("Context........: {0}".format(obj[4]))
    ret.append("Index..........: {0}".format(obj[5]))
    if extended:
        ret.append("f_back ID......: {0}".format(hex(id(obj[0].f_back))))
        ret.append("f_builtins.....: {0}".format(obj[0].f_builtins))
        ret.append("f_code.........: {0}".format(obj[0].f_code))
        ret.append("f_globals......: {0}".format(obj[0].f_globals))
        ret.append("f_lasti........: {0}".format(obj[0].f_lasti))
        ret.append("f_lineno.......: {0}".format(obj[0].f_lineno))
        ret.append("f_locals.......: {0}".format(obj[0].f_locals))
        if hasattr(obj[0], "f_restricted"):  # pragma: no cover
            ret.append("f_restricted...: {0}".format(obj[0].f_restricted))
        ret.append("f_trace........: {0}".format(obj[0].f_trace))
    return "\n".join(ret)


Instruction:
How would you implement a function in Python 3 that
sets variable values via a dictionary mapping name to value.

Response:
def set(self, x):
        """
        Set variable values via a dictionary mapping name to value.
        """
        for name, value in iter(x.items()):
            if hasattr(value, "ndim"):
                if self[name].value.ndim < value.ndim:
                    self[name].value.itemset(value.squeeze())
                else:
                    self[name].value = value
            else:
                self[name].value.itemset(value)


Instruction:
Can you write a function in Python 3 where it
returns a subset of variables according to fixed.

Response:
def select(self, fixed):
        """
        Return a subset of variables according to ``fixed``.
        """
        names = [n for n in self.names() if self[n].isfixed == fixed]
        return Variables({n: self[n] for n in names})


Instruction:
Write a Python 3 function that can
return True if this is a valid USPS tracking number.

Response:
def validate(self, tracking_number):
        "Return True if this is a valid USPS tracking number."
        tracking_num = tracking_number[:-1].replace(' ', '')
        odd_total = 0
        even_total = 0
        for ii, digit in enumerate(tracking_num):
            if ii % 2:
                odd_total += int(digit)
            else:
                even_total += int(digit)
        total = odd_total + even_total * 3
        check = ((total - (total % 10) + 10) - total) % 10
        return (check == int(tracking_number[-1:]))


Instruction:
Given the following Python 3 function, write the documentation
def validate(self, tracking_number):
        "Return True if this is a valid UPS tracking number."
        tracking_num = tracking_number[2:-1]
        odd_total = 0
        even_total = 0

        for ii, digit in enumerate(tracking_num.upper()):
            try:
                value = int(digit)
            except ValueError:
                value = int((ord(digit) - 63) % 10)
            if (ii + 1) % 2:
                odd_total += value
            else:
                even_total += value

        total = odd_total + even_total * 2
        check = ((total - (total % 10) + 10) - total) % 10
        return (check == int(tracking_number[-1:]))

Response: Return True if this is a valid UPS tracking number.


Instruction:
Here you have a function in Python 3, explain what it does
def track(self, tracking_number):
        "Track a UPS package by number. Returns just a delivery date."
        resp = self.send_request(tracking_number)
        return self.parse_response(resp)

Response: Track a UPS package by number. Returns just a delivery date.


Instruction:
Write a Python 3 script for
loading a matrix and wordlist from a. vec file.

Response:
def _load(pathtovector,
              wordlist,
              num_to_load=None,
              truncate_embeddings=None,
              sep=" "):
        """Load a matrix and wordlist from a .vec file."""
        vectors = []
        addedwords = set()
        words = []

        try:
            wordlist = set(wordlist)
        except ValueError:
            wordlist = set()

        logger.info("Loading {0}".format(pathtovector))

        firstline = open(pathtovector).readline().strip()
        try:
            num, size = firstline.split(sep)
            num, size = int(num), int(size)
            logger.info("Vector space: {} by {}".format(num, size))
            header = True
        except ValueError:
            size = len(firstline.split(sep)) - 1
            logger.info("Vector space: {} dim, # items unknown".format(size))
            word, rest = firstline.split(sep, 1)
            # If the first line is correctly parseable, set header to False.
            header = False

        if truncate_embeddings is None or truncate_embeddings == 0:
            truncate_embeddings = size

        for idx, line in enumerate(open(pathtovector, encoding='utf-8')):

            if header and idx == 0:
                continue

            word, rest = line.rstrip(" \n").split(sep, 1)

            if wordlist and word not in wordlist:
                continue

            if word in addedwords:
                raise ValueError("Duplicate: {} on line {} was in the "
                                 "vector space twice".format(word, idx))

            if len(rest.split(sep)) != size:
                raise ValueError("Incorrect input at index {}, size "
                                 "is {}, expected "
                                 "{}".format(idx+1,
                                             len(rest.split(sep)), size))

            words.append(word)
            addedwords.add(word)
            vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])

            if num_to_load is not None and len(addedwords) >= num_to_load:
                break

        vectors = np.array(vectors).astype(np.float32)

        logger.info("Loading finished")
        if wordlist:
            diff = wordlist - addedwords
            if diff:
                logger.info("Not all items from your wordlist were in your "
                            "vector space: {}.".format(diff))

        return vectors, words


Instruction:
Can you generate the documentation for the following Python 3 function
def bow(self, tokens, remove_oov=False):
        if remove_oov:
            tokens = [x for x in tokens if x in self.items]

        for t in tokens:
            try:
                yield self.items[t]
            except KeyError:
                if self.unk_index is None:
                    raise ValueError("You supplied OOV items but didn't "
                                     "provide the index of the replacement "
                                     "glyph. Either set remove_oov to True, "
                                     "or set unk_index to the index of the "
                                     "item which replaces any OOV items.")
                yield self.unk_index

Response: Create a BOW representation of a list of items.


Instruction:
Given the following Python 3 function, write the documentation
def transform(self, corpus, remove_oov=False, norm=False):
        return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
                for s in corpus]

Response: Transform a corpus by repeated calls to vectorize.


Instruction:
Here you have a function in Python 3, explain what it does
def most_similar(self,
                     items,
                     num=10,
                     batch_size=100,
                     show_progressbar=False,
                     return_names=True):
        """
        Return the num most similar items to a given list of items.

        Parameters
        ----------
        items : list of objects or a single object.
            The items to get the most similar items to.
        num : int, optional, default 10
            The number of most similar items to retrieve.
        batch_size : int, optional, default 100.
            The batch size to use. 100 is a good default option. Increasing
            the batch size may increase the speed.
        show_progressbar : bool, optional, default False
            Whether to show a progressbar.
        return_names : bool, optional, default True
            Whether to return the item names, or just the distances.

        Returns
        -------
        sim : array
            For each items in the input the num most similar items are returned
            in the form of (NAME, DISTANCE) tuples. If return_names is false,
            the returned list just contains distances.

        """
        # This line allows users to input single items.
        # We used to rely on string identities, but we now also allow
        # anything hashable as keys.
        # Might fail if a list of passed items is also in the vocabulary.
        # but I can't think of cases when this would happen, and what
        # user expectations are.
        try:
            if items in self.items:
                items = [items]
        except TypeError:
            pass
        x = np.stack([self.norm_vectors[self.items[x]] for x in items])

        result = self._batch(x,
                             batch_size,
                             num+1,
                             show_progressbar,
                             return_names)

        # list call consumes the generator.
        return [x[1:] for x in result]

Response: Returns the num most similar items to a given list of items.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def threshold(self,
                  items,
                  threshold=.5,
                  batch_size=100,
                  show_progressbar=False,
                  return_names=True):
        """
        Return all items whose similarity is higher than threshold.

        Parameters
        ----------
        items : list of objects or a single object.
            The items to get the most similar items to.
        threshold : float, optional, default .5
            The radius within which to retrieve items.
        batch_size : int, optional, default 100.
            The batch size to use. 100 is a good default option. Increasing
            the batch size may increase the speed.
        show_progressbar : bool, optional, default False
            Whether to show a progressbar.
        return_names : bool, optional, default True
            Whether to return the item names, or just the distances.

        Returns
        -------
        sim : array
            For each items in the input the num most similar items are returned
            in the form of (NAME, DISTANCE) tuples. If return_names is false,
            the returned list just contains distances.

        """
        # This line allows users to input single items.
        # We used to rely on string identities, but we now also allow
        # anything hashable as keys.
        # Might fail if a list of passed items is also in the vocabulary.
        # but I can't think of cases when this would happen, and what
        # user expectations are.
        try:
            if items in self.items:
                items = [items]
        except TypeError:
            pass
        x = np.stack([self.norm_vectors[self.items[x]] for x in items])

        result = self._threshold_batch(x,
                                       batch_size,
                                       threshold,
                                       show_progressbar,
                                       return_names)

        # list call consumes the generator.
        return [x[1:] for x in result]

Response: This function returns all items whose similarity is higher than threshold.


Instruction:
How would you explain what the following Python 3 function does
def nearest_neighbor(self,
                         vectors,
                         num=10,
                         batch_size=100,
                         show_progressbar=False,
                         return_names=True):
        """
        Find the nearest neighbors to some arbitrary vector.

        This function is meant to be used in composition operations. The
        most_similar function can only handle items that are in vocab, and
        looks up their vector through a dictionary. Compositions, e.g.
        "King - man + woman" are necessarily not in the vocabulary.

        Parameters
        ----------
        vectors : list of arrays or numpy array
            The vectors to find the nearest neighbors to.
        num : int, optional, default 10
            The number of most similar items to retrieve.
        batch_size : int, optional, default 100.
            The batch size to use. 100 is a good default option. Increasing
            the batch size may increase speed.
        show_progressbar : bool, optional, default False
            Whether to show a progressbar.
        return_names : bool, optional, default True
            Whether to return the item names, or just the distances.

        Returns
        -------
        sim : list of tuples.
            For each item in the input the num most similar items are returned
            in the form of (NAME, DISTANCE) tuples. If return_names is set to
            false, only the distances are returned.

        """
        vectors = np.array(vectors)
        if np.ndim(vectors) == 1:
            vectors = vectors[None, :]

        result = []

        result = self._batch(vectors,
                             batch_size,
                             num+1,
                             show_progressbar,
                             return_names)

        return list(result)

Response: This function returns the list of tuples that are the nearest neighbors to some arbitrary vector.


Instruction:
Given the following Python 3 function, write the documentation
def nearest_neighbor_threshold(self,
                                   vectors,
                                   threshold=.5,
                                   batch_size=100,
                                   show_progressbar=False,
                                   return_names=True):
        """
        Find the nearest neighbors to some arbitrary vector.

        This function is meant to be used in composition operations. The
        most_similar function can only handle items that are in vocab, and
        looks up their vector through a dictionary. Compositions, e.g.
        "King - man + woman" are necessarily not in the vocabulary.

        Parameters
        ----------
        vectors : list of arrays or numpy array
            The vectors to find the nearest neighbors to.
        threshold : float, optional, default .5
            The threshold within to retrieve items.
        batch_size : int, optional, default 100.
            The batch size to use. 100 is a good default option. Increasing
            the batch size may increase speed.
        show_progressbar : bool, optional, default False
            Whether to show a progressbar.
        return_names : bool, optional, default True
            Whether to return the item names, or just the distances.

        Returns
        -------
        sim : list of tuples.
            For each item in the input the num most similar items are returned
            in the form of (NAME, DISTANCE) tuples. If return_names is set to
            false, only the distances are returned.

        """
        vectors = np.array(vectors)
        if np.ndim(vectors) == 1:
            vectors = vectors[None, :]

        result = []

        result = self._threshold_batch(vectors,
                                       batch_size,
                                       threshold,
                                       show_progressbar,
                                       return_names)

        return list(result)

Response: This function returns the list of items that are nearest neighbors to some arbitrary vector.


Instruction:
Can you generate the documentation for the following Python 3 function
def _threshold_batch(self,
                         vectors,
                         batch_size,
                         threshold,
                         show_progressbar,
                         return_names):
        """Batched cosine distance."""
        vectors = self.normalize(vectors)

        # Single transpose, makes things faster.
        reference_transposed = self.norm_vectors.T

        for i in tqdm(range(0, len(vectors), batch_size),
                      disable=not show_progressbar):

            distances = vectors[i: i+batch_size].dot(reference_transposed)
            # For safety we clip
            distances = np.clip(distances, a_min=.0, a_max=1.0)
            for lidx, dists in enumerate(distances):
                indices = np.flatnonzero(dists >= threshold)
                sorted_indices = indices[np.argsort(-dists[indices])]
                if return_names:
                    yield [(self.indices[d], dists[d])
                           for d in sorted_indices]
                else:
                    yield list(dists[sorted_indices])

Response: Yields the batched cosine distance of the given set of entries.


Instruction:
How would you code a function in Python 3 to
normalize a matrix of row vectors to unit length.

Response:
def normalize(vectors):
        """
        Normalize a matrix of row vectors to unit length.

        Contains a shortcut if there are no zero vectors in the matrix.
        If there are zero vectors, we do some indexing tricks to avoid
        dividing by 0.

        Parameters
        ----------
        vectors : np.array
            The vectors to normalize.

        Returns
        -------
        vectors : np.array
            The input vectors, normalized to unit length.

        """
        if np.ndim(vectors) == 1:
            norm = np.linalg.norm(vectors)
            if norm == 0:
                return np.zeros_like(vectors)
            return vectors / norm

        norm = np.linalg.norm(vectors, axis=1)

        if np.any(norm == 0):

            nonzero = norm > 0

            result = np.zeros_like(vectors)

            n = norm[nonzero]
            p = vectors[nonzero]
            result[nonzero] = p / n[:, None]

            return result
        else:
            return vectors / norm[:, None]


Instruction:
Here you have a function in Python 3, explain what it does
def vector_similarity(self, vector, items):
        vector = self.normalize(vector)
        items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
        return vector.dot(items_vec.T)

Response: Compute the similarity between a vector and a set of items.


Instruction:
Write a Python 3 script for
computing the similarity between two sets of items.

Response:
def similarity(self, i1, i2):
        """
        Compute the similarity between two sets of items.

        Parameters
        ----------
        i1 : object
            The first set of items.
        i2 : object
            The second set of item.

        Returns
        -------
        sim : array of floats
            An array of similarity scores between 1 and 0.

        """
        try:
            if i1 in self.items:
                i1 = [i1]
        except TypeError:
            pass
        try:
            if i2 in self.items:
                i2 = [i2]
        except TypeError:
            pass
        i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
        i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
        return i1_vec.dot(i2_vec.T)


Instruction:
Write a Python 3 function for
pruning the current reach instance by removing items.

Response:
def prune(self, wordlist):
        """
        Prune the current reach instance by removing items.

        Parameters
        ----------
        wordlist : list of str
            A list of words to keep. Note that this wordlist need not include
            all words in the Reach instance. Any words which are in the
            wordlist, but not in the reach instance are ignored.

        """
        # Remove duplicates
        wordlist = set(wordlist).intersection(set(self.items.keys()))
        indices = [self.items[w] for w in wordlist if w in self.items]
        if self.unk_index is not None and self.unk_index not in indices:
            raise ValueError("Your unknown item is not in your list of items. "
                             "Set it to None before pruning, or pass your "
                             "unknown item.")
        self.vectors = self.vectors[indices]
        self.norm_vectors = self.norm_vectors[indices]
        self.items = {w: idx for idx, w in enumerate(wordlist)}
        self.indices = {v: k for k, v in self.items.items()}
        if self.unk_index is not None:
            self.unk_index = self.items[wordlist[self.unk_index]]


Instruction:
Make a summary of the following Python 3 code
def save(self, path, write_header=True):
        with open(path, 'w') as f:

            if write_header:
                f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
                        str(self.vectors.shape[1])))

            for i in range(len(self.items)):

                w = self.indices[i]
                vec = self.vectors[i]

                f.write(u"{0} {1}\n".format(w,
                                            " ".join([str(x) for x in vec])))

Response: Save the current vector space in word2vec format.


Instruction:
Make a summary of the following Python 3 code
def save_fast_format(self, filename):
        items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
        items = {"items": items,
                 "unk_index": self.unk_index,
                 "name": self.name}

        json.dump(items, open("{}_items.json".format(filename), 'w'))
        np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)

Response: Save a Reach instance in a fast format.


Instruction:
Implement a function in Python 3 to
load a reach instance in fast format.

Response:
def load_fast_format(filename):
        """
        Load a reach instance in fast format.

        As described above, the fast format stores the words and vectors of the
        Reach instance separately, and is drastically faster than loading from
        .txt files.

        Parameters
        ----------
        filename : str
            The filename prefix from which to load. Note that this is not a
            real filepath as such, but a shared prefix for both files.
            In order for this to work, both {filename}_words.json and
            {filename}_vectors.npy should be present.

        """
        words, unk_index, name, vectors = Reach._load_fast(filename)
        return Reach(vectors, words, unk_index=unk_index, name=name)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _load_fast(filename):
        it = json.load(open("{}_items.json".format(filename)))
        words, unk_index, name = it["items"], it["unk_index"], it["name"]
        vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
        return words, unk_index, name, vectors

Response: Sub for fast loader.


Instruction:
Implement a Python 3 function for
plotting a noisy sine curve and the fitting to it. Also presents the error and the error in the approximation of its first derivative (cosine curve) Usage example for benchmarking: $ time python sine.py --nhead 3 --ntail 3 --n-fit 500000 --n-data 50000 Usage example for plotting: $ python sine.py --nhead 1 --ntail 1 --plot

Response:
def demo_usage(n_data=50, n_fit=537, nhead=5, ntail=5, plot=False, alt=0):
    """
    Plots a noisy sine curve and the fitting to it.
    Also presents the error and the error in the
    approximation of its first derivative (cosine curve)

    Usage example for benchmarking:

    $ time python sine.py --nhead 3 --ntail 3 --n-fit 500000 --n-data 50000

    Usage example for plotting:

    $ python sine.py --nhead 1 --ntail 1 --plot

    """

    x0, xend = 0, 5
    # shaky linspace -5% to +5% noise
    x_data = (np.linspace(x0, xend, n_data) +
              np.random.rand(n_data)*(xend-x0)/n_data/1.5)
    y_data = np.sin(x_data) * (1.0+0.1*(np.random.rand(n_data)-0.5))

    x_fit = np.linspace(x0, xend, n_fit)

    # Edges behave badly, work around:
    x_fit[0] = x_fit[0] + (x_fit[1]-x_fit[0])/2
    x_fit[-1] = x_fit[-2]+(x_fit[-1]-x_fit[-2])/2

    if alt:
        y_fit = np.empty(n_fit)
        dydx_fit = np.empty(n_fit)
        for i, xf in enumerate(x_fit):
            # get index j of first data point beyond xf
            j = np.where(x_data > xf)[0][0]
            lower_bound = max(0,   j-alt)
            upper_bound = min(n_data-1, j+alt)
            y_fit[i] = derivatives_at_point_by_finite_diff(
                x_data[lower_bound:upper_bound],
                y_data[lower_bound:upper_bound], xf, 0)
            dydx_fit[i] = derivatives_at_point_by_finite_diff(
                x_data[lower_bound:upper_bound],
                y_data[lower_bound:upper_bound], xf, 1)[1]
    else:
        interp = interpolate_by_finite_diff(x_data, y_data, x_fit,
                                            1, nhead, ntail)
        y_fit = interp[:, 0]
        dydx_fit = interp[:, 1]

    if plot:
        import matplotlib.pyplot as plt

        plt.subplot(221)
        plt.plot(x_data, y_data, 'x', label='Data points (sin)')
        plt.plot(x_fit, y_fit, '-', label='Fitted curve (order=0)')
        plt.plot(x_data, np.sin(x_data), '-', label='Analytic sin(x)')
        plt.legend()

        plt.subplot(222)
        plt.plot(x_fit, y_fit-np.sin(x_fit), label='Error in order=0')
        plt.legend()

        plt.subplot(223)
        plt.plot(x_fit, dydx_fit, '-', label='Fitted derivative (order=1)')
        plt.plot(x_data, np.cos(x_data), '-', label='Analytic cos(x)')
        plt.legend()

        plt.subplot(224)
        plt.plot(x_fit, dydx_fit-np.cos(x_fit), label='Error in order=1')
        plt.legend()

        plt.show()


Instruction:
Explain what the following Python 3 code does
def display_results(repo_name, contributors, api_len):
    print("\n")

    print("All Contributors:")

    # Sort and consolidate on Name
    seen = []
    for user in sorted(contributors, key=_sort_by_name):
        if user.get("name"):
            key = user["name"]
        else:
            key = user["user_name"]
        if key not in seen:
            seen.append(key)
            if key != user["user_name"]:
                print("%s (%s)" % (user["name"], user["user_name"]))
            else:
                print(user["user_name"])

    print("")

    print("Repo: %s" % repo_name)
    print("GitHub Contributors: %s" % api_len)
    print("All Contributors: %s 👏" % len(seen))

Response: Display the results of the contributors and the number of contributors in the repository.


Instruction:
Explain what the following Python 3 code does
def get_json(uri):
    response = requests.get(API + uri, headers=HEADERS)

    limit = int(response.headers.get("x-ratelimit-remaining"))
    if limit == 0:
        sys.stdout.write("\n")
        message = "You have run out of GitHub request tokens. "

        if int(response.headers.get("x-ratelimit-limit")) == 60:
            message += "Set a GITHUB_TOKEN to increase your limit to 5000/hour. "

        wait_seconds = int(response.headers.get("x-ratelimit-reset")) - int(time.time())
        wait_minutes = math.ceil(wait_seconds / 60)
        message += "Try again in ~%d minutes. " % wait_minutes

        if "--wait-for-reset" in sys.argv:
            progress_message(message.replace("Try ", "Trying "))
            time.sleep(wait_seconds + 1)
            progress_message("Resuming")
            return get_json(uri)
        else:
            raise ValueError(message)

    progress()
    return response.json()

Response: Get a JSON object from GitHub.


Instruction:
Can you tell what is the following Python 3 function doing
def api_walk(uri, per_page=100, key="login"):
    page = 1
    result = []

    while True:
        response = get_json(uri + "?page=%d&per_page=%d" % (page, per_page))
        if len(response) == 0:
            break
        else:
            page += 1
            for r in response:
                if key == USER_LOGIN:
                    result.append(user_login(r))
                else:
                    result.append(r[key])

    return list(set(result))

Response: This function walks all the pages until there s no more content


Instruction:
Given the following Python 3 function, write the documentation
def reducejson(j):

    authors = []

    for key in j["data"]["repository"]["commitComments"]["edges"]:
            authors.append(key["node"]["author"])

    for key in j["data"]["repository"]["issues"]["nodes"]:
            authors.append(key["author"])
            for c in key["comments"]["nodes"]:
                    authors.append(c["author"])

    for key in j["data"]["repository"]["pullRequests"]["edges"]:
            authors.append(key["node"]["author"])
            for c in key["node"]["comments"]["nodes"]:
                    authors.append(c["author"])

    unique = list({v['login']:v for v in authors if v is not None}.values())
    return unique

Response: Reduce the JSON structure of a single object into a single object.


Instruction:
Write a Python 3 script for
converting a path to a dotted path.

Response:
def stringify_with_dot_if_path(x):
    '''Pathlib never renders a leading './' in front of a local path. That's an
    issue because on POSIX subprocess.py (like bash) won't execute scripts in
    the current directory without it. In the same vein, we also don't want
    Path('echo') to match '/usr/bin/echo' from the $PATH. To work around both
    issues, we explicitly join a leading dot to any relative pathlib path.'''
    if isinstance(x, PurePath):
        # Note that join does nothing if the path is absolute.
        return os.path.join('.', str(x))
    return x


Instruction:
Here you have a function in Python 3, explain what it does
def safe_popen(*args, **kwargs):
    '''This wrapper works around two major deadlock issues to do with pipes.
    The first is that, before Python 3.2 on POSIX systems, os.pipe() creates
    inheritable file descriptors, which leak to all child processes and prevent
    reads from reaching EOF. The workaround for this is to set close_fds=True
    on POSIX, which was not the default in those versions. See PEP 0446 for
    many details.

    The second issue arises on Windows, where we're not allowed to set
    close_fds=True while also setting stdin/stdout/stderr. Descriptors from
    os.pipe() on Windows have never been inheritable, so it would seem that
    we're safe. However, the Windows implementation of subprocess.Popen()
    creates temporary inheritable copies of its descriptors, and these can
    leak. The workaround for this is to protect Popen() with a global lock. See
    https://bugs.python.org/issue25565.'''

    close_fds = (os.name != 'nt')
    with popen_lock:
        return subprocess.Popen(*args, close_fds=close_fds, **kwargs)

Response: Wrapper for subprocess. Popen that does not lock popen_lock.


Instruction:
Can you generate the documentation for the following Python 3 function
def run(self):
        '''Execute the expression and return a Result, which includes the exit
        status and any captured output. Raise an exception if the status is
        non-zero.'''
        with spawn_output_reader() as (stdout_capture, stdout_thread):
            with spawn_output_reader() as (stderr_capture, stderr_thread):
                context = starter_iocontext(stdout_capture, stderr_capture)
                status = self._exec(context)
        stdout_bytes = stdout_thread.join()
        stderr_bytes = stderr_thread.join()
        result = Result(status.code, stdout_bytes, stderr_bytes)
        if is_checked_error(status):
            raise StatusError(result, self)
        return result

Response:
Execute the expression and return a Result which includes the exitStatus status and any captured output. Raise an exception if the status is
        non - zero.


Instruction:
Implement a function in Python 3 to
execute the expression and capture its output and return it as a string.

Response:
def read(self):
        '''Execute the expression and capture its output, similar to backticks
        or $() in the shell. This is a wrapper around run() which captures
        stdout, decodes it, trims it, and returns it directly.'''
        result = self.stdout_capture().run()
        stdout_str = decode_with_universal_newlines(result.stdout)
        return stdout_str.rstrip('\n')


Instruction:
Can you generate the documentation for the following Python 3 function
def start(self):
        '''Equivalent to `run`, but instead of blocking the current thread,
        return a WaitHandle that doesn't block until `wait` is called. This is
        currently implemented with a simple background thread, though in theory
        it could avoid using threads in most cases.'''
        thread = ThreadWithReturn(self.run)
        thread.start()
        return WaitHandle(thread)

Response: Equivalent to run but instead of blocking the current thread returns a WaitHandle that doesn t block until wait is called.


Instruction:
Can you write a function in Python 3 where it
executes a command at the device using the RESTful API

Response:
def _exec(self, cmd, url, json_data=None):
        """
        execute a command at the device using the RESTful API

        :param str cmd: one of the REST commands, e.g. GET or POST
        :param str url: URL of the REST API the command should be applied to
        :param dict json_data: json data that should be attached to the command
        """
        assert(cmd in ("GET", "POST", "PUT", "DELETE"))
        assert(self.dev is not None)

        if json_data is None:
            json_data = {}

        # add device address to the URL
        url = url.format(self.dev["ipv4_internal"])

        # set basic authentication
        auth = HTTPBasicAuth("dev", self.dev["api_key"])

        # execute HTTP request
        res = None
        if cmd == "GET":
            res = self._local_session.session.get(
                url, auth=auth, verify=False
            )

        elif cmd == "POST":
            res = self._local_session.session.post(
                url, auth=auth, json=json_data, verify=False
            )

        elif cmd == "PUT":
            res = self._local_session.session.put(
                url, auth=auth, json=json_data, verify=False
            )

        elif cmd == "DELETE":
            res = self._local_session.session.delete(
                url, auth=auth, verify=False
            )

        if res is not None:
            # raise an exception on error
            res.raise_for_status()

        return res.json()


Instruction:
Write a Python 3 script for
setting the current device

Response:
def set_device(self, dev):
        """
        set the current device (that will be used for following API calls)

        :param dict dev: device that should be used for the API calls
                         (can be obtained via get_devices function)
        """
        log.debug("setting device to '{}'".format(dev))
        self.dev = dev
        self.set_apps_list()


Instruction:
Write a Python 3 script to
return the first widget id for the given package_name

Response:
def _get_widget_id(self, package_name):
        """
        returns widget_id for given package_name does not care
        about multiple widget ids at the moment, just picks the first

        :param str package_name: package to check for
        :return: id of first widget which belongs to the given package_name
        :rtype: str
        """
        widget_id = ""
        for app in self.get_apps_list():
            if app.package == package_name:
                widget_id = list(app.widgets.keys())[0]

        return widget_id


Instruction:
Can you generate the documentation for the following Python 3 function
def get_user(self):
        log.debug("getting user information from LaMetric cloud...")
        _, url = CLOUD_URLS["get_user"]
        res = self._cloud_session.session.get(url)
        if res is not None:
            # raise an exception on error
            res.raise_for_status()

        return res.json()

Response: get the user details via the cloud


Instruction:
How would you explain what the following Python 3 function does
def get_devices(self, force_reload=False, save_devices=True):
        if (
            (not os.path.exists(self._devices_filename)) or
            (force_reload is True)
        ):
            # -- load devices from LaMetric cloud --
            log.debug("getting devices from LaMetric cloud...")
            _, url = CLOUD_URLS["get_devices"]
            res = self._cloud_session.session.get(url)
            if res is not None:
                # raise an exception on error
                res.raise_for_status()

            # store obtained devices internally
            self._devices = res.json()
            if save_devices is True:
                # save obtained devices to the local file
                self.save_devices()

            return self._devices

        else:
            # -- load devices from local file --
            log.debug(
                "getting devices from '{}'...".format(self._devices_filename)
            )
            return self.load_devices()

Response: get all devices that are linked to the user


Instruction:
Make a summary of the following Python 3 code
def save_devices(self):
        log.debug("saving devices to ''...".format(self._devices_filename))
        if self._devices != []:
            with codecs.open(self._devices_filename, "wb", "utf-8") as f:
                json.dump(self._devices, f)

Response: save the list of devices that have been obtained from LaMetric to a local file


Instruction:
Here you have a function in Python 3, explain what it does
def get_endpoint_map(self):
        log.debug("getting end points...")
        cmd, url = DEVICE_URLS["get_endpoint_map"]
        return self._exec(cmd, url)

Response: returns API version and endpoint map


Instruction:
Create a Python 3 function to
load stored devices from the local file

Response:
def load_devices(self):
        """
        load stored devices from the local file
        """
        self._devices = []
        if os.path.exists(self._devices_filename):
            log.debug(
                "loading devices from '{}'...".format(self._devices_filename)
            )
            with codecs.open(self._devices_filename, "rb", "utf-8") as f:
                self._devices = json.load(f)

        return self._devices


Instruction:
Write a Python 3 function that can
return the full device state

Response:
def get_device_state(self):
        """
        returns the full device state
        """
        log.debug("getting device state...")
        cmd, url = DEVICE_URLS["get_device_state"]
        return self._exec(cmd, url)


Instruction:
Can you tell what is the following Python 3 function doing
def send_notification(
        self, model, priority="warning", icon_type=None, lifetime=None
    ):
        """
        sends new notification to the device

        :param Model model: an instance of the Model class that should be used
        :param str priority: the priority of the notification
                             [info, warning or critical] (default: warning)
        :param str icon_type: the icon type of the notification
                              [none, info or alert] (default: None)
        :param int lifetime: the lifetime of the notification in ms
                             (default: 2 min)
        """
        assert(priority in ("info", "warning", "critical"))
        assert(icon_type in (None, "none", "info", "alert"))
        assert((lifetime is None) or (lifetime > 0))

        log.debug("sending notification...")

        cmd, url = DEVICE_URLS["send_notification"]

        json_data = {"model": model.json(), "priority": priority}

        if icon_type is not None:
            json_data["icon_type"] = icon_type
        if lifetime is not None:
            json_data["lifetime"] = lifetime

        return self._exec(cmd, url, json_data=json_data)

Response: sends a new notification to the device


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_notifications(self):
        log.debug("getting notifications in queue...")
        cmd, url = DEVICE_URLS["get_notifications_queue"]
        return self._exec(cmd, url)

Response: returns the list of all notifications in queue


Instruction:
Write a Python 3 function for
returning the current notification

Response:
def get_current_notification(self):
        """
        returns the current notification (i.e. the one that is visible)
        """
        log.debug("getting visible notification...")
        cmd, url = DEVICE_URLS["get_current_notification"]
        return self._exec(cmd, url)


Instruction:
Can you generate the documentation for the following Python 3 function
def get_notification(self, notification_id):
        log.debug("getting notification '{}'...".format(notification_id))
        cmd, url = DEVICE_URLS["get_notification"]
        return self._exec(cmd, url.replace(":id", notification_id))

Response: get a specific notification by given ID


Instruction:
Implement a Python 3 function for
returning information about the display including brightness screensaver etc.

Response:
def get_display(self):
        """
        returns information about the display, including
        brightness, screensaver etc.
        """
        log.debug("getting display information...")
        cmd, url = DEVICE_URLS["get_display"]
        return self._exec(cmd, url)


Instruction:
Create a Python 3 function to
allow to change display state

Response:
def set_display(self, brightness=100, brightness_mode="auto"):
        """
        allows to modify display state (change brightness)

        :param int brightness: display brightness [0, 100] (default: 100)
        :param str brightness_mode: the brightness mode of the display
                                    [auto, manual] (default: auto)
        """
        assert(brightness_mode in ("auto", "manual"))
        assert(brightness in range(101))

        log.debug("setting display information...")

        cmd, url = DEVICE_URLS["set_display"]
        json_data = {
            "brightness_mode": brightness_mode,
            "brightness": brightness
        }

        return self._exec(cmd, url, json_data=json_data)


Instruction:
Can you generate the documentation for the following Python 3 function
def set_screensaver(
        self, mode, is_mode_enabled, start_time=None, end_time=None,
        is_screensaver_enabled=True
    ):
        """
        set the display's screensaver mode

        :param str mode: mode of the screensaver
                         [when_dark, time_based]
        :param bool is_mode_enabled: specifies if mode is enabled or disabled
        :param str start_time: start time, only used in time_based mode
                               (format: %H:%M:%S)
        :param str end_time: end time, only used in time_based mode
                             (format: %H:%M:%S)
        :param bool is_screensaver_enabled: is overall screensaver turned on
                                            overrules mode specific settings
        """
        assert(mode in ("when_dark", "time_based"))

        log.debug("setting screensaver to '{}'...".format(mode))

        cmd, url = DEVICE_URLS["set_display"]
        json_data = {
            "screensaver": {
                "enabled": is_screensaver_enabled,
                "mode": mode,
                "mode_params": {
                    "enabled": is_mode_enabled
                },
            }
        }
        if mode == "time_based":
            # TODO: add time checks
            assert((start_time is not None) and (end_time is not None))
            json_data["screensaver"]["mode_params"]["start_time"] = start_time
            json_data["screensaver"]["mode_params"]["end_time"] = end_time

        return self._exec(cmd, url, json_data=json_data)

Response: set the display s screensaver mode


Instruction:
Write a Python 3 script to
return the current volume

Response:
def get_volume(self):
        """
        returns the current volume
        """
        log.debug("getting volumne...")
        cmd, url = DEVICE_URLS["get_volume"]
        return self._exec(cmd, url)


Instruction:
Can you implement a function in Python 3 that
allows to change the volume for the current device

Response:
def set_volume(self, volume=50):
        """
        allows to change the volume

        :param int volume: volume to be set for the current device
                           [0..100] (default: 50)
        """
        assert(volume in range(101))

        log.debug("setting volume...")

        cmd, url = DEVICE_URLS["set_volume"]
        json_data = {
            "volume": volume,
        }
        return self._exec(cmd, url, json_data=json_data)


Instruction:
Can you implement a function in Python 3 that
returns the bluetooth state

Response:
def get_bluetooth_state(self):
        """
        returns the bluetooth state
        """
        log.debug("getting bluetooth state...")
        cmd, url = DEVICE_URLS["get_bluetooth_state"]
        return self._exec(cmd, url)


Instruction:
Explain what the following Python 3 code does
def set_bluetooth(self, active=None, name=None):
        assert(active is not None or name is not None)

        log.debug("setting bluetooth state...")

        cmd, url = DEVICE_URLS["set_bluetooth"]
        json_data = {}
        if name is not None:
            json_data["name"] = name
        if active is not None:
            json_data["active"] = active

        return self._exec(cmd, url, json_data=json_data)

Response: allows to activate or deactivate bluetooth and change the name


Instruction:
How would you explain what the following Python 3 function does
def get_wifi_state(self):
        log.debug("getting wifi state...")
        cmd, url = DEVICE_URLS["get_wifi_state"]
        return self._exec(cmd, url)

Response: returns the current Wi - Fi state of the device connected to


Instruction:
Make a summary of the following Python 3 code
def set_apps_list(self):
        log.debug("getting apps and setting them in the internal app list...")

        cmd, url = DEVICE_URLS["get_apps_list"]
        result = self._exec(cmd, url)

        self.available_apps = [
            AppModel(result[app])
            for app in result
        ]

Response: gets installed apps and puts them into the available_apps list


Instruction:
Given the following Python 3 function, write the documentation
def switch_to_app(self, package):
        log.debug("switching to app '{}'...".format(package))
        cmd, url = DEVICE_URLS["switch_to_app"]
        widget_id = self._get_widget_id(package)

        url = url.format('{}', package, widget_id)

        self.result = self._exec(cmd, url)

Response:
Switches the app that is specified by package. Selects the first app that is found in the app list
       .


Instruction:
Write a Python 3 function for
switching to the next app

Response:
def switch_to_next_app(self):
        """
        switches to the next app
        """
        log.debug("switching to next app...")
        cmd, url = DEVICE_URLS["switch_to_next_app"]
        self.result = self._exec(cmd, url)


Instruction:
Write a Python 3 script for
activating the widget of the given package

Response:
def activate_widget(self, package):
        """
        activate the widget of the given package

        :param str package: name of the package
        """
        cmd, url = DEVICE_URLS["activate_widget"]

        # get widget id for the package
        widget_id = self._get_widget_id(package)
        url = url.format('{}', package, widget_id)

        self.result = self._exec(cmd, url)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _app_exec(self, package, action, params=None):
        # get list of possible commands from app.actions
        allowed_commands = []
        for app in self.get_apps_list():
            if app.package == package:
                allowed_commands = list(app.actions.keys())
                break

        # check if action is in this list
        assert(action in allowed_commands)

        cmd, url = DEVICE_URLS["do_action"]
        # get widget id for the package
        widget_id = self._get_widget_id(package)
        url = url.format('{}', package, widget_id)

        json_data = {"id": action}
        if params is not None:
            json_data["params"] = params

        self.result = self._exec(cmd, url, json_data=json_data)

Response: This method is used to execute a specific action on all apps with the same package.


Instruction:
Write a Python 3 script for
setting the alarm clock alid

Response:
def alarm_set(self, time, wake_with_radio=False):
        """
        set the alarm clock

        :param str time: time of the alarm (format: %H:%M:%S)
        :param bool wake_with_radio: if True, radio will be used for the alarm
                                     instead of beep sound
        """
        # TODO: check for correct time format
        log.debug("alarm => set...")
        params = {
            "enabled": True,
            "time": time,
            "wake_with_radio": wake_with_radio
        }
        self._app_exec("com.lametric.clock", "clock.alarm", params=params)


Instruction:
Create a Python 3 function to
set the countdown for a given time period

Response:
def countdown_set(self, duration, start_now):
        """
        set the countdown

        :param str duration:
        :param str start_now:
        """
        log.debug("countdown => set...")
        params = {'duration': duration, 'start_now': start_now}
        self._app_exec(
            "com.lametric.countdown", "countdown.configure", params
        )


Instruction:
How would you implement a function in Python 3 that
calls external script. :param includes: testcase's includes :param variables: variables :return: script's output

Response:
def action(self, includes: dict, variables: dict) -> tuple:
        """
        Call external script.

        :param includes: testcase's includes
        :param variables: variables
        :return: script's output
        """
        json_args = fill_template_str(json.dumps(self.data), variables)
        p = subprocess.Popen([self.module, json_args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        if p.wait() == 0:
            out = p.stdout.read().decode()
            debug(out)
            return variables, json.loads(out)
        else:
            out = p.stdout.read().decode()
            warning(out)
            raise Exception('Execution failed.')


Instruction:
Create a Python 3 function to
set credentials and reset the session

Response:
def set_credentials(self, client_id=None, client_secret=None):
        """
        set given credentials and reset the session
        """
        self._client_id = client_id
        self._client_secret = client_secret

        # make sure to reset session due to credential change
        self._session = None


Instruction:
Can you tell what is the following Python 3 function doing
def init_session(self, get_token=True):
        if (self._client_id is None) or (self._client_secret is None):
            sys.exit(
                "Please make sure to set the client id and client secret "
                "via the constructor, the environment variables or the config "
                "file; otherwise, the LaMetric cloud cannot be accessed. "
                "Abort!"
            )

        self._session = OAuth2Session(
            client=BackendApplicationClient(client_id=self._client_id)
        )

        if get_token is True:
            # get oauth token
            self.get_token()

Response: init a new oauth2 session that is required to access the cloud


Instruction:
Can you create a Python 3 function that
gets current oauth token

Response:
def get_token(self):
        """
        get current oauth token
        """
        self.token = self._session.fetch_token(
            token_url=CLOUD_URLS["get_token"][1],
            client_id=self._client_id,
            client_secret=self._client_secret
        )


Instruction:
Write a Python 3 script to
use this method to get simple input as python object with all templates filled in

Response:
def simple_input(self, variables):
        """
        Use this method to get simple input as python object, with all
        templates filled in

        :param variables:
        :return: python object

        """
        json_args = fill_template_str(json.dumps(self.data), variables)
        return try_get_objects(json_args)


Instruction:
Make a summary of the following Python 3 code
def create(self):
        if not self.exists():
            # create new empyt config file based on template
            self.config.add_section("lametric")
            self.config.set("lametric", "client_id", "")
            self.config.set("lametric", "client_secret", "")

            # save new config
            self.save()

            # stop here, so user can set his config
            sys.exit(
                "An empty config file '{}' has been created. Please set "
                "the corresponding LaMetric API credentials.".format(
                    self._filename
                )
            )

Response:
Creates an empty configuration file based on template
            and saves it.


Instruction:
Create a Python 3 function for
saving current config to the file

Response:
def save(self):
        """
        save current config to the file
        """
        with open(self._filename, "w") as f:
            self.config.write(f)


Instruction:
Explain what the following Python 3 code does
def rate_limit_wait(self):
        if self._rate_limit_dt and self._last_query is not None:
            dt = time.time() - self._last_query
            wait = self._rate_limit_dt - dt
            if wait > 0:
                time.sleep(wait)

Response: Sleep if rate limiting is required based on current time and last query.


Instruction:
Create a Python 3 function to
query a route from a Shapely line to a Shapely point.

Response:
def route(self, arg, destination=None, waypoints=None, raw=False, **kwargs):
        """
        Query a route.

        route(locations): points can be
            - a sequence of locations
            - a Shapely LineString
        route(origin, destination, waypoints=None)
             - origin and destination are a single destination
             - waypoints are the points to be inserted between the
               origin and destination

             If waypoints is specified, destination must also be specified

        Each location can be:
            - string (will be geocoded by the routing provider. Not all
              providers accept this as input)
            - (longitude, latitude) sequence (tuple, list, numpy array, etc.)
            - Shapely Point with x as longitude, y as latitude

        Additional parameters
        ---------------------
        raw : bool, default False
            Return the raw json dict response from the service

        Returns
        -------
        list of Route objects
        If raw is True, returns the json dict instead of converting to Route
        objects

        Examples
        --------
        mq = directions.Mapquest(key)
        routes = mq.route('1 magazine st. cambridge, ma',
                          'south station boston, ma')

        routes = mq.route('1 magazine st. cambridge, ma',
                          'south station boston, ma',
                          waypoints=['700 commonwealth ave. boston, ma'])

        # Uses each point in the line as a waypoint. There is a limit to the
        # number of waypoints for each service. Consult the docs.
        line = LineString(...)
        routes = mq.route(line)

        # Feel free to mix different location types
        routes = mq.route(line.coords[0], 'south station boston, ma',
                          waypoints=[(-71.103972, 42.349324)])

        """
        points = _parse_points(arg, destination, waypoints)
        if len(points) < 2:
            raise ValueError('You must specify at least 2 points')

        self.rate_limit_wait()
        data = self.raw_query(points, **kwargs)
        self._last_query = time.time()

        if raw:
            return data
        return self.format_output(data)


Instruction:
How would you explain what the following Python 3 function does
def from_geojson(cls, data):
        properties = data['properties']
        distance = properties.pop('distance')
        duration = properties.pop('duration')

        maneuvers = []
        for feature in data['features']:
            geom = feature['geometry']
            if geom['type'] == 'LineString':
                coords = geom['coordinates']
            else:
                maneuvers.append(Maneuver.from_geojson(feature))

        return Route(coords, distance, duration, maneuvers, **properties)

Response: Return a Route object from a GeoJSON dictionary.


Instruction:
Given the following Python 3 function, write the documentation
def prepare_modules(module_paths: list, available: dict) -> dict:
    indexed = {}
    for path in module_paths:
        if not os.path.exists(path) and path not in available:
            err = 'No such path: ' + path
            error(err)
        else:
            for f in os.listdir(path):
                mod_path = join(path, f)
                if f in indexed:
                    warning('Override ' + indexed[f] + ' with ' + mod_path)
                indexed[f] = mod_path
    return indexed

Response: Scan all paths for external modules and form key - value dict.


Instruction:
Here you have a function in Python 3, explain what it does
def discover_upnp_devices(
        self, st="upnp:rootdevice", timeout=2, mx=1, retries=1
    ):
        """
        sends an SSDP discovery packet to the network and collects
        the devices that replies to it. A dictionary is returned
        using the devices unique usn as key
        """
        # prepare UDP socket to transfer the SSDP packets
        s = socket.socket(
            socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP
        )
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
        s.settimeout(timeout)

        # prepare SSDP discover message
        msg = SSDPDiscoveryMessage(mx=mx, st=st)

        # try to get devices with multiple retries in case of failure
        devices = {}
        for _ in range(retries):
            # send SSDP discovery message
            s.sendto(msg.bytes, SSDP_MULTICAST_ADDR)

            devices = {}
            try:
                while True:
                    # parse response and store it in dict
                    r = SSDPResponse(s.recvfrom(65507))
                    devices[r.usn] = r

            except socket.timeout:
                break

        return devices

Response: Send an SSDP discovery packet to the network and collects the devices that replies to it.


Instruction:
How would you implement a function in Python 3 that
gets a dict of devices that contain the given model name.

Response:
def get_filtered_devices(
        self, model_name, device_types="upnp:rootdevice", timeout=2
    ):
        """
        returns a dict of devices that contain the given model name
        """

        # get list of all UPNP devices in the network
        upnp_devices = self.discover_upnp_devices(st=device_types)

        # go through all UPNP devices and filter wanted devices
        filtered_devices = collections.defaultdict(dict)
        for dev in upnp_devices.values():
            try:
                # download XML file with information about the device
                # from the device's location
                r = requests.get(dev.location, timeout=timeout)

                if r.status_code == requests.codes.ok:
                    # parse returned XML
                    root = ET.fromstring(r.text)

                    # add shortcut for XML namespace to access sub nodes
                    ns = {"upnp": "urn:schemas-upnp-org:device-1-0"}

                    # get device element
                    device = root.find("upnp:device", ns)

                    if model_name in device.find(
                        "upnp:modelName", ns
                    ).text:
                        # model name is wanted => add to list

                        # get unique UDN of the device that is used as key
                        udn = device.find("upnp:UDN", ns).text

                        # add url base
                        url_base = root.find("upnp:URLBase", ns)
                        if url_base is not None:
                            filtered_devices[udn][
                                "URLBase"
                            ] = url_base.text

                        # add interesting device attributes and
                        # use unique UDN as key
                        for attr in (
                            "deviceType", "friendlyName", "manufacturer",
                            "manufacturerURL", "modelDescription",
                            "modelName", "modelNumber"
                        ):
                            el = device.find("upnp:%s" % attr, ns)
                            if el is not None:
                                filtered_devices[udn][
                                    attr
                                ] = el.text.strip()

            except ET.ParseError:
                # just skip devices that are invalid xml
                pass
            except requests.exceptions.ConnectTimeout:
                # just skip devices that are not replying in time
                print("Timeout for '%s'. Skipping." % dev.location)

        return filtered_devices


Instruction:
Here you have a function in Python 3, explain what it does
def lazy_map(data_processor, data_generator, n_cpus=1, stepsize=None):
    if not n_cpus:
        n_cpus = mp.cpu_count()
    elif n_cpus < 0:
        n_cpus = mp.cpu_count() - n_cpus

    if stepsize is None:
        stepsize = n_cpus

    results = []

    with mp.Pool(processes=n_cpus) as p:
        while True:
            r = p.map(data_processor, islice(data_generator, stepsize))
            if r:
                results.extend(r)
            else:
                break
    return results

Response: A variant of multiprocessing. Pool. map that supports lazy evaluation of a single object.


Instruction:
Can you generate the documentation for the following Python 3 function
def lazy_imap(data_processor, data_generator, n_cpus=1, stepsize=None):
    if not n_cpus:
        n_cpus = mp.cpu_count()
    elif n_cpus < 0:
        n_cpus = mp.cpu_count() - n_cpus

    if stepsize is None:
        stepsize = n_cpus

    with mp.Pool(processes=n_cpus) as p:
        while True:
            r = p.map(data_processor, islice(data_generator, stepsize))
            if r:
                yield r
            else:
                break

Response: A variant of multiprocessing. Pool. imap that supports lazy evaluation of a single object.


Instruction:
How would you explain what the following Python 3 function does
def update_variables(func):

    @wraps(func)
    def wrapper(self, *args, **kwargs):
        result = func(self, *args, **kwargs)
        if isinstance(result, tuple):
            return self.process_register(result[0], result[1])
        else:
            return self.process_register(result)

    return wrapper

Response:
Decorator to update variables of the
 ArcGIS application.


Instruction:
Implement a function in Python 3 to
set the properties of the app model by the given data dict

Response:
def _set_properties(self, data):
        """
        set the properties of the app model by the given data dict
        """
        for property in data.keys():
            if property in vars(self):
                setattr(self, property, data[property])


Instruction:
Implement a Python 3 function for
getting long description from README. rst file

Response:
def get_long_description():
    """
    get long description from README.rst file
    """
    with codecs.open(os.path.join(here, "README.rst"), "r", "utf-8") as f:
        return f.read()


Instruction:
Can you tell what is the following Python 3 function doing
def _parse_order_by(model, order_by):
    # the list of filters for the models
    out = []
    # for each attribute we have to order by
    for key in order_by:
        # remove any whitespace
        key = key.strip()
        # if the key starts with a plus
        if key.startswith("+"):
            # add the ascending filter to the list
            out.append(getattr(model, key[1:]))
        # otherwise if the key starts with a minus
        elif key.startswith("-"):
            # add the descending filter to the list
            out.append(getattr(model, key[1:]).desc())
        # otherwise the key needs the default filter
        else:
            # add the default filter to the list
            out.append(getattr(model, key))

    # returnt the list of filters
    return out

Response: This function parses the order_by argument and returns a list of filters for the given model and the list of orderings for the given language.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def model(model_names):
    # for each model name we need to create
    for model_name in model_names:
        # the template context
        context = {
            'name': model_name,
        }

        # render the model template
        render_template(template='common', context=context)
        render_template(template='model', context=context)

Response: Creates the example directory structure necessary for a model service.


Instruction:
Can you implement a function in Python 3 that
creates the folder directories for an ApiGateway service.

Response:
def api():
    """
        Create the folder/directories for an ApiGateway service.
    """
    # the template context
    context = {
        'name': 'api',
        'secret_key': random_string(32)
    }

    render_template(template='common', context=context)
    render_template(template='api', context=context)


Instruction:
Make a summary of the following Python 3 code
def auth():
    # the template context
    context = {
        'name': 'auth',
    }

    render_template(template='common', context=context)
    render_template(template='auth', context=context)

Response: Create the folder directories for an Auth service.


Instruction:
Here you have a function in Python 3, explain what it does
def connection(model_connections):

    # for each connection group
    for connection_str in model_connections:

        # the services to connect
        services = connection_str.split(':')
        services.sort()

        service_name = ''.join([service.title() for service in services])

        # the template context
        context = {
            # make sure the first letter is lowercase
            'name': service_name[0].lower() + service_name[1:],
            'services': services,
        }

        render_template(template='common', context=context)
        render_template(template='connection', context=context)

Response: Creates the example directory structure necessary for a connection.


Instruction:
Make a summary of the following Python 3 code
def get_model_string(model):
    name = model if isinstance(model, str) else model.__name__
    return normalize_string(name)

Response: This function returns the conventional action designator for a given model


Instruction:
How would you code a function in Python 3 to
start the broker interaction with the kafka stream

Response:
def start(self):
        """
            This function starts the brokers interaction with the kafka stream
        """
        self.loop.run_until_complete(self._consumer.start())
        self.loop.run_until_complete(self._producer.start())
        self._consumer_task = self.loop.create_task(self._consume_event_callback())


Instruction:
Write a Python 3 script for
stopping the broker interaction with the kafka stream

Response:
def stop(self):
        """
            This method stops the brokers interaction with the kafka stream
        """
        self.loop.run_until_complete(self._consumer.stop())
        self.loop.run_until_complete(self._producer.stop())

        # attempt
        try:
            # to cancel the service
            self._consumer_task.cancel()
        # if there was no service
        except AttributeError:
            # keep going
            pass


Instruction:
How would you explain what the following Python 3 function does
async def send(self, payload='', action_type='', channel=None, **kwds):
        # use a custom channel if one was provided
        channel = channel or self.producer_channel

        # serialize the action type for the
        message = serialize_action(action_type=action_type, payload=payload, **kwds)
        # send the message
        return await self._producer.send(channel, message.encode())

Response: This method sends a message over the kafka stream.


Instruction:
Write a Python 3 script for
returning the fields that are part of the provided base model that are part of the base model.

Response:
def fields_for_model(model):
    """
        This function returns the fields for a schema that matches the provided
        nautilus model.

        Args:
            model (nautilus.model.BaseModel): The model to base the field list on

        Returns:
            (dict<field_name: str, graphqlType>): A mapping of field names to
                graphql types
    """

    # the attribute arguments (no filters)
    args = {field.name.lower() : convert_peewee_field(field) \
                                        for field in model.fields()}
    # use the field arguments, without the segments
    return args


Instruction:
Create a Python 3 function to
create an SQL Alchemy table that connects the provides services

Response:
def create_connection_model(service):
    """ Create an SQL Alchemy table that connects the provides services """
    # the services connected
    services = service._services

    # the mixins / base for the model
    bases = (BaseModel,)
    # the fields of the derived
    attributes = {model_service_name(service): fields.CharField() for service in services}

    # create an instance of base model with the right attributes
    return type(BaseModel)(connection_service_name(service), bases, attributes)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_handler(Model, name=None, **kwds):
    async def action_handler(service, action_type, payload, props, notify=True, **kwds):
        # if the payload represents a new instance of `Model`
        if action_type == get_crud_action('create', name or Model):
            # print('handling create for ' + name or Model)
            try:
                # the props of the message
                message_props = {}
                # if there was a correlation id in the request
                if 'correlation_id' in props:
                    # make sure it ends up in the reply
                    message_props['correlation_id'] = props['correlation_id']

                # for each required field
                for requirement in Model.required_fields():

                    # save the name of the field
                    field_name = requirement.name
                    # ensure the value is in the payload
                    # TODO: check all required fields rather than failing on the first
                    if not field_name in payload and field_name != 'id':
                        # yell loudly
                        raise ValueError(
                            "Required field not found in payload: %s" %field_name
                        )

                # create a new model
                new_model = Model(**payload)

                # save the new model instance
                new_model.save()

                # if we need to tell someone about what happened
                if notify:
                    # publish the scucess event
                    await service.event_broker.send(
                        payload=ModelSerializer().serialize(new_model),
                        action_type=change_action_status(action_type, success_status()),
                        **message_props
                    )

            # if something goes wrong
            except Exception as err:
                # if we need to tell someone about what happened
                if notify:
                    # publish the error as an event
                    await service.event_broker.send(
                        payload=str(err),
                        action_type=change_action_status(action_type, error_status()),
                        **message_props
                    )
                # otherwise we aren't supposed to notify
                else:
                    # raise the exception normally
                    raise err

    # return the handler
    return action_handler

Response: This factory returns an action handler that creates a new instance of a specified model.


Instruction:
How would you explain what the following Python 3 function does
def _find_id(self, result, uid):
        # if the result is a list
        if isinstance(result, list):
            # if the list has a valid entry
            if any([self._find_id(value, uid) for value in result]):
                # then we're done
                return True

        # otherwise results could be dictionaries
        if isinstance(result, dict):
            # the children of the result that are lists
            list_children = [value for value in result.values() if isinstance(value, list)]

            # go to every value that is a list
            for value in list_children:
                # if the value is a match
                if self._find_id(value, uid):
                    # we're done
                    return True

            # the children of the result that are dicts
            dict_children = [value for value in result.values() if isinstance(value, dict)]

            # perform the check on every child that is a dict
            for value in dict_children:
                # if the child is a match
                if self._find_id(value, uid):
                    # we're done
                    return True

            # if there are no values that are lists and there is an id key
            if not list_children and not dict_children and 'id' in result:
                # the value of the remote id field
                result_id = result['id']
                # we've found a match if the id field matches (cast to match type)
                return result_id == type(result_id)(uid)

        # we didn't find the result
        return False

Response: This method searches the result dictionary for the given uid.


Instruction:
Explain what the following Python 3 code does
def add_before(self):
        idx = self._container.structure.index(self)
        return BlockBuilder(self._container, idx)

Response: Returns a builder inserting a new block before the current block


Instruction:
Given the following Python 3 function, write the documentation
def add_after(self):
        idx = self._container.structure.index(self)
        return BlockBuilder(self._container, idx+1)

Response: Returns a builder inserting a new block after the current block


Instruction:
Write a Python 3 function that can
create a comment block for the current object

Response:
def comment(self, text, comment_prefix='#'):
        """Creates a comment block

        Args:
            text (str): content of comment without #
            comment_prefix (str): character indicating start of comment

        Returns:
            self for chaining
        """
        comment = Comment(self._container)
        if not text.startswith(comment_prefix):
            text = "{} {}".format(comment_prefix, text)
        if not text.endswith('\n'):
            text = "{}{}".format(text, '\n')
        comment.add_line(text)
        self._container.structure.insert(self._idx, comment)
        self._idx += 1
        return self


Instruction:
Make a summary of the following Python 3 code
def section(self, section):
        if not isinstance(self._container, ConfigUpdater):
            raise ValueError("Sections can only be added at section level!")
        if isinstance(section, str):
            # create a new section
            section = Section(section, container=self._container)
        elif not isinstance(section, Section):
            raise ValueError("Parameter must be a string or Section type!")
        if section.name in [block.name for block in self._container
                            if isinstance(block, Section)]:
            raise DuplicateSectionError(section.name)
        self._container.structure.insert(self._idx, section)
        self._idx += 1
        return self

Response: Creates a section block at the specified level.


Instruction:
Can you write a function in Python 3 where it
creates a vertical space of newlines.

Response:
def space(self, newlines=1):
        """Creates a vertical space of newlines

        Args:
            newlines (int): number of empty lines

        Returns:
            self for chaining
        """
        space = Space()
        for line in range(newlines):
            space.add_line('\n')
        self._container.structure.insert(self._idx, space)
        self._idx += 1
        return self


Instruction:
Can you generate the documentation for the following Python 3 function
def option(self, key, value=None, **kwargs):
        if not isinstance(self._container, Section):
            raise ValueError("Options can only be added inside a section!")
        option = Option(key, value, container=self._container, **kwargs)
        option.value = value
        self._container.structure.insert(self._idx, option)
        self._idx += 1
        return self

Response: Adds an option to the section with the specified key and value.


Instruction:
Write a Python 3 function for
adding a Comment object to the section Used during initial parsing mainly is a dict with the key = value and the value = value.

Response:
def add_comment(self, line):
        """Add a Comment object to the section

        Used during initial parsing mainly

        Args:
            line (str): one line in the comment
        """
        if not isinstance(self.last_item, Comment):
            comment = Comment(self._structure)
            self._structure.append(comment)
        self.last_item.add_line(line)
        return self


Instruction:
Can you tell what is the following Python 3 function doing
def add_space(self, line):
        if not isinstance(self.last_item, Space):
            space = Space(self._structure)
            self._structure.append(space)
        self.last_item.add_line(line)
        return self

Response:
Add a Space object to the section
            Used during initial parsing mainly
                   is a string that defines the space.


Instruction:
Make a summary of the following Python 3 code
def to_dict(self):
        return {key: self.__getitem__(key).value for key in self.options()}

Response:
Transform to dictionary

        Returns:
            dict: dictionary with same content


Instruction:
Here you have a function in Python 3, explain what it does
def set(self, option, value=None):
        option = self._container.optionxform(option)
        if option in self.options():
            self.__getitem__(option).value = value
        else:
            self.__setitem__(option, value)
        return self

Response: Set an option for chaining.


Instruction:
Can you generate the documentation for the following Python 3 function
def set_values(self, values, separator='\n', indent=4*' '):
        self._updated = True
        self._multiline_value_joined = True
        self._values = values
        if separator == '\n':
            values.insert(0, '')
            separator = separator + indent
        self._value = separator.join(values)

Response: Sets the value of the option to a given list of options e. g. multi - line values


Instruction:
Make a summary of the following Python 3 code
def read(self, filename, encoding=None):
        with open(filename, encoding=encoding) as fp:
            self._read(fp, filename)
        self._filename = os.path.abspath(filename)

Response: Read and parse a file.


Instruction:
How would you explain what the following Python 3 function does
def update_file(self):
        if self._filename is None:
            raise NoConfigFileReadError()
        with open(self._filename, 'w') as fb:
            self.write(fb)

Response: Update the read - in configuration file.


Instruction:
Can you generate the documentation for the following Python 3 function
def validate_format(self, **kwargs):
        args = dict(
            dict_type=self._dict,
            allow_no_value=self._allow_no_value,
            inline_comment_prefixes=self._inline_comment_prefixes,
            strict=self._strict,
            empty_lines_in_values=self._empty_lines_in_values
        )
        args.update(kwargs)
        parser = ConfigParser(**args)
        updated_cfg = str(self)
        parser.read_string(updated_cfg)

Response: Call ConfigParser to validate config


Instruction:
Given the following Python 3 function, write the documentation
def add_section(self, section):
        if section in self.sections():
            raise DuplicateSectionError(section)
        if isinstance(section, str):
            # create a new section
            section = Section(section, container=self)
        elif not isinstance(section, Section):
            raise ValueError("Parameter must be a string or Section type!")
        self._structure.append(section)

Response: Add a section to the configuration.


Instruction:
Here you have a function in Python 3, explain what it does
def options(self, section):
        if not self.has_section(section):
            raise NoSectionError(section) from None
        return self.__getitem__(section).options()

Response: Returns list of configuration options for the named section.


Instruction:
Create a Python 3 function for
getting an option value for a given section.

Response:
def get(self, section, option):
        """Gets an option value for a given section.

        Args:
            section (str): section name
            option (str): option name

        Returns:
            :class:`Option`: Option object holding key/value pair
        """
        if not self.has_section(section):
            raise NoSectionError(section) from None

        section = self.__getitem__(section)
        option = self.optionxform(option)
        try:
            value = section[option]
        except KeyError:
            raise NoOptionError(option, section)

        return value


Instruction:
Create a Python 3 function for
returning a list of tuples for options or sections.

Response:
def items(self, section=_UNSET):
        """Return a list of (name, value) tuples for options or sections.

        If section is given, return a list of tuples with (name, value) for
        each option in the section. Otherwise, return a list of tuples with
        (section_name, section_type) for each section.

        Args:
            section (str): optional section name, default UNSET

        Returns:
            list: list of :class:`Section` or :class:`Option` objects
        """
        if section is _UNSET:
            return [(sect.name, sect) for sect in self.sections_blocks()]

        section = self.__getitem__(section)
        return [(opt.key, opt) for opt in section.option_blocks()]


Instruction:
Can you tell what is the following Python 3 function doing
def has_option(self, section, option):
        if section not in self.sections():
            return False
        else:
            option = self.optionxform(option)
            return option in self[section]

Response: Checks if an option exists in a given section.


Instruction:
Create a Python 3 function for
setting an option. value

Response:
def set(self, section, option, value=None):
        """Set an option.

        Args:
            section (str): section name
            option (str): option name
            value (str): value, default None
        """
        try:
            section = self.__getitem__(section)
        except KeyError:
            raise NoSectionError(section) from None
        option = self.optionxform(option)
        if option in section:
            section[option].value = value
        else:
            section[option] = value
        return self


Instruction:
Write a Python 3 function for
removing an option from a section.

Response:
def remove_option(self, section, option):
        """Remove an option.

        Args:
            section (str): section name
            option (str): option name

        Returns:
            bool: whether the option was actually removed
        """
        try:
            section = self.__getitem__(section)
        except KeyError:
            raise NoSectionError(section) from None
        option = self.optionxform(option)
        existed = option in section.options()
        if existed:
            del section[option]
        return existed


Instruction:
Can you tell what is the following Python 3 function doing
def remove_section(self, name):
        existed = self.has_section(name)
        if existed:
            idx = self._get_section_idx(name)
            del self._structure[idx]
        return existed

Response: Removes a section from the file.