Instruction:
Can you generate the documentation for the following Python 3 function
def receive_bytes(self, data):
        i = 0
        n = len(data)
        responses = []
        while i < n:

            # Not receiving is the state of reading the payload header
            if not self._receiving:
                bytes_to_read = min(4 - self._header.tell(), n - i)
                self._header.write(data[i:i+bytes_to_read])
                i += bytes_to_read

                if self._header.tell() == 4:
                    self._header.seek(0)
                    nbytes = Int32.decode(self._header)
                    # reset buffer and switch state to receiving payload bytes
                    self._rbuffer = KafkaBytes(nbytes)
                    self._receiving = True
                elif self._header.tell() > 4:
                    raise Errors.KafkaError('this should not happen - are you threading?')

            if self._receiving:
                total_bytes = len(self._rbuffer)
                staged_bytes = self._rbuffer.tell()
                bytes_to_read = min(total_bytes - staged_bytes, n - i)
                self._rbuffer.write(data[i:i+bytes_to_read])
                i += bytes_to_read

                staged_bytes = self._rbuffer.tell()
                if staged_bytes > total_bytes:
                    raise Errors.KafkaError('Receive buffer has more bytes than expected?')

                if staged_bytes != total_bytes:
                    break

                self._receiving = False
                self._rbuffer.seek(0)
                resp = self._process_response(self._rbuffer)
                responses.append(resp)
                self._reset_buffer()
        return responses

Response: Process bytes received from a Kafka broker to a Kafka broker.


Instruction:
Can you generate the documentation for the following Python 3 function
def _get_conn(self, host, port, afi):
        host_key = (host, port)
        if host_key not in self._conns:
            self._conns[host_key] = BrokerConnection(
                host, port, afi,
                request_timeout_ms=self.timeout * 1000,
                client_id=self.client_id
            )

        conn = self._conns[host_key]
        if not conn.connect_blocking(self.timeout):
            conn.close()
            raise KafkaConnectionError("%s:%s (%s)" % (host, port, afi))
        return conn

Response: Get or create a connection to a broker using host and port


Instruction:
Create a Python 3 function to
return the leader for a topic and partition.

Response:
def _get_leader_for_partition(self, topic, partition):
        """
        Returns the leader for a partition or None if the partition exists
        but has no leader.

        Raises:
            UnknownTopicOrPartitionError: If the topic or partition is not part
                of the metadata.
            LeaderNotAvailableError: If the server has metadata, but there is no
        current leader.
        """

        key = TopicPartition(topic, partition)

        # Use cached metadata if it is there
        if self.topics_to_brokers.get(key) is not None:
            return self.topics_to_brokers[key]

        # Otherwise refresh metadata

        # If topic does not already exist, this will raise
        # UnknownTopicOrPartitionError if not auto-creating
        # LeaderNotAvailableError otherwise until partitions are created
        self.load_metadata_for_topics(topic)

        # If the partition doesn't actually exist, raise
        if partition not in self.topic_partitions.get(topic, []):
            raise UnknownTopicOrPartitionError(key)

        # If there's no leader for the partition, raise
        leader = self.topic_partitions[topic][partition]
        if leader == -1:
            raise LeaderNotAvailableError((topic, partition))

        # Otherwise return the BrokerMetadata
        return self.brokers[leader]


Instruction:
Given the following Python 3 function, write the documentation
def _get_coordinator_for_group(self, group):

        resp = self.send_consumer_metadata_request(group)

        # If there's a problem with finding the coordinator, raise the
        # provided error
        kafka.errors.check_error(resp)

        # Otherwise return the BrokerMetadata
        return BrokerMetadata(resp.nodeId, resp.host, resp.port, None)

Response: Returns the coordinator broker for a given consumer group.


Instruction:
How would you code a function in Python 3 to
send a broker - aware request to all available brokers.

Response:
def _send_broker_unaware_request(self, payloads, encoder_fn, decoder_fn):
        """
        Attempt to send a broker-agnostic request to one of the available
        brokers. Keep trying until you succeed.
        """
        hosts = set()
        for broker in self.brokers.values():
            host, port, afi = get_ip_port_afi(broker.host)
            hosts.add((host, broker.port, afi))

        hosts.update(self.hosts)
        hosts = list(hosts)
        random.shuffle(hosts)

        for (host, port, afi) in hosts:
            try:
                conn = self._get_conn(host, port, afi)
            except KafkaConnectionError:
                log.warning("Skipping unconnected connection: %s:%s (AFI %s)",
                            host, port, afi)
                continue
            request = encoder_fn(payloads=payloads)
            future = conn.send(request)

            # Block
            while not future.is_done:
                for r, f in conn.recv():
                    f.success(r)

            if future.failed():
                log.error("Request failed: %s", future.exception)
                continue

            return decoder_fn(future.value)

        raise KafkaUnavailableError('All servers failed to process request: %s' % (hosts,))


Instruction:
Given the following Python 3 function, write the documentation
def _send_broker_aware_request(self, payloads, encoder_fn, decoder_fn):
        # encoders / decoders do not maintain ordering currently
        # so we need to keep this so we can rebuild order before returning
        original_ordering = [(p.topic, p.partition) for p in payloads]

        # Connection errors generally mean stale metadata
        # although sometimes it means incorrect api request
        # Unfortunately there is no good way to tell the difference
        # so we'll just reset metadata on all errors to be safe
        refresh_metadata = False

        # For each broker, send the list of request payloads
        # and collect the responses and errors
        payloads_by_broker = self._payloads_by_broker(payloads)
        responses = {}

        def failed_payloads(payloads):
            for payload in payloads:
                topic_partition = (str(payload.topic), payload.partition)
                responses[(topic_partition)] = FailedPayloadsError(payload)

        # For each BrokerConnection keep the real socket so that we can use
        # a select to perform unblocking I/O
        connections_by_future = {}
        for broker, broker_payloads in six.iteritems(payloads_by_broker):
            if broker is None:
                failed_payloads(broker_payloads)
                continue

            host, port, afi = get_ip_port_afi(broker.host)
            try:
                conn = self._get_conn(host, broker.port, afi)
            except KafkaConnectionError:
                refresh_metadata = True
                failed_payloads(broker_payloads)
                continue

            request = encoder_fn(payloads=broker_payloads)
            future = conn.send(request)

            if future.failed():
                refresh_metadata = True
                failed_payloads(broker_payloads)
                continue

            if not request.expect_response():
                for payload in broker_payloads:
                    topic_partition = (str(payload.topic), payload.partition)
                    responses[topic_partition] = None
                continue

            connections_by_future[future] = (conn, broker)

        conn = None
        while connections_by_future:
            futures = list(connections_by_future.keys())

            # block until a socket is ready to be read
            sockets = [
                conn._sock
                for future, (conn, _) in six.iteritems(connections_by_future)
                if not future.is_done and conn._sock is not None]
            if sockets:
                read_socks, _, _ = select.select(sockets, [], [])

            for future in futures:

                if not future.is_done:
                    conn, _ = connections_by_future[future]
                    for r, f in conn.recv():
                        f.success(r)
                    continue

                _, broker = connections_by_future.pop(future)
                if future.failed():
                    refresh_metadata = True
                    failed_payloads(payloads_by_broker[broker])

                else:
                    for payload_response in decoder_fn(future.value):
                        topic_partition = (str(payload_response.topic),
                                           payload_response.partition)
                        responses[topic_partition] = payload_response

        if refresh_metadata:
            self.reset_all_metadata()

        # Return responses in the same order as provided
        return [responses[tp] for tp in original_ordering]

Response: Send a list of payloads to the broker and return a list of response objects.


Instruction:
Make a summary of the following Python 3 code
def _send_consumer_aware_request(self, group, payloads, encoder_fn, decoder_fn):
        # encoders / decoders do not maintain ordering currently
        # so we need to keep this so we can rebuild order before returning
        original_ordering = [(p.topic, p.partition) for p in payloads]

        broker = self._get_coordinator_for_group(group)

        # Send the list of request payloads and collect the responses and
        # errors
        responses = {}
        request_id = self._next_id()
        log.debug('Request %s to %s: %s', request_id, broker, payloads)
        request = encoder_fn(client_id=self.client_id,
                             correlation_id=request_id, payloads=payloads)

        # Send the request, recv the response
        try:
            host, port, afi = get_ip_port_afi(broker.host)
            conn = self._get_conn(host, broker.port, afi)
        except KafkaConnectionError as e:
            log.warning('KafkaConnectionError attempting to send request %s '
                        'to server %s: %s', request_id, broker, e)

            for payload in payloads:
                topic_partition = (payload.topic, payload.partition)
                responses[topic_partition] = FailedPayloadsError(payload)

        # No exception, try to get response
        else:

            future = conn.send(request_id, request)
            while not future.is_done:
                for r, f in conn.recv():
                    f.success(r)

            # decoder_fn=None signal that the server is expected to not
            # send a response.  This probably only applies to
            # ProduceRequest w/ acks = 0
            if decoder_fn is None:
                log.debug('Request %s does not expect a response '
                          '(skipping conn.recv)', request_id)
                for payload in payloads:
                    topic_partition = (payload.topic, payload.partition)
                    responses[topic_partition] = None
                return []

            if future.failed():
                log.warning('Error attempting to receive a '
                            'response to request %s from server %s: %s',
                            request_id, broker, future.exception)

                for payload in payloads:
                    topic_partition = (payload.topic, payload.partition)
                    responses[topic_partition] = FailedPayloadsError(payload)

            else:
                response = future.value
                _resps = []
                for payload_response in decoder_fn(response):
                    topic_partition = (payload_response.topic,
                                       payload_response.partition)
                    responses[topic_partition] = payload_response
                    _resps.append(payload_response)
                log.debug('Response %s: %s', request_id, _resps)

        # Return responses in the same order as provided
        return [responses[tp] for tp in original_ordering]

Response: Send a list of requests to the broker for the specified group and return the list of responses.


Instruction:
Can you generate the documentation for the following Python 3 function
def copy(self):
        _conns = self._conns
        self._conns = {}
        c = copy.deepcopy(self)
        self._conns = _conns
        return c

Response:
Create an inactive copy of the client object suitable for passing
        to a separate thread.


Instruction:
How would you explain what the following Python 3 function does
def load_metadata_for_topics(self, *topics, **kwargs):
        if 'ignore_leadernotavailable' in kwargs:
            ignore_leadernotavailable = kwargs['ignore_leadernotavailable']
        else:
            ignore_leadernotavailable = False

        if topics:
            self.reset_topic_metadata(*topics)
        else:
            self.reset_all_metadata()

        resp = self.send_metadata_request(topics)

        log.debug('Updating broker metadata: %s', resp.brokers)
        log.debug('Updating topic metadata: %s', [topic for _, topic, _ in resp.topics])

        self.brokers = dict([(nodeId, BrokerMetadata(nodeId, host, port, None))
                             for nodeId, host, port in resp.brokers])

        for error, topic, partitions in resp.topics:
            # Errors expected for new topics
            if error:
                error_type = kafka.errors.kafka_errors.get(error, UnknownError)
                if error_type in (UnknownTopicOrPartitionError, LeaderNotAvailableError):
                    log.error('Error loading topic metadata for %s: %s (%s)',
                              topic, error_type, error)
                    if topic not in topics:
                        continue
                    elif (error_type is LeaderNotAvailableError and
                          ignore_leadernotavailable):
                        continue
                raise error_type(topic)

            self.topic_partitions[topic] = {}
            for error, partition, leader, _, _ in partitions:

                self.topic_partitions[topic][partition] = leader

                # Populate topics_to_brokers dict
                topic_part = TopicPartition(topic, partition)

                # Check for partition errors
                if error:
                    error_type = kafka.errors.kafka_errors.get(error, UnknownError)

                    # If No Leader, topics_to_brokers topic_partition -> None
                    if error_type is LeaderNotAvailableError:
                        log.error('No leader for topic %s partition %d', topic, partition)
                        self.topics_to_brokers[topic_part] = None
                        continue

                    # If one of the replicas is unavailable -- ignore
                    # this error code is provided for admin purposes only
                    # we never talk to replicas, only the leader
                    elif error_type is ReplicaNotAvailableError:
                        log.debug('Some (non-leader) replicas not available for topic %s partition %d', topic, partition)

                    else:
                        raise error_type(topic_part)

                # If Known Broker, topic_partition -> BrokerMetadata
                if leader in self.brokers:
                    self.topics_to_brokers[topic_part] = self.brokers[leader]

                # If Unknown Broker, fake BrokerMetadata so we don't lose the id
                # (not sure how this could happen. server could be in bad state)
                else:
                    self.topics_to_brokers[topic_part] = BrokerMetadata(
                        leader, None, None, None
                    )

Response: Fetch broker and topic - partition metadata for the specified topics.


Instruction:
Write a Python 3 function for
sending a ProduceRequest to the broker.

Response:
def send_produce_request(self, payloads=(), acks=1, timeout=1000,
                             fail_on_error=True, callback=None):
        """
        Encode and send some ProduceRequests

        ProduceRequests will be grouped by (topic, partition) and then
        sent to a specific broker. Output is a list of responses in the
        same order as the list of payloads specified

        Arguments:
            payloads (list of ProduceRequest): produce requests to send to kafka
                ProduceRequest payloads must not contain duplicates for any
                topic-partition.
            acks (int, optional): how many acks the servers should receive from replica
                brokers before responding to the request. If it is 0, the server
                will not send any response. If it is 1, the server will wait
                until the data is written to the local log before sending a
                response.  If it is -1, the server will wait until the message
                is committed by all in-sync replicas before sending a response.
                For any value > 1, the server will wait for this number of acks to
                occur (but the server will never wait for more acknowledgements than
                there are in-sync replicas). defaults to 1.
            timeout (int, optional): maximum time in milliseconds the server can
                await the receipt of the number of acks, defaults to 1000.
            fail_on_error (bool, optional): raise exceptions on connection and
                server response errors, defaults to True.
            callback (function, optional): instead of returning the ProduceResponse,
                first pass it through this function, defaults to None.

        Returns:
            list of ProduceResponses, or callback results if supplied, in the
            order of input payloads
        """

        encoder = functools.partial(
            KafkaProtocol.encode_produce_request,
            acks=acks,
            timeout=timeout)

        if acks == 0:
            decoder = None
        else:
            decoder = KafkaProtocol.decode_produce_response

        resps = self._send_broker_aware_request(payloads, encoder, decoder)

        return [resp if not callback else callback(resp) for resp in resps
                if resp is not None and
                (not fail_on_error or not self._raise_on_response_error(resp))]


Instruction:
How would you explain what the following Python 3 function does
def send_fetch_request(self, payloads=(), fail_on_error=True,
                           callback=None, max_wait_time=100, min_bytes=4096):
        """
        Encode and send a FetchRequest

        Payloads are grouped by topic and partition so they can be pipelined
        to the same brokers.
        """

        encoder = functools.partial(KafkaProtocol.encode_fetch_request,
                          max_wait_time=max_wait_time,
                          min_bytes=min_bytes)

        resps = self._send_broker_aware_request(
            payloads, encoder,
            KafkaProtocol.decode_fetch_response)

        return [resp if not callback else callback(resp) for resp in resps
                if not fail_on_error or not self._raise_on_response_error(resp)]

Response: Send a FetchRequest to all brokers.


Instruction:
Implement a Python 3 function for
verifying that the token is valid and that the token type and exp claims are present.

Response:
def verify(self):
        """
        Performs additional validation steps which were not performed when this
        token was decoded.  This method is part of the "public" API to indicate
        the intention that it may be overridden in subclasses.
        """
        # According to RFC 7519, the "exp" claim is OPTIONAL
        # (https://tools.ietf.org/html/rfc7519#section-4.1.4).  As a more
        # correct behavior for authorization tokens, we require an "exp"
        # claim.  We don't want any zombie tokens walking around.
        self.check_exp()

        # Ensure token id is present
        if api_settings.JTI_CLAIM not in self.payload:
            raise TokenError(_('Token has no id'))

        self.verify_token_type()


Instruction:
Explain what the following Python 3 code does
def verify_token_type(self):
        try:
            token_type = self.payload[api_settings.TOKEN_TYPE_CLAIM]
        except KeyError:
            raise TokenError(_('Token has no type'))

        if self.token_type != token_type:
            raise TokenError(_('Token has wrong type'))

Response: Verifies that the token type claim is present and has the correct value.


Instruction:
Write a Python 3 script for
updating the expiration time of a token.

Response:
def set_exp(self, claim='exp', from_time=None, lifetime=None):
        """
        Updates the expiration time of a token.
        """
        if from_time is None:
            from_time = self.current_time

        if lifetime is None:
            lifetime = self.lifetime

        self.payload[claim] = datetime_to_epoch(from_time + lifetime)


Instruction:
Can you write a function in Python 3 where it
checks whether a timestamp value in the given claim has passed since the given datetime value in current_time. Raises a TokenError if so.

Response:
def check_exp(self, claim='exp', current_time=None):
        """
        Checks whether a timestamp value in the given claim has passed (since
        the given datetime value in `current_time`).  Raises a TokenError with
        a user-facing error message if so.
        """
        if current_time is None:
            current_time = self.current_time

        try:
            claim_value = self.payload[claim]
        except KeyError:
            raise TokenError(format_lazy(_("Token has no '{}' claim"), claim))

        claim_time = datetime_from_epoch(claim_value)
        if claim_time <= current_time:
            raise TokenError(format_lazy(_("Token '{}' claim has expired"), claim))


Instruction:
How would you code a function in Python 3 to
return an authorization token for the given user.

Response:
def for_user(cls, user):
        """
        Returns an authorization token for the given user that will be provided
        after authenticating the user's credentials.
        """
        user_id = getattr(user, api_settings.USER_ID_FIELD)
        if not isinstance(user_id, int):
            user_id = str(user_id)

        token = cls()
        token[api_settings.USER_ID_CLAIM] = user_id

        return token


Instruction:
Make a summary of the following Python 3 code
def access_token(self):
        access = AccessToken()

        # Use instantiation time of refresh token as relative timestamp for
        # access token "exp" claim.  This ensures that both a refresh and
        # access token expire relative to the same time if they are created as
        # a pair.
        access.set_exp(from_time=self.current_time)

        no_copy = self.no_copy_claims
        for claim, value in self.payload.items():
            if claim in no_copy:
                continue
            access[claim] = value

        return access

Response: Returns an access token created from this refresh token.


Instruction:
Can you create a Python 3 function that
returns an encoded token for the given payload dictionary.

Response:
def encode(self, payload):
        """
        Returns an encoded token for the given payload dictionary.
        """
        token = jwt.encode(payload, self.signing_key, algorithm=self.algorithm)
        return token.decode('utf-8')


Instruction:
Implement a Python 3 function for
decoding a given token and returns its payload dictionary.

Response:
def decode(self, token, verify=True):
        """
        Performs a validation of the given token and returns its payload
        dictionary.

        Raises a `TokenBackendError` if the token is malformed, if its
        signature check fails, or if its 'exp' claim indicates it has expired.
        """
        try:
            return jwt.decode(token, self.verifying_key, algorithms=[self.algorithm], verify=verify)
        except InvalidTokenError:
            raise TokenBackendError(_('Token is invalid or expired'))


Instruction:
Explain what the following Python 3 code does
def get_header(self, request):
        header = request.META.get('HTTP_AUTHORIZATION')

        if isinstance(header, str):
            # Work around django test client oddness
            header = header.encode(HTTP_HEADER_ENCODING)

        return header

Response: Extracts the header containing the JSON web token from the given request.


Instruction:
How would you explain what the following Python 3 function does
def get_raw_token(self, header):
        parts = header.split()

        if len(parts) == 0:
            # Empty AUTHORIZATION header sent
            return None

        if parts[0] not in AUTH_HEADER_TYPE_BYTES:
            # Assume the header does not contain a JSON web token
            return None

        if len(parts) != 2:
            raise AuthenticationFailed(
                _('Authorization header must contain two space-delimited values'),
                code='bad_authorization_header',
            )

        return parts[1]

Response: Extracts an unvalidated JSON web token from the given Authorization header value.


Instruction:
Write a Python 3 script for
validating an encoded JSON web token and returns a validated token wrapper object.

Response:
def get_validated_token(self, raw_token):
        """
        Validates an encoded JSON web token and returns a validated token
        wrapper object.
        """
        messages = []
        for AuthToken in api_settings.AUTH_TOKEN_CLASSES:
            try:
                return AuthToken(raw_token)
            except TokenError as e:
                messages.append({'token_class': AuthToken.__name__,
                                 'token_type': AuthToken.token_type,
                                 'message': e.args[0]})

        raise InvalidToken({
            'detail': _('Given token not valid for any token type'),
            'messages': messages,
        })


Instruction:
How would you implement a function in Python 3 that
attempts to find and return a user using the given validated token.

Response:
def get_user(self, validated_token):
        """
        Attempts to find and return a user using the given validated token.
        """
        try:
            user_id = validated_token[api_settings.USER_ID_CLAIM]
        except KeyError:
            raise InvalidToken(_('Token contained no recognizable user identification'))

        try:
            user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id})
        except User.DoesNotExist:
            raise AuthenticationFailed(_('User not found'), code='user_not_found')

        if not user.is_active:
            raise AuthenticationFailed(_('User is inactive'), code='user_inactive')

        return user


Instruction:
Implement a function in Python 3 to
return a stateless user object which is backed by the given validated_token.

Response:
def get_user(self, validated_token):
        """
        Returns a stateless user object which is backed by the given validated
        token.
        """
        if api_settings.USER_ID_CLAIM not in validated_token:
            # The TokenUser class assumes tokens will have a recognizable user
            # identifier claim.
            raise InvalidToken(_('Token contained no recognizable user identification'))

        return TokenUser(validated_token)


Instruction:
Given the following Python 3 function, write the documentation
def default_cx(self):
        px_width = self.image.px_width
        horz_dpi = self.image.horz_dpi
        width_in_inches = px_width / horz_dpi
        return Inches(width_in_inches)

Response: Default width of this image in inches.


Instruction:
Write a Python 3 script for
defaulting height of this image in pixels and the vertical dots per inch.

Response:
def default_cy(self):
        """
        Native height of this image, calculated from its height in pixels and
        vertical dots per inch (dpi).
        """
        px_height = self.image.px_height
        horz_dpi = self.image.horz_dpi
        height_in_emu = 914400 * px_height / horz_dpi
        return Emu(height_in_emu)


Instruction:
Can you tell what is the following Python 3 function doing
def filename(self):
        if self._image is not None:
            return self._image.filename
        return 'image.%s' % self.partname.ext

Response: Returns the name of the image part from which this image part was originally created.


Instruction:
Make a summary of the following Python 3 code
def from_image(cls, image, partname):
        return ImagePart(partname, image.content_type, image.blob, image)

Response: Return an |ImagePart| instance created from image and partname.


Instruction:
How would you implement a function in Python 3 that
loads an image part from a file.

Response:
def load(cls, partname, content_type, blob, package):
        """
        Called by ``docx.opc.package.PartFactory`` to load an image part from
        a package being opened by ``Document(...)`` call.
        """
        return cls(partname, content_type, blob)


Instruction:
How would you explain what the following Python 3 function does
def add_tab_stop(self, position, alignment=WD_TAB_ALIGNMENT.LEFT,
                     leader=WD_TAB_LEADER.SPACES):
        """
        Add a new tab stop at *position*, a |Length| object specifying the
        location of the tab stop relative to the paragraph edge. A negative
        *position* value is valid and appears in hanging indentation. Tab
        alignment defaults to left, but may be specified by passing a member
        of the :ref:`WdTabAlignment` enumeration as *alignment*. An optional
        leader character can be specified by passing a member of the
        :ref:`WdTabLeader` enumeration as *leader*.
        """
        tabs = self._pPr.get_or_add_tabs()
        tab = tabs.insert_tab_in_order(position, alignment, leader)
        return TabStop(tab)

Response: Adds a new tab stop at position.


Instruction:
Here you have a function in Python 3, explain what it does
def style(self, style):
        if style is None:
            self._remove_rStyle()
        elif self.rStyle is None:
            self._add_rStyle(val=style)
        else:
            self.rStyle.val = style

Response:
Set val attribute of a
            element to style.


Instruction:
Can you implement a function in Python 3 that
gets the value of the boolean child element having name name. e. g. c1 c2 c3 c4 c5 c6 c7 c9 c9

Response:
def _get_bool_val(self, name):
        """
        Return the value of the boolean child element having *name*, e.g.
        'b', 'i', and 'smallCaps'.
        """
        element = getattr(self, name)
        if element is None:
            return None
        return element.val


Instruction:
Explain what the following Python 3 code does
def val(self):
        val = self.get(qn('w:val'))
        underline = WD_UNDERLINE.from_xml(val)
        if underline == WD_UNDERLINE.SINGLE:
            return True
        if underline == WD_UNDERLINE.NONE:
            return False
        return underline

Response: Return the value of the w : val attribute.


Instruction:
Given the following Python 3 function, write the documentation
def new(cls, package):
        partname = package.next_partname("/word/footer%d.xml")
        content_type = CT.WML_FOOTER
        element = parse_xml(cls._default_footer_xml())
        return cls(partname, content_type, element, package)

Response: Return newly created footer part.


Instruction:
Here you have a function in Python 3, explain what it does
def new(cls, package):
        partname = package.next_partname("/word/header%d.xml")
        content_type = CT.WML_HEADER
        element = parse_xml(cls._default_header_xml())
        return cls(partname, content_type, element, package)

Response: Return newly created header part.


Instruction:
How would you explain what the following Python 3 function does
def default(cls, package):
        partname = PackURI('/word/styles.xml')
        content_type = CT.WML_STYLES
        element = parse_xml(cls._default_styles_xml())
        return cls(partname, content_type, element, package)

Response: Return a newly created styles part containing a default set of ArcGIS elements.


Instruction:
Here you have a function in Python 3, explain what it does
def _default_styles_xml(cls):
        path = os.path.join(
            os.path.split(__file__)[0], '..', 'templates',
            'default-styles.xml'
        )
        with open(path, 'rb') as f:
            xml_bytes = f.read()
        return xml_bytes

Response: Return a bytestream containing XML for a default styles part.


Instruction:
How would you implement a function in Python 3 that
adds a CT_HdrFtrRef element of type_ with rId.

Response:
def add_footerReference(self, type_, rId):
        """Return newly added CT_HdrFtrRef element of *type_* with *rId*.

        The element tag is `w:footerReference`.
        """
        footerReference = self._add_footerReference()
        footerReference.type_ = type_
        footerReference.rId = rId
        return footerReference


Instruction:
Can you tell what is the following Python 3 function doing
def add_headerReference(self, type_, rId):
        headerReference = self._add_headerReference()
        headerReference.type_ = type_
        headerReference.rId = rId
        return headerReference

Response: Add a CT_HdrFtrRef element of type_ with rId.


Instruction:
Explain what the following Python 3 code does
def get_footerReference(self, type_):
        path = "./w:footerReference[@w:type='%s']" % WD_HEADER_FOOTER.to_xml(type_)
        footerReferences = self.xpath(path)
        if not footerReferences:
            return None
        return footerReferences[0]

Response: Return footerReference element of type_ * or None.


Instruction:
Given the following Python 3 function, write the documentation
def get_headerReference(self, type_):
        matching_headerReferences = self.xpath(
            "./w:headerReference[@w:type='%s']" % WD_HEADER_FOOTER.to_xml(type_)
        )
        if len(matching_headerReferences) == 0:
            return None
        return matching_headerReferences[0]

Response: Return headerReference element of type_ or None.


Instruction:
Here you have a function in Python 3, explain what it does
def orientation(self):
        pgSz = self.pgSz
        if pgSz is None:
            return WD_ORIENTATION.PORTRAIT
        return pgSz.orient

Response: Returns the value of the orientation attribute of the WD_ORIENTATION enumeration corresponding to the passed in object.


Instruction:
Can you tell what is the following Python 3 function doing
def remove_footerReference(self, type_):
        footerReference = self.get_footerReference(type_)
        rId = footerReference.rId
        self.remove(footerReference)
        return rId

Response: Return rId of w : footerReference child of type_ * after removing it.


Instruction:
Write a Python 3 function that can
return rId of w : headerReference child of type_ * after removing it.

Response:
def remove_headerReference(self, type_):
        """Return rId of w:headerReference child of *type_* after removing it."""
        headerReference = self.get_headerReference(type_)
        rId = headerReference.rId
        self.remove(headerReference)
        return rId


Instruction:
How would you implement a function in Python 3 that
returns the value of the start type attribute of the WD_SECTION_START element.

Response:
def start_type(self):
        """
        The member of the ``WD_SECTION_START`` enumeration corresponding to
        the value of the ``val`` attribute of the ``<w:type>`` child element,
        or ``WD_SECTION_START.NEW_PAGE`` if not present.
        """
        type = self.type
        if type is None or type.val is None:
            return WD_SECTION_START.NEW_PAGE
        return type.val


Instruction:
Here you have a function in Python 3, explain what it does
def bool_prop(self, attr_name):
        value = getattr(self, attr_name)
        if value is None:
            return False
        return value

Response:
Return the boolean value of the attribute having attr_name * or
        |False| if not present.


Instruction:
Given the following Python 3 function, write the documentation
def base_style(self):
        basedOn = self.basedOn
        if basedOn is None:
            return None
        styles = self.getparent()
        base_style = styles.get_by_id(basedOn.val)
        if base_style is None:
            return None
        return base_style

Response: Returns the base style of this CT_Style element.


Instruction:
How would you code a function in Python 3 to
return the next Sibling CT_Style element.

Response:
def next_style(self):
        """
        Sibling CT_Style element identified by the value of `w:name/@w:val`
        or |None| if no value is present or no style with that style id
        is found.
        """
        next = self.next
        if next is None:
            return None
        styles = self.getparent()
        return styles.get_by_id(next.val)


Instruction:
Given the following Python 3 function, write the documentation
def add_style_of_type(self, name, style_type, builtin):
        style = self.add_style()
        style.type = style_type
        style.customStyle = None if builtin else True
        style.styleId = styleId_from_name(name)
        style.name_val = name
        return style

Response: Return a newly added w : style element having name and style_type.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def default_for(self, style_type):
        default_styles_for_type = [
            s for s in self._iter_styles()
            if s.type == style_type and s.default
        ]
        if not default_styles_for_type:
            return None
        # spec calls for last default in document order
        return default_styles_for_type[-1]

Response: Return the default for a given style type.


Instruction:
Explain what the following Python 3 code does
def add_break(self, break_type=WD_BREAK.LINE):
        type_, clear = {
            WD_BREAK.LINE:             (None,           None),
            WD_BREAK.PAGE:             ('page',         None),
            WD_BREAK.COLUMN:           ('column',       None),
            WD_BREAK.LINE_CLEAR_LEFT:  ('textWrapping', 'left'),
            WD_BREAK.LINE_CLEAR_RIGHT: ('textWrapping', 'right'),
            WD_BREAK.LINE_CLEAR_ALL:   ('textWrapping', 'all'),
        }[break_type]
        br = self._r.add_br()
        if type_ is not None:
            br.type = type_
        if clear is not None:
            br.clear = clear

Response: Add a break element of type WD_BREAK.


Instruction:
Write a Python 3 function for
adding a picture to the end of this run.

Response:
def add_picture(self, image_path_or_stream, width=None, height=None):
        """
        Return an |InlineShape| instance containing the image identified by
        *image_path_or_stream*, added to the end of this run.
        *image_path_or_stream* can be a path (a string) or a file-like object
        containing a binary image. 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.
        """
        inline = self.part.new_pic_inline(image_path_or_stream, width, height)
        self._r.add_drawing(inline)
        return InlineShape(inline)


Instruction:
Explain what the following Python 3 code does
def add_text(self, text):
        t = self._r.add_t(text)
        return _Text(t)

Response:
Adds a text to the run containing the new
       .


Instruction:
How would you explain what the following Python 3 function does
def style(self):
        style_id = self._r.style
        return self.part.get_style(style_id, WD_STYLE_TYPE.CHARACTER)

Response: A |_CharacterStyle| object representing the character style applied to this run.


Instruction:
Can you implement a function in Python 3 that
returns the value of the WdLineSpacing enumeration.

Response:
def spacing_lineRule(self):
        """
        The value of `w:spacing/@w:lineRule` as a member of the
        :ref:`WdLineSpacing` enumeration. Only the `MULTIPLE`, `EXACTLY`, and
        `AT_LEAST` members are used. It is the responsibility of the client
        to calculate the use of `SINGLE`, `DOUBLE`, and `MULTIPLE` based on
        the value of `w:spacing/@w:line` if that behavior is desired.
        """
        spacing = self.spacing
        if spacing is None:
            return None
        lineRule = spacing.lineRule
        if lineRule is None and spacing.line is not None:
            return WD_LINE_SPACING.MULTIPLE
        return lineRule


Instruction:
Given the following Python 3 function, write the documentation
def style(self, style):
        if style is None:
            self._remove_pStyle()
            return
        pStyle = self.get_or_add_pStyle()
        pStyle.val = style

Response:
Set val attribute of a
        child element to style.


Instruction:
Make a summary of the following Python 3 code
def insert_tab_in_order(self, pos, align, leader):
        new_tab = self._new_tab()
        new_tab.pos, new_tab.val, new_tab.leader = pos, align, leader
        for tab in self.tab_lst:
            if new_tab.pos < tab.pos:
                tab.addprevious(new_tab)
                return new_tab
        self.append(new_tab)
        return new_tab

Response: Insert a newly created w : tab element in * pos * order.


Instruction:
How would you code a function in Python 3 to
return a new inline element populated with the values passed as parameters.

Response:
def new(cls, cx, cy, shape_id, pic):
        """
        Return a new ``<wp:inline>`` element populated with the values passed
        as parameters.
        """
        inline = parse_xml(cls._inline_xml())
        inline.extent.cx = cx
        inline.extent.cy = cy
        inline.docPr.id = shape_id
        inline.docPr.name = 'Picture %d' % shape_id
        inline.graphic.graphicData.uri = (
            'http://schemas.openxmlformats.org/drawingml/2006/picture'
        )
        inline.graphic.graphicData._insert_pic(pic)
        return inline


Instruction:
Create a Python 3 function to
create a new pic element containing the pic : pic element containing the pic : pic specified by the argument values.

Response:
def new_pic_inline(cls, shape_id, rId, filename, cx, cy):
        """
        Return a new `wp:inline` element containing the `pic:pic` element
        specified by the argument values.
        """
        pic_id = 0  # Word doesn't seem to use this, but does not omit it
        pic = CT_Picture.new(pic_id, filename, rId, cx, cy)
        inline = cls.new(cx, cy, shape_id, pic)
        inline.graphic.graphicData._insert_pic(pic)
        return inline


Instruction:
How would you code a function in Python 3 to
return a new Pic element populated with the minimal contents required to define a viable picture element.

Response:
def new(cls, pic_id, filename, rId, cx, cy):
        """
        Return a new ``<pic:pic>`` element populated with the minimal
        contents required to define a viable picture element, based on the
        values passed as parameters.
        """
        pic = parse_xml(cls._pic_xml())
        pic.nvPicPr.cNvPr.id = pic_id
        pic.nvPicPr.cNvPr.name = filename
        pic.blipFill.blip.embed = rId
        pic.spPr.cx = cx
        pic.spPr.cy = cy
        return pic


Instruction:
Can you create a Python 3 function that
adds a new style object of type style_type to the document.

Response:
def add_style(self, name, style_type, builtin=False):
        """
        Return a newly added style object of *style_type* and identified
        by *name*. A builtin style can be defined by passing True for the
        optional *builtin* argument.
        """
        style_name = BabelFish.ui2internal(name)
        if style_name in self:
            raise ValueError("document already contains style '%s'" % name)
        style = self._element.add_style_of_type(
            style_name, style_type, builtin
        )
        return StyleFactory(style)


Instruction:
Implement a function in Python 3 to
return the default style for the given style type.

Response:
def default(self, style_type):
        """
        Return the default style for *style_type* or |None| if no default is
        defined for that type (not common).
        """
        style = self._element.default_for(style_type)
        if style is None:
            return None
        return StyleFactory(style)


Instruction:
Can you implement a function in Python 3 that
returns the style with the given style_id matching style_type.

Response:
def get_by_id(self, style_id, style_type):
        """Return the style of *style_type* matching *style_id*.

        Returns the default for *style_type* if *style_id* is not found or is |None|, or
        if the style having *style_id* is not of *style_type*.
        """
        if style_id is None:
            return self.default(style_type)
        return self._get_by_id(style_id, style_type)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_style_id(self, style_or_name, style_type):
        if style_or_name is None:
            return None
        elif isinstance(style_or_name, BaseStyle):
            return self._get_style_id_from_style(style_or_name, style_type)
        else:
            return self._get_style_id_from_name(style_or_name, style_type)

Response: Returns the id of the style corresponding to style_or_name or None if the style is not found.


Instruction:
Implement a function in Python 3 to
return the style of style_type matching style_id. Returns the default style for style_type.

Response:
def _get_by_id(self, style_id, style_type):
        """
        Return the style of *style_type* matching *style_id*. Returns the
        default for *style_type* if *style_id* is not found or if the style
        having *style_id* is not of *style_type*.
        """
        style = self._element.get_by_id(style_id)
        if style is None or style.type != style_type:
            return self.default(style_type)
        return StyleFactory(style)


Instruction:
Implement a function in Python 3 to
return a new instance from an RGB color hex string like 3C2F80.

Response:
def from_string(cls, rgb_hex_str):
        """
        Return a new instance from an RGB color hex string like ``'3C2F80'``.
        """
        r = int(rgb_hex_str[:2], 16)
        g = int(rgb_hex_str[2:4], 16)
        b = int(rgb_hex_str[4:], 16)
        return cls(r, g, b)


Instruction:
How would you explain what the following Python 3 function does
def iter_rels(self):
        def walk_rels(source, visited=None):
            visited = [] if visited is None else visited
            for rel in source.rels.values():
                yield rel
                if rel.is_external:
                    continue
                part = rel.target_part
                if part in visited:
                    continue
                visited.append(part)
                new_source = part
                for rel in walk_rels(new_source, visited):
                    yield rel

        for rel in walk_rels(self):
            yield rel

Response: Generate exactly one reference to each relationship in the package by iterating over the rels in the package.


Instruction:
Write a Python 3 script for
iterating over the parts of the package by iterating over the parts in the package.

Response:
def iter_parts(self):
        """
        Generate exactly one reference to each of the parts in the package by
        performing a depth-first traversal of the rels graph.
        """
        def walk_parts(source, visited=list()):
            for rel in source.rels.values():
                if rel.is_external:
                    continue
                part = rel.target_part
                if part in visited:
                    continue
                visited.append(part)
                yield part
                new_source = part
                for part in walk_parts(new_source, visited):
                    yield part

        for part in walk_parts(self):
            yield part


Instruction:
Here you have a function in Python 3, explain what it does
def load_rel(self, reltype, target, rId, is_external=False):
        return self.rels.add_relationship(reltype, target, rId, is_external)

Response: Load a relationship between thisCOOKIE and a target with key rId.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def next_partname(self, template):
        partnames = {part.partname for part in self.iter_parts()}
        for n in range(1, len(partnames) + 2):
            candidate_partname = template % n
            if candidate_partname not in partnames:
                return PackURI(candidate_partname)

Response: Return a |PackURI| instance representing the next available partname matching template.


Instruction:
Explain what the following Python 3 code does
def open(cls, pkg_file):
        pkg_reader = PackageReader.from_file(pkg_file)
        package = cls()
        Unmarshaller.unmarshal(pkg_reader, package, PartFactory)
        return package

Response: Open an OpcPackage instance from the contents of pkg_file.


Instruction:
How would you explain what the following Python 3 function does
def relate_to(self, part, reltype):
        rel = self.rels.get_or_add(reltype, part)
        return rel.rId

Response: Return rId key of relationship to part


Instruction:
How would you code a function in Python 3 to
save this package to a file - like object.

Response:
def save(self, pkg_file):
        """
        Save this package to *pkg_file*, where *file* can be either a path to
        a file (a string) or a file-like object.
        """
        for part in self.parts:
            part.before_marshal()
        PackageWriter.write(pkg_file, self.rels, self.parts)


Instruction:
Explain what the following Python 3 code does
def _core_properties_part(self):
        try:
            return self.part_related_by(RT.CORE_PROPERTIES)
        except KeyError:
            core_properties_part = CorePropertiesPart.default(self)
            self.relate_to(core_properties_part, RT.CORE_PROPERTIES)
            return core_properties_part

Response: Creates a core properties part related to this package.


Instruction:
Can you tell what is the following Python 3 function doing
def unmarshal(pkg_reader, package, part_factory):
        parts = Unmarshaller._unmarshal_parts(
            pkg_reader, package, part_factory
        )
        Unmarshaller._unmarshal_relationships(pkg_reader, package, parts)
        for part in parts.values():
            part.after_unmarshal()
        package.after_unmarshal()

Response: Unmarshalls the contents of pkg_reader into the package.


Instruction:
Implement a Python 3 function for
returning a dictionary of |Part| instances unmarshalled from *pkg_reader*, keyed by partname. Side-effect is that each part in *pkg_reader* is constructed using *part_factory*.

Response:
def _unmarshal_parts(pkg_reader, package, part_factory):
        """
        Return a dictionary of |Part| instances unmarshalled from
        *pkg_reader*, keyed by partname. Side-effect is that each part in
        *pkg_reader* is constructed using *part_factory*.
        """
        parts = {}
        for partname, content_type, reltype, blob in pkg_reader.iter_sparts():
            parts[partname] = part_factory(
                partname, content_type, reltype, blob, package
            )
        return parts


Instruction:
How would you explain what the following Python 3 function does
def _unmarshal_relationships(pkg_reader, package, parts):
        for source_uri, srel in pkg_reader.iter_srels():
            source = package if source_uri == '/' else parts[source_uri]
            target = (srel.target_ref if srel.is_external
                      else parts[srel.target_partname])
            source.load_rel(srel.reltype, target, srel.rId, srel.is_external)

Response:
Unmarshalls the relationships in pkg_reader into the source object corresponding to each of the actual
        relationships in parts.


Instruction:
Can you generate the documentation for the following Python 3 function
def default(cls, package):
        partname = PackURI('/word/settings.xml')
        content_type = CT.WML_SETTINGS
        element = parse_xml(cls._default_settings_xml())
        return cls(partname, content_type, element, package)

Response:
Return a newly created settings part containing a default
        xml.


Instruction:
Can you tell what is the following Python 3 function doing
def add_latent_style(self, name):
        lsdException = self._element.add_lsdException()
        lsdException.name = BabelFish.ui2internal(name)
        return _LatentStyle(lsdException)

Response: Add a latent style to the current object


Instruction:
How would you explain what the following Python 3 function does
def relate_to(self, target, reltype, is_external=False):
        if is_external:
            return self.rels.get_or_add_ext_rel(reltype, target)
        else:
            rel = self.rels.get_or_add(reltype, target)
            return rel.rId

Response: Return rId key of relationship of reltype to target.


Instruction:
How would you code a function in Python 3 to
return the count of references in this part s XML to the relationship identified by rId.

Response:
def _rel_ref_count(self, rId):
        """
        Return the count of references in this part's XML to the relationship
        identified by *rId*.
        """
        rIds = self._element.xpath('//@r:id')
        return len([_rId for _rId in rIds if _rId == rId])


Instruction:
Create a Python 3 function for
returning the custom part class registered for the given content type.

Response:
def _part_cls_for(cls, content_type):
        """
        Return the custom part class registered for *content_type*, or the
        default part class if no custom class is registered for
        *content_type*.
        """
        if content_type in cls.part_type_for:
            return cls.part_type_for[content_type]
        return cls.default_part_type


Instruction:
Implement a Python 3 function for
returning a newly added <w : t > element containing text.

Response:
def add_t(self, text):
        """
        Return a newly added ``<w:t>`` element containing *text*.
        """
        t = self._add_t(text=text)
        if len(text.strip()) < len(text):
            t.set(qn('xml:space'), 'preserve')
        return t


Instruction:
Create a Python 3 function to
add a drawing element to the current CT_Drawing element.

Response:
def add_drawing(self, inline_or_anchor):
        """
        Return a newly appended ``CT_Drawing`` (``<w:drawing>``) child
        element having *inline_or_anchor* as its child.
        """
        drawing = self._add_drawing()
        drawing.append(inline_or_anchor)
        return drawing


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

Response: Removes all child elements except the rPr element.


Instruction:
How would you explain what the following Python 3 function does
def append_to_run_from_text(cls, r, text):
        appender = cls(r)
        appender.add_text(text)

Response: Create a one - shot appender and append the text to the run content elements corresponding to r.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_text(self, text):
        for char in text:
            self.add_char(char)
        self.flush()

Response: Append the run content elements corresponding to text to the base element of this instance.


Instruction:
Can you generate the documentation for the following Python 3 function
def add_char(self, char):
        if char == '\t':
            self.flush()
            self._r.add_tab()
        elif char in '\r\n':
            self.flush()
            self._r.add_br()
        else:
            self._bfr.append(char)

Response: Add a character to the internal list of available items.


Instruction:
Create a Python 3 function to
return a |CorePropertiesPart| object initialized with default values for its base properties.

Response:
def default(cls, package):
        """
        Return a new |CorePropertiesPart| object initialized with default
        values for its base properties.
        """
        core_properties_part = cls._new(package)
        core_properties = core_properties_part.core_properties
        core_properties.title = 'Word Document'
        core_properties.last_modified_by = 'python-docx'
        core_properties.revision = 1
        core_properties.modified = datetime.utcnow()
        return core_properties_part


Instruction:
Create a Python 3 function for
getting the value of boolean child having name.

Response:
def _get_bool_prop(self, name):
        """
        Return the value of boolean child of `w:rPr` having *name*.
        """
        rPr = self._element.rPr
        if rPr is None:
            return None
        return rPr._get_bool_val(name)


Instruction:
Create a Python 3 function for
assigning value to the boolean child named name of the rPr.

Response:
def _set_bool_prop(self, name, value):
        """
        Assign *value* to the boolean child *name* of `w:rPr`.
        """
        rPr = self._element.get_or_add_rPr()
        rPr._set_bool_val(name, value)


Instruction:
How would you explain what the following Python 3 function does
def add_column(self, width):
        tblGrid = self._tbl.tblGrid
        gridCol = tblGrid.add_gridCol()
        gridCol.w = width
        for tr in self._tbl.tr_lst:
            tc = tr.add_tc()
            tc.width = width
        return _Column(gridCol, self)

Response:
Return a |_Column| object of * width* newly added rightmost to the
        table.


Instruction:
Implement a Python 3 function for
returning a |_Row| instance newly added bottom - most to the table.

Response:
def add_row(self):
        """
        Return a |_Row| instance, newly added bottom-most to the table.
        """
        tbl = self._tbl
        tr = tbl.add_tr()
        for gridCol in tbl.tblGrid.gridCol_lst:
            tc = tr.add_tc()
            tc.width = gridCol.w
        return _Row(tr, self)


Instruction:
Implement a Python 3 function for
returning |_Cell| instance correponding to table cell at row_idx col_idx intersection.

Response:
def cell(self, row_idx, col_idx):
        """
        Return |_Cell| instance correponding to table cell at *row_idx*,
        *col_idx* intersection, where (0, 0) is the top, left-most cell.
        """
        cell_idx = col_idx + (row_idx * self._column_count)
        return self._cells[cell_idx]


Instruction:
Given the following Python 3 function, write the documentation
def column_cells(self, column_idx):
        cells = self._cells
        idxs = range(column_idx, len(cells), self._column_count)
        return [cells[idx] for idx in idxs]

Response: Sequence of cells in the column at column_idx.


Instruction:
Implement a function in Python 3 to
return a sequence of cells in the row at the given index.

Response:
def row_cells(self, row_idx):
        """
        Sequence of cells in the row at *row_idx* in this table.
        """
        column_count = self._column_count
        start = row_idx * column_count
        end = start + column_count
        return self._cells[start:end]


Instruction:
Can you tell what is the following Python 3 function doing
def _cells(self):
        col_count = self._column_count
        cells = []
        for tc in self._tbl.iter_tcs():
            for grid_span_idx in range(tc.grid_span):
                if tc.vMerge == ST_Merge.CONTINUE:
                    cells.append(cells[-col_count])
                elif grid_span_idx > 0:
                    cells.append(cells[-1])
                else:
                    cells.append(_Cell(tc, self))
        return cells

Response: A sequence of |_Cell| objects one for each cell of the layout grid.


Instruction:
Here you have a function in Python 3, explain what it does
def add_paragraph(self, text='', style=None):
        return super(_Cell, self).add_paragraph(text, style)

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


Instruction:
Explain what the following Python 3 code does
def add_table(self, rows, cols):
        width = self.width if self.width is not None else Inches(1)
        table = super(_Cell, self).add_table(rows, cols, width)
        self.add_paragraph()
        return table

Response: Add a table to this cell after any existing cell with rows and cols columns.


Instruction:
Create a Python 3 function to
return a merged cell with this and other_cell as diagonal corners. Raises |InvalidSpanError| if the rectangular region is not defined.

Response:
def merge(self, other_cell):
        """
        Return a merged cell created by spanning the rectangular region
        having this cell and *other_cell* as diagonal corners. Raises
        |InvalidSpanError| if the cells do not define a rectangular region.
        """
        tc, tc_2 = self._tc, other_cell._tc
        merged_tc = tc.merge(tc_2)
        return _Cell(merged_tc, self._parent)


Instruction:
Implement a Python 3 function for
returning rId image pair for image identified by image_descriptor.

Response:
def get_or_add_image(self, image_descriptor):
        """Return (rId, image) pair for image identified by *image_descriptor*.

        *rId* is the str key (often like "rId7") for the relationship between this story
        part and the image part, reused if already present, newly created if not.
        *image* is an |Image| instance providing access to the properties of the image,
        such as dimensions and image type.
        """
        image_part = self._package.get_or_add_image_part(image_descriptor)
        rId = self.relate_to(image_part, RT.IMAGE)
        return rId, image_part.image


Instruction:
Can you implement a function in Python 3 that
returns a newly - created w : inline element.

Response:
def new_pic_inline(self, image_descriptor, width, height):
        """Return a newly-created `w:inline` element.

        The element contains the image specified by *image_descriptor* and is scaled
        based on the values of *width* and *height*.
        """
        rId, image = self.get_or_add_image(image_descriptor)
        cx, cy = image.scaled_dimensions(width, height)
        shape_id, filename = self.next_id, image.filename
        return CT_Inline.new_pic_inline(shape_id, rId, filename, cx, cy)


Instruction:
Implement a Python 3 function for
returning the next available positive integer id value in this story XML document.

Response:
def next_id(self):
        """Next available positive integer id value in this story XML document.

        The value is determined by incrementing the maximum existing id value. Gaps in
        the existing id sequence are not filled. The id attribute value is unique in the
        document, without regard to the element type it appears on.
        """
        id_str_lst = self._element.xpath('//@id')
        used_ids = [int(id_str) for id_str in id_str_lst if id_str.isdigit()]
        if not used_ids:
            return 1
        return max(used_ids) + 1


Instruction:
How would you code a function in Python 3 to
return |_Marker| or subclass instance appropriate for marker at offset.

Response:
def _MarkerFactory(marker_code, stream, offset):
    """
    Return |_Marker| or subclass instance appropriate for marker at *offset*
    in *stream* having *marker_code*.
    """
    if marker_code == JPEG_MARKER_CODE.APP0:
        marker_cls = _App0Marker
    elif marker_code == JPEG_MARKER_CODE.APP1:
        marker_cls = _App1Marker
    elif marker_code in JPEG_MARKER_CODE.SOF_MARKER_CODES:
        marker_cls = _SofMarker
    else:
        marker_cls = _Marker
    return marker_cls.from_stream(stream, marker_code, offset)


Instruction:
Implement a Python 3 function for
creating an exif instance from an image stream.

Response:
def from_stream(cls, stream):
        """
        Return |Exif| instance having header properties parsed from Exif
        image in *stream*.
        """
        markers = _JfifMarkers.from_stream(stream)
        # print('\n%s' % markers)

        px_width = markers.sof.px_width
        px_height = markers.sof.px_height
        horz_dpi = markers.app1.horz_dpi
        vert_dpi = markers.app1.vert_dpi

        return cls(px_width, px_height, horz_dpi, vert_dpi)


Instruction:
Create a Python 3 function to
create a new |_JfifMarkers| instance from a stream.

Response:
def from_stream(cls, stream):
        """
        Return a |_JfifMarkers| instance containing a |_JfifMarker| subclass
        instance for each marker in *stream*.
        """
        marker_parser = _MarkerParser.from_stream(stream)
        markers = []
        for marker in marker_parser.iter_markers():
            markers.append(marker)
            if marker.marker_code == JPEG_MARKER_CODE.SOS:
                break
        return cls(markers)


Instruction:
How would you explain what the following Python 3 function does
def app0(self):
        for m in self._markers:
            if m.marker_code == JPEG_MARKER_CODE.APP0:
                return m
        raise KeyError('no APP0 marker in image')

Response: Return the first APP0 marker in image markers.


Instruction:
Explain what the following Python 3 code does
def app1(self):
        for m in self._markers:
            if m.marker_code == JPEG_MARKER_CODE.APP1:
                return m
        raise KeyError('no APP1 marker in image')

Response: Return the first APP1 marker in image markers.


Instruction:
Create a Python 3 function to
return the first start of frame in this sequence.

Response:
def sof(self):
        """
        First start of frame (SOFn) marker in this sequence.
        """
        for m in self._markers:
            if m.marker_code in JPEG_MARKER_CODE.SOF_MARKER_CODES:
                return m
        raise KeyError('no start of frame (SOFn) marker in image')


Instruction:
Write a Python 3 script to
iterate over the ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440 ISO - 1440.

Response:
def iter_markers(self):
        """
        Generate a (marker_code, segment_offset) 2-tuple for each marker in
        the JPEG *stream*, in the order they occur in the stream.
        """
        marker_finder = _MarkerFinder.from_stream(self._stream)
        start = 0
        marker_code = None
        while marker_code != JPEG_MARKER_CODE.EOI:
            marker_code, segment_offset = marker_finder.next(start)
            marker = _MarkerFactory(
                marker_code, self._stream, segment_offset
            )
            yield marker
            start = segment_offset + marker.segment_length


Instruction:
Make a summary of the following Python 3 code
def next(self, start):
        position = start
        while True:
            # skip over any non-\xFF bytes
            position = self._offset_of_next_ff_byte(start=position)
            # skip over any \xFF padding bytes
            position, byte_ = self._next_non_ff_byte(start=position+1)
            # 'FF 00' sequence is not a marker, start over if found
            if byte_ == b'\x00':
                continue
            # this is a marker, gather return values and break out of scan
            marker_code, segment_offset = byte_, position+1
            break
        return marker_code, segment_offset

Response: Return the next available and available ISO - 8601 marker code and segment offset.


Instruction:
How would you code a function in Python 3 to
return an offset byte 2 - tuple for the next non - FF byte in the stream starting with the offset start.

Response:
def _next_non_ff_byte(self, start):
        """
        Return an offset, byte 2-tuple for the next byte in *stream* that is
        not '\xFF', starting with the byte at offset *start*. If the byte at
        offset *start* is not '\xFF', *start* and the returned *offset* will
        be the same.
        """
        self._stream.seek(start)
        byte_ = self._read_byte()
        while byte_ == b'\xFF':
            byte_ = self._read_byte()
        offset_of_non_ff_byte = self._stream.tell() - 1
        return offset_of_non_ff_byte, byte_


Instruction:
Can you generate the documentation for the following Python 3 function
def _offset_of_next_ff_byte(self, start):
        self._stream.seek(start)
        byte_ = self._read_byte()
        while byte_ != b'\xFF':
            byte_ = self._read_byte()
        offset_of_ff_byte = self._stream.tell() - 1
        return offset_of_ff_byte

Response: Return the offset of the next '\xFF' byte in the stream starting with start.


Instruction:
Implement a Python 3 function for
creating a |_Marker| instance from a stream.

Response:
def from_stream(cls, stream, marker_code, offset):
        """
        Return a generic |_Marker| instance for the marker at *offset* in
        *stream* having *marker_code*.
        """
        if JPEG_MARKER_CODE.is_standalone(marker_code):
            segment_length = 0
        else:
            segment_length = stream.read_short(offset)
        return cls(marker_code, offset, segment_length)


Instruction:
Can you generate the documentation for the following Python 3 function
def _dpi(self, density):
        if self._density_units == 1:
            dpi = density
        elif self._density_units == 2:
            dpi = int(round(density * 2.54))
        else:
            dpi = 72
        return dpi

Response: Return dots per inch corresponding to density value.


Instruction:
How would you explain what the following Python 3 function does
def from_stream(cls, stream, marker_code, offset):
        # field               off  type   notes
        # ------------------  ---  -----  -------------------
        # segment length       0   short
        # JFIF identifier      2   5 chr  'JFIF\x00'
        # major JPEG version   7   byte   typically 1
        # minor JPEG version   8   byte   typically 1 or 2
        # density units        9   byte   1=inches, 2=cm
        # horz dots per unit  10   short
        # vert dots per unit  12   short
        # ------------------  ---  -----  -------------------
        segment_length = stream.read_short(offset)
        density_units = stream.read_byte(offset, 9)
        x_density = stream.read_short(offset, 10)
        y_density = stream.read_short(offset, 12)
        return cls(
            marker_code, offset, segment_length, density_units, x_density,
            y_density
        )

Response: Read an APP0 marker from the given stream and return a |_App0Marker| instance.


Instruction:
Explain what the following Python 3 code does
def from_stream(cls, stream, marker_code, offset):
        # field                 off  len  type   notes
        # --------------------  ---  ---  -----  ----------------------------
        # segment length         0    2   short
        # Exif identifier        2    6   6 chr  'Exif\x00\x00'
        # TIFF byte order        8    2   2 chr  'II'=little 'MM'=big endian
        # meaning of universe   10    2   2 chr  '*\x00' or '\x00*' depending
        # IFD0 off fr/II or MM  10   16   long   relative to ...?
        # --------------------  ---  ---  -----  ----------------------------
        segment_length = stream.read_short(offset)
        if cls._is_non_Exif_APP1_segment(stream, offset):
            return cls(marker_code, offset, segment_length, 72, 72)
        tiff = cls._tiff_from_exif_segment(stream, offset, segment_length)
        return cls(
            marker_code, offset, segment_length, tiff.horz_dpi, tiff.vert_dpi
        )

Response: Extract the horizontal and vertical dots - per - inch values from the APP1 header at the given offset.


Instruction:
Can you tell what is the following Python 3 function doing
def _is_non_Exif_APP1_segment(cls, stream, offset):
        stream.seek(offset+2)
        exif_signature = stream.read(6)
        return exif_signature != b'Exif\x00\x00'

Response: Return True if the APP1 segment at offset is NOT an EXIF segment.


Instruction:
Write a Python 3 function that can
parse an EXIF segment into a |Tiff| instance.

Response:
def _tiff_from_exif_segment(cls, stream, offset, segment_length):
        """
        Return a |Tiff| instance parsed from the Exif APP1 segment of
        *segment_length* at *offset* in *stream*.
        """
        # wrap full segment in its own stream and feed to Tiff()
        stream.seek(offset+8)
        segment_bytes = stream.read(segment_length-8)
        substream = BytesIO(segment_bytes)
        return Tiff.from_stream(substream)


Instruction:
How would you code a function in Python 3 to
read a SOFn marker from the given stream and return a |_SofMarker| instance.

Response:
def from_stream(cls, stream, marker_code, offset):
        """
        Return an |_SofMarker| instance for the SOFn marker at *offset* in
        stream.
        """
        # field                 off  type   notes
        # ------------------  ---  -----  ----------------------------
        # segment length       0   short
        # Data precision       2   byte
        # Vertical lines       3   short  px_height
        # Horizontal lines     5   short  px_width
        # ------------------  ---  -----  ----------------------------
        segment_length = stream.read_short(offset)
        px_height = stream.read_short(offset, 3)
        px_width = stream.read_short(offset, 5)
        return cls(marker_code, offset, segment_length, px_width, px_height)


Instruction:
Can you write a function in Python 3 where it
returns the tc element appearing at a given index. Raises |ValueError| if no tc element appearing at that grid column. Raises |ValueError| if no tc element appearing at that grid column.

Response:
def tc_at_grid_col(self, idx):
        """
        The ``<w:tc>`` element appearing at grid column *idx*. Raises
        |ValueError| if no ``w:tc`` element begins at that grid column.
        """
        grid_col = 0
        for tc in self.tc_lst:
            if grid_col == idx:
                return tc
            grid_col += tc.grid_span
            if grid_col > idx:
                raise ValueError('no cell on grid column %d' % idx)
        raise ValueError('index out of bounds')


Instruction:
Implement a function in Python 3 to
return a new w : tbl element having rows cols and width distributed evenly between the columns.

Response:
def new_tbl(cls, rows, cols, width):
        """
        Return a new `w:tbl` element having *rows* rows and *cols* columns
        with *width* distributed evenly between the columns.
        """
        return parse_xml(cls._tbl_xml(rows, cols, width))


Instruction:
Create a Python 3 function for
setting the value of w : tblPr. tblStyle. val to * styleId*.

Response:
def tblStyle_val(self, styleId):
        """
        Set the value of `w:tblPr/w:tblStyle/@w:val` (a table style id) to
        *styleId*. If *styleId* is None, remove the `w:tblStyle` element.
        """
        tblPr = self.tblPr
        tblPr._remove_tblStyle()
        if styleId is None:
            return
        tblPr._add_tblStyle().val = styleId


Instruction:
Can you generate the documentation for the following Python 3 function
def autofit(self):
        tblLayout = self.tblLayout
        if tblLayout is None:
            return True
        return False if tblLayout.type == 'fixed' else True

Response: Return |True| if there is a child with the type set to fixed. Otherwise return |False|.


Instruction:
Here you have a function in Python 3, explain what it does
def bottom(self):
        if self.vMerge is not None:
            tc_below = self._tc_below
            if tc_below is not None and tc_below.vMerge == ST_Merge.CONTINUE:
                return tc_below.bottom
        return self._tr_idx + 1

Response: Returns the index of the bottom extent of the cell.


Instruction:
Given the following Python 3 function, write the documentation
def clear_content(self):
        new_children = []
        tcPr = self.tcPr
        if tcPr is not None:
            new_children.append(tcPr)
        self[:] = new_children

Response:
Removes all content child elements preserving the block - level
        element.


Instruction:
Can you generate the documentation for the following Python 3 function
def iter_block_items(self):
        block_item_tags = (qn('w:p'), qn('w:tbl'), qn('w:sdt'))
        for child in self:
            if child.tag in block_item_tags:
                yield child

Response: Iterate over the block - level content elements in this cell.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def merge(self, other_tc):
        top, left, height, width = self._span_dimensions(other_tc)
        top_tc = self._tbl.tr_lst[top].tc_at_grid_col(left)
        top_tc._grow_to(width, height)
        return top_tc

Response: Return the top - left element of a new span formed by this tc element and other_tc as diagonal corners.


Instruction:
How would you implement a function in Python 3 that
returns the top - most row index in the vertical span of this cell.

Response:
def top(self):
        """
        The top-most row index in the vertical span of this cell.
        """
        if self.vMerge is None or self.vMerge == ST_Merge.RESTART:
            return self._tr_idx
        return self._tc_above.top


Instruction:
Write a Python 3 script to
add the width of other_tc to this cell. Does nothing if self. width is not equal to other_tc.

Response:
def _add_width_of(self, other_tc):
        """
        Add the width of *other_tc* to this cell. Does nothing if either this
        tc or *other_tc* does not have a specified width.
        """
        if self.width and other_tc.width:
            self.width += other_tc.width


Instruction:
Explain what the following Python 3 code does
def _grow_to(self, width, height, top_tc=None):
        def vMerge_val(top_tc):
            if top_tc is not self:
                return ST_Merge.CONTINUE
            if height == 1:
                return None
            return ST_Merge.RESTART

        top_tc = self if top_tc is None else top_tc
        self._span_to_width(width, top_tc, vMerge_val(top_tc))
        if height > 1:
            self._tc_below._grow_to(width, height-1, top_tc)

Response: Grow this cell to width height by expanding horizontal spans and creating continuation cells for vertical ones.


Instruction:
Explain what the following Python 3 code does
def _is_empty(self):
        block_items = list(self.iter_block_items())
        if len(block_items) > 1:
            return False
        p = block_items[0]  # cell must include at least one <w:p> element
        if len(p.r_lst) == 0:
            return True
        return False

Response: Returns True if this cell contains only a single empty element.


Instruction:
Explain what the following Python 3 code does
def _move_content_to(self, other_tc):
        if other_tc is self:
            return
        if self._is_empty:
            return
        other_tc._remove_trailing_empty_p()
        # appending moves each element from self to other_tc
        for block_element in self.iter_block_items():
            other_tc.append(block_element)
        # add back the required minimum single empty <w:p> element
        self.append(self._new_p())

Response: Moves the content of this cell to other_tc.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _remove_trailing_empty_p(self):
        block_items = list(self.iter_block_items())
        last_content_elm = block_items[-1]
        if last_content_elm.tag != qn('w:p'):
            return
        p = last_content_elm
        if len(p.r_lst) > 0:
            return
        self.remove(p)

Response:
Remove the last empty content element from this cell if it is an empty
        element.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _span_dimensions(self, other_tc):
        def raise_on_inverted_L(a, b):
            if a.top == b.top and a.bottom != b.bottom:
                raise InvalidSpanError('requested span not rectangular')
            if a.left == b.left and a.right != b.right:
                raise InvalidSpanError('requested span not rectangular')

        def raise_on_tee_shaped(a, b):
            top_most, other = (a, b) if a.top < b.top else (b, a)
            if top_most.top < other.top and top_most.bottom > other.bottom:
                raise InvalidSpanError('requested span not rectangular')

            left_most, other = (a, b) if a.left < b.left else (b, a)
            if left_most.left < other.left and left_most.right > other.right:
                raise InvalidSpanError('requested span not rectangular')

        raise_on_inverted_L(self, other_tc)
        raise_on_tee_shaped(self, other_tc)

        top = min(self.top, other_tc.top)
        left = min(self.left, other_tc.left)
        bottom = max(self.bottom, other_tc.bottom)
        right = max(self.right, other_tc.right)

        return top, left, bottom - top, right - left

Response: Return the top left height and width of the merged cell formed by using this tc and other_tc as opposite ArcGIS corner extents.


Instruction:
Can you generate the documentation for the following Python 3 function
def _span_to_width(self, grid_width, top_tc, vMerge):
        self._move_content_to(top_tc)
        while self.grid_span < grid_width:
            self._swallow_next_tc(grid_width, top_tc)
        self.vMerge = vMerge

Response: Incorporate and then remove w : tc elements from the right of this oneCOOKIE.


Instruction:
Here you have a function in Python 3, explain what it does
def _swallow_next_tc(self, grid_width, top_tc):
        def raise_on_invalid_swallow(next_tc):
            if next_tc is None:
                raise InvalidSpanError('not enough grid columns')
            if self.grid_span + next_tc.grid_span > grid_width:
                raise InvalidSpanError('span is not rectangular')

        next_tc = self._next_tc
        raise_on_invalid_swallow(next_tc)
        next_tc._move_content_to(top_tc)
        self._add_width_of(next_tc)
        self.grid_span += next_tc.grid_span
        next_tc._remove()

Response: Swallows the next <w : tc element in the row.


Instruction:
Given the following Python 3 function, write the documentation
def _tc_below(self):
        tr_below = self._tr_below
        if tr_below is None:
            return None
        return tr_below.tc_at_grid_col(self._grid_col)

Response: The tc element immediately below this one in its grid column.


Instruction:
How would you explain what the following Python 3 function does
def alias(*aliases):
    def decorator(cls):
        # alias must be set in globals from caller's frame
        caller = sys._getframe(1)
        globals_dict = caller.f_globals
        for alias in aliases:
            globals_dict[alias] = cls
        return cls
    return decorator

Response: A class decorator that adds an alias to the class to be referenced by each of the names provided as arguments.


Instruction:
Create a Python 3 function for
returning a string representation of the enumeration page.

Response:
def page_str(self):
        """
        The RestructuredText documentation page for the enumeration. This is
        the only API member for the class.
        """
        tmpl = '.. _%s:\n\n%s\n\n%s\n\n----\n\n%s'
        components = (
            self._ms_name, self._page_title, self._intro_text,
            self._member_defs
        )
        return tmpl % components


Instruction:
Given the following Python 3 function, write the documentation
def _intro_text(self):
        try:
            cls_docstring = self._clsdict['__doc__']
        except KeyError:
            cls_docstring = ''

        if cls_docstring is None:
            return ''

        return textwrap.dedent(cls_docstring).strip()

Response: Return the enumeration docstring formatted for documentation page.


Instruction:
Can you implement a function in Python 3 that
returns an individual member definition formatted as an RST glossary entry.

Response:
def _member_def(self, member):
        """
        Return an individual member definition formatted as an RST glossary
        entry, wrapped to fit within 78 columns.
        """
        member_docstring = textwrap.dedent(member.docstring).strip()
        member_docstring = textwrap.fill(
            member_docstring, width=78, initial_indent=' '*4,
            subsequent_indent=' '*4
        )
        return '%s\n%s\n' % (member.name, member_docstring)


Instruction:
Can you tell what is the following Python 3 function doing
def _member_defs(self):
        members = self._clsdict['__members__']
        member_defs = [
            self._member_def(member) for member in members
            if member.name is not None
        ]
        return '\n'.join(member_defs)

Response:
A single string containing the aggregated member definitions section
            of the documentation page


Instruction:
Write a Python 3 function for
dispatching each member of the enumeration class to each member of the enumeration class.

Response:
def _add_enum_members(meta, clsdict):
        """
        Dispatch ``.add_to_enum()`` call to each member so it can do its
        thing to properly add itself to the enumeration class. This
        delegation allows member sub-classes to add specialized behaviors.
        """
        enum_members = clsdict['__members__']
        for member in enum_members:
            member.add_to_enum(clsdict)


Instruction:
Can you tell what is the following Python 3 function doing
def _collect_valid_settings(meta, clsdict):
        enum_members = clsdict['__members__']
        valid_settings = []
        for member in enum_members:
            valid_settings.extend(member.valid_settings)
        clsdict['_valid_settings'] = valid_settings

Response: Collect the valid_settings from the meta class and add them to the classdict.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def validate(cls, value):
        if value not in cls._valid_settings:
            raise ValueError(
                "%s not a member of %s enumeration" % (value, cls.__name__)
            )

Response: Validate the value of the resource.


Instruction:
Implement a function in Python 3 to
return the enumeration member corresponding to the XML value xml_val.

Response:
def from_xml(cls, xml_val):
        """
        Return the enumeration member corresponding to the XML value
        *xml_val*.
        """
        if xml_val not in cls._xml_to_member:
            raise InvalidXmlError(
                "attribute value '%s' not valid for this type" % xml_val
            )
        return cls._xml_to_member[xml_val]


Instruction:
Given the following Python 3 function, write the documentation
def to_xml(cls, enum_val):
        if enum_val not in cls._member_to_xml:
            raise ValueError(
                "value '%s' not in enumeration %s" % (enum_val, cls.__name__)
            )
        return cls._member_to_xml[enum_val]

Response: Return the XML value of the enumeration value enum_val.


Instruction:
Write a Python 3 script to
add a member name to the class dict clsdict containing the value of this member object.

Response:
def register_name(self, clsdict):
        """
        Add a member name to the class dict *clsdict* containing the value of
        this member object. Where the name of this object is None, do
        nothing; this allows out-of-band values to be defined without adding
        a name to the class dict.
        """
        if self.name is None:
            return
        clsdict[self.name] = self.value


Instruction:
Can you create a Python 3 function that
adds XML mappings to the enumeration.

Response:
def add_to_enum(self, clsdict):
        """
        Compile XML mappings in addition to base add behavior.
        """
        super(XmlMappedEnumMember, self).add_to_enum(clsdict)
        self.register_xml_mapping(clsdict)


Instruction:
Make a summary of the following Python 3 code
def register_xml_mapping(self, clsdict):
        member_to_xml = self._get_or_add_member_to_xml(clsdict)
        member_to_xml[self.value] = self.xml_value
        xml_to_member = self._get_or_add_xml_to_member(clsdict)
        xml_to_member[self.xml_value] = self.value

Response: Add XML mappings to the enumeration class state for this member.


Instruction:
Create a Python 3 function to
return a |Document| object loaded from a. docx file or a file - like object.

Response:
def Document(docx=None):
    """
    Return a |Document| object loaded from *docx*, where *docx* can be
    either a path to a ``.docx`` file (a string) or a file-like object. If
    *docx* is missing or ``None``, the built-in default document "template"
    is loaded.
    """
    docx = _default_docx_path() if docx is None else docx
    document_part = Package.open(docx).main_document_part
    if document_part.content_type != CT.WML_DOCUMENT_MAIN:
        tmpl = "file '%s' is not a Word file, content type is '%s'"
        raise ValueError(tmpl % (docx, document_part.content_type))
    return document_part.document


Instruction:
Write a Python 3 function that can
return the path to the built - in default. docx package.

Response:
def _default_docx_path():
    """
    Return the path to the built-in default .docx package.
    """
    _thisdir = os.path.split(__file__)[0]
    return os.path.join(_thisdir, 'templates', 'default-docx-template')


Instruction:
Write a Python 3 script for
returning |Pt| value representing the line spacing between baselines in successive lines of the paragraph.

Response:
def line_spacing(self):
        """
        |float| or |Length| value specifying the space between baselines in
        successive lines of the paragraph. A value of |None| indicates line
        spacing is inherited from the style hierarchy. A float value, e.g.
        ``2.0`` or ``1.75``, indicates spacing is applied in multiples of
        line heights. A |Length| value such as ``Pt(12)`` indicates spacing
        is a fixed height. The |Pt| value class is a convenient way to apply
        line spacing in units of points. Assigning |None| resets line spacing
        to inherit from the style hierarchy.
        """
        pPr = self._element.pPr
        if pPr is None:
            return None
        return self._line_spacing(pPr.spacing_line, pPr.spacing_lineRule)


Instruction:
Create a Python 3 function to
return the line spacing rule for the current entry.

Response:
def line_spacing_rule(self):
        """
        A member of the :ref:`WdLineSpacing` enumeration indicating how the
        value of :attr:`line_spacing` should be interpreted. Assigning any of
        the :ref:`WdLineSpacing` members :attr:`SINGLE`, :attr:`DOUBLE`, or
        :attr:`ONE_POINT_FIVE` will cause the value of :attr:`line_spacing`
        to be updated to produce the corresponding line spacing.
        """
        pPr = self._element.pPr
        if pPr is None:
            return None
        return self._line_spacing_rule(
            pPr.spacing_line, pPr.spacing_lineRule
        )


Instruction:
Make a summary of the following Python 3 code
def _line_spacing(spacing_line, spacing_lineRule):
        if spacing_line is None:
            return None
        if spacing_lineRule == WD_LINE_SPACING.MULTIPLE:
            return spacing_line / Pt(12)
        return spacing_line

Response:
Return the line spacing value calculated from the combination of
        spacing_line and spacing_lineRule.


Instruction:
Create a Python 3 function for
returning the line spacing rule value calculated from the combination of the line and lineRule.

Response:
def _line_spacing_rule(line, lineRule):
        """
        Return the line spacing rule value calculated from the combination of
        *line* and *lineRule*. Returns special members of the
        :ref:`WdLineSpacing` enumeration when line spacing is single, double,
        or 1.5 lines.
        """
        if lineRule == WD_LINE_SPACING.MULTIPLE:
            if line == Twips(240):
                return WD_LINE_SPACING.SINGLE
            if line == Twips(360):
                return WD_LINE_SPACING.ONE_POINT_FIVE
            if line == Twips(480):
                return WD_LINE_SPACING.DOUBLE
        return lineRule


Instruction:
Given the following Python 3 function, write the documentation
def new(cls, num_id, abstractNum_id):
        num = OxmlElement('w:num')
        num.numId = num_id
        abstractNumId = CT_DecimalNumber.new(
            'w:abstractNumId', abstractNum_id
        )
        num.append(abstractNumId)
        return num

Response: Return a new num element with numId of num_id and abstractNumId of abstractNum_id.


Instruction:
Explain what the following Python 3 code does
def add_num(self, abstractNum_id):
        next_num_id = self._next_numId
        num = CT_Num.new(next_num_id, abstractNum_id)
        return self._insert_num(num)

Response: Return a newly added CT_Num element referencing the abstract numbering definition identified by abstractNum_id.


Instruction:
Write a Python 3 function that can
return the first child element having numId attribute matching numId*.

Response:
def num_having_numId(self, numId):
        """
        Return the ``<w:num>`` child element having ``numId`` attribute
        matching *numId*.
        """
        xpath = './w:num[@w:numId="%d"]' % numId
        try:
            return self.xpath(xpath)[0]
        except IndexError:
            raise KeyError('no <w:num> element with numId %d' % numId)


Instruction:
Explain what the following Python 3 code does
def _next_numId(self):
        numId_strs = self.xpath('./w:num/@w:numId')
        num_ids = [int(numId_str) for numId_str in numId_strs]
        for num in range(1, len(num_ids)+2):
            if num not in num_ids:
                break
        return num

Response: Returns the next unused numId in the list of available numId elements.


Instruction:
How would you code a function in Python 3 to
add a relationship to the set.

Response:
def add_relationship(self, reltype, target, rId, is_external=False):
        """
        Return a newly added |_Relationship| instance.
        """
        rel = _Relationship(rId, reltype, target, self._baseURI, is_external)
        self[rId] = rel
        if not is_external:
            self._target_parts_by_rId[rId] = target
        return rel


Instruction:
Given the following Python 3 function, write the documentation
def get_or_add(self, reltype, target_part):
        rel = self._get_matching(reltype, target_part)
        if rel is None:
            rId = self._next_rId
            rel = self.add_relationship(reltype, target_part, rId)
        return rel

Response:
Get or add a new not
            relationship.


Instruction:
Can you write a function in Python 3 where it
gets or add an external relationship of the specified type to the collection.

Response:
def get_or_add_ext_rel(self, reltype, target_ref):
        """
        Return rId of external relationship of *reltype* to *target_ref*,
        newly added if not already present in collection.
        """
        rel = self._get_matching(reltype, target_ref, is_external=True)
        if rel is None:
            rId = self._next_rId
            rel = self.add_relationship(
                reltype, target_ref, rId, is_external=True
            )
        return rel.rId


Instruction:
Implement a Python 3 function for
serializing this relationship collection into XML suitable for storage as a. rels file in an OPC package.

Response:
def xml(self):
        """
        Serialize this relationship collection into XML suitable for storage
        as a .rels file in an OPC package.
        """
        rels_elm = CT_Relationships.new()
        for rel in self.values():
            rels_elm.add_rel(
                rel.rId, rel.reltype, rel.target_ref, rel.is_external
            )
        return rels_elm.xml


Instruction:
Can you implement a function in Python 3 that
returns the relationship of matching reltype target and is_external

Response:
def _get_matching(self, reltype, target, is_external=False):
        """
        Return relationship of matching *reltype*, *target*, and
        *is_external* from collection, or None if not found.
        """
        def matches(rel, reltype, target, is_external):
            if rel.reltype != reltype:
                return False
            if rel.is_external != is_external:
                return False
            rel_target = rel.target_ref if rel.is_external else rel.target_part
            if rel_target != target:
                return False
            return True

        for rel in self.values():
            if matches(rel, reltype, target, is_external):
                return rel
        return None


Instruction:
Create a Python 3 function to
return the next available rId in the collection.

Response:
def _next_rId(self):
        """
        Next available rId in collection, starting from 'rId1' and making use
        of any gaps in numbering, e.g. 'rId2' for rIds ['rId1', 'rId3'].
        """
        for n in range(1, len(self)+2):
            rId_candidate = 'rId%d' % n  # like 'rId19'
            if rId_candidate not in self:
                return rId_candidate


Instruction:
How would you code a function in Python 3 to
return a new OxmlElement having tagname nsptagname and val.

Response:
def new(cls, nsptagname, val):
        """
        Return a new ``CT_DecimalNumber`` element having tagname *nsptagname*
        and ``val`` attribute set to *val*.
        """
        return OxmlElement(nsptagname, attrs={qn('w:val'): str(val)})


Instruction:
How would you implement a function in Python 3 that
returns a new OxmlElement with tagname nsptagname and val.

Response:
def new(cls, nsptagname, val):
        """
        Return a new ``CT_String`` element with tagname *nsptagname* and
        ``val`` attribute set to *val*.
        """
        elm = OxmlElement(nsptagname)
        elm.val = val
        return elm