Instruction:
Implement a function in Python 3 to
return a |BaseStyle| subclass according to the type of style_elm.

Response:
def StyleFactory(style_elm):
    """
    Return a style object of the appropriate |BaseStyle| subclass, according
    to the type of *style_elm*.
    """
    style_cls = {
        WD_STYLE_TYPE.PARAGRAPH: _ParagraphStyle,
        WD_STYLE_TYPE.CHARACTER: _CharacterStyle,
        WD_STYLE_TYPE.TABLE:     _TableStyle,
        WD_STYLE_TYPE.LIST:      _NumberingStyle
    }[style_elm.type]

    return style_cls(style_elm)


Instruction:
Given the following Python 3 function, write the documentation
def name(self):
        name = self._element.name_val
        if name is None:
            return None
        return BabelFish.internal2ui(name)

Response: The name of the current object.


Instruction:
Can you generate the documentation for the following Python 3 function
def type(self):
        type = self._element.type
        if type is None:
            return WD_STYLE_TYPE.PARAGRAPH
        return type

Response: Returns the type of this style.


Instruction:
Write a Python 3 function that can
return |_ParagraphStyle| object representing the next paragraph style.

Response:
def next_paragraph_style(self):
        """
        |_ParagraphStyle| object representing the style to be applied
        automatically to a new paragraph inserted after a paragraph of this
        style. Returns self if no next paragraph style is defined. Assigning
        |None| or *self* removes the setting such that new paragraphs are
        created using this same style.
        """
        next_style_elm = self._element.next_style
        if next_style_elm is None:
            return self
        if next_style_elm.type != WD_STYLE_TYPE.PARAGRAPH:
            return self
        return StyleFactory(next_style_elm)


Instruction:
Given the following Python 3 function, write the documentation
def revision_number(self):
        revision = self.revision
        if revision is None:
            return 0
        revision_str = revision.text
        try:
            revision = int(revision_str)
        except ValueError:
            # non-integer revision strings also resolve to 0
            revision = 0
        # as do negative integers
        if revision < 0:
            revision = 0
        return revision

Response: Return the revision number of the current locale.


Instruction:
Implement a function in Python 3 to
set revision property to string value of integer value.

Response:
def revision_number(self, value):
        """
        Set revision property to string value of integer *value*.
        """
        if not isinstance(value, int) or value < 1:
            tmpl = "revision property requires positive int, got '%s'"
            raise ValueError(tmpl % value)
        revision = self.get_or_add_revision()
        revision.text = str(value)


Instruction:
How would you explain what the following Python 3 function does
def _get_or_add(self, prop_name):
        get_or_add_method_name = 'get_or_add_%s' % prop_name
        get_or_add_method = getattr(self, get_or_add_method_name)
        element = get_or_add_method()
        return element

Response: Get or add an entry from the cache.


Instruction:
Explain what the following Python 3 code does
def _offset_dt(cls, dt, offset_str):
        match = cls._offset_pattern.match(offset_str)
        if match is None:
            raise ValueError(
                "'%s' is not a valid offset string" % offset_str
            )
        sign, hours_str, minutes_str = match.groups()
        sign_factor = -1 if sign == '+' else 1
        hours = int(hours_str) * sign_factor
        minutes = int(minutes_str) * sign_factor
        td = timedelta(hours=hours, minutes=minutes)
        return dt + td

Response: Return a |datetime| instance that is offset from datetime dt by the timezone offset specified in offset_str.


Instruction:
Explain what the following Python 3 code does
def _set_element_datetime(self, prop_name, value):
        if not isinstance(value, datetime):
            tmpl = (
                "property requires <type 'datetime.datetime'> object, got %s"
            )
            raise ValueError(tmpl % type(value))
        element = self._get_or_add(prop_name)
        dt_str = value.strftime('%Y-%m-%dT%H:%M:%SZ')
        element.text = dt_str
        if prop_name in ('created', 'modified'):
            # These two require an explicit 'xsi:type="dcterms:W3CDTF"'
            # attribute. The first and last line are a hack required to add
            # the xsi namespace to the root element rather than each child
            # element in which it is referenced
            self.set(qn('xsi:foo'), 'bar')
            element.set(qn('xsi:type'), 'dcterms:W3CDTF')
            del self.attrib[qn('xsi:foo')]

Response: Set the date or time value of the child element having prop_name to value.


Instruction:
Can you generate the documentation for the following Python 3 function
def _set_element_text(self, prop_name, value):
        if not is_string(value):
            value = str(value)

        if len(value) > 255:
            tmpl = (
                "exceeded 255 char limit for property, got:\n\n'%s'"
            )
            raise ValueError(tmpl % value)
        element = self._get_or_add(prop_name)
        element.text = value

Response: Set string value of name * property to value *.


Instruction:
How would you implement a function in Python 3 that
returns the text of the element matching the given property name.

Response:
def _text_of_element(self, property_name):
        """
        Return the text in the element matching *property_name*, or an empty
        string if the element is not present or contains no text.
        """
        element = getattr(self, property_name)
        if element is None:
            return ''
        if element.text is None:
            return ''
        return element.text


Instruction:
Can you create a Python 3 function that
creates a new Gif instance from a file - like object.

Response:
def from_stream(cls, stream):
        """
        Return |Gif| instance having header properties parsed from GIF image
        in *stream*.
        """
        px_width, px_height = cls._dimensions_from_stream(stream)
        return cls(px_width, px_height, 72, 72)


Instruction:
Can you tell what is the following Python 3 function doing
def blob_for(self, pack_uri):
        path = os.path.join(self._path, pack_uri.membername)
        with open(path, 'rb') as f:
            blob = f.read()
        return blob

Response:
Return contents of file corresponding to pack_uri in package
        directory.


Instruction:
Given the following Python 3 function, write the documentation
def rels_xml_for(self, source_uri):
        try:
            rels_xml = self.blob_for(source_uri.rels_uri)
        except IOError:
            rels_xml = None
        return rels_xml

Response: Return rels item XML for source with source_uri.


Instruction:
Here you have a function in Python 3, explain what it does
def rels_xml_for(self, source_uri):
        try:
            rels_xml = self.blob_for(source_uri.rels_uri)
        except KeyError:
            rels_xml = None
        return rels_xml

Response: Return rels item XML for source with source_uri.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write(self, pack_uri, blob):
        self._zipf.writestr(pack_uri.membername, blob)

Response: Writes the given blob to the named zip file.


Instruction:
Can you tell what is the following Python 3 function doing
def from_stream(cls, stream):
        stream_rdr = StreamReader(stream, LITTLE_ENDIAN)

        px_width = stream_rdr.read_long(0x12)
        px_height = stream_rdr.read_long(0x16)

        horz_px_per_meter = stream_rdr.read_long(0x26)
        vert_px_per_meter = stream_rdr.read_long(0x2A)

        horz_dpi = cls._dpi(horz_px_per_meter)
        vert_dpi = cls._dpi(vert_px_per_meter)

        return cls(px_width, px_height, horz_dpi, vert_dpi)

Response: Create a new Bmp object from a file - like object.


Instruction:
How would you code a function in Python 3 to
return a Clark - notation qualified tag name for a namespace prefixed tag name.

Response:
def qn(tag):
    """
    Stands for "qualified name", a utility function to turn a namespace
    prefixed tag name into a Clark-notation qualified tag name for lxml. For
    example, ``qn('p:cSld')`` returns ``'{http://schemas.../main}cSld'``.
    """
    prefix, tagroot = tag.split(':')
    uri = nsmap[prefix]
    return '{%s}%s' % (uri, tagroot)


Instruction:
How would you explain what the following Python 3 function does
def clear_content(self):
        for child in self[:]:
            if child.tag == qn('w:pPr'):
                continue
            self.remove(child)

Response: Removes all child elements except the <w : pPr element.


Instruction:
Write a Python 3 script to
return a |PackageReader| instance loaded with contents of pkg_file.

Response:
def from_file(pkg_file):
        """
        Return a |PackageReader| instance loaded with contents of *pkg_file*.
        """
        phys_reader = PhysPkgReader(pkg_file)
        content_types = _ContentTypeMap.from_xml(phys_reader.content_types_xml)
        pkg_srels = PackageReader._srels_for(phys_reader, PACKAGE_URI)
        sparts = PackageReader._load_serialized_parts(
            phys_reader, pkg_srels, content_types
        )
        phys_reader.close()
        return PackageReader(content_types, pkg_srels, sparts)


Instruction:
Can you tell what is the following Python 3 function doing
def iter_sparts(self):
        for s in self._sparts:
            yield (s.partname, s.content_type, s.reltype, s.blob)

Response: Iterate over the serialized parts in the package.


Instruction:
How would you explain what the following Python 3 function does
def iter_srels(self):
        for srel in self._pkg_srels:
            yield (PACKAGE_URI, srel)
        for spart in self._sparts:
            for srel in spart.srels:
                yield (spart.partname, srel)

Response: Iterate over the relationships in the package.


Instruction:
How would you explain what the following Python 3 function does
def _srels_for(phys_reader, source_uri):
        rels_xml = phys_reader.rels_xml_for(source_uri)
        return _SerializedRelationships.load_from_xml(
            source_uri.baseURI, rels_xml)

Response:
Return |_SerializedRelationships| instance populated with
            relationships for source identified by source_uri.


Instruction:
Can you implement a function in Python 3 that
creates a |_ContentTypeMap| instance populated with the contents of content_types_xml.

Response:
def from_xml(content_types_xml):
        """
        Return a new |_ContentTypeMap| instance populated with the contents
        of *content_types_xml*.
        """
        types_elm = parse_xml(content_types_xml)
        ct_map = _ContentTypeMap()
        for o in types_elm.overrides:
            ct_map._add_override(o.partname, o.content_type)
        for d in types_elm.defaults:
            ct_map._add_default(d.extension, d.content_type)
        return ct_map


Instruction:
Explain what the following Python 3 code does
def target_partname(self):
        if self.is_external:
            msg = ('target_partname attribute on Relationship is undefined w'
                   'here TargetMode == "External"')
            raise ValueError(msg)
        # lazy-load _target_partname attribute
        if not hasattr(self, '_target_partname'):
            self._target_partname = PackURI.from_rel_ref(self._baseURI,
                                                         self.target_ref)
        return self._target_partname

Response: Return |PackURI| instance containing partname targeted by this relationship.


Instruction:
Implement a Python 3 function for
loading the _SerializedRelationships| instance from the XML representation of the item.

Response:
def load_from_xml(baseURI, rels_item_xml):
        """
        Return |_SerializedRelationships| instance loaded with the
        relationships contained in *rels_item_xml*. Returns an empty
        collection if *rels_item_xml* is |None|.
        """
        srels = _SerializedRelationships()
        if rels_item_xml is not None:
            rels_elm = parse_xml(rels_item_xml)
            for rel_elm in rels_elm.Relationship_lst:
                srels._srels.append(_SerializedRelationship(baseURI, rel_elm))
        return srels


Instruction:
Explain what the following Python 3 code does
def from_rel_ref(baseURI, relative_ref):
        joined_uri = posixpath.join(baseURI, relative_ref)
        abs_uri = posixpath.abspath(joined_uri)
        return PackURI(abs_uri)

Response: Return a |PackURI| instance containing the absolute pack URI formed by translating relative_ref onto baseURI.


Instruction:
Make a summary of the following Python 3 code
def ext(self):
        # raw_ext is either empty string or starts with period, e.g. '.xml'
        raw_ext = posixpath.splitext(self)[1]
        return raw_ext[1:] if raw_ext.startswith('.') else raw_ext

Response:
The extension portion of this pack URI e. g. xml for
       .


Instruction:
Create a Python 3 function to
return the index of the singleton partname.

Response:
def idx(self):
        """
        Return partname index as integer for tuple partname or None for
        singleton partname, e.g. ``21`` for ``'/ppt/slides/slide21.xml'`` and
        |None| for ``'/ppt/presentation.xml'``.
        """
        filename = self.filename
        if not filename:
            return None
        name_part = posixpath.splitext(filename)[0]  # filename w/ext removed
        match = self._filename_re.match(name_part)
        if match is None:
            return None
        if match.group(2):
            return int(match.group(2))
        return None


Instruction:
Explain what the following Python 3 code does
def relative_ref(self, baseURI):
        # workaround for posixpath bug in 2.6, doesn't generate correct
        # relative path when *start* (second) parameter is root ('/')
        if baseURI == '/':
            relpath = self[1:]
        else:
            relpath = posixpath.relpath(self, baseURI)
        return relpath

Response: Returns string containing relative reference to package item from baseURI. E. g. baseURI = baseURI. E. g. baseURI = baseURI. E. g. baseURI = baseURI. E. g. baseURI = baseURI. E. g. baseURI = baseURI. E. g. baseURI = baseURI. E. g. baseURI = baseURI.


Instruction:
How would you implement a function in Python 3 that
returns the pack URI of the. rels part corresponding to the current pack URI.

Response:
def rels_uri(self):
        """
        The pack URI of the .rels part corresponding to the current pack URI.
        Only produces sensible output if the pack URI is a partname or the
        package pseudo-partname '/'.
        """
        rels_filename = '%s.rels' % self.filename
        rels_uri_str = posixpath.join(self.baseURI, '_rels', rels_filename)
        return PackURI(rels_uri_str)


Instruction:
Explain what the following Python 3 code does
def new(ext, content_type):
        xml = '<Default xmlns="%s"/>' % nsmap['ct']
        default = parse_xml(xml)
        default.set('Extension', ext)
        default.set('ContentType', content_type)
        return default

Response: Return a new empty element with the specified extension and content type.


Instruction:
Here you have a function in Python 3, explain what it does
def new(partname, content_type):
        xml = '<Override xmlns="%s"/>' % nsmap['ct']
        override = parse_xml(xml)
        override.set('PartName', partname)
        override.set('ContentType', content_type)
        return override

Response:
Return a new element with the specified partname and content type set to parameter
        values.


Instruction:
How would you explain what the following Python 3 function does
def new(rId, reltype, target, target_mode=RTM.INTERNAL):
        xml = '<Relationship xmlns="%s"/>' % nsmap['pr']
        relationship = parse_xml(xml)
        relationship.set('Id', rId)
        relationship.set('Type', reltype)
        relationship.set('Target', target)
        if target_mode == RTM.EXTERNAL:
            relationship.set('TargetMode', RTM.EXTERNAL)
        return relationship

Response: Return a new Relationship element.


Instruction:
How would you code a function in Python 3 to
add a child relationship element with attributes set according to parameter values.

Response:
def add_rel(self, rId, reltype, target, is_external=False):
        """
        Add a child ``<Relationship>`` element with attributes set according
        to parameter values.
        """
        target_mode = RTM.EXTERNAL if is_external else RTM.INTERNAL
        relationship = CT_Relationship.new(rId, reltype, target, target_mode)
        self.append(relationship)


Instruction:
Write a Python 3 function for
adding a child <Default > element with the specified extension and content type.

Response:
def add_default(self, ext, content_type):
        """
        Add a child ``<Default>`` element with attributes set to parameter
        values.
        """
        default = CT_Default.new(ext, content_type)
        self.append(default)


Instruction:
Write a Python 3 script for
adding a child element with the specified partname and content type to the override list.

Response:
def add_override(self, partname, content_type):
        """
        Add a child ``<Override>`` element with attributes set to parameter
        values.
        """
        override = CT_Override.new(partname, content_type)
        self.append(override)


Instruction:
Given the following Python 3 function, write the documentation
def add_paragraph(self, text='', style=None):
        paragraph = self._add_paragraph()
        if text:
            paragraph.add_run(text)
        if style is not None:
            paragraph.style = style
        return paragraph

Response: Add a single paragraph to the end of the content in this Arc.


Instruction:
Implement a Python 3 function for
returning a new table with rows and cols and width added to the content of this container.

Response:
def add_table(self, rows, cols, width):
        """
        Return a table of *width* having *rows* rows and *cols* columns,
        newly appended to the content in this container. *width* is evenly
        distributed between the table columns.
        """
        from .table import Table
        tbl = CT_Tbl.new_tbl(rows, cols, width)
        self._element._insert_tbl(tbl)
        return Table(tbl, self)


Instruction:
Explain what the following Python 3 code does
def _ChunkFactory(chunk_type, stream_rdr, offset):
    chunk_cls_map = {
        PNG_CHUNK_TYPE.IHDR: _IHDRChunk,
        PNG_CHUNK_TYPE.pHYs: _pHYsChunk,
    }
    chunk_cls = chunk_cls_map.get(chunk_type, _Chunk)
    return chunk_cls.from_offset(chunk_type, stream_rdr, offset)

Response:
Returns a |_Chunk| subclass instance appropriate to chunk_type * parsed
    from stream_rdr at offset.


Instruction:
Write a Python 3 script to
return a |_Chunks| instance containing the PNG chunks in stream.

Response:
def from_stream(cls, stream):
        """
        Return a |_Chunks| instance containing the PNG chunks in *stream*.
        """
        chunk_parser = _ChunkParser.from_stream(stream)
        chunks = [chunk for chunk in chunk_parser.iter_chunks()]
        return cls(chunks)


Instruction:
Here you have a function in Python 3, explain what it does
def pHYs(self):
        match = lambda chunk: chunk.type_name == PNG_CHUNK_TYPE.pHYs  # noqa
        return self._find_first(match)

Response: Return the first pHYs chunk in PNG image or |None| if no pHYs chunk is present


Instruction:
Can you write a function in Python 3 where it
iterates over the PNG chunks in this parser s internal cache.

Response:
def iter_chunks(self):
        """
        Generate a |_Chunk| subclass instance for each chunk in this parser's
        PNG stream, in the order encountered in the stream.
        """
        for chunk_type, offset in self._iter_chunk_offsets():
            chunk = _ChunkFactory(chunk_type, self._stream_rdr, offset)
            yield chunk


Instruction:
Can you tell what is the following Python 3 function doing
def _iter_chunk_offsets(self):
        chunk_offset = 8
        while True:
            chunk_data_len = self._stream_rdr.read_long(chunk_offset)
            chunk_type = self._stream_rdr.read_str(4, chunk_offset, 4)
            data_offset = chunk_offset + 8
            yield chunk_type, data_offset
            if chunk_type == 'IEND':
                break
            # incr offset for chunk len long, chunk type, chunk data, and CRC
            chunk_offset += (4 + 4 + chunk_data_len + 4)

Response: Iterate over the chunk offsets in the PNG image stream.


Instruction:
Can you generate the documentation for the following Python 3 function
def from_offset(cls, chunk_type, stream_rdr, offset):
        px_width = stream_rdr.read_long(offset)
        px_height = stream_rdr.read_long(offset, 4)
        return cls(chunk_type, px_width, px_height)

Response: Return an _IHDRChunk instance containing the image dimensions and height extracted from the IHDR chunk at the given offset.


Instruction:
How would you implement a function in Python 3 that
creates a _pHYsChunk instance from the given chunk type and offset.

Response:
def from_offset(cls, chunk_type, stream_rdr, offset):
        """
        Return a _pHYsChunk instance containing the image resolution
        extracted from the pHYs chunk in *stream* at *offset*.
        """
        horz_px_per_unit = stream_rdr.read_long(offset)
        vert_px_per_unit = stream_rdr.read_long(offset, 4)
        units_specifier = stream_rdr.read_byte(offset, 8)
        return cls(
            chunk_type, horz_px_per_unit, vert_px_per_unit, units_specifier
        )


Instruction:
Explain what the following Python 3 code does
def read_byte(self, base, offset=0):
        fmt = 'B'
        return self._read_int(fmt, base, offset)

Response: Read a byte from the file and return it as an integer.


Instruction:
Here you have a function in Python 3, explain what it does
def read_long(self, base, offset=0):
        fmt = '<L' if self._byte_order is LITTLE_ENDIAN else '>L'
        return self._read_int(fmt, base, offset)

Response: Reads a long value from the stream.


Instruction:
Write a Python 3 script to
read a 2 byte short integer from the file and return it as a signed integer.

Response:
def read_short(self, base, offset=0):
        """
        Return the int value of the two bytes at the file position determined
        by *base* and *offset*, similarly to ``read_long()`` above.
        """
        fmt = b'<H' if self._byte_order is LITTLE_ENDIAN else b'>H'
        return self._read_int(fmt, base, offset)


Instruction:
Can you generate the documentation for the following Python 3 function
def read_str(self, char_count, base, offset=0):
        def str_struct(char_count):
            format_ = '%ds' % char_count
            return Struct(format_)
        struct = str_struct(char_count)
        chars = self._unpack_item(struct, base, offset)
        unicode_str = chars.decode('UTF-8')
        return unicode_str

Response: Read the string from the file.


Instruction:
How would you code a function in Python 3 to
load the image part collection with all the image parts in package.

Response:
def _gather_image_parts(self):
        """Load the image part collection with all the image parts in package."""
        for rel in self.iter_rels():
            if rel.is_external:
                continue
            if rel.reltype != RT.IMAGE:
                continue
            if rel.target_part in self.image_parts:
                continue
            self.image_parts.append(rel.target_part)


Instruction:
Explain what the following Python 3 code does
def get_or_add_image_part(self, image_descriptor):
        image = Image.from_file(image_descriptor)
        matching_image_part = self._get_by_sha1(image.sha1)
        if matching_image_part is not None:
            return matching_image_part
        return self._add_image_part(image)

Response: Return |ImagePart| object containing image identified by image_descriptor.


Instruction:
Can you write a function in Python 3 where it
adds an |ImagePart| instance to the collection and return it appended.

Response:
def _add_image_part(self, image):
        """
        Return an |ImagePart| instance newly created from image and appended
        to the collection.
        """
        partname = self._next_image_partname(image.ext)
        image_part = ImagePart.from_image(image, partname)
        self.append(image_part)
        return image_part


Instruction:
Create a Python 3 function for
returning the image part with the given SHA1 hash or None if not found.

Response:
def _get_by_sha1(self, sha1):
        """
        Return the image part in this collection having a SHA1 hash matching
        *sha1*, or |None| if not found.
        """
        for image_part in self._image_parts:
            if image_part.sha1 == sha1:
                return image_part
        return None


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _get_or_add_definition(self):
        # ---note this method is called recursively to access inherited definitions---
        # ---case-1: definition is not inherited---
        if self._has_definition:
            return self._definition
        # ---case-2: definition is inherited and belongs to second-or-later section---
        prior_headerfooter = self._prior_headerfooter
        if prior_headerfooter:
            return prior_headerfooter._get_or_add_definition()
        # ---case-3: definition is inherited, but belongs to first section---
        return self._add_definition()

Response: Return HeaderPart or FooterPart object for this section.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _add_definition(self):
        footer_part, rId = self._document_part.add_footer_part()
        self._sectPr.add_footerReference(self._hdrftr_index, rId)
        return footer_part

Response: Return newly - added footer part.


Instruction:
Given the following Python 3 function, write the documentation
def _definition(self):
        footerReference = self._sectPr.get_footerReference(self._hdrftr_index)
        return self._document_part.footer_part(footerReference.rId)

Response: Return |FooterPart| object containing content of this footer.


Instruction:
Create a Python 3 function to
remove footer definition associated with this section.

Response:
def _drop_definition(self):
        """Remove footer definition (footer part) associated with this section."""
        rId = self._sectPr.remove_footerReference(self._hdrftr_index)
        self._document_part.drop_rel(rId)


Instruction:
Implement a Python 3 function for
truing if a footer is defined for this section.

Response:
def _has_definition(self):
        """True if a footer is defined for this section."""
        footerReference = self._sectPr.get_footerReference(self._hdrftr_index)
        return False if footerReference is None else True


Instruction:
Given the following Python 3 function, write the documentation
def _prior_headerfooter(self):
        preceding_sectPr = self._sectPr.preceding_sectPr
        return (
            None if preceding_sectPr is None
            else _Footer(preceding_sectPr, self._document_part, self._hdrftr_index)
        )

Response: |_Footer| proxy on prior sectPr element or None.


Instruction:
Write a Python 3 script for
adding the definition of the section to the header part.

Response:
def _add_definition(self):
        """Return newly-added header part."""
        header_part, rId = self._document_part.add_header_part()
        self._sectPr.add_headerReference(self._hdrftr_index, rId)
        return header_part


Instruction:
Here you have a function in Python 3, explain what it does
def _definition(self):
        headerReference = self._sectPr.get_headerReference(self._hdrftr_index)
        return self._document_part.header_part(headerReference.rId)

Response: Return the definition of the header.


Instruction:
How would you code a function in Python 3 to
remove header definition associated with this section.

Response:
def _drop_definition(self):
        """Remove header definition associated with this section."""
        rId = self._sectPr.remove_headerReference(self._hdrftr_index)
        self._document_part.drop_header_part(rId)


Instruction:
Here you have a function in Python 3, explain what it does
def _has_definition(self):
        headerReference = self._sectPr.get_headerReference(self._hdrftr_index)
        return False if headerReference is None else True

Response: True if a header is explicitly defined for this section.


Instruction:
Given the following Python 3 function, write the documentation
def _prior_headerfooter(self):
        preceding_sectPr = self._sectPr.preceding_sectPr
        return (
            None if preceding_sectPr is None
            else _Header(preceding_sectPr, self._document_part, self._hdrftr_index)
        )

Response: |_Header| proxy on prior sectPr element or None.


Instruction:
How would you explain what the following Python 3 function does
def add_heading(self, text="", level=1):
        if not 0 <= level <= 9:
            raise ValueError("level must be in range 0-9, got %d" % level)
        style = "Title" if level == 0 else "Heading %d" % level
        return self.add_paragraph(text, style)

Response: Return a heading paragraph newly added to the end of the document.


Instruction:
Write a Python 3 script for
returning newly |Paragraph| object containing only a page break.

Response:
def add_page_break(self):
        """Return newly |Paragraph| object containing only a page break."""
        paragraph = self.add_paragraph()
        paragraph.add_run().add_break(WD_BREAK.PAGE)
        return paragraph


Instruction:
Can you write a function in Python 3 where it
adds a picture shape to the document.

Response:
def add_picture(self, image_path_or_stream, width=None, height=None):
        """
        Return a new picture shape added in its own paragraph at the end of
        the document. The picture contains the image at
        *image_path_or_stream*, scaled based on *width* and *height*. If
        neither width nor height is specified, the picture appears at its
        native size. If only one is specified, it is used to compute
        a scaling factor that is then applied to the unspecified dimension,
        preserving the aspect ratio of the image. The native size of the
        picture is calculated using the dots-per-inch (dpi) value specified
        in the image file, defaulting to 72 dpi if no value is specified, as
        is often the case.
        """
        run = self.add_paragraph().add_run()
        return run.add_picture(image_path_or_stream, width, height)


Instruction:
Implement a function in Python 3 to
add a new section to the end of the document.

Response:
def add_section(self, start_type=WD_SECTION.NEW_PAGE):
        """
        Return a |Section| object representing a new section added at the end
        of the document. The optional *start_type* argument must be a member
        of the :ref:`WdSectionStart` enumeration, and defaults to
        ``WD_SECTION.NEW_PAGE`` if not provided.
        """
        new_sectPr = self._element.body.add_section_break()
        new_sectPr.start_type = start_type
        return Section(new_sectPr, self._part)


Instruction:
How would you implement a function in Python 3 that
adds a new table to the document.

Response:
def add_table(self, rows, cols, style=None):
        """
        Add a table having row and column counts of *rows* and *cols*
        respectively and table style of *style*. *style* may be a paragraph
        style object or a paragraph style name. If *style* is |None|, the
        table inherits the default table style of the document.
        """
        table = self._body.add_table(rows, cols, self._block_width)
        table.style = style
        return table


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _block_width(self):
        section = self.sections[-1]
        return Emu(
            section.page_width - section.left_margin - section.right_margin
        )

Response: Return a |Length| object specifying the width of available writing space between the margins of the last section of this document.


Instruction:
Write a Python 3 function that can
return |_Body| instance containing the content for this document.

Response:
def _body(self):
        """
        The |_Body| instance containing the content for this document.
        """
        if self.__body is None:
            self.__body = _Body(self._element.body, self)
        return self.__body


Instruction:
Can you implement a function in Python 3 that
registers cls to be constructed when the oxml parser encounters an analyzed element with matching tag.

Response:
def register_element_cls(tag, cls):
    """
    Register *cls* to be constructed when the oxml parser encounters an
    element with matching *tag*. *tag* is a string of the form
    ``nspfx:tagroot``, e.g. ``'w:document'``.
    """
    nspfx, tagroot = tag.split(':')
    namespace = element_class_lookup.get_namespace(nsmap[nspfx])
    namespace[tagroot] = cls


Instruction:
How would you explain what the following Python 3 function does
def OxmlElement(nsptag_str, attrs=None, nsdecls=None):
    nsptag = NamespacePrefixedTag(nsptag_str)
    if nsdecls is None:
        nsdecls = nsptag.nsmap
    return oxml_parser.makeelement(
        nsptag.clark_name, attrib=attrs, nsmap=nsdecls
    )

Response: Return a loose lxml element with the specified tag specified by nsptag_str.


Instruction:
How would you code a function in Python 3 to
return an |_IfdEntry| subclass instance containing the value of the directory entry at offset in stream_rdr.

Response:
def _IfdEntryFactory(stream_rdr, offset):
    """
    Return an |_IfdEntry| subclass instance containing the value of the
    directory entry at *offset* in *stream_rdr*.
    """
    ifd_entry_classes = {
        TIFF_FLD.ASCII:    _AsciiIfdEntry,
        TIFF_FLD.SHORT:    _ShortIfdEntry,
        TIFF_FLD.LONG:     _LongIfdEntry,
        TIFF_FLD.RATIONAL: _RationalIfdEntry,
    }
    field_type = stream_rdr.read_short(offset, 2)
    if field_type in ifd_entry_classes:
        entry_cls = ifd_entry_classes[field_type]
    else:
        entry_cls = _IfdEntry
    return entry_cls.from_stream(stream_rdr, offset)


Instruction:
Can you write a function in Python 3 where it
creates a |Tiff| instance from a file - like object.

Response:
def from_stream(cls, stream):
        """
        Return a |Tiff| instance containing the properties of the TIFF image
        in *stream*.
        """
        parser = _TiffParser.parse(stream)

        px_width = parser.px_width
        px_height = parser.px_height
        horz_dpi = parser.horz_dpi
        vert_dpi = parser.vert_dpi

        return cls(px_width, px_height, horz_dpi, vert_dpi)


Instruction:
Implement a Python 3 function for
parsing the TIFF image in the given stream.

Response:
def parse(cls, stream):
        """
        Return an instance of |_TiffParser| containing the properties parsed
        from the TIFF image in *stream*.
        """
        stream_rdr = cls._make_stream_reader(stream)
        ifd0_offset = stream_rdr.read_long(4)
        ifd_entries = _IfdEntries.from_stream(stream_rdr, ifd0_offset)
        return cls(ifd_entries)


Instruction:
Can you write a function in Python 3 where it
detects the endian of the TIFF header.

Response:
def _detect_endian(cls, stream):
        """
        Return either BIG_ENDIAN or LITTLE_ENDIAN depending on the endian
        indicator found in the TIFF *stream* header, either 'MM' or 'II'.
        """
        stream.seek(0)
        endian_str = stream.read(2)
        return BIG_ENDIAN if endian_str == b'MM' else LITTLE_ENDIAN


Instruction:
Write a Python 3 function for
returning the dpi value for the given resolution tag.

Response:
def _dpi(self, resolution_tag):
        """
        Return the dpi value calculated for *resolution_tag*, which can be
        either TIFF_TAG.X_RESOLUTION or TIFF_TAG.Y_RESOLUTION. The
        calculation is based on the values of both that tag and the
        TIFF_TAG.RESOLUTION_UNIT tag in this parser's |_IfdEntries| instance.
        """
        ifd_entries = self._ifd_entries

        if resolution_tag not in ifd_entries:
            return 72

        # resolution unit defaults to inches (2)
        resolution_unit = (
            ifd_entries[TIFF_TAG.RESOLUTION_UNIT]
            if TIFF_TAG.RESOLUTION_UNIT in ifd_entries else 2
        )

        if resolution_unit == 1:  # aspect ratio only
            return 72
        # resolution_unit == 2 for inches, 3 for centimeters
        units_per_inch = 1 if resolution_unit == 2 else 2.54
        dots_per_unit = ifd_entries[resolution_tag]
        return int(round(dots_per_unit * units_per_inch))


Instruction:
Write a Python 3 script for
returning a |StreamReader| instance with wrapping stream and having "endian -ness determined by the MM or II indicator in the TIFF stream header.

Response:
def _make_stream_reader(cls, stream):
        """
        Return a |StreamReader| instance with wrapping *stream* and having
        "endian-ness" determined by the 'MM' or 'II' indicator in the TIFF
        stream header.
        """
        endian = cls._detect_endian(stream)
        return StreamReader(stream, endian)


Instruction:
Can you tell what is the following Python 3 function doing
def from_stream(cls, stream, offset):
        ifd_parser = _IfdParser(stream, offset)
        entries = dict((e.tag, e.value) for e in ifd_parser.iter_entries())
        return cls(entries)

Response: Parse an IfdEntries object from a stream starting at the given offset.


Instruction:
Make a summary of the following Python 3 code
def iter_entries(self):
        for idx in range(self._entry_count):
            dir_entry_offset = self._offset + 2 + (idx*12)
            ifd_entry = _IfdEntryFactory(self._stream_rdr, dir_entry_offset)
            yield ifd_entry

Response: Iterates over the entries in the ISO.


Instruction:
Write a Python 3 function for
parsing an entry from a stream.

Response:
def from_stream(cls, stream_rdr, offset):
        """
        Return an |_IfdEntry| subclass instance containing the tag and value
        of the tag parsed from *stream_rdr* at *offset*. Note this method is
        common to all subclasses. Override the ``_parse_value()`` method to
        provide distinctive behavior based on field type.
        """
        tag_code = stream_rdr.read_short(offset, 0)
        value_count = stream_rdr.read_long(offset, 4)
        value_offset = stream_rdr.read_long(offset, 8)
        value = cls._parse_value(
            stream_rdr, offset, value_count, value_offset
        )
        return cls(tag_code, value)


Instruction:
Implement a Python 3 function for
parsing a value from the stream_rdr at the given offset.

Response:
def _parse_value(cls, stream_rdr, offset, value_count, value_offset):
        """
        Return the ASCII string parsed from *stream_rdr* at *value_offset*.
        The length of the string, including a terminating '\x00' (NUL)
        character, is in *value_count*.
        """
        return stream_rdr.read_str(value_count-1, value_offset)


Instruction:
Can you implement a function in Python 3 that
parses the value of the entry.

Response:
def _parse_value(cls, stream_rdr, offset, value_count, value_offset):
        """
        Return the short int value contained in the *value_offset* field of
        this entry. Only supports single values at present.
        """
        if value_count == 1:
            return stream_rdr.read_short(offset, 8)
        else:  # pragma: no cover
            return 'Multi-value short integer NOT IMPLEMENTED'


Instruction:
Implement a function in Python 3 to
parse the value of the entry.

Response:
def _parse_value(cls, stream_rdr, offset, value_count, value_offset):
        """
        Return the long int value contained in the *value_offset* field of
        this entry. Only supports single values at present.
        """
        if value_count == 1:
            return stream_rdr.read_long(offset, 8)
        else:  # pragma: no cover
            return 'Multi-value long integer NOT IMPLEMENTED'


Instruction:
Create a Python 3 function to
parse a value from the stream.

Response:
def _parse_value(cls, stream_rdr, offset, value_count, value_offset):
        """
        Return the rational (numerator / denominator) value at *value_offset*
        in *stream_rdr* as a floating-point number. Only supports single
        values at present.
        """
        if value_count == 1:
            numerator = stream_rdr.read_long(value_offset)
            denominator = stream_rdr.read_long(value_offset, 4)
            return numerator / denominator
        else:  # pragma: no cover
            return 'Multi-value Rational NOT IMPLEMENTED'


Instruction:
Can you create a Python 3 function that
returns ( footer_part rId ) pair for newly - created footer part.

Response:
def add_footer_part(self):
        """Return (footer_part, rId) pair for newly-created footer part."""
        footer_part = FooterPart.new(self.package)
        rId = self.relate_to(footer_part, RT.FOOTER)
        return footer_part, rId


Instruction:
Write a Python 3 function that can
return ( header_part rId ) pair for newly - created header part.

Response:
def add_header_part(self):
        """Return (header_part, rId) pair for newly-created header part."""
        header_part = HeaderPart.new(self.package)
        rId = self.relate_to(header_part, RT.HEADER)
        return header_part, rId


Instruction:
Can you generate the documentation for the following Python 3 function
def numbering_part(self):
        try:
            return self.part_related_by(RT.NUMBERING)
        except KeyError:
            numbering_part = NumberingPart.new()
            self.relate_to(numbering_part, RT.NUMBERING)
            return numbering_part

Response: A |NumberingPart| object providing access to the numbering part definitions for this document.


Instruction:
Given the following Python 3 function, write the documentation
def _settings_part(self):
        try:
            return self.part_related_by(RT.SETTINGS)
        except KeyError:
            settings_part = SettingsPart.default(self.package)
            self.relate_to(settings_part, RT.SETTINGS)
            return settings_part

Response:
A |SettingsPart| object providing access to the document - level
        settings for this document.


Instruction:
Given the following Python 3 function, write the documentation
def _styles_part(self):
        try:
            return self.part_related_by(RT.STYLES)
        except KeyError:
            styles_part = StylesPart.default(self.package)
            self.relate_to(styles_part, RT.STYLES)
            return styles_part

Response: Returns |StylesPart| instance for this document. Creates an empty stylesPart part if one is not present.


Instruction:
How would you implement a function in Python 3 that
returns the contents of the file at relpath relative to this file.

Response:
def text_of(relpath):
    """
    Return string containing the contents of the file at *relpath* relative to
    this file.
    """
    thisdir = os.path.dirname(__file__)
    file_path = os.path.join(thisdir, os.path.normpath(relpath))
    with open(file_path) as f:
        text = f.read()
    return text


Instruction:
Write a Python 3 script for
writing a physical package file containing the current naccesstoken entries to the given file.

Response:
def write(pkg_file, pkg_rels, parts):
        """
        Write a physical package (.pptx file) to *pkg_file* containing
        *pkg_rels* and *parts* and a content types stream based on the
        content types of the parts.
        """
        phys_writer = PhysPkgWriter(pkg_file)
        PackageWriter._write_content_types_stream(phys_writer, parts)
        PackageWriter._write_pkg_rels(phys_writer, pkg_rels)
        PackageWriter._write_parts(phys_writer, parts)
        phys_writer.close()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _write_content_types_stream(phys_writer, parts):
        cti = _ContentTypesItem.from_parts(parts)
        phys_writer.write(CONTENT_TYPES_URI, cti.blob)

Response: Write the content types. xml part to the physical package with anonymization target for each part in parts.


Instruction:
Can you implement a function in Python 3 that
writes the blob of each part in parts to the package.

Response:
def _write_parts(phys_writer, parts):
        """
        Write the blob of each part in *parts* to the package, along with a
        rels item for its relationships if and only if it has any.
        """
        for part in parts:
            phys_writer.write(part.partname, part.blob)
            if len(part._rels):
                phys_writer.write(part.partname.rels_uri, part._rels.xml)


Instruction:
Here you have a function in Python 3, explain what it does
def from_parts(cls, parts):
        cti = cls()
        cti._defaults['rels'] = CT.OPC_RELATIONSHIPS
        cti._defaults['xml'] = CT.XML
        for part in parts:
            cti._add_content_type(part.partname, part.content_type)
        return cti

Response: Create a new object from a list of parts.


Instruction:
Can you generate the documentation for the following Python 3 function
def _add_content_type(self, partname, content_type):
        ext = partname.ext
        if (ext.lower(), content_type) in default_content_types:
            self._defaults[ext] = content_type
        else:
            self._overrides[partname] = content_type

Response: Add a content type for the given partname and content_type.


Instruction:
Can you generate the documentation for the following Python 3 function
def _element(self):
        _types_elm = CT_Types.new()
        for ext in sorted(self._defaults.keys()):
            _types_elm.add_default(ext, self._defaults[ext])
        for partname in sorted(self._overrides.keys()):
            _types_elm.add_override(partname, self._overrides[partname])
        return _types_elm

Response:
Return the XML representation of this content types item suitable for storage as
       . xml in an OPC package.


Instruction:
Given the following Python 3 function, write the documentation
def given_a_run_having_mixed_text_content(context):
    r_xml = """\
        <w:r %s>
          <w:t>abc</w:t>
          <w:tab/>
          <w:t>def</w:t>
          <w:cr/>
          <w:t>ghi</w:t>
          <w:drawing/>
          <w:br/>
          <w:t>jkl</w:t>
        </w:r>""" % nsdecls('w')
    r = parse_xml(r_xml)
    context.run = Run(r, None)

Response: A run with mixed text content.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_section_break(self):
        # ---get the sectPr at file-end, which controls last section (sections[-1])---
        sentinel_sectPr = self.get_or_add_sectPr()
        # ---add exact copy to new `w:p` element; that is now second-to last section---
        self.add_p().set_sectPr(sentinel_sectPr.clone())
        # ---remove any header or footer references from "new" last section---
        for hdrftr_ref in sentinel_sectPr.xpath("w:headerReference|w:footerReference"):
            sentinel_sectPr.remove(hdrftr_ref)
        # ---the sentinel `w:sectPr` now controls the new last section---
        return sentinel_sectPr

Response: Return the sentinel element for new section added at end of document.


Instruction:
Here you have a function in Python 3, explain what it does
def clear_content(self):
        if self.sectPr is not None:
            content_elms = self[:-1]
        else:
            content_elms = self[:]
        for content_elm in content_elms:
            self.remove(content_elm)

Response:
Remove all content child elements from this element. Leave
        the last element.


Instruction:
Create a Python 3 function to
return a |BaseImageHeader| subclass that knows how to parse the image in *stream*.

Response:
def _ImageHeaderFactory(stream):
    """
    Return a |BaseImageHeader| subclass instance that knows how to parse the
    headers of the image in *stream*.
    """
    from docx.image import SIGNATURES

    def read_32(stream):
        stream.seek(0)
        return stream.read(32)

    header = read_32(stream)
    for cls, offset, signature_bytes in SIGNATURES:
        end = offset + len(signature_bytes)
        found_bytes = header[offset:end]
        if found_bytes == signature_bytes:
            return cls.from_stream(stream)
    raise UnrecognizedImageError


Instruction:
Create a Python 3 function for
parsing an image from a binary blob.

Response:
def from_blob(cls, blob):
        """
        Return a new |Image| subclass instance parsed from the image binary
        contained in *blob*.
        """
        stream = BytesIO(blob)
        return cls._from_stream(stream, blob)


Instruction:
Implement a function in Python 3 to
return a |Image| subclass instance loaded from the image file identified by image_descriptor.

Response:
def from_file(cls, image_descriptor):
        """
        Return a new |Image| subclass instance loaded from the image file
        identified by *image_descriptor*, a path or file-like object.
        """
        if is_string(image_descriptor):
            path = image_descriptor
            with open(path, 'rb') as f:
                blob = f.read()
                stream = BytesIO(blob)
            filename = os.path.basename(path)
        else:
            stream = image_descriptor
            stream.seek(0)
            blob = stream.read()
            filename = None
        return cls._from_stream(stream, blob, filename)


Instruction:
How would you code a function in Python 3 to
return a tuple representing the width and height of the image.

Response:
def scaled_dimensions(self, width=None, height=None):
        """
        Return a (cx, cy) 2-tuple representing the native dimensions of this
        image scaled by applying the following rules to *width* and *height*.
        If both *width* and *height* are specified, the return value is
        (*width*, *height*); no scaling is performed. If only one is
        specified, it is used to compute a scaling factor that is then
        applied to the unspecified dimension, preserving the aspect ratio of
        the image. If both *width* and *height* are |None|, the native
        dimensions are returned. The native dimensions are calculated using
        the dots-per-inch (dpi) value embedded in the image, defaulting to 72
        dpi if no value is specified, as is often the case. The returned
        values are both |Length| objects.
        """
        if width is None and height is None:
            return self.width, self.height

        if width is None:
            scaling_factor = float(height) / float(self.height)
            width = round(self.width * scaling_factor)

        if height is None:
            scaling_factor = float(width) / float(self.width)
            height = round(self.height * scaling_factor)

        return Emu(width), Emu(height)


Instruction:
Can you create a Python 3 function that
creates an |Image| instance from the given |Stream| object.

Response:
def _from_stream(cls, stream, blob, filename=None):
        """
        Return an instance of the |Image| subclass corresponding to the
        format of the image in *stream*.
        """
        image_header = _ImageHeaderFactory(stream)
        if filename is None:
            filename = 'image.%s' % image_header.default_ext
        return cls(blob, filename, image_header)


Instruction:
Can you generate the documentation for the following Python 3 function
def add_run(self, text=None, style=None):
        r = self._p.add_r()
        run = Run(r, self)
        if text:
            run.text = text
        if style:
            run.style = style
        return run

Response:
Append a run to this paragraph containing text and having character
        style identified by style ID.


Instruction:
Given the following Python 3 function, write the documentation
def insert_paragraph_before(self, text=None, style=None):
        paragraph = self._insert_paragraph_before()
        if text:
            paragraph.add_run(text)
        if style is not None:
            paragraph.style = style
        return paragraph

Response: Insert a new paragraph before this one.


Instruction:
How would you implement a function in Python 3 that
returns |_ParagraphStyle| object representing the style assigned to this paragraph.

Response:
def style(self):
        """
        Read/Write. |_ParagraphStyle| object representing the style assigned
        to this paragraph. If no explicit style is assigned to this
        paragraph, its value is the default paragraph style for the document.
        A paragraph style name can be assigned in lieu of a paragraph style
        object. Assigning |None| removes any applied style, making its
        effective value the default paragraph style for the document.
        """
        style_id = self._p.style
        return self.part.get_style(style_id, WD_STYLE_TYPE.PARAGRAPH)


Instruction:
Write a Python 3 function that can
return the text of the content of this paragraph.

Response:
def text(self):
        """
        String formed by concatenating the text of each run in the paragraph.
        Tabs and line breaks in the XML are mapped to ``\\t`` and ``\\n``
        characters respectively.

        Assigning text to this property causes all existing paragraph content
        to be replaced with a single run containing the assigned text.
        A ``\\t`` character in the text is mapped to a ``<w:tab/>`` element
        and each ``\\n`` or ``\\r`` character is mapped to a line break.
        Paragraph-level formatting, such as style, is preserved. All
        run-level formatting, such as bold or italic, is removed.
        """
        text = ''
        for run in self.runs:
            text += run.text
        return text


Instruction:
Can you implement a function in Python 3 that
inserts a new paragraph before this one.

Response:
def _insert_paragraph_before(self):
        """
        Return a newly created paragraph, inserted directly before this
        paragraph.
        """
        p = self._p.add_p_before()
        return Paragraph(p, self._parent)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def serialize_for_reading(element):
    xml = etree.tostring(element, encoding='unicode', pretty_print=True)
    return XmlString(xml)

Response:
Serialize element to human - readable XML suitable for tests. No XML
    declaration.


Instruction:
Implement a function in Python 3 to
return a sequence of attribute strings parsed from attrs.

Response:
def _attr_seq(self, attrs):
        """
        Return a sequence of attribute strings parsed from *attrs*. Each
        attribute string is stripped of whitespace on both ends.
        """
        attrs = attrs.strip()
        attr_lst = attrs.split()
        return sorted(attr_lst)


Instruction:
Create a Python 3 function for
returning True if the element in line_2 is XML equivalent to the element in line.

Response:
def _eq_elm_strs(self, line, line_2):
        """
        Return True if the element in *line_2* is XML equivalent to the
        element in *line*.
        """
        front, attrs, close, text = self._parse_line(line)
        front_2, attrs_2, close_2, text_2 = self._parse_line(line_2)
        if front != front_2:
            return False
        if self._attr_seq(attrs) != self._attr_seq(attrs_2):
            return False
        if close != close_2:
            return False
        if text != text_2:
            return False
        return True


Instruction:
Given the following Python 3 function, write the documentation
def _parse_line(cls, line):
        match = cls._xml_elm_line_patt.match(line)
        front, attrs, close, text = [match.group(n) for n in range(1, 5)]
        return front, attrs, close, text

Response: Parse a line of XML element - level attributes and text.


Instruction:
Can you generate the documentation for the following Python 3 function
def populate_class_members(self, element_cls, prop_name):
        self._element_cls = element_cls
        self._prop_name = prop_name

        self._add_attr_property()

Response: Populates the internal state of the class members.


Instruction:
Explain what the following Python 3 code does
def _add_attr_property(self):
        property_ = property(self._getter, self._setter, None)
        # assign unconditionally to overwrite element name definition
        setattr(self._element_cls, self._prop_name, property_)

Response: Add a read or write property to the element class that contains this attribute.


Instruction:
Create a Python 3 function for
returning a function object suitable for the get side of the attribute property descriptor.

Response:
def _getter(self):
        """
        Return a function object suitable for the "get" side of the attribute
        property descriptor.
        """
        def get_attr_value(obj):
            attr_str_value = obj.get(self._clark_name)
            if attr_str_value is None:
                return self._default
            return self._simple_type.from_xml(attr_str_value)
        get_attr_value.__doc__ = self._docstring
        return get_attr_value


Instruction:
Explain what the following Python 3 code does
def _setter(self):
        def set_attr_value(obj, value):
            if value is None or value == self._default:
                if self._clark_name in obj.attrib:
                    del obj.attrib[self._clark_name]
                return
            str_value = self._simple_type.to_xml(value)
            obj.set(self._clark_name, str_value)
        return set_attr_value

Response:
Returns a function object suitable for the set side of the attribute
            property descriptor.


Instruction:
How would you explain what the following Python 3 function does
def _getter(self):
        def get_attr_value(obj):
            attr_str_value = obj.get(self._clark_name)
            if attr_str_value is None:
                raise InvalidXmlError(
                    "required '%s' attribute not present on element %s" %
                    (self._attr_name, obj.tag)
                )
            return self._simple_type.from_xml(attr_str_value)
        get_attr_value.__doc__ = self._docstring
        return get_attr_value

Response:
Return a function object suitable for the get side of the attribute
            property descriptor.


Instruction:
How would you code a function in Python 3 to
return a function object suitable for the set side of the attribute property descriptor.

Response:
def _setter(self):
        """
        Return a function object suitable for the "set" side of the attribute
        property descriptor.
        """
        def set_attr_value(obj, value):
            str_value = self._simple_type.to_xml(value)
            obj.set(self._clark_name, str_value)
        return set_attr_value


Instruction:
Can you write a function in Python 3 where it
adds an _add_x method to the element class for this childCOOKIE.

Response:
def _add_adder(self):
        """
        Add an ``_add_x()`` method to the element class for this child
        element.
        """
        def _add_child(obj, **attrs):
            new_method = getattr(obj, self._new_method_name)
            child = new_method()
            for key, value in attrs.items():
                setattr(child, key, value)
            insert_method = getattr(obj, self._insert_method_name)
            insert_method(child)
            return child

        _add_child.__doc__ = (
            'Add a new ``<%s>`` child element unconditionally, inserted in t'
            'he correct sequence.' % self._nsptagname
        )
        self._add_to_class(self._add_method_name, _add_child)


Instruction:
Explain what the following Python 3 code does
def _add_creator(self):
        creator = self._creator
        creator.__doc__ = (
            'Return a "loose", newly created ``<%s>`` element having no attri'
            'butes, text, or children.' % self._nsptagname
        )
        self._add_to_class(self._new_method_name, creator)

Response:
Add a creator method to the element class that creates
        a new empty element of the correct type and no attributes.


Instruction:
Implement a Python 3 function for
adding a read - only property to the element class for this child element.

Response:
def _add_getter(self):
        """
        Add a read-only ``{prop_name}`` property to the element class for
        this child element.
        """
        property_ = property(self._getter, None, None)
        # assign unconditionally to overwrite element name definition
        setattr(self._element_cls, self._prop_name, property_)


Instruction:
Can you tell what is the following Python 3 function doing
def _add_inserter(self):
        def _insert_child(obj, child):
            obj.insert_element_before(child, *self._successors)
            return child

        _insert_child.__doc__ = (
            'Return the passed ``<%s>`` element after inserting it as a chil'
            'd in the correct sequence.' % self._nsptagname
        )
        self._add_to_class(self._insert_method_name, _insert_child)

Response: Add an insert_x method to the element class for this childCOOKIE.


Instruction:
Can you write a function in Python 3 where it
adds a read - only property to the element class to retrieve a list of child elements matching this type.

Response:
def _add_list_getter(self):
        """
        Add a read-only ``{prop_name}_lst`` property to the element class to
        retrieve a list of child elements matching this type.
        """
        prop_name = '%s_lst' % self._prop_name
        property_ = property(self._list_getter, None, None)
        setattr(self._element_cls, prop_name, property_)


Instruction:
Make a summary of the following Python 3 code
def _add_public_adder(self):
        def add_child(obj):
            private_add_method = getattr(obj, self._add_method_name)
            child = private_add_method()
            return child

        add_child.__doc__ = (
            'Add a new ``<%s>`` child element unconditionally, inserted in t'
            'he correct sequence.' % self._nsptagname
        )
        self._add_to_class(self._public_add_method_name, add_child)

Response: Add a public add_x method to the parent element class.


Instruction:
Can you create a Python 3 function that
adds a method to the target class.

Response:
def _add_to_class(self, name, method):
        """
        Add *method* to the target class as *name*, unless *name* is already
        defined on the class.
        """
        if hasattr(self._element_cls, name):
            return
        setattr(self._element_cls, name, method)


Instruction:
Make a summary of the following Python 3 code
def _getter(self):
        def get_child_element(obj):
            return obj.find(qn(self._nsptagname))
        get_child_element.__doc__ = (
            '``<%s>`` child element or |None| if not present.'
            % self._nsptagname
        )
        return get_child_element

Response:
Return a function object suitable for the get side of the property
        descriptor. This default getter returns the child element with the specified tag name or |None| if not present.


Instruction:
Create a Python 3 function for
returning a function object suitable for the get side of a list property descriptor.

Response:
def _list_getter(self):
        """
        Return a function object suitable for the "get" side of a list
        property descriptor.
        """
        def get_child_element_list(obj):
            return obj.findall(qn(self._nsptagname))
        get_child_element_list.__doc__ = (
            'A list containing each of the ``<%s>`` child elements, in the o'
            'rder they appear.' % self._nsptagname
        )
        return get_child_element_list


Instruction:
Can you implement a function in Python 3 that
populates the internal state of the object with the appropriate methods to the class members.

Response:
def populate_class_members(
            self, element_cls, group_prop_name, successors):
        """
        Add the appropriate methods to *element_cls*.
        """
        self._element_cls = element_cls
        self._group_prop_name = group_prop_name
        self._successors = successors

        self._add_getter()
        self._add_creator()
        self._add_inserter()
        self._add_adder()
        self._add_get_or_change_to_method()


Instruction:
Can you write a function in Python 3 where it
adds a get_or_change_to_x method to the element class for thisCOOKIE.

Response:
def _add_get_or_change_to_method(self):
        """
        Add a ``get_or_change_to_x()`` method to the element class for this
        child element.
        """
        def get_or_change_to_child(obj):
            child = getattr(obj, self._prop_name)
            if child is not None:
                return child
            remove_group_method = getattr(
                obj, self._remove_group_method_name
            )
            remove_group_method()
            add_method = getattr(obj, self._add_method_name)
            child = add_method()
            return child

        get_or_change_to_child.__doc__ = (
            'Return the ``<%s>`` child, replacing any other group element if'
            ' found.'
        ) % self._nsptagname
        self._add_to_class(
            self._get_or_change_to_method_name, get_or_change_to_child
        )


Instruction:
Write a Python 3 script for
calculating property name from tag name e. g. a : schemeClr

Response:
def _prop_name(self):
        """
        Calculate property name from tag name, e.g. a:schemeClr -> schemeClr.
        """
        if ':' in self._nsptagname:
            start = self._nsptagname.index(':') + 1
        else:
            start = 0
        return self._nsptagname[start:]


Instruction:
Can you tell what is the following Python 3 function doing
def populate_class_members(self, element_cls, prop_name):
        super(OneAndOnlyOne, self).populate_class_members(
            element_cls, prop_name
        )
        self._add_getter()

Response: Add the appropriate methods to element_cls.


Instruction:
Here you have a function in Python 3, explain what it does
def populate_class_members(self, element_cls, prop_name):
        super(OneOrMore, self).populate_class_members(
            element_cls, prop_name
        )
        self._add_list_getter()
        self._add_creator()
        self._add_inserter()
        self._add_adder()
        self._add_public_adder()
        delattr(element_cls, prop_name)

Response: Add the appropriate methods to element_cls.


Instruction:
Implement a Python 3 function for
adding the appropriate methods to element_cls.

Response:
def populate_class_members(self, element_cls, prop_name):
        """
        Add the appropriate methods to *element_cls*.
        """
        super(ZeroOrOne, self).populate_class_members(element_cls, prop_name)
        self._add_getter()
        self._add_creator()
        self._add_inserter()
        self._add_adder()
        self._add_get_or_adder()
        self._add_remover()


Instruction:
Write a Python 3 function for
adding a get_or_add_x method to the element class for thisCOOKIE.

Response:
def _add_get_or_adder(self):
        """
        Add a ``get_or_add_x()`` method to the element class for this
        child element.
        """
        def get_or_add_child(obj):
            child = getattr(obj, self._prop_name)
            if child is None:
                add_method = getattr(obj, self._add_method_name)
                child = add_method()
            return child
        get_or_add_child.__doc__ = (
            'Return the ``<%s>`` child element, newly added if not present.'
        ) % self._nsptagname
        self._add_to_class(self._get_or_add_method_name, get_or_add_child)


Instruction:
Explain what the following Python 3 code does
def _add_remover(self):
        def _remove_child(obj):
            obj.remove_all(self._nsptagname)
        _remove_child.__doc__ = (
            'Remove all ``<%s>`` child elements.'
        ) % self._nsptagname
        self._add_to_class(self._remove_method_name, _remove_child)

Response: Add a remove_all method to the element class for this childCOOKIE.


Instruction:
Write a Python 3 script for
adding the appropriate methods to element_cls.

Response:
def populate_class_members(self, element_cls, prop_name):
        """
        Add the appropriate methods to *element_cls*.
        """
        super(ZeroOrOneChoice, self).populate_class_members(
            element_cls, prop_name
        )
        self._add_choice_getter()
        for choice in self._choices:
            choice.populate_class_members(
                element_cls, self._prop_name, self._successors
            )
        self._add_group_remover()


Instruction:
Explain what the following Python 3 code does
def _add_choice_getter(self):
        property_ = property(self._choice_getter, None, None)
        # assign unconditionally to overwrite element name definition
        setattr(self._element_cls, self._prop_name, property_)

Response:
Add a read - only getter property to the element class that returns the present member of this group or None if none are
        present.


Instruction:
Implement a Python 3 function for
adding a remove_eg_x method to the element class for this choice group.

Response:
def _add_group_remover(self):
        """
        Add a ``_remove_eg_x()`` method to the element class for this choice
        group.
        """
        def _remove_choice_group(obj):
            for tagname in self._member_nsptagnames:
                obj.remove_all(tagname)

        _remove_choice_group.__doc__ = (
            'Remove the current choice group child element if present.'
        )
        self._add_to_class(
            self._remove_choice_group_method_name, _remove_choice_group
        )


Instruction:
How would you explain what the following Python 3 function does
def _choice_getter(self):
        def get_group_member_element(obj):
            return obj.first_child_found_in(*self._member_nsptagnames)
        get_group_member_element.__doc__ = (
            'Return the child element belonging to this element group, or '
            '|None| if no member child is present.'
        )
        return get_group_member_element

Response:
Return a function object suitable for the get side of the property
            descriptor.


Instruction:
Can you generate the documentation for the following Python 3 function
def first_child_found_in(self, *tagnames):
        for tagname in tagnames:
            child = self.find(qn(tagname))
            if child is not None:
                return child
        return None

Response: Return the first child found with tag in tagnames.


Instruction:
How would you implement a function in Python 3 that
removes all child elements whose tagname appears in tagnames*.

Response:
def remove_all(self, *tagnames):
        """
        Remove all child elements whose tagname (e.g. 'a:p') appears in
        *tagnames*.
        """
        for tagname in tagnames:
            matching = self.findall(qn(tagname))
            for child in matching:
                self.remove(child)


Instruction:
Can you write a function in Python 3 where it
overrides of lxml. _Element. xpath method to provide standard Open XML namespace mapping.

Response:
def xpath(self, xpath_str):
        """
        Override of ``lxml`` _Element.xpath() method to provide standard Open
        XML namespace mapping (``nsmap``) in centralized location.
        """
        return super(BaseOxmlElement, self).xpath(
            xpath_str, namespaces=nsmap
        )


Instruction:
Write a Python 3 script for
returning the value of the RGB color property of the current locale.

Response:
def rgb(self):
        """
        An |RGBColor| value or |None| if no RGB color is specified.

        When :attr:`type` is `MSO_COLOR_TYPE.RGB`, the value of this property
        will always be an |RGBColor| value. It may also be an |RGBColor|
        value if :attr:`type` is `MSO_COLOR_TYPE.THEME`, as Word writes the
        current value of a theme color when one is assigned. In that case,
        the RGB value should be interpreted as no more than a good guess
        however, as the theme color takes precedence at rendering time. Its
        value is |None| whenever :attr:`type` is either |None| or
        `MSO_COLOR_TYPE.AUTO`.

        Assigning an |RGBColor| value causes :attr:`type` to become
        `MSO_COLOR_TYPE.RGB` and any theme color is removed. Assigning |None|
        causes any color to be removed such that the effective color is
        inherited from the style hierarchy.
        """
        color = self._color
        if color is None:
            return None
        if color.val == ST_HexColorAuto.AUTO:
            return None
        return color.val


Instruction:
Can you implement a function in Python 3 that
returns the value of the themeColor property of the current locale.

Response:
def theme_color(self):
        """
        A member of :ref:`MsoThemeColorIndex` or |None| if no theme color is
        specified. When :attr:`type` is `MSO_COLOR_TYPE.THEME`, the value of
        this property will always be a member of :ref:`MsoThemeColorIndex`.
        When :attr:`type` has any other value, the value of this property is
        |None|.

        Assigning a member of :ref:`MsoThemeColorIndex` causes :attr:`type`
        to become `MSO_COLOR_TYPE.THEME`. Any existing RGB value is retained
        but ignored by Word. Assigning |None| causes any color specification
        to be removed such that the effective color is inherited from the
        style hierarchy.
        """
        color = self._color
        if color is None or color.themeColor is None:
            return None
        return color.themeColor


Instruction:
Can you create a Python 3 function that
reads - only. A member of MsoColorType one of RGB THEME or MSO_COLOR_TYPE. AUTO or MSO_COLOR_TYPE. RGB or MSO_COLOR_TYPE. THEME or MSO_COLOR_TYPE. AUTO.

Response:
def type(self):
        """
        Read-only. A member of :ref:`MsoColorType`, one of RGB, THEME, or
        AUTO, corresponding to the way this color is defined. Its value is
        |None| if no color is applied at this level, which causes the
        effective color to be inherited from the style hierarchy.
        """
        color = self._color
        if color is None:
            return None
        if color.themeColor is not None:
            return MSO_COLOR_TYPE.THEME
        if color.val == ST_HexColorAuto.AUTO:
            return MSO_COLOR_TYPE.AUTO
        return MSO_COLOR_TYPE.RGB


Instruction:
Implement a function in Python 3 to
return the type of this inline shape as a member of WD_INLINE_SHAPE.

Response:
def type(self):
        """
        The type of this inline shape as a member of
        ``docx.enum.shape.WD_INLINE_SHAPE``, e.g. ``LINKED_PICTURE``.
        Read-only.
        """
        graphicData = self._inline.graphic.graphicData
        uri = graphicData.uri
        if uri == nsmap['pic']:
            blip = graphicData.pic.blipFill.blip
            if blip.link is not None:
                return WD_INLINE_SHAPE.LINKED_PICTURE
            return WD_INLINE_SHAPE.PICTURE
        if uri == nsmap['c']:
            return WD_INLINE_SHAPE.CHART
        if uri == nsmap['dgm']:
            return WD_INLINE_SHAPE.SMART_ART
        return WD_INLINE_SHAPE.NOT_IMPLEMENTED


Instruction:
Create a Python 3 function to
extract the data from a Plotly Figure and returns a DataFrame or list of DataFrame objects.

Response:
def to_df(figure):
    """
    Extracts the data from a Plotly Figure

    Parameters
    ----------
        figure : plotly_figure
            Figure from which data will be
            extracted

        Returns a DataFrame or list of DataFrame
    """
    dfs=[]
    for trace in figure['data']:
        if 'scatter' in trace['type']:
            try:
                if type(trace['x'][0])==float:
                    index=trace['x']
                else:
                    index=pd.to_datetime(trace['x'])
            except:
                index=trace['x']
            if 'marker' in trace:
                d={}
                if 'size' in trace['marker']:
                    size=trace['marker']['size']
                    if type(size)!=list:
                        size=[size]*len(index)
                    d['size']=size
                if 'text' in trace:
                    d['text']=trace['text']
                if 'name' in trace:
                    name=trace['name']
                    if type(name)!=list:
                        name=[name]*len(index)
                    d['categories']=name
                d['y']=trace['y']
                d['x']=trace['x']
                if 'z' in trace:
                    d['z']=trace['z']
                df=pd.DataFrame(d)
            else:
                df=pd.Series(trace['y'],index=index,name=trace['name'])
            dfs.append(df)
        elif trace['type'] in ('heatmap','surface'):
            df=pd.DataFrame(trace['z'].transpose(),index=trace['x'],columns=trace['y'])
            dfs.append(df)
        elif trace['type'] in ('box','histogram'):
            vals=trace['x'] if 'x' in trace else trace['y']
            df=pd.DataFrame({trace['name']:vals})
            dfs.append(df)
    if max(list(map(len,dfs)))==min(list(map(len,dfs))):
        if len(dfs)==1:
            return dfs[0]
        else:
            if type(dfs[0])==pd.core.series.Series:
                return pd.concat(dfs,axis=1)
            if all(dfs[0].columns==dfs[1].columns):
                    return pd.concat(dfs,axis=0)
            else:
                return pd.concat(dfs,axis=1)
    else:
        try:
            return pd.concat(dfs)
        except:
            return dfs


Instruction:
Can you write a function in Python 3 where it
converts from hex or rgb to rgba

Response:
def to_rgba(color, alpha):
    """
    Converts from hex|rgb to rgba

    Parameters:
    -----------
            color : string
                    Color representation on hex or rgb
            alpha : float
                    Value from 0 to 1.0 that represents the
                    alpha value.

    Example:
            to_rgba('#E1E5ED',0.6)
            to_rgba('#f03',0.7)
            to_rgba('rgb(23,23,23)',.5)
    """
    if type(color) == tuple:
        color, alpha = color
    color = color.lower()
    if 'rgba' in color:
        cl = list(eval(color.replace('rgba', '')))
        if alpha:
            cl[3] = alpha
        return 'rgba' + str(tuple(cl))
    elif 'rgb' in color:
        r, g, b = eval(color.replace('rgb', ''))
        return 'rgba' + str((r, g, b, alpha))
    else:
        return to_rgba(hex_to_rgb(color), alpha)


Instruction:
Can you create a Python 3 function that
converts from hex to rgb

Response:
def hex_to_rgb(color):
    """
    Converts from hex to rgb

    Parameters:
    -----------
            color : string
                    Color representation on hex or rgb

    Example:
            hex_to_rgb('#E1E5ED')
            hex_to_rgb('#f03')
    """
    color = normalize(color)
    color = color[1:]
    # return 'rgb'+str(tuple(ord(c) for c in color.decode('hex')))
    return 'rgb' + str((int(color[0:2], base=16), int(color[2:4], base=16), int(color[4:6], base=16)))


Instruction:
How would you code a function in Python 3 to
normalize a string in rgba or rgb format

Response:
def normalize(color):
    """
    Returns an hex color

    Parameters:
    -----------
            color : string
                    Color representation in rgba|rgb|hex

    Example:
            normalize('#f03')
    """
    if type(color) == tuple:
        color = to_rgba(*color)
    if 'rgba' in color:
        return rgb_to_hex(rgba_to_rgb(color))
    elif 'rgb' in color:
        return rgb_to_hex(color)
    elif '#' in color:
        if len(color) == 7:
            return color
        else:
            color = color[1:]
            return '#' + ''.join([x * 2 for x in list(color)])
    else:
        try:
            return normalize(cnames[color.lower()])
        except:
            raise CufflinksError('Not a valid color: ' + color)


Instruction:
How would you explain what the following Python 3 function does
def rgb_to_hex(color):
    rgb = eval(color.replace('rgb', ''))
    # return '#'+''.join(map(chr, rgb)).encode('hex')
    return '#' + ''.join(['{0:02x}'.format(x).upper() for x in rgb])

Response: Converts from rgb to hex


Instruction:
Can you tell what is the following Python 3 function doing
def rgba_to_rgb(color, bg='rgb(255,255,255)'):
    def c_tup(c):
        return eval(c[c.find('('):])
    color = c_tup(color)
    bg = hex_to_rgb(normalize(bg))
    bg = c_tup(bg)
    a = color[3]
    r = [int((1 - a) * bg[i] + a * color[i]) for i in range(3)]
    return 'rgb' + str(tuple(r))

Response: Converts from rgba to rgb


Instruction:
How would you implement a function in Python 3 that
converts from hex to hsv

Response:
def hex_to_hsv(color):
    """
    Converts from hex to hsv

    Parameters:
    -----------
            color : string
                    Color representation on color

    Example:
            hex_to_hsv('#ff9933')
    """
    color = normalize(color)
    color = color[1:]
    # color=tuple(ord(c)/255.0 for c in color.decode('hex'))
    color = (int(color[0:2], base=16) / 255.0, int(color[2:4],
                                                   base=16) / 255.0, int(color[4:6], base=16) / 255.0)
    return colorsys.rgb_to_hsv(*color)


Instruction:
How would you code a function in Python 3 to
generate a scale of colours from a base colour.

Response:
def color_range(color, N=20):
    """
    Generates a scale of colours from a base colour

    Parameters:
    -----------
            color : string
                    Color representation in hex
            N   : int
                    number of colours to generate

    Example:
            color_range('#ff9933',20)
    """
    color = normalize(color)
    org = color
    color = hex_to_hsv(color)
    HSV_tuples = [(color[0], x, color[2]) for x in np.arange(0, 1, 2.0 / N)]
    HSV_tuples.extend([(color[0], color[1], x)
                       for x in np.arange(0, 1, 2.0 / N)])
    hex_out = []
    for c in HSV_tuples:
        c = colorsys.hsv_to_rgb(*c)
        c = [int(_ * 255) for _ in c]
        # hex_out.append("#"+"".join([chr(x).encode('hex') for x in c]))
        hex_out.append("#" + "".join(['{0:02x}'.format(x) for x in c]))
    if org not in hex_out:
        hex_out.append(org)
    hex_out.sort()
    return hex_out


Instruction:
How would you explain what the following Python 3 function does
def color_table(color, N=1, sort=False, sort_values=False, inline=False, as_html=False):
    if isinstance(color, list):
        c_ = ''
        rgb_tup = [normalize(c) for c in color]
        if sort:
            rgb_tup.sort()
    elif isinstance(color, dict):
        c_ = ''
        items = [(k, normalize(v), hex_to_hsv(normalize(v)))
                 for k, v in list(color.items())]
        if sort_values:
            items = sorted(items, key=operator.itemgetter(2))
        elif sort:
            items = sorted(items, key=operator.itemgetter(0))
        rgb_tup = [(k, v) for k, v, _ in items]
    else:
        c_ = normalize(color)
        if N > 1:
            rgb_tup = np.array(color_range(c_, N))[::-1]
        else:
            rgb_tup = [c_]

    def _color(c):
        if hex_to_hsv(c)[2] < .5:
            color = "#ffffff"
            shadow = '0 1px 0 #000'
        else:
            color = "#000000"
            shadow = '0 1px 0 rgba(255,255,255,0.6)'
        if c == c_:
            border = " border: 1px solid #ffffff;"
        else:
            border = ''
        return color, shadow, border

    s = '
' if not inline else ''
    for c in rgb_tup:
        if isinstance(c, tuple):
            k, c = c
            k += ' : '
        else:
            k = ''
        if inline:
            s += '

'.format(
                c)
        else:
            color, shadow, border = _color(c)
            s += """

            """ + k + c.upper() + """

"""
    s += '
' if not inline else ''
    if as_html:
        return s
    return display(HTML(s))

Response: Generates a colour table for a single or multi - line color.


Instruction:
Implement a Python 3 function for
generating a generator that yields a list of colors and gradients of those colors.

Response:
def colorgen(colors=None, n=None, scale=None, theme=None):
    """
    Returns a generator with a list of colors
    and gradients of those colors

    Parameters:
    -----------
            colors : list(colors)
                    List of colors to use

    Example:
            colorgen()
            colorgen(['blue','red','pink'])
            colorgen(['#f03','rgb(23,25,25)'])
    """
    from .themes import THEMES
    step = .1
    if not colors:
        if not scale:
            if not theme:
                scale = get_config_file()['colorscale']
            else:
                scale = THEMES[theme]['colorscale']
        colors = get_scales(scale)
    dq = deque(colors)
    if len(dq) == 0:
        dq = deque(get_scales('ggplot'))
    if n:
        step = len(dq) * 0.8 / n if len(dq) * 8 < n else .1
    for i in np.arange(.2, 1, step):
        for y in dq:
            yield to_rgba(y, 1 - i + .2)
        dq.rotate(1)


Instruction:
Write a Python 3 function that can
display a list of available color scales for the current locale.

Response:
def scales(scale=None):
    """
    Displays a color scale (HTML)

    Parameters:
    -----------
            scale : str
                    Color scale name
                    If no scale name is provided then all scales are returned
                            (max number for each scale)
                    If scale='all' then all scale combinations available
                            will be returned

    Example:
            scales('accent')
            scales('all')
            scales()
    """
    if scale:
        if scale == 'all':
            display(HTML(cl.to_html(_scales)))
        else:
            display(HTML(cl.to_html(get_scales(scale))))
    else:
        s = ''
        keys = list(_scales_names.keys())
        keys.sort()
        for k in keys:
            scale = get_scales(k)
            s += '

{0}
{1}
'.format(
                k, cl.to_html(scale))
        display(HTML(s))


Instruction:
How would you code a function in Python 3 to
return a list of colors available for a given scale.

Response:
def get_scales(scale=None, n=None):
    """
    Returns a color scale

    Parameters:
    -----------
            scale : str
                    Color scale name
                    If the color name is preceded by a minus (-)
                    then the scale is inversed
            n : int
                    Number of colors
                    If n < number of colors available for a given scale then
                            the minimum number will be returned
                    If n > number of colors available for a given scale then
                            the maximum number will be returned

    Example:
            get_scales('accent',8)
            get_scales('pastel1')
    """
    if scale:
        is_reverse = False
        if scale[0] == '-':
            scale = scale[1:]
            is_reverse = True
        d = copy.deepcopy(_scales_names[scale.lower()])
        keys = list(map(int, list(d.keys())))
        cs = None
        if n:
            if n in keys:
                cs = d[str(n)]
            elif n < min(keys):
                cs = d[str(min(keys))]
        if cs is None:
            cs = d[str(max(keys))]
        if is_reverse:
            cs.reverse()
        return cs
    else:
        d = {}
        for k, v in list(_scales_names.items()):
            if isinstance(v, dict):
                keys = list(map(int, list(v.keys())))
                d[k] = v[str(max(keys))]
            else:
                d[k] = v
        return d


Instruction:
Write a Python 3 script to
return a color scale to be used for a plotly figure.

Response:
def get_colorscale(scale):
    """
    Returns a color scale to be used for a plotly figure

    Parameters:
    -----------
            scale : str or list
                    Color scale name
                    If the color name is preceded by a minus (-)
                    then the scale is inversed.
                    Also accepts a list of colors (rgb,rgba,hex)

    Example:
            get_colorscale('accent')
            get_colorscale(['rgb(127,201,127)','rgb(190,174,212)','rgb(253,192,134)'])
    """

    if type(scale) in string_types:
        scale = get_scales(scale)
    else:
        if type(scale) != list:
            raise Exception(
                "scale needs to be either a scale name or list of colors")

    cs = [[1.0 * c / (len(scale) - 1), scale[c]] for c in range(len(scale))]
    cs.sort()
    return cs


Instruction:
Can you generate the documentation for the following Python 3 function
def _to_iplot(self,colors=None,colorscale=None,kind='scatter',mode='lines',interpolation='linear',symbol='dot',size='12',fill=False,
		width=3,dash='solid',sortbars=False,keys=False,bestfit=False,bestfit_colors=None,opacity=0.6,
		mean=False,mean_colors=None,asDates=False,asTimestamp=False,text=None,**kwargs):
	"""
	Generates a plotly Data object

	Parameters
	----------
		colors : list or dict
			{key:color} to specify the color for each column
			[colors] to use the colors in the defined order
		colorscale : str
			Color scale name
			Only valid if 'colors' is null
			See cufflinks.colors.scales() for available scales
		kind : string
			Kind of chart
				scatter
				bar
		mode : string
			Plotting mode for scatter trace
				lines
				markers
				lines+markers
				lines+text
				markers+text
				lines+markers+text
		interpolation : string
			Positioning of the connecting lines
				linear
				spline
				vhv
				hvh
				vh
				hv
		symbol : string
			The symbol that is drawn on the plot for each marker
			Valid only when mode includes markers
				circle
				circle-dot
				diamond
				square
				and many more...(see plotly.validators.scatter.marker.SymbolValidator.values)
		size : string or int
			Size of marker
			Valid only if marker in mode
		fill : bool
			Filled Traces
		width : int
			Line width
		dash : string
			Drawing style of lines
				solid
				dash
				dashdot
				dot
		sortbars : boole
			Sort bars in descending order
			* Only valid when kind='bar'
		keys : list of columns
			List of columns to chart.
			Also can be usded for custom sorting.
		bestfit : boolean or list
			If True then a best fit line will be generated for
			all columns.
			If list then a best fit line will be generated for
			each key on the list.
		bestfit_colors : list or dict
			{key:color} to specify the color for each column
			[colors] to use the colors in the defined order
		asDates : bool
			If true it forces truncates times from a DatetimeIndex

	"""
	df=self.copy()

	if asTimestamp:
		x=[_ for _ in df.index]
	elif df.index.__class__.__name__ in ('PeriodIndex','DatetimeIndex'):
		if asDates:
			df.index=df.index.date
		x=df.index.format()
	elif isinstance(df.index,pd.MultiIndex):
		x=['({0})'.format(','.join([str(__) for __ in _])) for _ in df.index.values]
	else:
		x = df.index.values
	lines={}
	if type(df)==pd.core.series.Series:
		df=pd.DataFrame({df.name:df})

	if not keys:
		if 'bar' in kind:
			if sortbars:
				keys=list(df.sum().sort_values(ascending=False).keys())
			else:
				keys=list(df.keys())
		else:
			keys=list(df.keys())

	colors=get_colors(colors,colorscale,keys)
	dash=get_items_as_list(dash,keys,'dash')
	symbol=get_items_as_list(symbol,keys,'symbol')
	mode=get_items_as_list(mode,keys,'mode')
	interpolation=get_items_as_list(interpolation,keys,'interpolation')
	width=get_items_as_list(width,keys,'width')
	for key in keys:
		lines[key]={}
		lines[key]["x"]=x
		lines[key]["y"]=df[key].fillna('').values
		lines[key]["name"]=str(key)
		if text is not None:
			lines[key]["text"]=text
		if 'bar' in kind:
			lines[key]["marker"]={'color':to_rgba(colors[key],opacity),'line':{'color':colors[key],'width':1}}
		else:
			lines[key]["line"]={'color':colors[key],'width':width[key],'dash':dash[key], 'shape':interpolation[key]}
			lines[key]["mode"]=mode[key]
			if 'marker' in mode[key]:
				lines[key]["marker"]=dict(symbol=symbol[key],size=size)
			if fill:
				lines[key]["fill"]='tonexty' if kind=='area' else 'tozeroy'
				lines[key]["fillcolor"]=to_rgba(colors[key],kwargs['opacity'] if 'opacity' in kwargs else .3		)
	if 'bar' in kind:
		lines_plotly=[Bar(lines[key]).to_plotly_json() for key in keys]
	else:
		lines_plotly=[Scatter(lines[key]).to_plotly_json() for key in keys]
	for trace in lines_plotly:
		if isinstance(trace['name'],pd.Timestamp):
			trace.update(name=str(trace['name']))

	if bestfit:
		if type(bestfit)==list:
			keys=bestfit
		d={}
		for key in keys:
			bestfit=df[key].bestfit()
			d[bestfit.formula]=bestfit
		bestfit_lines=pd.DataFrame(d).to_iplot(bestfit=False,colors=bestfit_colors,kind='scatter',asTimestamp=asTimestamp)
		for line in bestfit_lines:
			line['line']['dash']='dash'
			if not bestfit_colors:
				line['line']['color']=to_rgba(line['line']['color'],.6)
		data=lines_plotly
		data.extend(bestfit_lines)
		return data

	if mean:
		if type(mean)==list:
			keys=mean
		d={}
		for key in keys:
			mean=df[key].mean()
			d['MEAN({key})'.format(key=key)]=pd.Series([mean]*len(df[key]),index=df[key].index)
		mean_lines=pd.DataFrame(d).to_iplot(mean=False,colors=mean_colors,kind='scatter',asTimestamp=asTimestamp)
		for line in mean_lines:
			line['line']['dash']='dash'
			if not mean_colors:
				line['line']['color']=to_rgba(line['line']['color'],.6)
		data=[lines_plotly]
		data.extend(mean_lines)
		return data
	return lines_plotly

Response: This function returns a string that can be used to create a plotly object for the given object.