Instruction:
Given the following Python 3 function, write the documentation
def _serial_connect(self, port, request):
        '''
        Handle connection request.

        Parameters
        ----------
        port : str
            Device name/port.
        request : dict
        '''
        #     baudrate : int
        #         Baud rate such as 9600 or 115200 etc.
        #     bytesize : str, optional
        #         Number of data bits.
        #
        #         Possible values: ``'FIVEBITS'``, ``'SIXBITS'``, ``'SEVENBITS'``,
        #         ``'EIGHTBITS'``.
        #
        #         Default: ``'EIGHTBITS'``
        #     parity : str, optional
        #         Enable parity checking.
        #
        #         Possible values: ``'PARITY_NONE'``, ``'PARITY_EVEN'``, ``'PARITY_ODD'``,
        #         ``'PARITY_MARK'``, ``'PARITY_SPACE'``.
        #
        #         Default: ``'PARITY_NONE'``
        #     stopbits : str, optional
        #         Number of stop bits.
        #
        #         Possible values: STOPBITS_ONE, STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO
        #     xonxoff : bool, optional
        #         Enable software flow control.
        #
        #         Default: ``False``
        #     rtscts : bool, optional
        #         Enable hardware (RTS/CTS) flow control.
        #
        #         Default: ``False``
        #     dsrdtr : bool, optional
        #         Enable hardware (DSR/DTR) flow control.
        #
        #         Default: ``False``
        command = 'connect'
        if port in self.open_devices:
            logger.debug('Already connected to: `%s`', port)
            self._publish_status(port)
            return

        # TODO Write JSON schema definition for valid connect request.
        if 'baudrate' not in request:
            logger.error('Invalid `%s` request: `baudrate` must be '
                         'specified.', command)
            return
        if 'bytesize' in request:
            try:
                bytesize = getattr(serial, request['bytesize'])
                if not bytesize in serial.Serial.BYTESIZES:
                    logger.error('`%s` request: `bytesize` `%s` not '
                                 'available on current platform.', command,
                                 request['bytesize'])
                    return
            except AttributeError as exception:
                logger.error('`%s` request: invalid `bytesize`, `%s`', command,
                             request['bytesize'])
                return
        else:
            bytesize = serial.EIGHTBITS
        if 'parity' in request:
            try:
                parity = getattr(serial, request['parity'])
                if not parity in serial.Serial.PARITIES:
                    logger.error('`%s` request: `parity` `%s` not available '
                                 'on current platform.', command,
                                 request['parity'])
                    return
            except AttributeError as exception:
                logger.error('`%s` request: invalid `parity`, `%s`', command,
                             request['parity'])
                return
        else:
            parity = serial.PARITY_NONE
        if 'stopbits' in request:
            try:
                stopbits = getattr(serial, request['stopbits'])
                if not stopbits in serial.Serial.STOPBITS:
                    logger.error('`%s` request: `stopbits` `%s` not '
                                 'available on current platform.', command,
                                 request['stopbits'])
                    return
            except AttributeError as exception:
                logger.error('`%s` request: invalid `stopbits`, `%s`', command,
                             request['stopbits'])
                return
        else:
            stopbits = serial.STOPBITS_ONE

        try:
            baudrate = int(request['baudrate'])
            xonxoff = bool(request.get('xonxoff'))
            rtscts = bool(request.get('rtscts'))
            dsrdtr = bool(request.get('dsrdtr'))
        except TypeError as exception:
            logger.error('`%s` request: %s', command, exception)
            return

        try:
            device = serial.serial_for_url(port, baudrate=baudrate,
                                           bytesize=bytesize, parity=parity,
                                           stopbits=stopbits, xonxoff=xonxoff,
                                           rtscts=rtscts, dsrdtr=dsrdtr)
            parent = self

            class PassThroughProtocol(serial.threaded.Protocol):
                PORT = port

                def connection_made(self, transport):
                    """Called when reader thread is started"""
                    parent.open_devices[port] = transport
                    parent._publish_status(self.PORT)

                def data_received(self, data):
                    """Called with snippets received from the serial port"""
                    parent.mqtt_client.publish(topic='serial_device/%s/received'
                                               % self.PORT, payload=data)

                def connection_lost(self, exception):
                    """\
                    Called when the serial port is closed or the reader loop terminated
                    otherwise.
                    """
                    if isinstance(exception, Exception):
                        logger.error('Connection to port `%s` lost: %s',
                                     self.PORT, exception)
                    del parent.open_devices[self.PORT]
                    parent._publish_status(self.PORT)

            reader_thread = serial.threaded.ReaderThread(device,
                                                         PassThroughProtocol)
            reader_thread.start()
            reader_thread.connect()
        except Exception as exception:
            logger.error('`%s` request: %s', command, exception)
            return

Response:
Handle connection request.

        Parameters
        ----------
        port : str
            Device name/port.
        request : dict


Instruction:
Write a Python 3 function that can
send data to a connected device.

Response:
def _serial_send(self, port, payload):
        '''
        Send data to connected device.

        Parameters
        ----------
        port : str
            Device name/port.
        payload : bytes
            Payload to send to device.
        '''
        if port not in self.open_devices:
            # Not connected to device.
            logger.error('Error sending data: `%s` not connected', port)
            self._publish_status(port)
        else:
            try:
                device = self.open_devices[port]
                device.write(payload)
                logger.debug('Sent data to `%s`', port)
            except Exception as exception:
                logger.error('Error sending data to `%s`: %s', port, exception)


Instruction:
Write a Python 3 function that can
print a datetime object

Response:
def print_datetime_object(dt):
    """prints a date-object"""
    print(dt)
    print('ctime  :', dt.ctime())
    print('tuple  :', dt.timetuple())
    print('ordinal:', dt.toordinal())
    print('Year   :', dt.year)
    print('Mon    :', dt.month)
    print('Day    :', dt.day)


Instruction:
Write a Python 3 script for
including the settings for how to examine the raw limits for the current and voltage of the current and voltage of the current and voltage of the current and voltage of the current and voltage of the current and voltage of the current and voltage of the current and voltage of the current and voltage are stable.

Response:
def get_raw_limits(self):
        """Include the settings for how to decide what kind of step you are examining here.

        The raw limits are 'epsilons' used to check if the current and/or voltage is stable (for example
        for galvanostatic steps, one would expect that the current is stable (constant) and non-zero).
        It is expected that different instruments (with different resolution etc.) have different
        'epsilons'.

        Returns: the raw limits (dict)

        """
        warnings.warn("raw limits have not been subject for testing yet")
        raw_limits = dict()
        raw_limits["current_hard"] = 0.1  # There is a bug in PEC
        raw_limits["current_soft"] = 1.0
        raw_limits["stable_current_hard"] = 2.0
        raw_limits["stable_current_soft"] = 4.0
        raw_limits["stable_voltage_hard"] = 2.0
        raw_limits["stable_voltage_soft"] = 4.0
        raw_limits["stable_charge_hard"] = 2.0
        raw_limits["stable_charge_soft"] = 5.0
        raw_limits["ir_change"] = 0.00001
        return raw_limits


Instruction:
Implement a function in Python 3 to
check if you are on a 64 bit platform

Response:
def check64bit(current_system="python"):
    """checks if you are on a 64 bit platform"""
    if current_system == "python":
        return sys.maxsize > 2147483647
    elif current_system == "os":
        import platform
        pm = platform.machine()
        if pm != ".." and pm.endswith('64'):  # recent Python (not Iron)
            return True
        else:
            if 'PROCESSOR_ARCHITEW6432' in os.environ:
                return True  # 32 bit program running on 64 bit Windows
            try:
                # 64 bit Windows 64 bit program
                return os.environ['PROCESSOR_ARCHITECTURE'].endswith('64')
            except IndexError:
                pass  # not Windows
            try:
                # this often works in Linux
                return '64' in platform.architecture()[0]
            except Exception:
                # is an older version of Python, assume also an older os@
                # (best we can guess)
                return False


Instruction:
Implement a function in Python 3 to
return a humanized string representation of a number of b.

Response:
def humanize_bytes(b, precision=1):
    """Return a humanized string representation of a number of b.

    Assumes `from __future__ import division`.

    >>> humanize_bytes(1)
    '1 byte'
    >>> humanize_bytes(1024)
    '1.0 kB'
    >>> humanize_bytes(1024*123)
    '123.0 kB'
    >>> humanize_bytes(1024*12342)
    '12.1 MB'
    >>> humanize_bytes(1024*12342,2)
    '12.05 MB'
    >>> humanize_bytes(1024*1234,2)
    '1.21 MB'
    >>> humanize_bytes(1024*1234*1111,2)
    '1.31 GB'
    >>> humanize_bytes(1024*1234*1111,1)
    '1.3 GB'
    """
    # abbrevs = (
    #     (1 << 50L, 'PB'),
    #     (1 << 40L, 'TB'),
    #     (1 << 30L, 'GB'),
    #     (1 << 20L, 'MB'),
    #     (1 << 10L, 'kB'),
    #     (1, 'b')
    # )
    abbrevs = (
        (1 << 50, 'PB'),
        (1 << 40, 'TB'),
        (1 << 30, 'GB'),
        (1 << 20, 'MB'),
        (1 << 10, 'kB'),
        (1, 'b')
    )
    if b == 1:
        return '1 byte'
    for factor, suffix in abbrevs:
        if b >= factor:
            break
    # return '%.*f %s' % (precision, old_div(b, factor), suffix)
    return '%.*f %s' % (precision, b // factor, suffix)


Instruction:
Create a Python 3 function for
converting a xls date stamp to a more sensible datetime object.

Response:
def xldate_as_datetime(xldate, datemode=0, option="to_datetime"):
    """Converts a xls date stamp to a more sensible format.

    Args:
        xldate (str): date stamp in Excel format.
        datemode (int): 0 for 1900-based, 1 for 1904-based.
        option (str): option in ("to_datetime", "to_float", "to_string"),
            return value

    Returns:
        datetime (datetime object, float, or string).

    """

    # This does not work for numpy-arrays

    if option == "to_float":
        d = (xldate - 25589) * 86400.0
    else:
        try:
            d = datetime.datetime(1899, 12, 30) + \
                datetime.timedelta(days=xldate + 1462 * datemode)
            # date_format = "%Y-%m-%d %H:%M:%S:%f" # with microseconds,
            # excel cannot cope with this!
            if option == "to_string":
                date_format = "%Y-%m-%d %H:%M:%S"  # without microseconds
                d = d.strftime(date_format)
        except TypeError:
            logging.info(f'The date is not of correct type [{xldate}]')
            d = xldate
    return d


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

        if os.path.isfile(filename):
            fid_st = os.stat(filename)
            self.name = os.path.abspath(filename)
            self.full_name = filename
            self.size = fid_st.st_size
            self.last_modified = fid_st.st_mtime
            self.last_accessed = fid_st.st_atime
            self.last_info_changed = fid_st.st_ctime
            self.location = os.path.dirname(filename)

Response: Finds the file - stats and populates the class with stat values.


Instruction:
Explain what the following Python 3 code does
def get_raw(self):
        return [self.name, self.size, self.last_modified, self.location]

Response: Get a list with information about the file.


Instruction:
Can you generate the documentation for the following Python 3 function
def dfsummary_made(self):
        try:
            empty = self.dfsummary.empty
        except AttributeError:
            empty = True
        return not empty

Response: check if the summary table exists


Instruction:
Explain what the following Python 3 code does
def step_table_made(self):
        try:
            empty = self.step_table.empty
        except AttributeError:
            empty = True
        return not empty

Response: check if the step table exists


Instruction:
How would you code a function in Python 3 to
open sheets and returns it

Response:
def _open_sheet(self, dtypes_dict=None):
        """Opens sheets and returns it"""
        table_name = self.db_sheet_table
        header_row = self.db_header_row
        nrows = self.nrows
        if dtypes_dict is None:
            dtypes_dict = self.dtypes_dict

        rows_to_skip = self.skiprows

        logging.debug(f"Trying to open the file {self.db_file}")
        logging.debug(f"Number of rows: {nrows}")
        logging.debug(f"Skipping the following rows: {rows_to_skip}")
        logging.debug(f"Declaring the following dtyps: {dtypes_dict}")
        work_book = pd.ExcelFile(self.db_file)
        try:
            sheet = work_book.parse(
                table_name, header=header_row, skiprows=rows_to_skip,
                dtype=dtypes_dict, nrows=nrows,
            )
        except ValueError as e:
            logging.debug("Could not parse all the columns (ValueError) "
                          "using given dtypes. Trying without dtypes.")
            logging.debug(str(e))
            sheet = work_book.parse(
                table_name, header=header_row, skiprows=rows_to_skip,
                nrows=nrows,
            )

        return sheet


Instruction:
Write a Python 3 function for
checking that the db - file is ok Returns True if OK False if not.

Response:
def _validate(self):
        """Checks that the db-file is ok

        Returns:
            True if OK, False if not.
            """
        probably_good_to_go = True
        sheet = self.table
        identity = self.db_sheet_cols.id

        # check if you have unique srnos
        id_col = sheet.loc[:, identity]
        if any(id_col.duplicated()):
            warnings.warn(
                "your database is corrupt: duplicates"
                " encountered in the srno-column")
            logger.debug("srno duplicates:\n" + str(
                id_col.duplicated()))
            probably_good_to_go = False
        return probably_good_to_go


Instruction:
Create a Python 3 function for
selecting row for identification number serial_number

Response:
def select_serial_number_row(self, serial_number):
        """Select row for identification number serial_number

        Args:
            serial_number: serial number

        Returns:
            pandas.DataFrame
        """
        sheet = self.table
        col = self.db_sheet_cols.id
        rows = sheet.loc[:, col] == serial_number
        return sheet.loc[rows, :]


Instruction:
Write a Python 3 script to
select rows for identification for a list of serial numbers.

Response:
def select_all(self, serial_numbers):
        """Select rows for identification for a list of serial_number.

        Args:
            serial_numbers: list (or ndarray) of serial numbers

        Returns:
            pandas.DataFrame
        """
        sheet = self.table
        col = self.db_sheet_cols.id
        rows = sheet.loc[:, col].isin(serial_numbers)
        return sheet.loc[rows, :]


Instruction:
Make a summary of the following Python 3 code
def print_serial_number_info(self, serial_number, print_to_screen=True):
        r = self.select_serial_number_row(serial_number)
        if r.empty:
            warnings.warn("missing serial number")
            return

        txt1 = 80 * "="
        txt1 += "\n"
        txt1 += f"   serial number {serial_number}\n"
        txt1 = 80 * "-"
        txt1 += "\n"
        txt2 = ""
        for label, value in zip(r.columns, r.values[0]):
            if label in self.headers:
                txt1 += f"{label}:    \t {value}\n"
            else:
                txt2 += f"({label}:    \t {value})\n"
        if print_to_screen:
            print(txt1)
            print(80 * "-")
            print(txt2)
            print(80 * "=")
            return
        else:
            return txt1

Response: Print information about the run.


Instruction:
Implement a function in Python 3 to
filter the table by slurry name.

Response:
def filter_by_slurry(self, slurry, appender="_"):
        """Filters sheet/table by slurry name.

        Input is slurry name or list of slurry names, for example 'es030' or
        ["es012","es033","es031"].

        Args:
            slurry (str or list of strings): slurry names.
            appender (chr): char that surrounds slurry names.

        Returns:
            List of serial_number (ints).
        """

        sheet = self.table
        identity = self.db_sheet_cols.id
        exists = self.db_sheet_cols.exists
        cellname = self.db_sheet_cols.cell_name
        search_string = ""

        if not isinstance(slurry, (list, tuple)):
            slurry = [slurry, ]

        first = True
        for slur in slurry:
            s_s = appender + slur + appender
            if first:
                search_string = s_s
                first = False
            else:
                search_string += "|"
                search_string += s_s

        criterion = sheet.loc[:, cellname].str.contains(
            search_string
        )
        exists = sheet.loc[:, exists] > 0
        sheet = sheet[criterion & exists]

        return sheet.loc[:, identity].values.astype(int)


Instruction:
Write a Python 3 function for
filtering sheet or table by columns

Response:
def filter_by_col(self, column_names):
        """filters sheet/table by columns (input is column header)

        The routine returns the serial numbers with values>1 in the selected
        columns.

        Args:
            column_names (list): the column headers.

        Returns:
            pandas.DataFrame
        """

        if not isinstance(column_names, (list, tuple)):
            column_names = [column_names, ]

        sheet = self.table
        identity = self.db_sheet_cols.id
        exists = self.db_sheet_cols.exists
        criterion = True

        for column_name in column_names:
            _criterion = sheet.loc[:, column_name] > 0
            _exists = sheet.loc[:, exists] > 0
            criterion = criterion & _criterion & _exists

        return sheet.loc[criterion, identity].values.astype(int)


Instruction:
How would you explain what the following Python 3 function does
def filter_by_col_value(self, column_name,
                            min_val=None, max_val=None):
        """filters sheet/table by column.

        The routine returns the serial-numbers with min_val <= values >= max_val
        in the selected column.

        Args:
            column_name (str): column name.
            min_val (int): minimum value of serial number.
            max_val (int): maximum value of serial number.

        Returns:
            pandas.DataFrame
        """
        sheet = self.table
        identity = self.db_sheet_cols.id
        exists_col_number = self.db_sheet_cols.exists

        exists = sheet.loc[:, exists_col_number] > 0

        if min_val is not None and max_val is not None:

            criterion1 = sheet.loc[:, column_name] >= min_val
            criterion2 = sheet.loc[:, column_name] <= max_val
            sheet = sheet[criterion1 & criterion2 & exists]

        elif min_val is not None or max_val is not None:

            if min_val is not None:
                criterion = sheet.loc[:, column_name] >= min_val

            if max_val is not None:
                criterion = sheet.loc[:, column_name] <= max_val

            # noinspection PyUnboundLocalVariable
            sheet = sheet[criterion & exists]
        else:
            sheet = sheet[exists]

        return sheet.loc[:, identity].values.astype(int)

Response: filters sheet or table by column.


Instruction:
Can you generate the documentation for the following Python 3 function
def select_batch(self, batch, batch_col_name=None):

        if not batch_col_name:
            batch_col_name = self.db_sheet_cols.batch
        logger.debug("selecting batch - %s" % batch)
        sheet = self.table
        identity = self.db_sheet_cols.id
        exists_col_number = self.db_sheet_cols.exists

        criterion = sheet.loc[:, batch_col_name] == batch
        exists = sheet.loc[:, exists_col_number] > 0
        # This will crash if the col is not of dtype number
        sheet = sheet[criterion & exists]
        return sheet.loc[:, identity].values.astype(int)

Response: selects the rows in column batch_col_number


Instruction:
How would you implement a function in Python 3 that
parses passed in single HTML file and create an epub of the tree.

Response:
def main(argv=None):
    """Parse passed in cooked single HTML."""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('collated_html', type=argparse.FileType('r'),
                        help='Path to the collated html'
                             ' file (use - for stdin)')
    parser.add_argument('-d', '--dump-tree', action='store_true',
                        help='Print out parsed model tree.')

    parser.add_argument('-o', '--output', type=argparse.FileType('w+'),
                        help='Write out epub of parsed tree.')

    parser.add_argument('-i', '--input', type=argparse.FileType('r'),
                        help='Read and copy resources/ for output epub.')

    args = parser.parse_args(argv)

    if args.input and args.output == sys.stdout:
        raise ValueError('Cannot output to stdout if reading resources')

    from cnxepub.collation import reconstitute
    binder = reconstitute(args.collated_html)

    if args.dump_tree:
        print(pformat(cnxepub.model_to_tree(binder)),
              file=sys.stdout)
    if args.output:
        cnxepub.adapters.make_epub(binder, args.output)

    if args.input:
        args.output.seek(0)
        zout = ZipFile(args.output, 'a', ZIP_DEFLATED)
        zin = ZipFile(args.input, 'r')
        for res in zin.namelist():
            if res.startswith('resources'):
                zres = zin.open(res)
                zi = zin.getinfo(res)
                zout.writestr(zi, zres.read(), ZIP_DEFLATED)
        zout.close()

    # TODO Check for documents that have no identifier.
    #      These should likely be composite-documents
    #      or the the metadata got wiped out.
    # docs = [x for x in cnxepub.flatten_to(binder, only_documents_filter)
    #         if x.ident_hash is None]

    return 0


Instruction:
Write a Python 3 script for
creating an embed UI containing a hex color message

Response:
def success(channel, image, hex_str):
    """
    Creates an embed UI containing a hex color message

    Args:
        channel (discord.Channel): The Discord channel to bind the embed to
        image (str): The url of the image to add
        hex_str (str): The hex value

    Returns:
        ui (ui_embed.UI): The embed UI object that was created
    """

    hex_number = int(hex_str, 16)

    # Create embed UI object
    gui = ui_embed.UI(
        channel,
        "",
        "#{}".format(hex_str),
        modulename=modulename,
        colour=hex_number,
        thumbnail=image,
    )

    return gui


Instruction:
Implement a Python 3 function for
adding text to the readme at the given level

Response:
def add_md(text, s, level=0):
    """Adds text to the readme at the given level"""
    if level > 0:
        if text != "":
            text += "\n"
        text += "#" * level
        text += " "

    text += s + "\n"

    if level > 0:
        text += "\n"

    return text


Instruction:
Can you tell what is the following Python 3 function doing
def add_ul(text, ul):
    text += "\n"
    for li in ul:
        text += "- " + li + "\n"
    text += "\n"

    return text

Response: Adds an unordered list to the readme


Instruction:
How would you implement a function in Python 3 that
takes a reporter editions dict and flatten it returning a dict for use in the DictWriter.

Response:
def make_editions_dict(editions):
    """Take a reporter editions dict and flatten it, returning a dict for
    use in the DictWriter.
    """
    d = {}
    nums = ['1', '2', '3', '4', '5', '6']
    num_counter = 0
    for k, date_dict in editions.items():
        d['edition%s' % nums[num_counter]] = k
        if date_dict['start'] is not None:
            d['start_e%s' % nums[num_counter]] = date_dict['start'].isoformat()
        if date_dict['end'] is not None:
            d['end_e%s' % nums[num_counter]] = date_dict['end'].isoformat()

        num_counter += 1

    return d


Instruction:
Can you tell what is the following Python 3 function doing
async def on_message(message):

    # Simplify message info
    server = message.server
    author = message.author
    channel = message.channel
    content = message.content

    data = datatools.get_data()

    if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
        return

    # Only reply to server messages and don't reply to myself
    if server is not None and author != channel.server.me:
        # Commands section
        prefix = data["discord"]["servers"][server.id]["prefix"]
        if content.startswith(prefix):
            # Parse message
            package = content.split(" ")
            command = package[0][len(prefix):]
            args = package[1:]

            alias_steam = ["steam", "pc"]
            alias_ps = ["ps", "psn", "playstation", "ps4", "playstation 4"]
            alias_xbox = ["xbox", "xb", "xb1", "xbone", "xbox one", "xbox one"]

            platform = "steam"
            if len(args) > 0:
                player_name = args[0]
            else:
                return

            if len(args) > 1:
                platform = ' '.join(args[1:]).lower()

            if platform in alias_steam:
                platform = "steam"
            elif platform in alias_ps:
                platform = "ps"
            elif platform in alias_xbox:
                platform = "xbox"

            # Commands
            if command == 'rlstats':
                await client.send_typing(channel)

                # Get Rocket League stats from stats API
                success, rldata = api_rocketleaguestats.check_rank(player_name, platform)
                # Create embed UI
                if success:
                    embed = ui_embed.success(channel, rldata[0], rldata[1], rldata[2], rldata[3])
                else:
                    embed = ui_embed.fail_api(channel)

                await embed.send()

Response: The on_message event handler for this module.


Instruction:
Can you implement a function in Python 3 that
updates the Google API key with the text value

Response:
def update_keys(self):
        """Updates the Google API key with the text value"""
        from ...main import add_api_key
        add_api_key("google_api_key", self.google_api_key.get())
        add_api_key("soundcloud_client_id", self.soundcloud_client_id.get())


Instruction:
Here you have a function in Python 3, explain what it does
def modify_module(channel, module_name, module_state):

    # Create embed UI object
    gui = ui_embed.UI(
        channel,
        "{} updated".format(module_name),
        "{} is now {}".format(module_name, "activated" if module_state else "deactivated"),
        modulename=modulename
    )

    return gui

Response: Creates an embed UI containing the module modified message


Instruction:
Write a Python 3 function that can
create an embed UI containing the prefix modified message

Response:
def modify_prefix(channel, new_prefix):
    """
    Creates an embed UI containing the prefix modified message

    Args:
        channel (discord.Channel): The Discord channel to bind the embed to
        new_prefix (str): The value of the new prefix

    Returns:
        embed: The created embed
    """

    # Create embed UI object
    gui = ui_embed.UI(
        channel,
        "Prefix updated",
        "Modis prefix is now `{}`".format(new_prefix),
        modulename=modulename
    )

    return gui


Instruction:
Explain what the following Python 3 code does
def user_warning(channel, user, warnings, max_warnings):

    username = user.name
    if isinstance(user, discord.Member):
        if user.nick is not None:
            username = user.nick

    warning_count_text = "warnings" if warnings != 1 else "warning"
    warning_text = "{} {}".format(warnings, warning_count_text)
    result_text = "at {} you will be banned".format(max_warnings)
    if warnings >= max_warnings:
        result_text = "you are being banned because you have more than the maximum warnings"

    # Create embed UI object
    gui = ui_embed.UI(
        channel,
        "Warning {}".format(username),
        "You now have {} {}, {}".format(warning_text, username, result_text),
        modulename=modulename
    )

    return gui

Response: Creates an embed UI containing a user warning message


Instruction:
Can you tell what is the following Python 3 function doing
def user_ban(channel, user):

    username = user.name
    if isinstance(user, discord.Member):
        if user.nick is not None:
            username = user.nick

    # Create embed UI object
    gui = ui_embed.UI(
        channel,
        "Banned {}".format(username),
        "{} has been banned from this server".format(username),
        modulename=modulename
    )

    return gui

Response: Creates an embed UI containing an user banned message


Instruction:
Implement a Python 3 function for
creating an embed UI containing an error message if the maximum warnings has been changed

Response:
def warning_max_changed(channel, max_warnings):
    """
    Creates an embed UI containing an error message

    Args:
        channel (discord.Channel): The Discord channel to bind the embed to
        max_warnings (int): The new maximum warnings

    Returns:
        ui (ui_embed.UI): The embed UI object
    """

    # Create embed UI object
    gui = ui_embed.UI(
        channel,
        "Maximum Warnings Changed",
        "Users must now have {} warnings to be banned "
        "(this won't ban existing users with warnings)".format(max_warnings),
        modulename=modulename
    )

    return gui


Instruction:
Make a summary of the following Python 3 code
def error(channel, title, description):

    # Create embed UI object
    gui = ui_embed.UI(
        channel,
        title,
        description,
        modulename=modulename
    )

    return gui

Response: Creates an embed UI containing an error message


Instruction:
Make a summary of the following Python 3 code
async def update_server_data(server):

    data = datatools.get_data()
    # Add the server to server data if it doesn't yet exist
    send_welcome_message = False
    if server.id not in data["discord"]["servers"]:
        logger.debug("Adding new server to serverdata")
        data["discord"]["servers"][server.id] = {"prefix": "!"}
        if "mute_intro" not in data or not data["mute_intro"]:
            send_welcome_message = True

    # Make sure all modules are in the server
    _dir = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
    _dir_modules = "{}/../".format(_dir)
    for module_name in os.listdir(_dir_modules):
        if module_name.startswith("_") or module_name.startswith("!"):
            continue

        if not os.path.isfile("{}/{}/_data.py".format(_dir_modules, module_name)):
            logger.warning("No _data.py file found for module {}".format(module_name))
            continue

        try:
            import_name = ".discord_modis.modules.{}.{}".format(module_name, "_data")
            _data = importlib.import_module(import_name, "modis")

            if _data.modulename not in data["discord"]["servers"][server.id]:
                data["discord"]["servers"][server.id][_data.modulename] = _data.sd_structure
                datatools.write_data(data)
        except Exception as e:
            logger.error("Could not initialise module {}".format(module_name))
            logger.exception(e)

    datatools.write_data(data)

    # Send a welcome message now
    if send_welcome_message:
        default_channel = server.default_channel
        if not default_channel:
            for channel in server.channels:
                if channel.name == "general":
                    default_channel = channel
                    break
        if not default_channel:
            for channel in server.channels:
                if "general" in channel.name:
                    default_channel = channel
                    break
        if not default_channel:
            for channel in server.channels:
                if channel.type == discord.ChannelType.text:
                    default_channel = channel
                    break

        # Display a welcome message
        if default_channel:
            hello_message = "Hello! I'm Modis.\n\n" + \
                            "The prefix is currently `!`, and can be changed at any time using `!prefix`\n\n" + \
                            "You can use `!help` to get help commands for all modules, " + \
                            "or {} me to get the server prefix and help commands.".format(server.me.mention)
            await client.send_message(default_channel, hello_message)

Response: Updates the server data for the given server.


Instruction:
Can you generate the documentation for the following Python 3 function
def remove_server_data(server_id):

    logger.debug("Removing server from serverdata")
    # Remove the server from data
    data = datatools.get_data()
    if server_id in data["discord"]["servers"]:
        data["discord"]["servers"].pop(server_id)
        datatools.write_data(data)

Response: Removes a server from the server data


Instruction:
Can you create a Python 3 function that
checks all servers and removes any that Modis isn t part of any more

Response:
def check_all_servers():
    """Checks all servers, removing any that Modis isn't part of any more"""
    data = datatools.get_data()
    for server_id in data["discord"]["servers"]:
        is_in_client = False
        for client_server in client.servers:
            if server_id == client_server.id:
                is_in_client = True
                break

        if not is_in_client:
            remove_server_data(server_id)


Instruction:
Create a Python 3 function for
clearing all modules from the list

Response:
def clear_modules(self):
        """Clears all modules from the list"""
        for child in self.module_selection.winfo_children():
            child.destroy()

        self.clear_ui()

        tk.Label(self.module_ui, text="Start Modis and select a module").grid(
            column=0, row=0, padx=0, pady=0, sticky="W E N S")

        if self.current_button is not None:
            self.current_button.config(bg="white")

        self.module_buttons = {}
        self.current_button = None


Instruction:
How would you explain what the following Python 3 function does
def add_module(self, module_name, module_ui):
        m_button = tk.Label(self.module_selection, text=module_name, bg="white", anchor="w")
        m_button.grid(column=0, row=len(self.module_selection.winfo_children()), padx=0, pady=0, sticky="W E N S")

        self.module_buttons[module_name] = m_button
        m_button.bind("<Button-1>", lambda e: self.module_selected(module_name, module_ui))

Response: Adds a module to the list of available modules


Instruction:
Write a Python 3 function for
calling when a module is selected.

Response:
def module_selected(self, module_name, module_ui):
        """
        Called when a module is selected

        Args:
            module_name (str): The name of the module
            module_ui: The function to call to create the module's UI
        """
        if self.current_button == self.module_buttons[module_name]:
            return

        self.module_buttons[module_name].config(bg="#cacaca")
        if self.current_button is not None:
            self.current_button.config(bg="white")
        self.current_button = self.module_buttons[module_name]

        self.clear_ui()

        try:
            # Create the UI
            module_ui_frame = ModuleUIBaseFrame(self.module_ui, module_name, module_ui)
            module_ui_frame.grid(column=0, row=0, sticky="W E N S")
        except Exception as e:
            logger.error("Could not load UI for {}".format(module_name))
            logger.exception(e)
            # Create a error UI
            tk.Label(self.module_ui, text="Could not load UI for {}".format(module_name)).grid(
                column=0, row=0, padx=0, pady=0, sticky="W E N S")


Instruction:
Implement a function in Python 3 to
toggle Modis on or off

Response:
def toggle(self, discord_token, discord_client_id):
        """Toggles Modis on or off"""
        if self.state == 'off':
            self.start(discord_token, discord_client_id)
        elif self.state == 'on':
            self.stop()


Instruction:
Explain what the following Python 3 code does
def start(self, discord_token, discord_client_id):
        self.button_toggle_text.set("Stop Modis")
        self.state = "on"

        self.status_bar.set_status(1)

        logger.info("----------------STARTING DISCORD MODIS----------------")

        # Clear the module list
        self.module_frame.clear_modules()

        # Start Modis
        from modis.discord_modis import main
        logger.debug("Creating event loop")
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        self.discord_thread = threading.Thread(
            target=main.start,
            args=[discord_token, discord_client_id, loop, self.on_ready])
        logger.debug("Starting event loop")
        self.discord_thread.start()

        # Find module UIs
        database_dir = "{}/modules".format(
            os.path.dirname(os.path.realpath(__file__)))
        for module_name in os.listdir(database_dir):
            module_dir = "{}/{}".format(database_dir, module_name)

            # Iterate through files in module
            if os.path.isdir(module_dir) and not module_name.startswith("_"):
                # Add all defined event handlers in module files
                module_event_handlers = os.listdir(module_dir)

                if "_ui.py" in module_event_handlers:
                    import_name = ".discord_modis.modules.{}.{}".format(
                        module_name, "_ui")
                    logger.debug(
                        "Found module UI file {}".format(import_name[23:]))

                    self.module_frame.add_module(module_name, importlib.import_module(import_name, "modis"))
                else:
                    self.module_frame.add_module(module_name, None)

Response: Start Modis and log it into Discord.


Instruction:
Make a summary of the following Python 3 code
def stop(self):
        self.button_toggle_text.set("Start Modis")
        self.state = "off"

        logger.info("Stopping Discord Modis")

        from ._client import client
        asyncio.run_coroutine_threadsafe(client.logout(), client.loop)
        self.status_bar.set_status(0)

Response: Stop Modis and log it out of Discord.


Instruction:
Create a Python 3 function to
check if the key name and value fields have been set and updates the add key button

Response:
def key_changed(self):
        """Checks if the key name and value fields have been set, and updates the add key button"""
        if self.key_name.get() and self.key_val.get():
            self.button_key_add.state(["!disabled"])
        else:
            self.button_key_add.state(["disabled"])


Instruction:
Can you generate the documentation for the following Python 3 function
def key_add(self):
        from .main import add_api_key
        add_api_key(self.key_name.get(), self.key_val.get())

        # Clear the text fields
        self.key_name.set("")
        self.key_val.set("")

Response: Adds the current API key to the bot s data


Instruction:
Can you write a function in Python 3 where it
updates the status text for the modisical cache entry.

Response:
def set_status(self, status):
        """
        Updates the status text

        Args:
            status (int): The offline/starting/online status of Modis
                0: offline, 1: starting, 2: online
        """

        text = ""
        colour = "#FFFFFF"
        if status == 0:
            text = "OFFLINE"
            colour = "#EF9A9A"
        elif status == 1:
            text = "STARTING"
            colour = "#FFE082"
        elif status == 2:
            text = "ONLINE"
            colour = "#A5D6A7"

        self.status.set(text)
        self.statusbar.config(background=colour)


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

    try:
        with open(filepath, 'r') as file:
            return _json.load(file, object_pairs_hook=OrderedDict)
    except Exception as e:
        logger.error("Could not load file {}".format(filepath))
        logger.exception(e)
        return {}

Response: Get the json data from a help file


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_help_datapacks(filepath, prefix="!"):

    help_contents = get_help_data(filepath)

    datapacks = []

    # Add the content
    for d in help_contents:
        heading = d
        content = ""

        if "commands" in d.lower():
            for c in help_contents[d]:
                if "name" not in c:
                    continue

                content += "- `"
                command = prefix + c["name"]
                content += "{}".format(command)
                if "params" in c:
                    for param in c["params"]:
                        content += " [{}]".format(param)
                content += "`: "
                if "description" in c:
                    content += c["description"]
                content += "\n"
        else:
            content += help_contents[d]

        datapacks.append((heading, content, False))

    return datapacks

Response:
Load help text from a file and give it as datapacks
WorkItem


Instruction:
Create a Python 3 function to
load the help text from a file and add it to the parent object.

Response:
def add_help_text(parent, filepath, prefix="!"):
    """
    Load help text from a file and adds it to the parent

    Args:
        parent: A tk or ttk object
        filepath (str): The file to load help text from
        prefix (str): The prefix to use for commands
    """

    import tkinter as tk
    import tkinter.ttk as ttk

    help_contents = get_help_data(filepath)

    text = tk.Text(parent, wrap='word', font=("Helvetica", 10))
    text.grid(row=0, column=0, sticky="W E N S")
    text.tag_config("heading", font=("Helvetica", 14))
    text.tag_config("command", font=("Courier", 10))
    text.tag_config("param", font=("Courier", 10))
    text.tag_config("description")

    # Vertical Scrollbar
    scrollbar = ttk.Scrollbar(parent, orient="vertical", command=text.yview)
    scrollbar.grid(column=1, row=0, sticky="N S")
    text['yscrollcommand'] = scrollbar.set

    # Add the content
    for d in help_contents:
        text.insert('end', d, "heading")
        text.insert('end', '\n')

        if "commands" in d.lower():
            for c in help_contents[d]:
                if "name" not in c:
                    continue

                command = prefix + c["name"]
                text.insert('end', command, ("command", "description"))
                if "params" in c:
                    for param in c["params"]:
                        text.insert('end', " [{}]".format(param), ("param", "description"))
                text.insert('end', ": ")
                if "description" in c:
                    text.insert('end', c["description"], "description")

                text.insert('end', '\n')

            text.insert('end', '\n')
        else:
            text.insert('end', help_contents[d], "description")
            text.insert('end', '\n\n')

    text.config(state=tk.DISABLED)


Instruction:
Can you tell what is the following Python 3 function doing
async def on_reaction_add(reaction, user):

    # Simplify reaction info
    server = reaction.message.server
    emoji = reaction.emoji

    data = datatools.get_data()

    if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
        return

    # Commands section
    if user != reaction.message.channel.server.me:
        if server.id not in _data.cache or _data.cache[server.id].state == 'destroyed':
            return

        try:
            valid_reaction = reaction.message.id == _data.cache[server.id].embed.sent_embed.id
        except AttributeError:
            pass
        else:
            if valid_reaction:
                # Remove reaction
                try:
                    await client.remove_reaction(reaction.message, emoji, user)
                except discord.errors.NotFound:
                    pass
                except discord.errors.Forbidden:
                    pass

                # Commands
                if emoji == "⏯":
                    await _data.cache[server.id].toggle()
                if emoji == "⏹":
                    await _data.cache[server.id].stop()
                if emoji == "⏭":
                    await _data.cache[server.id].skip("1")
                if emoji == "⏮":
                    await _data.cache[server.id].rewind("1")
                if emoji == "🔀":
                    await _data.cache[server.id].shuffle()
                if emoji == "🔉":
                    await _data.cache[server.id].setvolume('-')
                if emoji == "🔊":
                    await _data.cache[server.id].setvolume('+')

Response: The on_message event handler for this module.


Instruction:
Write a Python 3 function for
starting Modis in console format.

Response:
def console(discord_token, discord_client_id):
    """
    Start Modis in console format.

    Args:
        discord_token (str): The bot token for your Discord application
        discord_client_id: The bot's client ID
    """

    state, response = datatools.get_compare_version()

    logger.info("Starting Modis in console")
    logger.info(response)

    import threading
    import asyncio

    logger.debug("Loading packages")
    from modis.discord_modis import main as discord_modis_console
    from modis.reddit_modis import main as reddit_modis_console
    from modis.facebook_modis import main as facebook_modis_console

    # Create threads
    logger.debug("Initiating threads")
    loop = asyncio.get_event_loop()
    discord_thread = threading.Thread(
        target=discord_modis_console.start,
        args=[discord_token, discord_client_id, loop])
    reddit_thread = threading.Thread(
        target=reddit_modis_console.start, args=[])
    facebook_thread = threading.Thread(
        target=facebook_modis_console.start, args=[])

    # Run threads
    logger.debug("Starting threads")
    discord_thread.start()
    reddit_thread.start()
    facebook_thread.start()

    logger.debug("Root startup completed")


Instruction:
How would you explain what the following Python 3 function does
def gui(discord_token, discord_client_id):

    logger.info("Starting Modis in GUI")

    import tkinter as tk

    logger.debug("Loading packages")
    from modis.discord_modis import gui as discord_modis_gui
    from modis.reddit_modis import gui as reddit_modis_gui
    from modis.facebook_modis import gui as facebook_modis_gui

    logger.debug("Initialising window")

    # Setup the root window
    root = tk.Tk()
    root.minsize(width=800, height=400)
    root.geometry("800x600")
    root.title("Modis Control Panel")
    # Icon
    root.iconbitmap(r"{}/assets/modis.ico".format(file_dir))

    # Setup the notebook
    """notebook = ttk.Notebook(root)
    notebook.grid(column=0, row=0, padx=0, pady=0, sticky="W E N S")

    # Configure stretch ratios
    root.columnconfigure(0, weight=1)
    root.rowconfigure(0, weight=1)
    notebook.columnconfigure(0, weight=1)
    notebook.rowconfigure(0, weight=1)

    # Add tabs
    logger.debug("Adding packages to window")
    notebook.add(
        discord_modis_gui.Frame(notebook, discord_token, discord_client_id),
        text="Discord")
    notebook.add(reddit_modis_gui.Frame(notebook), text="Reddit")
    notebook.add(facebook_modis_gui.Frame(notebook), text="Facebook")"""
    discord = discord_modis_gui.Frame(root, discord_token, discord_client_id)
    discord.grid(column=0, row=0, padx=0, pady=0, sticky="W E N S")
    # Configure stretch ratios
    root.columnconfigure(0, weight=1)
    root.rowconfigure(0, weight=1)
    discord.columnconfigure(0, weight=1)
    discord.rowconfigure(0, weight=1)

    logger.debug("GUI initialised")

    # Run the window UI
    root.mainloop()

Response: Start Modis in GUI format.


Instruction:
Given the following Python 3 function, write the documentation
def write_data(data):

    sorted_dict = sort_recursive(data)

    with open(_datafile, 'w') as file:
        _json.dump(sorted_dict, file, indent=2)

Response: Writes the data dictionary to the data. json file


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

    newdict = {}

    for i in data.items():
        if type(i[1]) is dict:
            newdict[i[0]] = sort_recursive(i[1])
        else:
            newdict[i[0]] = i[1]

    return OrderedDict(sorted(newdict.items(), key=lambda item: (compare_type(type(item[1])), item[0])))

Response: Recursively sorts all elements in a dictionary


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

    state, latest_version = compare_latest_version()
    if state < 0:
        return -1, "A new version of Modis is available (v{})".format(latest_version)
    elif state == 0:
        return 0, "You are running the latest version of Modis (v{})".format(version)
    else:
        return 1, "You are running a preview version of Modis (v{} pre-release)".format(version)

Response: Get the version comparison info.


Instruction:
Can you generate the documentation for the following Python 3 function
def success(channel, stats, name, platform, dp):

    # Create datapacks
    datapacks = [("Platform", platform, False)]
    for stat in stats:
        # Add stats
        if stat[0] in ("Duel 1v1", "Doubles 2v2", "Solo Standard 3v3", "Standard 3v3"):
            stat_name = "__" + stat[0] + "__"
            stat_value = "**" + stat[1] + "**"
        else:
            stat_name = stat[0]
            stat_value = stat[1]

        # Add percentile if it exists
        if stat[2]:
            stat_value += " *(Top " + stat[2] + "%)*"

        datapacks.append((stat_name, stat_value, True))

    # Create embed UI object
    gui = ui_embed.UI(
        channel,
        "Rocket League Stats: {}".format(name),
        "*Stats obtained from [Rocket League Tracker Network](https://rocketleague.tracker.network/)*",
        modulename=modulename,
        colour=0x0088FF,
        thumbnail=dp,
        datapacks=datapacks
    )

    return gui

Response: Create an embed UI containing the Rocket League Stats


Instruction:
Explain what the following Python 3 code does
def fail_steamid(channel):

    gui = ui_embed.UI(
        channel,
        "That SteamID doesn't exist.",
        "You can get your SteamID by going to your profile page and looking at the url, "
        "or you can set a custom ID by going to edit profile on your profile page.",
        modulename=modulename,
        colour=0x0088FF
    )

    return gui

Response: Creates an embed UI for invalid SteamIDs


Instruction:
Make a summary of the following Python 3 code
def fail_api(channel):

    gui = ui_embed.UI(
        channel,
        "Couldn't get stats off RLTrackerNetwork.",
        "Maybe the API changed, please tell Infraxion.",
        modulename=modulename,
        colour=0x0088FF
    )

    return gui

Response: Creates an embed UI for when the API call didn t work


Instruction:
Can you tell what is the following Python 3 function doing
async def on_message(message):

    # Simplify message info
    server = message.server
    author = message.author
    channel = message.channel
    content = message.content

    data = datatools.get_data()

    if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
        return

    # Only reply to server messages and don't reply to myself
    if server is not None and author != channel.server.me:
        # Commands section
        prefix = data["discord"]["servers"][server.id]["prefix"]
        if content.startswith(prefix):
            # Parse message
            package = content.split(" ")
            command = package[0][len(prefix):]

            # Commands
            if command == 'gamedeals':
                await client.send_typing(channel)

                # Get posts from Reddit API
                posts = api_reddit.get_top10()

                if posts:
                    for post in posts:
                        # Create embed UI
                        embed = ui_embed.success(channel, post)
                        await embed.send()
                else:
                    embed = ui_embed.no_results(channel)
                    await embed.send()

Response: The on_message event handler for this module.


Instruction:
How would you implement a function in Python 3 that
creates an embed UI containing the Reddit posts

Response:
def success(channel, post):
    """Creates an embed UI containing the Reddit posts

    Args:
        channel (discord.Channel): The Discord channel to bind the embed to
        post (tuple): Tuples of (field, value, percentile)

    Returns:

    """

    # Create datapacks
    datapacks = [("Game", post[0], True), ("Upvotes", post[2], True)]

    # Create embed UI object
    gui = ui_embed.UI(
        channel,
        "Link",
        post[1],
        modulename=modulename,
        colour=0xFF8800,
        thumbnail=post[1],
        datapacks=datapacks
    )

    return gui


Instruction:
Make a summary of the following Python 3 code
def no_results(channel):

    gui = ui_embed.UI(
        channel,
        "No results",
        ":c",
        modulename=modulename,
        colour=0xFF8800
    )

    return gui

Response: Creates an embed UI for when there were no results


Instruction:
Implement a Python 3 function for
making a new time bar string based on the current song s progress and duration.

Response:
def make_timebar(progress=0, duration=0):
    """
    Makes a new time bar string

    Args:
        progress: How far through the current song we are (in seconds)
        duration: The duration of the current song (in seconds)

    Returns:
        timebar (str): The time bar string
    """

    duration_string = api_music.duration_to_string(duration)
    if duration <= 0:
        return "---"

    time_counts = int(round((progress / duration) * TIMEBAR_LENGTH))
    if time_counts > TIMEBAR_LENGTH:
        time_counts = TIMEBAR_LENGTH

    if duration > 0:
        bar = "│" + (TIMEBAR_PCHAR * time_counts) + (TIMEBAR_ECHAR * (TIMEBAR_LENGTH - time_counts)) + "│"
        time_bar = "{} {}".format(bar, duration_string)
    else:
        time_bar = duration_string

    return time_bar


Instruction:
Make a summary of the following Python 3 code
def build(self):

        if self.colour:
            embed = discord.Embed(
                title=self.title,
                type='rich',
                description=self.description,
                colour=self.colour)
        else:
            embed = discord.Embed(
                title=self.title,
                type='rich',
                description=self.description)

        if self.thumbnail:
            embed.set_thumbnail(url=self.thumbnail)

        if self.image:
            embed.set_image(url=self.image)

        embed.set_author(
            name="Modis",
            url="https://musicbyango.com/modis/",
            icon_url="http://musicbyango.com/modis/dp/modis64t.png")

        for pack in self.datapacks:
            embed.add_field(
                name=pack[0],
                value=pack[1],
                inline=pack[2]
            )

        return embed

Response: Builds Discord embed for a specific object.


Instruction:
Make a summary of the following Python 3 code
def update_data(self, index, data):

        datapack = self.built_embed.to_dict()["fields"][index]
        self.built_embed.set_field_at(index, name=datapack["name"], value=data, inline=datapack["inline"])

Response:
Updates a particular datapack s data
            at the given index


Instruction:
Write a Python 3 script to
build a dictionary of variations to canonical reporters.

Response:
def suck_out_variations_only(reporters):
    """Builds a dictionary of variations to canonical reporters.

    The dictionary takes the form of:
        {
         "A. 2d": ["A.2d"],
         ...
         "P.R.": ["Pen. & W.", "P.R.R.", "P."],
        }

    In other words, it's a dictionary that maps each variation to a list of
    reporters that it could be possibly referring to.
    """
    variations_out = {}
    for reporter_key, data_list in reporters.items():
        # For each reporter key...
        for data in data_list:
            # For each book it maps to...
            for variation_key, variation_value in data["variations"].items():
                try:
                    variations_list = variations_out[variation_key]
                    if variation_value not in variations_list:
                        variations_list.append(variation_value)
                except KeyError:
                    # The item wasn't there; add it.
                    variations_out[variation_key] = [variation_value]

    return variations_out


Instruction:
Here you have a function in Python 3, explain what it does
def suck_out_editions(reporters):
    editions_out = {}
    for reporter_key, data_list in reporters.items():
        # For each reporter key...
        for data in data_list:
            # For each book it maps to...
            for edition_key, edition_value in data["editions"].items():
                try:
                    editions_out[edition_key]
                except KeyError:
                    # The item wasn't there; add it.
                    editions_out[edition_key] = reporter_key
    return editions_out

Response: Builds a dictionary mapping edition keys to their root name.


Instruction:
Implement a Python 3 function for
building a dict mapping names to their variations.

Response:
def names_to_abbreviations(reporters):
    """Build a dict mapping names to their variations

    Something like:

        {
            "Atlantic Reporter": ['A.', 'A.2d'],
        }

    Note that the abbreviations are sorted by start date.
    """
    names = {}
    for reporter_key, data_list in reporters.items():
        for data in data_list:
            abbrevs = data['editions'].keys()
            # Sort abbreviations by start date of the edition
            sort_func = lambda x: str(data['editions'][x]['start']) + x
            abbrevs = sorted(abbrevs, key=sort_func)
            names[data['name']] = abbrevs
    sorted_names = OrderedDict(sorted(names.items(), key=lambda t: t[0]))
    return sorted_names


Instruction:
Explain what the following Python 3 code does
def check_rank(player, platform="steam"):

    # Get player ID and name Rocket League Tracker Network
    webpage = requests.get(
        "https://rocketleague.tracker.network/profile/{}/{}".format(platform, player)
    ).text

    try:
        # Get player ID
        playerid_index = webpage.index("/live?ids=") + len("/live?ids=")
        playerid_end_index = webpage.index("""">""", playerid_index)
        playerid = webpage[playerid_index:playerid_end_index]

        # Get player name
        name_index = webpage.index("Stats Profile : ") + len("Stats Profile : ")
        name_end_index = webpage.index("""\n""", name_index)
        name = webpage[name_index:name_end_index]
    except (ValueError, IndexError):
        return False, ()

    # Get player stats from Rocket League Tracker Network
    livedata = json.loads(
        requests.post(
            "https://rocketleague.tracker.network/live/data",
            json={"playerIds": [playerid]}
        ).text
    )

    stats = []
    try:
        for statpack in livedata['players'][0]['Stats']:
            field = statpack['Value']['Label']
            value = str(statpack['Value']['DisplayValue'])
            if statpack['Value']['Percentile']:
                percentile = str(statpack['Value']['Percentile'])
            else:
                percentile = None
            stats.append((field, value, percentile))
    except (IndexError, KeyError):
        return False, ()

    dp = "https://rocketleague.media.zestyio.com/rocket-league-logos-vr-white.f1cb27a519bdb5b6ed34049a5b86e317.png"

    platform_display = platform
    if platform == "steam":
        platform_display = "Steam"
    elif platform == "ps":
        platform_display = "PlayStation"
    elif platform == "xbox":
        platform_display = "Xbox"

    return True, (stats, name, platform_display, dp)

Response: Checks if the player has ranked on the Rocket League Tracker.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def send_message(channel_id, message):

    channel = client.get_channel(channel_id)

    if channel is None:
        logger.info("{} is not a channel".format(channel_id))
        return

    # Check that it's enabled in the server
    data = datatools.get_data()
    if not data["discord"]["servers"][channel.server.id][modulename]["activated"]:
        logger.info("This module has been disabled in {} ({})".format(channel.server.name, channel.server.id))

    try:
        runcoro(client.send_message(channel, message))
    except Exception as e:
        logger.exception(e)

Response: Send a message to a channel


Instruction:
Given the following Python 3 function, write the documentation
def runcoro(async_function):

    future = _asyncio.run_coroutine_threadsafe(async_function, client.loop)
    result = future.result()
    return result

Response: Runs an asynchronous function without needing to use async - useful for lambda


Instruction:
Can you generate a brief explanation for the following Python 3 code
async def on_message(message):

    # Simplify message info
    server = message.server
    author = message.author
    channel = message.channel
    content = message.content

    data = datatools.get_data()

    if not data["discord"]["servers"][server.id][_data.modulename]["activated"]:
        return

    # Only reply to server messages and don't reply to myself
    if server is not None and author != channel.server.me:
        # Do a flip check
        flipchecked = api_flipcheck.flipcheck(content)
        if flipchecked:
            await client.send_typing(channel)
            await client.send_message(channel, flipchecked)

Response: The on_message event handler for this module.


Instruction:
Can you generate the documentation for the following Python 3 function
def update_keys(self):
        from ...main import add_api_key
        add_api_key("reddit_api_user_agent", self.reddit_api_user_agent.get())
        add_api_key("reddit_api_client_id", self.reddit_api_client_id.get())
        add_api_key("reddit_api_client_secret", self.reddit_api_client_secret.get())

Response: Updates the Google API key with the text value


Instruction:
Can you implement a function in Python 3 that
activates a module in the server

Response:
async def activate_module(channel, module_name, activate):
    """
    Changes a modules activated/deactivated state for a server

    Args:
        channel: The channel to send the message to
        module_name: The name of the module to change state for
        activate: The activated/deactivated state of the module
    """

    data = datatools.get_data()
    server_id = channel.server.id

    _dir = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
    _dir_modules = "{}/../".format(_dir)
    if not os.path.isfile("{}/{}/_data.py".format(_dir_modules, module_name)):
        await client.send_typing(channel)
        embed = ui_embed.error(channel, "Error", "No module found named '{}'".format(module_name))
        await embed.send()
        return

    try:
        import_name = ".discord_modis.modules.{}.{}".format(module_name, "_data")
        module_data = importlib.import_module(import_name, "modis")

        # Don't try and deactivate this module (not that it would do anything)
        if module_data.modulename == _data.modulename:
            await client.send_typing(channel)
            embed = ui_embed.error(channel, "Error", "I'm sorry, Dave. I'm afraid I can't do that.")
            await embed.send()
            return

        # This /should/ never happen if everything goes well
        if module_data.modulename not in data["discord"]["servers"][server_id]:
            await client.send_typing(channel)
            embed = ui_embed.error(channel, "Error",
                                   "No data found for module '{}'".format(module_data.modulename))
            await embed.send()
            return

        # Modify the module
        if "activated" in data["discord"]["servers"][server_id][module_data.modulename]:
            data["discord"]["servers"][server_id][module_data.modulename]["activated"] = activate
            # Write the data
            datatools.write_data(data)

            await client.send_typing(channel)
            embed = ui_embed.modify_module(channel, module_data.modulename, activate)
            await embed.send()
            return
        else:
            await client.send_typing(channel)
            embed = ui_embed.error(channel, "Error", "Can't deactivate module '{}'".format(module_data.modulename))
            await embed.send()
            return
    except Exception as e:
        logger.error("Could not modify module {}".format(module_name))
        logger.exception(e)


Instruction:
Can you implement a function in Python 3 that
bans a user from a server

Response:
async def ban_user(channel, user):
    """
    Bans a user from a server

    Args:
        channel: The channel to send the warning message in
        user: The user to give the warning to
    """

    data = datatools.get_data()
    server_id = channel.server.id

    try:
        await client.ban(user)
    except discord.errors.Forbidden:
        await client.send_typing(channel)
        embed = ui_embed.error(channel, "Ban Error", "I do not have the permissions to ban that person.")
        await embed.send()
        return

    # Set the user's warnings to 0
    if "warnings" in data["discord"]["servers"][server_id][_data.modulename]:
        if user.id in data["discord"]["servers"][server_id][_data.modulename]["warnings"]:
            data["discord"]["servers"][server_id][_data.modulename]["warnings"][user.id] = 0
            datatools.write_data(data)

    await client.send_typing(channel)
    embed = ui_embed.user_ban(channel, user)
    await embed.send()

    try:
        response = "You have been banned from the server '{}' " \
                   "contact the owners to resolve this issue.".format(channel.server.name)
        await client.send_message(user, response)
    except Exception as e:
        logger.exception(e)


Instruction:
How would you code a function in Python 3 to
get the help datapacks for a module

Response:
def get_help_datapacks(module_name, server_prefix):
    """
    Get the help datapacks for a module

    Args:
        module_name (str): The module to get help data for
        server_prefix (str): The command prefix for this server

    Returns:
        datapacks (list): The help datapacks for the module
    """

    _dir = os.path.realpath(
        os.path.join(os.getcwd(), os.path.dirname(__file__)))
    module_dir = "{}/../{}".format(_dir, module_name, "_help.json")
    if os.path.isdir(module_dir):
        module_help_path = "{}/{}".format(module_dir, "_help.json")

        if os.path.isfile(module_help_path):
            return helptools.get_help_datapacks(module_help_path, server_prefix)
        else:
            return [("Help", "{} does not have a help.json file".format(module_name), False)]
    else:
        return [("Help", "No module found called {}".format(module_name), False)]


Instruction:
Given the following Python 3 function, write the documentation
def get_help_commands(server_prefix):

    datapacks = []

    _dir = os.path.realpath(
        os.path.join(os.getcwd(), os.path.dirname(__file__)))
    for module_name in os.listdir("{}/../".format(_dir)):
        if not module_name.startswith("_") and not module_name.startswith("!"):
            help_command = "`{}help {}`".format(server_prefix, module_name)
            datapacks.append((module_name, help_command, True))

    return datapacks

Response: Get the help commands for all modules in the current directory


Instruction:
Can you generate a brief explanation for the following Python 3 code
async def on_message(message):

    # Simplify message info
    server = message.server
    author = message.author
    channel = message.channel
    content = message.content

    data = datatools.get_data()

    # Only reply to server messages and don't reply to myself
    if server is not None and author != channel.server.me:
        # Commands section
        prefix = data["discord"]["servers"][server.id]["prefix"]
        if content.startswith(prefix):
            # Parse message
            package = content.split(" ")
            command = package[0][len(prefix):]
            args = package[1:]
            arg = ' '.join(args)

            # Commands
            if command == 'help':
                if args:
                    # Parse message
                    datapacks = api_help.get_help_datapacks(arg, prefix)
                    # Create embed UI
                    if datapacks:
                        await client.send_typing(channel)
                        embed = ui_embed.success(channel, arg, datapacks)
                        try:
                            await embed.send()
                        except discord.errors.HTTPException:
                            embed = ui_embed.http_exception(channel, arg)
                            await embed.send()
                else:
                    # Parse message
                    datapacks = api_help.get_help_commands(prefix)
                    # Create embed UI
                    if datapacks:
                        await client.send_typing(channel)
                        embed = ui_embed.success(channel, arg, datapacks)
                        try:
                            await embed.send()
                        except discord.errors.HTTPException:
                            embed = ui_embed.http_exception(channel, arg)
                            await embed.send()

Response: The on_message event handler for this module.


Instruction:
Make a summary of the following Python 3 code
async def on_message(message):

    # Simplify message info
    server = message.server
    author = message.author
    channel = message.channel
    content = message.content

    data = datatools.get_data()

    # Only reply to server messages and don't reply to myself
    if server is not None and author != channel.server.me:
        prefix = data["discord"]["servers"][server.id]["prefix"]
        # Check for mentions reply to mentions
        if channel.server.me in message.mentions:
            await client.send_typing(channel)
            response = "The current server prefix is `{0}`. Type `{0}help` for help.".format(prefix)
            await client.send_message(channel, response)

        # Commands section
        if content.startswith(prefix):
            # Parse message
            package = content.split(" ")
            command = package[0][len(prefix):]
            args = package[1:]
            arg = ' '.join(args)

            # Commands
            if command not in ["prefix", "activate", "deactivate", "warnmax", "warn", "ban"]:
                return

            is_admin = author == server.owner
            for role in message.author.roles:
                if role.permissions.administrator:
                    is_admin = True

            if not is_admin:
                await client.send_typing(channel)
                reason = "You must have a role that has the permission 'Administrator'"
                embed = ui_embed.error(channel, "Insufficient Permissions", reason)
                await embed.send()
                return

            if command == "prefix" and args:
                new_prefix = arg.replace(" ", "").strip()
                data["discord"]["servers"][server.id]["prefix"] = new_prefix
                # Write the data
                datatools.write_data(data)

                await client.send_typing(channel)
                embed = ui_embed.modify_prefix(channel, new_prefix)
                await embed.send()

            if command == "warnmax" and args:
                try:
                    warn_max = int(arg)
                    if warn_max > 0:
                        data["discord"]["servers"][server.id][_data.modulename]["warnings_max"] = warn_max
                        datatools.write_data(data)
                        await client.send_typing(channel)
                        embed = ui_embed.warning_max_changed(channel, warn_max)
                        await embed.send()
                    else:
                        reason = "Maximum warnings must be greater than 0"
                        embed = ui_embed.error(channel, "Error", reason)
                        await embed.send()
                except (ValueError, TypeError):
                    reason = "Warning maximum must be a number"
                    embed = ui_embed.error(channel, "Error", reason)
                    await embed.send()
                except Exception as e:
                    logger.exception(e)

            if command == "warn" and args:
                for user in message.mentions:
                    await api_manager.warn_user(channel, user)

            if command == "ban" and args:
                for user in message.mentions:
                    await api_manager.ban_user(channel, user)

            if command == "activate" and args:
                await api_manager.activate_module(channel, arg, True)
            elif command == "deactivate" and args:
                await api_manager.activate_module(channel, arg, False)

Response: The on_message event handler for this module.


Instruction:
How would you code a function in Python 3 to
create an embed UI for the topic update

Response:
def topic_update(channel, topic_channel):
    """
    Creates an embed UI for the topic update

    Args:
        channel (discord.Channel): The Discord channel to bind the embed to
        topic_channel: The new topic channel

    Returns:
        embed: The created embed
    """

    if topic_channel is not None:
        try:
            channel_message = "Topic channel is now `{}`.".format(topic_channel.name)
        except Exception as e:
            logger.exception(e)
            channel_message = "Topic channel has been updated."
    else:
        channel_message = "Topic channel has been cleared."

    # Create embed UI object
    gui = ui_embed.UI(
            channel,
            "Topic channel updated",
            channel_message,
            modulename=modulename,
            colour=modulecolor_info
    )

    return gui


Instruction:
Create a Python 3 function for
creating an embed UI for the topic update with an error message

Response:
def error_message(channel, err_title, err_message):
    """
    Creates an embed UI for the topic update

    Args:
        channel (discord.Channel): The Discord channel to bind the embed to
        err_title: The title for the error
        err_message: The message for the error

    Returns:
        embed: The created embed
    """

    # Create embed UI object
    gui = ui_embed.UI(
            channel,
            err_title,
            err_message,
            modulename=modulename,
            colour=modulecolor_error
    )

    return gui


Instruction:
Can you tell what is the following Python 3 function doing
def clear_cache_root():
    logger.debug("Clearing root cache")
    if os.path.isdir(_root_songcache_dir):
        for filename in os.listdir(_root_songcache_dir):
            file_path = os.path.join(_root_songcache_dir, filename)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except PermissionError:
                pass
            except Exception as e:
                logger.exception(e)
    logger.debug("Root cache cleared")

Response: Clears all the song cache from the root folder.


Instruction:
Write a Python 3 function for
playing the song .

Response:
async def play(self, author, text_channel, query, index=None, stop_current=False, shuffle=False):
        """
        The play command

        Args:
            author (discord.Member): The member that called the command
            text_channel (discord.Channel): The channel where the command was called
            query (str): The argument that was passed with the command
            index (str): Whether to play next or at the end of the queue
            stop_current (bool): Whether to stop the currently playing song
            shuffle (bool): Whether to shuffle the queue after starting
        """

        if self.state == 'off':
            self.state = 'starting'
            self.prev_queue = []
            await self.set_topic("")
            # Init the music player
            await self.msetup(text_channel)
            # Queue the song
            await self.enqueue(query, index, stop_current, shuffle)
            # Connect to voice
            await self.vsetup(author)

            # Mark as 'ready' if everything is ok
            self.state = 'ready' if self.mready and self.vready else 'off'
        else:
            # Queue the song
            await self.enqueue(query, index, stop_current, shuffle)

        if self.state == 'ready':
            if self.streamer is None:
                await self.vplay()


Instruction:
Write a Python 3 script to
destroy the whole gui and music player

Response:
async def destroy(self):
        """Destroy the whole gui and music player"""

        self.logger.debug("destroy command")
        self.state = 'destroyed'

        await self.set_topic("")
        self.nowplayinglog.debug("---")
        self.nowplayingauthorlog.debug("---")
        self.nowplayingsourcelog.debug("---")
        self.timelog.debug(_timebar.make_timebar())
        self.prev_time = "---"
        self.statuslog.debug("Destroying")

        self.mready = False
        self.vready = False
        self.pause_time = None
        self.loop_type = 'off'

        if self.vclient:
            try:
                await self.vclient.disconnect()
            except Exception as e:
                logger.error(e)
                pass

        if self.streamer:
            try:
                self.streamer.stop()
            except:
                pass

        self.vclient = None
        self.vchannel = None
        self.streamer = None
        self.current_duration = 0
        self.current_download_elapsed = 0
        self.is_live = False
        self.queue = []
        self.prev_queue = []

        if self.embed:
            await self.embed.delete()
            self.embed = None

        self.clear_cache()


Instruction:
Explain what the following Python 3 code does
async def toggle(self):

        self.logger.debug("toggle command")

        if not self.state == 'ready':
            return

        if self.streamer is None:
            return

        try:
            if self.streamer.is_playing():
                await self.pause()
            else:
                await self.resume()
        except Exception as e:
            logger.error(e)
            pass

Response: Toggles between pause and resume command


Instruction:
How would you implement a function in Python 3 that
pauses playback if playing

Response:
async def pause(self):
        """Pauses playback if playing"""

        self.logger.debug("pause command")

        if not self.state == 'ready':
            return

        if self.streamer is None:
            return

        try:
            if self.streamer.is_playing():
                self.streamer.pause()
                self.pause_time = self.vclient.loop.time()
                self.statuslog.info("Paused")
        except Exception as e:
            logger.error(e)
            pass


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

        self.logger.debug("resume command")

        if not self.state == 'ready':
            return

        if self.streamer is None:
            return

        try:
            if not self.streamer.is_playing():
                play_state = "Streaming" if self.is_live else "Playing"
                self.statuslog.info(play_state)
                self.streamer.resume()

                if self.pause_time is not None:
                    self.vclient_starttime += (self.vclient.loop.time() - self.pause_time)
                self.pause_time = None
        except Exception as e:
            logger.error(e)
            pass

Response: Resumes playback if paused


Instruction:
Here you have a function in Python 3, explain what it does
async def skip(self, query="1"):

        if not self.state == 'ready':
            logger.debug("Trying to skip from wrong state '{}'".format(self.state))
            return

        if query == "":
            query = "1"
        elif query == "all":
            query = str(len(self.queue) + 1)

        try:
            num = int(query)
        except TypeError:
            self.statuslog.error("Skip argument must be a number")
        except ValueError:
            self.statuslog.error("Skip argument must be a number")
        else:
            self.statuslog.info("Skipping")

            for i in range(num - 1):
                if len(self.queue) > 0:
                    self.prev_queue.append(self.queue.pop(0))

            try:
                self.streamer.stop()
            except Exception as e:
                logger.exception(e)

Response:
The skip command

        Args:
            query (str): The number of items to skip


Instruction:
Write a Python 3 script to
remove a single entry from the queue.

Response:
async def remove(self, index=""):
        """
        The remove command

        Args:
            index (str): The index to remove, can be either a number, or a range in the for '##-##'
        """

        if not self.state == 'ready':
            logger.debug("Trying to remove from wrong state '{}'".format(self.state))
            return

        if index == "":
            self.statuslog.error("Must provide index to remove")
            return
        elif index == "all":
            self.queue = []
            self.update_queue()
            self.statuslog.info("Removed all songs")
            return

        indexes = index.split("-")
        self.logger.debug("Removing {}".format(indexes))

        try:
            if len(indexes) == 0:
                self.statuslog.error("Remove must specify an index or range")
                return
            elif len(indexes) == 1:
                num_lower = int(indexes[0]) - 1
                num_upper = num_lower + 1
            elif len(indexes) == 2:
                num_lower = int(indexes[0]) - 1
                num_upper = int(indexes[1])
            else:
                self.statuslog.error("Cannot have more than 2 indexes for remove range")
                return
        except TypeError:
            self.statuslog.error("Remove index must be a number")
            return
        except ValueError:
            self.statuslog.error("Remove index must be a number")
            return

        if num_lower < 0 or num_lower >= len(self.queue) or num_upper > len(self.queue):
            if len(self.queue) == 0:
                self.statuslog.warning("No songs in queue")
            elif len(self.queue) == 1:
                self.statuslog.error("Remove index must be 1 (only 1 song in queue)")
            else:
                self.statuslog.error("Remove index must be between 1 and {}".format(len(self.queue)))
            return

        if num_upper <= num_lower:
            self.statuslog.error("Second index in range must be greater than first")
            return

        lower_songname = self.queue[num_lower][1]
        for num in range(0, num_upper - num_lower):
            self.logger.debug("Removed {}".format(self.queue[num_lower][1]))
            self.queue.pop(num_lower)

        if len(indexes) == 1:
            self.statuslog.info("Removed {}".format(lower_songname))
        else:
            self.statuslog.info("Removed songs {}-{}".format(num_lower + 1, num_upper))

        self.update_queue()


Instruction:
Implement a Python 3 function for
rewinding the current state of the current state of the current songs.

Response:
async def rewind(self, query="1"):
        """
        The rewind command

        Args:
            query (str): The number of items to skip
        """

        if not self.state == 'ready':
            logger.debug("Trying to rewind from wrong state '{}'".format(self.state))
            return

        if query == "":
            query = "1"

        try:
            num = int(query)
        except TypeError:
            self.statuslog.error("Rewind argument must be a number")
        except ValueError:
            self.statuslog.error("Rewind argument must be a number")
        else:
            if len(self.prev_queue) == 0:
                self.statuslog.error("No songs to rewind")
                return

            if num < 0:
                self.statuslog.error("Rewind must be postitive or 0")
                return
            elif num > len(self.prev_queue):
                self.statuslog.warning("Rewinding to start")
            else:
                self.statuslog.info("Rewinding")

            for i in range(num + 1):
                if len(self.prev_queue) > 0:
                    self.queue.insert(0, self.prev_queue.pop())

            try:
                self.streamer.stop()
            except Exception as e:
                logger.exception(e)


Instruction:
Explain what the following Python 3 code does
async def set_loop(self, loop_value):
        if loop_value not in ['on', 'off', 'shuffle']:
            self.statuslog.error("Loop value must be `off`, `on`, or `shuffle`")
            return

        self.loop_type = loop_value
        if self.loop_type == 'on':
            self.statuslog.info("Looping on")
        elif self.loop_type == 'off':
            self.statuslog.info("Looping off")
        elif self.loop_type == 'shuffle':
            self.statuslog.info("Looping on and shuffling")

Response: Updates the loop value.


Instruction:
Can you tell what is the following Python 3 function doing
def write_volume(self):
        # Update the volume
        data = datatools.get_data()
        data["discord"]["servers"][self.server_id][_data.modulename]["volume"] = self.volume
        datatools.write_data(data)

Response: Writes the current volume to the data. json


Instruction:
Create a Python 3 function for
moving the embed message to a new channel

Response:
async def movehere(self, channel):
        """
        Moves the embed message to a new channel; can also be used to move the musicplayer to the front

        Args:
            channel (discord.Channel): The channel to move to
        """

        self.logger.debug("movehere command")

        # Delete the old message
        await self.embed.delete()
        # Set the channel to this channel
        self.embed.channel = channel
        # Send a new embed to the channel
        await self.embed.send()
        # Re-add the reactions
        await self.add_reactions()

        self.statuslog.info("Moved to front")


Instruction:
Write a Python 3 function for
setting the topic channel for this server

Response:
async def set_topic_channel(self, channel):
        """Set the topic channel for this server"""
        data = datatools.get_data()
        data["discord"]["servers"][self.server_id][_data.modulename]["topic_id"] = channel.id
        datatools.write_data(data)

        self.topicchannel = channel
        await self.set_topic(self.topic)

        await client.send_typing(channel)
        embed = ui_embed.topic_update(channel, self.topicchannel)
        await embed.send()


Instruction:
How would you implement a function in Python 3 that
clears the topic channel for this server

Response:
async def clear_topic_channel(self, channel):
        """Set the topic channel for this server"""
        try:
            if self.topicchannel:
                await client.edit_channel(self.topicchannel, topic="")
        except Exception as e:
            logger.exception(e)

        self.topicchannel = None
        logger.debug("Clearing topic channel")

        data = datatools.get_data()
        data["discord"]["servers"][self.server_id][_data.modulename]["topic_id"] = ""
        datatools.write_data(data)

        await client.send_typing(channel)
        embed = ui_embed.topic_update(channel, self.topicchannel)
        await embed.send()


Instruction:
Make a summary of the following Python 3 code
async def vsetup(self, author):

        if self.vready:
            logger.warning("Attempt to init voice when already initialised")
            return

        if self.state != 'starting':
            logger.error("Attempt to init from wrong state ('{}'), must be 'starting'.".format(self.state))
            return

        self.logger.debug("Setting up voice")

        # Create voice client
        self.vchannel = author.voice.voice_channel
        if self.vchannel:
            self.statuslog.info("Connecting to voice")
            try:
                self.vclient = await client.join_voice_channel(self.vchannel)
            except discord.ClientException as e:
                logger.exception(e)
                self.statuslog.warning("I'm already connected to a voice channel.")
                return
            except discord.opus.OpusNotLoaded as e:
                logger.exception(e)
                logger.error("Could not load Opus. This is an error with your FFmpeg setup.")
                self.statuslog.error("Could not load Opus.")
                return
            except discord.DiscordException as e:
                logger.exception(e)
                self.statuslog.error("I couldn't connect to the voice channel. Check my permissions.")
                return
            except Exception as e:
                self.statuslog.error("Internal error connecting to voice, disconnecting.")
                logger.error("Error connecting to voice {}".format(e))
                return
        else:
            self.statuslog.error("You're not connected to a voice channel.")
            return

        self.vready = True

Response: Creates the voice client and sets up the internal state of the object.


Instruction:
Can you implement a function in Python 3 that
creates the gui and the music

Response:
async def msetup(self, text_channel):
        """Creates the gui

        Args:
            text_channel (discord.Channel): The channel for the embed ui to run in
        """

        if self.mready:
            logger.warning("Attempt to init music when already initialised")
            return

        if self.state != 'starting':
            logger.error("Attempt to init from wrong state ('{}'), must be 'starting'.".format(self.state))
            return

        self.logger.debug("Setting up gui")

        # Create gui
        self.mchannel = text_channel
        self.new_embed_ui()
        await self.embed.send()
        await self.embed.usend()
        await self.add_reactions()

        self.mready = True


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

        self.logger.debug("Creating new embed ui object")

        # Initial queue display
        queue_display = []
        for i in range(self.queue_display):
            queue_display.append("{}. ---\n".format(str(i + 1)))

        # Initial datapacks
        datapacks = [
            ("Now playing", "---", False),
            ("Author", "---", True),
            ("Source", "---", True),
            ("Time", "```http\n" + _timebar.make_timebar() + "\n```", False),
            ("Queue", "```md\n{}\n```".format(''.join(queue_display)), False),
            ("Songs left in queue", "---", True),
            ("Volume", "{}%".format(self.volume), True),
            ("Status", "```---```", False)
        ]

        # Create embed UI object
        self.embed = ui_embed_tools.UI(
            self.mchannel,
            "",
            "",
            modulename=_data.modulename,
            colour=_data.modulecolor,
            datapacks=datapacks
        )

        # Add handlers to update gui
        noformatter = logging.Formatter("{message}", style="{")
        timeformatter = logging.Formatter("```http\n{message}\n```", style="{")
        mdformatter = logging.Formatter("```md\n{message}\n```", style="{")
        statusformatter = logging.Formatter("```__{levelname}__\n{message}\n```", style="{")
        volumeformatter = logging.Formatter("{message}%", style="{")

        nowplayinghandler = EmbedLogHandler(self, self.embed, 0)
        nowplayinghandler.setFormatter(noformatter)
        nowplayingauthorhandler = EmbedLogHandler(self, self.embed, 1)
        nowplayingauthorhandler.setFormatter(noformatter)
        nowplayingsourcehandler = EmbedLogHandler(self, self.embed, 2)
        nowplayingsourcehandler.setFormatter(noformatter)
        timehandler = EmbedLogHandler(self, self.embed, 3)
        timehandler.setFormatter(timeformatter)
        queuehandler = EmbedLogHandler(self, self.embed, 4)
        queuehandler.setFormatter(mdformatter)
        queuelenhandler = EmbedLogHandler(self, self.embed, 5)
        queuelenhandler.setFormatter(noformatter)
        volumehandler = EmbedLogHandler(self, self.embed, 6)
        volumehandler.setFormatter(volumeformatter)
        statushandler = EmbedLogHandler(self, self.embed, 7)
        statushandler.setFormatter(statusformatter)

        self.nowplayinglog.addHandler(nowplayinghandler)
        self.nowplayingauthorlog.addHandler(nowplayingauthorhandler)
        self.nowplayingsourcelog.addHandler(nowplayingsourcehandler)
        self.timelog.addHandler(timehandler)
        self.queuelog.addHandler(queuehandler)
        self.queuelenlog.addHandler(queuelenhandler)
        self.volumelog.addHandler(volumehandler)
        self.statuslog.addHandler(statushandler)

Response: Create the embed UI object and save it to self


Instruction:
Implement a Python 3 function for
adding the reactions buttons to the current message

Response:
async def add_reactions(self):
        """Adds the reactions buttons to the current message"""
        self.statuslog.info("Loading buttons")
        for e in ("⏯", "⏮", "⏹", "⏭", "🔀", "🔉", "🔊"):
            try:
                if self.embed is not None:
                    await client.add_reaction(self.embed.sent_embed, e)
            except discord.DiscordException as e:
                logger.exception(e)
                self.statuslog.error("I couldn't add the buttons. Check my permissions.")
            except Exception as e:
                logger.exception(e)


Instruction:
Write a Python 3 script for
queuing songs based on either a YouTube search or a link Args: query (str): Either a search term or a link queue_index (str): The queue index to enqueue at (None for end) stop_current (bool): Whether to stop the current song after the songs are queued shuffle (bool): Whether to shuffle the added songs

Response:
async def enqueue(self, query, queue_index=None, stop_current=False, shuffle=False):
        """
        Queues songs based on either a YouTube search or a link

        Args:
            query (str): Either a search term or a link
            queue_index (str): The queue index to enqueue at (None for end)
            stop_current (bool): Whether to stop the current song after the songs are queued
            shuffle (bool): Whether to shuffle the added songs
        """

        if query is None or query == "":
            return

        self.statuslog.info("Parsing {}".format(query))
        self.logger.debug("Enqueueing from query")

        indexnum = None
        if queue_index is not None:
            try:
                indexnum = int(queue_index) - 1
            except TypeError:
                self.statuslog.error("Play index argument must be a number")
                return
            except ValueError:
                self.statuslog.error("Play index argument must be a number")
                return

        if not self.vready:
            self.parse_query(query, indexnum, stop_current, shuffle)
        else:
            parse_thread = threading.Thread(
                target=self.parse_query,
                args=[query, indexnum, stop_current, shuffle])
            # Run threads
            parse_thread.start()