Instruction:
Write a Python 3 function that can
analyze queries from a given log file

Response:
def analyze_profile(self):
        """Analyzes queries from a given log file"""
        profile_parser = ProfileParser()
        databases = self._get_requested_databases()
        connection = pymongo.MongoClient(self._db_uri,
                                         document_class=OrderedDict,
                                         read_preference=pymongo.ReadPreference.PRIMARY_PREFERRED)

        if databases == []:
            try:
                databases = connection.database_names()
            except:
                message = "Error: Could not list databases on server. Please " \
                          +         "check the auth components of your URI or provide " \
                          +         "a namespace filter with -n.\n"
                sys.stderr.write(message)
                databases = []

            for ignore_db in IGNORE_DBS:
                if ignore_db in databases:
                    databases.remove(ignore_db)

        for database in databases:

            db = connection[database]

            profile_entries = db['system.profile'].find()

            for profile_entry in profile_entries:
                self._process_query(profile_entry,
                                    profile_parser)

        self._output_aggregated_report(sys.stdout)

        return 0


Instruction:
Can you tell what is the following Python 3 function doing
def watch_profile(self):
        profile_parser = ProfileParser()
        databases = self._get_requested_databases()
        connection = pymongo.MongoClient(self._db_uri,
                                         document_class=OrderedDict,
                                         read_preference=pymongo.ReadPreference.PRIMARY_PREFERRED)
        enabled_profile = False

        if databases == []:
            try:
                databases = connection.database_names()
            except:
                message = "Error: Could not list databases on server. Please " \
                          +         "check the auth components of your URI.\n"
                sys.stderr.write(message)
                databases = []

            for ignore_db in IGNORE_DBS:
                if ignore_db in databases:
                    databases.remove(ignore_db)

        if len(databases) != 1:
            message = "Error: Please use namespaces (-n) to specify a single " \
                      +         "database for profile watching.\n"
            sys.stderr.write(message)
            return 1

        database = databases[0]
        db = connection[database]

        initial_profile_level = db.profiling_level()

        if initial_profile_level is pymongo.OFF:
            message = "Profile level currently 0. Dex is setting profile " \
                      +         "level 1. To run --watch at profile level 2, " \
                      +         "enable profile level 2 before running Dex.\n"
            sys.stderr.write(message)
            db.set_profiling_level(DEFAULT_PROFILE_LEVEL)

        output_time = time.time() + WATCH_DISPLAY_REFRESH_SECONDS
        try:
            for profile_entry in self._tail_profile(db, WATCH_INTERVAL_SECONDS):
                self._process_query(profile_entry,
                                    profile_parser)
                if time.time() >= output_time:
                    self._output_aggregated_report(sys.stderr)
                    output_time = time.time() + WATCH_DISPLAY_REFRESH_SECONDS
        except KeyboardInterrupt:
            sys.stderr.write("Interrupt received\n")
        finally:
            self._output_aggregated_report(sys.stdout)
            if initial_profile_level is pymongo.OFF:
                message = "Dex is resetting profile level to initial value " \
                          +         "of 0. You may wish to drop the system.profile " \
                          +         "collection.\n"
                sys.stderr.write(message)
                db.set_profiling_level(initial_profile_level)

        return 0

Response: Analyzes queries from a given log file and writes them to the output file.


Instruction:
Can you write a function in Python 3 where it
analyzes queries from a given log file

Response:
def analyze_logfile(self, logfile_path):
        self._run_stats['logSource'] = logfile_path
        """Analyzes queries from a given log file"""
        with open(logfile_path) as obj:
            self.analyze_logfile_object(obj)

        self._output_aggregated_report(sys.stdout)

        return 0


Instruction:
How would you code a function in Python 3 to
analyze queries from a given log file object

Response:
def analyze_logfile_object(self, file_object):
        """Analyzes queries from a given log file"""
        log_parser = LogParser()

        if self._start_time is None:
            self._start_time = datetime.now()
            if self._timeout != 0:
                self._end_time = self._start_time + timedelta(minutes=self._timeout)
            else:
                self._end_time = None

        # For each line in the logfile ...
        for line in file_object:
            if self._end_time is not None and datetime.now() > self._end_time:
                self._run_stats['timedOut'] = True
                self._run_stats['timeoutInMinutes'] = self._timeout
                break
            self._process_query(line, log_parser)

        return 0


Instruction:
Create a Python 3 function to
analyze queries from the tail of a given log file and writes them to the output

Response:
def watch_logfile(self, logfile_path):
        """Analyzes queries from the tail of a given log file"""
        self._run_stats['logSource'] = logfile_path
        log_parser = LogParser()

        # For each new line in the logfile ...
        output_time = time.time() + WATCH_DISPLAY_REFRESH_SECONDS
        try:
            firstLine = True
            for line in self._tail_file(open(logfile_path),
                                        WATCH_INTERVAL_SECONDS):
                if firstLine:
                    self._run_stats['timeRange']['start'] = get_line_time(line)
                self._process_query(line, log_parser)
                self._run_stats['timeRange']['end'] = get_line_time(line)
                if time.time() >= output_time:
                    self._output_aggregated_report(sys.stderr)
                    output_time = time.time() + WATCH_DISPLAY_REFRESH_SECONDS
        except KeyboardInterrupt:
            sys.stderr.write("Interrupt received\n")
        finally:
            self._output_aggregated_report(sys.stdout)

        return 0


Instruction:
Implement a Python 3 function for
tailing the system. profile collection

Response:
def _tail_profile(self, db, interval):
        """Tails the system.profile collection"""
        latest_doc = None
        while latest_doc is None:
            time.sleep(interval)
            latest_doc = db['system.profile'].find_one()

        current_time = latest_doc['ts']

        while True:
            time.sleep(interval)
            cursor = db['system.profile'].find({'ts': {'$gte': current_time}}).sort('ts', pymongo.ASCENDING)
            for doc in cursor:
                current_time = doc['ts']
                yield doc


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _tuplefy_namespace(self, namespace):
        namespace_split = namespace.split('.', 1)
        if len(namespace_split) is 1:
            # we treat a single element as a collection name.
            # this also properly tuplefies '*'
            namespace_tuple = ('*', namespace_split[0])
        elif len(namespace_split) is 2:
            namespace_tuple = (namespace_split[0],namespace_split[1])
        else:
            return None
        return namespace_tuple

Response: Converts a mongodb namespace to a db collection tuple


Instruction:
Write a Python 3 script to
convert a list of db namespaces to a list of namespace tuples supporting basic commandline wildcards

Response:
def _validate_namespaces(self, input_namespaces):
        """Converts a list of db namespaces to a list of namespace tuples,
            supporting basic commandline wildcards"""
        output_namespaces = []
        if input_namespaces == []:
            return output_namespaces
        elif '*' in input_namespaces:
            if len(input_namespaces) > 1:
                warning = 'Warning: Multiple namespaces are '
                warning += 'ignored when one namespace is "*"\n'
                sys.stderr.write(warning)
            return output_namespaces
        else:
            for namespace in input_namespaces:
                if not isinstance(namespace, unicode):
                    namespace = unicode(namespace)
                namespace_tuple = self._tuplefy_namespace(namespace)
                if namespace_tuple is None:
                    warning = 'Warning: Invalid namespace ' + namespace
                    warning += ' will be ignored\n'
                    sys.stderr.write(warning)
                else:
                    if namespace_tuple not in output_namespaces:
                        output_namespaces.append(namespace_tuple)
                    else:
                        warning = 'Warning: Duplicate namespace ' + namespace
                        warning += ' will be ignored\n'
                        sys.stderr.write(warning)
        return output_namespaces


Instruction:
How would you explain what the following Python 3 function does
def _namespace_requested(self, namespace):
        if namespace is None:
            return False
        namespace_tuple = self._tuplefy_namespace(namespace)
        if namespace_tuple[0] in IGNORE_DBS:
            return False
        elif namespace_tuple[1] in IGNORE_COLLECTIONS:
            return False
        else:
            return self._tuple_requested(namespace_tuple)

Response: Checks whether the requested_namespaces contain the provided namespace


Instruction:
How would you explain what the following Python 3 function does
def _tuple_requested(self, namespace_tuple):
        if not isinstance(namespace_tuple[0], unicode):
            encoded_db = unicode(namespace_tuple[0])
        else:
            encoded_db = namespace_tuple[0]
        if not isinstance(namespace_tuple[1], unicode):
            encoded_coll = unicode(namespace_tuple[1])
        else:
            encoded_coll = namespace_tuple[1]

        if namespace_tuple is None:
            return False
        elif len(self._requested_namespaces) is 0:
            return True
        for requested_namespace in self._requested_namespaces:
            if  ((((requested_namespace[0]) == u'*') or
                 (encoded_db == requested_namespace[0])) and
                (((requested_namespace[1]) == u'*') or
                 (encoded_coll == requested_namespace[1]))):
                return True
        return False

Response: Helper for _namespace_requested. Supports limited wildcards


Instruction:
Can you write a function in Python 3 where it
returns a list of databases requested not including ignored dbs

Response:
def _get_requested_databases(self):
        """Returns a list of databases requested, not including ignored dbs"""
        requested_databases = []
        if ((self._requested_namespaces is not None) and
                (self._requested_namespaces != [])):
            for requested_namespace in self._requested_namespaces:
                if requested_namespace[0] is '*':
                    return []
                elif requested_namespace[0] not in IGNORE_DBS:
                    requested_databases.append(requested_namespace[0])
        return requested_databases


Instruction:
Can you generate the documentation for the following Python 3 function
def retrieve(self, state=None, favorite=None, tag=None, contentType=None,
                 sort=None, detailType=None, search=None, domain=None,
                 since=None, count=None, offset=None):
        """
        Retrieve the list of your articles
        See: https://getpocket.com/developer/docs/v3/retrieve
        :param state: filter by state
        :param favorite: only fetch favorite
        :param tag: filter by tag or _untagged_
        :param contentType: get article, video or image
        :param sort: sort by provided value
        :param detailType: defines the response details to return
        :param search: search term
        :param domain: search domain
        :param since: search modified since unix timestamp
        :param count: the number of required items
        :param offset: the position to start results from
        :return: A dictionary containing the response result
        :rtype: dict
        """
        return self._make_request('get')

Response: Retrieve the list of your articles with optional parameters


Instruction:
Here you have a function in Python 3, explain what it does
def bulk_add(self, item_id, ref_id=None, tags=None,
                 time=None, title=None, url=None):
        """
        Add an item to list
        See: https://getpocket.com/developer/docs/v3/modify
        :param item_id: int
        :param ref_id: tweet_id
        :param tags: list of tags
        :param time: time of action
        :param title: given title
        :param url: item url
        :return: self for chaining
        :rtype: Pocket
        """
        self._add_action('add')
        return self

Response: Add an item to the list of items


Instruction:
Write a Python 3 script to
register an action into bulk_actions

Response:
def _add_action(self, action):
        """
        Register an action into bulk
        :param action: action name
        """
        kwargs = self._get_method_params()

        kwargs['action'] = action

        self._bulk_actions.append(kwargs)


Instruction:
Implement a function in Python 3 to
perform the request to the specified action name

Response:
def _make_request(self, action):
        """
        Perform the request
        :param action: action name
        :return: a dict containing the request result
        :rtype: dict
        """
        if isinstance(action, list):
            kwargs = {'actions': action}
            action = 'send'
        else:
            kwargs = self._get_method_params()

        kwargs.update({
            'consumer_key': self._consumer_key,
            'access_token': self._access_token
        })

        response = requests.post(
            self._get_url(action),
            json=kwargs,
            headers=self._get_headers()
        )

        if response.status_code != requests.codes.ok:
            raise self._make_exception(response)

        return response.json()


Instruction:
How would you explain what the following Python 3 function does
def _get_method_params(self):
        caller = sys._getframe(2)
        var_names = list(caller.f_code.co_varnames)
        caller_locals = caller.f_locals

        var_names.remove('self')
        kwargs = {key: value for key, value in caller_locals.items()
                  if key in var_names and value is not None}
        return kwargs

Response: This method reads the caller s parameters and filters the params passed to the caller s make_request method.


Instruction:
How would you explain what the following Python 3 function does
def _make_exception(self, response):
        headers = response.headers

        limit_headers = []
        if 'X-Limit-User-Limit' in headers:
            limit_headers = [
                headers['X-Limit-User-Limit'],
                headers['X-Limit-User-Remaining'],
                headers['X-Limit-User-Reset'],
                headers['X-Limit-Key-Limit'],
                headers['X-Limit-Key-Remaining'],
                headers['X-Limit-Key-Reset']
            ]

        x_error_code = int(headers['X-Error-Code'])
        exc = PocketException
        if x_error_code in self.auth_error_codes:
            exc = PocketAutException

        return exc(
            response.status_code,
            x_error_code,
            headers['X-Error'],
            *limit_headers
        )

Response: Construct an exception instance from the response.


Instruction:
Can you tell what is the following Python 3 function doing
def set_money_currency(self, money_currency):
        if money_currency not in self.money_formats:
            raise CurrencyDoesNotExist

        self.money_currency = money_currency

Response: Sets the money currency for the log entry.


Instruction:
Implement a Python 3 function for
getting the money format for a given amount

Response:
def get_money_format(self, amount):
        """
        :type amount: int or float or str

        Usage:
        >>> currency = Currency('USD')
        >>> currency.get_money_format(13)
        >>> '$13'
        >>> currency.get_money_format(13.99)
        >>> '$13.99'
        >>> currency.get_money_format('13,2313,33')
        >>> '$13,2313,33'

        :rtype: str
        """
        return self.money_formats[
            self.get_money_currency()
        ]['money_format'].format(amount=amount)


Instruction:
Can you tell what is the following Python 3 function doing
def get_money_with_currency_format(self, amount):
        return self.money_formats[
            self.get_money_currency()
        ]['money_with_currency_format'].format(amount=amount)

Response: Get money with currency format


Instruction:
Create a Python 3 function to
connect to the Deluge instance and logs in to Deluge.

Response:
def connect(self):
        """
        Connects to the Deluge instance
        """
        self._connect()
        logger.debug('Connected to Deluge, detecting daemon version')
        self._detect_deluge_version()
        logger.debug('Daemon version {} detected, logging in'.format(self.deluge_version))
        if self.deluge_version == 2:
            result = self.call('daemon.login', self.username, self.password, client_version='deluge-client')
        else:
            result = self.call('daemon.login', self.username, self.password)
        logger.debug('Logged in with value %r' % result)
        self.connected = True


Instruction:
Create a Python 3 function for
calling an RPC function and returns the response.

Response:
def call(self, method, *args, **kwargs):
        """
        Calls an RPC function
        """
        tried_reconnect = False
        for _ in range(2):
            try:
                self._send_call(self.deluge_version, self.deluge_protocol_version, method, *args, **kwargs)
                return self._receive_response(self.deluge_version, self.deluge_protocol_version)
            except (socket.error, ConnectionLostException, CallTimeoutException):
                if self.automatic_reconnect:
                    if tried_reconnect:
                        raise FailedToReconnectException()
                    else:
                        try:
                            self.reconnect()
                        except (socket.error, ConnectionLostException, CallTimeoutException):
                            raise FailedToReconnectException()

                    tried_reconnect = True
                else:
                    raise


Instruction:
Implement a function in Python 3 to
serialize this StickerSet to a dictionary.

Response:
def to_array(self):
        """
        Serializes this StickerSet to a dictionary.

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(StickerSet, self).to_array()
        array['name'] = u(self.name)  # py2: type unicode, py3: type str

        array['title'] = u(self.title)  # py2: type unicode, py3: type str

        array['contains_masks'] = bool(self.contains_masks)  # type bool
        array['stickers'] = self._as_array(self.stickers)  # type list of Sticker

        return array


Instruction:
How would you explain what the following Python 3 function does
def from_array(array):
        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")
        from pytgbot.api_types.receivable.media import Sticker

        data = {}
        data['name'] = u(array.get('name'))
        data['title'] = u(array.get('title'))
        data['contains_masks'] = bool(array.get('contains_masks'))
        data['stickers'] = Sticker.from_array_list(array.get('stickers'), list_level=1)
        data['_raw'] = array
        return StickerSet(**data)

Response: Deserialize a new StickerSet from a given dictionary.


Instruction:
How would you code a function in Python 3 to
serialize this MaskPosition to a dictionary.

Response:
def to_array(self):
        """
        Serializes this MaskPosition to a dictionary.

        :return: dictionary representation of this object.
        :rtype: dict
        """
        array = super(MaskPosition, self).to_array()
        array['point'] = u(self.point)  # py2: type unicode, py3: type str

        array['x_shift'] = float(self.x_shift)  # type float
        array['y_shift'] = float(self.y_shift)  # type float
        array['scale'] = float(self.scale)  # type float
        return array


Instruction:
Can you implement a function in Python 3 that
uses ACE to compile a grammar.

Response:
def compile(cfg_path, out_path, executable=None, env=None, log=None):
    """
    Use ACE to compile a grammar.

    Args:
        cfg_path (str): the path to the ACE config file
        out_path (str): the path where the compiled grammar will be
            written
        executable (str, optional): the path to the ACE binary; if
            `None`, the `ace` command will be used
        env (dict, optional): environment variables to pass to the ACE
            subprocess
        log (file, optional): if given, the file, opened for writing,
            or stream to write ACE's stdout and stderr compile messages
    """
    try:
        check_call(
            [(executable or 'ace'), '-g', cfg_path, '-G', out_path],
            stdout=log, stderr=log, close_fds=True,
            env=(env or os.environ)
        )
    except (CalledProcessError, OSError):
        logging.error(
            'Failed to compile grammar with ACE. See {}'
            .format(log.name if log is not None else '<stderr>')
        )
        raise


Instruction:
How would you explain what the following Python 3 function does
def parse_from_iterable(grm, data, **kwargs):
    with AceParser(grm, **kwargs) as parser:
        for datum in data:
            yield parser.interact(datum)

Response: Parse each sentence in data with ACE using grammar grm.


Instruction:
Can you create a Python 3 function that
transfers from each MRS in data with ACE using grammar grm.

Response:
def transfer_from_iterable(grm, data, **kwargs):
    """
    Transfer from each MRS in *data* with ACE using grammar *grm*.

    Args:
        grm (str): path to a compiled grammar image
        data (iterable): source MRSs as SimpleMRS strings
        **kwargs: additional keyword arguments to pass to the
            AceTransferer
    Yields:
        :class:`~delphin.interfaces.ParseResponse`
    """
    with AceTransferer(grm, **kwargs) as transferer:
        for datum in data:
            yield transferer.interact(datum)


Instruction:
Write a Python 3 script to
generate from each MRS in data using ACE using grammar grm.

Response:
def generate_from_iterable(grm, data, **kwargs):
    """
    Generate from each MRS in *data* with ACE using grammar *grm*.

    Args:
        grm (str): path to a compiled grammar image
        data (iterable): MRSs as SimpleMRS strings
        **kwargs: additional keyword arguments to pass to the
            AceGenerator
    Yields:
        :class:`~delphin.interfaces.ParseResponse`
    """
    with AceGenerator(grm, **kwargs) as generator:
        for datum in data:
            yield generator.interact(datum)


Instruction:
Implement a Python 3 function for
sending a string to the ACE.

Response:
def send(self, datum):
        """
        Send *datum* (e.g. a sentence or MRS) to ACE.

        Warning:
          Sending data without reading (e.g., via :meth:`receive`) can
          fill the buffer and cause data to be lost. Use the
          :meth:`interact` method for most data-processing tasks with
          ACE.
        """
        try:
            self._p.stdin.write((datum.rstrip() + '\n'))
            self._p.stdin.flush()
        except (IOError, OSError):  # ValueError if file was closed manually
            logging.info(
                'Attempted to write to a closed process; attempting to reopen'
            )
            self._open()
            self._p.stdin.write((datum.rstrip() + '\n'))
            self._p.stdin.flush()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def interact(self, datum):
        validated = self._validate_input(datum)
        if validated:
            self.send(validated)
            result = self.receive()
        else:
            result, lines = _make_response(
                [('NOTE: PyDelphin could not validate the input and '
                  'refused to send it to ACE'),
                 'SKIP: {}'.format(datum)],
                self.run_info)
        result['input'] = datum
        return result

Response: Send a datum to ACE and return the response.


Instruction:
Write a Python 3 function that can
send a datum to ACE and return the response with context.

Response:
def process_item(self, datum, keys=None):
        """
        Send *datum* to ACE and return the response with context.

        The *keys* parameter can be used to track item identifiers
        through an ACE interaction. If the `task` member is set on
        the AceProcess instance (or one of its subclasses), it is
        kept in the response as well.
        Args:
            datum (str): the input sentence or MRS
            keys (dict): a mapping of item identifier names and values
        Returns:
            :class:`~delphin.interfaces.ParseResponse`
        """
        response = self.interact(datum)
        if keys is not None:
            response['keys'] = keys
        if 'task' not in response and self.task is not None:
            response['task'] = self.task
        return response


Instruction:
Can you tell what is the following Python 3 function doing
def close(self):
        self.run_info['end'] = datetime.now()
        self._p.stdin.close()
        for line in self._p.stdout:
            if line.startswith('NOTE: tsdb run:'):
                self._read_run_info(line)
            else:
                logging.debug('ACE cleanup: {}'.format(line.rstrip()))
        retval = self._p.wait()
        return retval

Response: Close the ACE process and return the process s exit code.


Instruction:
Make a summary of the following Python 3 code
def load(fh, single=False):
    ms = deserialize(fh)
    if single:
        ms = next(ms)
    return ms

Response: Deserialize DMRX from a file handle or filename.


Instruction:
Given the following Python 3 function, write the documentation
def derivation(self):
        drv = self.get('derivation')
        if drv is not None:
            if isinstance(drv, dict):
                drv = Derivation.from_dict(drv)
            elif isinstance(drv, stringtypes):
                drv = Derivation.from_string(drv)
        return drv

Response:
Deserialize and return a Derivation object for UDF - or
        JSON - formatted derivation data ; otherwise return the original
        string.


Instruction:
How would you explain what the following Python 3 function does
def mrs(self):
        mrs = self.get('mrs')
        if mrs is not None:
            if isinstance(mrs, dict):
                mrs = Mrs.from_dict(mrs)
            elif isinstance(mrs, stringtypes):
                mrs = simplemrs.loads_one(mrs)
        return mrs

Response:
Deserialize and return an Mrs object for simplemrs or
        JSON - formatted MRS data ; otherwise return the original string.


Instruction:
Can you tell what is the following Python 3 function doing
def eds(self):
        _eds = self.get('eds')
        if _eds is not None:
            if isinstance(_eds, dict):
                _eds = eds.Eds.from_dict(_eds)
            elif isinstance(_eds, stringtypes):
                _eds = eds.loads_one(_eds)
        return _eds

Response:
Deserialize and return an Eds object for native - or
        JSON - formatted EDS data ; otherwise return the original string.


Instruction:
Make a summary of the following Python 3 code
def dmrs(self):
        dmrs = self.get('dmrs')
        if dmrs is not None:
            if isinstance(dmrs, dict):
                dmrs = Dmrs.from_dict(dmrs)
        return dmrs

Response:
Deserialize and return a Dmrs object for JSON - formatted DMRS
        data ; otherwise return the original string.


Instruction:
Here you have a function in Python 3, explain what it does
def map(self, response):
        inserts = []

        parse = {}
        # custom remapping, cleanup, and filling in holes
        parse['i-id'] = response.get('keys', {}).get('i-id', -1)
        self._parse_id = max(self._parse_id + 1, parse['i-id'])
        parse['parse-id'] = self._parse_id
        parse['run-id'] = response.get('run', {}).get('run-id', -1)
        if 'tokens' in response:
            parse['p-input'] = response['tokens'].get('initial')
            parse['p-tokens'] = response['tokens'].get('internal')
            if 'ninputs' not in response:
                toks = response.tokens('initial')
                if toks is not None:
                    response['ninputs'] = len(toks.tokens)
            if 'ntokens' not in response:
                toks = response.tokens('internal')
                if toks is not None:
                    response['ntokens'] = len(toks.tokens)
        if 'readings' not in response and 'results' in response:
            response['readings'] = len(response['results'])
        # basic mapping
        for key in self._parse_keys:
            if key in response:
                parse[key] = response[key]
        inserts.append(('parse', parse))

        for result in response.get('results', []):
            d = {'parse-id': self._parse_id}
            if 'flags' in result:
                d['flags'] = SExpr.format(result['flags'])
            for key in self._result_keys:
                if key in result:
                    d[key] = result[key]
            inserts.append(('result', d))

        if 'run' in response:
            run_id = response['run'].get('run-id', -1)
            # check if last run was not closed properly
            if run_id not in self._runs and self._last_run_id in self._runs:
                last_run = self._runs[self._last_run_id]
                if 'end' not in last_run:
                    last_run['end'] = datetime.now()
            self._runs[run_id] = response['run']
            self._last_run_id = run_id

        return inserts

Response: Process a response dict and return a list of tuples.


Instruction:
Implement a function in Python 3 to
return aggregated ( table rowdata ) tuples and clear the state.

Response:
def cleanup(self):
        """
        Return aggregated (table, rowdata) tuples and clear the state.
        """
        inserts = []

        last_run = self._runs[self._last_run_id]
        if 'end' not in last_run:
            last_run['end'] = datetime.now()

        for run_id in sorted(self._runs):
            run = self._runs[run_id]
            d = {'run-id': run.get('run-id', -1)}
            for key in self._run_keys:
                if key in run:
                    d[key] = run[key]
            inserts.append(('run', d))

        # reset for next task
        self._parse_id = -1
        self._runs = {}
        self._last_run_id = -1

        return inserts


Instruction:
How would you explain what the following Python 3 function does
def to_array(self):
        array = super(GameHighScore, self).to_array()
        array['position'] = int(self.position)  # type int
        array['user'] = self.user.to_array()  # type User
        array['score'] = int(self.score)  # type int
        return array

Response: Serializes this GameHighScore to a dictionary.


Instruction:
How would you explain what the following Python 3 function does
def from_array(array):
        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")

        from pytgbot.api_types.receivable.peer import User

        data = {}
        data['position'] = int(array.get('position'))
        data['user'] = User.from_array(array.get('user'))
        data['score'] = int(array.get('score'))
        data['_raw'] = array
        return GameHighScore(**data)

Response: Deserialize a new GameHighScore instance from a given dictionary.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def dmrs_tikz_dependency(xs, **kwargs):
    def link_label(link):
        return '{}/{}'.format(link.rargname or '', link.post)

    def label_edge(link):
        if link.post == H_POST and link.rargname == RSTR_ROLE:
            return 'rstr'
        elif link.post == EQ_POST:
            return 'eq'
        else:
            return 'arg'

    if isinstance(xs, Xmrs):
        xs = [xs]

    lines = """\\documentclass{standalone}

\\usepackage{tikz-dependency}
\\usepackage{relsize}

%%%
%%% style for dmrs graph
%%%
\\depstyle{dmrs}{edge unit distance=1.5ex,
  label style={above, scale=.9, opacity=0, text opacity=1},
  baseline={([yshift=-0.7\\baselineskip]current bounding box.north)}}
%%% set text opacity=0 to hide text, opacity = 0 to hide box
\\depstyle{root}{edge unit distance=3ex, label style={opacity=1}}
\\depstyle{arg}{edge above}
\\depstyle{rstr}{edge below, dotted, label style={text opacity=1}}
\\depstyle{eq}{edge below, label style={text opacity=1}}
\\depstyle{icons}{edge below, dashed}
\\providecommand{\\named}{}
\\renewcommand{\\named}{named}

%%% styles for predicates and roles (from mrs.sty)
\\providecommand{\\spred}{}
\\renewcommand{\\spred}[1]{\\mbox{\\textsf{#1}}}
\\providecommand{\\srl}{}
\\renewcommand{\\srl}[1]{\\mbox{\\textsf{\\smaller #1}}}
%%%

\\begin{document}""".split("\n")

    for ix, x in enumerate(xs):
        lines.append("%%%\n%%% {}\n%%%".format(ix+1))
        lines.append("\\begin{dependency}[dmrs]")
        ns = nodes(x)
        ### predicates
        lines.append("  \\begin{deptext}[column sep=10pt]")
        for i, n in enumerate(ns):
            sep = "\\&"  if  (i < len(ns) - 1) else  "\\\\"
            pred = _latex_escape(n.pred.short_form())
            pred = "\\named{}" if pred == 'named' else pred
            if n.carg is not None:
                print(n.carg.strip('"'))
                pred += "\\smaller ({})".format(n.carg.strip('"'))
            lines.append("    \\spred{{{}}} {}     % node {}".format(
                pred, sep, i+1))
        lines.append("  \\end{deptext}")
        nodeidx = {n.nodeid: i+1 for i, n in enumerate(ns)}
        ### links
        for link in links(x):
            if link.start == 0:
                lines.append(
                    '  \\deproot[root]{{{}}}{{{}}}'.format(
                        nodeidx[link.end],
                        '\\srl{TOP}'  # _latex_escape('/' + link.post)
                    )
                )
            else:
                lines.append('  \\depedge[{}]{{{}}}{{{}}}{{\\srl{{{}}}}}'.format(
                    label_edge(link),
                    nodeidx[link.start],
                    nodeidx[link.end],
                    _latex_escape(link_label(link))
                ))
        ### placeholder for icons
        lines.append('%  \\depedge[icons]{f}{t}{FOCUS}')
        lines.append('\\end{dependency}\n')
    lines.append('\\end{document}')
    return '\n'.join(lines)

Response: Returns a LaTeX document with each Xmrs in xs rendered as dmrs - tikz - dependency.


Instruction:
Given the following Python 3 function, write the documentation
def valuemap(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        if 'value' in kwargs:
            val = kwargs['value']
            del kwargs['value']
            _f = f(*args, **kwargs)
            def valued_f(*args, **kwargs):
                result = _f(*args, **kwargs)
                s, obj, span = result
                if callable(val):
                    return PegreResult(s, val(obj), span)
                else:
                    return PegreResult(s, val, span)
            return valued_f
        else:
            return f(*args, **kwargs)
    return wrapper

Response: Decorator to help PEG functions handle value conversions.


Instruction:
Can you generate the documentation for the following Python 3 function
def literal(x):
    xlen = len(x)
    msg = 'Expected: "{}"'.format(x)
    def match_literal(s, grm=None, pos=0):
        if s[:xlen] == x:
            return PegreResult(s[xlen:], x, (pos, pos+xlen))
        raise PegreError(msg, pos)
    return match_literal

Response: Create a PEG function to consume a literal.


Instruction:
Can you implement a function in Python 3 that
creates a PEG function to match a regular expression.

Response:
def regex(r):
    """
    Create a PEG function to match a regular expression.
    """
    if isinstance(r, stringtypes):
        p = re.compile(r)
    else:
        p = r
    msg = 'Expected to match: {}'.format(p.pattern)
    def match_regex(s, grm=None, pos=0):
        m = p.match(s)
        if m is not None:
            start, end = m.span()
            data = m.groupdict() if p.groupindex else m.group()
            return PegreResult(s[m.end():], data, (pos+start, pos+end))
        raise PegreError(msg, pos)
    return match_regex


Instruction:
Write a Python 3 function for
creating a PEG function to match a nonterminal.

Response:
def nonterminal(n):
    """
    Create a PEG function to match a nonterminal.
    """
    def match_nonterminal(s, grm=None, pos=0):
        if grm is None: grm = {}
        expr = grm[n]
        return expr(s, grm, pos)
    return match_nonterminal


Instruction:
Can you generate the documentation for the following Python 3 function
def and_next(e):
    def match_and_next(s, grm=None, pos=0):
        try:
            e(s, grm, pos)
        except PegreError as ex:
            raise PegreError('Positive lookahead failed', pos)
        else:
            return PegreResult(s, Ignore, (pos, pos))
    return match_and_next

Response: Create a PEG function for positive lookahead.


Instruction:
Can you tell what is the following Python 3 function doing
def not_next(e):
    def match_not_next(s, grm=None, pos=0):
        try:
            e(s, grm, pos)
        except PegreError as ex:
            return PegreResult(s, Ignore, (pos, pos))
        else:
            raise PegreError('Negative lookahead failed', pos)
    return match_not_next

Response: Create a PEG function for negative lookahead.


Instruction:
How would you explain what the following Python 3 function does
def sequence(*es):
    def match_sequence(s, grm=None, pos=0):
        data = []
        start = pos
        for e in es:
            s, obj, span = e(s, grm, pos)
            pos = span[1]
            if obj is not Ignore:
                data.append(obj)
        return PegreResult(s, data, (start, pos))
    return match_sequence

Response: Create a PEG function to match a sequence.


Instruction:
Create a Python 3 function for
creating a PEG function to match an ordered choice.

Response:
def choice(*es):
    """
    Create a PEG function to match an ordered choice.
    """
    msg = 'Expected one of: {}'.format(', '.join(map(repr, es)))
    def match_choice(s, grm=None, pos=0):
        errs = []
        for e in es:
            try:
                return e(s, grm, pos)
            except PegreError as ex:
                errs.append((ex.message, ex.position))
        if errs:
            raise PegreChoiceError(errs, pos)
    return match_choice


Instruction:
Write a Python 3 script to
create a PEG function to optionally match an expression.

Response:
def optional(e, default=Ignore):
    """
    Create a PEG function to optionally match an expression.
    """
    def match_optional(s, grm=None, pos=0):
        try:
            return e(s, grm, pos)
        except PegreError:
            return PegreResult(s, default, (pos, pos))
    return match_optional


Instruction:
Given the following Python 3 function, write the documentation
def zero_or_more(e, delimiter=None):
    if delimiter is None:
        delimiter = lambda s, grm, pos: (s, Ignore, (pos, pos))
    def match_zero_or_more(s, grm=None, pos=0):
        start = pos
        try:
            s, obj, span = e(s, grm, pos)
            pos = span[1]
            data = [] if obj is Ignore else [obj]
        except PegreError:
            return PegreResult(s, [], (pos, pos))
        try:
            while True:
                s, obj, span = delimiter(s, grm, pos)
                pos = span[1]
                if obj is not Ignore:
                    data.append(obj)
                s, obj, span = e(s, grm, pos)
                pos = span[1]
                if obj is not Ignore:
                    data.append(obj)
        except PegreError:
            pass
        return PegreResult(s, data, (start, pos))
    return match_zero_or_more

Response: Create a PEG function to match zero or more expressions.


Instruction:
Can you create a Python 3 function that
creates a PEG function to match one or more expressions.

Response:
def one_or_more(e, delimiter=None):
    """
    Create a PEG function to match one or more expressions.

    Args:
        e: the expression to match
        delimiter: an optional expression to match between the
            primary *e* matches.
    """
    if delimiter is None:
        delimiter = lambda s, grm, pos: (s, Ignore, (pos, pos))
    msg = 'Expected one or more of: {}'.format(repr(e))
    def match_one_or_more(s, grm=None, pos=0):
        start = pos
        s, obj, span = e(s, grm, pos)
        pos = span[1]
        data = [] if obj is Ignore else [obj]
        try:
            while True:
                s, obj, span = delimiter(s, grm, pos)
                pos = span[1]
                if obj is not Ignore:
                    data.append(obj)
                s, obj, span = e(s, grm, pos)
                pos = span[1]
                if obj is not Ignore:
                    data.append(obj)
        except PegreError:
            pass
        return PegreResult(s, data, (start, pos))
    return match_one_or_more


Instruction:
Explain what the following Python 3 code does
def merge(base, obj, location=None):
    # pump object to it's location with dummy nodes
    while location:
        axis = location.pop()
        obj = XmrsPathNode(None, None, links={axis: obj})
    if base is None:
        return obj
    _merge(base, obj)
    # if isinstance(base, XmrsPath):
    #     base.calculate_metrics()
    return base

Response: merge two objects into a single object


Instruction:
Make a summary of the following Python 3 code
def _prepare_axes(node, sort_key):
    links = node.links
    o_links = node._overlapping_links
    overlap = {ax2 for ax in links for ax2 in o_links.get(ax, [])}
    axes = []
    for axis in sorted(links.keys(), key=sort_key):
        if axis in overlap: continue
        tgt = links[axis]
        if axis in o_links:
            s, e = axis[0], axis[-1]
            axis = '%s%s%s' % (
                s, '&'.join(a[1:-1] for a in [axis] + o_links[axis]), e
            )
        axes.append((axis, tgt))
    return axes

Response:
Sort axes and combine those that point to the same target and go
    in the same direction.


Instruction:
Write a Python 3 script for
getting the value for a key.

Response:
def get(self, key, default=None):
        """
        Return the value for *key* if it exists, otherwise *default*.
        """
        try:
            val = self[key]
        except KeyError:
            val = default
        return val


Instruction:
Create a Python 3 function for
returning the list of tuples of feature paths and feature values.

Response:
def features(self, expand=False):
        """
        Return the list of tuples of feature paths and feature values.

        Args:
            expand (bool): if `True`, expand all feature paths
        Example:
            >>> fs = FeatureStructure([('A.B', 1), ('A.C', 2)])
            >>> fs.features()
            [('A', <FeatureStructure object at ...>)]
            >>> fs.features(expand=True)
            [('A.B', 1), ('A.C', 2)]
        """
        fs = []
        if self._avm is not None:
            if len(self._feats) == len(self._avm):
                feats = self._feats
            else:
                feats = list(self._avm)
            for feat in feats:
                val = self._avm[feat]
                if isinstance(val, FeatureStructure):
                    if not expand and val._is_notable():
                        fs.append((feat, val))
                    else:
                        for subfeat, subval in val.features(expand=expand):
                            fs.append(('{}.{}'.format(feat, subfeat), subval))
                else:
                    fs.append((feat, val))
        return fs


Instruction:
Write a Python 3 function for
returning the ancestors of the given type.

Response:
def ancestors(self, typename):
        """Return the ancestor types of *typename*."""
        xs = []
        for parent in self._hier[typename][0]:
            xs.append(parent)
            xs.extend(self.ancestors(parent))
        return xs


Instruction:
How would you explain what the following Python 3 function does
def descendants(self, typename):
        xs = []
        for child in self._hier[typename][1]:
            xs.append(child)
            xs.extend(self.descendants(child))
        return xs

Response: Return the descendant types of typename.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def subsumes(self, a, b):
        return a == b or b in self.descendants(a)

Response: Return True if type a subsumes type b.


Instruction:
Can you implement a function in Python 3 that
returns True if type a is compatible with type b.

Response:
def compatible(self, a, b):
        """Return `True` if type *a* is compatible with type *b*."""
        return len(set([a] + self.descendants(a))
                   .intersection([b] + self.descendants(b))) > 0


Instruction:
Can you write a function in Python 3 where it
returns True if Xmrs objects q and g are isomorphic.

Response:
def isomorphic(q, g, check_varprops=True):
    """
    Return `True` if Xmrs objects *q* and *g* are isomorphic.

    Isomorphicity compares the predicates of an Xmrs, the variable
    properties of their predications (if `check_varprops=True`),
    constant arguments, and the argument structure between
    predications. Node IDs and Lnk values are ignored.

    Args:
        q: the left Xmrs to compare
        g: the right Xmrs to compare
        check_varprops: if `True`, make sure variable properties are
            equal for mapped predications
    """

    qdg = _make_digraph(q, check_varprops)
    gdg = _make_digraph(g, check_varprops)
    def nem(qd, gd):  # node-edge-match
        return qd.get('sig') == gd.get('sig')
    return nx.is_isomorphic(qdg, gdg, node_match=nem, edge_match=nem)


Instruction:
Write a Python 3 function that can
check if a given Xmrs q is isomorphic to given Xmrs g.

Response:
def _turbo_isomorphic(q, g, check_varprops=True):
    """
    Query Xmrs q is isomorphic to given Xmrs g if there exists an
    isomorphism (bijection of eps and vars) from q to g.
    """
    # first some quick checks
    if len(q.eps()) != len(g.eps()): return False
    if len(q.variables()) != len(g.variables()): return False
    #if len(a.hcons()) != len(b.hcons()): return False
    try:
        next(_isomorphisms(q, g, check_varprops=check_varprops))
        return True
    except StopIteration:
        return False


Instruction:
How would you code a function in Python 3 to
inspire by Turbo_ISO: http://dl.acm.org/citation.cfm?id=2465300

Response:
def _isomorphisms(q, g, check_varprops=True):
    """
    Inspired by Turbo_ISO: http://dl.acm.org/citation.cfm?id=2465300
    """
    # convert MRSs to be more graph-like, and add some indices
    qig = _IsoGraph(q, varprops=check_varprops)  # qig = q isograph
    gig = _IsoGraph(g, varprops=check_varprops)  # gig = q isograph
    # qsigs, qsigidx = _isomorphism_sigs(q, check_varprops)
    # gsigs, gsigidx = _isomorphism_sigs(g, check_varprops)
    # (it would be nice to not have to do this... maybe later)
    # qadj = _isomorphism_adj(q, qsigidx)
    # gadj = _isomorphism_adj(g, gsigidx)
    # the degree of each node is useful (but can it be combined with adj?)
    # qdeg = _isomorphism_deg(qadj)
    # gdeg = _isomorphism_deg(gadj)

    u_s = _isomorphism_choose_start_q_vertex(qig, gig, subgraph=False)
    q_ = _isomorphism_rewrite_to_NECtree(u_s, qig)
    for v_s in gsigs.get(qsigidx[u_s], []):
        cr = _isomorphism_explore_CR(q_, {v_s}, qig, gig)
        if cr is None:
            continue
        order = _isomorphism_determine_matching_order(q_, cr)
        update_state(M,F,{u_s}, {v_s})
        subraph_search(q, q_, g, order, 1)  # 1="the first query vertex to match"
        restore_state(M, F, {u_s}, {v_s})


Instruction:
Write a Python 3 script for
rewriting the isomorphism to NEC tree

Response:
def _isomorphism_rewrite_to_NECtree(q_s, qgraph):
    """
    Neighborhood Equivalence Class tree (see Turbo_ISO paper)
    """
    qadj = qgraph.adj
    adjsets = lambda x: set(chain.from_iterable(qadj[x].values()))
    t = ([q_s], [])  # (NEC_set, children)
    visited = {q_s}
    vcur, vnext = [t], []
    while vcur:
        for (nec, children) in vcur:
            c = defaultdict(list)
            for u in nec:
                for sig, adjlist in qadj[u].items():
                    c[sig].extend(x for x, _, _ in adjlist if x not in visited)
            for sig, c_adjlist in c.items():
                visited.update(c_adjlist)
                # these are already grouped by label; now group by adjacents
                for key, grp in groupby(c_adjlist, key=adjsets):
                    grp = list(grp)
                    if len(grp) > 1:
                        children.append((list(grp), []))
                    else:
                        # NOTE: the paper says to look for mergeable things,
                        # but I don't know what else to merge by.
                        children.append((list(grp), []))
            vnext.extend(children)
        vcur, vnext = vnext, []
    return t


Instruction:
Write a Python 3 script for
returning True if two Xmrs objects are isomorphic.

Response:
def _node_isomorphic(a, b, check_varprops=True):
    """
    Two Xmrs objects are isomorphic if they have the same structure as
    determined by variable linkages between preds.
    """
    # first some quick checks
    a_var_refs = sorted(len(vd['refs']) for vd in a._vars.values())
    b_var_refs = sorted(len(vd['refs']) for vd in b._vars.values())
    if a_var_refs != b_var_refs:
        return False
    print()

    # these signature: [node] indices are meant to avoid unnecessary
    # comparisons; they also take care of "semantic feasibility"
    # constraints (comparing node values and properties). All that's
    # left is the "syntactic feasibility", or node-edge shapes.
    # nodedicts are {sig: [(id, edges), ...], ...}
    a_nd = _node_isomorphic_build_nodedict(a, check_varprops)
    #print('a', a_nd)
    b_nd = _node_isomorphic_build_nodedict(b, check_varprops)
    #print('b', b_nd)
    #return

    a_sigs = {}  # for node -> sig mapping
    # don't recurse when things are unique
    agenda = []
    isomap = {}
    for sig, a_pairs in sorted(a_nd.items(), key=lambda x: len(x[1])):
        b_pairs = b_nd.get(sig, [])
        if len(a_pairs) != len(b_pairs):
            return False
        if len(a_pairs) == 1:
            a_, a_edges = a_pairs[0]
            b_, b_edges = b_pairs[0]
            if len(a_edges) != len(b_edges):
                return False
            a_sigs[a_] = sig
            isomap[a_] = b_
            for edge, a_tgt in a_edges.items():
                if edge not in b_edges:
                    return False
                isomap[a_tgt] = b_edges[edge]
        else:
            for a_, ed in a_pairs:
                a_sigs[a_] = sig
                agenda.append((a_, sig, ed))
    #print(agenda)
    #return
    isomaps = _node_isomorphic(agenda, a_sigs, b_nd, isomap, {})
    # for sig, a_candidates in sorted(a_nodes.items(), key=lambda x: len(x[1])):
    #     b_candidates = b_nodes.get(sig, [])
    #     if len(a_candidates) != len(b_candidates): return False
    #     candidates.append((a_candidates, b_candidates))
    #
    # nodemaps = _isomorphic(a, b, candidates, {})
    try:
        next(isomaps)
        return True
    except StopIteration:
        return False


Instruction:
Write a Python 3 function for
returning True if two Xmrs objects are isomorphic.

Response:
def _var_isomorphic(a, b, check_varprops=True):
    """
    Two Xmrs objects are isomorphic if they have the same structure as
    determined by variable linkages between preds.
    """
    # first some quick checks
    if len(a.eps()) != len(b.eps()): return False
    if len(a.variables()) != len(b.variables()): return False
    #if len(a.hcons()) != len(b.hcons()): return False

    # pre-populate varmap; first top variables
    varmap = {}
    for pair in [(a.top, b.top), (a.index, b.index), (a.xarg, b.xarg)]:
        if pair != (None, None):
            v1, v2 = pair
            if None in pair:
                return False
            if check_varprops and a.properties(v1) != b.properties(v2):
                return False
            varmap[v1] = v2

    # find permutations of variables, grouped by those that share the
    # same signature.

    a_sigs = defaultdict(list)
    for var, vd in a._vars.items():
        if var not in varmap:
            var_sig = _isomorphic_var_signature(vd, a, check_varprops)
            a_sigs[var_sig].append(var)
    b_sigs = defaultdict(list)
    tgtmapped = set(varmap.values())
    for var, vd in b._vars.items():
        if var not in tgtmapped:
            var_sig = _isomorphic_var_signature(vd, b, check_varprops)
            b_sigs[var_sig].append(var)

    candidates = []
    for sig, a_vars in sorted(a_sigs.items(), key=lambda x: len(x[1])):
        b_vars = b_sigs.get(sig, [])
        if len(a_vars) != len(b_vars):
            return False
        print(sig, a_vars, b_vars)
        candidates.append((a_vars, b_vars))

    varmaps = _var_isomorphic(a, b, candidates, varmap)

    # double check HCONS (it's hard to do with var signatures)
    for vm in varmaps:
        if all(vm[lo] == b._hcons.get(vm[hi], (None, None, None))[2]
               for hi, _, lo in a.hcons()):
            return True
    return False


Instruction:
Implement a Python 3 function for
comparing two bags of Xmrs objects returning a triple of the unique in test shared and unique in gold.

Response:
def compare_bags(testbag, goldbag, count_only=True):
    """
    Compare two bags of Xmrs objects, returning a triple of
    (unique in test, shared, unique in gold).

    Args:
        testbag: An iterable of Xmrs objects to test.
        goldbag: An iterable of Xmrs objects to compare against.
        count_only: If True, the returned triple will only have the
            counts of each; if False, a list of Xmrs objects will be
            returned for each (using the ones from testbag for the
            shared set)
    Returns:
        A triple of (unique in test, shared, unique in gold), where
        each of the three items is an integer count if the count_only
        parameter is True, or a list of Xmrs objects otherwise.
    """
    gold_remaining = list(goldbag)
    test_unique = []
    shared = []
    for test in testbag:
        gold_match = None
        for gold in gold_remaining:
            if isomorphic(test, gold):
                gold_match = gold
                break
        if gold_match is not None:
            gold_remaining.remove(gold_match)
            shared.append(test)
        else:
            test_unique.append(test)
    if count_only:
        return (len(test_unique), len(shared), len(gold_remaining))
    else:
        return (test_unique, shared, gold_remaining)


Instruction:
Create a Python 3 function for
querying the specified TSQL query string on the specified testsuite.

Response:
def query(query, ts, **kwargs):
    """
    Perform *query* on the testsuite *ts*.

    Note: currently only 'select' queries are supported.

    Args:
        query (str): TSQL query string
        ts (:class:`delphin.itsdb.TestSuite`): testsuite to query over
        kwargs: keyword arguments passed to the more specific query
            function (e.g., :func:`select`)
    Example:
        >>> list(tsql.query('select i-id where i-length < 4', ts))
        [[142], [1061]]
    """
    queryobj = _parse_query(query)

    if queryobj['querytype'] in ('select', 'retrieve'):
        return _select(
            queryobj['projection'],
            queryobj['tables'],
            queryobj['where'],
            ts,
            mode=kwargs.get('mode', 'list'),
            cast=kwargs.get('cast', True))
    else:
        # not really a syntax error; replace with TSQLError or something
        # when the proper exception class exists
        raise TSQLSyntaxError(queryobj['querytype'] +
                              ' queries are not supported')


Instruction:
How would you explain what the following Python 3 function does
def select(query, ts, mode='list', cast=True):
    queryobj = _parse_select(query)
    return _select(
        queryobj['projection'],
        queryobj['tables'],
        queryobj['where'],
        ts,
        mode,
        cast)

Response: Perform the TSQL select query on the specified testsuite.


Instruction:
How would you code a function in Python 3 to
use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned. Notes1. This method will not work if an outgoing webhook is set up.2. In order to avoid getting duplicate updates, recalculate offset after each server response. https://core.telegram.org/bots/api#getupdates Optional keyword parameters: :param offset: Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will forgotten. :type offset: int :param limit: Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100. :type limit: int :param timeout: Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only. :type timeout: int :param allowed_updates: List the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used.Please note that this parameter doesn't affect updates created before the call to the getUpdates, so unwanted updates may be received for a short period of time. :type allowed_updates: list of str|unicode Returns: :return: An Array of Update objects is returned :rtype: list of pytgbot.api_types.receivable.updates.Update

Response:
def get_updates(self, offset=None, limit=None, timeout=None, allowed_updates=None):
        """
        Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.

        Notes1. This method will not work if an outgoing webhook is set up.2. In order to avoid getting duplicate updates, recalculate offset after each server response.

        https://core.telegram.org/bots/api#getupdates

        Optional keyword parameters:

        :param offset: Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue. All previous updates will forgotten.
        :type  offset: int

        :param limit: Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100.
        :type  limit: int

        :param timeout: Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only.
        :type  timeout: int

        :param allowed_updates: List the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used.Please note that this parameter doesn't affect updates created before the call to the getUpdates, so unwanted updates may be received for a short period of time.
        :type  allowed_updates: list of str|unicode

        Returns:

        :return: An Array of Update objects is returned
        :rtype:  list of pytgbot.api_types.receivable.updates.Update
        """
        assert_type_or_raise(offset, None, int, parameter_name="offset")

        assert_type_or_raise(limit, None, int, parameter_name="limit")

        assert_type_or_raise(timeout, None, int, parameter_name="timeout")

        assert_type_or_raise(allowed_updates, None, list, parameter_name="allowed_updates")

        result = self.do("getUpdates", offset=offset, limit=limit, timeout=timeout, allowed_updates=allowed_updates)
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            from pytgbot.api_types.receivable.updates import Update
            try:
                return Update.from_array_list(result, list_level=1)
            except TgApiParseException:
                logger.debug("Failed parsing as api_type Update", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result


Instruction:
Write a Python 3 function that can
use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success. If you'd like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. https://www.example.com/<token>. Since nobody else knows your bot‘s token, you can be pretty sure it’s us. Notes1. You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up.2. To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please upload as InputFile, sending a String will not work.3. Ports currently supported for Webhooks: 443, 80, 88, 8443. NEW! If you're having any trouble setting up webhooks, please check out this amazing guide to Webhooks. https://core.telegram.org/bots/api#setwebhook Parameters: :param url: HTTPS url to send updates to. Use an empty string to remove webhook integration :type url: str|unicode Optional keyword parameters: :param certificate: Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details. :type certificate: pytgbot.api_types.sendable.files.InputFile :param max_connections: Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot‘s server, and higher values to increase your bot’s throughput. :type max_connections: int :param allowed_updates: List the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used.Please note that this parameter doesn't affect updates created before the call to the setWebhook, so unwanted updates may be received for a short period of time. :type allowed_updates: list of str|unicode Returns: :return: Returns True on success :rtype: bool

Response:
def set_webhook(self, url, certificate=None, max_connections=None, allowed_updates=None):
        """
        Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns True on success.
        If you'd like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. https://www.example.com/<token>. Since nobody else knows your bot‘s token, you can be pretty sure it’s us.

        Notes1. You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up.2. To use a self-signed certificate, you need to upload your public key certificate using certificate parameter. Please upload as InputFile, sending a String will not work.3. Ports currently supported for Webhooks: 443, 80, 88, 8443.
        NEW! If you're having any trouble setting up webhooks, please check out this amazing guide to Webhooks.

        https://core.telegram.org/bots/api#setwebhook

        Parameters:

        :param url: HTTPS url to send updates to. Use an empty string to remove webhook integration
        :type  url: str|unicode

        Optional keyword parameters:

        :param certificate: Upload your public key certificate so that the root certificate in use can be checked. See our self-signed guide for details.
        :type  certificate: pytgbot.api_types.sendable.files.InputFile

        :param max_connections: Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40. Use lower values to limit the load on your bot‘s server, and higher values to increase your bot’s throughput.
        :type  max_connections: int

        :param allowed_updates: List the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used.Please note that this parameter doesn't affect updates created before the call to the setWebhook, so unwanted updates may be received for a short period of time.
        :type  allowed_updates: list of str|unicode

        Returns:

        :return: Returns True on success
        :rtype:  bool
        """
        from pytgbot.api_types.sendable.files import InputFile

        assert_type_or_raise(url, unicode_type, parameter_name="url")

        assert_type_or_raise(certificate, None, InputFile, parameter_name="certificate")

        assert_type_or_raise(max_connections, None, int, parameter_name="max_connections")

        assert_type_or_raise(allowed_updates, None, list, parameter_name="allowed_updates")

        result = self.do("setWebhook", url=url, certificate=certificate, max_connections=max_connections, allowed_updates=allowed_updates)
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            try:
                return from_array_list(bool, result, list_level=0, is_builtin=True)
            except TgApiParseException:
                logger.debug("Failed parsing as primitive bool", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result


Instruction:
Create a Python 3 function for
using this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters. https://core.telegram.org/bots/api#deletewebhook Returns: :return: Returns True on success :rtype: bool

Response:
def delete_webhook(self, ):
        """
        Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters.

        https://core.telegram.org/bots/api#deletewebhook

        Returns:

        :return: Returns True on success
        :rtype:  bool
        """

        result = self.do("deleteWebhook", )
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            try:
                return from_array_list(bool, result, list_level=0, is_builtin=True)
            except TgApiParseException:
                logger.debug("Failed parsing as primitive bool", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result


Instruction:
Implement a function in Python 3 to
use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty. https://core.telegram.org/bots/api#getwebhookinfo Returns: :return: On success, returns a WebhookInfo object :rtype: pytgbot.api_types.receivable.updates.WebhookInfo

Response:
def get_webhook_info(self, ):
        """
        Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.

        https://core.telegram.org/bots/api#getwebhookinfo

        Returns:

        :return: On success, returns a WebhookInfo object
        :rtype:  pytgbot.api_types.receivable.updates.WebhookInfo
        """

        result = self.do("getWebhookInfo", )
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            from pytgbot.api_types.receivable.updates import WebhookInfo
            try:
                return WebhookInfo.from_array(result)
            except TgApiParseException:
                logger.debug("Failed parsing as api_type WebhookInfo", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result


Instruction:
Given the following Python 3 function, write the documentation
def send_photo(self, chat_id, photo, caption=None, parse_mode=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
        from pytgbot.api_types.sendable.files import InputFile
        from pytgbot.api_types.sendable.reply_markup import ForceReply
        from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup
        from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardMarkup
        from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardRemove

        assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")

        assert_type_or_raise(photo, (InputFile, unicode_type), parameter_name="photo")

        assert_type_or_raise(caption, None, unicode_type, parameter_name="caption")

        assert_type_or_raise(parse_mode, None, unicode_type, parameter_name="parse_mode")

        assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification")

        assert_type_or_raise(reply_to_message_id, None, int, parameter_name="reply_to_message_id")

        assert_type_or_raise(reply_markup, None, (InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply), parameter_name="reply_markup")

        result = self.do("sendPhoto", chat_id=chat_id, photo=photo, caption=caption, parse_mode=parse_mode, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup)
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            from pytgbot.api_types.receivable.updates import Message
            try:
                return Message.from_array(result)
            except TgApiParseException:
                logger.debug("Failed parsing as api_type Message", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result

Response: Use this method to send photos. You must be an administrator in the chat for this to work and must have the appropriate admin rights.


Instruction:
Implement a Python 3 function for
using this method to send a group of photos or videos as an album. You must be an administrator in the chat for this to work and must have the appropriate admin rights. You must have the appropriate admin rights. You must have the appropriate admin rights.

Response:
def send_media_group(self, chat_id, media, disable_notification=None, reply_to_message_id=None):
        """
        Use this method to send a group of photos or videos as an album. On success, an array of the sent Messages is returned.

        https://core.telegram.org/bots/api#sendmediagroup

        Parameters:

        :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
        :type  chat_id: int | str|unicode

        :param media: A JSON-serialized array describing photos and videos to be sent, must include 2–10 items
        :type  media: list of pytgbot.api_types.sendable.input_media.InputMediaPhoto | list of pytgbot.api_types.sendable.input_media.InputMediaVideo

        Optional keyword parameters:

        :param disable_notification: Sends the messages silently. Users will receive a notification with no sound.
        :type  disable_notification: bool

        :param reply_to_message_id: If the messages are a reply, ID of the original message
        :type  reply_to_message_id: int

        Returns:

        :return: On success, an array of the sent Messages is returned
        :rtype:  list of pytgbot.api_types.receivable.updates.Message
        """
        from pytgbot.api_types.sendable.input_media import InputMediaPhoto
        from pytgbot.api_types.sendable.input_media import InputMediaVideo

        assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")

        assert_type_or_raise(media, (list, list), parameter_name="media")

        assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification")

        assert_type_or_raise(reply_to_message_id, None, int, parameter_name="reply_to_message_id")

        result = self.do("sendMediaGroup", chat_id=chat_id, media=media, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id)
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            from pytgbot.api_types.receivable.updates import Message
            try:
                return Message.from_array_list(result, list_level=1)
            except TgApiParseException:
                logger.debug("Failed parsing as api_type Message", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result


Instruction:
Here you have a function in Python 3, explain what it does
def send_location(self, chat_id, latitude, longitude, live_period=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
        from pytgbot.api_types.sendable.reply_markup import ForceReply
        from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup
        from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardMarkup
        from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardRemove

        assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")

        assert_type_or_raise(latitude, float, parameter_name="latitude")

        assert_type_or_raise(longitude, float, parameter_name="longitude")

        assert_type_or_raise(live_period, None, int, parameter_name="live_period")

        assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification")

        assert_type_or_raise(reply_to_message_id, None, int, parameter_name="reply_to_message_id")

        assert_type_or_raise(reply_markup, None, (InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply), parameter_name="reply_markup")

        result = self.do("sendLocation", chat_id=chat_id, latitude=latitude, longitude=longitude, live_period=live_period, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup)
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            from pytgbot.api_types.receivable.updates import Message
            try:
                return Message.from_array(result)
            except TgApiParseException:
                logger.debug("Failed parsing as api_type Message", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result

Response: Use this method to send a location on the map.


Instruction:
Implement a Python 3 function for
using this method to send phone contacts. You must be an administrator in the chat for this to work and must have the appropriate admin rights.

Response:
def send_contact(self, chat_id, phone_number, first_name, last_name=None, vcard=None, disable_notification=None, reply_to_message_id=None, reply_markup=None):
        """
        Use this method to send phone contacts. On success, the sent Message is returned.

        https://core.telegram.org/bots/api#sendcontact

        Parameters:

        :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
        :type  chat_id: int | str|unicode

        :param phone_number: Contact's phone number
        :type  phone_number: str|unicode

        :param first_name: Contact's first name
        :type  first_name: str|unicode

        Optional keyword parameters:

        :param last_name: Contact's last name
        :type  last_name: str|unicode

        :param vcard: Additional data about the contact in the form of a vCard, 0-2048 bytes
        :type  vcard: str|unicode

        :param disable_notification: Sends the message silently. Users will receive a notification with no sound.
        :type  disable_notification: bool

        :param reply_to_message_id: If the message is a reply, ID of the original message
        :type  reply_to_message_id: int

        :param reply_markup: Additional interface options. A JSON-serialized object for an inline keyboard, custom reply keyboard, instructions to remove keyboard or to force a reply from the user.
        :type  reply_markup: pytgbot.api_types.sendable.reply_markup.InlineKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardMarkup | pytgbot.api_types.sendable.reply_markup.ReplyKeyboardRemove | pytgbot.api_types.sendable.reply_markup.ForceReply

        Returns:

        :return: On success, the sent Message is returned
        :rtype:  pytgbot.api_types.receivable.updates.Message
        """
        from pytgbot.api_types.sendable.reply_markup import ForceReply
        from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup
        from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardMarkup
        from pytgbot.api_types.sendable.reply_markup import ReplyKeyboardRemove

        assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")

        assert_type_or_raise(phone_number, unicode_type, parameter_name="phone_number")

        assert_type_or_raise(first_name, unicode_type, parameter_name="first_name")

        assert_type_or_raise(last_name, None, unicode_type, parameter_name="last_name")

        assert_type_or_raise(vcard, None, unicode_type, parameter_name="vcard")

        assert_type_or_raise(disable_notification, None, bool, parameter_name="disable_notification")

        assert_type_or_raise(reply_to_message_id, None, int, parameter_name="reply_to_message_id")

        assert_type_or_raise(reply_markup, None, (InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply), parameter_name="reply_markup")

        result = self.do("sendContact", chat_id=chat_id, phone_number=phone_number, first_name=first_name, last_name=last_name, vcard=vcard, disable_notification=disable_notification, reply_to_message_id=reply_to_message_id, reply_markup=reply_markup)
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            from pytgbot.api_types.receivable.updates import Message
            try:
                return Message.from_array(result)
            except TgApiParseException:
                logger.debug("Failed parsing as api_type Message", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result


Instruction:
Can you generate the documentation for the following Python 3 function
def get_user_profile_photos(self, user_id, offset=None, limit=None):
        assert_type_or_raise(user_id, int, parameter_name="user_id")

        assert_type_or_raise(offset, None, int, parameter_name="offset")

        assert_type_or_raise(limit, None, int, parameter_name="limit")

        result = self.do("getUserProfilePhotos", user_id=user_id, offset=offset, limit=limit)
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            from pytgbot.api_types.receivable.media import UserProfilePhotos
            try:
                return UserProfilePhotos.from_array(result)
            except TgApiParseException:
                logger.debug("Failed parsing as api_type UserProfilePhotos", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result

Response: This method returns a list of profile pictures for a user.


Instruction:
Implement a Python 3 function for
using this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again. Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received. https://core.telegram.org/bots/api#getfile Parameters: :param file_id: File identifier to get info about :type file_id: str|unicode Returns: :return: On success, a File object is returned :rtype: pytgbot.api_types.receivable.media.File

Response:
def get_file(self, file_id):
        """
        Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again.
        Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received.

        https://core.telegram.org/bots/api#getfile

        Parameters:

        :param file_id: File identifier to get info about
        :type  file_id: str|unicode

        Returns:

        :return: On success, a File object is returned
        :rtype:  pytgbot.api_types.receivable.media.File
        """
        assert_type_or_raise(file_id, unicode_type, parameter_name="file_id")

        result = self.do("getFile", file_id=file_id)
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            from pytgbot.api_types.receivable.media import File
            try:
                return File.from_array(result)
            except TgApiParseException:
                logger.debug("Failed parsing as api_type File", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result


Instruction:
Given the following Python 3 function, write the documentation
def restrict_chat_member(self, chat_id, user_id, until_date=None, can_send_messages=None, can_send_media_messages=None, can_send_other_messages=None, can_add_web_page_previews=None):
        assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")

        assert_type_or_raise(user_id, int, parameter_name="user_id")

        assert_type_or_raise(until_date, None, int, parameter_name="until_date")

        assert_type_or_raise(can_send_messages, None, bool, parameter_name="can_send_messages")

        assert_type_or_raise(can_send_media_messages, None, bool, parameter_name="can_send_media_messages")

        assert_type_or_raise(can_send_other_messages, None, bool, parameter_name="can_send_other_messages")

        assert_type_or_raise(can_add_web_page_previews, None, bool, parameter_name="can_add_web_page_previews")

        result = self.do("restrictChatMember", chat_id=chat_id, user_id=user_id, until_date=until_date, can_send_messages=can_send_messages, can_send_media_messages=can_send_media_messages, can_send_other_messages=can_send_other_messages, can_add_web_page_previews=can_add_web_page_previews)
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            try:
                return from_array_list(bool, result, list_level=0, is_builtin=True)
            except TgApiParseException:
                logger.debug("Failed parsing as primitive bool", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result

Response: Use this method to restrict a user in a supergroup.


Instruction:
Create a Python 3 function for
promoting a user in a supergroup or a channel.

Response:
def promote_chat_member(self, chat_id, user_id, can_change_info=None, can_post_messages=None, can_edit_messages=None, can_delete_messages=None, can_invite_users=None, can_restrict_members=None, can_pin_messages=None, can_promote_members=None):
        """
        Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user. Returns True on success.

        https://core.telegram.org/bots/api#promotechatmember

        Parameters:

        :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
        :type  chat_id: int | str|unicode

        :param user_id: Unique identifier of the target user
        :type  user_id: int

        Optional keyword parameters:

        :param can_change_info: Pass True, if the administrator can change chat title, photo and other settings
        :type  can_change_info: bool

        :param can_post_messages: Pass True, if the administrator can create channel posts, channels only
        :type  can_post_messages: bool

        :param can_edit_messages: Pass True, if the administrator can edit messages of other users and can pin messages, channels only
        :type  can_edit_messages: bool

        :param can_delete_messages: Pass True, if the administrator can delete messages of other users
        :type  can_delete_messages: bool

        :param can_invite_users: Pass True, if the administrator can invite new users to the chat
        :type  can_invite_users: bool

        :param can_restrict_members: Pass True, if the administrator can restrict, ban or unban chat members
        :type  can_restrict_members: bool

        :param can_pin_messages: Pass True, if the administrator can pin messages, supergroups only
        :type  can_pin_messages: bool

        :param can_promote_members: Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by him)
        :type  can_promote_members: bool

        Returns:

        :return: Returns True on success
        :rtype:  bool
        """
        assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")

        assert_type_or_raise(user_id, int, parameter_name="user_id")

        assert_type_or_raise(can_change_info, None, bool, parameter_name="can_change_info")

        assert_type_or_raise(can_post_messages, None, bool, parameter_name="can_post_messages")

        assert_type_or_raise(can_edit_messages, None, bool, parameter_name="can_edit_messages")

        assert_type_or_raise(can_delete_messages, None, bool, parameter_name="can_delete_messages")

        assert_type_or_raise(can_invite_users, None, bool, parameter_name="can_invite_users")

        assert_type_or_raise(can_restrict_members, None, bool, parameter_name="can_restrict_members")

        assert_type_or_raise(can_pin_messages, None, bool, parameter_name="can_pin_messages")

        assert_type_or_raise(can_promote_members, None, bool, parameter_name="can_promote_members")

        result = self.do("promoteChatMember", chat_id=chat_id, user_id=user_id, can_change_info=can_change_info, can_post_messages=can_post_messages, can_edit_messages=can_edit_messages, can_delete_messages=can_delete_messages, can_invite_users=can_invite_users, can_restrict_members=can_restrict_members, can_pin_messages=can_pin_messages, can_promote_members=can_promote_members)
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            try:
                return from_array_list(bool, result, list_level=0, is_builtin=True)
            except TgApiParseException:
                logger.debug("Failed parsing as primitive bool", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result


Instruction:
Implement a Python 3 function for
using this method to set a new profile photo for a chat. Photos can t be changed for private chats.

Response:
def set_chat_photo(self, chat_id, photo):
        """
        Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.

        Note: In regular groups (non-supergroups), this method will only work if the ‘All Members Are Admins’ setting is off in the target group.

        https://core.telegram.org/bots/api#setchatphoto

        Parameters:

        :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername)
        :type  chat_id: int | str|unicode

        :param photo: New chat photo, uploaded using multipart/form-data
        :type  photo: pytgbot.api_types.sendable.files.InputFile

        Returns:

        :return: Returns True on success
        :rtype:  bool
        """
        from pytgbot.api_types.sendable.files import InputFile

        assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")

        assert_type_or_raise(photo, InputFile, parameter_name="photo")

        result = self.do("setChatPhoto", chat_id=chat_id, photo=photo)
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            try:
                return from_array_list(bool, result, list_level=0, is_builtin=True)
            except TgApiParseException:
                logger.debug("Failed parsing as primitive bool", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result


Instruction:
Create a Python 3 function to
use this method to get up to date information about a chat.

Response:
def get_chat(self, chat_id):
        """
        Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.

        https://core.telegram.org/bots/api#getchat

        Parameters:

        :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
        :type  chat_id: int | str|unicode

        Returns:

        :return: Returns a Chat object on success
        :rtype:  pytgbot.api_types.receivable.peer.Chat
        """
        assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")

        result = self.do("getChat", chat_id=chat_id)
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            from pytgbot.api_types.receivable.peer import Chat
            try:
                return Chat.from_array(result)
            except TgApiParseException:
                logger.debug("Failed parsing as api_type Chat", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result


Instruction:
How would you explain what the following Python 3 function does
def set_chat_sticker_set(self, chat_id, sticker_set_name):
        assert_type_or_raise(chat_id, (int, unicode_type), parameter_name="chat_id")

        assert_type_or_raise(sticker_set_name, unicode_type, parameter_name="sticker_set_name")

        result = self.do("setChatStickerSet", chat_id=chat_id, sticker_set_name=sticker_set_name)
        if self.return_python_objects:
            logger.debug("Trying to parse {data}".format(data=repr(result)))
            try:
                return from_array_list(bool, result, list_level=0, is_builtin=True)
            except TgApiParseException:
                logger.debug("Failed parsing as primitive bool", exc_info=True)
            # end try
            # no valid parsing so far
            raise TgApiParseException("Could not parse result.")  # See debug log for details!
        # end if return_python_objects
        return result

Response: Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.