Instruction:
Create a Python 3 function to
build a simple ResponseMessage containing a single error result.

Response:
def build_error_response(self, version, reason, message):
        """
        Build a simple ResponseMessage with a single error result.

        Args:
            version (ProtocolVersion): The protocol version the response
                should be addressed with.
            reason (ResultReason): An enumeration classifying the type of
                error occurred.
            message (str): A string providing additional information about
                the error.

        Returns:
            ResponseMessage: The simple ResponseMessage containing a
                single error result.
        """
        batch_item = messages.ResponseBatchItem(
            result_status=contents.ResultStatus(
                enums.ResultStatus.OPERATION_FAILED
            ),
            result_reason=contents.ResultReason(reason),
            result_message=contents.ResultMessage(message)
        )
        return self._build_response(version, [batch_item])


Instruction:
Make a summary of the following Python 3 code
def _process_template_attribute(self, template_attribute):
        attributes = {}

        if len(template_attribute.names) > 0:
            raise exceptions.ItemNotFound(
                "Attribute templates are not supported."
            )

        for attribute in template_attribute.attributes:
            name = attribute.attribute_name.value

            if not self._attribute_policy.is_attribute_supported(name):
                raise exceptions.InvalidField(
                    "The {0} attribute is unsupported.".format(name)
                )

            if self._attribute_policy.is_attribute_multivalued(name):
                values = attributes.get(name, list())
                if (not attribute.attribute_index) and len(values) > 0:
                    raise exceptions.InvalidField(
                        "Attribute index missing from multivalued attribute."
                    )

                values.append(attribute.attribute_value)
                attributes.update([(name, values)])
            else:
                if attribute.attribute_index:
                    if attribute.attribute_index.value != 0:
                        raise exceptions.InvalidField(
                            "Non-zero attribute index found for "
                            "single-valued attribute."
                        )
                value = attributes.get(name, None)
                if value:
                    raise exceptions.IndexOutOfBounds(
                        "Cannot set multiple instances of the "
                        "{0} attribute.".format(name)
                    )
                else:
                    attributes.update([(name, attribute.attribute_value)])

        return attributes

Response: Given a kmip. core TemplateAttribute object extract the attribute data into a usable dictionary format.


Instruction:
Create a Python 3 function to
give a kmip. pie object and a list of attribute names attempt to get all of the existing attributes from the object.

Response:
def _get_attributes_from_managed_object(self, managed_object, attr_names):
        """
        Given a kmip.pie object and a list of attribute names, attempt to get
        all of the existing attribute values from the object.
        """
        attr_factory = attribute_factory.AttributeFactory()
        retrieved_attributes = list()

        if not attr_names:
            attr_names = self._attribute_policy.get_all_attribute_names()

        for attribute_name in attr_names:
            object_type = managed_object._object_type

            if not self._attribute_policy.is_attribute_supported(
                    attribute_name
            ):
                continue

            if self._attribute_policy.is_attribute_applicable_to_object_type(
                attribute_name,
                object_type
            ):
                try:
                    attribute_value = self._get_attribute_from_managed_object(
                        managed_object,
                        attribute_name
                    )
                except Exception:
                    attribute_value = None

                if attribute_value is not None:
                    if self._attribute_policy.is_attribute_multivalued(
                            attribute_name
                    ):
                        for count, value in enumerate(attribute_value):
                            attribute = attr_factory.create_attribute(
                                enums.AttributeType(attribute_name),
                                value,
                                count
                            )
                            retrieved_attributes.append(attribute)
                    else:
                        attribute = attr_factory.create_attribute(
                            enums.AttributeType(attribute_name),
                            attribute_value
                        )
                        retrieved_attributes.append(attribute)

        return retrieved_attributes


Instruction:
Can you generate the documentation for the following Python 3 function
def _get_attribute_from_managed_object(self, managed_object, attr_name):
        if attr_name == 'Unique Identifier':
            return str(managed_object.unique_identifier)
        elif attr_name == 'Name':
            names = list()
            for name in managed_object.names:
                name = attributes.Name(
                    attributes.Name.NameValue(name),
                    attributes.Name.NameType(
                        enums.NameType.UNINTERPRETED_TEXT_STRING
                    )
                )
                names.append(name)
            return names
        elif attr_name == 'Object Type':
            return managed_object._object_type
        elif attr_name == 'Cryptographic Algorithm':
            return managed_object.cryptographic_algorithm
        elif attr_name == 'Cryptographic Length':
            return managed_object.cryptographic_length
        elif attr_name == 'Cryptographic Parameters':
            return None
        elif attr_name == 'Cryptographic Domain Parameters':
            return None
        elif attr_name == 'Certificate Type':
            return managed_object.certificate_type
        elif attr_name == 'Certificate Length':
            return None
        elif attr_name == 'X.509 Certificate Identifier':
            return None
        elif attr_name == 'X.509 Certificate Subject':
            return None
        elif attr_name == 'X.509 Certificate Issuer':
            return None
        elif attr_name == 'Certificate Identifier':
            return None
        elif attr_name == 'Certificate Subject':
            return None
        elif attr_name == 'Certificate Issuer':
            return None
        elif attr_name == 'Digital Signature Algorithm':
            return None
        elif attr_name == 'Digest':
            return None
        elif attr_name == 'Operation Policy Name':
            return managed_object.operation_policy_name
        elif attr_name == 'Cryptographic Usage Mask':
            return managed_object.cryptographic_usage_masks
        elif attr_name == 'Lease Time':
            return None
        elif attr_name == 'Usage Limits':
            return None
        elif attr_name == 'State':
            return managed_object.state
        elif attr_name == 'Initial Date':
            return managed_object.initial_date
        elif attr_name == 'Activation Date':
            return None
        elif attr_name == 'Process Start Date':
            return None
        elif attr_name == 'Protect Stop Date':
            return None
        elif attr_name == 'Deactivation Date':
            return None
        elif attr_name == 'Destroy Date':
            return None
        elif attr_name == 'Compromise Occurrence Date':
            return None
        elif attr_name == 'Compromise Date':
            return None
        elif attr_name == 'Revocation Reason':
            return None
        elif attr_name == 'Archive Date':
            return None
        elif attr_name == 'Object Group':
            return None
        elif attr_name == 'Fresh':
            return None
        elif attr_name == 'Link':
            return None
        elif attr_name == 'Application Specific Information':
            return None
        elif attr_name == 'Contact Information':
            return None
        elif attr_name == 'Last Change Date':
            return None
        else:
            # Since custom attribute names are possible, just return None
            # for unrecognized attributes. This satisfies the spec.
            return None

Response: Get the attribute value from the kmip. pie managed object.


Instruction:
Write a Python 3 function for
attempting to set the attributes on the object.

Response:
def _set_attributes_on_managed_object(self, managed_object, attributes):
        """
        Given a kmip.pie object and a dictionary of attributes, attempt to set
        the attribute values on the object.
        """
        for attribute_name, attribute_value in six.iteritems(attributes):
            object_type = managed_object._object_type
            if self._attribute_policy.is_attribute_applicable_to_object_type(
                    attribute_name,
                    object_type):
                self._set_attribute_on_managed_object(
                    managed_object,
                    (attribute_name, attribute_value)
                )
            else:
                name = object_type.name
                raise exceptions.InvalidField(
                    "Cannot set {0} attribute on {1} object.".format(
                        attribute_name,
                        ''.join([x.capitalize() for x in name.split('_')])
                    )
                )


Instruction:
Here you have a function in Python 3, explain what it does
def _set_attribute_on_managed_object(self, managed_object, attribute):
        attribute_name = attribute[0]
        attribute_value = attribute[1]

        if self._attribute_policy.is_attribute_multivalued(attribute_name):
            if attribute_name == 'Name':
                managed_object.names.extend(
                    [x.name_value.value for x in attribute_value]
                )
                for name in managed_object.names:
                    if managed_object.names.count(name) > 1:
                        raise exceptions.InvalidField(
                            "Cannot set duplicate name values."
                        )
            else:
                # TODO (peterhamilton) Remove when all attributes are supported
                raise exceptions.InvalidField(
                    "The {0} attribute is unsupported.".format(attribute_name)
                )
        else:
            field = None
            value = attribute_value.value

            if attribute_name == 'Cryptographic Algorithm':
                field = 'cryptographic_algorithm'
            elif attribute_name == 'Cryptographic Length':
                field = 'cryptographic_length'
            elif attribute_name == 'Cryptographic Usage Mask':
                field = 'cryptographic_usage_masks'
                value = list()
                for e in enums.CryptographicUsageMask:
                    if e.value & attribute_value.value:
                        value.append(e)
            elif attribute_name == 'Operation Policy Name':
                field = 'operation_policy_name'

            if field:
                existing_value = getattr(managed_object, field)
                if existing_value:
                    if existing_value != value:
                        raise exceptions.InvalidField(
                            "Cannot overwrite the {0} attribute.".format(
                                attribute_name
                            )
                        )
                else:
                    setattr(managed_object, field, value)
            else:
                # TODO (peterhamilton) Remove when all attributes are supported
                raise exceptions.InvalidField(
                    "The {0} attribute is unsupported.".format(attribute_name)
                )

Response: Sets the attribute value on the kmip. pie managed object.


Instruction:
Create a Python 3 function to
look up the relevant policy section.

Response:
def get_relevant_policy_section(self, policy_name, group=None):
        """
        Look up the policy corresponding to the provided policy name and
        group (optional). Log any issues found during the look up.
        """
        policy_bundle = self._operation_policies.get(policy_name)

        if not policy_bundle:
            self._logger.warning(
                "The '{}' policy does not exist.".format(policy_name)
            )
            return None

        if group:
            groups_policy_bundle = policy_bundle.get('groups')
            if not groups_policy_bundle:
                self._logger.debug(
                    "The '{}' policy does not support groups.".format(
                        policy_name
                    )
                )
                return None
            else:
                group_policy = groups_policy_bundle.get(group)
                if not group_policy:
                    self._logger.debug(
                        "The '{}' policy does not support group '{}'.".format(
                            policy_name,
                            group
                        )
                    )
                    return None
                else:
                    return group_policy
        else:
            return policy_bundle.get('preset')


Instruction:
Write a Python 3 function that can
determine if object access is allowed for the provided policy and session settings.

Response:
def is_allowed(
            self,
            policy_name,
            session_user,
            session_group,
            object_owner,
            object_type,
            operation
    ):
        """
        Determine if object access is allowed for the provided policy and
        session settings.
        """
        policy_section = self.get_relevant_policy_section(
            policy_name,
            session_group
        )
        if policy_section is None:
            return False

        object_policy = policy_section.get(object_type)
        if not object_policy:
            self._logger.warning(
                "The '{0}' policy does not apply to {1} objects.".format(
                    policy_name,
                    self._get_enum_string(object_type)
                )
            )
            return False

        operation_object_policy = object_policy.get(operation)
        if not operation_object_policy:
            self._logger.warning(
                "The '{0}' policy does not apply to {1} operations on {2} "
                "objects.".format(
                    policy_name,
                    self._get_enum_string(operation),
                    self._get_enum_string(object_type)
                )
            )
            return False

        if operation_object_policy == enums.Policy.ALLOW_ALL:
            return True
        elif operation_object_policy == enums.Policy.ALLOW_OWNER:
            if session_user == object_owner:
                return True
            else:
                return False
        elif operation_object_policy == enums.Policy.DISALLOW_ALL:
            return False
        else:
            return False


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._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)
        else:
            raise ValueError("invalid payload missing the data attribute")

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

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

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


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

        self.unique_identifier = attributes.UniqueIdentifier()
        self.unique_identifier.read(tstream, kmip_version=kmip_version)

        self.revocation_reason = objects.RevocationReason()
        self.revocation_reason.read(tstream, kmip_version=kmip_version)

        if self.is_tag_next(enums.Tags.COMPROMISE_OCCURRENCE_DATE, tstream):
            self.compromise_occurrence_date = primitives.DateTime(
                tag=enums.Tags.COMPROMISE_OCCURRENCE_DATE)
            self.compromise_occurrence_date.read(
                tstream,
                kmip_version=kmip_version
            )

        self.is_oversized(tstream)
        self.validate()

Response: Reads the data encoding the RevokeRequestPayload object and decode it into its constituent parts.


Instruction:
How would you explain what the following Python 3 function does
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        tstream = BytearrayStream()

        # Write the contents of the request payload
        if self.unique_identifier is not None:
            self.unique_identifier.write(tstream, kmip_version=kmip_version)

        self.revocation_reason.write(tstream, kmip_version=kmip_version)

        if self.compromise_occurrence_date is not None:
            self.compromise_occurrence_date.write(
                tstream,
                kmip_version=kmip_version
            )

        # Write the length and value of the request payload
        self.length = tstream.length()
        super(RevokeRequestPayload, self).write(
            ostream,
            kmip_version=kmip_version
        )
        ostream.write(tstream.buffer)

Response: Writes the contents of the RevokeRequestPayload object to the data stream.


Instruction:
Can you implement a function in Python 3 that
validates the attributes of the ActivateRequestPayload object.

Response:
def validate(self):
        """
        Error check the attributes of the ActivateRequestPayload object.
        """
        if self.unique_identifier is not None:
            if not isinstance(self.unique_identifier,
                              attributes.UniqueIdentifier):
                msg = "invalid unique identifier"
                raise TypeError(msg)
        if self.compromise_occurrence_date is not None:
            if not isinstance(self.compromise_occurrence_date,
                              primitives.DateTime):
                msg = "invalid compromise time"
                raise TypeError(msg)
        if not isinstance(self.revocation_reason, objects.RevocationReason):
            msg = "invalid revocation reason"
            raise TypeError(msg)


Instruction:
How would you explain what the following Python 3 function does
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        super(RevokeResponsePayload, self).read(
            istream,
            kmip_version=kmip_version
        )
        tstream = BytearrayStream(istream.read(self.length))

        self.unique_identifier = attributes.UniqueIdentifier()
        self.unique_identifier.read(tstream, kmip_version=kmip_version)

        self.is_oversized(tstream)
        self.validate()

Response: Reads the data encoding the RevokeResponsePayload object and decode it into constituent parts.


Instruction:
Write a Python 3 script for
creating a new secret object of the specified type with the given value.

Response:
def create(self, secret_type, value=None):
        """
        Create a secret object of the specified type with the given value.

        Args:
            secret_type (ObjectType): An ObjectType enumeration specifying the
                type of secret to create.
            value (dict): A dictionary containing secret data. Optional,
                defaults to None.

        Returns:
            secret: The newly constructed secret object.

        Raises:
            TypeError: If the provided secret type is unrecognized.

        Example:
            >>> factory.create(ObjectType.SYMMETRIC_KEY)
            SymmetricKey(...)
        """
        if secret_type is ObjectType.CERTIFICATE:
            return self._create_certificate(value)
        elif secret_type is ObjectType.SYMMETRIC_KEY:
            return self._create_symmetric_key(value)
        elif secret_type is ObjectType.PUBLIC_KEY:
            return self._create_public_key(value)
        elif secret_type is ObjectType.PRIVATE_KEY:
            return self._create_private_key(value)
        elif secret_type is ObjectType.SPLIT_KEY:
            return self._create_split_key(value)
        elif secret_type is ObjectType.TEMPLATE:
            return self._create_template(value)
        elif secret_type is ObjectType.SECRET_DATA:
            return self._create_secret_data(value)
        elif secret_type is ObjectType.OPAQUE_DATA:
            return self._create_opaque_data(value)
        else:
            raise TypeError("Unrecognized secret type: {0}".format(
                secret_type))


Instruction:
Explain what the following Python 3 code does
def set_setting(self, setting, value):
        if setting not in self._expected_settings + self._optional_settings:
            raise exceptions.ConfigurationError(
                "Setting '{0}' is not supported.".format(setting)
            )

        if setting == 'hostname':
            self._set_hostname(value)
        elif setting == 'port':
            self._set_port(value)
        elif setting == 'certificate_path':
            self._set_certificate_path(value)
        elif setting == 'key_path':
            self._set_key_path(value)
        elif setting == 'ca_path':
            self._set_ca_path(value)
        elif setting == 'auth_suite':
            self._set_auth_suite(value)
        elif setting == 'policy_path':
            self._set_policy_path(value)
        elif setting == 'enable_tls_client_auth':
            self._set_enable_tls_client_auth(value)
        elif setting == 'tls_cipher_suites':
            self._set_tls_cipher_suites(value)
        elif setting == 'logging_level':
            self._set_logging_level(value)
        else:
            self._set_database_path(value)

Response: Sets the value of a specific setting.


Instruction:
Write a Python 3 script to
load the server configuration settings from the file pointed to by path.

Response:
def load_settings(self, path):
        """
        Load configuration settings from the file pointed to by path.

        This will overwrite all current setting values.

        Args:
            path (string): The path to the configuration file containing
                the settings to load. Required.
        Raises:
            ConfigurationError: Raised if the path does not point to an
                existing file or if a setting value is invalid.
        """
        if not os.path.exists(path):
            raise exceptions.ConfigurationError(
                "The server configuration file ('{0}') could not be "
                "located.".format(path)
            )

        self._logger.info(
            "Loading server configuration settings from: {0}".format(path)
        )

        parser = configparser.ConfigParser()
        parser.read(path)
        self._parse_settings(parser)
        self.parse_auth_settings(parser)


Instruction:
Write a Python 3 function for
processing the bind parameter value for the field.

Response:
def process_bind_param(self, value, dialect):
        """
        Returns the integer value of the usage mask bitmask. This value is
        stored in the database.

        Args:
            value(list<enums.CryptographicUsageMask>): list of enums in the
            usage mask
            dialect(string): SQL dialect
        """
        bitmask = 0x00
        for e in value:
            bitmask = bitmask | e.value
        return bitmask


Instruction:
How would you implement a function in Python 3 that
returns a new list of enums.CryptographicUsageMask Enums. This converts the integer value into the list of enums. Args: value(int): The integer value stored in the database that is used to create the list of enums.CryptographicUsageMask Enums. dialect(string): SQL dialect

Response:
def process_result_value(self, value, dialect):
        """
        Returns a new list of enums.CryptographicUsageMask Enums. This converts
        the integer value into the list of enums.

        Args:
            value(int): The integer value stored in the database that is used
                to create the list of enums.CryptographicUsageMask Enums.
            dialect(string): SQL dialect
        """
        masks = list()
        if value:
            for e in enums.CryptographicUsageMask:
                if e.value & value:
                    masks.append(e)
        return masks


Instruction:
Write a Python 3 function that can
read the encoding of the LongInteger from the input stream.

Response:
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Read the encoding of the LongInteger from the input stream.

        Args:
            istream (stream): A buffer containing the encoded bytes of a
                LongInteger. Usually a BytearrayStream object. Required.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            InvalidPrimitiveLength: if the long integer encoding read in has
                an invalid encoded length.
        """
        super(LongInteger, self).read(istream, kmip_version=kmip_version)

        if self.length is not LongInteger.LENGTH:
            raise exceptions.InvalidPrimitiveLength(
                "invalid long integer length read; "
                "expected: {0}, observed: {1}".format(
                    LongInteger.LENGTH, self.length))

        self.value = unpack('!q', istream.read(self.length))[0]
        self.validate()


Instruction:
Make a summary of the following Python 3 code
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        super(LongInteger, self).write(ostream, kmip_version=kmip_version)
        ostream.write(pack('!q', self.value))

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


Instruction:
Can you write a function in Python 3 where it
verifies that the value of the LongInteger is valid.

Response:
def validate(self):
        """
        Verify that the value of the LongInteger is valid.

        Raises:
            TypeError: if the value is not of type int or long
            ValueError: if the value cannot be represented by a signed 64-bit
                integer
        """
        if self.value is not None:
            if not isinstance(self.value, six.integer_types):
                raise TypeError('expected (one of): {0}, observed: {1}'.format(
                    six.integer_types, type(self.value)))
            else:
                if self.value > LongInteger.MAX:
                    raise ValueError(
                        'long integer value greater than accepted max')
                elif self.value < LongInteger.MIN:
                    raise ValueError(
                        'long integer value less than accepted min')


Instruction:
Can you generate a brief explanation for the following Python 3 code
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        super(BigInteger, self).read(istream, kmip_version=kmip_version)

        # Check for a valid length before even trying to parse the value.
        if self.length % 8:
            raise exceptions.InvalidPrimitiveLength(
                "invalid big integer length read; "
                "expected: multiple of 8, observed: {0}".format(self.length))

        sign = 1
        binary = ''

        # Read the value byte by byte and convert it into binary, padding each
        # byte as needed.
        for _ in range(self.length):
            byte = struct.unpack('!B', istream.read(1))[0]
            bits = "{0:b}".format(byte)
            pad = len(bits) % 8
            if pad:
                bits = ('0' * (8 - pad)) + bits
            binary += bits

        # If the value is negative, convert via two's complement.
        if binary[0] == '1':
            sign = -1
            binary = binary.replace('1', 'i')
            binary = binary.replace('0', '1')
            binary = binary.replace('i', '0')

            pivot = binary.rfind('0')
            binary = binary[0:pivot] + '1' + ('0' * len(binary[pivot + 1:]))

        # Convert the value back to an integer and reapply the sign.
        self.value = int(binary, 2) * sign

Response:
Reads the encoding of the has
            from the input stream.


Instruction:
Write a Python 3 function for
writing the encoding of the BigInteger object to the output stream.

Response:
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the encoding of the BigInteger to the output stream.

        Args:
            ostream (Stream): A buffer to contain the encoded bytes of a
                BigInteger object. Usually a BytearrayStream object.
                Required.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.
        """
        # Convert the value to binary and pad it as needed.
        binary = "{0:b}".format(abs(self.value))
        binary = ("0" * (64 - (len(binary) % 64))) + binary

        # If the value is negative, convert via two's complement.
        if self.value < 0:
            binary = binary.replace('1', 'i')
            binary = binary.replace('0', '1')
            binary = binary.replace('i', '0')

            pivot = binary.rfind('0')
            binary = binary[0:pivot] + '1' + ('0' * len(binary[pivot + 1:]))

        # Convert each byte to hex and build the hex string for the value.
        hexadecimal = b''
        for i in range(0, len(binary), 8):
            byte = binary[i:i + 8]
            byte = int(byte, 2)
            hexadecimal += struct.pack('!B', byte)

        self.length = len(hexadecimal)
        super(BigInteger, self).write(ostream, kmip_version=kmip_version)
        ostream.write(hexadecimal)


Instruction:
Make a summary of the following Python 3 code
def validate(self):
        if self.value is not None:
            if not isinstance(self.value, six.integer_types):
                raise TypeError('expected (one of): {0}, observed: {1}'.format(
                    six.integer_types, type(self.value)))

Response: Verify that the value of the BigInteger is valid.


Instruction:
How would you implement a function in Python 3 that
verifies that the value of the Enumeration is valid.

Response:
def validate(self):
        """
        Verify that the value of the Enumeration is valid.

        Raises:
            TypeError: if the enum is not of type Enum
            ValueError: if the value is not of the expected Enum subtype or if
                the value cannot be represented by an unsigned 32-bit integer
        """
        if not isinstance(self.enum, enumeration.EnumMeta):
            raise TypeError(
                'enumeration type {0} must be of type EnumMeta'.format(
                    self.enum))
        if self.value is not None:
            if not isinstance(self.value, self.enum):
                raise TypeError(
                    'enumeration {0} must be of type {1}'.format(
                        self.value, self.enum))
            if type(self.value.value) not in six.integer_types:
                raise TypeError('enumeration value must be an int')
            else:
                if self.value.value > Enumeration.MAX:
                    raise ValueError(
                        'enumeration value greater than accepted max')
                elif self.value.value < Enumeration.MIN:
                    raise ValueError(
                        'enumeration value less than accepted min')


Instruction:
Make a summary of the following Python 3 code
def read_value(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        try:
            value = unpack('!Q', istream.read(self.LENGTH))[0]
        except Exception:
            self.logger.error("Error reading boolean value from buffer")
            raise

        if value == 1:
            self.value = True
        elif value == 0:
            self.value = False
        else:
            raise ValueError("expected: 0 or 1, observed: {0}".format(value))

        self.validate()

Response: Reads the value of the KMIP Boolean object from the input stream.


Instruction:
Create a Python 3 function to
write the value of the object to the output stream.

Response:
def write_value(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the value of the Boolean object to the output stream.

        Args:
            ostream (Stream): A buffer to contain the encoded bytes of the
                value of a Boolean object. Usually a BytearrayStream object.
                Required.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 1.0.
        """
        try:
            ostream.write(pack('!Q', self.value))
        except Exception:
            self.logger.error("Error writing boolean value to buffer")
            raise


Instruction:
How would you explain what the following Python 3 function does
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        super(Boolean, self).write(ostream, kmip_version=kmip_version)
        self.write_value(ostream, kmip_version=kmip_version)

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


Instruction:
Explain what the following Python 3 code does
def validate(self):
        if self.value:
            if not isinstance(self.value, bool):
                raise TypeError("expected: {0}, observed: {1}".format(
                    bool, type(self.value)))

Response: Verify that the value of the Boolean object is valid.


Instruction:
How would you code a function in Python 3 to
read the encoding of the Interval from the input stream.

Response:
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Read the encoding of the Interval from the input stream.

        Args:
            istream (stream): A buffer containing the encoded bytes of the
                value of an Interval. Usually a BytearrayStream object.
                Required.
            kmip_version (KMIPVersion): An enumeration defining the KMIP
                version with which the object will be decoded. Optional,
                defaults to KMIP 1.0.

        Raises:
            InvalidPrimitiveLength: if the Interval encoding read in has an
                invalid encoded length.
            InvalidPaddingBytes: if the Interval encoding read in does not use
                zeroes for its padding bytes.
        """
        super(Interval, self).read(istream, kmip_version=kmip_version)

        # Check for a valid length before even trying to parse the value.
        if self.length != Interval.LENGTH:
            raise exceptions.InvalidPrimitiveLength(
                "interval length must be {0}".format(Interval.LENGTH))

        # Decode the Interval value and the padding bytes.
        self.value = unpack('!I', istream.read(Interval.LENGTH))[0]
        pad = unpack('!I', istream.read(Interval.LENGTH))[0]

        # Verify that the padding bytes are zero bytes.
        if pad != 0:
            raise exceptions.InvalidPaddingBytes("padding bytes must be zero")

        self.validate()


Instruction:
Write a Python 3 script to
verify that the value of the Interval is valid.

Response:
def validate(self):
        """
        Verify that the value of the Interval is valid.

        Raises:
            TypeError: if the value is not of type int or long
            ValueError: if the value cannot be represented by an unsigned
                32-bit integer
        """
        if self.value is not None:
            if type(self.value) not in six.integer_types:
                raise TypeError('expected (one of): {0}, observed: {1}'.format(
                    six.integer_types, type(self.value)))
            else:
                if self.value > Interval.MAX:
                    raise ValueError(
                        'interval value greater than accepted max')
                elif self.value < Interval.MIN:
                    raise ValueError('interval value less than accepted min')


Instruction:
Can you generate a brief explanation for the following Python 3 code
def key_wrapping_data(self):
        key_wrapping_data = {}
        encryption_key_info = {
            'unique_identifier': self._kdw_eki_unique_identifier,
            'cryptographic_parameters': {
                'block_cipher_mode': self._kdw_eki_cp_block_cipher_mode,
                'padding_method': self._kdw_eki_cp_padding_method,
                'hashing_algorithm': self._kdw_eki_cp_hashing_algorithm,
                'key_role_type': self._kdw_eki_cp_key_role_type,
                'digital_signature_algorithm':
                    self._kdw_eki_cp_digital_signature_algorithm,
                'cryptographic_algorithm':
                    self._kdw_eki_cp_cryptographic_algorithm,
                'random_iv': self._kdw_eki_cp_random_iv,
                'iv_length': self._kdw_eki_cp_iv_length,
                'tag_length': self._kdw_eki_cp_tag_length,
                'fixed_field_length': self._kdw_eki_cp_fixed_field_length,
                'invocation_field_length':
                    self._kdw_eki_cp_invocation_field_length,
                'counter_length': self._kdw_eki_cp_counter_length,
                'initial_counter_value':
                    self._kdw_eki_cp_initial_counter_value
            }
        }
        if not any(encryption_key_info['cryptographic_parameters'].values()):
            encryption_key_info['cryptographic_parameters'] = {}
        if not any(encryption_key_info.values()):
            encryption_key_info = {}

        mac_sign_key_info = {
            'unique_identifier': self._kdw_mski_unique_identifier,
            'cryptographic_parameters': {
                'block_cipher_mode': self._kdw_mski_cp_block_cipher_mode,
                'padding_method': self._kdw_mski_cp_padding_method,
                'hashing_algorithm': self._kdw_mski_cp_hashing_algorithm,
                'key_role_type': self._kdw_mski_cp_key_role_type,
                'digital_signature_algorithm':
                    self._kdw_mski_cp_digital_signature_algorithm,
                'cryptographic_algorithm':
                    self._kdw_mski_cp_cryptographic_algorithm,
                'random_iv': self._kdw_mski_cp_random_iv,
                'iv_length': self._kdw_mski_cp_iv_length,
                'tag_length': self._kdw_mski_cp_tag_length,
                'fixed_field_length': self._kdw_mski_cp_fixed_field_length,
                'invocation_field_length':
                    self._kdw_mski_cp_invocation_field_length,
                'counter_length': self._kdw_mski_cp_counter_length,
                'initial_counter_value':
                    self._kdw_mski_cp_initial_counter_value
            }
        }
        if not any(mac_sign_key_info['cryptographic_parameters'].values()):
            mac_sign_key_info['cryptographic_parameters'] = {}
        if not any(mac_sign_key_info.values()):
            mac_sign_key_info = {}

        key_wrapping_data['wrapping_method'] = self._kdw_wrapping_method
        key_wrapping_data['encryption_key_information'] = encryption_key_info
        key_wrapping_data['mac_signature_key_information'] = mac_sign_key_info
        key_wrapping_data['mac_signature'] = self._kdw_mac_signature
        key_wrapping_data['iv_counter_nonce'] = self._kdw_iv_counter_nonce
        key_wrapping_data['encoding_option'] = self._kdw_encoding_option
        if not any(key_wrapping_data.values()):
            key_wrapping_data = {}

        return key_wrapping_data

Response: Retrieves all of the relevant key wrapping data fields and return them as a dictionary.


Instruction:
Implement a Python 3 function for
setting the key wrapping data attributes using a dictionary.

Response:
def key_wrapping_data(self, value):
        """
        Set the key wrapping data attributes using a dictionary.
        """
        if value is None:
            value = {}
        elif not isinstance(value, dict):
            raise TypeError("Key wrapping data must be a dictionary.")

        self._kdw_wrapping_method = value.get('wrapping_method')

        eki = value.get('encryption_key_information')
        if eki is None:
            eki = {}
        self._kdw_eki_unique_identifier = eki.get('unique_identifier')
        eki_cp = eki.get('cryptographic_parameters')
        if eki_cp is None:
            eki_cp = {}
        self._kdw_eki_cp_block_cipher_mode = eki_cp.get('block_cipher_mode')
        self._kdw_eki_cp_padding_method = eki_cp.get('padding_method')
        self._kdw_eki_cp_hashing_algorithm = eki_cp.get('hashing_algorithm')
        self._kdw_eki_cp_key_role_type = eki_cp.get('key_role_type')
        self._kdw_eki_cp_digital_signature_algorithm = \
            eki_cp.get('digital_signature_algorithm')
        self._kdw_eki_cp_cryptographic_algorithm = \
            eki_cp.get('cryptographic_algorithm')
        self._kdw_eki_cp_random_iv = eki_cp.get('random_iv')
        self._kdw_eki_cp_iv_length = eki_cp.get('iv_length')
        self._kdw_eki_cp_tag_length = eki_cp.get('tag_length')
        self._kdw_eki_cp_fixed_field_length = eki_cp.get('fixed_field_length')
        self._kdw_eki_cp_invocation_field_length = \
            eki_cp.get('invocation_field_length')
        self._kdw_eki_cp_counter_length = eki_cp.get('counter_length')
        self._kdw_eki_cp_initial_counter_value = \
            eki_cp.get('initial_counter_value')

        mski = value.get('mac_signature_key_information')
        if mski is None:
            mski = {}
        self._kdw_mski_unique_identifier = mski.get('unique_identifier')
        mski_cp = mski.get('cryptographic_parameters')
        if mski_cp is None:
            mski_cp = {}
        self._kdw_mski_cp_block_cipher_mode = mski_cp.get('block_cipher_mode')
        self._kdw_mski_cp_padding_method = mski_cp.get('padding_method')
        self._kdw_mski_cp_hashing_algorithm = mski_cp.get('hashing_algorithm')
        self._kdw_mski_cp_key_role_type = mski_cp.get('key_role_type')
        self._kdw_mski_cp_digital_signature_algorithm = \
            mski_cp.get('digital_signature_algorithm')
        self._kdw_mski_cp_cryptographic_algorithm = \
            mski_cp.get('cryptographic_algorithm')
        self._kdw_mski_cp_random_iv = mski_cp.get('random_iv')
        self._kdw_mski_cp_iv_length = mski_cp.get('iv_length')
        self._kdw_mski_cp_tag_length = mski_cp.get('tag_length')
        self._kdw_mski_cp_fixed_field_length = \
            mski_cp.get('fixed_field_length')
        self._kdw_mski_cp_invocation_field_length = \
            mski_cp.get('invocation_field_length')
        self._kdw_mski_cp_counter_length = mski_cp.get('counter_length')
        self._kdw_mski_cp_initial_counter_value = \
            mski_cp.get('initial_counter_value')

        self._kdw_mac_signature = value.get('mac_signature')
        self._kdw_iv_counter_nonce = value.get('iv_counter_nonce')
        self._kdw_encoding_option = value.get('encoding_option')


Instruction:
How would you explain what the following Python 3 function does
def validate(self):
        if not isinstance(self.value, bytes):
            raise TypeError("key value must be bytes")
        elif not isinstance(self.cryptographic_algorithm,
                            enums.CryptographicAlgorithm):
            raise TypeError("key algorithm must be a CryptographicAlgorithm "
                            "enumeration")
        elif not isinstance(self.cryptographic_length, six.integer_types):
            raise TypeError("key length must be an integer")
        elif not isinstance(self.key_format_type, enums.KeyFormatType):
            raise TypeError("key format type must be a KeyFormatType "
                            "enumeration")
        elif self.key_format_type not in self._valid_formats:
            raise ValueError("key format type must be one of {0}".format(
                self._valid_formats))

        # TODO (peter-hamilton) Verify that the key bytes match the key format

        mask_count = len(self.cryptographic_usage_masks)
        for i in range(mask_count):
            mask = self.cryptographic_usage_masks[i]
            if not isinstance(mask, enums.CryptographicUsageMask):
                position = "({0} in list)".format(i)
                raise TypeError(
                    "key mask {0} must be a CryptographicUsageMask "
                    "enumeration".format(position))

        name_count = len(self.names)
        for i in range(name_count):
            name = self.names[i]
            if not isinstance(name, six.string_types):
                position = "({0} in list)".format(i)
                raise TypeError("key name {0} must be a string".format(
                    position))

Response: Validates that the contents of the PublicKey object are valid.


Instruction:
How would you implement a function in Python 3 that
ensures that the contents of the SecretData object is valid.

Response:
def validate(self):
        """
        Verify that the contents of the SecretData object are valid.

        Raises:
            TypeError: if the types of any SecretData attributes are invalid.
        """
        if not isinstance(self.value, bytes):
            raise TypeError("secret value must be bytes")
        elif not isinstance(self.data_type, enums.SecretDataType):
            raise TypeError("secret data type must be a SecretDataType "
                            "enumeration")

        mask_count = len(self.cryptographic_usage_masks)
        for i in range(mask_count):
            mask = self.cryptographic_usage_masks[i]
            if not isinstance(mask, enums.CryptographicUsageMask):
                position = "({0} in list)".format(i)
                raise TypeError(
                    "secret data mask {0} must be a CryptographicUsageMask "
                    "enumeration".format(position))

        name_count = len(self.names)
        for i in range(name_count):
            name = self.names[i]
            if not isinstance(name, six.string_types):
                position = "({0} in list)".format(i)
                raise TypeError("secret data name {0} must be a string".format(
                    position))


Instruction:
Create a Python 3 function for
verifying that the contents of the OpaqueObject are valid.

Response:
def validate(self):
        """
        Verify that the contents of the OpaqueObject are valid.

        Raises:
            TypeError: if the types of any OpaqueObject attributes are invalid.
        """
        if not isinstance(self.value, bytes):
            raise TypeError("opaque value must be bytes")
        elif not isinstance(self.opaque_type, enums.OpaqueDataType):
            raise TypeError("opaque data type must be an OpaqueDataType "
                            "enumeration")

        name_count = len(self.names)
        for i in range(name_count):
            name = self.names[i]
            if not isinstance(name, six.string_types):
                position = "({0} in list)".format(i)
                raise TypeError("opaque data name {0} must be a string".format(
                    position))


Instruction:
Can you tell what is the following Python 3 function doing
def get_bit_mask_from_enumerations(enumerations):
    return functools.reduce(
        lambda x, y: x | y, [z.value for z in enumerations]
    )

Response: A utility function that computes a bit mask from a collection of enumeration values.


Instruction:
Explain what the following Python 3 code does
def get_enumerations_from_bit_mask(enumeration, mask):
    return [x for x in enumeration if (x.value & mask) == x.value]

Response: This utility function creates a list of enumeration values corresponding to a specific bit mask enumeration class.


Instruction:
Make a summary of the following Python 3 code
def is_bit_mask(enumeration, potential_mask):
    if not isinstance(potential_mask, six.integer_types):
        return False

    mask_enumerations = (
        CryptographicUsageMask,
        ProtectionStorageMask,
        StorageStatusMask
    )
    if enumeration not in mask_enumerations:
        return False

    mask = 0
    for value in [e.value for e in enumeration]:
        if (value & potential_mask) == value:
            mask |= value

    if mask != potential_mask:
        return False

    return True

Response: A utility function that checks if the provided value is a composite bit mask of the specified enumeration class.


Instruction:
How would you explain what the following Python 3 function does
def is_attribute(tag, kmip_version=None):
    kmip_1_0_attribute_tags = [
        Tags.UNIQUE_IDENTIFIER,
        Tags.NAME,
        Tags.OBJECT_TYPE,
        Tags.CRYPTOGRAPHIC_ALGORITHM,
        Tags.CRYPTOGRAPHIC_LENGTH,
        Tags.CRYPTOGRAPHIC_PARAMETERS,
        Tags.CRYPTOGRAPHIC_DOMAIN_PARAMETERS,
        Tags.CERTIFICATE_TYPE,
        Tags.CERTIFICATE_IDENTIFIER,
        Tags.CERTIFICATE_SUBJECT,
        Tags.CERTIFICATE_ISSUER,
        Tags.DIGEST,
        Tags.OPERATION_POLICY_NAME,
        Tags.CRYPTOGRAPHIC_USAGE_MASK,
        Tags.LEASE_TIME,
        Tags.USAGE_LIMITS,
        Tags.STATE,
        Tags.INITIAL_DATE,
        Tags.ACTIVATION_DATE,
        Tags.PROCESS_START_DATE,
        Tags.PROTECT_STOP_DATE,
        Tags.DEACTIVATION_DATE,
        Tags.DESTROY_DATE,
        Tags.COMPROMISE_OCCURRENCE_DATE,
        Tags.COMPROMISE_DATE,
        Tags.REVOCATION_REASON,
        Tags.ARCHIVE_DATE,
        Tags.OBJECT_GROUP,
        Tags.LINK,
        Tags.APPLICATION_SPECIFIC_INFORMATION,
        Tags.CONTACT_INFORMATION,
        Tags.LAST_CHANGE_DATE,
        Tags.CUSTOM_ATTRIBUTE
    ]
    kmip_1_1_attribute_tags = copy.deepcopy(kmip_1_0_attribute_tags) + [
        Tags.CERTIFICATE_LENGTH,
        Tags.X_509_CERTIFICATE_IDENTIFIER,
        Tags.X_509_CERTIFICATE_SUBJECT,
        Tags.X_509_CERTIFICATE_ISSUER,
        Tags.DIGITAL_SIGNATURE_ALGORITHM,
        Tags.FRESH
    ]
    kmip_1_2_attribute_tags = copy.deepcopy(kmip_1_1_attribute_tags) + [
        Tags.ALTERNATIVE_NAME,
        Tags.KEY_VALUE_PRESENT,
        Tags.KEY_VALUE_LOCATION,
        Tags.ORIGINAL_CREATION_DATE
    ]
    kmip_1_3_attribute_tags = copy.deepcopy(kmip_1_2_attribute_tags) + [
        Tags.RANDOM_NUMBER_GENERATOR
    ]
    kmip_1_4_attribute_tags = copy.deepcopy(kmip_1_3_attribute_tags) + [
        Tags.PKCS12_FRIENDLY_NAME,
        Tags.DESCRIPTION,
        Tags.COMMENT,
        Tags.SENSITIVE,
        Tags.ALWAYS_SENSITIVE,
        Tags.EXTRACTABLE,
        Tags.NEVER_EXTRACTABLE
    ]
    kmip_2_0_attribute_tags = copy.deepcopy(kmip_1_4_attribute_tags) + [
        Tags.CERTIFICATE_SUBJECT_CN,
        Tags.CERTIFICATE_SUBJECT_O,
        Tags.CERTIFICATE_SUBJECT_OU,
        Tags.CERTIFICATE_SUBJECT_EMAIL,
        Tags.CERTIFICATE_SUBJECT_C,
        Tags.CERTIFICATE_SUBJECT_ST,
        Tags.CERTIFICATE_SUBJECT_L,
        Tags.CERTIFICATE_SUBJECT_UID,
        Tags.CERTIFICATE_SUBJECT_SERIAL_NUMBER,
        Tags.CERTIFICATE_SUBJECT_TITLE,
        Tags.CERTIFICATE_SUBJECT_DC,
        Tags.CERTIFICATE_SUBJECT_DN_QUALIFIER,
        Tags.CERTIFICATE_ISSUER_CN,
        Tags.CERTIFICATE_ISSUER_O,
        Tags.CERTIFICATE_ISSUER_OU,
        Tags.CERTIFICATE_ISSUER_EMAIL,
        Tags.CERTIFICATE_ISSUER_C,
        Tags.CERTIFICATE_ISSUER_ST,
        Tags.CERTIFICATE_ISSUER_L,
        Tags.CERTIFICATE_ISSUER_UID,
        Tags.CERTIFICATE_ISSUER_SERIAL_NUMBER,
        Tags.CERTIFICATE_ISSUER_TITLE,
        Tags.CERTIFICATE_ISSUER_DC,
        Tags.CERTIFICATE_ISSUER_DN_QUALIFIER,
        Tags.KEY_FORMAT_TYPE,
        Tags.NIST_KEY_TYPE,
        Tags.OPAQUE_DATA_TYPE,
        Tags.PROTECTION_LEVEL,
        Tags.PROTECTION_PERIOD,
        Tags.PROTECTION_STORAGE_MASK,
        Tags.QUANTUM_SAFE,
        Tags.SHORT_UNIQUE_IDENTIFIER,
        Tags.ATTRIBUTE
    ]
    kmip_2_0_attribute_tags.remove(Tags.CERTIFICATE_IDENTIFIER)
    kmip_2_0_attribute_tags.remove(Tags.CERTIFICATE_SUBJECT)
    kmip_2_0_attribute_tags.remove(Tags.CERTIFICATE_ISSUER)
    kmip_2_0_attribute_tags.remove(Tags.OPERATION_POLICY_NAME)
    kmip_2_0_attribute_tags.remove(Tags.CUSTOM_ATTRIBUTE)

    if kmip_version == KMIPVersion.KMIP_1_0:
        return tag in kmip_1_0_attribute_tags
    elif kmip_version == KMIPVersion.KMIP_1_1:
        return tag in kmip_1_1_attribute_tags
    elif kmip_version == KMIPVersion.KMIP_1_2:
        return tag in kmip_1_2_attribute_tags
    elif kmip_version == KMIPVersion.KMIP_1_3:
        return tag in kmip_1_3_attribute_tags
    elif kmip_version == KMIPVersion.KMIP_1_4:
        return tag in kmip_1_4_attribute_tags
    elif kmip_version == KMIPVersion.KMIP_2_0:
        return tag in kmip_2_0_attribute_tags
    else:
        all_attribute_tags = set(
            kmip_1_0_attribute_tags +
            kmip_1_1_attribute_tags +
            kmip_1_2_attribute_tags +
            kmip_1_3_attribute_tags +
            kmip_1_4_attribute_tags +
            kmip_2_0_attribute_tags
        )
        return tag in all_attribute_tags

Response: A utility function that checks if the tag is a valid attribute tag.


Instruction:
Can you tell what is the following Python 3 function doing
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
        super(CreateKeyPairRequestPayload, self).read(
            input_buffer,
            kmip_version=kmip_version
        )
        local_buffer = utils.BytearrayStream(input_buffer.read(self.length))

        if kmip_version < enums.KMIPVersion.KMIP_2_0:
            if self.is_tag_next(
                    enums.Tags.COMMON_TEMPLATE_ATTRIBUTE,
                    local_buffer
            ):
                self._common_template_attribute = objects.TemplateAttribute(
                    tag=enums.Tags.COMMON_TEMPLATE_ATTRIBUTE
                )
                self._common_template_attribute.read(
                    local_buffer,
                    kmip_version=kmip_version
                )
        else:
            if self.is_tag_next(enums.Tags.COMMON_ATTRIBUTES, local_buffer):
                attributes = objects.Attributes(
                    tag=enums.Tags.COMMON_ATTRIBUTES
                )
                attributes.read(local_buffer, kmip_version=kmip_version)
                self._common_template_attribute = \
                    objects.convert_attributes_to_template_attribute(
                        attributes
                    )

        if kmip_version < enums.KMIPVersion.KMIP_2_0:
            if self.is_tag_next(
                    enums.Tags.PRIVATE_KEY_TEMPLATE_ATTRIBUTE,
                    local_buffer
            ):
                self._private_key_template_attribute = \
                    objects.TemplateAttribute(
                        tag=enums.Tags.PRIVATE_KEY_TEMPLATE_ATTRIBUTE
                    )
                self._private_key_template_attribute.read(
                    local_buffer,
                    kmip_version=kmip_version
                )
        else:
            if self.is_tag_next(
                    enums.Tags.PRIVATE_KEY_ATTRIBUTES,
                    local_buffer
            ):
                attributes = objects.Attributes(
                    tag=enums.Tags.PRIVATE_KEY_ATTRIBUTES
                )
                attributes.read(local_buffer, kmip_version=kmip_version)
                self._private_key_template_attribute = \
                    objects.convert_attributes_to_template_attribute(
                        attributes
                    )

        if kmip_version < enums.KMIPVersion.KMIP_2_0:
            if self.is_tag_next(
                    enums.Tags.PUBLIC_KEY_TEMPLATE_ATTRIBUTE,
                    local_buffer
            ):
                self._public_key_template_attribute = \
                    objects.TemplateAttribute(
                        tag=enums.Tags.PUBLIC_KEY_TEMPLATE_ATTRIBUTE
                    )
                self._public_key_template_attribute.read(
                    local_buffer,
                    kmip_version=kmip_version
                )
        else:
            if self.is_tag_next(
                    enums.Tags.PUBLIC_KEY_ATTRIBUTES,
                    local_buffer
            ):
                attributes = objects.Attributes(
                    tag=enums.Tags.PUBLIC_KEY_ATTRIBUTES
                )
                attributes.read(local_buffer, kmip_version=kmip_version)
                self._public_key_template_attribute = \
                    objects.convert_attributes_to_template_attribute(
                        attributes
                    )

        self.is_oversized(local_buffer)

Response: Reads the data encoding the CreateKeyPairRequestPayload and decodes it into constituent parts.


Instruction:
How would you implement a function in Python 3 that
writes the data encoding the CreateKeyPair request payload to a stream.

Response:
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the CreateKeyPair request payload to a buffer.

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

        if kmip_version < enums.KMIPVersion.KMIP_2_0:
            if self._common_template_attribute is not None:
                self._common_template_attribute.write(
                    local_buffer,
                    kmip_version=kmip_version
                )
        else:
            if self._common_template_attribute is not None:
                attributes = objects.convert_template_attribute_to_attributes(
                    self._common_template_attribute
                )
                attributes.write(local_buffer, kmip_version=kmip_version)

        if kmip_version < enums.KMIPVersion.KMIP_2_0:
            if self._private_key_template_attribute is not None:
                self._private_key_template_attribute.write(
                    local_buffer,
                    kmip_version=kmip_version
                )
        else:
            if self._private_key_template_attribute is not None:
                attributes = objects.convert_template_attribute_to_attributes(
                    self._private_key_template_attribute
                )
                attributes.write(local_buffer, kmip_version=kmip_version)

        if kmip_version < enums.KMIPVersion.KMIP_2_0:
            if self._public_key_template_attribute is not None:
                self._public_key_template_attribute.write(
                    local_buffer,
                    kmip_version=kmip_version
                )
        else:
            if self._public_key_template_attribute is not None:
                attributes = objects.convert_template_attribute_to_attributes(
                    self._public_key_template_attribute
                )
                attributes.write(local_buffer, kmip_version=kmip_version)

        self.length = local_buffer.length()
        super(CreateKeyPairRequestPayload, self).write(
            output_buffer,
            kmip_version=kmip_version
        )
        output_buffer.write(local_buffer.buffer)


Instruction:
How would you explain what the following Python 3 function does
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
        super(CreateKeyPairResponsePayload, self).read(
            input_buffer,
            kmip_version=kmip_version
        )
        local_buffer = utils.BytearrayStream(input_buffer.read(self.length))

        if self.is_tag_next(
                enums.Tags.PRIVATE_KEY_UNIQUE_IDENTIFIER,
                local_buffer
        ):
            self._private_key_unique_identifier = primitives.TextString(
                tag=enums.Tags.PRIVATE_KEY_UNIQUE_IDENTIFIER
            )
            self._private_key_unique_identifier.read(
                local_buffer,
                kmip_version=kmip_version
            )
        else:
            raise exceptions.InvalidKmipEncoding(
                "The CreateKeyPair response payload encoding is missing the "
                "private key unique identifier."
            )

        if self.is_tag_next(
                enums.Tags.PUBLIC_KEY_UNIQUE_IDENTIFIER,
                local_buffer
        ):
            self._public_key_unique_identifier = primitives.TextString(
                tag=enums.Tags.PUBLIC_KEY_UNIQUE_IDENTIFIER
            )
            self._public_key_unique_identifier.read(
                local_buffer,
                kmip_version=kmip_version
            )
        else:
            raise exceptions.InvalidKmipEncoding(
                "The CreateKeyPair response payload encoding is missing the "
                "public key unique identifier."
            )

        if kmip_version < enums.KMIPVersion.KMIP_2_0:
            if self.is_tag_next(
                    enums.Tags.PRIVATE_KEY_TEMPLATE_ATTRIBUTE,
                    local_buffer
            ):
                self._private_key_template_attribute = \
                    objects.TemplateAttribute(
                        tag=enums.Tags.PRIVATE_KEY_TEMPLATE_ATTRIBUTE
                    )
                self._private_key_template_attribute.read(
                    local_buffer,
                    kmip_version=kmip_version
                )

            if self.is_tag_next(
                    enums.Tags.PUBLIC_KEY_TEMPLATE_ATTRIBUTE,
                    local_buffer
            ):
                self._public_key_template_attribute = \
                    objects.TemplateAttribute(
                        tag=enums.Tags.PUBLIC_KEY_TEMPLATE_ATTRIBUTE
                    )
                self._public_key_template_attribute.read(
                    local_buffer,
                    kmip_version=kmip_version
                )

        self.is_oversized(local_buffer)

Response: Reads the data encoding the CreateKeyPair response payload and decode it into constituent parts.


Instruction:
Can you tell what is the following Python 3 function doing
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
        local_buffer = utils.BytearrayStream()

        if self._private_key_unique_identifier:
            self._private_key_unique_identifier.write(
                local_buffer,
                kmip_version=kmip_version
            )
        else:
            raise exceptions.InvalidField(
                "The CreateKeyPair response payload is missing the private "
                "key unique identifier field."
            )

        if self._public_key_unique_identifier:
            self._public_key_unique_identifier.write(
                local_buffer,
                kmip_version=kmip_version
            )
        else:
            raise exceptions.InvalidField(
                "The CreateKeyPair response payload is missing the public "
                "key unique identifier field."
            )

        if self._private_key_template_attribute:
            self._private_key_template_attribute.write(
                local_buffer,
                kmip_version=kmip_version
            )

        if self._public_key_template_attribute:
            self._public_key_template_attribute.write(
                local_buffer,
                kmip_version=kmip_version
            )

        self.length = local_buffer.length()
        super(CreateKeyPairResponsePayload, self).write(
            output_buffer,
            kmip_version=kmip_version
        )
        output_buffer.write(local_buffer.buffer)

Response: Writes the data encoding the CreateKeyPair response payload to the output_buffer.


Instruction:
Write a Python 3 function that can
read the data encoding the GetAttributeList request payload and decode it into its constituent parts.

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

        Args:
            input_buffer (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(GetAttributeListRequestPayload, self).read(
            input_buffer,
            kmip_version=kmip_version
        )
        local_buffer = utils.BytearrayStream(input_buffer.read(self.length))

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

        self.is_oversized(local_buffer)


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

        if self._unique_identifier:
            self._unique_identifier.write(
                local_buffer,
                kmip_version=kmip_version
            )

        self.length = local_buffer.length()
        super(GetAttributeListRequestPayload, self).write(
            output_buffer,
            kmip_version=kmip_version
        )
        output_buffer.write(local_buffer.buffer)

Response: Writes the data encoding the GetAttributeList request payload to the output_buffer.


Instruction:
Here you have a function in Python 3, explain what it does
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
        super(GetAttributeListResponsePayload, self).read(
            input_buffer,
            kmip_version=kmip_version
        )
        local_buffer = utils.BytearrayStream(input_buffer.read(self.length))

        if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_buffer):
            self._unique_identifier = primitives.TextString(
                tag=enums.Tags.UNIQUE_IDENTIFIER
            )
            self._unique_identifier.read(
                local_buffer,
                kmip_version=kmip_version
            )
        else:
            raise exceptions.InvalidKmipEncoding(
                "The GetAttributeList response payload encoding is missing "
                "the unique identifier."
            )

        names = list()
        if kmip_version < enums.KMIPVersion.KMIP_2_0:
            while self.is_tag_next(enums.Tags.ATTRIBUTE_NAME, local_buffer):
                name = primitives.TextString(tag=enums.Tags.ATTRIBUTE_NAME)
                name.read(local_buffer, kmip_version=kmip_version)
                names.append(name)
            if len(names) == 0:
                raise exceptions.InvalidKmipEncoding(
                    "The GetAttributeList response payload encoding is "
                    "missing the attribute names."
                )
            self._attribute_names = names
        else:
            while self.is_tag_next(
                    enums.Tags.ATTRIBUTE_REFERENCE,
                    local_buffer
            ):
                if self.is_type_next(enums.Types.STRUCTURE, local_buffer):
                    reference = objects.AttributeReference()
                    reference.read(local_buffer, kmip_version=kmip_version)
                    names.append(
                        primitives.TextString(
                            value=reference.attribute_name,
                            tag=enums.Tags.ATTRIBUTE_NAME
                        )
                    )
                elif self.is_type_next(enums.Types.ENUMERATION, local_buffer):
                    reference = primitives.Enumeration(
                        enums.Tags,
                        tag=enums.Tags.ATTRIBUTE_REFERENCE
                    )
                    reference.read(local_buffer, kmip_version=kmip_version)
                    name = enums.convert_attribute_tag_to_name(reference.value)
                    names.append(
                        primitives.TextString(
                            value=name,
                            tag=enums.Tags.ATTRIBUTE_NAME
                        )
                    )
                else:
                    raise exceptions.InvalidKmipEncoding(
                        "The GetAttributeList response payload encoding "
                        "contains an invalid AttributeReference type."
                    )
            self._attribute_names = names

        self.is_oversized(local_buffer)

Response: Reads the data encoding the GetAttributeList response payload and decodes it into constituent parts.


Instruction:
Write a Python 3 script to
write the data encoding the GetAttributeList response payload to the output_buffer.

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

        Args:
            output_buffer (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:
            InvalidField: Raised if the unique identifier or attribute name
                are not defined.
        """
        local_buffer = utils.BytearrayStream()

        if self._unique_identifier:
            self._unique_identifier.write(
                local_buffer,
                kmip_version=kmip_version
            )
        else:
            raise exceptions.InvalidField(
                "The GetAttributeList response payload is missing the unique "
                "identifier field."
            )

        if self._attribute_names:
            if kmip_version < enums.KMIPVersion.KMIP_2_0:
                for attribute_name in self._attribute_names:
                    attribute_name.write(
                        local_buffer,
                        kmip_version=kmip_version
                    )
            else:
                # NOTE (ph) This approach simplifies backwards compatible
                #           issues but limits easy support for Attribute
                #           Reference structures going forward, specifically
                #           limiting the use of VendorIdentification for
                #           custom attributes. If custom attributes need to
                #           be retrieved using the GetAttributeList operation
                #           for KMIP 2.0 applications this code will need to
                #           change.
                for attribute_name in self._attribute_names:
                    t = enums.convert_attribute_name_to_tag(
                        attribute_name.value
                    )
                    e = primitives.Enumeration(
                        enums.Tags,
                        value=t,
                        tag=enums.Tags.ATTRIBUTE_REFERENCE
                    )
                    e.write(local_buffer, kmip_version=kmip_version)

        else:
            raise exceptions.InvalidField(
                "The GetAttributeList response payload is missing the "
                "attribute names field."
            )

        self.length = local_buffer.length()
        super(GetAttributeListResponsePayload, self).write(
            output_buffer,
            kmip_version=kmip_version
        )
        output_buffer.write(local_buffer.buffer)


Instruction:
Implement a function in Python 3 to
scan the provided directory for all JSON policy files.

Response:
def get_json_files(p):
    """
    Scan the provided policy directory for all JSON policy files.
    """
    f = [os.path.join(p, x) for x in os.listdir(p) if x.endswith(".json")]
    return sorted(f)


Instruction:
How would you code a function in Python 3 to
scan the policy directory for policies and load them into memory.

Response:
def scan_policies(self):
        """
        Scan the policy directory for policy data.
        """
        policy_files = get_json_files(self.policy_directory)
        for f in set(policy_files) - set(self.policy_files):
            self.file_timestamps[f] = 0
        for f in set(self.policy_files) - set(policy_files):
            self.logger.info("Removing policies for file: {}".format(f))
            self.file_timestamps.pop(f, None)
            for p in self.policy_cache.keys():
                self.disassociate_policy_and_file(p, f)
            for p in [k for k, v in self.policy_map.items() if v == f]:
                self.restore_or_delete_policy(p)
        self.policy_files = policy_files

        for f in sorted(self.file_timestamps.keys()):
            t = os.path.getmtime(f)
            if t > self.file_timestamps[f]:
                self.logger.info("Loading policies for file: {}".format(f))
                self.file_timestamps[f] = t
                old_p = [k for k, v in self.policy_map.items() if v == f]
                try:
                    new_p = operation_policy.read_policy_from_file(f)
                except ValueError:
                    self.logger.error("Failure loading file: {}".format(f))
                    self.logger.debug("", exc_info=True)
                    continue
                for p in new_p.keys():
                    self.logger.info("Loading policy: {}".format(p))
                    if p in self.reserved_policies:
                        self.logger.warning(
                            "Policy '{}' overwrites a reserved policy and "
                            "will be thrown out.".format(p)
                        )
                        continue
                    if p in sorted(self.policy_store.keys()):
                        self.logger.debug(
                            "Policy '{}' overwrites an existing "
                            "policy.".format(p)
                        )
                        if f != self.policy_map.get(p):
                            self.policy_cache.get(p).append(
                                (
                                    time.time(),
                                    self.policy_map.get(p),
                                    self.policy_store.get(p)
                                )
                            )
                    else:
                        self.policy_cache[p] = []
                    self.policy_store[p] = new_p.get(p)
                    self.policy_map[p] = f
                for p in set(old_p) - set(new_p.keys()):
                    self.disassociate_policy_and_file(p, f)
                    self.restore_or_delete_policy(p)


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

        if self.live_monitoring:
            self.logger.info("Starting up the operation policy file monitor.")
            while not self.halt_trigger.is_set():
                time.sleep(1)
                self.scan_policies()
            self.logger.info("Stopping the operation policy file monitor.")
        else:
            self.scan_policies()

Response: Start monitoring the operation policy files.


Instruction:
Can you write a function in Python 3 where it
extracts an X.509 certificate from a socket connection.

Response:
def get_certificate_from_connection(connection):
    """
    Extract an X.509 certificate from a socket connection.
    """
    certificate = connection.getpeercert(binary_form=True)
    if certificate:
        return x509.load_der_x509_certificate(
            certificate,
            backends.default_backend()
        )
    return None


Instruction:
Can you generate the documentation for the following Python 3 function
def get_extended_key_usage_from_certificate(certificate):
    try:
        return certificate.extensions.get_extension_for_oid(
            x509.oid.ExtensionOID.EXTENDED_KEY_USAGE
        ).value
    except x509.ExtensionNotFound:
        return None

Response:
Given an X.509 certificate extract and return the extendedKeyUsage
    extension.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_common_names_from_certificate(certificate):

    common_names = certificate.subject.get_attributes_for_oid(
        x509.oid.NameOID.COMMON_NAME
    )
    return [common_name.value for common_name in common_names]

Response: Given an X.509 certificate extract and return all common names.


Instruction:
Create a Python 3 function to
give an X.509 certificate extract and return the client identity.

Response:
def get_client_identity_from_certificate(certificate):
    """
    Given an X.509 certificate, extract and return the client identity.
    """
    client_ids = get_common_names_from_certificate(certificate)

    if len(client_ids) > 0:
        if len(client_ids) > 1:
            raise exceptions.PermissionDenied(
                "Multiple client identities found."
            )
        return client_ids[0]
    else:
        raise exceptions.PermissionDenied(
            "The certificate does not define any subject common names. "
            "Client identity unavailable."
        )


Instruction:
Can you generate the documentation for the following Python 3 function
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
        super(CreateRequestPayload, self).read(
            input_buffer,
            kmip_version=kmip_version
        )
        local_buffer = utils.BytearrayStream(input_buffer.read(self.length))

        if self.is_tag_next(enums.Tags.OBJECT_TYPE, local_buffer):
            self._object_type = primitives.Enumeration(
                enums.ObjectType,
                tag=enums.Tags.OBJECT_TYPE
            )
            self._object_type.read(local_buffer, kmip_version=kmip_version)
        else:
            raise exceptions.InvalidKmipEncoding(
                "The Create request payload encoding is missing the object "
                "type."
            )

        if kmip_version < enums.KMIPVersion.KMIP_2_0:
            if self.is_tag_next(enums.Tags.TEMPLATE_ATTRIBUTE, local_buffer):
                self._template_attribute = objects.TemplateAttribute()
                self._template_attribute.read(
                    local_buffer,
                    kmip_version=kmip_version
                )
            else:
                raise exceptions.InvalidKmipEncoding(
                    "The Create request payload encoding is missing the "
                    "template attribute."
                )
        else:
            # NOTE (ph) For now, leave attributes natively in TemplateAttribute
            # form and just convert to the KMIP 2.0 Attributes form as needed
            # for encoding/decoding purposes. Changing the payload to require
            # the new Attributes structure will trigger a bunch of second-order
            # effects across the client and server codebases that is beyond
            # the scope of updating the Create payloads to support KMIP 2.0.
            if self.is_tag_next(enums.Tags.ATTRIBUTES, local_buffer):
                attributes = objects.Attributes()
                attributes.read(local_buffer, kmip_version=kmip_version)
                value = objects.convert_attributes_to_template_attribute(
                    attributes
                )
                self._template_attribute = value
            else:
                raise exceptions.InvalidKmipEncoding(
                    "The Create request payload encoding is missing the "
                    "attributes structure."
                )

        self.is_oversized(local_buffer)

Response: Reads the data encoding the Create Request Payload and decode it into the object type and template attribute parts.


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

Response:
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
        """
        Write the data encoding the Create request payload to a buffer.

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

        Raises:
            InvalidField: Raised if the object type attribute or template
                attribute is not defined.
        """
        local_buffer = utils.BytearrayStream()

        if self._object_type:
            self._object_type.write(local_buffer, kmip_version=kmip_version)
        else:
            raise exceptions.InvalidField(
                "The Create request payload is missing the object type field."
            )

        if kmip_version < enums.KMIPVersion.KMIP_2_0:
            if self._template_attribute:
                self._template_attribute.write(
                    local_buffer,
                    kmip_version=kmip_version
                )
            else:
                raise exceptions.InvalidField(
                    "The Create request payload is missing the template "
                    "attribute field."
                )
        else:
            # NOTE (ph) For now, leave attributes natively in TemplateAttribute
            # form and just convert to the KMIP 2.0 Attributes form as needed
            # for encoding/decoding purposes. Changing the payload to require
            # the new Attributes structure will trigger a bunch of second-order
            # effects across the client and server codebases that is beyond
            # the scope of updating the Create payloads to support KMIP 2.0.
            if self._template_attribute:
                attributes = objects.convert_template_attribute_to_attributes(
                    self._template_attribute
                )
                attributes.write(local_buffer, kmip_version=kmip_version)
            else:
                raise exceptions.InvalidField(
                    "The Create request payload is missing the template "
                    "attribute field."
                )

        self.length = local_buffer.length()
        super(CreateRequestPayload, self).write(
            output_buffer,
            kmip_version=kmip_version
        )
        output_buffer.write(local_buffer.buffer)


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

        if self.is_tag_next(enums.Tags.OBJECT_TYPE, local_buffer):
            self._object_type = primitives.Enumeration(
                enums.ObjectType,
                tag=enums.Tags.OBJECT_TYPE
            )
            self._object_type.read(local_buffer, kmip_version=kmip_version)
        else:
            raise exceptions.InvalidKmipEncoding(
                "The Create response payload encoding is missing the object "
                "type."
            )

        if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_buffer):
            self._unique_identifier = primitives.TextString(
                tag=enums.Tags.UNIQUE_IDENTIFIER
            )
            self._unique_identifier.read(
                local_buffer,
                kmip_version=kmip_version
            )
        else:
            raise exceptions.InvalidKmipEncoding(
                "The Create response payload encoding is missing the unique "
                "identifier."
            )

        if kmip_version < enums.KMIPVersion.KMIP_2_0:
            if self.is_tag_next(enums.Tags.TEMPLATE_ATTRIBUTE, local_buffer):
                self._template_attribute = objects.TemplateAttribute()
                self._template_attribute.read(
                    local_buffer,
                    kmip_version=kmip_version
                )

        self.is_oversized(local_buffer)

Response: Reads the data encoding the Create response payload and decode it into the corresponding parts.


Instruction:
Can you generate the documentation for the following Python 3 function
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
        local_buffer = utils.BytearrayStream()

        if self._object_type:
            self._object_type.write(local_buffer, kmip_version=kmip_version)
        else:
            raise exceptions.InvalidField(
                "The Create response payload is missing the object type field."
            )

        if self._unique_identifier:
            self._unique_identifier.write(
                local_buffer,
                kmip_version=kmip_version
            )
        else:
            raise exceptions.InvalidField(
                "The Create response payload is missing the unique identifier "
                "field."
            )

        if kmip_version < enums.KMIPVersion.KMIP_2_0:
            if self._template_attribute:
                self._template_attribute.write(
                    local_buffer,
                    kmip_version=kmip_version
                )

        self.length = local_buffer.length()
        super(CreateResponsePayload, self).write(
            output_buffer,
            kmip_version=kmip_version
        )
        output_buffer.write(local_buffer.buffer)

Response: Writes the data encoding the object into a stream.


Instruction:
Write a Python 3 script to
convert a Pie object into a core secret object and vice versa.

Response:
def convert(self, obj):
        """
        Convert a Pie object into a core secret object and vice versa.

        Args:
            obj (various): A Pie or core secret object to convert into the
                opposite object space. Required.

        Raises:
            TypeError: if the object type is unrecognized or unsupported.
        """
        if isinstance(obj, pobjects.SymmetricKey):
            return self._build_core_key(obj, secrets.SymmetricKey)
        elif isinstance(obj, secrets.SymmetricKey):
            return self._build_pie_key(obj, pobjects.SymmetricKey)
        elif isinstance(obj, pobjects.PublicKey):
            return self._build_core_key(obj, secrets.PublicKey)
        elif isinstance(obj, secrets.PublicKey):
            return self._build_pie_key(obj, pobjects.PublicKey)
        elif isinstance(obj, pobjects.PrivateKey):
            return self._build_core_key(obj, secrets.PrivateKey)
        elif isinstance(obj, secrets.PrivateKey):
            return self._build_pie_key(obj, pobjects.PrivateKey)
        elif isinstance(obj, pobjects.Certificate):
            return self._build_core_certificate(obj)
        elif isinstance(obj, secrets.Certificate):
            return self._build_pie_certificate(obj)
        elif isinstance(obj, pobjects.SecretData):
            return self._build_core_secret_data(obj)
        elif isinstance(obj, secrets.SecretData):
            return self._build_pie_secret_data(obj)
        elif isinstance(obj, pobjects.OpaqueObject):
            return self._build_core_opaque_object(obj)
        elif isinstance(obj, secrets.OpaqueObject):
            return self._build_pie_opaque_object(obj)
        else:
            raise TypeError("object type unsupported and cannot be converted")


Instruction:
Can you tell what is the following Python 3 function doing
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
        super(EncryptResponsePayload, 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(
                "invalid payload missing the unique identifier attribute"
            )

        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
            )
        else:
            raise ValueError("invalid payload missing the data attribute")

        if self.is_tag_next(enums.Tags.IV_COUNTER_NONCE, local_stream):
            self._iv_counter_nonce = primitives.ByteString(
                tag=enums.Tags.IV_COUNTER_NONCE
            )
            self._iv_counter_nonce.read(
                local_stream,
                kmip_version=kmip_version
            )

        self.is_oversized(local_stream)

Response: Reads the data encoding the Encrypt response payload and decode it into its constituent parts.


Instruction:
Can you write a function in Python 3 where it
reads the DeriveKey request payload and decodes it into its constituent parts.

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

        Args:
            input_buffer (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(DeriveKeyRequestPayload, self).read(
            input_buffer,
            kmip_version=kmip_version
        )
        local_buffer = utils.BytearrayStream(input_buffer.read(self.length))

        if self.is_tag_next(enums.Tags.OBJECT_TYPE, local_buffer):
            self._object_type = primitives.Enumeration(
                enums.ObjectType,
                tag=enums.Tags.OBJECT_TYPE
            )
            self._object_type.read(local_buffer, kmip_version=kmip_version)
        else:
            raise exceptions.InvalidKmipEncoding(
                "The DeriveKey request payload encoding is missing the object "
                "type."
            )

        unique_identifiers = []
        while self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_buffer):
            unique_identifier = primitives.TextString(
                tag=enums.Tags.UNIQUE_IDENTIFIER
            )
            unique_identifier.read(local_buffer, kmip_version=kmip_version)
            unique_identifiers.append(unique_identifier)
        if not unique_identifiers:
            raise exceptions.InvalidKmipEncoding(
                "The DeriveKey request payload encoding is missing the unique "
                "identifiers."
            )
        else:
            self._unique_identifiers = unique_identifiers

        if self.is_tag_next(enums.Tags.DERIVATION_METHOD, local_buffer):
            self._derivation_method = primitives.Enumeration(
                enums.DerivationMethod,
                tag=enums.Tags.DERIVATION_METHOD
            )
            self._derivation_method.read(
                local_buffer,
                kmip_version=kmip_version
            )
        else:
            raise exceptions.InvalidKmipEncoding(
                "The DeriveKey request payload encoding is missing the "
                "derivation method."
            )

        if self.is_tag_next(enums.Tags.DERIVATION_PARAMETERS, local_buffer):
            self._derivation_parameters = attributes.DerivationParameters()
            self._derivation_parameters.read(
                local_buffer,
                kmip_version=kmip_version
            )
        else:
            raise exceptions.InvalidKmipEncoding(
                "The DeriveKey request payload encoding is missing the "
                "derivation parameters."
            )

        if kmip_version < enums.KMIPVersion.KMIP_2_0:
            if self.is_tag_next(enums.Tags.TEMPLATE_ATTRIBUTE, local_buffer):
                self._template_attribute = objects.TemplateAttribute()
                self._template_attribute.read(
                    local_buffer,
                    kmip_version=kmip_version
                )
            else:
                raise exceptions.InvalidKmipEncoding(
                    "The DeriveKey request payload encoding is missing the "
                    "template attribute."
                )
        else:
            if self.is_tag_next(enums.Tags.ATTRIBUTES, local_buffer):
                attrs = objects.Attributes()
                attrs.read(local_buffer, kmip_version=kmip_version)
                value = objects.convert_attributes_to_template_attribute(
                    attrs
                )
                self._template_attribute = value
            else:
                raise exceptions.InvalidKmipEncoding(
                    "The DeriveKey request payload encoding is missing the "
                    "attributes structure."
                )

        self.is_oversized(local_buffer)


Instruction:
Create a Python 3 function to
write the DeriveKey request payload to the output_buffer.

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

        Args:
            output_buffer (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_buffer = utils.BytearrayStream()

        if self._object_type:
            self._object_type.write(local_buffer, kmip_version=kmip_version)
        else:
            raise exceptions.InvalidField(
                "The DeriveKey request payload is missing the object type "
                "field."
            )

        if self._unique_identifiers:
            for unique_identifier in self._unique_identifiers:
                unique_identifier.write(
                    local_buffer,
                    kmip_version=kmip_version
                )
        else:
            raise exceptions.InvalidField(
                "The DeriveKey request payload is missing the unique "
                "identifiers field."
            )

        if self._derivation_method:
            self._derivation_method.write(
                local_buffer,
                kmip_version=kmip_version
            )
        else:
            raise exceptions.InvalidField(
                "The DeriveKey request payload is missing the derivation "
                "method field."
            )

        if self._derivation_parameters:
            self._derivation_parameters.write(
                local_buffer,
                kmip_version=kmip_version
            )
        else:
            raise exceptions.InvalidField(
                "The DeriveKey request payload is missing the derivation "
                "parameters field."
            )

        if kmip_version < enums.KMIPVersion.KMIP_2_0:
            if self._template_attribute:
                self._template_attribute.write(
                    local_buffer,
                    kmip_version=kmip_version
                )
            else:
                raise exceptions.InvalidField(
                    "The DeriveKey request payload is missing the template "
                    "attribute field."
                )
        else:
            if self._template_attribute:
                attrs = objects.convert_template_attribute_to_attributes(
                    self._template_attribute
                )
                attrs.write(local_buffer, kmip_version=kmip_version)
            else:
                raise exceptions.InvalidField(
                    "The DeriveKey request payload is missing the template "
                    "attribute field."
                )

        self.length = local_buffer.length()
        super(DeriveKeyRequestPayload, self).write(
            output_buffer,
            kmip_version=kmip_version
        )
        output_buffer.write(local_buffer.buffer)