Instruction:
Can you generate the documentation for the following Python 3 function
def get(cls):

        if PyFunceble.INTERN["to_test_type"] == "domain":
            # We are testing for domain or ip.

            if Check().is_domain_valid() or Check().is_ip_valid():
                # * The domain is valid.
                # or
                # * The IP is valid.

                # We handle and return the valid status.
                return SyntaxStatus(PyFunceble.STATUS["official"]["valid"]).handle()
        elif PyFunceble.INTERN["to_test_type"] == "url":
            # We are testing for URL.

            if Check().is_url_valid():
                # * The url is valid.

                # We handle and return the valid status.
                return SyntaxStatus(PyFunceble.STATUS["official"]["valid"]).handle()
        else:
            raise Exception("Unknow test type.")

        # We handle and return the invalid status.
        return SyntaxStatus(PyFunceble.STATUS["official"]["invalid"]).handle()

Response: Execute the logic behind the Syntax handling.


Instruction:
Here you have a function in Python 3, explain what it does
def _reformat_historical_formating_error(self):  # pragma: no cover

        if PyFunceble.CONFIGURATION["inactive_database"]:
            # The database subsystem is activated.

            # We construct the possible path to an older version of the database.
            historical_formating_error = (
                PyFunceble.CURRENT_DIRECTORY + "inactive-db.json"
            )

            if PyFunceble.path.isfile(historical_formating_error):
                # The histortical file already exists.

                # We get its content.
                data = Dict().from_json(File(historical_formating_error).read())

                # We initiate a variable which will save the data that is going
                # to be merged.
                data_to_parse = {}

                # We get the database keybase.
                top_keys = data.keys()

                for top_key in top_keys:
                    # We loop through the list of upper keys.

                    # We get the lowest keys.
                    low_keys = data[top_key].keys()

                    # We initiate the data to parse.
                    data_to_parse[top_key] = {}

                    for low_key in low_keys:
                        # We loop through the list of lower keys.

                        if low_key.isdigit():
                            # The current low key is a digit.

                            # We parse its content (from the old) into the new format.
                            # In between, we remove 30 days from the low_key so that
                            # it become in the past. This way they will be retested
                            # automatically.
                            data_to_parse[top_key][
                                int(low_key) - (self.one_day_in_seconds * 30)
                            ] = data[top_key][low_key]
                        else:
                            # The current low key is not a digit.

                            # We parse its content (from the old) into the new format.
                            # In between, we remove 30 days from the current time so that
                            # it become in the past. This way they will be retested
                            # automatically.
                            data_to_parse[top_key][
                                int(PyFunceble.time()) - (self.one_day_in_seconds * 30)
                            ] = data[top_key][low_key]

                if "inactive_db" in PyFunceble.INTERN:
                    # The current (new) database is not empty.

                    # We update add the content of the old into the current database.
                    PyFunceble.INTERN["inactive_db"].update(data_to_parse)
                else:
                    # The current (new) database is empty.

                    # We replace the content with the data_to_parse as it is complient
                    # with the new format.
                    PyFunceble.INTERN["inactive_db"] = data_to_parse

                # We delete the old database file.
                File(historical_formating_error).delete()

Response: Reformat the historical formating error into the new format.


Instruction:
Can you generate the documentation for the following Python 3 function
def _merge(self):

        if PyFunceble.CONFIGURATION["inactive_database"]:
            # The database subsystem is activated.

            # We get the content of the database.
            database_content = Dict().from_json(File(self.inactive_db_path).read())

            # We get the database top keys.
            database_top_keys = database_content.keys()

            for database_top_key in database_top_keys:
                # We loop through the list of database top keys.

                if database_top_key not in PyFunceble.INTERN["inactive_db"]:
                    # The currently read top key is not already into the database.

                    # We initiate the currently read key with the same key from
                    # our database file.
                    PyFunceble.INTERN["inactive_db"][
                        database_top_key
                    ] = database_content[database_top_key]
                else:
                    # The currently read top key is already into the database.

                    # We get the list of lower indexes.
                    database_low_keys = database_content[database_top_key].keys()

                    for database_low_key in database_low_keys:
                        # We loop through the lower keys.

                        if (
                            database_low_key
                            not in PyFunceble.INTERN["inactive_db"][database_top_key]
                        ):  # pragma: no cover
                            # The lower key is not already into the database.

                            # We initiate the currently read low and top key with the
                            # same combinaison from our database file.
                            PyFunceble.INTERN["inactive_db"][database_top_key][
                                database_low_key
                            ] = database_content[database_top_key][database_low_key]
                        else:
                            # The lower key is not already into the database.

                            # We exted the currently read low and top key combinaison
                            # with the same combinaison from our database file.
                            PyFunceble.INTERN["inactive_db"][database_top_key][
                                database_low_key
                            ].extend(
                                database_content[database_top_key][database_low_key]
                            )

                            # And we format the list of element to ensure that there is no
                            # duplicate into the database content.
                            PyFunceble.INTERN["inactive_db"][database_top_key][
                                database_low_key
                            ] = List(
                                PyFunceble.INTERN["inactive_db"][database_top_key][
                                    database_low_key
                                ]
                            ).format()

Response: Merge the real database with the older one which has already been set into the inactive database.


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

        if PyFunceble.CONFIGURATION["inactive_database"]:
            # The database subsystem is activated.

            # We get, format and initiate the historical database file.
            self._reformat_historical_formating_error()

            if PyFunceble.path.isfile(self.inactive_db_path):
                # The database file exist.

                # We merge our current database into already initiated one.
                self._merge()

Response: Retrieve the current content of the inactive - db. json file.


Instruction:
Write a Python 3 script for
saving the current database into the inactive-db.json file.

Response:
def _backup(self):
        """
        Save the current database into the inactive-db.json file.
        """

        if PyFunceble.CONFIGURATION["inactive_database"]:
            # The database subsystem is activated.

            # We save the current database state into the database file.
            Dict(PyFunceble.INTERN["inactive_db"]).to_json(self.inactive_db_path)


Instruction:
Can you generate the documentation for the following Python 3 function
def _timestamp(self):

        if PyFunceble.CONFIGURATION["inactive_database"]:
            # The database subsystem is activated.

            if (
                "inactive_db" in PyFunceble.INTERN
                and PyFunceble.INTERN["file_to_test"]
                in PyFunceble.INTERN["inactive_db"]
                and PyFunceble.INTERN["inactive_db"][PyFunceble.INTERN["file_to_test"]]
            ):
                # The file we are testing is into the database and its content
                # is not empty.

                # We get the indexes of the current file (in the dabase).
                database_keys = [
                    x
                    for x in PyFunceble.INTERN["inactive_db"][
                        PyFunceble.INTERN["file_to_test"]
                    ].keys()
                    if x.isdigit()
                ]

                if database_keys:
                    # The list of keys is not empty.

                    # We get the most recent date.
                    recent_date = max(database_keys)
                else:  # pragma: no cover
                    # The list of keys is empty.

                    # We return the current time.
                    return int(PyFunceble.time())

                if int(PyFunceble.time()) > int(recent_date) + self.one_day_in_seconds:
                    # The most recent time was in more than one day.

                    # We return the current time.
                    return int(PyFunceble.time())

                # The most recent time was in less than one day.

                if int(PyFunceble.time()) < int(recent_date) + self.days_in_seconds:
                    # The most recent time was in less than the expected number of day for
                    # retesting.

                    # We return the most recent data.
                    return int(recent_date)

        # The database subsystem is not activated.

        # We return the current time.
        return int(PyFunceble.time())

Response: Return the timestamp where we are going to save our current list.


Instruction:
Implement a Python 3 function for
adding the current time to the database.

Response:
def add(self):
        """
        Save the current :code.`PyFunceble.CONFIGURATION['to_test']`
        into the current timestamp.
        """

        if PyFunceble.CONFIGURATION["inactive_database"]:
            # The database subsystem is activated.

            # We get the timestamp to use as index.
            timestamp = str(self._timestamp())

            if (
                "inactive_db" in PyFunceble.INTERN
                and PyFunceble.INTERN["file_to_test"]
                in PyFunceble.INTERN["inactive_db"]
            ):
                # * The file path is not into the database.

                if (
                    timestamp
                    in PyFunceble.INTERN["inactive_db"][
                        PyFunceble.INTERN["file_to_test"]
                    ]
                ):
                    # The timetamp is already into the database related to the file we
                    # are testing.

                    if (
                        PyFunceble.INTERN["to_test"]
                        not in PyFunceble.INTERN["inactive_db"][
                            PyFunceble.INTERN["file_to_test"]
                        ][timestamp]
                    ):
                        # The currently tested element is not into the database related
                        # to the file we are testing.

                        # We append the currently tested element into the database.
                        PyFunceble.INTERN["inactive_db"][
                            PyFunceble.INTERN["file_to_test"]
                        ][timestamp].append(PyFunceble.INTERN["to_test"])
                else:
                    # The timetamp is not into the database related to the file we
                    # are testing.

                    # We append the index and the database element into the databse
                    # related to the file we are testing.
                    PyFunceble.INTERN["inactive_db"][
                        PyFunceble.INTERN["file_to_test"]
                    ].update({timestamp: [PyFunceble.INTERN["to_test"]]})

                if (
                    "to_test"
                    in PyFunceble.INTERN["inactive_db"][
                        PyFunceble.INTERN["file_to_test"]
                    ]
                    and PyFunceble.INTERN["to_test"]
                    in PyFunceble.INTERN["inactive_db"][
                        PyFunceble.INTERN["file_to_test"]
                    ]["to_test"]
                ):
                    # * The `to_test` index is into the database related to the file we
                    #   are testing.
                    # and
                    # * The element we are testing is into the `to_test` index related to
                    #   the file we are testing.

                    # We remove the element from the list of element to test.
                    PyFunceble.INTERN["inactive_db"][PyFunceble.INTERN["file_to_test"]][
                        "to_test"
                    ].remove(PyFunceble.INTERN["to_test"])
            else:
                # The file path is not into the database.

                # We initiate the file path and its content into the database.
                PyFunceble.INTERN["inactive_db"] = {
                    PyFunceble.INTERN["file_to_test"]: {
                        timestamp: [PyFunceble.INTERN["to_test"]]
                    }
                }

            # And we save the data into the database.
            self._backup()


Instruction:
Implement a Python 3 function for
removing all occurence of to_test from the database.

Response:
def remove(self):
        """
        Remove all occurence of :code:`PyFunceble.CONFIGURATION['to_test']`
        from the database.
        """

        if PyFunceble.CONFIGURATION["inactive_database"]:
            # The database subsystem is activated.

            if PyFunceble.INTERN["file_to_test"] in PyFunceble.INTERN["inactive_db"]:
                #  The file path is into the database.

                for data in PyFunceble.INTERN["inactive_db"][
                    PyFunceble.INTERN["file_to_test"]
                ]:
                    # We loop through the index of the file database.

                    if (
                        PyFunceble.INTERN["to_test"]
                        in PyFunceble.INTERN["inactive_db"][
                            PyFunceble.INTERN["file_to_test"]
                        ][data]
                    ):
                        # The currently tested element into the currently read index.

                        # We remove the currently tested element from the read index.
                        PyFunceble.INTERN["inactive_db"][
                            PyFunceble.INTERN["file_to_test"]
                        ][data].remove(PyFunceble.INTERN["to_test"])

            # And we save the data into the database.
            self._backup()


Instruction:
How would you implement a function in Python 3 that
gets the content of the database.

Response:
def content(cls):
        """
        Get the content of the database.

        :return: The content of the database.
        :rtype: list
        """

        # We initiate a variable which will save what we are going to return.
        result = []

        if (
            PyFunceble.CONFIGURATION["inactive_database"]
            and PyFunceble.INTERN["inactive_db"]
        ):
            # * The database subsystem is activated.
            # and
            # * The database is not empty.

            for key in PyFunceble.INTERN["inactive_db"][
                PyFunceble.INTERN["file_to_test"]
            ]:
                # We loop through the index of the current file database.

                if key == "to_test":
                    # The current key is `to_test`.

                    # We continue to the next element.
                    continue

                # We extend the result with the content of the currently read index.
                result.extend(
                    PyFunceble.INTERN["inactive_db"][PyFunceble.INTERN["file_to_test"]][
                        key
                    ]
                )

        # We return the content of the database.
        return result


Instruction:
Write a Python 3 function for
checking if the currently tested element is into the database.

Response:
def is_present(cls):
        """
        Check if the currently tested element is into the database.
        """

        if PyFunceble.CONFIGURATION["inactive_database"]:
            # The database subsystem is activated.

            if PyFunceble.INTERN["to_test"] in PyFunceble.INTERN[
                "flatten_inactive_db"
            ] or (
                PyFunceble.INTERN["file_to_test"] in PyFunceble.INTERN["inactive_db"]
                and PyFunceble.INTERN["inactive_db"][PyFunceble.INTERN["file_to_test"]]
                and "to_test"
                in PyFunceble.INTERN["inactive_db"][PyFunceble.INTERN["file_to_test"]]
                and PyFunceble.INTERN["to_test"]
                in PyFunceble.INTERN["inactive_db"][PyFunceble.INTERN["file_to_test"]][
                    "to_test"
                ]
            ):
                return True

        return False


Instruction:
Write a Python 3 function for
retrieving the data from the database.

Response:
def _retrieve(self):
        """
        Retrieve the data from the database.
        """

        if self._authorization() and "whois_db" not in PyFunceble.INTERN:
            # The usage of the whois database is activated.

            if PyFunceble.path.isfile(self.whois_db_path):
                # The database file exist.

                # We merge our current database into already initiated one.
                PyFunceble.INTERN["whois_db"] = Dict().from_json(
                    File(self.whois_db_path).read()
                )
            else:
                # The database file does not exist.

                # We initiate an empty database.
                PyFunceble.INTERN["whois_db"] = {}


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

        if (
            self._authorization()
            and PyFunceble.INTERN["file_to_test"] in PyFunceble.INTERN["whois_db"]
            and PyFunceble.INTERN["to_test"]
            in PyFunceble.INTERN["whois_db"][PyFunceble.INTERN["file_to_test"]]
        ):
            # * We are authorized to work.
            # and
            # * The given file path exist in the database.
            # and
            # * The element we are testing is in the database related to the
            # given file path.

            # We return True, the element we are testing is into the database.
            return True

        # * We are not authorized to work.
        # or
        # * The given file path does not exist in the database.
        # or
        # * The element we are testing is not in the database related to the
        # given file path.

        # We return False,the element we are testing is not into the database.
        return False

Response: Check if the element is in the database.


Instruction:
How would you implement a function in Python 3 that
checks if the current time is older than the one in the database.

Response:
def is_time_older(self):
        """
        Check if the current time is older than the one in the database.
        """

        if (
            self._authorization()
            and self.is_in_database()
            and int(
                PyFunceble.INTERN["whois_db"][PyFunceble.INTERN["file_to_test"]][
                    PyFunceble.INTERN["to_test"]
                ]["epoch"]
            )
            < int(PyFunceble.time())
        ):
            # * We are authorized to work.
            # and
            # * The element we are testing is in the database.
            # and
            # * The epoch of the expiration date is less than our current epoch.

            # The expiration date is in the past, we return True.
            return True

        # The expiration date is in the future, we return False.
        return False


Instruction:
How would you code a function in Python 3 to
get the expiration date from the database.

Response:
def get_expiration_date(self):
        """
        Get the expiration date from the database.

        :return: The expiration date from the database.
        :rtype: str|None
        """

        if self._authorization() and self.is_in_database() and not self.is_time_older():
            # * We are authorized to work.
            # and
            # * The element we are testing is in the database.
            # and
            # * The expiration date is in the future.

            # We get the expiration date from the database.
            result = PyFunceble.INTERN["whois_db"][PyFunceble.INTERN["file_to_test"]][
                PyFunceble.INTERN["to_test"]
            ]["expiration_date"]

            if result:
                # The expiration date from the database is not empty nor
                # equal to None.

                # We return it.
                return result

        # We return None, there is no data to work with.
        return None


Instruction:
Implement a Python 3 function for
adding the currently tested element into the database.

Response:
def add(self):
        """
        Add the currently tested element into the database.
        """

        if self._authorization():
            # We are authorized to work.

            if self.epoch < int(PyFunceble.time()):
                state = "past"
            else:
                state = "future"

            if self.is_in_database():
                # The element we are working with is in the database.

                if (
                    str(self.epoch)
                    != PyFunceble.INTERN["whois_db"][PyFunceble.INTERN["file_to_test"]][
                        PyFunceble.INTERN["to_test"]
                    ]["epoch"]
                ):
                    # The given epoch is diffent from the one saved.

                    # We update it.
                    PyFunceble.INTERN["whois_db"][PyFunceble.INTERN["file_to_test"]][
                        PyFunceble.INTERN["to_test"]
                    ].update(
                        {
                            "epoch": str(self.epoch),
                            "state": state,
                            "expiration_date": self.expiration_date,
                        }
                    )

                elif self.is_time_older():
                    # The expiration date from the database is in the past.

                    if (
                        PyFunceble.INTERN["whois_db"][
                            PyFunceble.INTERN["file_to_test"]
                        ][PyFunceble.INTERN["to_test"]]["state"]
                        != "past"
                    ):  # pragma: no cover
                        # The state of the element in the datbase is not
                        # equal to `past`.

                        # We update it to `past`.
                        PyFunceble.INTERN["whois_db"][
                            PyFunceble.INTERN["file_to_test"]
                        ][PyFunceble.INTERN["to_test"]].update({"state": "past"})
                elif (
                    PyFunceble.INTERN["whois_db"][PyFunceble.INTERN["file_to_test"]][
                        PyFunceble.INTERN["to_test"]
                    ]["state"]
                    != "future"
                ):
                    # * The expiration date from the database is in the future.
                    # and
                    # * The state of the element in the database is not
                    # equal to `future`.

                    # We update it to `future`.
                    PyFunceble.INTERN["whois_db"][PyFunceble.INTERN["file_to_test"]][
                        PyFunceble.INTERN["to_test"]
                    ].update({"state": "future"})
            else:
                # The element we are working with is not in the database.

                if (
                    not PyFunceble.INTERN["file_to_test"]
                    in PyFunceble.INTERN["whois_db"]
                ):
                    # The file path is not in the database.

                    # We initiate it.
                    PyFunceble.INTERN["whois_db"][
                        PyFunceble.INTERN["file_to_test"]
                    ] = {}

                # We create the first dataset.
                PyFunceble.INTERN["whois_db"][PyFunceble.INTERN["file_to_test"]].update(
                    {
                        PyFunceble.INTERN["to_test"]: {
                            "epoch": str(self.epoch),
                            "state": state,
                            "expiration_date": self.expiration_date,
                        }
                    }
                )

            # We do a safety backup of our database.
            self._backup()


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

        if PyFunceble.CONFIGURATION["travis"]:
            try:
                build_dir = PyFunceble.environ["TRAVIS_BUILD_DIR"]
                commands = [
                    "sudo chown -R travis:travis %s" % (build_dir),
                    "sudo chgrp -R travis %s" % (build_dir),
                    "sudo chmod -R g+rwX %s" % (build_dir),
                    "sudo chmod 777 -Rf %s.git"
                    % (build_dir + PyFunceble.directory_separator),
                    r"sudo find %s -type d -exec chmod g+x '{}' \;" % (build_dir),
                ]

                for command in commands:
                    Command(command).execute()

                if Command("git config core.sharedRepository").execute() == "":
                    Command("git config core.sharedRepository group").execute()
            except KeyError:
                pass

Response: Set permissions for the travis project.


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

        if PyFunceble.CONFIGURATION["travis"]:
            try:
                _ = PyFunceble.environ["TRAVIS_BUILD_DIR"]
                time_autorisation = False

                try:
                    time_autorisation = int(PyFunceble.time()) >= int(
                        PyFunceble.INTERN["start"]
                    ) + (int(PyFunceble.CONFIGURATION["travis_autosave_minutes"]) * 60)
                except KeyError:
                    if self.last and not self.bypass:
                        raise Exception(
                            "Please review the way `ExecutionTime()` is called."
                        )

                if self.last or time_autorisation or self.bypass:
                    Percentage().log()
                    self.travis_permissions()

                    command = 'git add --all && git commit -a -m "%s"'

                    if self.last or self.bypass:
                        if PyFunceble.CONFIGURATION["command_before_end"]:
                            for line in Command(
                                PyFunceble.CONFIGURATION["command_before_end"]
                            ).run():
                                sys_stdout.write("{}\n".format(line))

                            self.travis_permissions()

                        message = (
                            PyFunceble.CONFIGURATION["travis_autosave_final_commit"]
                            + " [ci skip]"
                        )

                        Command(command % message).execute()
                    else:
                        if PyFunceble.CONFIGURATION["command"]:
                            for line in Command(
                                PyFunceble.CONFIGURATION["command"]
                            ).run():
                                sys_stdout.write("{}\n".format(line))

                            self.travis_permissions()

                        Command(
                            command % PyFunceble.CONFIGURATION["travis_autosave_commit"]
                        ).execute()

                    print(
                        Command(
                            "git push origin %s"
                            % PyFunceble.CONFIGURATION["travis_branch"]
                        ).execute()
                    )
                    exit(0)
            except KeyError:
                pass

Response: This function is called by the travis daemon when the application is running in Travis CI.


Instruction:
Can you write a function in Python 3 where it
executes the logic behind the URL handling.

Response:
def get(cls):  # pragma: no cover
        """
        Execute the logic behind the URL handling.

        :return: The status of the URL.
        :rtype: str
        """

        if Check().is_url_valid() or PyFunceble.CONFIGURATION["local"]:
            # * The url is valid.
            # or
            # * We are testing in/for a local or private network.

            if "current_test_data" in PyFunceble.INTERN:
                PyFunceble.INTERN["current_test_data"]["url_syntax_validation"] = True

            # We initiate the HTTP status code.
            PyFunceble.INTERN.update({"http_code": HTTPCode().get()})

            # We initiate the list of active status code.
            active_list = []
            active_list.extend(PyFunceble.HTTP_CODE["list"]["potentially_up"])
            active_list.extend(PyFunceble.HTTP_CODE["list"]["up"])

            # We initiate the list of inactive status code.
            inactive_list = []
            inactive_list.extend(PyFunceble.HTTP_CODE["list"]["potentially_down"])
            inactive_list.append("*" * 3)

            if PyFunceble.INTERN["http_code"] in active_list:
                # The extracted HTTP status code is in the list of active list.

                # We handle and return the up status.
                return URLStatus(PyFunceble.STATUS["official"]["up"]).handle()

            if PyFunceble.INTERN["http_code"] in inactive_list:
                # The extracted HTTP status code is in the list of inactive list.

                # We handle and return the down status.
                return URLStatus(PyFunceble.STATUS["official"]["down"]).handle()

        # The extracted HTTP status code is not in the list of active nor invalid list.

        if "current_test_data" in PyFunceble.INTERN:
            # The end-user want more information whith his test.

            # We update the url_syntax_validation index.
            PyFunceble.INTERN["current_test_data"]["url_syntax_validation"] = False

        # We handle and return the invalid down status.
        return URLStatus(PyFunceble.STATUS["official"]["invalid"]).handle()


Instruction:
Can you write a function in Python 3 where it
returns the referer aka the WHOIS server of the current domain extension.

Response:
def get(self):
        """
        Return the referer aka the WHOIS server of the current domain extension.
        """

        if not PyFunceble.CONFIGURATION["local"]:
            # We are not running a test in a local network.

            if self.domain_extension not in self.ignored_extension:
                # The extension of the domain we are testing is not into
                # the list of ignored extensions.

                # We set the referer to None as we do not have any.
                referer = None

                if self.domain_extension in PyFunceble.INTERN["iana_db"]:
                    # The domain extension is in the iana database.

                    if not PyFunceble.CONFIGURATION["no_whois"]:
                        # We are authorized to use WHOIS for the test result.

                        # We get the referer from the database.
                        referer = PyFunceble.INTERN["iana_db"][self.domain_extension]

                        if not referer:
                            # The referer is not filled.

                            # We log the case of the current extension.
                            Logs().referer_not_found(self.domain_extension)

                            # And we handle and return None status.
                            return None

                        # The referer is into the database.

                        # We return the extracted referer.
                        return referer

                    # We are not authorized to use WHOIS for the test result.

                    # We return None.
                    return None

                # The domain extension is not in the iana database.

                # We return False, it is an invalid domain.
                return False

            # The extension of the domain we are testing is not into
            # the list of ignored extensions.

            # We return None, the domain does not have a whois server.
            return None

        # We are running a test in a local network.

        # We return None.
        return None


Instruction:
Make a summary of the following Python 3 code
def _register_servicer(self, servicer):
        name = servicer.__name__
        if name in self._servicers:
            raise exceptions.ConfigException(
                'servicer duplicated: {}'.format(name))
        add_func = self._get_servicer_add_func(servicer)
        self._servicers[name] = (add_func, servicer)

Response:
register serviser

        :param servicer: servicer


Instruction:
Write a Python 3 script to
register an extension with the cache

Response:
def _register_extension(self, name, ext):
        """register extension

        :param name: extension name
        :param ext: extension object
        """
        ext.init_app(self)
        if name in self._extensions:
            raise exceptions.ConfigException(
                'extension duplicated: {}'.format(name))
        self._extensions[name] = ext


Instruction:
Create a Python 3 function for
getting current object. This is useful if you want the real object behind the proxy at a time for performance reasons or because you want to pass the object into a different context.

Response:
def _get_current_object(self):
        """Get current object.
        This is useful if you want the real
        object behind the proxy at a time for performance reasons or because
        you want to pass the object into a different context.
        """
        loc = object.__getattribute__(self, '_Proxy__local')
        if not hasattr(loc, '__release_local__'):
            return loc(*self.__args, **self.__kwargs)
        try:  # pragma: no cover
            # not sure what this is about
            return getattr(loc, self.__name__)
        except AttributeError:  # pragma: no cover
            raise RuntimeError('no object bound to {0.__name__}'.format(self))


Instruction:
Can you write a function in Python 3 where it
yields paths to standard modules.

Response:
def standard_paths():
    """Yield paths to standard modules."""
    for is_plat_spec in [True, False]:
        path = distutils.sysconfig.get_python_lib(standard_lib=True,
                                                  plat_specific=is_plat_spec)

        for name in os.listdir(path):
            yield name

        try:
            for name in os.listdir(os.path.join(path, 'lib-dynload')):
                yield name
        except OSError:  # pragma: no cover
            pass


Instruction:
How would you implement a function in Python 3 that
yields all standard module names.

Response:
def standard_package_names():
    """Yield standard module names."""
    for name in standard_paths():
        if name.startswith('_') or '-' in name:
            continue

        if '.' in name and name.rsplit('.')[-1] not in ['so', 'py', 'pyc']:
            continue

        yield name.split('.')[0]


Instruction:
Can you create a Python 3 function that
yields line numbers of unused imports.

Response:
def unused_import_line_numbers(messages):
    """Yield line numbers of unused imports."""
    for message in messages:
        if isinstance(message, pyflakes.messages.UnusedImport):
            yield message.lineno


Instruction:
Can you create a Python 3 function that
yields line number and module name of unused imports.

Response:
def unused_import_module_name(messages):
    """Yield line number and module name of unused imports."""
    pattern = r'\'(.+?)\''
    for message in messages:
        if isinstance(message, pyflakes.messages.UnusedImport):
            module_name = re.search(pattern, str(message))
            module_name = module_name.group()[1:-1]
            if module_name:
                yield (message.lineno, module_name)


Instruction:
How would you implement a function in Python 3 that
yields line numbers of star import used messages.

Response:
def star_import_used_line_numbers(messages):
    """Yield line number of star import usage."""
    for message in messages:
        if isinstance(message, pyflakes.messages.ImportStarUsed):
            yield message.lineno


Instruction:
How would you code a function in Python 3 to
yield line number undefined name and its possible origin module.

Response:
def star_import_usage_undefined_name(messages):
    """Yield line number, undefined name, and its possible origin module."""
    for message in messages:
        if isinstance(message, pyflakes.messages.ImportStarUsage):
            undefined_name = message.message_args[0]
            module_name = message.message_args[1]
            yield (message.lineno, undefined_name, module_name)


Instruction:
Can you tell what is the following Python 3 function doing
def unused_variable_line_numbers(messages):
    for message in messages:
        if isinstance(message, pyflakes.messages.UnusedVariable):
            yield message.lineno

Response: Yield line numbers of unused variables.


Instruction:
Here you have a function in Python 3, explain what it does
def duplicate_key_line_numbers(messages, source):
    messages = [
        message for message in messages
        if isinstance(message, pyflakes.messages.MultiValueRepeatedKeyLiteral)]

    if messages:
        # Filter out complex cases. We don't want to bother trying to parse
        # this stuff and get it right. We can do it on a key-by-key basis.

        key_to_messages = create_key_to_messages_dict(messages)

        lines = source.split('\n')

        for (key, messages) in key_to_messages.items():
            good = True
            for message in messages:
                line = lines[message.lineno - 1]
                key = message.message_args[0]

                if not dict_entry_has_key(line, key):
                    good = False

            if good:
                for message in messages:
                    yield message.lineno

Response: Yield line numbers of duplicate keys.


Instruction:
Create a Python 3 function to
return dict mapping the key to list of messages.

Response:
def create_key_to_messages_dict(messages):
    """Return dict mapping the key to list of messages."""
    dictionary = collections.defaultdict(lambda: [])
    for message in messages:
        dictionary[message.message_args[0]].append(message)
    return dictionary


Instruction:
Can you generate a brief explanation for the following Python 3 code
def check(source):
    if sys.version_info[0] == 2 and isinstance(source, unicode):
        # Convert back to original byte string encoding, otherwise pyflakes
        # call to compile() will complain. See PEP 263. This only affects
        # Python 2.
        try:
            source = source.encode('utf-8')
        except UnicodeError:  # pragma: no cover
            return []

    reporter = ListReporter()
    try:
        pyflakes.api.check(source, filename='<string>', reporter=reporter)
    except (AttributeError, RecursionError, UnicodeDecodeError):
        pass
    return reporter.messages

Response: Return messages from pyflakes.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def extract_package_name(line):
    assert '\\' not in line
    assert '(' not in line
    assert ')' not in line
    assert ';' not in line

    if line.lstrip().startswith(('import', 'from')):
        word = line.split()[1]
    else:
        # Ignore doctests.
        return None

    package = word.split('.')[0]
    assert ' ' not in package

    return package

Response: Return package name in import statement.


Instruction:
Can you write a function in Python 3 where it
returns True if import is spans multiples lines.

Response:
def multiline_import(line, previous_line=''):
    """Return True if import is spans multiples lines."""
    for symbol in '()':
        if symbol in line:
            return True

    # Ignore doctests.
    if line.lstrip().startswith('>'):
        return True

    return multiline_statement(line, previous_line)


Instruction:
Make a summary of the following Python 3 code
def multiline_statement(line, previous_line=''):
    for symbol in '\\:;':
        if symbol in line:
            return True

    sio = io.StringIO(line)
    try:
        list(tokenize.generate_tokens(sio.readline))
        return previous_line.rstrip().endswith('\\')
    except (SyntaxError, tokenize.TokenError):
        return True

Response: Return True if this is part of a multiline statement.


Instruction:
Can you tell what is the following Python 3 function doing
def filter_from_import(line, unused_module):
    (indentation, imports) = re.split(pattern=r'\bimport\b',
                                      string=line, maxsplit=1)
    base_module = re.search(pattern=r'\bfrom\s+([^ ]+)',
                            string=indentation).group(1)

    # Create an imported module list with base module name
    # ex ``from a import b, c as d`` -> ``['a.b', 'a.c as d']``
    imports = re.split(pattern=r',', string=imports.strip())
    imports = [base_module + '.' + x.strip() for x in imports]

    # We compare full module name (``a.module`` not `module`) to
    # guarantee the exact same module as detected from pyflakes.
    filtered_imports = [x.replace(base_module + '.', '')
                        for x in imports if x not in unused_module]

    # All of the import in this statement is unused
    if not filtered_imports:
        return get_indentation(line) + 'pass' + get_line_ending(line)

    indentation += 'import '

    return (
        indentation +
        ', '.join(sorted(filtered_imports)) +
        get_line_ending(line))

Response: Parse and filter from something import a b c as d.


Instruction:
Write a Python 3 script for
returning line with imports on separate lines.

Response:
def break_up_import(line):
    """Return line with imports on separate lines."""
    assert '\\' not in line
    assert '(' not in line
    assert ')' not in line
    assert ';' not in line
    assert '#' not in line
    assert not line.lstrip().startswith('from')

    newline = get_line_ending(line)
    if not newline:
        return line

    (indentation, imports) = re.split(pattern=r'\bimport\b',
                                      string=line, maxsplit=1)

    indentation += 'import '
    assert newline

    return ''.join([indentation + i.strip() + newline
                    for i in sorted(imports.split(','))])


Instruction:
Given the following Python 3 function, write the documentation
def filter_code(source, additional_imports=None,
                expand_star_imports=False,
                remove_all_unused_imports=False,
                remove_duplicate_keys=False,
                remove_unused_variables=False,
                ignore_init_module_imports=False,
                ):
    """Yield code with unused imports removed."""
    imports = SAFE_IMPORTS
    if additional_imports:
        imports |= frozenset(additional_imports)
    del additional_imports

    messages = check(source)

    if ignore_init_module_imports:
        marked_import_line_numbers = frozenset()
    else:
        marked_import_line_numbers = frozenset(
            unused_import_line_numbers(messages))
    marked_unused_module = collections.defaultdict(lambda: [])
    for line_number, module_name in unused_import_module_name(messages):
        marked_unused_module[line_number].append(module_name)

    if expand_star_imports and not (
        # See explanations in #18.
        re.search(r'\b__all__\b', source) or
        re.search(r'\bdel\b', source)
    ):
        marked_star_import_line_numbers = frozenset(
            star_import_used_line_numbers(messages))
        if len(marked_star_import_line_numbers) > 1:
            # Auto expanding only possible for single star import
            marked_star_import_line_numbers = frozenset()
        else:
            undefined_names = []
            for line_number, undefined_name, _ \
                    in star_import_usage_undefined_name(messages):
                undefined_names.append(undefined_name)
            if not undefined_names:
                marked_star_import_line_numbers = frozenset()
    else:
        marked_star_import_line_numbers = frozenset()

    if remove_unused_variables:
        marked_variable_line_numbers = frozenset(
            unused_variable_line_numbers(messages))
    else:
        marked_variable_line_numbers = frozenset()

    if remove_duplicate_keys:
        marked_key_line_numbers = frozenset(
            duplicate_key_line_numbers(messages, source))
    else:
        marked_key_line_numbers = frozenset()

    line_messages = get_messages_by_line(messages)

    sio = io.StringIO(source)
    previous_line = ''
    for line_number, line in enumerate(sio.readlines(), start=1):
        if '#' in line:
            yield line
        elif line_number in marked_import_line_numbers:
            yield filter_unused_import(
                line,
                unused_module=marked_unused_module[line_number],
                remove_all_unused_imports=remove_all_unused_imports,
                imports=imports,
                previous_line=previous_line)
        elif line_number in marked_variable_line_numbers:
            yield filter_unused_variable(line)
        elif line_number in marked_key_line_numbers:
            yield filter_duplicate_key(line, line_messages[line_number],
                                       line_number, marked_key_line_numbers,
                                       source)
        elif line_number in marked_star_import_line_numbers:
            yield filter_star_import(line, undefined_names)
        else:
            yield line

        previous_line = line

Response: Yields code with unused imports removed.


Instruction:
Write a Python 3 function for
returning dictionary that maps line number to message.

Response:
def get_messages_by_line(messages):
    """Return dictionary that maps line number to message."""
    line_messages = {}
    for message in messages:
        line_messages[message.lineno] = message
    return line_messages


Instruction:
How would you implement a function in Python 3 that
returns line with the star import expanded.

Response:
def filter_star_import(line, marked_star_import_undefined_name):
    """Return line with the star import expanded."""
    undefined_name = sorted(set(marked_star_import_undefined_name))
    return re.sub(r'\*', ', '.join(undefined_name), line)


Instruction:
Create a Python 3 function for
returning line if used otherwise return None.

Response:
def filter_unused_import(line, unused_module, remove_all_unused_imports,
                         imports, previous_line=''):
    """Return line if used, otherwise return None."""
    if multiline_import(line, previous_line):
        return line

    is_from_import = line.lstrip().startswith('from')

    if ',' in line and not is_from_import:
        return break_up_import(line)

    package = extract_package_name(line)
    if not remove_all_unused_imports and package not in imports:
        return line

    if ',' in line:
        assert is_from_import
        return filter_from_import(line, unused_module)
    else:
        # We need to replace import with "pass" in case the import is the
        # only line inside a block. For example,
        # "if True:\n    import os". In such cases, if the import is
        # removed, the block will be left hanging with no body.
        return (get_indentation(line) +
                'pass' +
                get_line_ending(line))


Instruction:
Explain what the following Python 3 code does
def filter_unused_variable(line, previous_line=''):
    if re.match(EXCEPT_REGEX, line):
        return re.sub(r' as \w+:$', ':', line, count=1)
    elif multiline_statement(line, previous_line):
        return line
    elif line.count('=') == 1:
        split_line = line.split('=')
        assert len(split_line) == 2
        value = split_line[1].lstrip()
        if ',' in split_line[0]:
            return line

        if is_literal_or_name(value):
            # Rather than removing the line, replace with it "pass" to avoid
            # a possible hanging block with no body.
            value = 'pass' + get_line_ending(line)

        return get_indentation(line) + value
    else:
        return line

Response: Return line if used otherwise return None.


Instruction:
How would you code a function in Python 3 to
return line if line_number is the first occurrence of the key otherwise return line.

Response:
def filter_duplicate_key(line, message, line_number, marked_line_numbers,
                         source, previous_line=''):
    """Return '' if first occurrence of the key otherwise return `line`."""
    if marked_line_numbers and line_number == sorted(marked_line_numbers)[0]:
        return ''

    return line


Instruction:
Can you tell what is the following Python 3 function doing
def dict_entry_has_key(line, key):
    if '#' in line:
        return False

    result = re.match(r'\s*(.*)\s*:\s*(.*),\s*$', line)
    if not result:
        return False

    try:
        candidate_key = ast.literal_eval(result.group(1))
    except (SyntaxError, ValueError):
        return False

    if multiline_statement(result.group(2)):
        return False

    return candidate_key == key

Response: Return True if line is a dict entry that uses key.


Instruction:
Given the following Python 3 function, write the documentation
def is_literal_or_name(value):
    try:
        ast.literal_eval(value)
        return True
    except (SyntaxError, ValueError):
        pass

    if value.strip() in ['dict()', 'list()', 'set()']:
        return True

    # Support removal of variables on the right side. But make sure
    # there are no dots, which could mean an access of a property.
    return re.match(r'^\w+\s*$', value)

Response: Return True if value is a literal or a name.


Instruction:
Write a Python 3 function for
yielding line numbers of unneeded pass statements.

Response:
def useless_pass_line_numbers(source):
    """Yield line numbers of unneeded "pass" statements."""
    sio = io.StringIO(source)
    previous_token_type = None
    last_pass_row = None
    last_pass_indentation = None
    previous_line = ''
    for token in tokenize.generate_tokens(sio.readline):
        token_type = token[0]
        start_row = token[2][0]
        line = token[4]

        is_pass = (token_type == tokenize.NAME and line.strip() == 'pass')

        # Leading "pass".
        if (start_row - 1 == last_pass_row and
                get_indentation(line) == last_pass_indentation and
                token_type in ATOMS and
                not is_pass):
            yield start_row - 1

        if is_pass:
            last_pass_row = start_row
            last_pass_indentation = get_indentation(line)

        # Trailing "pass".
        if (is_pass and
                previous_token_type != tokenize.INDENT and
                not previous_line.rstrip().endswith('\\')):
            yield start_row

        previous_token_type = token_type
        previous_line = line


Instruction:
Make a summary of the following Python 3 code
def filter_useless_pass(source):
    try:
        marked_lines = frozenset(useless_pass_line_numbers(source))
    except (SyntaxError, tokenize.TokenError):
        marked_lines = frozenset()

    sio = io.StringIO(source)
    for line_number, line in enumerate(sio.readlines(), start=1):
        if line_number not in marked_lines:
            yield line

Response: Yield code with useless pass lines removed.


Instruction:
Implement a Python 3 function for
returning code with all filtering run on it.

Response:
def fix_code(source, additional_imports=None, expand_star_imports=False,
             remove_all_unused_imports=False, remove_duplicate_keys=False,
             remove_unused_variables=False, ignore_init_module_imports=False):
    """Return code with all filtering run on it."""
    if not source:
        return source

    # pyflakes does not handle "nonlocal" correctly.
    if 'nonlocal' in source:
        remove_unused_variables = False

    filtered_source = None
    while True:
        filtered_source = ''.join(
            filter_useless_pass(''.join(
                filter_code(
                    source,
                    additional_imports=additional_imports,
                    expand_star_imports=expand_star_imports,
                    remove_all_unused_imports=remove_all_unused_imports,
                    remove_duplicate_keys=remove_duplicate_keys,
                    remove_unused_variables=remove_unused_variables,
                    ignore_init_module_imports=ignore_init_module_imports,
                ))))

        if filtered_source == source:
            break
        source = filtered_source

    return filtered_source


Instruction:
Implement a Python 3 function for
running fix_code() on a file.

Response:
def fix_file(filename, args, standard_out):
    """Run fix_code() on a file."""
    encoding = detect_encoding(filename)
    with open_with_encoding(filename, encoding=encoding) as input_file:
        source = input_file.read()

    original_source = source

    isInitFile = os.path.basename(filename) == '__init__.py'

    if args.ignore_init_module_imports and isInitFile:
        ignore_init_module_imports = True
    else:
        ignore_init_module_imports = False

    filtered_source = fix_code(
        source,
        additional_imports=args.imports.split(',') if args.imports else None,
        expand_star_imports=args.expand_star_imports,
        remove_all_unused_imports=args.remove_all_unused_imports,
        remove_duplicate_keys=args.remove_duplicate_keys,
        remove_unused_variables=args.remove_unused_variables,
        ignore_init_module_imports=ignore_init_module_imports,
    )

    if original_source != filtered_source:
        if args.check:
            standard_out.write('Unused imports/variables detected.')
            sys.exit(1)
        if args.in_place:
            with open_with_encoding(filename, mode='w',
                                    encoding=encoding) as output_file:
                output_file.write(filtered_source)
        else:
            diff = get_diff_text(
                io.StringIO(original_source).readlines(),
                io.StringIO(filtered_source).readlines(),
                filename)
            standard_out.write(''.join(diff))
    else:
        if args.check:
            standard_out.write('No issues detected!')


Instruction:
How would you implement a function in Python 3 that
detects encoding of a file.

Response:
def detect_encoding(filename, limit_byte_check=-1):
    """Return file encoding."""
    try:
        with open(filename, 'rb') as input_file:
            encoding = _detect_encoding(input_file.readline)

            # Check for correctness of encoding.
            with open_with_encoding(filename, encoding) as input_file:
                input_file.read(limit_byte_check)

        return encoding
    except (LookupError, SyntaxError, UnicodeDecodeError):
        return 'latin-1'


Instruction:
Write a Python 3 function for
detecting encoding of the file.

Response:
def _detect_encoding(readline):
    """Return file encoding."""
    try:
        from lib2to3.pgen2 import tokenize as lib2to3_tokenize
        encoding = lib2to3_tokenize.detect_encoding(readline)[0]
        return encoding
    except (LookupError, SyntaxError, UnicodeDecodeError):
        return 'latin-1'


Instruction:
Can you write a function in Python 3 where it
returns a set of strings.

Response:
def _split_comma_separated(string):
    """Return a set of strings."""
    return set(text.strip() for text in string.split(',') if text.strip())


Instruction:
Can you tell what is the following Python 3 function doing
def is_python_file(filename):
    if filename.endswith('.py'):
        return True

    try:
        with open_with_encoding(
                filename,
                None,
                limit_byte_check=MAX_PYTHON_FILE_DETECTION_BYTES) as f:
            text = f.read(MAX_PYTHON_FILE_DETECTION_BYTES)
            if not text:
                return False
            first_line = text.splitlines()[0]
    except (IOError, IndexError):
        return False

    if not PYTHON_SHEBANG_REGEX.match(first_line):
        return False

    return True

Response: Return True if filename is Python file.


Instruction:
Can you generate the documentation for the following Python 3 function
def is_exclude_file(filename, exclude):
    base_name = os.path.basename(filename)

    if base_name.startswith('.'):
        return True

    for pattern in exclude:
        if fnmatch.fnmatch(base_name, pattern):
            return True
        if fnmatch.fnmatch(filename, pattern):
            return True
    return False

Response: Return True if file matches exclude pattern.


Instruction:
Make a summary of the following Python 3 code
def match_file(filename, exclude):
    if is_exclude_file(filename, exclude):
        return False

    if not os.path.isdir(filename) and not is_python_file(filename):
        return False

    return True

Response: Return True if file is okay for modifying or recursing.


Instruction:
Write a Python 3 function for
yielding the names of all files in the archive.

Response:
def find_files(filenames, recursive, exclude):
    """Yield filenames."""
    while filenames:
        name = filenames.pop(0)
        if recursive and os.path.isdir(name):
            for root, directories, children in os.walk(name):
                filenames += [os.path.join(root, f) for f in children
                              if match_file(os.path.join(root, f),
                                            exclude)]
                directories[:] = [d for d in directories
                                  if match_file(os.path.join(root, d),
                                                exclude)]
        else:
            if not is_exclude_file(name, exclude):
                yield name


Instruction:
How would you explain what the following Python 3 function does
def _main(argv, standard_out, standard_error):
    import argparse
    parser = argparse.ArgumentParser(description=__doc__, prog='autoflake')
    parser.add_argument('-c', '--check', action='store_true',
                        help='return error code if changes are needed')
    parser.add_argument('-i', '--in-place', action='store_true',
                        help='make changes to files instead of printing diffs')
    parser.add_argument('-r', '--recursive', action='store_true',
                        help='drill down directories recursively')
    parser.add_argument('--exclude', metavar='globs',
                        help='exclude file/directory names that match these '
                             'comma-separated globs')
    parser.add_argument('--imports',
                        help='by default, only unused standard library '
                             'imports are removed; specify a comma-separated '
                             'list of additional modules/packages')
    parser.add_argument('--expand-star-imports', action='store_true',
                        help='expand wildcard star imports with undefined '
                             'names; this only triggers if there is only '
                             'one star import in the file; this is skipped if '
                             'there are any uses of `__all__` or `del` in the '
                             'file')
    parser.add_argument('--remove-all-unused-imports', action='store_true',
                        help='remove all unused imports (not just those from '
                             'the standard library)')
    parser.add_argument('--ignore-init-module-imports', action='store_true',
                        help='exclude __init__.py when removing unused '
                             'imports')
    parser.add_argument('--remove-duplicate-keys', action='store_true',
                        help='remove all duplicate keys in objects')
    parser.add_argument('--remove-unused-variables', action='store_true',
                        help='remove unused variables')
    parser.add_argument('--version', action='version',
                        version='%(prog)s ' + __version__)
    parser.add_argument('files', nargs='+', help='files to format')

    args = parser.parse_args(argv[1:])

    if args.remove_all_unused_imports and args.imports:
        print('Using both --remove-all and --imports is redundant',
              file=standard_error)
        return 1

    if args.exclude:
        args.exclude = _split_comma_separated(args.exclude)
    else:
        args.exclude = set([])

    filenames = list(set(args.files))
    failure = False
    for name in find_files(filenames, args.recursive, args.exclude):
        try:
            fix_file(name, args=args, standard_out=standard_out)
        except IOError as exception:
            print(unicode(exception), file=standard_error)
            failure = True

    return 1 if failure else 0

Response: Main function for the automlake command line interface.


Instruction:
Can you write a function in Python 3 where it
reads the data encoding the ObtainLease response payload and decode it into its constituent parts.

Response:
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Read the data encoding the ObtainLease response payload and decode it
        into its constituent parts.

        Args:
            input_stream (stream): A data stream containing encoded object
                data, supporting a read method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the data attribute is missing from the
                encoded payload.
        """
        super(ObtainLeaseResponsePayload, self).read(
            input_stream,
            kmip_version=kmip_version
        )
        local_stream = utils.BytearrayStream(input_stream.read(self.length))

        if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):
            self._unique_identifier = primitives.TextString(
                tag=enums.Tags.UNIQUE_IDENTIFIER
            )
            self._unique_identifier.read(
                local_stream,
                kmip_version=kmip_version
            )
        if self.is_tag_next(enums.Tags.LEASE_TIME, local_stream):
            self._lease_time = primitives.Interval(
                tag=enums.Tags.LEASE_TIME
            )
            self._lease_time.read(local_stream, kmip_version=kmip_version)
        if self.is_tag_next(enums.Tags.LAST_CHANGE_DATE, local_stream):
            self._last_change_date = primitives.DateTime(
                tag=enums.Tags.LAST_CHANGE_DATE
            )
            self._last_change_date.read(
                local_stream,
                kmip_version=kmip_version
            )

        self.is_oversized(local_stream)


Instruction:
Can you write a function in Python 3 where it
writes the data encoding the ObtainLease response payload to the output stream.

Response:
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the ObtainLease response payload to a stream.

        Args:
            output_stream (stream): A data stream in which to encode object
                data, supporting a write method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the data attribute is not defined.
        """
        local_stream = utils.BytearrayStream()

        if self._unique_identifier:
            self._unique_identifier.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._lease_time:
            self._lease_time.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._last_change_date:
            self._last_change_date.write(
                local_stream,
                kmip_version=kmip_version
            )

        self.length = local_stream.length()
        super(ObtainLeaseResponsePayload, self).write(
            output_stream,
            kmip_version=kmip_version
        )
        output_stream.write(local_stream.buffer)


Instruction:
Make a summary of the following Python 3 code
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        local_stream = utils.BytearrayStream()

        if self._asynchronous_correlation_value:
            self._asynchronous_correlation_value.write(
                local_stream,
                kmip_version=kmip_version
            )

        self.length = local_stream.length()
        super(CancelRequestPayload, self).write(
            output_stream,
            kmip_version=kmip_version
        )
        output_stream.write(local_stream.buffer)

Response: Writes the data encoding the object to the output stream.


Instruction:
Write a Python 3 function that can
read the data encoding the Cancel response payload and decode it into the object.

Response:
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Read the data encoding the Cancel response payload and decode it into
        its constituent parts.

        Args:
            input_stream (stream): A data stream containing encoded object
                data, supporting a read method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the data attribute is missing from the
                encoded payload.
        """
        super(CancelResponsePayload, self).read(
            input_stream,
            kmip_version=kmip_version
        )
        local_stream = utils.BytearrayStream(input_stream.read(self.length))

        if self.is_tag_next(
                enums.Tags.ASYNCHRONOUS_CORRELATION_VALUE,
                local_stream
        ):
            self._asynchronous_correlation_value = primitives.ByteString(
                tag=enums.Tags.ASYNCHRONOUS_CORRELATION_VALUE
            )
            self._asynchronous_correlation_value.read(
                local_stream,
                kmip_version=kmip_version
            )
        if self.is_tag_next(enums.Tags.CANCELLATION_RESULT, local_stream):
            self._cancellation_result = primitives.Enumeration(
                enums.CancellationResult,
                tag=enums.Tags.CANCELLATION_RESULT
            )
            self._cancellation_result.read(
                local_stream,
                kmip_version=kmip_version
            )

        self.is_oversized(local_stream)


Instruction:
How would you explain what the following Python 3 function does
def create(cls, name_value, name_type):
        '''
            Returns a Name object, populated with the given value and type
        '''
        if isinstance(name_value, Name.NameValue):
            value = name_value
        elif isinstance(name_value, str):
            value = cls.NameValue(name_value)
        else:
            name = 'Name'
            msg = exceptions.ErrorStrings.BAD_EXP_RECV
            member = 'name_value'
            raise TypeError(msg.format('{0}.{1}'.format(name, member),
                                       'name_value', type(Name.NameValue),
                                       type(name_value)))

        if isinstance(name_type, Name.NameType):
            n_type = name_type
        elif isinstance(name_type, Enum):
            n_type = cls.NameType(name_type)
        else:
            name = 'Name'
            msg = exceptions.ErrorStrings.BAD_EXP_RECV
            member = 'name_type'
            raise TypeError(msg.format('{0}.{1}'.format(name, member),
                                       'name_type', type(Name.NameType),
                                       type(name_type)))

        return Name(name_value=value,
                    name_type=n_type)

Response: Returns a Name object populated with the given value and type


Instruction:
Given the following Python 3 function, write the documentation
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        super(Digest, self).read(istream, kmip_version=kmip_version)
        tstream = BytearrayStream(istream.read(self.length))

        self.hashing_algorithm.read(tstream, kmip_version=kmip_version)
        self.digest_value.read(tstream, kmip_version=kmip_version)
        self.key_format_type.read(tstream, kmip_version=kmip_version)

        self.is_oversized(tstream)
        self.validate()

Response: Reads the data encoding the Digest object and decode it into its own parts.


Instruction:
Implement a Python 3 function for
writing the data encoding the object to the data stream.

Response:
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the Digest object to a stream.

        Args:
            ostream (Stream): A data stream in which to encode object data,
                supporting a write method; usually a BytearrayStream object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.
        """
        tstream = BytearrayStream()

        self.hashing_algorithm.write(tstream, kmip_version=kmip_version)
        self.digest_value.write(tstream, kmip_version=kmip_version)
        self.key_format_type.write(tstream, kmip_version=kmip_version)

        self.length = tstream.length()
        super(Digest, self).write(ostream, kmip_version=kmip_version)
        ostream.write(tstream.buffer)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create(cls,
               hashing_algorithm=HashingAlgorithmEnum.SHA_256,
               digest_value=b'',
               key_format_type=KeyFormatTypeEnum.RAW):
        """
        Construct a Digest object from provided digest values.

        Args:
            hashing_algorithm (HashingAlgorithm): An enumeration representing
                the hash algorithm used to compute the digest. Optional,
                defaults to HashingAlgorithm.SHA_256.
            digest_value (byte string): The bytes of the digest hash. Optional,
                defaults to the empty byte string.
            key_format_type (KeyFormatType): An enumeration representing the
                format of the key corresponding to the digest. Optional,
                defaults to KeyFormatType.RAW.

        Returns:
            Digest: The newly created Digest.

        Example:
            >>> x = Digest.create(HashingAlgorithm.MD5, b'\x00',
            ... KeyFormatType.RAW)
            >>> x.hashing_algorithm
            HashingAlgorithm(value=HashingAlgorithm.MD5)
            >>> x.digest_value
            DigestValue(value=bytearray(b'\x00'))
            >>> x.key_format_type
            KeyFormatType(value=KeyFormatType.RAW)
        """
        algorithm = HashingAlgorithm(hashing_algorithm)
        value = DigestValue(bytearray(digest_value))
        format_type = KeyFormatType(key_format_type)

        return Digest(hashing_algorithm=algorithm,
                      digest_value=value,
                      key_format_type=format_type)

Response: Constructs a new Digest object from provided digest values.


Instruction:
Implement a Python 3 function for
reading the data encoding the ApplicationSpecificInformation object and decode it into constituent parts.

Response:
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Read the data encoding the ApplicationSpecificInformation object and
        decode it into its constituent parts.

        Args:
            istream (Stream): A data stream containing encoded object data,
                supporting a read method; usually a BytearrayStream object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.
        """
        super(ApplicationSpecificInformation, self).read(
            istream,
            kmip_version=kmip_version
        )
        tstream = BytearrayStream(istream.read(self.length))

        self.application_namespace.read(tstream, kmip_version=kmip_version)
        self.application_data.read(tstream, kmip_version=kmip_version)

        self.is_oversized(tstream)
        self.validate()


Instruction:
Write a Python 3 script to
write the data encoding the ApplicationSpecificInformation object to an output stream.

Response:
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the ApplicationSpecificInformation object to a
        stream.

        Args:
            ostream (Stream): A data stream in which to encode object data,
                supporting a write method; usually a BytearrayStream object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.
        """
        tstream = BytearrayStream()

        self.application_namespace.write(tstream, kmip_version=kmip_version)
        self.application_data.write(tstream, kmip_version=kmip_version)

        self.length = tstream.length()
        super(ApplicationSpecificInformation, self).write(
            ostream,
            kmip_version=kmip_version
        )
        ostream.write(tstream.buffer)


Instruction:
Given the following Python 3 function, write the documentation
def create(cls, application_namespace, application_data):
        namespace = ApplicationNamespace(application_namespace)
        data = ApplicationData(application_data)
        return ApplicationSpecificInformation(
            application_namespace=namespace, application_data=data)

Response: Create an ApplicationSpecificInformation object from provided data and application namespace values.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        super(DerivationParameters, self).read(
            input_stream,
            kmip_version=kmip_version
        )
        local_stream = BytearrayStream(input_stream.read(self.length))

        if self.is_tag_next(
                enums.Tags.CRYPTOGRAPHIC_PARAMETERS,
                local_stream
        ):
            self._cryptographic_parameters = CryptographicParameters()
            self._cryptographic_parameters.read(
                local_stream,
                kmip_version=kmip_version
            )

        if self.is_tag_next(enums.Tags.INITIALIZATION_VECTOR, local_stream):
            self._initialization_vector = ByteString(
                tag=enums.Tags.INITIALIZATION_VECTOR
            )
            self._initialization_vector.read(
                local_stream,
                kmip_version=kmip_version
            )

        if self.is_tag_next(enums.Tags.DERIVATION_DATA, local_stream):
            self._derivation_data = ByteString(tag=enums.Tags.DERIVATION_DATA)
            self._derivation_data.read(local_stream, kmip_version=kmip_version)

        if self.is_tag_next(enums.Tags.SALT, local_stream):
            self._salt = ByteString(tag=enums.Tags.SALT)
            self._salt.read(local_stream, kmip_version=kmip_version)

        if self.is_tag_next(Tags.ITERATION_COUNT, local_stream):
            self._iteration_count = Integer(tag=Tags.ITERATION_COUNT)
            self._iteration_count.read(local_stream, kmip_version=kmip_version)

        self.is_oversized(local_stream)

Response: Reads the data encoding the DerivationParameters struct and decodes it into parts.


Instruction:
Write a Python 3 script for
writing the DerivationParameters struct to a byte array stream.

Response:
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the DerivationParameters struct to a stream.

        Args:
            output_stream (stream): A data stream in which to encode object
                data, supporting a write method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.
        """
        local_stream = BytearrayStream()

        if self._cryptographic_parameters:
            self._cryptographic_parameters.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._initialization_vector:
            self._initialization_vector.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._derivation_data:
            self._derivation_data.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._salt:
            self._salt.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._iteration_count:
            self._iteration_count.write(
                local_stream,
                kmip_version=kmip_version
            )

        self.length = local_stream.length()
        super(DerivationParameters, self).write(
            output_stream,
            kmip_version=kmip_version
        )
        output_stream.write(local_stream.buffer)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        super(GetRequestPayload, self).read(
            input_stream,
            kmip_version=kmip_version
        )
        local_stream = utils.BytearrayStream(input_stream.read(self.length))

        if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):
            self._unique_identifier = primitives.TextString(
                tag=enums.Tags.UNIQUE_IDENTIFIER
            )
            self._unique_identifier.read(
                local_stream,
                kmip_version=kmip_version
            )

        if self.is_tag_next(enums.Tags.KEY_FORMAT_TYPE, local_stream):
            self._key_format_type = primitives.Enumeration(
                enum=enums.KeyFormatType,
                tag=enums.Tags.KEY_FORMAT_TYPE
            )
            self._key_format_type.read(
                local_stream,
                kmip_version=kmip_version
            )

        if self.is_tag_next(enums.Tags.KEY_COMPRESSION_TYPE, local_stream):
            self._key_compression_type = primitives.Enumeration(
                enum=enums.KeyCompressionType,
                tag=enums.Tags.KEY_COMPRESSION_TYPE
            )
            self._key_compression_type.read(
                local_stream,
                kmip_version=kmip_version
            )

        if self.is_tag_next(
                enums.Tags.KEY_WRAPPING_SPECIFICATION,
                local_stream
        ):
            self._key_wrapping_specification = \
                objects.KeyWrappingSpecification()
            self._key_wrapping_specification.read(
                local_stream,
                kmip_version=kmip_version
            )

        self.is_oversized(local_stream)

Response: Reads the data encoding the Get Request Payload and decodes it into its components.


Instruction:
Can you implement a function in Python 3 that
writes the data encoding the object to the output stream.

Response:
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the Get request payload to a stream.

        Args:
            output_stream (stream): A data stream in which to encode object
                data, supporting a write method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.
        """
        local_stream = utils.BytearrayStream()

        if self._unique_identifier is not None:
            self._unique_identifier.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._key_format_type is not None:
            self._key_format_type.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._key_compression_type is not None:
            self._key_compression_type.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._key_wrapping_specification is not None:
            self._key_wrapping_specification.write(
                local_stream,
                kmip_version=kmip_version
            )

        self.length = local_stream.length()
        super(GetRequestPayload, self).write(
            output_stream,
            kmip_version=kmip_version
        )
        output_stream.write(local_stream.buffer)


Instruction:
Write a Python 3 script for
reading the data encoding the Get response payload and decode it into parts.

Response:
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Read the data encoding the Get response payload and decode it
        into its constituent parts.

        Args:
            input_stream (stream): A data stream containing encoded object
                data, supporting a read method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the object type, unique identifier, or
                secret attributes are missing from the encoded payload.
        """
        super(GetResponsePayload, self).read(
            input_stream,
            kmip_version=kmip_version
        )
        local_stream = utils.BytearrayStream(input_stream.read(self.length))

        if self.is_tag_next(enums.Tags.OBJECT_TYPE, local_stream):
            self._object_type = primitives.Enumeration(
                enum=enums.ObjectType,
                tag=enums.Tags.OBJECT_TYPE
            )
            self._object_type.read(local_stream, kmip_version=kmip_version)
        else:
            raise ValueError(
                "Parsed payload encoding is missing the object type field."
            )

        if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):
            self._unique_identifier = primitives.TextString(
                tag=enums.Tags.UNIQUE_IDENTIFIER
            )
            self._unique_identifier.read(
                local_stream,
                kmip_version=kmip_version
            )
        else:
            raise ValueError(
                "Parsed payload encoding is missing the unique identifier "
                "field."
            )

        self.secret = self.secret_factory.create(self.object_type)
        if self.is_tag_next(self._secret.tag, local_stream):
            self._secret.read(local_stream, kmip_version=kmip_version)
        else:
            raise ValueError(
                "Parsed payload encoding is missing the secret field."
            )

        self.is_oversized(local_stream)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        local_stream = utils.BytearrayStream()

        if self.object_type:
            self._object_type.write(local_stream, kmip_version=kmip_version)
        else:
            raise ValueError("Payload is missing the object type field.")

        if self.unique_identifier:
            self._unique_identifier.write(
                local_stream,
                kmip_version=kmip_version
            )
        else:
            raise ValueError(
                "Payload is missing the unique identifier field."
            )

        if self.secret:
            self._secret.write(local_stream, kmip_version=kmip_version)
        else:
            raise ValueError("Payload is missing the secret field.")

        self.length = local_stream.length()
        super(GetResponsePayload, self).write(
            output_stream,
            kmip_version=kmip_version
        )
        output_stream.write(local_stream.buffer)

Response: Writes the data encoding the Get response payload to the output stream.


Instruction:
Given the following Python 3 function, write the documentation
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        super(SignatureVerifyRequestPayload, self).read(
            input_stream,
            kmip_version=kmip_version
        )
        local_stream = utils.BytearrayStream(input_stream.read(self.length))

        if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):
            self._unique_identifier = primitives.TextString(
                tag=enums.Tags.UNIQUE_IDENTIFIER
            )
            self._unique_identifier.read(
                local_stream,
                kmip_version=kmip_version
            )
        if self.is_tag_next(enums.Tags.CRYPTOGRAPHIC_PARAMETERS, local_stream):
            self._cryptographic_parameters = \
                attributes.CryptographicParameters()
            self._cryptographic_parameters.read(
                local_stream,
                kmip_version=kmip_version
            )
        if self.is_tag_next(enums.Tags.DATA, local_stream):
            self._data = primitives.ByteString(tag=enums.Tags.DATA)
            self._data.read(local_stream, kmip_version=kmip_version)
        if self.is_tag_next(enums.Tags.DIGESTED_DATA, local_stream):
            self._digested_data = primitives.ByteString(
                tag=enums.Tags.DIGESTED_DATA
            )
            self._digested_data.read(local_stream, kmip_version=kmip_version)
        if self.is_tag_next(enums.Tags.SIGNATURE_DATA, local_stream):
            self._signature_data = primitives.ByteString(
                tag=enums.Tags.SIGNATURE_DATA
            )
            self._signature_data.read(local_stream, kmip_version=kmip_version)
        if self.is_tag_next(enums.Tags.CORRELATION_VALUE, local_stream):
            self._correlation_value = primitives.ByteString(
                tag=enums.Tags.CORRELATION_VALUE
            )
            self._correlation_value.read(
                local_stream,
                kmip_version=kmip_version
            )
        if self.is_tag_next(enums.Tags.INIT_INDICATOR, local_stream):
            self._init_indicator = primitives.Boolean(
                tag=enums.Tags.INIT_INDICATOR
            )
            self._init_indicator.read(local_stream, kmip_version=kmip_version)
        if self.is_tag_next(enums.Tags.FINAL_INDICATOR, local_stream):
            self._final_indicator = primitives.Boolean(
                tag=enums.Tags.FINAL_INDICATOR
            )
            self._final_indicator.read(local_stream, kmip_version=kmip_version)

        self.is_oversized(local_stream)

Response: Reads the contents of the SignatureVerifyRequestPayload into the object.


Instruction:
Implement a function in Python 3 to
write the contents of this object to the output stream.

Response:
def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the SignatureVerify request payload to a
        stream.

        Args:
            output_stream (stream): A data stream in which to encode object
                data, supporting a write method; usually a BytearrayStream
                object.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            ValueError: Raised if the data attribute is not defined.
        """
        local_stream = utils.BytearrayStream()

        if self._unique_identifier:
            self._unique_identifier.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._cryptographic_parameters:
            self._cryptographic_parameters.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._data:
            self._data.write(local_stream, kmip_version=kmip_version)
        if self._digested_data:
            self._digested_data.write(local_stream, kmip_version=kmip_version)
        if self._signature_data:
            self._signature_data.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._correlation_value:
            self._correlation_value.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._init_indicator:
            self._init_indicator.write(
                local_stream,
                kmip_version=kmip_version
            )
        if self._final_indicator:
            self._final_indicator.write(
                local_stream,
                kmip_version=kmip_version
            )

        self.length = local_stream.length()
        super(SignatureVerifyRequestPayload, self).write(
            output_stream,
            kmip_version=kmip_version
        )
        output_stream.write(local_stream.buffer)


Instruction:
Given the following Python 3 function, write the documentation
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        super(SignatureVerifyResponsePayload, self).read(
            input_stream,
            kmip_version=kmip_version
        )
        local_stream = utils.BytearrayStream(input_stream.read(self.length))

        if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):
            self._unique_identifier = primitives.TextString(
                tag=enums.Tags.UNIQUE_IDENTIFIER
            )
            self._unique_identifier.read(
                local_stream,
                kmip_version=kmip_version
            )
        else:
            raise ValueError(
                "Parsed payload encoding is missing the unique identifier "
                "field."
            )
        if self.is_tag_next(enums.Tags.VALIDITY_INDICATOR, local_stream):
            self._validity_indicator = primitives.Enumeration(
                enums.ValidityIndicator,
                tag=enums.Tags.VALIDITY_INDICATOR
            )
            self._validity_indicator.read(
                local_stream,
                kmip_version=kmip_version
            )
        else:
            raise ValueError(
                "Parsed payload encoding is missing the validity indicator "
                "field."
            )
        if self.is_tag_next(enums.Tags.DATA, local_stream):
            self._data = primitives.ByteString(tag=enums.Tags.DATA)
            self._data.read(local_stream, kmip_version=kmip_version)
        if self.is_tag_next(enums.Tags.CORRELATION_VALUE, local_stream):
            self._correlation_value = primitives.ByteString(
                tag=enums.Tags.CORRELATION_VALUE
            )
            self._correlation_value.read(
                local_stream,
                kmip_version=kmip_version
            )

        self.is_oversized(local_stream)

Response: Reads the contents of the SignatureVerify response payload and decodes it into its constituent parts.


Instruction:
Can you write a function in Python 3 where it
processes a KMIP request message. This routine is the main driver of the KmipEngine. It breaks apart and processes the request header, handles any message errors that may result, and then passes the set of request batch items on for processing. This routine is thread-safe, allowing multiple client connections to use the same KmipEngine. Args: request (RequestMessage): The request message containing the batch items to be processed. credential (string): Identifying information about the client obtained from the client certificate. Optional, defaults to None. Returns: ResponseMessage: The response containing all of the results from the request batch items.

Response:
def process_request(self, request, credential=None):
        """
        Process a KMIP request message.

        This routine is the main driver of the KmipEngine. It breaks apart and
        processes the request header, handles any message errors that may
        result, and then passes the set of request batch items on for
        processing. This routine is thread-safe, allowing multiple client
        connections to use the same KmipEngine.

        Args:
            request (RequestMessage): The request message containing the batch
                items to be processed.
            credential (string): Identifying information about the client
                obtained from the client certificate. Optional, defaults to
                None.

        Returns:
            ResponseMessage: The response containing all of the results from
                the request batch items.
        """
        self._client_identity = [None, None]
        header = request.request_header

        # Process the protocol version
        self._set_protocol_version(header.protocol_version)

        # Process the maximum response size
        max_response_size = None
        if header.maximum_response_size:
            max_response_size = header.maximum_response_size.value

        # Process the time stamp
        now = int(time.time())
        if header.time_stamp:
            then = header.time_stamp.value

            if (now >= then) and ((now - then) < 60):
                self._logger.info("Received request at time: {0}".format(
                    time.strftime(
                        "%Y-%m-%d %H:%M:%S",
                        time.gmtime(then)
                    )
                ))
            else:
                if now < then:
                    self._logger.warning(
                        "Received request with future timestamp. Received "
                        "timestamp: {0}, Current timestamp: {1}".format(
                            then,
                            now
                        )
                    )

                    raise exceptions.InvalidMessage(
                        "Future request rejected by server."
                    )
                else:
                    self._logger.warning(
                        "Received request with old timestamp. Possible "
                        "replay attack. Received timestamp: {0}, Current "
                        "timestamp: {1}".format(then, now)
                    )

                    raise exceptions.InvalidMessage(
                        "Stale request rejected by server."
                    )
        else:
            self._logger.info("Received request at time: {0}".format(
                time.strftime(
                    "%Y-%m-%d %H:%M:%S",
                    time.gmtime(now)
                )
            ))

        # Process the asynchronous indicator
        self.is_asynchronous = False
        if header.asynchronous_indicator is not None:
            self.is_asynchronous = header.asynchronous_indicator.value

        if self.is_asynchronous:
            raise exceptions.InvalidMessage(
                "Asynchronous operations are not supported."
            )

        # Process the authentication credentials
        if header.authentication:
            if header.authentication.credentials:
                auth_credentials = header.authentication.credentials[0]
            else:
                auth_credentials = None
        else:
            auth_credentials = None

        self._verify_credential(auth_credentials, credential)

        # Process the batch error continuation option
        batch_error_option = enums.BatchErrorContinuationOption.STOP
        if header.batch_error_cont_option is not None:
            batch_error_option = header.batch_error_cont_option.value

        if batch_error_option == enums.BatchErrorContinuationOption.UNDO:
            raise exceptions.InvalidMessage(
                "Undo option for batch handling is not supported."
            )

        # Process the batch order option
        batch_order_option = False
        if header.batch_order_option:
            batch_order_option = header.batch_order_option.value

        response_batch = self._process_batch(
            request.batch_items,
            batch_error_option,
            batch_order_option
        )
        response = self._build_response(
            header.protocol_version,
            response_batch
        )

        return response, max_response_size, header.protocol_version