Instruction:
How would you code a function in Python 3 to
return a message instance for the specified message type.

Response:
def message_factory(msg_type, msg_types=MESSAGE_TYPES, *args, **kwargs):
    """
    Factory function to return the specified message instance.

    Args:
        :msg_type: (str) the type of message to send, i.e. 'Email'
        :msg_types: (str, list, or set) the supported message types
        :kwargs: (dict) keywords arguments that are required for the
            various message types.  See docstrings for each type.
            i.e. help(messages.Email), help(messages.Twilio), etc.
    """
    try:
        return msg_types[msg_type.lower()](*args, **kwargs)
    except (UnknownProfileError, InvalidMessageInputError) as e:
        err_exit("Unable to send message: ", e)
    except KeyError:
        raise UnsupportedMessageTypeError(msg_type, msg_types)


Instruction:
Can you tell what is the following Python 3 function doing
def credential_property(cred):

    def getter(instance):
        return "***obfuscated***"

    def setter(instance, value):
        private = "_" + cred
        instance.__dict__[private] = value

    return property(fget=getter, fset=setter)

Response: A credential property factory for each message class that will set the credentials for obfuscated credentials when requested.


Instruction:
Explain what the following Python 3 code does
def validate_property(attr):

    def getter(instance):
        return instance.__dict__[attr]

    def setter(instance, value):
        validate_input(instance.__class__.__name__, attr, value)
        instance.__dict__[attr] = value

    return property(fget=getter, fset=setter)

Response: A property factory that will dispatch the to a specific validator function that will validate the user s input to ensure critical parameters are of the specific type.


Instruction:
Can you generate the documentation for the following Python 3 function
def validate_input(msg_type, attr, value):
    try:
        valid = {
            "Email": validate_email,
            "Twilio": validate_twilio,
            "SlackWebhook": validate_slackwebhook,
            "SlackPost": validate_slackpost,
            "TelegramBot": validate_telegrambot,
            "WhatsApp": validate_whatsapp,
        }[msg_type](attr, value)
    except KeyError:
        return 1
    else:
        return 0

Response: Base function to validate input dispatched via message type.


Instruction:
Create a Python 3 function for
checking if input is valid as per .

Response:
def check_valid(msg_type, attr, value, func, exec_info):
    """
    Checker function all validate_* functions below will call.
    Raises InvalidMessageInputError if input is not valid as per
    given func.
    """
    if value is not None:
        if isinstance(value, MutableSequence):
            for v in value:
                if not func(v):
                    raise InvalidMessageInputError(msg_type, attr, value, exec_info)
        else:
            if not func(value):
                raise InvalidMessageInputError(msg_type, attr, value, exec_info)


Instruction:
Here you have a function in Python 3, explain what it does
def validate_twilio(attr, value):
    if attr in ("from_", "to"):
        check_valid("Twilio", attr, value, validus.isphone, "phone number")
    elif attr in ("attachments"):
        check_valid("Twilio", attr, value, validus.isurl, "url")

Response: Twilio input validator function.


Instruction:
Can you tell what is the following Python 3 function doing
def validate_whatsapp(attr, value):
    if attr in ("from_", "to"):
        if value is not None and "whatsapp:" in value:
            value = value.split("whatsapp:+")[-1]
        check_valid(
            "WhatsApp",
            attr,
            value,
            validus.isint,
            "phone number starting with the '+' symbol",
        )
    elif attr in ("attachments"):
        check_valid("WhatsApp", attr, value, validus.isurl, "url")

Response: WhatsApp input validator function.


Instruction:
Can you generate the documentation for the following Python 3 function
def _send_coroutine():
    with PoolExecutor() as executor:
        while True:
            msg = yield
            future = executor.submit(msg.send)
            future.add_done_callback(_exception_handler)

Response: Creates a running coroutine to receive message instances and send them in a futures executor.


Instruction:
Explain what the following Python 3 code does
def add_message(self, msg):
        try:
            self._coro.send(msg)
        except AttributeError:
            raise UnsupportedMessageTypeError(msg.__class__.__name__)

Response: Add a message to the futures executor.


Instruction:
Can you tell what is the following Python 3 function doing
def get_body_from_file(kwds):
    if kwds["file"] and os.path.isfile(kwds["file"]):
        kwds["body"] = open(kwds["file"], "r").read()
        kwds["file"] = None

Response: Reads message body if specified via filepath.


Instruction:
Implement a Python 3 function for
getting rid of args with value of None as well as select keys.

Response:
def trim_args(kwds):
    """Gets rid of args with value of None, as well as select keys."""
    reject_key = ("type", "types", "configure")
    reject_val = (None, ())
    kwargs = {
        k: v for k, v in kwds.items() if k not in reject_key and v not in reject_val
    }
    for k, v in kwargs.items():
        if k in ("to", "cc", "bcc", "attachments"):
            kwargs[k] = list(kwargs[k])
    return kwargs


Instruction:
Can you generate a brief explanation for the following Python 3 code
def send_message(msg_type, kwds):
    if kwds["file"]:
        get_body_from_file(kwds)
    kwargs = trim_args(kwds)
    send(msg_type, send_async=False, **kwargs)

Response: Send a message to the current page.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_chat_id(self, username):
        if username is not None:
            chats = requests.get(self.base_url + "/getUpdates").json()
            user = username.split("@")[-1]
            for chat in chats["result"]:
                if chat["message"]["from"]["username"] == user:
                    return chat["message"]["from"]["id"]

Response: Lookup chat_id of username if chat_id is unknown via API call.


Instruction:
Make a summary of the following Python 3 code
def _construct_message(self):
        self.message["chat_id"] = self.chat_id
        self.message["text"] = ""
        if self.from_:
            self.message["text"] += "From: " + self.from_ + "\n"
        if self.subject:
            self.message["text"] += "Subject: " + self.subject + "\n"

        self.message["text"] += self.body
        self.message.update(self.params)

Response: Build the message params.


Instruction:
Make a summary of the following Python 3 code
def _send_content(self, method="/sendMessage"):
        url = self.base_url + method

        try:
            resp = requests.post(url, json=self.message)
            resp.raise_for_status()
        except requests.exceptions.HTTPError as e:
            raise MessageSendError(e)

        if self.verbose:
            if method == "/sendMessage":
                content_type = "Message body"
            elif method == "/sendDocument":
                content_type = "Attachment: " + self.message["document"]
            print(timestamp(), content_type, "sent.")

Response: send content via HTTP POST.


Instruction:
Create a Python 3 function for
starting sending the message and attachments.

Response:
def send(self):
        """Start sending the message and attachments."""
        self._construct_message()

        if self.verbose:
            print(
                "Debugging info"
                "\n--------------"
                "\n{} Message created.".format(timestamp())
            )

        self._send_content("/sendMessage")

        if self.attachments:
            if isinstance(self.attachments, str):
                self.attachments = [self.attachments]
            for a in self.attachments:
                self.message["document"] = a
                self._send_content(method="/sendDocument")

        if self.verbose:
            print(
                timestamp(),
                type(self).__name__ + " info:",
                self.__str__(indentation="\n * "),
            )

        print("Message sent.")


Instruction:
Implement a function in Python 3 to
send the SMS message.

Response:
def send(self):
        """
        Send the SMS/MMS message.
        Set self.sid to return code of message.
        """
        url = (
            "https://api.twilio.com/2010-04-01/Accounts/"
            + self._auth[0]
            + "/Messages.json"
        )
        data = {
            "From": self.from_,
            "To": self.to,
            "Body": self.body,
            "MediaUrl": self.attachments,
        }

        if self.verbose:
            print(
                "Debugging info"
                "\n--------------"
                "\n{} Message created.".format(timestamp())
            )

        try:
            resp = requests.post(url, data=data, auth=(self._auth[0], self._auth[1]))
            resp.raise_for_status()
        except requests.exceptions.RequestException as e:
            exc = "{}\n{}".format(e, resp.json()["message"])
            raise MessageSendError(exc)

        self.sid = resp.json()["sid"]

        if self.verbose:
            print(
                timestamp(),
                type(self).__name__ + " info:",
                self.__str__(indentation="\n * "),
                "\n * HTTP status code:",
                resp.status_code,
            )

        print("Message sent.")

        return resp


Instruction:
How would you code a function in Python 3 to
return an SMTP servername guess from outgoing email address.

Response:
def get_server(address=None):
        """Return an SMTP servername guess from outgoing email address."""
        if address:
            domain = address.split("@")[1]
            try:
                return SMTP_SERVERS[domain]
            except KeyError:
                return ("smtp." + domain, 465)
        return (None, None)


Instruction:
Given the following Python 3 function, write the documentation
def _generate_email(self):
        self.message = MIMEMultipart()
        self._add_header()
        self._add_body()
        self._add_attachments()

Response: Put the parts of the email together.


Instruction:
Can you implement a function in Python 3 that
adds email header info.

Response:
def _add_header(self):
        """Add email header info."""
        self.message["From"] = self.from_
        self.message["Subject"] = self.subject
        if self.to:
            self.message["To"] = self.list_to_string(self.to)
        if self.cc:
            self.message["Cc"] = self.list_to_string(self.cc)
        if self.bcc:
            self.message["Bcc"] = self.list_to_string(self.bcc)


Instruction:
Can you generate the documentation for the following Python 3 function
def _add_body(self):
        if self.body:
            b = MIMEText("text", "plain")
            b.set_payload(self.body)
            self.message.attach(b)

Response: Add body content of email.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _get_session(self):
        if self.port in (465, "465"):
            session = self._get_ssl()
        elif self.port in (587, "587"):
            session = self._get_tls()

        try:
            session.login(self.from_, self._auth)
        except SMTPResponseException as e:
            raise MessageSendError(e.smtp_error.decode("unicode_escape"))

        return session

Response: Start session with email server.


Instruction:
Make a summary of the following Python 3 code
def _get_ssl(self):
        return smtplib.SMTP_SSL(
            self.server, self.port, context=ssl.create_default_context()
        )

Response: Get an SMTP_SSL object.


Instruction:
Can you implement a function in Python 3 that
gets an SMTP session with TLS.

Response:
def _get_tls(self):
        """Get an SMTP session with TLS."""
        session = smtplib.SMTP(self.server, self.port)
        session.ehlo()
        session.starttls(context=ssl.create_default_context())
        session.ehlo()
        return session


Instruction:
Write a Python 3 script to
send the message. First, a message is constructed, then a session with the email servers is created, finally the message is sent and the session is stopped.

Response:
def send(self):
        """
        Send the message.
        First, a message is constructed, then a session with the email
        servers is created, finally the message is sent and the session
        is stopped.
        """
        self._generate_email()

        if self.verbose:
            print(
                "Debugging info"
                "\n--------------"
                "\n{} Message created.".format(timestamp())
            )

        recipients = []
        for i in (self.to, self.cc, self.bcc):
            if i:
                if isinstance(i, MutableSequence):
                    recipients += i
                else:
                    recipients.append(i)

        session = self._get_session()
        if self.verbose:
            print(timestamp(), "Login successful.")

        session.sendmail(self.from_, recipients, self.message.as_string())
        session.quit()

        if self.verbose:
            print(timestamp(), "Logged out.")

        if self.verbose:
            print(
                timestamp(),
                type(self).__name__ + " info:",
                self.__str__(indentation="\n * "),
            )

        print("Message sent.")


Instruction:
How would you explain what the following Python 3 function does
def delete(self, filename=None):

        if self.tags is not None:
            if filename is None:
                filename = self.filename
            else:
                warnings.warn(
                    "delete(filename=...) is deprecated, reload the file",
                    DeprecationWarning)
            return self.tags.delete(filename)

Response: Remove tags from a file.


Instruction:
Make a summary of the following Python 3 code
def unload(self):
        '''Releases renderer resources associated with this image.'''
        if self._handle != -1:
            lib.UnloadImage(self._handle)
        self._handle = -1

Response: Releases renderer resources associated with this image.


Instruction:
Given the following Python 3 function, write the documentation
def get_region(self, x1, y1, x2, y2):
        '''Get an image that refers to the given rectangle within this image.  The image data is not actually
        copied; if the image region is rendered into, it will affect this image.

        :param int x1: left edge of the image region to return
        :param int y1: top edge of the image region to return
        :param int x2: right edge of the image region to return
        :param int y2: bottom edge of the image region to return
        :return: :class:`Image`
        '''
        handle = c_int()
        lib.GetImageRegion(byref(handle), self._handle, x1, y1, x2, y2)
        return Image(width = x2 - x1, height = y2 - y1, content_scale = self._content_scale, handle = handle)

Response: Get an image that refers to the given rectangle within this image.


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

    global output_dir

    try:
        opts, args = getopt.getopt( sys.argv[1:], \
                                    "hb",         \
                                    ["help", "backup"] )
    except getopt.GetoptError:
        usage()
        sys.exit( 2 )

    if args == []:
        usage()
        sys.exit( 1 )

    # process options
    #
    output_dir = None
    do_backup  = None

    for opt in opts:
        if opt[0] in ( "-h", "--help" ):
            usage()
            sys.exit( 0 )

        if opt[0] in ( "-b", "--backup" ):
            do_backup = 1

    # create context and processor
    source_processor = SourceProcessor()

    # retrieve the list of files to process
    file_list = make_file_list( args )
    for filename in file_list:
        source_processor.parse_file( filename )

        for block in source_processor.blocks:
            beautify_block( block )

        new_name = filename + ".new"
        ok       = None

        try:
            file = open( new_name, "wt" )
            for block in source_processor.blocks:
                for line in block.lines:
                    file.write( line )
                    file.write( "\n" )
            file.close()
        except:
            ok = 0

Response: main entry point for the get_resource_file command


Instruction:
Can you generate a brief explanation for the following Python 3 code
def connect(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):

    from route53.connection import Route53Connection
    return Route53Connection(
        aws_access_key_id,
        aws_secret_access_key,
        **kwargs
    )

Response:
Creates a new connection to the Amazon s Route 53
    API.


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

        # be stricter in Python 3
        if PY3:
            if not isinstance(self.vendor, text_type):
                raise ValueError
            for key, value in self:
                if not isinstance(key, text_type):
                    raise ValueError
                if not isinstance(value, text_type):
                    raise ValueError

        if not isinstance(self.vendor, text_type):
            try:
                self.vendor.decode('utf-8')
            except UnicodeDecodeError:
                raise ValueError

        for key, value in self._internal:
            try:
                if not is_valid_key(key):
                    raise ValueError
            except:
                raise ValueError("%r is not a valid key" % key)

            if not isinstance(value, text_type):
                try:
                    value.decode("utf-8")
                except:
                    raise ValueError("%r is not a valid value" % value)
        else:
            return True

Response: Validate keys and values.


Instruction:
How would you implement a function in Python 3 that
clears all keys from the comment.

Response:
def clear(self):
        """Clear all keys from the comment."""

        for i in list(self._internal):
            self._internal.remove(i)


Instruction:
Write a Python 3 script to
return a string representation of the data.

Response:
def write(self, framing=True):
        """Return a string representation of the data.

        Validation is always performed, so calling this function on
        invalid data may raise a ValueError.

        Keyword arguments:

        * framing -- if true, append a framing bit (see load)
        """

        self.validate()

        def _encode(value):
            if not isinstance(value, bytes):
                return value.encode('utf-8')
            return value

        f = BytesIO()
        vendor = _encode(self.vendor)
        f.write(cdata.to_uint_le(len(vendor)))
        f.write(vendor)
        f.write(cdata.to_uint_le(len(self)))
        for tag, value in self._internal:
            tag = _encode(tag)
            value = _encode(value)
            comment = tag + b"=" + value
            f.write(cdata.to_uint_le(len(comment)))
            f.write(comment)
        if framing:
            f.write(b"\x01")
        return f.getvalue()


Instruction:
Explain what the following Python 3 code does
def read(self):
        self.__fileobj.seek(self.data_offset)
        self.data = self.__fileobj.read(self.data_size)

Response: Read the chunks data


Instruction:
Can you implement a function in Python 3 that
removes the chunk from the file

Response:
def delete(self):
        """Removes the chunk from the file"""
        delete_bytes(self.__fileobj, self.size, self.offset)
        if self.parent_chunk is not None:
            self.parent_chunk.resize(self.parent_chunk.data_size - self.size)


Instruction:
Make a summary of the following Python 3 code
def resize(self, data_size):
        self.__fileobj.seek(self.offset + 4)
        self.__fileobj.write(pack('>I', data_size))
        if self.parent_chunk is not None:
            size_diff = self.data_size - data_size
            self.parent_chunk.resize(self.parent_chunk.data_size - size_diff)
        self.data_size = data_size
        self.size = data_size + self.HEADER_SIZE

Response: Update the size of the file object


Instruction:
Can you tell what is the following Python 3 function doing
def insert_chunk(self, id_):

        if not isinstance(id_, text_type):
            id_ = id_.decode('ascii')

        if not is_valid_chunk_id(id_):
            raise KeyError("AIFF key must be four ASCII characters.")

        self.__fileobj.seek(self.__next_offset)
        self.__fileobj.write(pack('>4si', id_.ljust(4).encode('ascii'), 0))
        self.__fileobj.seek(self.__next_offset)
        chunk = IFFChunk(self.__fileobj, self[u'FORM'])
        self[u'FORM'].resize(self[u'FORM'].data_size + chunk.size)

        self.__chunks[id_] = chunk
        self.__next_offset = chunk.offset + chunk.size

Response: Insert a new chunk at the end of the IFF file


Instruction:
How would you explain what the following Python 3 function does
def save(self, filename=None, v2_version=4, v23_sep='/'):

        framedata = self._prepare_framedata(v2_version, v23_sep)
        framesize = len(framedata)

        if filename is None:
            filename = self.filename

        # Unlike the parent ID3.save method, we won't save to a blank file
        # since we would have to construct a empty AIFF file
        fileobj = open(filename, 'rb+')
        iff_file = IFFFile(fileobj)

        try:
            if u'ID3' not in iff_file:
                iff_file.insert_chunk(u'ID3')

            chunk = iff_file[u'ID3']
            fileobj.seek(chunk.data_offset)

            header = fileobj.read(10)
            header = self._prepare_id3_header(header, framesize, v2_version)
            header, new_size, _ = header

            data = header + framedata + (b'\x00' * (new_size - framesize))

            # Include ID3 header size in 'new_size' calculation
            new_size += 10

            # Expand the chunk if necessary, including pad byte
            if new_size > chunk.size:
                insert_at = chunk.offset + chunk.size
                insert_size = new_size - chunk.size + new_size % 2
                insert_bytes(fileobj, insert_size, insert_at)
                chunk.resize(new_size)

            fileobj.seek(chunk.data_offset)
            fileobj.write(data)
        finally:
            fileobj.close()

Response: Save the ID3v2 data to the AIFF file.


Instruction:
Can you implement a function in Python 3 that
loads stream and tag information from a file.

Response:
def load(self, filename, **kwargs):
        """Load stream and tag information from a file."""
        self.filename = filename

        try:
            self.tags = _IFFID3(filename, **kwargs)
        except ID3Error:
            self.tags = None

        try:
            fileobj = open(filename, "rb")
            self.info = AIFFInfo(fileobj)
        finally:
            fileobj.close()


Instruction:
Explain what the following Python 3 code does
def  parse_file( self, filename ):
        self.reset()

        self.filename = filename

        fileinput.close()
        self.format = None
        self.lineno = 0
        self.lines  = []

        for line in fileinput.input( filename ):
            # strip trailing newlines, important on Windows machines!
            if line[-1] == '\012':
                line = line[0:-1]

            if self.format == None:
                self.process_normal_line( line )
            else:
                if self.format.end.match( line ):
                    # that's a normal block end, add it to 'lines' and
                    # create a new block
                    self.lines.append( line )
                    self.add_block_lines()
                elif self.format.column.match( line ):
                    # that's a normal column line, add it to 'lines'
                    self.lines.append( line )
                else:
                    # humm.. this is an unexpected block end,
                    # create a new block, but don't process the line
                    self.add_block_lines()

                    # we need to process the line again
                    self.process_normal_line( line )

        # record the last lines
        self.add_block_lines()

Response: parse a C source file and add its blocks to the processor s list


Instruction:
Implement a function in Python 3 to
process a normal line and check whether it is the start of a new block

Response:
def  process_normal_line( self, line ):
        """process a normal line and check whether it is the start of a new block"""
        for f in re_source_block_formats:
            if f.start.match( line ):
                self.add_block_lines()
                self.format = f
                self.lineno = fileinput.filelineno()

        self.lines.append( line )


Instruction:
Create a Python 3 function for
adding the current accumulated lines and create a new block

Response:
def  add_block_lines( self ):
        """add the current accumulated lines and create a new block"""
        if self.lines != []:
            block = SourceBlock( self, self.filename, self.lineno, self.lines )

            self.blocks.append( block )
            self.format = None
            self.lines  = []


Instruction:
Write a Python 3 function for
drawing a string with the given font.

Response:
def draw_string(font, text, x, y, width=None, height=None, align=Alignment.left, vertical_align=VerticalAlignment.baseline):
    '''Draw a string with the given font.

    :note: Text alignment and word-wrapping is not yet implemented.  The text is rendered with the left edge and
        baseline at ``(x, y)``.

    :param font: the :class:`Font` to render text with
    :param text: a string of text to render.
    '''
    style = Style(font)
    run = GlyphRun(style, text)
    glyph_layout = GlyphLayout([run], x, y, width, height, align, vertical_align)
    draw_glyph_layout(glyph_layout)


Instruction:
Given the following Python 3 function, write the documentation
def draw_glyph_layout(glyph_layout):
    '''Draw a prepared :class:`GlyphLayout`
    '''
    pushed_color = False

    # Draw lines
    for line in glyph_layout.lines:
        x = line.x
        y = line.y

        for run in line.runs:
            style = run.style
            if style.color is not None:
                if not pushed_color:
                    bacon.push_color()
                    pushed_color = True
                bacon.set_color(*style.color)
            elif pushed_color:
                bacon.pop_color()
                pushed_color = False

            for glyph in run.glyphs:
                if glyph.image:
                    bacon.draw_image(glyph.image, x + glyph.offset_x, y - glyph.offset_y)
                x += glyph.advance

    if pushed_color:
        bacon.pop_color()

Response: Draw a prepared glyph layout.


Instruction:
Can you tell what is the following Python 3 function doing
def parse_iso_8601_time_str(time_str):
    if re.search('\.\d{3}Z$', time_str):
        submitted_at = datetime.datetime.strptime(time_str, \
            '%Y-%m-%dT%H:%M:%S.%fZ')
    else:
        submitted_at = datetime.datetime.strptime(time_str, \
            '%Y-%m-%dT%H:%M:%SZ')
    # Parse the string, and make it explicitly UTC.
    return submitted_at.replace(tzinfo=UTC_TIMEZONE)

Response: Parses a standard ISO 8601 time string.


Instruction:
Write a Python 3 script to
convert a series of simple words into some HTML text

Response:
def  make_html_words( self, words ):
        """ convert a series of simple words into some HTML text """
        line = ""
        if words:
            line = html_quote( words[0] )
            for w in words[1:]:
                line = line + " " + html_quote( w )

        return line


Instruction:
Write a Python 3 function for
analyzing a simple word to detect cross - references and styling

Response:
def  make_html_word( self, word ):
        """analyze a simple word to detect cross-references and styling"""
        # look for cross-references
        m = re_crossref.match( word )
        if m:
            try:
                name = m.group( 1 )
                rest = m.group( 2 )
                block = self.identifiers[name]
                url   = self.make_block_url( block )
                return '' + name + '' + rest
            except:
                # we detected a cross-reference to an unknown item
                sys.stderr.write( \
                   "WARNING: undefined cross reference '" + name + "'.\n" )
                return '?' + name + '?' + rest

        # look for italics and bolds
        m = re_italic.match( word )
        if m:
            name = m.group( 1 )
            rest = m.group( 3 )
            return '' + name + '' + rest

        m = re_bold.match( word )
        if m:
            name = m.group( 1 )
            rest = m.group( 3 )
            return '' + name + '' + rest

        return html_quote( word )


Instruction:
Given the following Python 3 function, write the documentation
def  make_html_para( self, words ):
        line = ""
        if words:
            line = self.make_html_word( words[0] )
            for word in words[1:]:
                line = line + " " + self.make_html_word( word )
            # convert `...' quotations into real left and right single quotes
            line = re.sub( r"(^|\W)`(.*?)'(\W|$)",  \
                           r'\1‘\2’\3', \
                           line )
            # convert tilde into non-breakable space
            line = string.replace( line, "~", " " )

        return para_header + line + para_footer

Response: convert words of a paragraph into tagged HTML text


Instruction:
How would you code a function in Python 3 to
convert a code sequence to HTML

Response:
def  make_html_code( self, lines ):
        """ convert a code sequence to HTML """
        line = code_header + '\n'
        for l in lines:
            line = line + html_quote( l ) + '\n'

        return line + code_footer


Instruction:
How would you implement a function in Python 3 that
converts a field s content into some valid HTML

Response:
def  make_html_items( self, items ):
        """ convert a field's content into some valid HTML """
        lines = []
        for item in items:
            if item.lines:
                lines.append( self.make_html_code( item.lines ) )
            else:
                lines.append( self.make_html_para( item.words ) )

        return string.join( lines, '\n' )


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

    global output_dir

    try:
        opts, args = getopt.getopt( sys.argv[1:], \
                                    "ht:o:p:",    \
                                    ["help", "title=", "output=", "prefix="] )
    except getopt.GetoptError:
        usage()
        sys.exit( 2 )

    if args == []:
        usage()
        sys.exit( 1 )

    # process options
    #
    project_title  = "Project"
    project_prefix = None
    output_dir     = None

    for opt in opts:
        if opt[0] in ( "-h", "--help" ):
            usage()
            sys.exit( 0 )

        if opt[0] in ( "-t", "--title" ):
            project_title = opt[1]

        if opt[0] in ( "-o", "--output" ):
            utils.output_dir = opt[1]

        if opt[0] in ( "-p", "--prefix" ):
            project_prefix = opt[1]

    check_output()

    # create context and processor
    source_processor  = SourceProcessor()
    content_processor = ContentProcessor()

    # retrieve the list of files to process
    file_list = make_file_list( args )
    for filename in file_list:
        source_processor.parse_file( filename )
        content_processor.parse_sources( source_processor )

    # process sections
    content_processor.finish()

    formatter = HtmlFormatter( content_processor, project_title, project_prefix )

    formatter.toc_dump()
    formatter.index_dump()
    formatter.section_dump_all()

Response: main function for the base class


Instruction:
Given the following Python 3 function, write the documentation
def get_hosted_zone_by_id_parser(root, connection):

    e_zone = root.find('./{*}HostedZone')
    # This pops out a HostedZone instance.
    hosted_zone =  parse_hosted_zone(e_zone, connection)
    # Now we'll fill in the nameservers.
    e_delegation_set = root.find('./{*}DelegationSet')
    # Modifies the HostedZone in place.
    parse_delegation_set(hosted_zone, e_delegation_set)
    return hosted_zone

Response: Parses the API responses for the get_hosted_zone_by_id method.


Instruction:
Can you write a function in Python 3 where it
saves the metadata to the given filename.

Response:
def save(self, filename):
        """Save the metadata to the given filename."""

        values = []
        items = sorted(self.items(), key=MP4Tags.__get_sort_stats )
        for key, value in items:
            info = self.__atoms.get(key[:4], (None, type(self).__render_text))
            try:
                values.append(info[1](self, key, value, *info[2:]))
            except (TypeError, ValueError) as s:
                reraise(MP4MetadataValueError, s, sys.exc_info()[2])
        data = Atom.render(b"ilst", b"".join(values))

        # Find the old atoms.
        fileobj = open(filename, "rb+")
        try:
            atoms = Atoms(fileobj)
            try:
                path = atoms.path(b"moov", b"udta", b"meta", b"ilst")
            except KeyError:
                self.__save_new(fileobj, atoms, data)
            else:
                self.__save_existing(fileobj, atoms, path, data)
        finally:
            fileobj.close()


Instruction:
How would you implement a function in Python 3 that
updates all parent atoms with the new size.

Response:
def __update_parents(self, fileobj, path, delta):
        """Update all parent atoms with the new size."""
        for atom in path:
            fileobj.seek(atom.offset)
            size = cdata.uint_be(fileobj.read(4))
            if size == 1:  # 64bit
                # skip name (4B) and read size (8B)
                size = cdata.ulonglong_be(fileobj.read(12)[4:])
                fileobj.seek(atom.offset + 8)
                fileobj.write(cdata.to_ulonglong_be(size + delta))
            else:  # 32bit
                fileobj.seek(atom.offset)
                fileobj.write(cdata.to_uint_be(size + delta))


Instruction:
How would you explain what the following Python 3 function does
def run(game):
    '''Start running the game.  The window is created and shown at this point, and then
    the main event loop is entered.  'game.on_tick' and other event handlers are called
    repeatedly until the game exits.

    If a game is already running, this function replaces the :class:`Game` instance that
    receives events.
    '''
    if bacon._current_game:
        bacon._current_game = game
        return

    global _tick_callback_handle
    bacon._current_game = game

    # Window handler
    window_resize_callback_handle = lib.WindowResizeEventHandler(window._window_resize_event_handler)
    lib.SetWindowResizeEventHandler(window_resize_callback_handle)

    # Key handler
    key_callback_handle = lib.KeyEventHandler(keyboard._key_event_handler)
    lib.SetKeyEventHandler(key_callback_handle)

    # Mouse handlers
    mouse_button_callback_handle = lib.MouseButtonEventHandler(mouse_input._mouse_button_event_handler)
    lib.SetMouseButtonEventHandler(mouse_button_callback_handle)
    mouse_scroll_callback_handle = lib.MouseScrollEventHandler(mouse_input._mouse_scroll_event_handler)
    lib.SetMouseScrollEventHandler(mouse_scroll_callback_handle)

    # Controller handlers
    controller_connected_handle = lib.ControllerConnectedEventHandler(controller._controller_connected_event_handler)
    lib.SetControllerConnectedEventHandler(controller_connected_handle)
    controller_button_handle = lib.ControllerButtonEventHandler(controller._controller_button_event_handler)
    lib.SetControllerButtonEventHandler(controller_button_handle)
    controller_axis_handle = lib.ControllerAxisEventHandler(controller._controller_axis_event_handler)
    lib.SetControllerAxisEventHandler(controller_axis_handle)

    # Tick handler
    _tick_callback_handle = lib.TickCallback(_first_tick_callback)
    lib.SetTickCallback(_tick_callback_handle)

    lib.Run()
    bacon._current_game = None
    _tick_callback_handle = None

    lib.SetWindowResizeEventHandler(lib.WindowResizeEventHandler(0))
    lib.SetKeyEventHandler(lib.KeyEventHandler(0))
    lib.SetMouseButtonEventHandler(lib.MouseButtonEventHandler(0))
    lib.SetMouseScrollEventHandler(lib.MouseScrollEventHandler(0))
    lib.SetControllerConnectedEventHandler(lib.ControllerConnectedEventHandler(0))
    lib.SetControllerButtonEventHandler(lib.ControllerButtonEventHandler(0))
    lib.SetControllerAxisEventHandler(lib.ControllerAxisEventHandler(0))
    lib.SetTickCallback(lib.TickCallback(0))

Response:
Start running the game.  The window is created and shown at this point, and then
    the main event loop is entered.  'game.on_tick' and other event handlers are called
    repeatedly until the game exits.

    If a game is already running, this function replaces the :class:`Game` instance that
    receives events.


Instruction:
Can you tell what is the following Python 3 function doing
def register(cls, vendor_id, product_id, mapping):
        '''Register a mapping for controllers with the given vendor and product IDs.  The mapping will
        replace any existing mapping for these IDs for controllers not yet connected.

        :param vendor_id: the vendor ID of the controller, as reported by :attr:`Controller.vendor_id`
        :param product_id: the vendor ID of the controller, as reported by :attr:`Controller.product_id`
        :param mapping: a :class:`ControllerMapping` to apply
        '''
        cls._registry[(vendor_id, product_id)] = mapping

Response: Register a mapping for controllers with the given vendor and product IDs.


Instruction:
Implement a function in Python 3 to
return the controller mapping that can apply to the given controller. Returns None if unsuccessful.

Response:
def get(cls, controller):
        '''Find a mapping that can apply to the given controller.  Returns None if unsuccessful.

        :param controller: :class:`Controller` to look up
        :return: :class:`ControllerMapping`
        '''
        try:
            return cls._registry[(controller.vendor_id, controller.product_id)]
        except KeyError:
            return None


Instruction:
Make a summary of the following Python 3 code
def RegisterFreeformKey(cls, key, name, mean=b"com.apple.iTunes"):
        atomid = b"----:" + mean + b":" + name

        def getter(tags, key):
            return [s.decode("utf-8", "replace") for s in tags[atomid]]

        def setter(tags, key, value):
            tags[atomid] = [utf8(v) for v in value]

        def deleter(tags, key):
            del(tags[atomid])

        cls.RegisterKey(key, getter, setter, deleter)

Response: Register a text key.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_request_headers(self):

        date_header = time.asctime(time.gmtime())
        # We sign the time string above with the user's AWS secret access key
        # in order to authenticate our request.
        signing_key = self._hmac_sign_string(date_header)

        # Amazon's super fun auth token.
        auth_header = "AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=HmacSHA256,Signature=%s" % (
            self.connection._aws_access_key_id,
            signing_key,
        )

        return {
            'X-Amzn-Authorization': auth_header,
            'x-amz-date': date_header,
            'Host': 'route53.amazonaws.com',
        }

Response: Determine the headers to send along with the request.


Instruction:
Explain what the following Python 3 code does
def send_request(self, path, data, method):

        headers = self.get_request_headers()

        if method == 'GET':
            return self._send_get_request(path, data, headers)
        elif method == 'POST':
            return self._send_post_request(path, data, headers)
        elif method == 'DELETE':
            return self._send_delete_request(path, headers)
        else:
            raise Route53Error("Invalid request method: %s" % method)

Response: This method is used to send out a request to the route53 server. It defers to the route53 HTTP method - specific methods.


Instruction:
Can you implement a function in Python 3 that
sends a GET request to the Route53 endpoint.

Response:
def _send_get_request(self, path, params, headers):
        """
        Sends the GET request to the Route53 endpoint.

        :param str path: The path to tack on to the endpoint URL for
            the query.
        :param dict params: Key/value pairs to send.
        :param dict headers: A dict of headers to send with the request.
        :rtype: str
        :returns: The body of the response.
        """

        r = requests.get(self.endpoint + path, params=params, headers=headers)
        r.raise_for_status()
        return r.text


Instruction:
Here you have a function in Python 3, explain what it does
def _send_post_request(self, path, data, headers):

        r = requests.post(self.endpoint + path, data=data, headers=headers)
        return r.text

Response: Sends a POST request to the Route53 endpoint.


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

        r = requests.delete(self.endpoint + path, headers=headers)
        return r.text

Response: Sends a DELETE request to the Route53 endpoint.


Instruction:
Implement a function in Python 3 to
load tags from a file.

Response:
def load(self, filename):
        """Load tags from a filename."""

        self.filename = filename
        fileobj = open(filename, "rb")
        try:
            data = _APEv2Data(fileobj)
        finally:
            fileobj.close()
        if data.tag:
            self.clear()
            self.__casemap.clear()
            self.__parse_tag(data.tag, data.items)
        else:
            raise APENoHeaderError("No APE tag found")


Instruction:
Can you generate the documentation for the following Python 3 function
def save(self, filename=None):

        filename = filename or self.filename
        try:
            fileobj = open(filename, "r+b")
        except IOError:
            fileobj = open(filename, "w+b")
        data = _APEv2Data(fileobj)

        if data.is_at_start:
            delete_bytes(fileobj, data.end - data.start, data.start)
        elif data.start is not None:
            fileobj.seek(data.start)
            # Delete an ID3v1 tag if present, too.
            fileobj.truncate()
        fileobj.seek(0, 2)

        # "APE tags items should be sorted ascending by size... This is
        # not a MUST, but STRONGLY recommended. Actually the items should
        # be sorted by importance/byte, but this is not feasible."
        tags = sorted((v._internal(k) for k, v in self.items()), key=len)
        num_tags = len(tags)
        tags = b"".join(tags)

        header = bytearray(b"APETAGEX")
        # version, tag size, item count, flags
        header += struct.pack("<4I", 2000, len(tags) + 32, num_tags,
                              HAS_HEADER | IS_HEADER)
        header += b"\0" * 8
        fileobj.write(header)

        fileobj.write(tags)

        footer = bytearray(b"APETAGEX")
        footer += struct.pack("<4I", 2000, len(tags) + 32, num_tags,
                              HAS_HEADER)
        footer += b"\0" * 8

        fileobj.write(footer)
        fileobj.close()

Response: Save the current state of the APE tags to a file.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def delete(self, filename=None):

        filename = filename or self.filename
        fileobj = open(filename, "r+b")
        try:
            data = _APEv2Data(fileobj)
            if data.start is not None and data.size is not None:
                delete_bytes(fileobj, data.end - data.start, data.start)
        finally:
            fileobj.close()
        self.clear()

Response: Remove tags from a file.


Instruction:
Can you implement a function in Python 3 that
sends a request to the Route53 API and returns the response.

Response:
def _send_request(self, path, data, method):
        """
        Uses the HTTP transport to query the Route53 API. Runs the response
        through lxml's parser, before we hand it off for further picking
        apart by our call-specific parsers.

        :param str path: The RESTful path to tack on to the :py:attr:`endpoint`.
        :param data: The params to send along with the request.
        :type data: Either a dict or bytes, depending on the request type.
        :param str method: One of 'GET', 'POST', or 'DELETE'.
        :rtype: lxml.etree._Element
        :returns: An lxml Element root.
        """

        response_body = self._transport.send_request(path, data, method)
        root = etree.fromstring(response_body)
        #print(prettyprint_xml(root))
        return root


Instruction:
Can you generate the documentation for the following Python 3 function
def _do_autopaginating_api_call(self, path, params, method, parser_func,
        next_marker_xpath, next_marker_param_name,
        next_type_xpath=None, parser_kwargs=None):
        """
        Given an API method, the arguments passed to it, and a function to
        hand parsing off to, loop through the record sets in the API call
        until all records have been yielded.

        :param str method: The API method on the endpoint.
        :param dict params: The kwargs from the top-level API method.
        :param callable parser_func: A callable that is used for parsing the
            output from the API call.
        :param str next_marker_param_name: The XPath to the marker tag that
            will determine whether we continue paginating.
        :param str next_marker_param_name: The parameter name to manipulate
            in the request data to bring up the next page on the next
            request loop.
        :keyword str next_type_xpath: For the
            py:meth:`list_resource_record_sets_by_zone_id` method, there's
            an additional paginator token. Specifying this XPath looks for it.
        :keyword dict parser_kwargs: Optional dict of additional kwargs to pass
            on to the parser function.
        :rtype: generator
        :returns: Returns a generator that may be returned by the top-level
            API method.
        """

        if not parser_kwargs:
            parser_kwargs = {}

        # We loop indefinitely since we have no idea how many "pages" of
        # results we're going to have to go through.
        while True:
            # An lxml Element node.
            root = self._send_request(path, params, method)

            # Individually yield HostedZone instances after parsing/instantiating.
            for record in parser_func(root, connection=self, **parser_kwargs):
                yield record

            # This will determine at what offset we start the next query.
            next_marker = root.find(next_marker_xpath)
            if next_marker is None:
                # If the NextMarker tag is absent, we know we've hit the
                # last page.
                break

            # if NextMarker is present, we'll adjust our API request params
            # and query again for the next page.
            params[next_marker_param_name] = next_marker.text

            if next_type_xpath:
                # This is a _list_resource_record_sets_by_zone_id call. Look
                # for the given tag via XPath and adjust our type arg for
                # the next request. Without specifying this, we loop
                # infinitely.
                next_type = root.find(next_type_xpath)
                params['type'] = next_type.text

Response: This method will loop through the resource record sets in the API call to get the next page of the next record set.


Instruction:
Write a Python 3 script for
listing all hosted zones associated with this connection's account. Since this method returns a generator, you can pull as many or as few entries as you'd like, without having to query and receive every hosted zone you may have. :keyword int page_chunks: This API call is "paginated" behind-the-scenes in order to break up large result sets. This number determines the maximum number of :py:class:`HostedZone <route53.hosted_zone.HostedZone>` instances to retrieve per request. The default is fine for almost everyone. :rtype: generator :returns: A generator of :py:class:`HostedZone <route53.hosted_zone.HostedZone>` instances.

Response:
def list_hosted_zones(self, page_chunks=100):
        """
        List all hosted zones associated with this connection's account. Since
        this method returns a generator, you can pull as many or as few
        entries as you'd like, without having to query and receive every
        hosted zone you may have.

        :keyword int page_chunks: This API call is "paginated" behind-the-scenes
            in order to break up large result sets. This number determines
            the maximum number of
            :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
            instances to retrieve per request. The default is fine for almost
            everyone.

        :rtype: generator
        :returns: A generator of :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
            instances.
        """

        return  self._do_autopaginating_api_call(
            path='hostedzone',
            params={'maxitems': page_chunks},
            method='GET',
            parser_func=xml_parsers.list_hosted_zones_parser,
            next_marker_xpath="./{*}NextMarker",
            next_marker_param_name="marker",
        )


Instruction:
Can you generate the documentation for the following Python 3 function
def create_hosted_zone(self, name, caller_reference=None, comment=None):

        body = xml_generators.create_hosted_zone_writer(
            connection=self,
            name=name,
            caller_reference=caller_reference,
            comment=comment
        )

        root = self._send_request(
            path='hostedzone',
            data=body,
            method='POST',
        )

        return xml_parsers.created_hosted_zone_parser(
            root=root,
            connection=self
        )

Response: Creates and returns a new hosted zone.


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

        root = self._send_request(
            path='hostedzone/%s' % id,
            data={},
            method='GET',
        )

        return xml_parsers.get_hosted_zone_by_id_parser(
            root=root,
            connection=self,
        )

Response: Retrieves a hosted zone by ID.


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

        root = self._send_request(
            path='hostedzone/%s' % id,
            data={},
            method='DELETE',
        )

        return xml_parsers.delete_hosted_zone_by_id_parser(
            root=root,
            connection=self,
        )

Response: Deletes a hosted zone by ID.


Instruction:
Make a summary of the following Python 3 code
def _list_resource_record_sets_by_zone_id(self, id, rrset_type=None,
                                             identifier=None, name=None,
                                             page_chunks=100):
        """
        Lists a hosted zone's resource record sets by Zone ID, if you
        already know it.

        .. tip:: For most cases, we recommend going through a
            :py:class:`HostedZone <route53.hosted_zone.HostedZone>`
            instance's
            :py:meth:`HostedZone.record_sets <route53.hosted_zone.HostedZone.record_sets>`
            property, but this saves an HTTP request if you already know the
            zone's ID.

        :param str id: The ID of the zone whose record sets we're listing.
        :keyword str rrset_type: The type of resource record set to begin the
            record listing from.
        :keyword str identifier: Weighted and latency resource record sets
            only: If results were truncated for a given DNS name and type,
            the value of SetIdentifier for the next resource record set
            that has the current DNS name and type.
        :keyword str name: Not really sure what this does.
        :keyword int page_chunks: This API call is paginated behind-the-scenes
            by this many ResourceRecordSet instances. The default should be
            fine for just about everybody, aside from those with tons of RRS.

        :rtype: generator
        :returns: A generator of ResourceRecordSet instances.
        """

        params = {
            'name': name,
            'type': rrset_type,
            'identifier': identifier,
            'maxitems': page_chunks,
        }

        return  self._do_autopaginating_api_call(
            path='hostedzone/%s/rrset' % id,
            params=params,
            method='GET',
            parser_func=xml_parsers.list_resource_record_sets_by_zone_id_parser,
            parser_kwargs={'zone_id': id},
            next_marker_xpath="./{*}NextRecordName",
            next_marker_param_name="name",
            next_type_xpath="./{*}NextRecordType"
        )

Response: This method returns a generator of ResourceRecordSet instances for the given hosted zone ID.


Instruction:
Can you create a Python 3 function that
gives a ChangeSet POST it to the Route53 API and return a dict of change info.

Response:
def _change_resource_record_sets(self, change_set, comment=None):
        """
        Given a ChangeSet, POST it to the Route53 API.

        .. note:: You probably shouldn't be using this method directly,
            as there are convenience methods on the ResourceRecordSet
            sub-classes.

        :param change_set.ChangeSet change_set: The ChangeSet object to create
            the XML doc from.
        :keyword str comment: An optional comment to go along with the request.
        :rtype: dict
        :returns: A dict of change info, which contains some details about
            the request.
        """

        body = xml_generators.change_resource_record_set_writer(
            connection=self,
            change_set=change_set,
            comment=comment
        )

        root = self._send_request(
            path='hostedzone/%s/rrset' % change_set.hosted_zone_id,
            data=body,
            method='POST',
        )

        #print(prettyprint_xml(root))

        e_change_info = root.find('./{*}ChangeInfo')
        if e_change_info is None:
            error = root.find('./{*}Error').find('./{*}Message').text
            raise Route53Error(error)
        return parse_change_info(e_change_info)


Instruction:
Write a Python 3 function that can
draw an image. The image's top-left corner is drawn at ``(x1, y1)``, and its lower-left at ``(x2, y2)``. If ``x2`` and ``y2`` are omitted, they are calculated to render the image at its native resoultion. Note that images can be flipped and scaled by providing alternative values for ``x2`` and ``y2``. :param image: an :class:`Image` to draw

Response:
def draw_image(image, x1, y1, x2 = None, y2 = None):
    '''Draw an image.

    The image's top-left corner is drawn at ``(x1, y1)``, and its lower-left at ``(x2, y2)``.  If ``x2`` and ``y2`` are omitted, they
    are calculated to render the image at its native resoultion.

    Note that images can be flipped and scaled by providing alternative values for ``x2`` and ``y2``.

    :param image: an :class:`Image` to draw
    '''
    if x2 is None:
        x2 = x1 + image.width
    if y2 is None:
        y2 = y1 + image.height
    lib.DrawImage(image._handle, x1, y1, x2, y2)


Instruction:
Make a summary of the following Python 3 code
def draw_image_region(image, x1, y1, x2, y2,
                      ix1, iy1, ix2, iy2):
    '''Draw a rectangular region of an image.

    The part of the image contained by the rectangle in texel-space by the coordinates ``(ix1, iy1)`` to ``(ix2, iy2)`` is
    drawn at coordinates ``(x1, y1)`` to ``(x2, y2)``.  All coordinates have the origin ``(0, 0)`` at the upper-left corner.

    For example, to draw the left half of a ``100x100`` image at coordinates ``(x, y)``::

        bacon.draw_image_region(image, x, y, x + 50, y + 100,
                                0, 0, 50, 100)

    :param image: an :class:`Image` to draw
    '''
    lib.DrawImageRegion(image._handle, x1, y1, x2, y2, ix1, iy1, ix2, iy2)

Response: Draw a rectangular region of an image.


Instruction:
Can you tell what is the following Python 3 function doing
def size(self):

        header_size = 27 # Initial header size
        for datum in self.packets:
            quot, rem = divmod(len(datum), 255)
            header_size += quot + 1
        if not self.complete and rem == 0:
            # Packet contains a multiple of 255 bytes and is not
            # terminated, so we don't have a \x00 at the end.
            header_size -= 1
        header_size += sum(map(len, self.packets))
        return header_size

Response: Total size of the message.


Instruction:
Here you have a function in Python 3, explain what it does
def replace(cls, fileobj, old_pages, new_pages):

        # Number the new pages starting from the first old page.
        first = old_pages[0].sequence
        for page, seq in zip(new_pages, range(first, first + len(new_pages))):
            page.sequence = seq
            page.serial = old_pages[0].serial

        new_pages[0].first = old_pages[0].first
        new_pages[0].last = old_pages[0].last
        new_pages[0].continued = old_pages[0].continued

        new_pages[-1].first = old_pages[-1].first
        new_pages[-1].last = old_pages[-1].last
        new_pages[-1].complete = old_pages[-1].complete
        if not new_pages[-1].complete and len(new_pages[-1].packets) == 1:
            new_pages[-1].position = -1

        new_data = b''.join(cls.write(p) for p in new_pages)

        # Make room in the file for the new data.
        delta = len(new_data)
        fileobj.seek(old_pages[0].offset, 0)
        insert_bytes(fileobj, delta, old_pages[0].offset)
        fileobj.seek(old_pages[0].offset, 0)
        fileobj.write(new_data)
        new_data_end = old_pages[0].offset + delta

        # Go through the old pages and delete them. Since we shifted
        # the data down the file, we need to adjust their offsets. We
        # also need to go backwards, so we don't adjust the deltas of
        # the other pages.
        old_pages.reverse()
        for old_page in old_pages:
            adj_offset = old_page.offset + delta
            delete_bytes(fileobj, old_page.size, adj_offset)

        # Finally, if there's any discrepency in length, we need to
        # renumber the pages for the logical stream.
        if len(old_pages) != len(new_pages):
            fileobj.seek(new_data_end, 0)
            serial = new_pages[-1].serial
            sequence = new_pages[-1].sequence + 1
            cls.renumber(fileobj, serial, sequence)

Response: Replace old_pages with new_pages within fileobj.


Instruction:
Create a Python 3 function for
finding the last page of the stream serial.

Response:
def find_last(fileobj, serial):
        """Find the last page of the stream 'serial'.

        If the file is not multiplexed this function is fast. If it is,
        it must read the whole the stream.

        This finds the last page in the actual file object, or the last
        page in the stream (with eos set), whichever comes first.
        """

        # For non-muxed streams, look at the last page.
        try:
            fileobj.seek(-256*256, 2)
        except IOError:
            # The file is less than 64k in length.
            fileobj.seek(0)
        data = fileobj.read()
        try:
            index = data.rindex(b"OggS")
        except ValueError:
            raise error("unable to find final Ogg header")
        bytesobj = cBytesIO(data[index:])
        best_page = None
        try:
            page = OggPage(bytesobj)
        except error:
            pass
        else:
            if page.serial == serial:
                if page.last:
                    return page
                else:
                    best_page = page
            else:
                best_page = None

        # The stream is muxed, so use the slow way.
        fileobj.seek(0)
        try:
            page = OggPage(fileobj)
            while not page.last:
                page = OggPage(fileobj)
                while page.serial != serial:
                    page = OggPage(fileobj)
                best_page = page
            return page
        except error:
            return best_page
        except EOFError:
            return best_page


Instruction:
Given the following Python 3 function, write the documentation
def load(self, filename):

        self.filename = filename
        fileobj = open(filename, "rb")
        try:
            try:
                self.info = self._Info(fileobj)
                self.tags = self._Tags(fileobj, self.info)
                self.info._post_tags(fileobj)
            except error as e:
                reraise(self._Error, e, sys.exc_info()[2])
            except EOFError:
                raise self._Error("no appropriate stream found")
        finally:
            fileobj.close()

Response: Load information from a file.


Instruction:
Can you implement a function in Python 3 that
removes tags from a file.

Response:
def delete(self, filename=None):
        """Remove tags from a file.

        If no filename is given, the one most recently loaded is used.
        """

        if filename is None:
            filename = self.filename

        self.tags.clear()
        fileobj = open(filename, "rb+")
        try:
            try:
                self.tags._inject(fileobj)
            except error as e:
                reraise(self._Error, e, sys.exc_info()[2])
            except EOFError:
                raise self._Error("no appropriate stream found")
        finally:
            fileobj.close()


Instruction:
Make a summary of the following Python 3 code
def _inject(self, fileobj):

        fileobj.seek(0)
        page = OggPage(fileobj)
        while not page.packets[0].startswith(b"\x81theora"):
            page = OggPage(fileobj)

        old_pages = [page]
        while not (old_pages[-1].complete or len(old_pages[-1].packets) > 1):
            page = OggPage(fileobj)
            if page.serial == old_pages[0].serial:
                old_pages.append(page)

        packets = OggPage.to_packets(old_pages, strict=False)

        packets[0] = b"\x81theora" + self.write(framing=False)

        new_pages = OggPage.from_packets(packets, old_pages[0].sequence)
        OggPage.replace(fileobj, old_pages, new_pages)

Response: Write tag data into the Theora comment packet or page.


Instruction:
Explain what the following Python 3 code does
def created_hosted_zone_parser(root, connection):

    zone = root.find('./{*}HostedZone')
    # This pops out a HostedZone instance.
    hosted_zone = parse_hosted_zone(zone, connection)

    # Now we'll fill in the nameservers.
    e_delegation_set = root.find('./{*}DelegationSet')
    # Modifies the HostedZone in place.
    parse_delegation_set(hosted_zone, e_delegation_set)

    # With each CreateHostedZone request, there's some details about the
    # request's ID, status, and submission time. We'll return this in a tuple
    # just for the sake of completeness.
    e_change_info = root.find('./{*}ChangeInfo')
    # Translate the ChangeInfo values to a dict.
    change_info = parse_change_info(e_change_info)

    return hosted_zone, change_info

Response: Parses the API responses for the create_hosted_zone method.


Instruction:
Make a summary of the following Python 3 code
def  set_section( self, section_name ):
        if not self.sections.has_key( section_name ):
            section = DocSection( section_name )
            self.sections[section_name] = section
            self.section                = section
        else:
            self.section = self.sections[section_name]

Response: set current section during parsing


Instruction:
Given the following Python 3 function, write the documentation
def  add_markup( self ):
        if self.markup and self.markup_lines:

            # get rid of last line of markup if it's empty
            marks = self.markup_lines
            if len( marks ) > 0 and not string.strip( marks[-1] ):
                self.markup_lines = marks[:-1]

            m = DocMarkup( self.markup, self.markup_lines )

            self.markups.append( m )

            self.markup       = None
            self.markup_lines = []

Response: add a new markup section


Instruction:
Create a Python 3 function to
process a block content and return a list of DocMarkup objects that correspond to it

Response:
def  process_content( self, content ):
        """process a block content and return a list of DocMarkup objects
           corresponding to it"""
        markup       = None
        markup_lines = []
        first        = 1

        for line in content:
            found = None
            for t in re_markup_tags:
                m = t.match( line )
                if m:
                    found  = string.lower( m.group( 1 ) )
                    prefix = len( m.group( 0 ) )
                    line   = " " * prefix + line[prefix:]   # remove markup from line
                    break

            # is it the start of a new markup section ?
            if found:
                first = 0
                self.add_markup()  # add current markup content
                self.markup = found
                if len( string.strip( line ) ) > 0:
                    self.markup_lines.append( line )
            elif first == 0:
                self.markup_lines.append( line )

        self.add_markup()

        return self.markups


Instruction:
Write a Python 3 script to
return the DocMarkup corresponding to a given tag in a block

Response:
def  get_markup( self, tag_name ):
        """return the DocMarkup corresponding to a given tag in a block"""
        for m in self.markups:
            if m.tag == string.lower( tag_name ):
                return m
        return None


Instruction:
Can you create a Python 3 function that
creates a new hosted zone.

Response:
def create_hosted_zone_writer(connection, name, caller_reference, comment):
    """
    Forms an XML string that we'll send to Route53 in order to create
    a new hosted zone.

    :param Route53Connection connection: The connection instance used to
        query the API.
    :param str name: The name of the hosted zone to create.
    """

    if not caller_reference:
        caller_reference = str(uuid.uuid4())

    e_root = etree.Element(
        "CreateHostedZoneRequest",
        xmlns=connection._xml_namespace
    )

    e_name = etree.SubElement(e_root, "Name")
    e_name.text = name

    e_caller_reference = etree.SubElement(e_root, "CallerReference")
    e_caller_reference.text = caller_reference

    if comment:
        e_config = etree.SubElement(e_root, "HostedZoneConfig")
        e_comment = etree.SubElement(e_config, "Comment")
        e_comment.text = comment

    e_tree = etree.ElementTree(element=e_root)

    fobj = BytesIO()
    # This writes bytes.
    e_tree.write(fobj, xml_declaration=True, encoding='utf-8', method="xml")
    return fobj.getvalue().decode('utf-8')


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

    try:
        import fcntl
    except ImportError:
        return False
    else:
        try:
            fcntl.lockf(fileobj, fcntl.LOCK_EX)
        except IOError:
            # FIXME: There's possibly a lot of complicated
            # logic that needs to go here in case the IOError
            # is EACCES or EAGAIN.
            return False
        else:
            return True

Response: Lock a file object safely.


Instruction:
How would you explain what the following Python 3 function does
def insert_bytes(fobj, size, offset, BUFFER_SIZE=2**16):

    assert 0 < size
    assert 0 <= offset
    locked = False
    fobj.seek(0, 2)
    filesize = fobj.tell()
    movesize = filesize - offset
    fobj.write(b'\x00' * size)
    fobj.flush()
    try:
        try:
            import mmap
            file_map = mmap.mmap(fobj.fileno(), filesize + size)
            try:
                file_map.move(offset + size, offset, movesize)
            finally:
                file_map.close()
        except (ValueError, EnvironmentError, ImportError):
            # handle broken mmap scenarios
            locked = lock(fobj)
            fobj.truncate(filesize)

            fobj.seek(0, 2)
            padsize = size
            # Don't generate an enormous string if we need to pad
            # the file out several megs.
            while padsize:
                addsize = min(BUFFER_SIZE, padsize)
                fobj.write(b"\x00" * addsize)
                padsize -= addsize

            fobj.seek(filesize, 0)
            while movesize:
                # At the start of this loop, fobj is pointing at the end
                # of the data we need to move, which is of movesize length.
                thismove = min(BUFFER_SIZE, movesize)
                # Seek back however much we're going to read this frame.
                fobj.seek(-thismove, 1)
                nextpos = fobj.tell()
                # Read it, so we're back at the end.
                data = fobj.read(thismove)
                # Seek back to where we need to write it.
                fobj.seek(-thismove + size, 1)
                # Write it.
                fobj.write(data)
                # And seek back to the end of the unmoved data.
                fobj.seek(nextpos)
                movesize -= thismove

            fobj.flush()
    finally:
        if locked:
            unlock(fobj)

Response: Insert size bytes of empty space starting at offset.


Instruction:
Can you tell what is the following Python 3 function doing
def delete_bytes(fobj, size, offset, BUFFER_SIZE=2**16):

    locked = False
    assert 0 < size
    assert 0 <= offset
    fobj.seek(0, 2)
    filesize = fobj.tell()
    movesize = filesize - offset - size
    assert 0 <= movesize
    try:
        if movesize > 0:
            fobj.flush()
            try:
                import mmap
                file_map = mmap.mmap(fobj.fileno(), filesize)
                try:
                    file_map.move(offset, offset + size, movesize)
                finally:
                    file_map.close()
            except (ValueError, EnvironmentError, ImportError):
                # handle broken mmap scenarios
                locked = lock(fobj)
                fobj.seek(offset + size)
                buf = fobj.read(BUFFER_SIZE)
                while buf:
                    fobj.seek(offset)
                    fobj.write(buf)
                    offset += len(buf)
                    fobj.seek(offset + size)
                    buf = fobj.read(BUFFER_SIZE)
        fobj.truncate(filesize - size)
        fobj.flush()
    finally:
        if locked:
            unlock(fobj)

Response: Delete size bytes of empty space starting at offset.


Instruction:
Write a Python 3 script for
converting a basestring to a valid UTF - 8 str.

Response:
def utf8(data):
    """Convert a basestring to a valid UTF-8 str."""

    if isinstance(data, bytes):
        return data.decode("utf-8", "replace").encode("utf-8")
    elif isinstance(data, text_type):
        return data.encode("utf-8")
    else:
        raise TypeError("only unicode/bytes types can be converted to UTF-8")


Instruction:
Write a Python 3 function for
adding a change to this change set.

Response:
def add_change(self, action, record_set):
        """
        Adds a change to this change set.

        :param str action: Must be one of either 'CREATE' or 'DELETE'.
        :param resource_record_set.ResourceRecordSet record_set: The
            ResourceRecordSet object that was created or deleted.
        """

        action = action.upper()

        if action not in ['CREATE', 'DELETE']:
            raise Route53Error("action must be one of 'CREATE' or 'DELETE'")

        change_tuple = (action, record_set)

        if action == 'CREATE':
            self.creations.append(change_tuple)
        else:
            self.deletions.append(change_tuple)


Instruction:
Write a Python 3 script for
parsing a ChangeInfo tag and returns a dict representation of the change info.

Response:
def parse_change_info(e_change_info):
    """
    Parses a ChangeInfo tag. Seen in CreateHostedZone, DeleteHostedZone,
    and ChangeResourceRecordSetsRequest.

    :param lxml.etree._Element e_change_info: A ChangeInfo element.
    :rtype: dict
    :returns: A dict representation of the change info.
    """

    if e_change_info is None:
        return e_change_info

    status = e_change_info.find('./{*}Status').text
    submitted_at = e_change_info.find('./{*}SubmittedAt').text
    submitted_at = parse_iso_8601_time_str(submitted_at)

    return {
        'request_id': id,
        'request_status': status,
        'request_submitted_at': submitted_at
    }


Instruction:
Can you tell what is the following Python 3 function doing
def get_resource_path(filename):
    '''Get a path to the given filename to load as a resource.  All non-absolute filenames passed to
    :class:`Image`, :class:`Font`, :class:`Sound`, etc are transformed through this function.

    :param str filename: a relative path to a resource file
    :return str: an absolute path to the file
    '''
    path = os.path.join(resource_dir, filename)
    if _dll_dir and not os.path.exists(path):
        path = os.path.join(_dll_dir, filename)
    return path

Response: Get a path to the given filename to load as a resource.


Instruction:
How would you code a function in Python 3 to
retrieve a glyph that renders the given character.

Response:
def get_glyph(self, char):
        '''Retrieves a :class:`Glyph` that renders the given character.

        :param char: the character (a string)
        '''
        try:
            return self._glyphs[char]
        except KeyError:
            glyph = self._font_file.get_glyph(self._size, self._content_scale, char, self._flags)
            self._glyphs[char] = glyph
            return glyph


Instruction:
Create a Python 3 function to
calculate the width of the given string in this font.

Response:
def measure_string(self, str):
        '''Calculates the width of the given string in this font.

        :param str: the string to measure
        :return float: width of the string, in pixels
        '''
        style = bacon.text.Style(self)
        run = bacon.text.GlyphRun(style, str)
        glyph_layout = bacon.text.GlyphLayout([run], 0, 0)
        return glyph_layout.content_width


Instruction:
How would you code a function in Python 3 to
determine whether this record set has been modified since the last retrieval or save.

Response:
def is_modified(self):
        """
        Determines whether this record set has been modified since the
        last retrieval or save.

        :rtype: bool
        :returns: ``True` if the record set has been modified,
            and ``False`` if not.
        """

        for key, val in self._initial_vals.items():
            if getattr(self, key) != val:
                # One of the initial values doesn't match, we know
                # this object has been touched.
                return True

        return False


Instruction:
How would you implement a function in Python 3 that
deletes this record set.

Response:
def delete(self):
        """
        Deletes this record set.
        """

        cset = ChangeSet(connection=self.connection, hosted_zone_id=self.zone_id)
        cset.add_change('DELETE', self)

        return self.connection._change_resource_record_sets(cset)


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

        cset = ChangeSet(connection=self.connection, hosted_zone_id=self.zone_id)
        # Record sets can't actually be modified. You have to delete the
        # existing one and create a new one. Since this happens within a single
        # change set, it appears that the values were modified, when instead
        # the whole thing is replaced.
        cset.add_change('DELETE', self)
        cset.add_change('CREATE', self)
        retval = self.connection._change_resource_record_sets(cset)

        # Now copy the current attribute values on this instance to
        # the initial_vals dict. This will re-set the modification tracking.
        for key, val in self._initial_vals.items():
            self._initial_vals[key] = getattr(self, key)

        return retval

Response: Saves any changes to this record set.


Instruction:
Can you tell what is the following Python 3 function doing
def delete(filename, delete_v1=True, delete_v2=True):

    f = open(filename, 'rb+')

    if delete_v1:
        try:
            f.seek(-128, 2)
        except IOError:
            pass
        else:
            if f.read(3) == b'TAG':
                f.seek(-128, 2)
                f.truncate()

    # technically an insize=0 tag is invalid, but we delete it anyway
    # (primarily because we used to write it)
    if delete_v2:
        f.seek(0, 0)
        idata = f.read(10)
        try:
            id3, vmaj, vrev, flags, insize = unpack('>3sBBB4s', idata)
        except struct.error:
            id3, insize = b'', -1
        insize = BitPaddedInt(insize)
        if id3 == b'ID3' and insize >= 0:
            delete_bytes(f, insize + 10, 0)

Response: Delete tags from a file.


Instruction:
Make a summary of the following Python 3 code
def ParseID3v1(data):

    try:
        data = data[data.index(b'TAG'):]
    except ValueError:
        return None
    if 128 < len(data) or len(data) < 124:
        return None

    # Issue #69 - Previous versions of Mutagen, when encountering
    # out-of-spec TDRC and TYER frames of less than four characters,
    # wrote only the characters available - e.g. "1" or "" - into the
    # year field. To parse those, reduce the size of the year field.
    # Amazingly, "0s" works as a struct format string.
    unpack_fmt = "3s30s30s30s%ds29sBB" % (len(data) - 124)

    try:
        tag, title, artist, album, year, comment, track, genre = unpack(
            unpack_fmt, data)
    except StructError:
        return None

    if tag != b"TAG":
        return None

    def fix(data):
        return data.split(b'\x00')[0].strip().decode('latin1')

    title, artist, album, year, comment = map(
        fix, [title, artist, album, year, comment])

    frames = {}
    if title:
        frames['TIT2'] = TIT2(encoding=0, text=title)
    if artist:
        frames['TPE1'] = TPE1(encoding=0, text=[artist])
    if album:
        frames['TALB'] = TALB(encoding=0, text=album)
    if year:
        frames['TDRC'] = TDRC(encoding=0, text=year)
    if comment:
        frames['COMM'] = COMM(encoding=0, lang='eng', desc="ID3v1 Comment",
                              text=comment)

    # Don't read a track number if it looks like the comment was
    # padded with spaces instead of nulls (thanks, WinAmp).
    if track and ((track != 32) or (data[-3] == b'\x00'[0])):
        frames['TRCK'] = TRCK(encoding=0, text=str(track))
    if genre != 255:
        frames['TCON'] = TCON(encoding=0, text=str(genre))
    return frames

Response: Parse an ID3v1 tag returning a list of ID3v2. 4 frames.


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

    v1 = {}

    for v2id, name in {"TIT2": "title", "TPE1": "artist",
                       "TALB": "album"}.items():
        if v2id in id3:
            text = id3[v2id].text[0].encode('latin1', 'replace')[:30]
        else:
            text = b''
        v1[name] = text + (b'\x00' * (30 - len(text)))

    if "COMM" in id3:
        cmnt = id3["COMM"].text[0].encode('latin1', 'replace')[:28]
    else:
        cmnt = b''
    v1['comment'] = cmnt + (b'\x00' * (29 - len(cmnt)))

    if "TRCK" in id3:
        try:
            v1["track"] = chr_(+id3["TRCK"])
        except ValueError:
            v1["track"] = b'\x00'
    else:
        v1["track"] = b'\x00'

    if "TCON" in id3:
        try:
            genre = id3["TCON"].genres[0]
        except IndexError:
            pass
        else:
            if genre in TCON.GENRES:
                v1["genre"] = chr_(TCON.GENRES.index(genre))
    if "genre" not in v1:
        v1["genre"] = b"\xff"

    if "TDRC" in id3:
        year = text_type(id3["TDRC"]).encode('latin1', 'replace')
    elif "TYER" in id3:
        year = text_type(id3["TYER"]).encode('latin1', 'replace')
    else:
        year = b''
    v1['year'] = (year + b'\x00\x00\x00\x00')[:4]

    return (b'TAG' +
            v1['title'] +
            v1['artist'] +
            v1['album'] +
            v1['year'] +
            v1['comment'] +
            v1['track'] +
            v1['genre'])

Response: Make an ID3v1. 1 tag string from a dict of ID3v2. 4 frames.


Instruction:
How would you implement a function in Python 3 that
reads a certain number of bytes from the source file.

Response:
def __fullread(self, size):
        """ Read a certain number of bytes from the source file. """

        try:
            if size < 0:
                raise ValueError('Requested bytes (%s) less than zero' % size)
            if size > self.__filesize:
                raise EOFError('Requested %#x of %#x (%s)' % (
                    int(size), int(self.__filesize), self.filename))
        except AttributeError:
            pass
        data = self._fileobj.read(size)
        if len(data) != size:
            raise EOFError
        self.__readbytes += size
        return data


Instruction:
Given the following Python 3 function, write the documentation
def load(self, filename, known_frames=None, translate=True, v2_version=4):

        if not v2_version in (3, 4):
            raise ValueError("Only 3 and 4 possible for v2_version")

        from os.path import getsize

        self.filename = filename
        self.__known_frames = known_frames
        self._fileobj = open(filename, 'rb')
        self.__filesize = getsize(filename)
        try:
            try:
                self._load_header()
            except EOFError:
                self.size = 0
                raise ID3NoHeaderError("%s: too small (%d bytes)" % (
                    filename, self.__filesize))
            except (ID3NoHeaderError, ID3UnsupportedVersionError) as err:
                self.size = 0
                import sys
                stack = sys.exc_info()[2]
                try:
                    self._fileobj.seek(-128, 2)
                except EnvironmentError:
                    reraise(err, None, stack)
                else:
                    frames = ParseID3v1(self._fileobj.read(128))
                    if frames is not None:
                        self.version = self._V11
                        for v in frames.values():
                            self.add(v)
                    else:
                        reraise(err, None, stack)
            else:
                frames = self.__known_frames
                if frames is None:
                    if self._V23 <= self.version:
                        frames = Frames
                    elif self._V22 <= self.version:
                        frames = Frames_2_2
                data = self.__fullread(self.size - 10)
                for frame in self.__read_frames(data, frames=frames):
                    if isinstance(frame, Frame):
                        self.add(frame)
                    else:
                        self.unknown_frames.append(frame)
                self.__unknown_version = self.version
        finally:
            self._fileobj.close()
            del self._fileobj
            del self.__filesize
            if translate:
                if v2_version == 3:
                    self.update_to_v23()
                else:
                    self.update_to_v24()

Response: Load a tag from a file.


Instruction:
Can you generate the documentation for the following Python 3 function
def getall(self, key):
        if key in self:
            return [self[key]]
        else:
            key = key + ':'
            return [v for s, v in self.items() if s.startswith(key)]

Response: Return all frames with a given name.


Instruction:
Can you implement a function in Python 3 that
deletes all tags of a given kind ; see getall.

Response:
def delall(self, key):
        """Delete all tags of a given kind; see getall."""
        if key in self:
            del(self[key])
        else:
            key = key + ":"
            for k in self.keys():
                if k.startswith(key):
                    del(self[k])


Instruction:
Implement a Python 3 function for
deprecating ; use the add method.

Response:
def loaded_frame(self, tag):
        """Deprecated; use the add method."""
        # turn 2.2 into 2.3/2.4 tags
        if len(type(tag).__name__) == 3:
            tag = type(tag).__base__(tag)
        self[tag.HashKey] = tag


Instruction:
Can you generate the documentation for the following Python 3 function
def save(self, filename=None, v1=1, v2_version=4, v23_sep='/'):

        framedata = self._prepare_framedata(v2_version, v23_sep)
        framesize = len(framedata)

        if not framedata:
            try:
                self.delete(filename)
            except EnvironmentError as err:
                from errno import ENOENT
                if err.errno != ENOENT:
                    raise
            return

        if filename is None:
            filename = self.filename
        try:
            f = open(filename, 'rb+')
        except IOError as err:
            from errno import ENOENT
            if err.errno != ENOENT:
                raise
            f = open(filename, 'ab')  # create, then reopen
            f = open(filename, 'rb+')
        try:
            idata = f.read(10)

            header = self._prepare_id3_header(idata, framesize, v2_version)
            header, outsize, insize = header

            data = header + framedata + (b'\x00' * (outsize - framesize))

            if (insize < outsize):
                insert_bytes(f, outsize-insize, insize+10)
            f.seek(0)
            f.write(data)

            try:
                f.seek(-128, 2)
            except IOError as err:
                # If the file is too small, that's OK - it just means
                # we're certain it doesn't have a v1 tag.
                from errno import EINVAL
                if err.errno != EINVAL:
                    # If we failed to see for some other reason, bail out.
                    raise
                # Since we're sure this isn't a v1 tag, don't read it.
                f.seek(0, 2)

            data = f.read(128)
            try:
                idx = data.index(b"TAG")
            except ValueError:
                offset = 0
                has_v1 = False
            else:
                offset = idx - len(data)
                has_v1 = True

            f.seek(offset, 2)
            if v1 == 1 and has_v1 or v1 == 2:
                f.write(MakeID3v1(self))
            else:
                f.truncate()

        finally:
            f.close()

Response: Save the ID3v2 tags to a file.


Instruction:
How would you explain what the following Python 3 function does
def delete(self, filename=None, delete_v1=True, delete_v2=True):
        if filename is None:
            filename = self.filename
        delete(filename, delete_v1, delete_v2)
        self.clear()

Response: Remove tags from a file.


Instruction:
Can you create a Python 3 function that
updates done by both v23 and v24 update.

Response:
def __update_common(self):
        """Updates done by both v23 and v24 update"""

        if "TCON" in self:
            # Get rid of "(xx)Foobr" format.
            self["TCON"].genres = self["TCON"].genres

        if self.version < self._V23:
            # ID3v2.2 PIC frames are slightly different.
            pics = self.getall("APIC")
            mimes = {"PNG": "image/png", "JPG": "image/jpeg"}
            self.delall("APIC")
            for pic in pics:
                newpic = APIC(
                    encoding=pic.encoding, mime=mimes.get(pic.mime, pic.mime),
                    type=pic.type, desc=pic.desc, data=pic.data)
                self.add(newpic)

            # ID3v2.2 LNK frames are just way too different to upgrade.
            self.delall("LINK")


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

        self.__update_common()

        if self.__unknown_version == self._V23:
            # convert unknown 2.3 frames (flags/size) to 2.4
            converted = []
            for frame in self.unknown_frames:
                try:
                    name, size, flags = unpack('>4sLH', frame[:10])
                    frame = BinaryFrame.fromData(self, flags, frame[10:])
                except (struct.error, error):
                    continue
                name = name.decode('ascii')
                converted.append(self.__save_frame(frame, name=name))
            self.unknown_frames[:] = converted
            self.__unknown_version = self._V24

        # TDAT, TYER, and TIME have been turned into TDRC.
        try:
            date = text_type(self.get("TYER", ""))
            if date.strip(u"\x00"):
                self.pop("TYER")
                dat = text_type(self.get("TDAT", ""))
                if dat.strip("\x00"):
                    self.pop("TDAT")
                    date = "%s-%s-%s" % (date, dat[2:], dat[:2])
                    time = text_type(self.get("TIME", ""))
                    if time.strip("\x00"):
                        self.pop("TIME")
                        date += "T%s:%s:00" % (time[:2], time[2:])
                if "TDRC" not in self:
                    self.add(TDRC(encoding=0, text=date))
        except UnicodeDecodeError:
            # Old ID3 tags have *lots* of Unicode problems, so if TYER
            # is bad, just chuck the frames.
            pass

        # TORY can be the first part of a TDOR.
        if "TORY" in self:
            f = self.pop("TORY")
            if "TDOR" not in self:
                try:
                    self.add(TDOR(encoding=0, text=str(f)))
                except UnicodeDecodeError:
                    pass

        # IPLS is now TIPL.
        if "IPLS" in self:
            f = self.pop("IPLS")
            if "TIPL" not in self:
                self.add(TIPL(encoding=f.encoding, people=f.people))

        # These can't be trivially translated to any ID3v2.4 tags, or
        # should have been removed already.
        for key in ["RVAD", "EQUA", "TRDA", "TSIZ", "TDAT", "TIME", "CRM"]:
            if key in self:
                del(self[key])

Response: Convert old ID3v2. 4 tags into an ID3v2. 4 tag.


Instruction:
Can you tell what is the following Python 3 function doing
def update_to_v23(self):

        self.__update_common()

        # we could downgrade unknown v2.4 frames here, but given that
        # the main reason to save v2.3 is compatibility and this
        # might increase the chance of some parser breaking.. better not

        # TMCL, TIPL -> TIPL
        if "TIPL" in self or "TMCL" in self:
            people = []
            if "TIPL" in self:
                f = self.pop("TIPL")
                people.extend(f.people)
            if "TMCL" in self:
                f = self.pop("TMCL")
                people.extend(f.people)
            if "IPLS" not in self:
                self.add(IPLS(encoding=f.encoding, people=people))

        # TDOR -> TORY
        if "TDOR" in self:
            f = self.pop("TDOR")
            if f.text:
                d = f.text[0]
                if d.year and "TORY" not in self:
                    self.add(TORY(encoding=f.encoding, text="%04d" % d.year))

        # TDRC -> TYER, TDAT, TIME
        if "TDRC" in self:
            f = self.pop("TDRC")
            if f.text:
                d = f.text[0]
                if d.year and "TYER" not in self:
                    self.add(TYER(encoding=f.encoding, text="%04d" % d.year))
                if d.month and d.day and "TDAT" not in self:
                    self.add(TDAT(encoding=f.encoding,
                                  text="%02d%02d" % (d.day, d.month)))
                if d.hour and d.minute and "TIME" not in self:
                    self.add(TIME(encoding=f.encoding,
                                  text="%02d%02d" % (d.hour, d.minute)))

        # New frames added in v2.4
        v24_frames = [
            'ASPI', 'EQU2', 'RVA2', 'SEEK', 'SIGN', 'TDEN', 'TDOR',
            'TDRC', 'TDRL', 'TDTG', 'TIPL', 'TMCL', 'TMOO', 'TPRO',
            'TSOA', 'TSOP', 'TSOT', 'TSST',
        ]

        for key in v24_frames:
            if key in self:
                del(self[key])

Response: Convert older and newer tags into an ID3v2. 3 tag.


Instruction:
Can you create a Python 3 function that
loads stream and tag information from a file.

Response:
def load(self, filename, ID3=None, **kwargs):
        """Load stream and tag information from a file.

        A custom tag reader may be used in instead of the default
        mutagen.id3.ID3 object, e.g. an EasyID3 reader.
        """

        if ID3 is None:
            ID3 = self.ID3
        else:
            # If this was initialized with EasyID3, remember that for
            # when tags are auto-instantiated in add_tags.
            self.ID3 = ID3
        self.filename = filename
        try:
            self.tags = ID3(filename, **kwargs)
        except error:
            self.tags = None
        if self.tags is not None:
            try:
                offset = self.tags.size
            except AttributeError:
                offset = None
        else:
            offset = None
        try:
            fileobj = open(filename, "rb")
            self.info = self._Info(fileobj, offset)
        finally:
            fileobj.close()


Instruction:
Given the following Python 3 function, write the documentation
def unload(self):
        '''Release all resources associated with the sound.'''
        if self._handle != -1:
            lib.UnloadSound(self._handle)
            self._handle = -1

Response: Release all resources associated with the sound.


Instruction:
Implement a Python 3 function for
playing the sound as a one - shot.

Response:
def play(self, gain=None, pan=None, pitch=None):
        '''Play the sound as a `one-shot`.

        The sound will be played to completion.  If the sound is played more than once at a time, it will mix
        with all previous instances of itself.  If you need more control over the playback of sounds, see
        :class:`Voice`.

        :param gain: optional volume level to play the sound back at, between 0.0 and 1.0 (defaults to 1.0)
        :param pan: optional stereo pan, between -1.0 (left) and 1.0 (right)
        :param pitch: optional sampling rate modification, between 0.4 and 16.0, where 1.0 represents the original pitch
        '''
        if gain is None and pan is None and pitch is None:
            lib.PlaySound(self._handle)
        else:
            voice = Voice(self)
            if gain is not None:
                voice.gain = gain
            if pan is not None:
                voice.pan = pan
            if pitch is not None:
                voice.pitch = pitch
            voice.play()


Instruction:
How would you explain what the following Python 3 function does
def set_loop_points(self, start_sample=-1, end_sample=0):
        '''Set the loop points within the sound.

        The sound must have been created with ``loop=True``.  The default parameters cause the loop points to be set to
        the entire sound duration.

        :note: There is currently no API for converting sample numbers to times.
        :param start_sample: sample number to loop back to
        :param end_sample: sample number to loop at
        '''
        lib.SetVoiceLoopPoints(self._handle, start_sample, end_sample)

Response: Set the loop points within the sound.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def list_hosted_zones_parser(root, connection):

    # The rest of the list pagination tags are handled higher up in the stack.
    # We'll just worry about the HostedZones tag, which has HostedZone tags
    # nested beneath it.
    zones = root.find('./{*}HostedZones')

    for zone in zones:
        yield parse_hosted_zone(zone, connection)

Response:
Parses the API responses for the
    :py : meth : Route53Connection. list_hosted_zones method.


Instruction:
Implement a Python 3 function for
returning the list of glyph names and their unicode values

Response:
def adobe_glyph_values():
  """return the list of glyph names and their unicode values"""

  lines  = string.split( adobe_glyph_list, '\n' )
  glyphs = []
  values = []

  for line in lines:
    if line:
      fields = string.split( line, ';' )
#     print fields[1] + ' - ' + fields[0]
      subfields = string.split( fields[1], ' ' )
      if len( subfields ) == 1:
        glyphs.append( fields[0] )
        values.append( fields[1] )

  return glyphs, values


Instruction:
How would you explain what the following Python 3 function does
def filter_glyph_names( alist, filter ):

  count  = 0
  extras = []

  for name in alist:
    try:
      filtered_index = filter.index( name )
    except:
      extras.append( name )

  return extras

Response: filter alist by taking out all glyph names that are in filter


Instruction:
Write a Python 3 script for
dumping a given encoding

Response:
def dump_encoding( file, encoding_name, encoding_list ):
  """dump a given encoding"""

  write = file.write
  write( "  /* the following are indices into the SID name table */\n" )
  write( "  static const unsigned short  " + encoding_name +
         "[" + repr( len( encoding_list ) ) + "] =\n" )
  write( "  {\n" )

  line  = "    "
  comma = ""
  col   = 0
  for value in encoding_list:
    line += comma
    line += "%3d" % value
    comma = ","
    col  += 1
    if col == 16:
      col = 0
      comma = ",\n    "

  write( line + "\n  };\n\n\n" )