Instruction:
Can you tell what is the following Python 3 function doing
def p_annotation_comment_1(self, p):
        try:
            if six.PY2:
                value = p[2].decode(encoding='utf-8')
            else:
                value = p[2]
            self.builder.add_annotation_comment(self.document, value)
        except CardinalityError:
            self.more_than_one_error('AnnotationComment', p.lineno(1))
        except OrderError:
            self.order_error('AnnotationComment', 'Annotator', p.lineno(1))

Response: annotation_comment : ANNOTATION_COMMENT TEXT


Instruction:
Explain what the following Python 3 code does
def p_ext_doc_refs_1(self, p):
        try:
            if six.PY2:
                doc_ref_id = p[2].decode(encoding='utf-8')
                doc_uri = p[3].decode(encoding='utf-8')
                ext_doc_chksum = p[4].decode(encoding='utf-8')
            else:
                doc_ref_id = p[2]
                doc_uri = p[3]
                ext_doc_chksum = p[4]

            self.builder.add_ext_doc_refs(self.document, doc_ref_id, doc_uri,
                                          ext_doc_chksum)
        except SPDXValueError:
            self.error = True
            msg = ERROR_MESSAGES['EXT_DOC_REF_VALUE'].format(p.lineno(2))
            self.logger.log(msg)

Response: \ x1b [ 1mNAME \ x1b [ 0m ext_doc_refs - Adds a new entry to the list of external doc_refs.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def p_creator_comment_1(self, p):
        try:
            if six.PY2:
                value = p[2].decode(encoding='utf-8')
            else:
                value = p[2]
            self.builder.set_creation_comment(self.document, value)
        except CardinalityError:
            self.more_than_one_error('CreatorComment', p.lineno(1))

Response: \ x1b [ 1mNAME \ x1b [ 0m creator_comment - Creates a CREATOR_COMMENT.


Instruction:
Given the following Python 3 function, write the documentation
def p_created_1(self, p):
        try:
            if six.PY2:
                value = p[2].decode(encoding='utf-8')
            else:
                value = p[2]
            self.builder.set_created_date(self.document, value)
        except CardinalityError:
            self.more_than_one_error('Created', p.lineno(1))

Response: \ x1b [ 1mNAME \ x1b [ 0m created - Gets the date of the created item.


Instruction:
Create a Python 3 function for
writing the creation info to out.

Response:
def write_creation_info(creation_info, out):
    """
    Write the creation info to out.
    """
    out.write('# Creation Info\n\n')
    # Write sorted creators
    for creator in sorted(creation_info.creators):
        write_value('Creator', creator, out)

    # write created
    write_value('Created', creation_info.created_iso_format, out)
    # possible comment
    if creation_info.has_comment:
        write_text_value('CreatorComment', creation_info.comment, out)


Instruction:
Can you generate the documentation for the following Python 3 function
def write_review(review, out):
    out.write('# Review\n\n')
    write_value('Reviewer', review.reviewer, out)
    write_value('ReviewDate', review.review_date_iso_format, out)
    if review.has_comment:
        write_text_value('ReviewComment', review.comment, out)

Response: Write the fields of a single review to out.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write_annotation(annotation, out):
    out.write('# Annotation\n\n')
    write_value('Annotator', annotation.annotator, out)
    write_value('AnnotationDate', annotation.annotation_date_iso_format, out)
    if annotation.has_comment:
        write_text_value('AnnotationComment', annotation.comment, out)
    write_value('AnnotationType', annotation.annotation_type, out)
    write_value('SPDXREF', annotation.spdx_id, out)

Response: Writes the fields of an annotation to out.


Instruction:
Create a Python 3 function for
writing a single file to out.

Response:
def write_file(spdx_file, out):
    """
    Write a file fields to out.
    """
    out.write('# File\n\n')
    write_value('FileName', spdx_file.name, out)
    write_value('SPDXID', spdx_file.spdx_id, out)
    if spdx_file.has_optional_field('type'):
        write_file_type(spdx_file.type, out)
    write_value('FileChecksum', spdx_file.chk_sum.to_tv(), out)
    if isinstance(spdx_file.conc_lics, (document.LicenseConjunction, document.LicenseDisjunction)):
        write_value('LicenseConcluded', u'({0})'.format(spdx_file.conc_lics), out)
    else:
        write_value('LicenseConcluded', spdx_file.conc_lics, out)

    # write sorted list
    for lics in sorted(spdx_file.licenses_in_file):
        write_value('LicenseInfoInFile', lics, out)

    if isinstance(spdx_file.copyright, six.string_types):
        write_text_value('FileCopyrightText', spdx_file.copyright, out)
    else:
        write_value('FileCopyrightText', spdx_file.copyright, out)

    if spdx_file.has_optional_field('license_comment'):
        write_text_value('LicenseComments', spdx_file.license_comment, out)

    if spdx_file.has_optional_field('comment'):
        write_text_value('FileComment', spdx_file.comment, out)

    if spdx_file.has_optional_field('notice'):
        write_text_value('FileNotice', spdx_file.notice, out)

    for contributor in sorted(spdx_file.contributors):
        write_value('FileContributor', contributor, out)

    for dependency in sorted(spdx_file.dependencies):
        write_value('FileDependency', dependency, out)

    names = spdx_file.artifact_of_project_name
    homepages = spdx_file.artifact_of_project_home
    uris = spdx_file.artifact_of_project_uri

    for name, homepage, uri in sorted(zip_longest(names, homepages, uris)):
        write_value('ArtifactOfProjectName', name, out)
        if homepage is not None:
            write_value('ArtifactOfProjectHomePage', homepage, out)
        if uri is not None:
            write_value('ArtifactOfProjectURI', uri, out)


Instruction:
How would you explain what the following Python 3 function does
def write_package(package, out):
    out.write('# Package\n\n')
    write_value('PackageName', package.name, out)
    if package.has_optional_field('version'):
        write_value('PackageVersion', package.version, out)
    write_value('PackageDownloadLocation', package.download_location, out)

    if package.has_optional_field('summary'):
        write_text_value('PackageSummary', package.summary, out)

    if package.has_optional_field('source_info'):
        write_text_value('PackageSourceInfo', package.source_info, out)

    if package.has_optional_field('file_name'):
        write_value('PackageFileName', package.file_name, out)

    if package.has_optional_field('supplier'):
        write_value('PackageSupplier', package.supplier, out)

    if package.has_optional_field('originator'):
        write_value('PackageOriginator', package.originator, out)

    if package.has_optional_field('check_sum'):
        write_value('PackageChecksum', package.check_sum.to_tv(), out)

    write_value('PackageVerificationCode', format_verif_code(package), out)

    if package.has_optional_field('description'):
        write_text_value('PackageDescription', package.description, out)

    if isinstance(package.license_declared, (document.LicenseConjunction,
        document.LicenseDisjunction)):
        write_value('PackageLicenseDeclared', u'({0})'.format(package.license_declared), out)
    else:
        write_value('PackageLicenseDeclared', package.license_declared, out)

    if isinstance(package.conc_lics, (document.LicenseConjunction,
        document.LicenseDisjunction)):
        write_value('PackageLicenseConcluded', u'({0})'.format(package.conc_lics), out)
    else:
        write_value('PackageLicenseConcluded', package.conc_lics, out)

    # Write sorted list of licenses.
    for lics in sorted(package.licenses_from_files):
        write_value('PackageLicenseInfoFromFiles', lics, out)

    if package.has_optional_field('license_comment'):
        write_text_value('PackageLicenseComments', package.license_comment, out)

    # cr_text is either free form text or NONE or NOASSERTION.
    if isinstance(package.cr_text, six.string_types):
        write_text_value('PackageCopyrightText', package.cr_text, out)
    else:
        write_value('PackageCopyrightText', package.cr_text, out)

    if package.has_optional_field('homepage'):
        write_value('PackageHomePage', package.homepage, out)

    # Write sorted files.
    for spdx_file in sorted(package.files):
        write_separators(out)
        write_file(spdx_file, out)

Response: Write a single package to out.


Instruction:
Here you have a function in Python 3, explain what it does
def write_extracted_licenses(lics, out):
    write_value('LicenseID', lics.identifier, out)

    if lics.full_name is not None:
        write_value('LicenseName', lics.full_name, out)

    if lics.comment is not None:
        write_text_value('LicenseComment', lics.comment, out)

    for xref in sorted(lics.cross_ref):
        write_value('LicenseCrossReference', xref, out)

    write_text_value('ExtractedText', lics.text, out)

Response: Write extracted licenses to out.


Instruction:
Can you implement a function in Python 3 that
writes an SPDX document to out.

Response:
def write_document(document, out, validate=True):
    """
    Write an SPDX tag value document.
    - document - spdx.document instance.
    - out - file like object that will be written to.
    Optionally `validate` the document before writing and raise
    InvalidDocumentError if document.validate returns False.
    """
    messages = []
    messages = document.validate(messages)
    if validate and messages:
        raise InvalidDocumentError(messages)

    # Write out document information
    out.write('# Document Information\n\n')
    write_value('SPDXVersion', str(document.version), out)
    write_value('DataLicense', document.data_license.identifier, out)
    write_value('DocumentName', document.name, out)
    write_value('SPDXID', 'SPDXRef-DOCUMENT', out)
    write_value('DocumentNamespace', document.namespace, out)
    if document.has_comment:
        write_text_value('DocumentComment', document.comment, out)
    for doc_ref in document.ext_document_references:
        doc_ref_str = ' '.join([doc_ref.external_document_id,
                                doc_ref.spdx_document_uri,
                                doc_ref.check_sum.identifier + ':' +
                                doc_ref.check_sum.value])
        write_value('ExternalDocumentRef', doc_ref_str, out)
    write_separators(out)
    # Write out creation info
    write_creation_info(document.creation_info, out)
    write_separators(out)

    # Writesorted reviews
    for review in sorted(document.reviews):
        write_review(review, out)
        write_separators(out)

    #Write sorted annotations
    for annotation in sorted(document.annotations):
        write_annotation(annotation, out)
        write_separators(out)

    # Write out package info
    write_package(document.package, out)
    write_separators(out)

    out.write('# Extracted Licenses\n\n')
    for lic in sorted(document.extracted_licenses):
        write_extracted_licenses(lic, out)
        write_separators(out)


Instruction:
Given the following Python 3 function, write the documentation
def checksum_from_sha1(value):
    # More constrained regex at lexer level
    CHECKSUM_RE = re.compile('SHA1:\s*([\S]+)', re.UNICODE)
    match = CHECKSUM_RE.match(value)
    if match:
        return checksum.Algorithm(identifier='SHA1', value=match.group(1))
    else:
        return None

Response:
Returns an spdx. checksum. Algorithm instance representing the SHA1
    checksum or None if the value does not match the SHA1 checksum.


Instruction:
How would you explain what the following Python 3 function does
def str_from_text(text):
    REGEX = re.compile('<text>((.|\n)+)</text>', re.UNICODE)
    match = REGEX.match(text)
    if match:
        return match.group(1)
    else:
        return None

Response: Return content of a free form text block as a string.


Instruction:
Can you generate the documentation for the following Python 3 function
def set_doc_version(self, doc, value):
        if not self.doc_version_set:
            self.doc_version_set = True
            m = self.VERS_STR_REGEX.match(value)
            if m is None:
                raise SPDXValueError('Document::Version')
            else:
                doc.version = version.Version(major=int(m.group(1)),
                                              minor=int(m.group(2)))
                return True
        else:
            raise CardinalityError('Document::Version')

Response: Set the document version.


Instruction:
Can you tell what is the following Python 3 function doing
def set_doc_data_lics(self, doc, lics):
        if not self.doc_data_lics_set:
            self.doc_data_lics_set = True
            if validations.validate_data_lics(lics):
                doc.data_license = document.License.from_identifier(lics)
                return True
            else:
                raise SPDXValueError('Document::DataLicense')
        else:
            raise CardinalityError('Document::DataLicense')

Response:
Sets the document data license. Raises value error if malformed value CardinalityError
            Raises value error if malformed value CardinalityError
            raises CardinalityError


Instruction:
Can you create a Python 3 function that
sets the document name.

Response:
def set_doc_name(self, doc, name):
        """Sets the document name.
        Raises CardinalityError if already defined.
        """
        if not self.doc_name_set:
            doc.name = name
            self.doc_name_set = True
            return True
        else:
            raise CardinalityError('Document::Name')


Instruction:
Make a summary of the following Python 3 code
def set_doc_spdx_id(self, doc, doc_spdx_id_line):
        if not self.doc_spdx_id_set:
            if doc_spdx_id_line == 'SPDXRef-DOCUMENT':
                doc.spdx_id = doc_spdx_id_line
                self.doc_spdx_id_set = True
                return True
            else:
                raise SPDXValueError('Document::SPDXID')
        else:
            raise CardinalityError('Document::SPDXID')

Response: Sets the document SPDX Identifier. Raises value error if malformed value CardinalityError if CardinalityError is raised.


Instruction:
Can you generate the documentation for the following Python 3 function
def reset_document(self):
        # FIXME: this state does not make sense
        self.doc_version_set = False
        self.doc_comment_set = False
        self.doc_namespace_set = False
        self.doc_data_lics_set = False
        self.doc_name_set = False
        self.doc_spdx_id_set = False

Response: Resets the state to allow building new documents


Instruction:
Create a Python 3 function to
set the spdx_document_uri attribute of the ExternalDocumentRef object.

Response:
def set_spdx_doc_uri(self, doc, spdx_doc_uri):
        """
        Sets the `spdx_document_uri` attribute of the `ExternalDocumentRef`
        object.
        """
        if validations.validate_doc_namespace(spdx_doc_uri):
            doc.ext_document_references[-1].spdx_document_uri = spdx_doc_uri
        else:
            raise SPDXValueError('Document::ExternalDocumentRef')


Instruction:
Implement a function in Python 3 to
build a tool object out of a string representation.

Response:
def build_tool(self, doc, entity):
        """Builds a tool object out of a string representation.
        Returns built tool. Raises SPDXValueError if failed to extract
        tool name or name is malformed
        """
        match = self.tool_re.match(entity)
        if match and validations.validate_tool_name(match.group(self.TOOL_NAME_GROUP)):
            name = match.group(self.TOOL_NAME_GROUP)
            return creationinfo.Tool(name)
        else:
            raise SPDXValueError('Failed to extract tool name')


Instruction:
Make a summary of the following Python 3 code
def build_org(self, doc, entity):
        match = self.org_re.match(entity)
        if match and validations.validate_org_name(match.group(self.ORG_NAME_GROUP)):
            name = match.group(self.ORG_NAME_GROUP).strip()
            email = match.group(self.ORG_EMAIL_GROUP)
            if (email is not None) and (len(email) != 0):
                return creationinfo.Organization(name=name, email=email.strip())
            else:
                return creationinfo.Organization(name=name, email=None)
        else:
            raise SPDXValueError('Failed to extract Organization name')

Response: Builds an organization object of a string representation.


Instruction:
How would you explain what the following Python 3 function does
def build_person(self, doc, entity):
        match = self.person_re.match(entity)
        if match and validations.validate_person_name(match.group(self.PERSON_NAME_GROUP)):
            name = match.group(self.PERSON_NAME_GROUP).strip()
            email = match.group(self.PERSON_EMAIL_GROUP)
            if (email is not None) and (len(email) != 0):
                return creationinfo.Person(name=name, email=email.strip())
            else:
                return creationinfo.Person(name=name, email=None)
        else:
            raise SPDXValueError('Failed to extract person name')

Response: Builds an organization object of a string representation.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_creator(self, doc, creator):
        if validations.validate_creator(creator):
            doc.creation_info.add_creator(creator)
            return True
        else:
            raise SPDXValueError('CreationInfo::Creator')

Response: Adds a creator to the document s creation info. Returns True if creator is valid.


Instruction:
How would you implement a function in Python 3 that
sets the created date of the resource.

Response:
def set_created_date(self, doc, created):
        """Sets created date, Raises CardinalityError if
        created date already set.
        Raises SPDXValueError if created is not a date.
        """
        if not self.created_date_set:
            self.created_date_set = True
            date = utils.datetime_from_iso_format(created)
            if date is not None:
                doc.creation_info.created = date
                return True
            else:
                raise SPDXValueError('CreationInfo::Date')
        else:
            raise CardinalityError('CreationInfo::Created')


Instruction:
Write a Python 3 function for
setting creation comment for the current object.

Response:
def set_creation_comment(self, doc, comment):
        """Sets creation comment, Raises CardinalityError if
        comment already set.
        Raises SPDXValueError if not free form text.
        """
        if not self.creation_comment_set:
            self.creation_comment_set = True
            if validations.validate_creation_comment(comment):
                doc.creation_info.comment = str_from_text(comment)
                return True
            else:
                raise SPDXValueError('CreationInfo::Comment')
        else:
            raise CardinalityError('CreationInfo::Comment')


Instruction:
Can you implement a function in Python 3 that
sets the license list version of the user. Raises CardinalityError if the attribute license_list_ver is already set.

Response:
def set_lics_list_ver(self, doc, value):
        """Sets the license list version, Raises CardinalityError if
        already set, SPDXValueError if incorrect value.
        """
        if not self.lics_list_ver_set:
            self.lics_list_ver_set = True
            vers = version.Version.from_str(value)
            if vers is not None:
                doc.creation_info.license_list_version = vers
                return True
            else:
                raise SPDXValueError('CreationInfo::LicenseListVersion')
        else:
            raise CardinalityError('CreationInfo::LicenseListVersion')


Instruction:
How would you implement a function in Python 3 that
resets the builder state to allow building new creation info.

Response:
def reset_creation_info(self):
        """
        Resets builder state to allow building new creation info."""
        # FIXME: this state does not make sense
        self.created_date_set = False
        self.creation_comment_set = False
        self.lics_list_ver_set = False


Instruction:
Given the following Python 3 function, write the documentation
def add_reviewer(self, doc, reviewer):
        # Each reviewer marks the start of a new review object.
        # FIXME: this state does not make sense
        self.reset_reviews()
        if validations.validate_reviewer(reviewer):
            doc.add_review(review.Review(reviewer=reviewer))
            return True
        else:
            raise SPDXValueError('Review::Reviewer')

Response: Adds a reviewer to the SPDX Document.


Instruction:
Explain what the following Python 3 code does
def add_review_comment(self, doc, comment):
        if len(doc.reviews) != 0:
            if not self.review_comment_set:
                self.review_comment_set = True
                if validations.validate_review_comment(comment):
                    doc.reviews[-1].comment = str_from_text(comment)
                    return True
                else:
                    raise SPDXValueError('ReviewComment::Comment')
            else:
                raise CardinalityError('ReviewComment')
        else:
            raise OrderError('ReviewComment')

Response: Adds a review comment to the article. Raises CardinalityError if no reviewer defined before. Raises SPDXValueError if comment is not free form text. Raises OrderError if no reviewer defined before. Raises SPDXValueError if comment is not free form text. Returns True if the comment was valid.


Instruction:
Can you write a function in Python 3 where it
resets the builder s state to allow building new annotations.

Response:
def reset_annotations(self):
        """Resets the builder's state to allow building new annotations."""
        # FIXME: this state does not make sense
        self.annotation_date_set = False
        self.annotation_comment_set = False
        self.annotation_type_set = False
        self.annotation_spdx_id_set = False


Instruction:
Here you have a function in Python 3, explain what it does
def add_annotator(self, doc, annotator):
        # Each annotator marks the start of a new annotation object.
        # FIXME: this state does not make sense
        self.reset_annotations()
        if validations.validate_annotator(annotator):
            doc.add_annotation(annotation.Annotation(annotator=annotator))
            return True
        else:
            raise SPDXValueError('Annotation::Annotator')

Response: Adds an annotator to the SPDX Document.


Instruction:
Explain what the following Python 3 code does
def add_annotation_date(self, doc, annotation_date):
        if len(doc.annotations) != 0:
            if not self.annotation_date_set:
                self.annotation_date_set = True
                date = utils.datetime_from_iso_format(annotation_date)
                if date is not None:
                    doc.annotations[-1].annotation_date = date
                    return True
                else:
                    raise SPDXValueError('Annotation::AnnotationDate')
            else:
                raise CardinalityError('Annotation::AnnotationDate')
        else:
            raise OrderError('Annotation::AnnotationDate')

Response: Adds an annotation date to the document. Raises CardinalityError if no annotator defined before. Raises SPDXValueError if invalid value. Raises OrderError if no annotator defined before. Raises SPDXValueError if invalid value. Returns True if the document has annotations and an annotation date is not set.


Instruction:
Create a Python 3 function for
adding an annotation comment to the document. Raises CardinalityError if no annotator defined before. Raises SPDXValueError if comment is not free form text. Raises OrderError if no annotator defined before. Raises SPDXValueError if comment is not free form text. Returns True if the comment was valid.

Response:
def add_annotation_comment(self, doc, comment):
        """Sets the annotation comment. Raises CardinalityError if
        already set. OrderError if no annotator defined before.
        Raises SPDXValueError if comment is not free form text.
        """
        if len(doc.annotations) != 0:
            if not self.annotation_comment_set:
                self.annotation_comment_set = True
                if validations.validate_annotation_comment(comment):
                    doc.annotations[-1].comment = str_from_text(comment)
                    return True
                else:
                    raise SPDXValueError('AnnotationComment::Comment')
            else:
                raise CardinalityError('AnnotationComment::Comment')
        else:
            raise OrderError('AnnotationComment::Comment')


Instruction:
Explain what the following Python 3 code does
def add_annotation_type(self, doc, annotation_type):
        if len(doc.annotations) != 0:
            if not self.annotation_type_set:
                self.annotation_type_set = True
                if validations.validate_annotation_type(annotation_type):
                    doc.annotations[-1].annotation_type = annotation_type
                    return True
                else:
                    raise SPDXValueError('Annotation::AnnotationType')
            else:
                raise CardinalityError('Annotation::AnnotationType')
        else:
            raise OrderError('Annotation::AnnotationType')

Response: Adds an annotation type to the annotation type list. Raises CardinalityError if no such annotation type is defined before. Raises SPDXValueError if invalid value.


Instruction:
Given the following Python 3 function, write the documentation
def reset_package(self):
        # FIXME: this state does not make sense
        self.package_set = False
        self.package_vers_set = False
        self.package_file_name_set = False
        self.package_supplier_set = False
        self.package_originator_set = False
        self.package_down_location_set = False
        self.package_home_set = False
        self.package_verif_set = False
        self.package_chk_sum_set = False
        self.package_source_info_set = False
        self.package_conc_lics_set = False
        self.package_license_declared_set = False
        self.package_license_comment_set = False
        self.package_cr_text_set = False
        self.package_summary_set = False
        self.package_desc_set = False

Response: Resets the state of the internal state to build new packages.


Instruction:
Can you tell what is the following Python 3 function doing
def create_package(self, doc, name):
        if not self.package_set:
            self.package_set = True
            doc.package = package.Package(name=name)
            return True
        else:
            raise CardinalityError('Package::Name')

Response: Creates a package for the SPDX Document.


Instruction:
How would you code a function in Python 3 to
set the version of the package in the given doc.

Response:
def set_pkg_vers(self, doc, version):
        """Sets package version, if not already set.
        version - Any string.
        Raises CardinalityError if already has a version.
        Raises OrderError if no package previously defined.
        """
        self.assert_package_exists()
        if not self.package_vers_set:
            self.package_vers_set = True
            doc.package.version = version
            return True
        else:
            raise CardinalityError('Package::Version')


Instruction:
Can you generate the documentation for the following Python 3 function
def set_pkg_file_name(self, doc, name):
        self.assert_package_exists()
        if not self.package_file_name_set:
            self.package_file_name_set = True
            doc.package.file_name = name
            return True
        else:
            raise CardinalityError('Package::FileName')

Response: Sets the package file name.


Instruction:
Write a Python 3 function that can
set the package supplier if not already set.

Response:
def set_pkg_supplier(self, doc, entity):
        """Sets the package supplier, if not already set.
        entity - Organization, Person or NoAssert.
        Raises CardinalityError if already has a supplier.
        Raises OrderError if no package previously defined.
        """
        self.assert_package_exists()
        if not self.package_supplier_set:
            self.package_supplier_set = True
            if validations.validate_pkg_supplier(entity):
                doc.package.supplier = entity
                return True
            else:
                raise SPDXValueError('Package::Supplier')
        else:
            raise CardinalityError('Package::Supplier')


Instruction:
Can you implement a function in Python 3 that
sets the package originator if not already set.

Response:
def set_pkg_originator(self, doc, entity):
        """Sets the package originator, if not already set.
        entity - Organization, Person or NoAssert.
        Raises CardinalityError if already has an originator.
        Raises OrderError if no package previously defined.
        """
        self.assert_package_exists()
        if not self.package_originator_set:
            self.package_originator_set = True
            if validations.validate_pkg_originator(entity):
                doc.package.originator = entity
                return True
            else:
                raise SPDXValueError('Package::Originator')
        else:
            raise CardinalityError('Package::Originator')


Instruction:
Write a Python 3 function that can
set the package download location.

Response:
def set_pkg_down_location(self, doc, location):
        """Sets the package download location, if not already set.
        location - A string
        Raises CardinalityError if already defined.
        Raises OrderError if no package previously defined.
        """
        self.assert_package_exists()
        if not self.package_down_location_set:
            self.package_down_location_set = True
            doc.package.download_location = location
            return True
        else:
            raise CardinalityError('Package::DownloadLocation')


Instruction:
Can you write a function in Python 3 where it
sets the package homepage location if not already set.

Response:
def set_pkg_home(self, doc, location):
        """Sets the package homepage location if not already set.
        location - A string or None or NoAssert.
        Raises CardinalityError if already defined.
        Raises OrderError if no package previously defined.
        Raises SPDXValueError if location has incorrect value.
        """
        self.assert_package_exists()
        if not self.package_home_set:
            self.package_home_set = True
            if validations.validate_pkg_homepage(location):
                doc.package.homepage = location
                return True
            else:
                raise SPDXValueError('Package::HomePage')
        else:
            raise CardinalityError('Package::HomePage')


Instruction:
Write a Python 3 script for
setting the verification code for the given package.

Response:
def set_pkg_verif_code(self, doc, code):
        """Sets the package verification code, if not already set.
        code - A string.
        Raises CardinalityError if already defined.
        Raises OrderError if no package previously defined.
        Raises Value error if doesn't match verifcode form
        """
        self.assert_package_exists()
        if not self.package_verif_set:
            self.package_verif_set = True
            match = self.VERIF_CODE_REGEX.match(code)
            if match:
                doc.package.verif_code = match.group(self.VERIF_CODE_CODE_GRP)
                if match.group(self.VERIF_CODE_EXC_FILES_GRP) is not None:
                    doc.package.verif_exc_files = match.group(self.VERIF_CODE_EXC_FILES_GRP).split(',')
                return True
            else:
                raise SPDXValueError('Package::VerificationCode')
        else:
            raise CardinalityError('Package::VerificationCode')


Instruction:
Given the following Python 3 function, write the documentation
def set_pkg_chk_sum(self, doc, chk_sum):
        self.assert_package_exists()
        if not self.package_chk_sum_set:
            self.package_chk_sum_set = True
            doc.package.check_sum = checksum_from_sha1(chk_sum)
            return True
        else:
            raise CardinalityError('Package::CheckSum')

Response: Sets the package check sum if not already set.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_pkg_source_info(self, doc, text):
        self.assert_package_exists()
        if not self.package_source_info_set:
            self.package_source_info_set = True
            if validations.validate_pkg_src_info(text):
                doc.package.source_info = str_from_text(text)
                return True
            else:
                raise SPDXValueError('Pacckage::SourceInfo')
        else:
            raise CardinalityError('Package::SourceInfo')

Response: Sets the package s source information if not already set.


Instruction:
Can you implement a function in Python 3 that
sets the package s concluded licenses.

Response:
def set_pkg_licenses_concluded(self, doc, licenses):
        """Sets the package's concluded licenses.
        licenses - License info.
        Raises CardinalityError if already defined.
        Raises OrderError if no package previously defined.
        Raises SPDXValueError if data malformed.
        """
        self.assert_package_exists()
        if not self.package_conc_lics_set:
            self.package_conc_lics_set = True
            if validations.validate_lics_conc(licenses):
                doc.package.conc_lics = licenses
                return True
            else:
                raise SPDXValueError('Package::ConcludedLicenses')
        else:
            raise CardinalityError('Package::ConcludedLicenses')


Instruction:
Here you have a function in Python 3, explain what it does
def set_pkg_license_from_file(self, doc, lic):
        self.assert_package_exists()
        if validations.validate_lics_from_file(lic):
            doc.package.licenses_from_files.append(lic)
            return True
        else:
            raise SPDXValueError('Package::LicensesFromFile')

Response: Adds a license from a file to the package.


Instruction:
Can you write a function in Python 3 where it
sets the package s declared license.

Response:
def set_pkg_license_declared(self, doc, lic):
        """Sets the package's declared license.
        Raises SPDXValueError if data malformed.
        Raises OrderError if no package previously defined.
        Raises CardinalityError if already set.
        """
        self.assert_package_exists()
        if not self.package_license_declared_set:
            self.package_license_declared_set = True
            if validations.validate_lics_conc(lic):
                doc.package.license_declared = lic
                return True
            else:
                raise SPDXValueError('Package::LicenseDeclared')
        else:
            raise CardinalityError('Package::LicenseDeclared')


Instruction:
Here you have a function in Python 3, explain what it does
def set_pkg_license_comment(self, doc, text):
        self.assert_package_exists()
        if not self.package_license_comment_set:
            self.package_license_comment_set = True
            if validations.validate_pkg_lics_comment(text):
                doc.package.license_comment = str_from_text(text)
                return True
            else:
                raise SPDXValueError('Package::LicenseComment')
        else:
            raise CardinalityError('Package::LicenseComment')

Response: Sets the package s license comment.


Instruction:
Explain what the following Python 3 code does
def set_pkg_cr_text(self, doc, text):
        self.assert_package_exists()
        if not self.package_cr_text_set:
            self.package_cr_text_set = True
            if validations.validate_pkg_cr_text(text):
                if isinstance(text, string_types):
                    doc.package.cr_text = str_from_text(text)
                else:
                    doc.package.cr_text = text  # None or NoAssert
            else:
                raise SPDXValueError('Package::CopyrightText')
        else:
            raise CardinalityError('Package::CopyrightText')

Response: Sets the copyright text of the package.


Instruction:
How would you code a function in Python 3 to
set the package summary.

Response:
def set_pkg_summary(self, doc, text):
        """Set's the package summary.
        Raises SPDXValueError if text is not free form text.
        Raises CardinalityError if summary already set.
        Raises OrderError if no package previously defined.
        """
        self.assert_package_exists()
        if not self.package_summary_set:
            self.package_summary_set = True
            if validations.validate_pkg_summary(text):
                doc.package.summary = str_from_text(text)
            else:
                raise SPDXValueError('Package::Summary')
        else:
            raise CardinalityError('Package::Summary')


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_pkg_desc(self, doc, text):
        self.assert_package_exists()
        if not self.package_desc_set:
            self.package_desc_set = True
            if validations.validate_pkg_desc(text):
                doc.package.description = str_from_text(text)
            else:
                raise SPDXValueError('Package::Description')
        else:
            raise CardinalityError('Package::Description')

Response: Set the package s description.


Instruction:
Write a Python 3 function that can
set the name of the file instance in the specified doc.

Response:
def set_file_name(self, doc, name):
        """Raises OrderError if no package defined.
        """
        if self.has_package(doc):
            doc.package.files.append(file.File(name))
            # A file name marks the start of a new file instance.
            # The builder must be reset
            # FIXME: this state does not make sense
            self.reset_file_stat()
            return True
        else:
            raise OrderError('File::Name')


Instruction:
Can you write a function in Python 3 where it
sets the file SPDX Identifier.

Response:
def set_file_spdx_id(self, doc, spdx_id):
        """
        Sets the file SPDX Identifier.
        Raises OrderError if no package or no file defined.
        Raises SPDXValueError if malformed value.
        Raises CardinalityError if more than one spdx_id set.
        """
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_spdx_id_set:
                self.file_spdx_id_set = True
                if validations.validate_file_spdx_id(spdx_id):
                    self.file(doc).spdx_id = spdx_id
                    return True
                else:
                    raise SPDXValueError('File::SPDXID')
            else:
                raise CardinalityError('File::SPDXID')
        else:
            raise OrderError('File::SPDXID')


Instruction:
Make a summary of the following Python 3 code
def set_file_comment(self, doc, text):
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_comment_set:
                self.file_comment_set = True
                if validations.validate_file_comment(text):
                    self.file(doc).comment = str_from_text(text)
                    return True
                else:
                    raise SPDXValueError('File::Comment')
            else:
                raise CardinalityError('File::Comment')
        else:
            raise OrderError('File::Comment')

Response: Sets the comment for a file in the archive.


Instruction:
Write a Python 3 function for
setting the type of the file in the archive.

Response:
def set_file_type(self, doc, type_value):
        """
        Raises OrderError if no package or file defined.
        Raises CardinalityError if more than one type set.
        Raises SPDXValueError if type is unknown.
        """
        type_dict = {
            'SOURCE': file.FileType.SOURCE,
            'BINARY': file.FileType.BINARY,
            'ARCHIVE': file.FileType.ARCHIVE,
            'OTHER': file.FileType.OTHER
        }
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_type_set:
                self.file_type_set = True
                if type_value in type_dict.keys():
                    self.file(doc).type = type_dict[type_value]
                    return True
                else:
                    raise SPDXValueError('File::Type')
            else:
                raise CardinalityError('File::Type')
        else:
            raise OrderError('File::Type')


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_file_chksum(self, doc, chksum):
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_chksum_set:
                self.file_chksum_set = True
                self.file(doc).chk_sum = checksum_from_sha1(chksum)
                return True
            else:
                raise CardinalityError('File::CheckSum')
        else:
            raise OrderError('File::CheckSum')

Response: Sets the chksum of a file in the database.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_concluded_license(self, doc, lic):
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_conc_lics_set:
                self.file_conc_lics_set = True
                if validations.validate_lics_conc(lic):
                    self.file(doc).conc_lics = lic
                    return True
                else:
                    raise SPDXValueError('File::ConcludedLicense')
            else:
                raise CardinalityError('File::ConcludedLicense')
        else:
            raise OrderError('File::ConcludedLicense')

Response: Sets the concluded license for the file.


Instruction:
Given the following Python 3 function, write the documentation
def set_file_license_in_file(self, doc, lic):
        if self.has_package(doc) and self.has_file(doc):
            if validations.validate_file_lics_in_file(lic):
                self.file(doc).add_lics(lic)
                return True
            else:
                raise SPDXValueError('File::LicenseInFile')
        else:
            raise OrderError('File::LicenseInFile')

Response: Sets the license in file for the specified document.


Instruction:
Write a Python 3 script to
set the license comment for the file.

Response:
def set_file_license_comment(self, doc, text):
        """
        Raises OrderError if no package or file defined.
        Raises SPDXValueError if text is not free form text.
        Raises CardinalityError if more than one per file.
        """
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_license_comment_set:
                self.file_license_comment_set = True
                if validations.validate_file_lics_comment(text):
                    self.file(doc).license_comment = str_from_text(text)
                else:
                    raise SPDXValueError('File::LicenseComment')
            else:
                raise CardinalityError('File::LicenseComment')
        else:
            raise OrderError('File::LicenseComment')


Instruction:
How would you code a function in Python 3 to
set copyright text for a file in the order.

Response:
def set_file_copyright(self, doc, text):
        """Raises OrderError if no package or file defined.
        Raises SPDXValueError if not free form text or NONE or NO_ASSERT.
        Raises CardinalityError if more than one.
        """
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_copytext_set:
                self.file_copytext_set = True
                if validations.validate_file_cpyright(text):
                    if isinstance(text, string_types):
                        self.file(doc).copyright = str_from_text(text)
                    else:
                        self.file(doc).copyright = text  # None or NoAssert
                    return True
                else:
                    raise SPDXValueError('File::CopyRight')
            else:
                raise CardinalityError('File::CopyRight')
        else:
            raise OrderError('File::CopyRight')


Instruction:
How would you implement a function in Python 3 that
sets the notice for the file in the article.

Response:
def set_file_notice(self, doc, text):
        """Raises OrderError if no package or file defined.
        Raises SPDXValueError if not free form text.
        Raises CardinalityError if more than one.
        """
        if self.has_package(doc) and self.has_file(doc):
            if not self.file_notice_set:
                self.file_notice_set = True
                if validations.validate_file_notice(text):
                    self.file(doc).notice = str_from_text(text)
                else:
                    raise SPDXValueError('File::Notice')
            else:
                raise CardinalityError('File::Notice')
        else:
            raise OrderError('File::Notice')


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_file_contribution(self, doc, value):
        if self.has_package(doc) and self.has_file(doc):
            self.file(doc).add_contrib(value)
        else:
            raise OrderError('File::Contributor')

Response: Adds a contributor to the order.


Instruction:
Can you tell what is the following Python 3 function doing
def add_file_dep(self, doc, value):
        if self.has_package(doc) and self.has_file(doc):
            self.file(doc).add_depend(value)
        else:
            raise OrderError('File::Dependency')

Response: Adds a dependency to the file.


Instruction:
How would you implement a function in Python 3 that
sets a file name uri or home artificat. Raises OrderError if no package or file defined.

Response:
def set_file_atrificat_of_project(self, doc, symbol, value):
        """Sets a file name, uri or home artificat.
        Raises OrderError if no package or file defined.
        """
        if self.has_package(doc) and self.has_file(doc):
            self.file(doc).add_artifact(symbol, value)
        else:
            raise OrderError('File::Artificat')


Instruction:
Can you implement a function in Python 3 that
resets the state of the file stat to the default state.

Response:
def reset_file_stat(self):
        """Resets the builder's state to enable building new files."""
        # FIXME: this state does not make sense
        self.file_spdx_id_set = False
        self.file_comment_set = False
        self.file_type_set = False
        self.file_chksum_set = False
        self.file_conc_lics_set = False
        self.file_license_comment_set = False
        self.file_notice_set = False
        self.file_copytext_set = False


Instruction:
Write a Python 3 script to
add a new extracted license to the document.

Response:
def set_lic_id(self, doc, lic_id):
        """Adds a new extracted license to the document.
        Raises SPDXValueError if data format is incorrect.
        """
        # FIXME: this state does not make sense
        self.reset_extr_lics()
        if validations.validate_extracted_lic_id(lic_id):
            doc.add_extr_lic(document.ExtractedLicense(lic_id))
            return True
        else:
            raise SPDXValueError('ExtractedLicense::id')


Instruction:
Make a summary of the following Python 3 code
def set_lic_text(self, doc, text):
        if self.has_extr_lic(doc):
            if not self.extr_text_set:
                self.extr_text_set = True
                if validations.validate_is_free_form_text(text):
                    self.extr_lic(doc).text = str_from_text(text)
                    return True
                else:
                    raise SPDXValueError('ExtractedLicense::text')
            else:
                raise CardinalityError('ExtractedLicense::text')
        else:
            raise OrderError('ExtractedLicense::text')

Response: Sets the extracted text of a license.


Instruction:
Can you create a Python 3 function that
sets the name of the license in the article.

Response:
def set_lic_name(self, doc, name):
        """Sets license name.
        Raises SPDXValueError if name is not str or utils.NoAssert
        Raises OrderError if no license id defined.
        """
        if self.has_extr_lic(doc):
            if not self.extr_lic_name_set:
                self.extr_lic_name_set = True
                if validations.validate_extr_lic_name(name):
                    self.extr_lic(doc).full_name = name
                    return True
                else:
                    raise SPDXValueError('ExtractedLicense::Name')
            else:
                raise CardinalityError('ExtractedLicense::Name')
        else:
            raise OrderError('ExtractedLicense::Name')


Instruction:
Explain what the following Python 3 code does
def set_lic_comment(self, doc, comment):
        if self.has_extr_lic(doc):
            if not self.extr_lic_comment_set:
                self.extr_lic_comment_set = True
                if validations.validate_is_free_form_text(comment):
                    self.extr_lic(doc).comment = str_from_text(comment)
                    return True
                else:
                    raise SPDXValueError('ExtractedLicense::comment')
            else:
                raise CardinalityError('ExtractedLicense::comment')
        else:
            raise OrderError('ExtractedLicense::comment')

Response: Sets the comment of a license in the article.


Instruction:
Can you create a Python 3 function that
adds a license cross reference.

Response:
def add_lic_xref(self, doc, ref):
        """Adds a license cross reference.
        Raises OrderError if no License ID defined.
        """
        if self.has_extr_lic(doc):
            self.extr_lic(doc).add_xref(ref)
            return True
        else:
            raise OrderError('ExtractedLicense::CrossRef')


Instruction:
Make a summary of the following Python 3 code
def reset(self):
        # FIXME: this state does not make sense
        self.reset_creation_info()
        self.reset_document()
        self.reset_package()
        self.reset_file_stat()
        self.reset_reviews()
        self.reset_annotations()
        self.reset_extr_lics()

Response: Resets the builder s state for building new documents.


Instruction:
Implement a Python 3 function for
returning an ISO - 8601 representation of a datetime object.

Response:
def datetime_iso_format(date):
    """
    Return an ISO-8601 representation of a datetime object.
    """
    return "{0:0>4}-{1:0>2}-{2:0>2}T{3:0>2}:{4:0>2}:{5:0>2}Z".format(
        date.year, date.month, date.day, date.hour,
        date.minute, date.second)


Instruction:
How would you implement a function in Python 3 that
returns a datetime object from an ISO 8601 representation.

Response:
def datetime_from_iso_format(string):
    """
    Return a datetime object from an iso 8601 representation.
    Return None if string is non conforming.
    """
    match = DATE_ISO_REGEX.match(string)
    if match:
        date = datetime.datetime(year=int(match.group(DATE_ISO_YEAR_GRP)),
                                 month=int(match.group(DATE_ISO_MONTH_GRP)),
                                 day=int(match.group(DATE_ISO_DAY_GRP)),
                                 hour=int(match.group(DATE_ISO_HOUR_GRP)),
                                 second=int(match.group(DATE_ISO_SEC_GRP)),
                                 minute=int(match.group(DATE_ISO_MIN_GRP)))
        return date
    else:
        return None


Instruction:
Make a summary of the following Python 3 code
def build(self, **kwargs):
        self.yacc = yacc.yacc(module=self, **kwargs)

Response: Build a YACC object.


Instruction:
Explain what the following Python 3 code does
def parse(self, data):
        try:
            return self.yacc.parse(data, lexer=self.lex)
        except:
            return None

Response: Parses a license list and returns a License or None.


Instruction:
Explain what the following Python 3 code does
def write_document(document, out, validate=True):

    if validate:
        messages = []
        messages = document.validate(messages)
        if messages:
            raise InvalidDocumentError(messages)

    writer = Writer(document, out)
    writer.write()

Response: Write a SPDX RDF document to out.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_checksum_node(self, chksum):
        chksum_node = BNode()
        type_triple = (chksum_node, RDF.type, self.spdx_namespace.Checksum)
        self.graph.add(type_triple)
        algorithm_triple = (chksum_node, self.spdx_namespace.algorithm, Literal(chksum.identifier))
        self.graph.add(algorithm_triple)
        value_triple = (chksum_node, self.spdx_namespace.checksumValue, Literal(chksum.value))
        self.graph.add(value_triple)
        return chksum_node

Response: Create a node representing the checksum of the current skeleton.


Instruction:
Can you implement a function in Python 3 that
converts a value to a proper spdx term or Literal.

Response:
def to_special_value(self, value):
        """
        Return proper spdx term or Literal
        """
        if isinstance(value, utils.NoAssert):
            return self.spdx_namespace.noassertion
        elif isinstance(value, utils.SPDXNone):
            return self.spdx_namespace.none
        else:
            return Literal(value)


Instruction:
Implement a Python 3 function for
traversing conjunctions and disjunctions like trees and return a set of all licenses in that tree.

Response:
def licenses_from_tree(self, tree):
        """
        Traverse conjunctions and disjunctions like trees and return a
        set of all licenses in it as nodes.
        """
        # FIXME: this is unordered!
        licenses = set()
        self.licenses_from_tree_helper(tree, licenses)
        return licenses


Instruction:
How would you code a function in Python 3 to
create a node representing a conjunction of licenses.

Response:
def create_conjunction_node(self, conjunction):
        """
        Return a node representing a conjunction of licenses.
        """
        node = BNode()
        type_triple = (node, RDF.type, self.spdx_namespace.ConjunctiveLicenseSet)
        self.graph.add(type_triple)
        licenses = self.licenses_from_tree(conjunction)
        for lic in licenses:
            member_triple = (node, self.spdx_namespace.member, lic)
            self.graph.add(member_triple)
        return node


Instruction:
Can you tell what is the following Python 3 function doing
def create_disjunction_node(self, disjunction):
        node = BNode()
        type_triple = (node, RDF.type, self.spdx_namespace.DisjunctiveLicenseSet)
        self.graph.add(type_triple)
        licenses = self.licenses_from_tree(disjunction)
        for lic in licenses:
            member_triple = (node, self.spdx_namespace.member, lic)
            self.graph.add(member_triple)
        return node

Response: Create a disjunction node representing a licenses set.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_license_helper(self, lic):
        if isinstance(lic, document.ExtractedLicense):
            return self.create_extracted_license(lic)
        if lic.identifier.rstrip('+') in config.LICENSE_MAP:
            return URIRef(lic.url)
        else:
            matches = [l for l in self.document.extracted_licenses if l.identifier == lic.identifier]
            if len(matches) != 0:
                return self.create_extracted_license(matches[0])
            else:
                raise InvalidDocumentError('Missing extracted license: {0}'.format(lic.identifier))

Response: Create a node from a single or multiple licenses.


Instruction:
Here you have a function in Python 3, explain what it does
def create_extracted_license(self, lic):
        licenses = list(self.graph.triples((None, self.spdx_namespace.licenseId, lic.identifier)))
        if len(licenses) != 0:
            return licenses[0][0]  # return subject in first triple
        else:
            license_node = BNode()
            type_triple = (license_node, RDF.type, self.spdx_namespace.ExtractedLicensingInfo)
            self.graph.add(type_triple)
            ident_triple = (license_node, self.spdx_namespace.licenseId, Literal(lic.identifier))
            self.graph.add(ident_triple)
            text_triple = (license_node, self.spdx_namespace.extractedText, Literal(lic.text))
            self.graph.add(text_triple)
            if lic.full_name is not None:
                name_triple = (license_node, self.spdx_namespace.licenseName, self.to_special_value(lic.full_name))
                self.graph.add(name_triple)
            for ref in lic.cross_ref:
                triple = (license_node, RDFS.seeAlso, URIRef(ref))
                self.graph.add(triple)
            if lic.comment is not None:
                comment_triple = (license_node, RDFS.comment, Literal(lic.comment))
                self.graph.add(comment_triple)
            return license_node

Response: Create the extracted license.


Instruction:
Can you implement a function in Python 3 that
creates a node representing a license.

Response:
def create_license_node(self, lic):
        """
        Return a node representing a license.
        Could be a single license (extracted or part of license list.) or
        a conjunction/disjunction of licenses.
        """
        if isinstance(lic, document.LicenseConjunction):
            return self.create_conjunction_node(lic)
        elif isinstance(lic, document.LicenseDisjunction):
            return self.create_disjunction_node(lic)
        else:
            return self.create_license_helper(lic)


Instruction:
Create a Python 3 function for
returning the term for the license or the special value if the license is special.

Response:
def license_or_special(self, lic):
        """
        Check for special values spdx:none and spdx:noassertion.
        Return the term for the special value or the result of passing
        license to create_license_node.
        """
        if isinstance(lic, utils.NoAssert):
            return self.spdx_namespace.noassertion
        elif isinstance(lic, utils.SPDXNone):
            return self.spdx_namespace.none
        else:
            return self.create_license_node(lic)


Instruction:
Create a Python 3 function for
creating a node for the file.

Response:
def create_file_node(self, doc_file):
        """
        Create a node for spdx.file.
        """
        file_node = URIRef('http://www.spdx.org/files#{id}'.format(
            id=str(doc_file.spdx_id)))
        type_triple = (file_node, RDF.type, self.spdx_namespace.File)
        self.graph.add(type_triple)

        name_triple = (file_node, self.spdx_namespace.fileName, Literal(doc_file.name))
        self.graph.add(name_triple)

        if doc_file.has_optional_field('comment'):
            comment_triple = (file_node, RDFS.comment, Literal(doc_file.comment))
            self.graph.add(comment_triple)

        if doc_file.has_optional_field('type'):
            ftype = self.spdx_namespace[self.FILE_TYPES[doc_file.type]]
            ftype_triple = (file_node, self.spdx_namespace.fileType, ftype)
            self.graph.add(ftype_triple)

        self.graph.add((file_node, self.spdx_namespace.checksum, self.create_checksum_node(doc_file.chk_sum)))

        conc_lic_node = self.license_or_special(doc_file.conc_lics)
        conc_lic_triple = (file_node, self.spdx_namespace.licenseConcluded, conc_lic_node)
        self.graph.add(conc_lic_triple)

        license_info_nodes = map(self.license_or_special, doc_file.licenses_in_file)
        for lic in license_info_nodes:
            triple = (file_node, self.spdx_namespace.licenseInfoInFile, lic)
            self.graph.add(triple)

        if doc_file.has_optional_field('license_comment'):
            comment_triple = (file_node, self.spdx_namespace.licenseComments, Literal(doc_file.license_comment))
            self.graph.add(comment_triple)

        cr_text_node = self.to_special_value(doc_file.copyright)
        cr_text_triple = (file_node, self.spdx_namespace.copyrightText, cr_text_node)
        self.graph.add(cr_text_triple)

        if doc_file.has_optional_field('notice'):
            notice_triple = (file_node, self.spdx_namespace.noticeText, doc_file.notice)
            self.graph.add(notice_triple)

        contrib_nodes = map(lambda c: Literal(c), doc_file.contributors)
        contrib_triples = [(file_node, self.spdx_namespace.fileContributor, node) for node in contrib_nodes]
        for triple in contrib_triples:
            self.graph.add(triple)

        return file_node


Instruction:
Here you have a function in Python 3, explain what it does
def add_file_dependencies_helper(self, doc_file):
        subj_triples = list(self.graph.triples((None, self.spdx_namespace.fileName, Literal(doc_file.name))))
        if len(subj_triples) != 1:
            raise InvalidDocumentError('Could not find dependency subject {0}'.format(doc_file.name))
        subject_node = subj_triples[0][0]
        for dependency in doc_file.dependencies:
            dep_triples = list(self.graph.triples((None, self.spdx_namespace.fileName, Literal(dependency))))
            if len(dep_triples) == 1:
                dep_node = dep_triples[0][0]
                dep_triple = (subject_node, self.spdx_namespace.fileDependency, dep_node)
                self.graph.add(dep_triple)
            else:
                print('Warning could not resolve file dependency {0} -> {1}'.format(doc_file.name, dependency))

Response: Add all the file dependencies for a single file.


Instruction:
Can you implement a function in Python 3 that
creates a review node.

Response:
def create_review_node(self, review):
        """
        Return a review node.
        """
        review_node = BNode()
        type_triple = (review_node, RDF.type, self.spdx_namespace.Review)
        self.graph.add(type_triple)

        reviewer_node = Literal(review.reviewer.to_value())
        self.graph.add((review_node, self.spdx_namespace.reviewer, reviewer_node))
        reviewed_date_node = Literal(review.review_date_iso_format)
        reviewed_triple = (review_node, self.spdx_namespace.reviewDate, reviewed_date_node)
        self.graph.add(reviewed_triple)
        if review.has_comment:
            comment_node = Literal(review.comment)
            comment_triple = (review_node, RDFS.comment, comment_node)
            self.graph.add(comment_triple)

        return review_node


Instruction:
Create a Python 3 function for
creating an annotation node.

Response:
def create_annotation_node(self, annotation):
        """
        Return an annotation node.
        """
        annotation_node = URIRef(str(annotation.spdx_id))
        type_triple = (annotation_node, RDF.type, self.spdx_namespace.Annotation)
        self.graph.add(type_triple)

        annotator_node = Literal(annotation.annotator.to_value())
        self.graph.add((annotation_node, self.spdx_namespace.annotator, annotator_node))
        annotation_date_node = Literal(annotation.annotation_date_iso_format)
        annotation_triple = (annotation_node, self.spdx_namespace.annotationDate, annotation_date_node)
        self.graph.add(annotation_triple)
        if annotation.has_comment:
            comment_node = Literal(annotation.comment)
            comment_triple = (annotation_node, RDFS.comment, comment_node)
            self.graph.add(comment_triple)
        annotation_type_node = Literal(annotation.annotation_type)
        annotation_type_triple = (annotation_node, self.spdx_namespace.annotationType, annotation_type_node)
        self.graph.add(annotation_type_triple)

        return annotation_node


Instruction:
Can you generate a brief explanation for the following Python 3 code
def creators(self):
        return map(lambda c: Literal(c.to_value()), self.document.creation_info.creators)

Response: Return a list of creator nodes.


Instruction:
Implement a Python 3 function for
adding and return a creation info node to the graph

Response:
def create_creation_info(self):
        """
        Add and return a creation info node to graph
        """
        ci_node = BNode()
        # Type property
        type_triple = (ci_node, RDF.type, self.spdx_namespace.CreationInfo)
        self.graph.add(type_triple)

        created_date = Literal(self.document.creation_info.created_iso_format)
        created_triple = (ci_node, self.spdx_namespace.created, created_date)
        self.graph.add(created_triple)

        creators = self.creators()
        for creator in creators:
            self.graph.add((ci_node, self.spdx_namespace.creator, creator))

        if self.document.creation_info.has_comment:
            comment_node = Literal(self.document.creation_info.comment)
            comment_triple = (ci_node, RDFS.comment, comment_node)
            self.graph.add(comment_triple)

        return ci_node


Instruction:
Given the following Python 3 function, write the documentation
def create_external_document_ref_node(self, ext_document_references):
        ext_doc_ref_node = BNode()
        type_triple = (ext_doc_ref_node, RDF.type, self.spdx_namespace.ExternalDocumentRef)
        self.graph.add(type_triple)

        ext_doc_id = Literal(
            ext_document_references.external_document_id)
        ext_doc_id_triple = (
            ext_doc_ref_node, self.spdx_namespace.externalDocumentId, ext_doc_id)
        self.graph.add(ext_doc_id_triple)

        doc_uri = Literal(
            ext_document_references.spdx_document_uri)
        doc_uri_triple = (
            ext_doc_ref_node, self.spdx_namespace.spdxDocument, doc_uri)
        self.graph.add(doc_uri_triple)

        checksum_node = self.create_checksum_node(
            ext_document_references.check_sum)
        self.graph.add(
            (ext_doc_ref_node, self.spdx_namespace.checksum, checksum_node))

        return ext_doc_ref_node

Response: Add and return a creation info node to the graph


Instruction:
Create a Python 3 function to
return a node representing the verification code of a package.

Response:
def package_verif_node(self, package):
        """
        Return a node representing package verification code.
        """
        verif_node = BNode()
        type_triple = (verif_node, RDF.type, self.spdx_namespace.PackageVerificationCode)
        self.graph.add(type_triple)
        value_triple = (verif_node, self.spdx_namespace.packageVerificationCodeValue, Literal(package.verif_code))
        self.graph.add(value_triple)
        excl_file_nodes = map(
            lambda excl: Literal(excl), package.verif_exc_files)
        excl_predicate = self.spdx_namespace.packageVerificationCodeExcludedFile
        excl_file_triples = [(verif_node, excl_predicate, xcl_file) for xcl_file in excl_file_nodes]
        for trp in excl_file_triples:
            self.graph.add(trp)
        return verif_node


Instruction:
Can you generate the documentation for the following Python 3 function
def handle_package_literal_optional(self, package, package_node, predicate, field):
        if package.has_optional_field(field):
            value = getattr(package, field, None)
            value_node = self.to_special_value(value)
            triple = (package_node, predicate, value_node)
            self.graph.add(triple)

Response: Handle optional field in package.


Instruction:
Can you implement a function in Python 3 that
handles optional fields in the package node.

Response:
def handle_pkg_optional_fields(self, package, package_node):
        """
        Write package optional fields.
        """
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.versionInfo, 'version')
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.packageFileName, 'file_name')
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.supplier, 'supplier')
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.originator, 'originator')
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.sourceInfo, 'source_info')
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.licenseComments, 'license_comment')
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.summary, 'summary')
        self.handle_package_literal_optional(package, package_node, self.spdx_namespace.description, 'description')

        if package.has_optional_field('check_sum'):
            checksum_node = self.create_checksum_node(package.check_sum)
            self.graph.add((package_node, self.spdx_namespace.checksum, checksum_node))

        if package.has_optional_field('homepage'):
            homepage_node = URIRef(self.to_special_value(package.homepage))
            homepage_triple = (package_node, self.doap_namespace.homepage, homepage_node)
            self.graph.add(homepage_triple)


Instruction:
How would you code a function in Python 3 to
create a node representing the package.

Response:
def create_package_node(self, package):
        """
        Return a Node representing the package.
        Files must have been added to the graph before this method is called.
        """
        package_node = BNode()
        type_triple = (package_node, RDF.type, self.spdx_namespace.Package)
        self.graph.add(type_triple)
        # Handle optional fields:
        self.handle_pkg_optional_fields(package, package_node)
        # package name
        name_triple = (package_node, self.spdx_namespace.name, Literal(package.name))
        self.graph.add(name_triple)
        # Package download location
        down_loc_node = (package_node, self.spdx_namespace.downloadLocation, self.to_special_value(package.download_location))
        self.graph.add(down_loc_node)
        # Handle package verification
        verif_node = self.package_verif_node(package)
        verif_triple = (package_node, self.spdx_namespace.packageVerificationCode, verif_node)
        self.graph.add(verif_triple)
        # Handle concluded license
        conc_lic_node = self.license_or_special(package.conc_lics)
        conc_lic_triple = (package_node, self.spdx_namespace.licenseConcluded, conc_lic_node)
        self.graph.add(conc_lic_triple)
        # Handle declared license
        decl_lic_node = self.license_or_special(package.license_declared)
        decl_lic_triple = (package_node, self.spdx_namespace.licenseDeclared, decl_lic_node)
        self.graph.add(decl_lic_triple)
        # Package licenses from files
        licenses_from_files_nodes = map(lambda el: self.license_or_special(el), package.licenses_from_files)
        lic_from_files_predicate = self.spdx_namespace.licenseInfoFromFiles
        lic_from_files_triples = [(package_node, lic_from_files_predicate, node) for node in licenses_from_files_nodes]
        for triple in lic_from_files_triples:
            self.graph.add(triple)
        # Copyright Text
        cr_text_node = self.to_special_value(package.cr_text)
        cr_text_triple = (package_node, self.spdx_namespace.copyrightText, cr_text_node)
        self.graph.add(cr_text_triple)
        # Handle files
        self.handle_package_has_file(package, package_node)
        return package_node


Instruction:
Can you implement a function in Python 3 that
handles the case where a package has a file.

Response:
def handle_package_has_file_helper(self, pkg_file):
        """
        Return node representing pkg_file
        pkg_file should be instance of spdx.file.
        """
        nodes = list(self.graph.triples((None, self.spdx_namespace.fileName, Literal(pkg_file.name))))
        if len(nodes) == 1:
            return nodes[0][0]
        else:
            raise InvalidDocumentError('handle_package_has_file_helper could not' +
                                       ' find file node for file: {0}'.format(pkg_file.name))


Instruction:
Can you implement a function in Python 3 that
handles hasFile nodes in package.

Response:
def handle_package_has_file(self, package, package_node):
        """
        Add hasFile triples to graph.
        Must be called after files have been added.
        """
        file_nodes = map(self.handle_package_has_file_helper, package.files)
        triples = [(package_node, self.spdx_namespace.hasFile, node) for node in file_nodes]
        for triple in triples:
            self.graph.add(triple)


Instruction:
Can you write a function in Python 3 where it
creates the root document node and return it.

Response:
def create_doc(self):
        """
        Add and return the root document node to graph.
        """
        doc_node = URIRef('http://www.spdx.org/tools#SPDXRef-DOCUMENT')
        # Doc type
        self.graph.add((doc_node, RDF.type, self.spdx_namespace.SpdxDocument))
        # Version
        vers_literal = Literal(str(self.document.version))
        self.graph.add((doc_node, self.spdx_namespace.specVersion, vers_literal))
        # Data license
        data_lics = URIRef(self.document.data_license.url)
        self.graph.add((doc_node, self.spdx_namespace.dataLicense, data_lics))
        doc_name = URIRef(self.document.name)
        self.graph.add((doc_node, self.spdx_namespace.name, doc_name))
        return doc_node


Instruction:
Can you tell what is the following Python 3 function doing
def load_license_list(file_name):
    licenses_map = {}
    with codecs.open(file_name, 'rb', encoding='utf-8') as lics:
        licenses = json.load(lics)
        version = licenses['licenseListVersion'].split('.')
        for lic in licenses['licenses']:
            if lic.get('isDeprecatedLicenseId'):
                continue
            name = lic['name']
            identifier = lic['licenseId']
            licenses_map[name] = identifier
            licenses_map[identifier] = name
    return version, licenses_map

Response: Load the licenses list from a JSON file and return the version tuple and a mapping of name - > id - > name


Instruction:
Here you have a function in Python 3, explain what it does
def validate(self, messages):
        messages = self.validate_creators(messages)
        messages = self.validate_created(messages)

        return messages

Response: Returns True if the fields are valid according to the SPDX standard.


Instruction:
Explain what the following Python 3 code does
def more_than_one_error(self, field):
        msg = 'More than one {0} defined.'.format(field)
        self.logger.log(msg)
        self.error = True

Response: Logs a more than one error.


Instruction:
Here you have a function in Python 3, explain what it does
def value_error(self, key, bad_value):
        msg = ERROR_MESSAGES[key].format(bad_value)
        self.logger.log(msg)
        self.error = True

Response: Reports a value error using ERROR_MESSAGES dict.


Instruction:
Create a Python 3 function for
checking if value is a special SPDX value such as NONE NOASSERTION or UNKNOWN returns proper model. Otherwise returns value

Response:
def to_special_value(self, value):
        """Checks if value is a special SPDX value such as
        NONE, NOASSERTION or UNKNOWN if so returns proper model.
        else returns value"""
        if value == self.spdx_namespace.none:
            return utils.SPDXNone()
        elif value == self.spdx_namespace.noassertion:
            return utils.NoAssert()
        elif value == self.spdx_namespace.unknown:
            return utils.UnKnown()
        else:
            return value


Instruction:
Write a Python 3 script to
handle a license from a lics resource.

Response:
def handle_lics(self, lics):
        """
        Return a License from a `lics` license resource.
        """
        # Handle extracted licensing info type.
        if (lics, RDF.type, self.spdx_namespace['ExtractedLicensingInfo']) in self.graph:
            return self.parse_only_extr_license(lics)

        # Assume resource, hence the path separator
        ident_start = lics.rfind('/') + 1
        if ident_start == 0:
            # special values such as spdx:noassertion
            special = self.to_special_value(lics)
            if special == lics:
                if self.LICS_REF_REGEX.match(lics):
                    # Is a license ref i.e LicenseRef-1
                    return document.License.from_identifier(lics)
                else:
                    # Not a known license form
                    raise SPDXValueError('License')
            else:
                # is a special value
                return special
        else:
            # license url
            return document.License.from_identifier(lics[ident_start:])


Instruction:
Given the following Python 3 function, write the documentation
def get_extr_license_ident(self, extr_lic):
        identifier_tripples = list(self.graph.triples((extr_lic, self.spdx_namespace['licenseId'], None)))

        if not identifier_tripples:
            self.error = True
            msg = 'Extracted license must have licenseId property.'
            self.logger.log(msg)
            return

        if len(identifier_tripples) > 1:
            self.more_than_one_error('extracted license identifier_tripples')
            return

        identifier_tripple = identifier_tripples[0]
        _s, _p, identifier = identifier_tripple
        return identifier

Response: Get an a license identifier from an ExtractedLicense or None.


Instruction:
Can you create a Python 3 function that
gets extracted text from an ExtractedLicense object.

Response:
def get_extr_license_text(self, extr_lic):
        """
        Return extracted text  from an ExtractedLicense or None.
        """
        text_tripples = list(self.graph.triples((extr_lic, self.spdx_namespace['extractedText'], None)))
        if not text_tripples:
            self.error = True
            msg = 'Extracted license must have extractedText property'
            self.logger.log(msg)
            return

        if len(text_tripples) > 1:
            self.more_than_one_error('extracted license text')
            return

        text_tripple = text_tripples[0]
        _s, _p, text = text_tripple
        return text


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_extr_lic_name(self, extr_lic):
        extr_name_list = list(self.graph.triples((extr_lic, self.spdx_namespace['licenseName'], None)))
        if len(extr_name_list) > 1:
            self.more_than_one_error('extracted license name')
            return
        elif len(extr_name_list) == 0:
            return
        return self.to_special_value(extr_name_list[0][2])

Response: Get the ExtractedLicense name from an ExtractedLicense object or None.


Instruction:
Create a Python 3 function for
returning a list of cross references for the given LIC.

Response:
def get_extr_lics_xref(self, extr_lic):
        """
        Return a list of cross references.
        """
        xrefs = list(self.graph.triples((extr_lic, RDFS.seeAlso, None)))
        return map(lambda xref_triple: xref_triple[2], xrefs)


Instruction:
Can you create a Python 3 function that
gets the extracted license comment from the extraneous lics.

Response:
def get_extr_lics_comment(self, extr_lics):
        """
        Return license comment or None.
        """
        comment_list = list(self.graph.triples(
            (extr_lics, RDFS.comment, None)))
        if len(comment_list) > 1 :
            self.more_than_one_error('extracted license comment')
            return
        elif len(comment_list) == 1:
            return comment_list[0][2]
        else:
            return


Instruction:
Can you tell what is the following Python 3 function doing
def parse_only_extr_license(self, extr_lic):
        # Grab all possible values
        ident = self.get_extr_license_ident(extr_lic)
        text = self.get_extr_license_text(extr_lic)
        comment = self.get_extr_lics_comment(extr_lic)
        xrefs = self.get_extr_lics_xref(extr_lic)
        name = self.get_extr_lic_name(extr_lic)

        if not ident:
            # Must have identifier
            return

        # Set fields
        # FIXME: the constructor of the license should alwas accept a name
        lic = document.ExtractedLicense(ident)
        if text is not None:
            lic.text = text
        if name is not None:
            lic.full_name = name
        if comment is not None:
            lic.comment = comment
        lic.cross_ref = map(lambda x: six.text_type(x), xrefs)
        return lic

Response: Parse a ExtractedLicense object that is only relevant to a single license.


Instruction:
Create a Python 3 function to
build and return an ExtractedLicense or None.

Response:
def handle_extracted_license(self, extr_lic):
        """
        Build and return an ExtractedLicense or None.
        Note that this function adds the license to the document.
        """
        lic = self.parse_only_extr_license(extr_lic)
        if lic is not None:
            self.doc.add_extr_lic(lic)
        return lic


Instruction:
How would you code a function in Python 3 to
handle a list of licenses and returns a license representing a cls object.

Response:
def _handle_license_list(self, lics_set, cls=None):
        """
        Return a license representing a `cls` object (LicenseConjunction
        or LicenseDisjunction) from a list of license resources or None.
        """
        licenses = []
        for _, _, lics_member in self.graph.triples(
            (lics_set, self.spdx_namespace['member'], None)):
            try:
                if (lics_member, RDF.type, self.spdx_namespace['ExtractedLicensingInfo']) in self.graph:
                    lics = self.handle_extracted_license(lics_member)
                    if lics is not None:
                        licenses.append(lics)
                else:
                    licenses.append(self.handle_lics(lics_member))
            except CardinalityError:
                self.value_error('LICS_LIST_MEMBER', lics_member)
                break
        if len(licenses) > 1:
            return reduce(lambda a, b: cls(a, b), licenses)
        else:
            self.value_error('PKG_CONC_LIST', '')
            return


Instruction:
Create a Python 3 function for
parsing the package fields.

Response:
def parse_package(self, p_term):
        """Parses package fields."""
        # Check there is a pacakge name
        if not (p_term, self.spdx_namespace['name'], None) in self.graph:
            self.error = True
            self.logger.log('Package must have a name.')
            # Create dummy package so that we may continue parsing the rest of
            # the package fields.
            self.builder.create_package(self.doc, 'dummy_package')
        else:
            for _s, _p, o in self.graph.triples((p_term, self.spdx_namespace['name'], None)):
                try:
                    self.builder.create_package(self.doc, six.text_type(o))
                except CardinalityError:
                    self.more_than_one_error('Package name')
                    break

        self.p_pkg_vinfo(p_term, self.spdx_namespace['versionInfo'])
        self.p_pkg_fname(p_term, self.spdx_namespace['packageFileName'])
        self.p_pkg_suppl(p_term, self.spdx_namespace['supplier'])
        self.p_pkg_originator(p_term, self.spdx_namespace['originator'])
        self.p_pkg_down_loc(p_term, self.spdx_namespace['downloadLocation'])
        self.p_pkg_homepg(p_term, self.doap_namespace['homepage'])
        self.p_pkg_chk_sum(p_term, self.spdx_namespace['checksum'])
        self.p_pkg_src_info(p_term, self.spdx_namespace['sourceInfo'])
        self.p_pkg_verif_code(p_term, self.spdx_namespace['packageVerificationCode'])
        self.p_pkg_lic_conc(p_term, self.spdx_namespace['licenseConcluded'])
        self.p_pkg_lic_decl(p_term, self.spdx_namespace['licenseDeclared'])
        self.p_pkg_lics_info_from_files(p_term, self.spdx_namespace['licenseInfoFromFiles'])
        self.p_pkg_comments_on_lics(p_term, self.spdx_namespace['licenseComments'])
        self.p_pkg_cr_text(p_term, self.spdx_namespace['copyrightText'])
        self.p_pkg_summary(p_term, self.spdx_namespace['summary'])
        self.p_pkg_descr(p_term, self.spdx_namespace['description'])


Instruction:
Can you generate the documentation for the following Python 3 function
def handle_pkg_lic(self, p_term, predicate, builder_func):
        try:
            for _, _, licenses in self.graph.triples((p_term, predicate, None)):
                if (licenses, RDF.type, self.spdx_namespace['ConjunctiveLicenseSet']) in self.graph:
                    lics = self.handle_conjunctive_list(licenses)
                    builder_func(self.doc, lics)

                elif (licenses, RDF.type, self.spdx_namespace['DisjunctiveLicenseSet']) in self.graph:
                    lics = self.handle_disjunctive_list(licenses)
                    builder_func(self.doc, lics)

                else:
                    try:
                        lics = self.handle_lics(licenses)
                        builder_func(self.doc, lics)
                    except SPDXValueError:
                        self.value_error('PKG_SINGLE_LICS', licenses)
        except CardinalityError:
            self.more_than_one_error('package {0}'.format(predicate))

Response: Handles package lics concluded or declared.


Instruction:
Write a Python 3 function that can
return first found fileName property or None.

Response:
def get_file_name(self, f_term):
        """Returns first found fileName property or None if not found."""
        for _, _, name in self.graph.triples((f_term, self.spdx_namespace['fileName'], None)):
            return name
        return


Instruction:
Implement a Python 3 function for
parsing all file contributors and add them to the model.

Response:
def p_file_contributor(self, f_term, predicate):
        """
        Parse all file contributors and adds them to the model.
        """
        for _, _, contributor in self.graph.triples((f_term, predicate, None)):
            self.builder.add_file_contribution(self.doc, six.text_type(contributor))


Instruction:
Implement a function in Python 3 to
set file notice text.

Response:
def p_file_notice(self, f_term, predicate):
        """Sets file notice text."""
        try:
            for _, _, notice in self.graph.triples((f_term, predicate, None)):
                self.builder.set_file_notice(self.doc, six.text_type(notice))
        except CardinalityError:
            self.more_than_one_error('file notice')


Instruction:
Write a Python 3 script for
setting file comment text.

Response:
def p_file_comment(self, f_term, predicate):
        """Sets file comment text."""
        try:
            for _, _, comment in self.graph.triples((f_term, predicate, None)):
                self.builder.set_file_comment(self.doc, six.text_type(comment))
        except CardinalityError:
            self.more_than_one_error('file comment')


Instruction:
Create a Python 3 function for
handling file artifactOf. Note: does not handle artifact of project URI.

Response:
def p_file_artifact(self, f_term, predicate):
        """Handles file artifactOf.
        Note: does not handle artifact of project URI.
        """
        for _, _, project in self.graph.triples((f_term, predicate, None)):
            if (project, RDF.type, self.doap_namespace['Project']):
                self.p_file_project(project)
            else:
                self.error = True
                msg = 'File must be artifact of doap:Project'
                self.logger.log(msg)


Instruction:
Can you tell what is the following Python 3 function doing
def p_file_project(self, project):
        for _, _, name in self.graph.triples((project, self.doap_namespace['name'], None)):
            self.builder.set_file_atrificat_of_project(self.doc, 'name', six.text_type(name))
        for _, _, homepage in self.graph.triples(
            (project, self.doap_namespace['homepage'], None)):
            self.builder.set_file_atrificat_of_project(self.doc, 'home', six.text_type(homepage))

Response: Parse the doap project name and homepage and set them using the file builder.


Instruction:
Make a summary of the following Python 3 code
def p_file_cr_text(self, f_term, predicate):
        try:
            for _, _, cr_text in self.graph.triples((f_term, predicate, None)):
                self.builder.set_file_copyright(self.doc, six.text_type(cr_text))
        except CardinalityError:
            self.more_than_one_error('file copyright text')

Response: Sets file copyright text.


Instruction:
Write a Python 3 script for
setting file license comments on licensing.

Response:
def p_file_comments_on_lics(self, f_term, predicate):
        """Sets file license comment."""
        try:
            for _, _, comment in self.graph.triples((f_term, predicate, None)):
                self.builder.set_file_license_comment(self.doc, six.text_type(comment))
        except CardinalityError:
            self.more_than_one_error('file comments on license')


Instruction:
How would you code a function in Python 3 to
set file license information.

Response:
def p_file_lic_info(self, f_term, predicate):
        """Sets file license information."""
        for _, _, info in self.graph.triples((f_term, predicate, None)):
            lic = self.handle_lics(info)
            if lic is not None:
                self.builder.set_file_license_in_file(self.doc, lic)


Instruction:
How would you implement a function in Python 3 that
sets the file type of the file.

Response:
def p_file_type(self, f_term, predicate):
        """Sets file type."""
        try:
            for _, _, ftype in self.graph.triples((f_term, predicate, None)):
                try:
                    if ftype.endswith('binary'):
                        ftype = 'BINARY'
                    elif ftype.endswith('source'):
                        ftype = 'SOURCE'
                    elif ftype.endswith('other'):
                        ftype = 'OTHER'
                    elif ftype.endswith('archive'):
                        ftype = 'ARCHIVE'
                    self.builder.set_file_type(self.doc, ftype)
                except SPDXValueError:
                    self.value_error('FILE_TYPE', ftype)
        except CardinalityError:
            self.more_than_one_error('file type')


Instruction:
Implement a Python 3 function for
setting file checksum. Assumes SHA1 algorithm without checking.

Response:
def p_file_chk_sum(self, f_term, predicate):
        """Sets file checksum. Assumes SHA1 algorithm without checking."""
        try:
            for _s, _p, checksum in self.graph.triples((f_term, predicate, None)):
                for _, _, value in self.graph.triples((checksum, self.spdx_namespace['checksumValue'], None)):
                    self.builder.set_file_chksum(self.doc, six.text_type(value))
        except CardinalityError:
            self.more_than_one_error('File checksum')


Instruction:
Can you generate the documentation for the following Python 3 function
def p_file_lic_conc(self, f_term, predicate):
        try:
            for _, _, licenses in self.graph.triples((f_term, predicate, None)):
                if (licenses, RDF.type, self.spdx_namespace['ConjunctiveLicenseSet']) in self.graph:
                    lics = self.handle_conjunctive_list(licenses)
                    self.builder.set_concluded_license(self.doc, lics)

                elif (licenses, RDF.type, self.spdx_namespace['DisjunctiveLicenseSet']) in self.graph:
                    lics = self.handle_disjunctive_list(licenses)
                    self.builder.set_concluded_license(self.doc, lics)

                else:
                    try:
                        lics = self.handle_lics(licenses)
                        self.builder.set_concluded_license(self.doc, lics)
                    except SPDXValueError:
                        self.value_error('FILE_SINGLE_LICS', licenses)
        except CardinalityError:
            self.more_than_one_error('file {0}'.format(predicate))

Response: Sets file licenses concluded.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_review_date(self, r_term):
        reviewed_list = list(self.graph.triples((r_term, self.spdx_namespace['reviewDate'], None)))
        if len(reviewed_list) != 1:
            self.error = True
            msg = 'Review must have exactlyone review date'
            self.logger.log(msg)
            return
        return six.text_type(reviewed_list[0][2])

Response: Returns the review date of the object.


Instruction:
Write a Python 3 function that can
return the reviewer as creator object or None if failed.

Response:
def get_reviewer(self, r_term):
        """Returns reviewer as creator object or None if failed.
        Reports errors on failure.
        """
        reviewer_list = list(self.graph.triples((r_term, self.spdx_namespace['reviewer'], None)))
        if len(reviewer_list) != 1:
            self.error = True
            msg = 'Review must have exactly one reviewer'
            self.logger.log(msg)
            return
        try:
            return self.builder.create_entity(self.doc, six.text_type(reviewer_list[0][2]))
        except SPDXValueError:
            self.value_error('REVIEWER_VALUE', reviewer_list[0][2])


Instruction:
Here you have a function in Python 3, explain what it does
def get_annotation_type(self, r_term):
        for _, _, typ in self.graph.triples((
                r_term, self.spdx_namespace['annotationType'], None)):
            if typ is not None:
                return typ
            else:
                self.error = True
                msg = 'Annotation must have exactly one annotation type.'
                self.logger.log(msg)
                return

Response: Returns the annotation type or None if found none or more than one.


Instruction:
Create a Python 3 function to
return annotation comment or None if found none or more than one.

Response:
def get_annotation_comment(self, r_term):
        """Returns annotation comment or None if found none or more than one.
        Reports errors.
        """
        comment_list = list(self.graph.triples((r_term, RDFS.comment, None)))
        if len(comment_list) > 1:
            self.error = True
            msg = 'Annotation can have at most one comment.'
            self.logger.log(msg)
            return
        else:
            return six.text_type(comment_list[0][2])


Instruction:
Can you implement a function in Python 3 that
returns annotation date or None if not found.

Response:
def get_annotation_date(self, r_term):
        """Returns annotation date or None if not found.
        Reports error on failure.
        Note does not check value format.
        """
        annotation_date_list = list(self.graph.triples((r_term, self.spdx_namespace['annotationDate'], None)))
        if len(annotation_date_list) != 1:
            self.error = True
            msg = 'Annotation must have exactly one annotation date.'
            self.logger.log(msg)
            return
        return six.text_type(annotation_date_list[0][2])


Instruction:
Can you generate a brief explanation for the following Python 3 code
def parse(self, fil):
        self.error = False
        self.graph = Graph()
        self.graph.parse(file=fil, format='xml')
        self.doc = document.Document()

        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['SpdxDocument'])):
            self.parse_doc_fields(s)

        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['ExternalDocumentRef'])):
            self.parse_ext_doc_ref(s)

        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['CreationInfo'])):
            self.parse_creation_info(s)

        for s, _p, o in self.graph.triples((None, RDF.type, self.spdx_namespace['Package'])):
            self.parse_package(s)

        for s, _p, o in self.graph.triples((None, self.spdx_namespace['referencesFile'], None)):
            self.parse_file(o)

        for s, _p, o in self.graph.triples((None, self.spdx_namespace['reviewed'], None)):
            self.parse_review(o)

        for s, _p, o in self.graph.triples((None, self.spdx_namespace['annotation'], None)):
            self.parse_annotation(o)

        validation_messages = []
        # Report extra errors if self.error is False otherwise there will be
        # redundent messages
        validation_messages = self.doc.validate(validation_messages)
        if not self.error:
            if validation_messages:
                for msg in validation_messages:
                    self.logger.log(msg)
                self.error = True
        return self.doc, self.error

Response: Parses a file and returns a document object.


Instruction:
Can you create a Python 3 function that
parses creation info from a term.

Response:
def parse_creation_info(self, ci_term):
        """
        Parse creators, created and comment.
        """
        for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['creator'], None)):
            try:
                ent = self.builder.create_entity(self.doc, six.text_type(o))
                self.builder.add_creator(self.doc, ent)
            except SPDXValueError:
                self.value_error('CREATOR_VALUE', o)

        for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['created'], None)):
            try:
                self.builder.set_created_date(self.doc, six.text_type(o))
            except SPDXValueError:
                self.value_error('CREATED_VALUE', o)
            except CardinalityError:
                self.more_than_one_error('created')
                break

        for _s, _p, o in self.graph.triples((ci_term, RDFS.comment, None)):
            try:
                self.builder.set_creation_comment(self.doc, six.text_type(o))
            except CardinalityError:
                self.more_than_one_error('CreationInfo comment')
                break
        for _s, _p, o in self.graph.triples((ci_term, self.spdx_namespace['licenseListVersion'], None)):
            try:
                self.builder.set_lics_list_ver(self.doc, six.text_type(o))
            except CardinalityError:
                self.more_than_one_error('licenseListVersion')
                break
            except SPDXValueError:
                self.value_error('LL_VALUE', o)