Instruction:
Create a Python 3 function to
handle the return call from the api and return a data and meta_data_object object. It raises a ValueError on problems

Response:
def _handle_api_call(self, url):
        """ Handle the return call from the  api and return a data and meta_data
        object. It raises a ValueError on problems

        Keyword Arguments:
            url:  The url of the service
            data_key:  The key for getting the data from the jso object
            meta_data_key:  The key for getting the meta data information out
            of the json object
        """
        response = requests.get(url, proxies=self.proxy)
        if 'json' in self.output_format.lower() or 'pandas' in \
                self.output_format.lower():
            json_response = response.json()
            if "Error Message" in json_response:
                raise ValueError(json_response["Error Message"])
            elif "Information" in json_response and self.treat_info_as_error:
                raise ValueError(json_response["Information"])
            elif "Note" in json_response and self.treat_info_as_error:
                raise ValueError(json_response["Note"])
            return json_response
        else:
            csv_response = csv.reader(response.text.splitlines())
            if not csv_response:
                raise ValueError(
                    'Error getting data from the api, no return was given.')
            return csv_response


Instruction:
Write a Python 3 function that can
return the moving average convergence/divergence time series in two json objects as data and meta_data. It raises ValueError when problems arise Keyword Arguments: symbol: the symbol for the equity we want to get its data interval: time interval between two conscutive values, supported values are '1min', '5min', '15min', '30min', '60min', 'daily', 'weekly', 'monthly' (default 'daily' series_type: The desired price type in the time series. Four types are supported: 'close', 'open', 'high', 'low' (default 'close') fastperiod: Positive integers are accepted (default=None) slowperiod: Positive integers are accepted (default=None) signalperiod: Positive integers are accepted (default=None)

Response:
def get_macd(self, symbol, interval='daily', series_type='close',
                 fastperiod=None, slowperiod=None, signalperiod=None):
        """ Return the moving average convergence/divergence time series in two
        json objects as data and meta_data. It raises ValueError when problems
        arise

        Keyword Arguments:
            symbol:  the symbol for the equity we want to get its data
            interval:  time interval between two conscutive values,
                supported values are '1min', '5min', '15min', '30min', '60min', 'daily',
                'weekly', 'monthly' (default 'daily'
            series_type:  The desired price type in the time series. Four types
                are supported: 'close', 'open', 'high', 'low' (default 'close')
            fastperiod:  Positive integers are accepted (default=None)
            slowperiod:  Positive integers are accepted (default=None)
            signalperiod:  Positive integers are accepted (default=None)
        """
        _FUNCTION_KEY = "MACD"
        return _FUNCTION_KEY, 'Technical Analysis: MACD', 'Meta Data'


Instruction:
Make a summary of the following Python 3 code
def get_macdext(self, symbol, interval='daily', series_type='close',
                    fastperiod=None, slowperiod=None, signalperiod=None, fastmatype=None,
                    slowmatype=None, signalmatype=None):
        """ Return the moving average convergence/divergence time series in two
        json objects as data and meta_data. It raises ValueError when problems
        arise

        Keyword Arguments:
            symbol:  the symbol for the equity we want to get its data
            interval:  time interval between two conscutive values,
                supported values are '1min', '5min', '15min', '30min', '60min', 'daily',
                'weekly', 'monthly' (default 'daily')
            series_type:  The desired price type in the time series. Four types
                are supported: 'close', 'open', 'high', 'low' (default 'close')
            fastperiod:  Positive integers are accepted (default=None)
            slowperiod:  Positive integers are accepted (default=None)
            signalperiod:  Positive integers are accepted (default=None)
            fastmatype:  Moving average type for the faster moving average.
                By default, fastmatype=0. Integers 0 - 8 are accepted
                (check  down the mappings) or the string containing the math type can
                also be used.
            slowmatype:  Moving average type for the slower moving average.
                By default, slowmatype=0. Integers 0 - 8 are accepted
                (check down the mappings) or the string containing the math type can
                also be used.
            signalmatype:  Moving average type for the signal moving average.
                By default, signalmatype=0. Integers 0 - 8 are accepted
                (check down the mappings) or the string containing the math type can
                also be used.

                * 0 = Simple Moving Average (SMA),
                * 1 = Exponential Moving Average (EMA),
                * 2 = Weighted Moving Average (WMA),
                * 3 = Double Exponential Moving Average (DEMA),
                * 4 = Triple Exponential Moving Average (TEMA),
                * 5 = Triangular Moving Average (TRIMA),
                * 6 = T3 Moving Average,
                * 7 = Kaufman Adaptive Moving Average (KAMA),
                * 8 = MESA Adaptive Moving Average (MAMA)
        """
        _FUNCTION_KEY = "MACDEXT"
        return _FUNCTION_KEY, 'Technical Analysis: MACDEXT', 'Meta Data'

Response: This function returns the convergence or divergence time series in two - tuple json objects as data and meta_data. It raises ValueError when problems are encountered.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_stoch(self, symbol, interval='daily', fastkperiod=None,
                  slowkperiod=None, slowdperiod=None, slowkmatype=None, slowdmatype=None):
        """ Return the stochatic oscillator values in two
        json objects as data and meta_data. It raises ValueError when problems
        arise

        Keyword Arguments:
            symbol:  the symbol for the equity we want to get its data
            interval:  time interval between two conscutive values,
                supported values are '1min', '5min', '15min', '30min', '60min', 'daily',
                'weekly', 'monthly' (default 'daily')
            fastkperiod:  The time period of the fastk moving average. Positive
                integers are accepted (default=None)
            slowkperiod:  The time period of the slowk moving average. Positive
                integers are accepted (default=None)
            slowdperiod: The time period of the slowd moving average. Positive
                integers are accepted (default=None)
            slowkmatype:  Moving average type for the slowk moving average.
                By default, fastmatype=0. Integers 0 - 8 are accepted
                (check  down the mappings) or the string containing the math type can
                also be used.
            slowdmatype:  Moving average type for the slowd moving average.
                By default, slowmatype=0. Integers 0 - 8 are accepted
                (check down the mappings) or the string containing the math type can
                also be used.

                * 0 = Simple Moving Average (SMA),
                * 1 = Exponential Moving Average (EMA),
                * 2 = Weighted Moving Average (WMA),
                * 3 = Double Exponential Moving Average (DEMA),
                * 4 = Triple Exponential Moving Average (TEMA),
                * 5 = Triangular Moving Average (TRIMA),
                * 6 = T3 Moving Average,
                * 7 = Kaufman Adaptive Moving Average (KAMA),
                * 8 = MESA Adaptive Moving Average (MAMA)
        """
        _FUNCTION_KEY = "STOCH"
        return _FUNCTION_KEY, 'Technical Analysis: STOCH', 'Meta Data'

Response: Returns the stochatic oscillator values in two - tuple json objects as data and meta_data.


Instruction:
Can you tell what is the following Python 3 function doing
def get_stochrsi(self, symbol, interval='daily', time_period=20,
                     series_type='close', fastkperiod=None, fastdperiod=None, fastdmatype=None):
        """ Return the stochatic relative strength index in two
        json objects as data and meta_data. It raises ValueError when problems
        arise

        Keyword Arguments:
            symbol:  the symbol for the equity we want to get its data
            interval:  time interval between two conscutive values,
                supported values are '1min', '5min', '15min', '30min', '60min', 'daily',
                'weekly', 'monthly' (default 'daily')
            time_period:  How many data points to average (default 20)
            series_type:  The desired price type in the time series. Four types
                are supported: 'close', 'open', 'high', 'low' (default 'close')
            fastkperiod:  The time period of the fastk moving average. Positive
                integers are accepted (default=None)
            fastdperiod:  The time period of the fastd moving average. Positive
                integers are accepted (default=None)
            fastdmatype:  Moving average type for the fastdmatype moving average.
                By default, fastmatype=0. Integers 0 - 8 are accepted
                (check  down the mappings) or the string containing the math type can
                also be used.

                * 0 = Simple Moving Average (SMA),
                * 1 = Exponential Moving Average (EMA),
                * 2 = Weighted Moving Average (WMA),
                * 3 = Double Exponential Moving Average (DEMA),
                * 4 = Triple Exponential Moving Average (TEMA),
                * 5 = Triangular Moving Average (TRIMA),
                * 6 = T3 Moving Average,
                * 7 = Kaufman Adaptive Moving Average (KAMA),
                * 8 = MESA Adaptive Moving Average (MAMA)
        """
        _FUNCTION_KEY = "STOCHRSI"
        return _FUNCTION_KEY, 'Technical Analysis: STOCHRSI', 'Meta Data'

Response: Return the stochatic relative strength index in json objects as data and meta_data.


Instruction:
Can you create a Python 3 function that
returns the absolute price oscillator values in two - item json objects as data and meta_data.

Response:
def get_apo(self, symbol, interval='daily', series_type='close',
                fastperiod=None, slowperiod=None, matype=None):
        """ Return the absolute price oscillator values in two
        json objects as data and meta_data. It raises ValueError when problems
        arise

        Keyword Arguments:
            symbol:  the symbol for the equity we want to get its data
            interval:  time interval between two conscutive values,
                supported values are '1min', '5min', '15min', '30min', '60min', 'daily',
                'weekly', 'monthly' (default '60min)'
            series_type:  The desired price type in the time series. Four types
                are supported: 'close', 'open', 'high', 'low' (default 'close')
            fastperiod:  Positive integers are accepted (default=None)
            slowperiod:  Positive integers are accepted (default=None)
            matype    :  Moving average type. By default, fastmatype=0.
                Integers 0 - 8 are accepted (check  down the mappings) or the string
                containing the math type can also be used.

                * 0 = Simple Moving Average (SMA),
                * 1 = Exponential Moving Average (EMA),
                * 2 = Weighted Moving Average (WMA),
                * 3 = Double Exponential Moving Average (DEMA),
                * 4 = Triple Exponential Moving Average (TEMA),
                * 5 = Triangular Moving Average (TRIMA),
                * 6 = T3 Moving Average,
                * 7 = Kaufman Adaptive Moving Average (KAMA),
                * 8 = MESA Adaptive Moving Average (MAMA)
        """
        _FUNCTION_KEY = "APO"
        return _FUNCTION_KEY, 'Technical Analysis: APO', 'Meta Data'


Instruction:
Here you have a function in Python 3, explain what it does
def get_bbands(self, symbol, interval='daily', time_period=20,  series_type='close',
                   nbdevup=None, nbdevdn=None, matype=None):
        """ Return the bollinger bands values in two
        json objects as data and meta_data. It raises ValueError when problems
        arise

        Keyword Arguments:
            symbol:  the symbol for the equity we want to get its data
            interval:  time interval between two conscutive values,
                supported values are '1min', '5min', '15min', '30min', '60min', 'daily',
                'weekly', 'monthly' (default 'daily'
            series_type:  The desired price type in the time series. Four types
                are supported: 'close', 'open', 'high', 'low' (default 'close')
            nbdevup:  The standard deviation multiplier of the upper band. Positive
                integers are accepted as default (default=2)
            nbdevdn:  The standard deviation multiplier of the lower band. Positive
                integers are accepted as default (default=2)
            matype :  Moving average type. By default, matype=0.
                Integers 0 - 8 are accepted (check  down the mappings) or the string
                containing the math type can also be used.

                * 0 = Simple Moving Average (SMA),
                * 1 = Exponential Moving Average (EMA),
                * 2 = Weighted Moving Average (WMA),
                * 3 = Double Exponential Moving Average (DEMA),
                * 4 = Triple Exponential Moving Average (TEMA),
                * 5 = Triangular Moving Average (TRIMA),
                * 6 = T3 Moving Average,
                * 7 = Kaufman Adaptive Moving Average (KAMA),
                * 8 = MESA Adaptive Moving Average (MAMA)
        """
        _FUNCTION_KEY = "BBANDS"
        return _FUNCTION_KEY, 'Technical Analysis: BBANDS', 'Meta Data'

Response: Return the bollinger bands values in two - band format as data and meta_data.


Instruction:
Explain what the following Python 3 code does
def unpack(value):
    if not isinstance(value, tuple):
        return value, 200, {}

    try:
        data, code, headers = value
        return data, code, headers
    except ValueError:
        pass

    try:
        data, code = value
        return data, code, {}
    except ValueError:
        pass

    return value, 200, {}

Response: Return a three tuple of data code and headers


Instruction:
Can you create a Python 3 function that
makes a Flask response with a XML encoded body

Response:
def output_xml(data, code, headers=None):
    """Makes a Flask response with a XML encoded body"""
    resp = make_response(dumps({'response' :data}), code)
    resp.headers.extend(headers or {})
    return resp


Instruction:
Implement a function in Python 3 to
make a Flask response with a JSON encoded body

Response:
def output_json(data, code, headers=None):
    """Makes a Flask response with a JSON encoded body"""

    settings = current_app.config.get('RESTFUL_JSON', {})

    # If we're in debug mode, and the indent is not set, we set it to a
    # reasonable value here.  Note that this won't override any existing value
    # that was set.  We also set the "sort_keys" value.
    if current_app.debug:
        settings.setdefault('indent', 4)
        settings.setdefault('sort_keys', not PY3)

    # always end the json dumps with a new line
    # see https://github.com/mitsuhiko/flask/pull/1262
    dumped = dumps(data, **settings) + "\n"

    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp


Instruction:
Can you generate a brief explanation for the following Python 3 code
def abort(http_status_code, **kwargs):
    #noinspection PyUnresolvedReferences
    try:
        original_flask_abort(http_status_code)
    except HTTPException as e:
        if len(kwargs):
            e.data = kwargs
        raise

Response: Raise a HTTPException for the given http_status_code.


Instruction:
Can you implement a function in Python 3 that
takes raw data and a dict of fields to output and filters the data based on those fields.

Response:
def marshal(data, fields, envelope=None):
    """Takes raw data (in the form of a dict, list, object) and a dict of
    fields to output and filters the data based on those fields.

    :param data: the actual object(s) from which the fields are taken from
    :param fields: a dict of whose keys will make up the final serialized
                   response output
    :param envelope: optional key that will be used to envelop the serialized
                     response

    >>> from flask_restful import fields, marshal
    >>> data = { 'a': 100, 'b': 'foo' }
    >>> mfields = { 'a': fields.Raw }

    >>> marshal(data, mfields)
    OrderedDict([('a', 100)])

    >>> marshal(data, mfields, envelope='data')
    OrderedDict([('data', OrderedDict([('a', 100)]))])

    """

    def make(cls):
        if isinstance(cls, type):
            return cls()
        return cls

    if isinstance(data, (list, tuple)):
        return (OrderedDict([(envelope, [marshal(d, fields) for d in data])])
                if envelope else [marshal(d, fields) for d in data])

    items = ((k, marshal(data, v) if isinstance(v, dict)
              else make(v).output(k, data))
             for k, v in fields.items())
    return OrderedDict([(envelope, OrderedDict(items))]) if envelope else OrderedDict(items)


Instruction:
Can you create a Python 3 function that
initializes this class with the given Flask application or blueprint object.

Response:
def init_app(self, app):
        """Initialize this class with the given :class:`flask.Flask`
        application or :class:`flask.Blueprint` object.

        :param app: the Flask application or blueprint object
        :type app: flask.Flask
        :type app: flask.Blueprint

        Examples::

            api = Api()
            api.add_resource(...)
            api.init_app(app)

        """
        # If app is a blueprint, defer the initialization
        try:
            app.record(self._deferred_blueprint_init)
        # Flask.Blueprint has a 'record' attribute, Flask.Api does not
        except AttributeError:
            self._init_app(app)
        else:
            self.blueprint = app


Instruction:
Can you generate the documentation for the following Python 3 function
def _init_app(self, app):
        app.handle_exception = partial(self.error_router, app.handle_exception)
        app.handle_user_exception = partial(self.error_router, app.handle_user_exception)

        if len(self.resources) > 0:
            for resource, urls, kwargs in self.resources:
                self._register_view(app, resource, *urls, **kwargs)

Response: Perform initialization actions with the given flask. Flask object.


Instruction:
Given the following Python 3 function, write the documentation
def owns_endpoint(self, endpoint):

        if self.blueprint:
            if endpoint.startswith(self.blueprint.name):
                endpoint = endpoint.split(self.blueprint.name + '.', 1)[-1]
            else:
                return False
        return endpoint in self.endpoints

Response: Tests if an endpoint name belongs to this Api.


Instruction:
Create a Python 3 function for
determining if error should be handled with FR or default Flask

Response:
def _should_use_fr_error_handler(self):
        """ Determine if error should be handled with FR or default Flask

        The goal is to return Flask error handlers for non-FR-related routes,
        and FR errors (with the correct media type) for FR endpoints. This
        method currently handles 404 and 405 errors.

        :return: bool
        """
        adapter = current_app.create_url_adapter(request)

        try:
            adapter.match()
        except MethodNotAllowed as e:
            # Check if the other HTTP methods at this url would hit the Api
            valid_route_method = e.valid_methods[0]
            rule, _ = adapter.match(method=valid_route_method, return_rule=True)
            return self.owns_endpoint(rule.endpoint)
        except NotFound:
            return self.catch_all_404s
        except:
            # Werkzeug throws other kinds of exceptions, such as Redirect
            pass


Instruction:
Explain what the following Python 3 code does
def _has_fr_route(self):
        # 404's, 405's, which might not have a url_rule
        if self._should_use_fr_error_handler():
            return True
        # for all other errors, just check if FR dispatched the route
        if not request.url_rule:
            return False
        return self.owns_endpoint(request.url_rule.endpoint)

Response: Returns True if the request was to a Flask endpoint False otherwise.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def error_router(self, original_handler, e):
        if self._has_fr_route():
            try:
                return self.handle_error(e)
            except Exception:
                pass  # Fall through to original handler
        return original_handler(e)

Response: This function decides whether the error occured in a flask - restful endpoint or not.


Instruction:
Here you have a function in Python 3, explain what it does
def add_resource(self, resource, *urls, **kwargs):
        if self.app is not None:
            self._register_view(self.app, resource, *urls, **kwargs)
        else:
            self.resources.append((resource, urls, kwargs))

Response: Adds a resource to the api.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def resource(self, *urls, **kwargs):
        def decorator(cls):
            self.add_resource(cls, *urls, **kwargs)
            return cls
        return decorator

Response:
A decorator that creates a class that adds it to the the
            api.


Instruction:
How would you explain what the following Python 3 function does
def output(self, resource):
        @wraps(resource)
        def wrapper(*args, **kwargs):
            resp = resource(*args, **kwargs)
            if isinstance(resp, ResponseBase):  # There may be a better way to test
                return resp
            data, code, headers = unpack(resp)
            return self.make_response(data, code, headers=headers)
        return wrapper

Response: Wraps a resource function to return a response object


Instruction:
How would you explain what the following Python 3 function does
def url_for(self, resource, **values):
        endpoint = resource.endpoint
        if self.blueprint:
            endpoint = '{0}.{1}'.format(self.blueprint.name, endpoint)
        return url_for(endpoint, **values)

Response: Generates a URL to the given resource.


Instruction:
Explain what the following Python 3 code does
def make_response(self, data, *args, **kwargs):
        default_mediatype = kwargs.pop('fallback_mediatype', None) or self.default_mediatype
        mediatype = request.accept_mimetypes.best_match(
            self.representations,
            default=default_mediatype,
        )
        if mediatype is None:
            raise NotAcceptable()
        if mediatype in self.representations:
            resp = self.representations[mediatype](data, *args, **kwargs)
            resp.headers['Content-Type'] = mediatype
            return resp
        elif mediatype == 'text/plain':
            resp = original_flask_make_response(str(data), *args, **kwargs)
            resp.headers['Content-Type'] = 'text/plain'
            return resp
        else:
            raise InternalServerError()

Response: Creates a response object for the requested media - level - related resource.


Instruction:
Here you have a function in Python 3, explain what it does
def mediatypes(self):
        return [h for h, q in sorted(request.accept_mimetypes,
                                     key=operator.itemgetter(1), reverse=True)]

Response: Returns a list of requested mediatypes sent in the Accept header


Instruction:
Given the following Python 3 function, write the documentation
def representation(self, mediatype):
        def wrapper(func):
            self.representations[mediatype] = func
            return func
        return wrapper

Response: Decorator for the API representation


Instruction:
Write a Python 3 function that can
pull values off the request in the provided location

Response:
def source(self, request):
        """Pulls values off the request in the provided location
        :param request: The flask request object to parse arguments from
        """
        if isinstance(self.location, six.string_types):
            value = getattr(request, self.location, MultiDict())
            if callable(value):
                value = value()
            if value is not None:
                return value
        else:
            values = MultiDict()
            for l in self.location:
                value = getattr(request, l, None)
                if callable(value):
                    value = value()
                if value is not None:
                    values.update(value)
            return values

        return MultiDict()


Instruction:
Make a summary of the following Python 3 code
def handle_validation_error(self, error, bundle_errors):
        error_str = six.text_type(error)
        error_msg = self.help.format(error_msg=error_str) if self.help else error_str
        msg = {self.name: error_msg}

        if current_app.config.get("BUNDLE_ERRORS", False) or bundle_errors:
            return error, msg
        flask_restful.abort(400, message=msg)

Response:
Called when an error occurs while parsing the a
            dictionary.


Instruction:
Can you implement a function in Python 3 that
parses the argument value from the request and returns a list of a objects.

Response:
def parse(self, request, bundle_errors=False):
        """Parses argument value(s) from the request, converting according to
        the argument's type.

        :param request: The flask request object to parse arguments from
        :param bundle_errors: Do not abort when first error occurs, return a
            dict with the name of the argument and the error message to be
            bundled
        """
        source = self.source(request)

        results = []

        # Sentinels
        _not_found = False
        _found = True

        for operator in self.operators:
            name = self.name + operator.replace("=", "", 1)
            if name in source:
                # Account for MultiDict and regular dict
                if hasattr(source, "getlist"):
                    values = source.getlist(name)
                else:
                    values = source.get(name)
                    if not (isinstance(values, collections.MutableSequence) and self.action == 'append'):
                        values = [values]

                for value in values:
                    if hasattr(value, "strip") and self.trim:
                        value = value.strip()
                    if hasattr(value, "lower") and not self.case_sensitive:
                        value = value.lower()

                        if hasattr(self.choices, "__iter__"):
                            self.choices = [choice.lower()
                                            for choice in self.choices]

                    try:
                        value = self.convert(value, operator)
                    except Exception as error:
                        if self.ignore:
                            continue
                        return self.handle_validation_error(error, bundle_errors)

                    if self.choices and value not in self.choices:
                        if current_app.config.get("BUNDLE_ERRORS", False) or bundle_errors:
                            return self.handle_validation_error(
                                ValueError(u"{0} is not a valid choice".format(
                                    value)), bundle_errors)
                        self.handle_validation_error(
                                ValueError(u"{0} is not a valid choice".format(
                                    value)), bundle_errors)

                    if name in request.unparsed_arguments:
                        request.unparsed_arguments.pop(name)
                    results.append(value)

        if not results and self.required:
            if isinstance(self.location, six.string_types):
                error_msg = u"Missing required parameter in {0}".format(
                    _friendly_location.get(self.location, self.location)
                )
            else:
                friendly_locations = [_friendly_location.get(loc, loc)
                                      for loc in self.location]
                error_msg = u"Missing required parameter in {0}".format(
                    ' or '.join(friendly_locations)
                )
            if current_app.config.get("BUNDLE_ERRORS", False) or bundle_errors:
                return self.handle_validation_error(ValueError(error_msg), bundle_errors)
            self.handle_validation_error(ValueError(error_msg), bundle_errors)

        if not results:
            if callable(self.default):
                return self.default(), _not_found
            else:
                return self.default, _not_found

        if self.action == 'append':
            return results, _found

        if self.action == 'store' or len(results) == 1:
            return results[0], _found
        return results, _found


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_argument(self, *args, **kwargs):

        if len(args) == 1 and isinstance(args[0], self.argument_class):
            self.args.append(args[0])
        else:
            self.args.append(self.argument_class(*args, **kwargs))

        # Do not know what other argument classes are out there
        if self.trim and self.argument_class is Argument:
            # enable trim for appended element
            self.args[-1].trim = kwargs.get('trim', self.trim)

        return self

Response: Adds an argument to be parsed.


Instruction:
Write a Python 3 function that can
parse all arguments from the provided request and return the results as a Namespace object.

Response:
def parse_args(self, req=None, strict=False, http_error_code=400):
        """Parse all arguments from the provided request and return the results
        as a Namespace

        :param req: Can be used to overwrite request from Flask
        :param strict: if req includes args not in parser, throw 400 BadRequest exception
        :param http_error_code: use custom error code for `flask_restful.abort()`
        """
        if req is None:
            req = request

        namespace = self.namespace_class()

        # A record of arguments not yet parsed; as each is found
        # among self.args, it will be popped out
        req.unparsed_arguments = dict(self.argument_class('').source(req)) if strict else {}
        errors = {}
        for arg in self.args:
            value, found = arg.parse(req, self.bundle_errors)
            if isinstance(value, ValueError):
                errors.update(found)
                found = None
            if found or arg.store_missing:
                namespace[arg.dest or arg.name] = value
        if errors:
            flask_restful.abort(http_error_code, message=errors)

        if strict and req.unparsed_arguments:
            raise exceptions.BadRequest('Unknown arguments: %s'
                                        % ', '.join(req.unparsed_arguments.keys()))

        return namespace


Instruction:
Here you have a function in Python 3, explain what it does
def copy(self):
        parser_copy = self.__class__(self.argument_class, self.namespace_class)
        parser_copy.args = deepcopy(self.args)
        parser_copy.trim = self.trim
        parser_copy.bundle_errors = self.bundle_errors
        return parser_copy

Response: Creates a copy of this RequestParser with the same set of arguments


Instruction:
Can you implement a function in Python 3 that
replaces the argument matching the given name with a new version.

Response:
def replace_argument(self, name, *args, **kwargs):
        """ Replace the argument matching the given name with a new version. """
        new_arg = self.argument_class(name, *args, **kwargs)
        for index, arg in enumerate(self.args[:]):
            if new_arg.name == arg.name:
                del self.args[index]
                self.args.append(new_arg)
                break
        return self


Instruction:
Can you tell what is the following Python 3 function doing
def remove_argument(self, name):
        for index, arg in enumerate(self.args[:]):
            if name == arg.name:
                del self.args[index]
                break
        return self

Response: Removes the argument matching the given name.


Instruction:
Can you write a function in Python 3 where it
returns the value for the given key from the object.

Response:
def output(self, key, obj):
        """Pulls the value for the given key from the object, applies the
        field's formatting and returns the result. If the key is not found
        in the object, returns the default value. Field classes that create
        values which do not require the existence of the key in the object
        should override this and return the desired value.

        :exception MarshallingException: In case of formatting problem
        """

        value = get_value(key if self.attribute is None else self.attribute, obj)

        if value is None:
            return self.default

        return self.format(value)


Instruction:
Can you tell what is the following Python 3 function doing
def url(value):
    if not url_regex.search(value):
        message = u"{0} is not a valid URL".format(value)
        if url_regex.search('http://' + value):
            message += u". Did you mean: http://{0}".format(value)
        raise ValueError(message)
    return value

Response:
Validate a URL.

    :param string value: The URL to validate
    :returns: The URL if valid.
    :raises: ValueError


Instruction:
How would you code a function in Python 3 to
normalize datetime intervals. Given a pair of datetime.date or datetime.datetime objects, returns a 2-tuple of tz-aware UTC datetimes spanning the same interval. For datetime.date objects, the returned interval starts at 00:00:00.0 on the first date and ends at 00:00:00.0 on the second. Naive datetimes are upgraded to UTC. Timezone-aware datetimes are normalized to the UTC tzdata. Params: - start: A date or datetime - end: A date or datetime

Response:
def _normalize_interval(start, end, value):
    """Normalize datetime intervals.

    Given a pair of datetime.date or datetime.datetime objects,
    returns a 2-tuple of tz-aware UTC datetimes spanning the same interval.

    For datetime.date objects, the returned interval starts at 00:00:00.0
    on the first date and ends at 00:00:00.0 on the second.

    Naive datetimes are upgraded to UTC.

    Timezone-aware datetimes are normalized to the UTC tzdata.

    Params:
        - start: A date or datetime
        - end: A date or datetime
    """
    if not isinstance(start, datetime):
        start = datetime.combine(start, START_OF_DAY)
        end = datetime.combine(end, START_OF_DAY)

    if start.tzinfo is None:
        start = pytz.UTC.localize(start)
        end = pytz.UTC.localize(end)
    else:
        start = start.astimezone(pytz.UTC)
        end = end.astimezone(pytz.UTC)

    return start, end


Instruction:
Implement a function in Python 3 to
try to parse an interval from a string.

Response:
def _parse_interval(value):
    """Do some nasty try/except voodoo to get some sort of datetime
    object(s) out of the string.
    """
    try:
        return sorted(aniso8601.parse_interval(value))
    except ValueError:
        try:
            return aniso8601.parse_datetime(value), None
        except ValueError:
            return aniso8601.parse_date(value), None


Instruction:
Make a summary of the following Python 3 code
def iso8601interval(value, argument='argument'):

    try:
        start, end = _parse_interval(value)

        if end is None:
            end = _expand_datetime(start, value)

        start, end = _normalize_interval(start, end, value)

    except ValueError:
        raise ValueError(
            "Invalid {arg}: {value}. {arg} must be a valid ISO8601 "
            "date/time interval.".format(arg=argument, value=value),
        )

    return start, end

Response: Parses ISO 8601 - formatted datetime intervals into two UTC datetimes.


Instruction:
Write a Python 3 script to
restrict input type to the natural numbers 0 1 2 3 etc.

Response:
def natural(value, argument='argument'):
    """ Restrict input type to the natural numbers (0, 1, 2, 3...) """
    value = _get_integer(value)
    if value < 0:
        error = ('Invalid {arg}: {value}. {arg} must be a non-negative '
                 'integer'.format(arg=argument, value=value))
        raise ValueError(error)
    return value


Instruction:
Create a Python 3 function to
restrict input type to the positive integers 1 2 3 etc.

Response:
def positive(value, argument='argument'):
    """ Restrict input type to the positive integers (1, 2, 3...) """
    value = _get_integer(value)
    if value < 1:
        error = ('Invalid {arg}: {value}. {arg} must be a positive '
                 'integer'.format(arg=argument, value=value))
        raise ValueError(error)
    return value


Instruction:
Create a Python 3 function for
parsing the string true or false as a boolean.

Response:
def boolean(value):
    """Parse the string ``"true"`` or ``"false"`` as a boolean (case
    insensitive). Also accepts ``"1"`` and ``"0"`` as ``True``/``False``
    (respectively). If the input is from the request JSON body, the type is
    already a native python boolean, and will be passed through without
    further parsing.
    """
    if isinstance(value, bool):
        return value

    if not value:
        raise ValueError("boolean type must be non-null")
    value = value.lower()
    if value in ('true', '1',):
        return True
    if value in ('false', '0',):
        return False
    raise ValueError("Invalid literal for boolean(): {0}".format(value))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _keyDown(key):
    if key not in keyboardMapping or keyboardMapping[key] is None:
        return

    if type(key) == int:
        fake_input(_display, X.KeyPress, key)
        _display.sync()
        return

    needsShift = pyautogui.isShiftCharacter(key)
    if needsShift:
        fake_input(_display, X.KeyPress, keyboardMapping['shift'])

    fake_input(_display, X.KeyPress, keyboardMapping[key])

    if needsShift:
        fake_input(_display, X.KeyRelease, keyboardMapping['shift'])
    _display.sync()

Response: Performs a keyboard key press without the release.


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

    """
    Release a given character key. Also works with character keycodes as
    integers, but not keysyms.
    """
    if key not in keyboardMapping or keyboardMapping[key] is None:
        return

    if type(key) == int:
        keycode = key
    else:
        keycode = keyboardMapping[key]

    fake_input(_display, X.KeyRelease, keycode)
    _display.sync()

Response: Performs a keyboard key release up.


Instruction:
Can you implement a function in Python 3 that
returns dict of window title and handle for all visible windows

Response:
def getWindows():    #https://sjohannes.wordpress.com/2012/03/23/win32-python-getting-all-window-titles/
    """Return dict: {'window title' : window handle} for all visible windows"""
    titles = {}

    def foreach_window(hwnd, lparam):
        if IsWindowVisible(hwnd):
            length = GetWindowTextLength(hwnd)
            buff = ctypes.create_unicode_buffer(length + 1)
            GetWindowText(hwnd, buff, length + 1)
            titles[buff.value] = hwnd
        return True
    EnumWindows(EnumWindowsProc(foreach_window), 0)

    return titles


Instruction:
Can you generate the documentation for the following Python 3 function
def getWindow(title, exact=False):
    titles = getWindows()
    hwnd = titles.get(title, None)
    if not hwnd and not exact:
        for k, v in titles.items():
            if title in k:
                hwnd = v
                break
    if hwnd:
        return Window(hwnd)
    else:
        return None

Response: Return Window object if title or its part found in visible windows titles else return None


Instruction:
Make a summary of the following Python 3 code
def set_position(self, x, y, width, height):
        SetWindowPos(self._hwnd, None, x, y, width, height, ctypes.c_uint(0))

Response: Set top - left corner position and size


Instruction:
Can you create a Python 3 function that
moves the window top - left corner to position

Response:
def move(self, x, y):
        """Move window top-left corner to position"""
        SetWindowPos(self._hwnd, None, x, y, 0, 0, SWP_NOSIZE)


Instruction:
Given the following Python 3 function, write the documentation
def get_position(self):
        rect = _Rect()
        GetWindowRect(self._hwnd, ctypes.pointer(rect))
        return rect.left, rect.top, rect.right, rect.bottom

Response: Returns tuple of 4 numbers : left top right bottom right corners


Instruction:
Explain what the following Python 3 code does
def getPointOnLine(x1, y1, x2, y2, n):
    x = ((x2 - x1) * n) + x1
    y = ((y2 - y1) * n) + y1
    return (x, y)

Response:
Returns the x y tuple of the point that has progressed a proportion
    n along the line defined by the two x y coordinates x2 y2 x2 y2 n along the line defined by the two x y coordinates y2 x2 y2 n along the line defined by the two x y coordinates y2 x2 y2 n.


Instruction:
How would you implement a function in Python 3 that
unpacks x and y coordinates into the correct order.

Response:
def _unpackXY(x, y):
    """If x is a sequence and y is None, returns x[0], y[0]. Else, returns x, y.

    On functions that receive a pair of x,y coordinates, they can be passed as
    separate arguments, or as a single two-element sequence.
    """
    if isinstance(x, str):
        # x parameter is the string of an image filename to find and click on:
        x, y = center(locateOnScreen(x))

    elif isinstance(x, collectionsSequence):
        if len(x) == 2:
            if y is None:
                x, y = x
            else:
                raise ValueError('When passing a sequence at the x argument, the y argument must not be passed (received {0}).'.format(repr(y)))
        else:
            raise ValueError('The supplied sequence must have exactly 2 elements ({0} were received).'.format(len(x)))
    else:
        pass # x and y are just number values

    return x, y


Instruction:
Write a Python 3 script to
return the current xy coordinates of the mouse cursor.

Response:
def position(x=None, y=None):
    """Returns the current xy coordinates of the mouse cursor as a two-integer
    tuple.

    Args:
      x (int, None, optional) - If not None, this argument overrides the x in
        the return value.
      y (int, None, optional) - If not None, this argument overrides the y in
        the return value.

    Returns:
      (x, y) tuple of the current xy coordinates of the mouse cursor.
    """
    posx, posy = platformModule._position()
    posx = int(posx)
    posy = int(posy)
    if x is not None: # If set, the x parameter overrides the return value.
        posx = int(x)
    if y is not None: # If set, the y parameter overrides the return value.
        posy = int(y)
    return Point(posx, posy)


Instruction:
Here you have a function in Python 3, explain what it does
def onScreen(x, y=None):
    x, y = _unpackXY(x, y)
    x = int(x)
    y = int(y)

    width, height = platformModule._size()
    return 0 <= x < width and 0 <= y < height

Response: Returns whether the given xy coordinates are on the screen or not.


Instruction:
Write a Python 3 script for
performing a mouse button up and releasing a resource.

Response:
def mouseUp(x=None, y=None, button='left', duration=0.0, tween=linear, pause=None, _pause=True):
    """Performs releasing a mouse button up (but not down beforehand).

    The x and y parameters detail where the mouse event happens. If None, the
    current mouse position is used. If a float value, it is rounded down. If
    outside the boundaries of the screen, the event happens at edge of the
    screen.

    Args:
      x (int, float, None, tuple, optional): The x position on the screen where the
        mouse up happens. None by default. If tuple, this is used for x and y.
        If x is a str, it's considered a filename of an image to find on
        the screen with locateOnScreen() and click the center of.
      y (int, float, None, optional): The y position on the screen where the
        mouse up happens. None by default.
      button (str, int, optional): The mouse button released. Must be one of
        'left', 'middle', 'right' (or 1, 2, or 3) respectively. 'left' by
        default.

    Returns:
      None

    Raises:
      ValueError: If button is not one of 'left', 'middle', 'right', 1, 2, or 3
    """
    if button not in ('left', 'middle', 'right', 1, 2, 3):
        raise ValueError("button argument must be one of ('left', 'middle', 'right', 1, 2, 3), not %s" % button)

    _failSafeCheck()
    x, y = _unpackXY(x, y)

    _mouseMoveDrag('move', x, y, 0, 0, duration=0, tween=None)

    x, y = platformModule._position()
    if button == 1 or str(button).lower() == 'left':
        platformModule._mouseUp(x, y, 'left')
    elif button == 2 or str(button).lower() == 'middle':
        platformModule._mouseUp(x, y, 'middle')
    elif button == 3 or str(button).lower() == 'right':
        platformModule._mouseUp(x, y, 'right')

    _autoPause(pause, _pause)


Instruction:
Write a Python 3 function for
performing a mouse button down and then immediately releasing it.

Response:
def click(x=None, y=None, clicks=1, interval=0.0, button='left', duration=0.0, tween=linear, pause=None, _pause=True):
    """Performs pressing a mouse button down and then immediately releasing it.

    The x and y parameters detail where the mouse event happens. If None, the
    current mouse position is used. If a float value, it is rounded down. If
    outside the boundaries of the screen, the event happens at edge of the
    screen.

    Args:
      x (int, float, None, tuple, str, optional): The x position on the screen where
        the click happens. None by default. If tuple, this is used for x and y.
        If x is a str, it's considered a filename of an image to find on
        the screen with locateOnScreen() and click the center of.
      y (int, float, None, optional): The y position on the screen where the
        click happens. None by default.
      clicks (int, optional): The number of clicks to perform. 1 by default.
        For example, passing 2 would do a doubleclick.
      interval (float, optional): The number of seconds in between each click,
        if the number of clicks is greater than 1. 0.0 by default, for no
        pause in between clicks.
      button (str, int, optional): The mouse button clicked. Must be one of
        'left', 'middle', 'right' (or 1, 2, or 3) respectively. 'left' by
        default.

    Returns:
      None

    Raises:
      ValueError: If button is not one of 'left', 'middle', 'right', 1, 2, 3
    """
    if button not in ('left', 'middle', 'right', 1, 2, 3):
        raise ValueError("button argument must be one of ('left', 'middle', 'right', 1, 2, 3)")

    _failSafeCheck()
    x, y = _unpackXY(x, y)

    _mouseMoveDrag('move', x, y, 0, 0, duration, tween)

    x, y = platformModule._position()
    for i in range(clicks):
        _failSafeCheck()
        if button == 1 or str(button).lower() == 'left':
            platformModule._click(x, y, 'left')
        elif button == 2 or str(button).lower() == 'middle':
            platformModule._click(x, y, 'middle')
        elif button == 3 or str(button).lower() == 'right':
            platformModule._click(x, y, 'right')
        else:
            # These mouse buttons for hor. and vert. scrolling only apply to x11:
            platformModule._click(x, y, button)

        time.sleep(interval)

    _autoPause(pause, _pause)


Instruction:
Implement a Python 3 function for
performing a right mouse button click on the .

Response:
def rightClick(x=None, y=None, duration=0.0, tween=linear, pause=None, _pause=True):
    """Performs a right mouse button click.

    This is a wrapper function for click('right', x, y).

    The x and y parameters detail where the mouse event happens. If None, the
    current mouse position is used. If a float value, it is rounded down. If
    outside the boundaries of the screen, the event happens at edge of the
    screen.

    Args:
      x (int, float, None, tuple, optional): The x position on the screen where the
        click happens. None by default. If tuple, this is used for x and y.
        If x is a str, it's considered a filename of an image to find on
        the screen with locateOnScreen() and click the center of.
      y (int, float, None, optional): The y position on the screen where the
        click happens. None by default.

    Returns:
      None
    """
    _failSafeCheck()

    click(x, y, 1, 0.0, 'right', _pause=False)

    _autoPause(pause, _pause)


Instruction:
Here you have a function in Python 3, explain what it does
def doubleClick(x=None, y=None, interval=0.0, button='left', duration=0.0, tween=linear, pause=None, _pause=True):
    _failSafeCheck()

    # Multiple clicks work different in OSX
    if sys.platform == 'darwin':
        x, y = _unpackXY(x, y)
        _mouseMoveDrag('move', x, y, 0, 0, duration=0, tween=None)
        x, y = platformModule._position()
        platformModule._multiClick(x, y, button, 2)
    else:
        click(x, y, 2, interval, button, _pause=False)

    _autoPause(pause, _pause)

Response: Performs a double click on the base image.


Instruction:
Can you create a Python 3 function that
performs a vertical or horizontal scroll of the underlying .

Response:
def scroll(clicks, x=None, y=None, pause=None, _pause=True):
    """Performs a scroll of the mouse scroll wheel.

    Whether this is a vertical or horizontal scroll depends on the underlying
    operating system.

    The x and y parameters detail where the mouse event happens. If None, the
    current mouse position is used. If a float value, it is rounded down. If
    outside the boundaries of the screen, the event happens at edge of the
    screen.

    Args:
      clicks (int, float): The amount of scrolling to perform.
      x (int, float, None, tuple, optional): The x position on the screen where the
        click happens. None by default. If tuple, this is used for x and y.
      y (int, float, None, optional): The y position on the screen where the
        click happens. None by default.

    Returns:
      None
    """
    _failSafeCheck()
    if type(x) in (tuple, list):
        x, y = x[0], x[1]
    x, y = position(x, y)

    platformModule._scroll(clicks, x, y)

    _autoPause(pause, _pause)


Instruction:
Create a Python 3 function to
perform an explicitly horizontal scroll of the mouse scroll wheel.

Response:
def hscroll(clicks, x=None, y=None, pause=None, _pause=True):
    """Performs an explicitly horizontal scroll of the mouse scroll wheel,
    if this is supported by the operating system. (Currently just Linux.)

    The x and y parameters detail where the mouse event happens. If None, the
    current mouse position is used. If a float value, it is rounded down. If
    outside the boundaries of the screen, the event happens at edge of the
    screen.

    Args:
      clicks (int, float): The amount of scrolling to perform.
      x (int, float, None, tuple, optional): The x position on the screen where the
        click happens. None by default. If tuple, this is used for x and y.
      y (int, float, None, optional): The y position on the screen where the
        click happens. None by default.

    Returns:
      None
    """
    _failSafeCheck()
    if type(x) in (tuple, list):
        x, y = x[0], x[1]
    x, y = position(x, y)

    platformModule._hscroll(clicks, x, y)

    _autoPause(pause, _pause)


Instruction:
Create a Python 3 function to
perform an explicitly vertical scroll of the mouse scroll wheel.

Response:
def vscroll(clicks, x=None, y=None, pause=None, _pause=True):
    """Performs an explicitly vertical scroll of the mouse scroll wheel,
    if this is supported by the operating system. (Currently just Linux.)

    The x and y parameters detail where the mouse event happens. If None, the
    current mouse position is used. If a float value, it is rounded down. If
    outside the boundaries of the screen, the event happens at edge of the
    screen.

    Args:
      clicks (int, float): The amount of scrolling to perform.
      x (int, float, None, tuple, optional): The x position on the screen where the
        click happens. None by default. If tuple, this is used for x and y.
      y (int, float, None, optional): The y position on the screen where the
        click happens. None by default.

    Returns:
      None
    """
    _failSafeCheck()
    if type(x) in (tuple, list):
        x, y = x[0], x[1]
    x, y = position(x, y)
    platformModule._vscroll(clicks, x, y)

    _autoPause(pause, _pause)


Instruction:
Can you tell what is the following Python 3 function doing
def moveTo(x=None, y=None, duration=0.0, tween=linear, pause=None, _pause=True):
    _failSafeCheck()
    x, y = _unpackXY(x, y)

    _mouseMoveDrag('move', x, y, 0, 0, duration, tween)

    _autoPause(pause, _pause)

Response: Moves the mouse cursor to a point on the screen.


Instruction:
Write a Python 3 function that can
move the mouse cursor to a point on the screen relative to its current cursor position.

Response:
def moveRel(xOffset=None, yOffset=None, duration=0.0, tween=linear, pause=None, _pause=True):
    """Moves the mouse cursor to a point on the screen, relative to its current
    position.

    The x and y parameters detail where the mouse event happens. If None, the
    current mouse position is used. If a float value, it is rounded down. If
    outside the boundaries of the screen, the event happens at edge of the
    screen.

    Args:
      x (int, float, None, tuple, optional): How far left (for negative values) or
        right (for positive values) to move the cursor. 0 by default. If tuple, this is used for x and y.
      y (int, float, None, optional): How far up (for negative values) or
        down (for positive values) to move the cursor. 0 by default.
      duration (float, optional): The amount of time it takes to move the mouse
        cursor to the new xy coordinates. If 0, then the mouse cursor is moved
        instantaneously. 0.0 by default.
      tween (func, optional): The tweening function used if the duration is not
        0. A linear tween is used by default. See the tweens.py file for
        details.

    Returns:
      None
    """

    _failSafeCheck()

    xOffset, yOffset = _unpackXY(xOffset, yOffset)

    _mouseMoveDrag('move', None, None, xOffset, yOffset, duration, tween)

    _autoPause(pause, _pause)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def dragTo(x=None, y=None, duration=0.0, tween=linear, button='left', pause=None, _pause=True, mouseDownUp=True):
    _failSafeCheck()
    x, y = _unpackXY(x, y)

    if mouseDownUp:
        mouseDown(button=button, _pause=False)
    _mouseMoveDrag('drag', x, y, 0, 0, duration, tween, button)
    if mouseDownUp:
        mouseUp(button=button, _pause=False)

    _autoPause(pause, _pause)

Response:
Performs a mouse drag to the a
   .


Instruction:
Can you generate the documentation for the following Python 3 function
def dragRel(xOffset=0, yOffset=0, duration=0.0, tween=linear, button='left', pause=None, _pause=True, mouseDownUp=True):
    if xOffset is None:
        xOffset = 0
    if yOffset is None:
        yOffset = 0

    if type(xOffset) in (tuple, list):
        xOffset, yOffset = xOffset[0], xOffset[1]

    if xOffset == 0 and yOffset == 0:
        return # no-op case

    _failSafeCheck()

    mousex, mousey = platformModule._position()
    if mouseDownUp:
        mouseDown(button=button, _pause=False)
    _mouseMoveDrag('drag', mousex, mousey, xOffset, yOffset, duration, tween, button)
    if mouseDownUp:
        mouseUp(button=button, _pause=False)

    _autoPause(pause, _pause)

Response:
Performs a mouse drag to the a
    point on the screen relative to its current position.


Instruction:
Given the following Python 3 function, write the documentation
def _mouseMoveDrag(moveOrDrag, x, y, xOffset, yOffset, duration, tween=linear, button=None):

    # The move and drag code is similar, but OS X requires a special drag event instead of just a move event when dragging.
    # See https://stackoverflow.com/a/2696107/1893164
    assert moveOrDrag in ('move', 'drag'), "moveOrDrag must be in ('move', 'drag'), not %s" % (moveOrDrag)

    if sys.platform != 'darwin':
        moveOrDrag = 'move' # Only OS X needs the drag event specifically.

    xOffset = int(xOffset) if xOffset is not None else 0
    yOffset = int(yOffset) if yOffset is not None else 0

    if x is None and y is None and xOffset == 0 and yOffset == 0:
        return  # Special case for no mouse movement at all.

    startx, starty = position()

    x = int(x) if x is not None else startx
    y = int(y) if y is not None else starty

    # x, y, xOffset, yOffset are now int.
    x += xOffset
    y += yOffset

    width, height = size()

    # Make sure x and y are within the screen bounds.
    x = max(0, min(x, width - 1))
    y = max(0, min(y, height - 1))

    # If the duration is small enough, just move the cursor there instantly.
    steps = [(x, y)]

    if duration > MINIMUM_DURATION:
        # Non-instant moving/dragging involves tweening:
        num_steps = max(width, height)
        sleep_amount = duration / num_steps
        if sleep_amount < MINIMUM_SLEEP:
            num_steps = int(duration / MINIMUM_SLEEP)
            sleep_amount = duration / num_steps

        steps = [
            getPointOnLine(startx, starty, x, y, tween(n / num_steps))
            for n in range(num_steps)
        ]
        # Making sure the last position is the actual destination.
        steps.append((x, y))

    for tweenX, tweenY in steps:
        if len(steps) > 1:
            # A single step does not require tweening.
            time.sleep(sleep_amount)

        _failSafeCheck()
        tweenX = int(round(tweenX))
        tweenY = int(round(tweenY))
        if moveOrDrag == 'move':
            platformModule._moveTo(tweenX, tweenY)
        elif moveOrDrag == 'drag':
            platformModule._dragTo(tweenX, tweenY, button)
        else:
            raise NotImplementedError('Unknown value of moveOrDrag: {0}'.format(moveOrDrag))

    _failSafeCheck()

Response: Handles the mouse move and drag events.


Instruction:
Write a Python 3 function that can
perform a keyboard key press without the release.

Response:
def keyDown(key, pause=None, _pause=True):
    """Performs a keyboard key press without the release. This will put that
    key in a held down state.

    NOTE: For some reason, this does not seem to cause key repeats like would
    happen if a keyboard key was held down on a text field.

    Args:
      key (str): The key to be pressed down. The valid names are listed in
      KEYBOARD_KEYS.

    Returns:
      None
    """
    if len(key) > 1:
        key = key.lower()

    _failSafeCheck()
    platformModule._keyDown(key)

    _autoPause(pause, _pause)


Instruction:
Write a Python 3 function that can
perform a keyboard key release up.

Response:
def keyUp(key, pause=None, _pause=True):
    """Performs a keyboard key release (without the press down beforehand).

    Args:
      key (str): The key to be released up. The valid names are listed in
      KEYBOARD_KEYS.

    Returns:
      None
    """
    if len(key) > 1:
        key = key.lower()

    _failSafeCheck()
    platformModule._keyUp(key)

    _autoPause(pause, _pause)


Instruction:
Explain what the following Python 3 code does
def press(keys, presses=1, interval=0.0, pause=None, _pause=True):
    if type(keys) == str:
        keys = [keys] # put string in a list
    else:
        lowerKeys = []
        for s in keys:
            if len(s) > 1:
                lowerKeys.append(s.lower())
            else:
                lowerKeys.append(s)
    interval = float(interval)
    for i in range(presses):
        for k in keys:
            _failSafeCheck()
            platformModule._keyDown(k)
            platformModule._keyUp(k)
        time.sleep(interval)

    _autoPause(pause, _pause)

Response: Performs a keyboard key press down followed by a release.


Instruction:
How would you implement a function in Python 3 that
performs a keyboard key press down followed by a release for each of the keyboards in message.

Response:
def typewrite(message, interval=0.0, pause=None, _pause=True):
    """Performs a keyboard key press down, followed by a release, for each of
    the characters in message.

    The message argument can also be list of strings, in which case any valid
    keyboard name can be used.

    Since this performs a sequence of keyboard presses and does not hold down
    keys, it cannot be used to perform keyboard shortcuts. Use the hotkey()
    function for that.

    Args:
      message (str, list): If a string, then the characters to be pressed. If a
        list, then the key names of the keys to press in order. The valid names
        are listed in KEYBOARD_KEYS.
      interval (float, optional): The number of seconds in between each press.
        0.0 by default, for no pause in between presses.

    Returns:
      None
    """
    interval = float(interval)

    _failSafeCheck()

    for c in message:
        if len(c) > 1:
            c = c.lower()
        press(c, _pause=False)
        time.sleep(interval)
        _failSafeCheck()

    _autoPause(pause, _pause)


Instruction:
Can you generate the documentation for the following Python 3 function
def displayMousePosition(xOffset=0, yOffset=0):
    print('Press Ctrl-C to quit.')
    if xOffset != 0 or yOffset != 0:
        print('xOffset: %s yOffset: %s' % (xOffset, yOffset))
    resolution = size()
    try:
        while True:
            # Get and print the mouse coordinates.
            x, y = position()
            positionStr = 'X: ' + str(x - xOffset).rjust(4) + ' Y: ' + str(y - yOffset).rjust(4)
            if (x - xOffset) < 0 or (y - yOffset) < 0 or (x - xOffset) >= resolution[0] or (y - yOffset) >= resolution[1]:
                pixelColor = ('NaN', 'NaN', 'NaN')
            else:
                pixelColor = pyscreeze.screenshot().getpixel((x, y))
            positionStr += ' RGB: (' + str(pixelColor[0]).rjust(3)
            positionStr += ', ' + str(pixelColor[1]).rjust(3)
            positionStr += ', ' + str(pixelColor[2]).rjust(3) + ')'
            sys.stdout.write(positionStr)
            sys.stdout.write('\b' * len(positionStr))
            sys.stdout.flush()
    except KeyboardInterrupt:
        sys.stdout.write('\n')
        sys.stdout.flush()

Response: This function will display the location and RGB of the mouse cursor. It will automatically display the location and RGB of the mouse cursor.


Instruction:
Write a Python 3 function for
performing a keyboard key press without the release.

Response:
def _keyDown(key):
    """Performs a keyboard key press without the release. This will put that
    key in a held down state.

    NOTE: For some reason, this does not seem to cause key repeats like would
    happen if a keyboard key was held down on a text field.

    Args:
      key (str): The key to be pressed down. The valid names are listed in
      pyautogui.KEY_NAMES.

    Returns:
      None
    """
    if key not in keyboardMapping or keyboardMapping[key] is None:
        return

    needsShift = pyautogui.isShiftCharacter(key)

    """
    # OLD CODE: The new code relies on having all keys be loaded in keyboardMapping from the start.
    if key in keyboardMapping.keys():
        vkCode = keyboardMapping[key]
    elif len(key) == 1:
        # note: I could use this case to update keyboardMapping to cache the VkKeyScan results, but I've decided not to just to make any possible bugs easier to reproduce.
        vkCode = ctypes.windll.user32.VkKeyScanW(ctypes.wintypes.WCHAR(key))
        if vkCode == -1:
            raise ValueError('There is no VK code for key "%s"' % (key))
        if vkCode > 0x100: # the vk code will be > 0x100 if it needs shift
            vkCode -= 0x100
            needsShift = True
    """
    mods, vkCode = divmod(keyboardMapping[key], 0x100)

    for apply_mod, vk_mod in [(mods & 4, 0x12), (mods & 2, 0x11),
        (mods & 1 or needsShift, 0x10)]: #HANKAKU not suported! mods & 8
        if apply_mod:
            ctypes.windll.user32.keybd_event(vk_mod, 0, 0, 0) #
    ctypes.windll.user32.keybd_event(vkCode, 0, 0, 0)
    for apply_mod, vk_mod in [(mods & 1 or needsShift, 0x10), (mods & 2, 0x11),
        (mods & 4, 0x12)]: #HANKAKU not suported! mods & 8
        if apply_mod:
            ctypes.windll.user32.keybd_event(vk_mod, 0, KEYEVENTF_KEYUP, 0)


Instruction:
Can you create a Python 3 function that
returns the current xy coordinates of the mouse cursor as a two - integer tuple by calling the GetCursorPos win32 function.

Response:
def _position():
    """Returns the current xy coordinates of the mouse cursor as a two-integer
    tuple by calling the GetCursorPos() win32 function.

    Returns:
      (x, y) tuple of the current xy coordinates of the mouse cursor.
    """

    cursor = POINT()
    ctypes.windll.user32.GetCursorPos(ctypes.byref(cursor))
    return (cursor.x, cursor.y)


Instruction:
Write a Python 3 script for
sending the mouse down event to the Windows by calling the mouse_event function.

Response:
def _mouseDown(x, y, button):
    """Send the mouse down event to Windows by calling the mouse_event() win32
    function.

    Args:
      x (int): The x position of the mouse event.
      y (int): The y position of the mouse event.
      button (str): The mouse button, either 'left', 'middle', or 'right'

    Returns:
      None
    """
    if button == 'left':
        try:
            _sendMouseEvent(MOUSEEVENTF_LEFTDOWN, x, y)
        except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60
            pass
    elif button == 'middle':
        try:
            _sendMouseEvent(MOUSEEVENTF_MIDDLEDOWN, x, y)
        except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60
            pass
    elif button == 'right':
        try:
            _sendMouseEvent(MOUSEEVENTF_RIGHTDOWN, x, y)
        except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60
            pass
    else:
        assert False, "button argument not in ('left', 'middle', 'right')"


Instruction:
Explain what the following Python 3 code does
def _mouseUp(x, y, button):
    if button == 'left':
        try:
            _sendMouseEvent(MOUSEEVENTF_LEFTUP, x, y)
        except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60
            pass
    elif button == 'middle':
        try:
            _sendMouseEvent(MOUSEEVENTF_MIDDLEUP, x, y)
        except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60
            pass
    elif button == 'right':
        try:
            _sendMouseEvent(MOUSEEVENTF_RIGHTUP, x, y)
        except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60
            pass
    else:
        assert False, "button argument not in ('left', 'middle', 'right')"

Response: Send the mouse up event to the Windows by calling the mouse_event function.


Instruction:
Implement a function in Python 3 to
send the mouse click event to Windows by calling the mouse_event function.

Response:
def _click(x, y, button):
    """Send the mouse click event to Windows by calling the mouse_event() win32
    function.

    Args:
      button (str): The mouse button, either 'left', 'middle', or 'right'
      x (int): The x position of the mouse event.
      y (int): The y position of the mouse event.

    Returns:
      None
    """
    if button == 'left':
        try:
            _sendMouseEvent(MOUSEEVENTF_LEFTCLICK, x, y)
        except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60
            pass
    elif button == 'middle':
        try:
            _sendMouseEvent(MOUSEEVENTF_MIDDLECLICK, x, y)
        except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60
            pass
    elif button == 'right':
        try:
            _sendMouseEvent(MOUSEEVENTF_RIGHTCLICK, x, y)
        except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60
            pass
    else:
        assert False, "button argument not in ('left', 'middle', 'right')"


Instruction:
Make a summary of the following Python 3 code
def _scroll(clicks, x=None, y=None):
    startx, starty = _position()
    width, height = _size()

    if x is None:
        x = startx
    else:
        if x < 0:
            x = 0
        elif x >= width:
            x = width - 1
    if y is None:
        y = starty
    else:
        if y < 0:
            y = 0
        elif y >= height:
            y = height - 1

    try:
        _sendMouseEvent(MOUSEEVENTF_WHEEL, x, y, dwData=clicks)
    except (PermissionError, OSError): # TODO: We need to figure out how to prevent these errors, see https://github.com/asweigart/pyautogui/issues/60
            pass

Response: Send the mouse vertical scroll event to the available Windows modules.


Instruction:
Can you implement a function in Python 3 that
logs-in to Google API using OAuth2 credentials.

Response:
def authorize(credentials, client_class=Client):
    """Login to Google API using OAuth2 credentials.
    This is a shortcut function which
    instantiates :class:`gspread.client.Client`
    and performs login right away.

    :returns: :class:`gspread.Client` instance.
    """
    client = client_class(auth=credentials)
    client.login()
    return client


Instruction:
Write a Python 3 function for
lowering - level method that directly calls sheets. batchUpdate.

Response:
def batch_update(self, body):
        """Lower-level method that directly calls `spreadsheets.batchUpdate <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate>`_.

        :param dict body: `Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#request-body>`_.
        :returns: `Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/batchUpdate#response-body>`_.
        :rtype: dict

        .. versionadded:: 3.0

        """
        r = self.client.request(
            'post',
            SPREADSHEET_BATCH_UPDATE_URL % self.id,
            json=body
        )

        return r.json()


Instruction:
Explain what the following Python 3 code does
def values_append(self, range, params, body):
        url = SPREADSHEET_VALUES_APPEND_URL % (self.id, quote(range))
        r = self.client.request('post', url, params=params, json=body)
        return r.json()

Response: Lower - level method that directly calls spreadsheets. values. append <https://developers. google. com / sheets > _. Values are appended after the last row of the table.


Instruction:
Given the following Python 3 function, write the documentation
def values_clear(self, range):
        url = SPREADSHEET_VALUES_CLEAR_URL % (self.id, quote(range))
        r = self.client.request('post', url)
        return r.json()

Response: Lower - level method that directly calls spreadsheets. values. clear.


Instruction:
Can you generate the documentation for the following Python 3 function
def values_get(self, range, params=None):
        url = SPREADSHEET_VALUES_URL % (self.id, quote(range))
        r = self.client.request('get', url, params=params)
        return r.json()

Response: Lower - level method that directly calls sheets. values. get <https://developers. google. com / sheets / api / guides / concepts#a1_notation >_ of the values to retrieve.


Instruction:
How would you code a function in Python 3 to
lower - level method that directly calls spreadsheets. values. update.

Response:
def values_update(self, range, params=None, body=None):
        """Lower-level method that directly calls `spreadsheets.values.update <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update>`_.

        :param str range: The `A1 notation <https://developers.google.com/sheets/api/guides/concepts#a1_notation>`_ of the values to update.
        :param dict params: (optional) `Query parameters <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#query-parameters>`_.
        :param dict body: (optional) `Request body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#request-body>`_.
        :returns: `Response body <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update#response-body>`_.
        :rtype: dict

        Example::

            sh.values_update(
                'Sheet1!A2',
                params={
                    'valueInputOption': 'USER_ENTERED'
                },
                body={
                    'values': [[1, 2, 3]]
                }
            )

        .. versionadded:: 3.0

        """
        url = SPREADSHEET_VALUES_URL % (self.id, quote(range))
        r = self.client.request('put', url, params=params, json=body)
        return r.json()


Instruction:
Implement a function in Python 3 to
return a worksheet with specified index.

Response:
def get_worksheet(self, index):
        """Returns a worksheet with specified `index`.

        :param index: An index of a worksheet. Indexes start from zero.
        :type index: int

        :returns: an instance of :class:`gsperad.models.Worksheet`
                  or `None` if the worksheet is not found.

        Example. To get first worksheet of a spreadsheet:

        >>> sht = client.open('My fancy spreadsheet')
        >>> worksheet = sht.get_worksheet(0)

        """
        sheet_data = self.fetch_sheet_metadata()

        try:
            properties = sheet_data['sheets'][index]['properties']
            return Worksheet(self, properties)
        except (KeyError, IndexError):
            return None


Instruction:
Here you have a function in Python 3, explain what it does
def worksheets(self):
        sheet_data = self.fetch_sheet_metadata()
        return [Worksheet(self, x['properties']) for x in sheet_data['sheets']]

Response: Returns a list of all sheets in a spreadsheet.


Instruction:
Implement a function in Python 3 to
return a worksheet with the specified title.

Response:
def worksheet(self, title):
        """Returns a worksheet with specified `title`.

        :param title: A title of a worksheet. If there're multiple
                      worksheets with the same title, first one will
                      be returned.
        :type title: int

        :returns: an instance of :class:`gsperad.models.Worksheet`.

        Example. Getting worksheet named 'Annual bonuses'

        >>> sht = client.open('Sample one')
        >>> worksheet = sht.worksheet('Annual bonuses')

        """
        sheet_data = self.fetch_sheet_metadata()
        try:
            item = finditem(
                lambda x: x['properties']['title'] == title,
                sheet_data['sheets']
            )
            return Worksheet(self, item['properties'])
        except (StopIteration, KeyError):
            raise WorksheetNotFound(title)


Instruction:
Explain what the following Python 3 code does
def add_worksheet(self, title, rows, cols):
        body = {
            'requests': [{
                'addSheet': {
                    'properties': {
                        'title': title,
                        'sheetType': 'GRID',
                        'gridProperties': {
                            'rowCount': rows,
                            'columnCount': cols
                        }
                    }
                }
            }]
        }

        data = self.batch_update(body)

        properties = data['replies'][0]['addSheet']['properties']

        worksheet = Worksheet(self, properties)

        return worksheet

Response: Adds a new worksheet to a spreadsheet.


Instruction:
Can you tell what is the following Python 3 function doing
def duplicate_sheet(
        self,
        source_sheet_id,
        insert_sheet_index=None,
        new_sheet_id=None,
        new_sheet_name=None
    ):
        """Duplicates the contents of a sheet.

        :param int source_sheet_id: The sheet ID to duplicate.
        :param int insert_sheet_index: (optional) The zero-based index
                                       where the new sheet should be inserted.
                                       The index of all sheets after this are
                                       incremented.
        :param int new_sheet_id: (optional) The ID of the new sheet.
                                 If not set, an ID is chosen. If set, the ID
                                 must not conflict with any existing sheet ID.
                                 If set, it must be non-negative.
        :param str new_sheet_name: (optional) The name of the new sheet.
                                   If empty, a new name is chosen for you.

        :returns: a newly created :class:`<gspread.models.Worksheet>`.

        .. versionadded:: 3.1.0

        """
        body = {
            'requests': [{
                'duplicateSheet': {
                    'sourceSheetId': source_sheet_id,
                    'insertSheetIndex': insert_sheet_index,
                    'newSheetId': new_sheet_id,
                    'newSheetName': new_sheet_name
                }
            }]
        }

        data = self.batch_update(body)

        properties = data['replies'][0]['duplicateSheet']['properties']

        worksheet = Worksheet(self, properties)

        return worksheet

Response:
Duplicates the contents of a sheet.

        :param int source_sheet_id: The sheet ID to duplicate.
        :param int insert_sheet_index: (optional) The zero-based index
                                       where the new sheet should be inserted.
                                       The index of all sheets after this are
                                       incremented.
        :param int new_sheet_id: (optional) The ID of the new sheet.
                                 If not set, an ID is chosen. If set, the ID
                                 must not conflict with any existing sheet ID.
                                 If set, it must be non-negative.
        :param str new_sheet_name: (optional) The name of the new sheet.
                                   If empty, a new name is chosen for you.

        :returns: a newly created :class:`<gspread.models.Worksheet>`.

        .. versionadded:: 3.1.0


Instruction:
How would you explain what the following Python 3 function does
def share(self, value, perm_type, role, notify=True, email_message=None, with_link=False):
        self.client.insert_permission(
            self.id,
            value=value,
            perm_type=perm_type,
            role=role,
            notify=notify,
            email_message=email_message,
            with_link=with_link
        )

Response: Share the spreadsheet with other accounts.


Instruction:
How would you implement a function in Python 3 that
removes permissions from a user or domain.

Response:
def remove_permissions(self, value, role='any'):
        """Remove permissions from a user or domain.

        :param value: User or domain to remove permissions from
        :type value: str
        :param role: (optional) Permission to remove. Defaults to all
                     permissions.
        :type role: str

        Example::

            # Remove Otto's write permission for this spreadsheet
            sh.remove_permissions('otto@example.com', role='writer')

            # Remove all Otto's permissions for this spreadsheet
            sh.remove_permissions('otto@example.com')
        """
        permission_list = self.client.list_permissions(self.id)

        key = 'emailAddress' if '@' in value else 'domain'

        filtered_id_list = [
            p['id'] for p in permission_list
            if p[key] == value and (p['role'] == role or role == 'any')
        ]

        for permission_id in filtered_id_list:
            self.client.remove_permission(self.id, permission_id)

        return filtered_id_list


Instruction:
Given the following Python 3 function, write the documentation
def acell(self, label, value_render_option='FORMATTED_VALUE'):

        return self.cell(
            *(a1_to_rowcol(label)),
            value_render_option=value_render_option
        )

Response: Returns an instance of a : class : gspread. models. Cell with the given label.


Instruction:
Given the following Python 3 function, write the documentation
def cell(self, row, col, value_render_option='FORMATTED_VALUE'):

        range_label = '%s!%s' % (self.title, rowcol_to_a1(row, col))
        data = self.spreadsheet.values_get(
            range_label,
            params={'valueRenderOption': value_render_option}
        )

        try:
            value = data['values'][0][0]
        except KeyError:
            value = ''

        return Cell(row, col, value)

Response:
Returns an instance of a : class : ~gspread. models. Cell located at
        row and col.


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

        range_label = '%s!%s' % (self.title, name)

        data = self.spreadsheet.values_get(range_label)

        start, end = name.split(':')
        (row_offset, column_offset) = a1_to_rowcol(start)
        (last_row, last_column) = a1_to_rowcol(end)

        values = data.get('values', [])

        rect_values = fill_gaps(
            values,
            rows=last_row - row_offset + 1,
            cols=last_column - column_offset + 1
        )

        return [
            Cell(row=i + row_offset, col=j + column_offset, value=value)
            for i, row in enumerate(rect_values)
            for j, value in enumerate(row)
        ]

Response: Returns a list of Cell objects from a specified range.


Instruction:
Can you write a function in Python 3 where it
returns a list of lists containing all cells values as strings.

Response:
def get_all_values(self):
        """Returns a list of lists containing all cells' values as strings.

        .. note::

            Empty trailing rows and columns will not be included.
        """

        data = self.spreadsheet.values_get(self.title)

        try:
            return fill_gaps(data['values'])
        except KeyError:
            return []


Instruction:
Can you tell what is the following Python 3 function doing
def get_all_records(
        self,
        empty2zero=False,
        head=1,
        default_blank="",
        allow_underscores_in_numeric_literals=False,
    ):
        """Returns a list of dictionaries, all of them having the contents
            of the spreadsheet with the head row as keys and each of these
            dictionaries holding the contents of subsequent rows of cells
            as values.

            Cell values are numericised (strings that can be read as ints
            or floats are converted).

            :param empty2zero: (optional) Determines whether empty cells are
                               converted to zeros.
            :type empty2zero: bool
            :param head: (optional) Determines wich row to use as keys, starting
                         from 1 following the numeration of the spreadsheet.
            :type head: int
            :param default_blank: (optional) Determines whether empty cells are
                                  converted to something else except empty string
                                  or zero.
            :type default_blank: str
            :param allow_underscores_in_numeric_literals: (optional) Allow underscores
                                                          in numeric literals,
                                                          as introduced in PEP 515
            :type allow_underscores_in_numeric_literals: bool
            """

        idx = head - 1

        data = self.get_all_values()

        # Return an empty list if the sheet doesn't have enough rows
        if len(data) <= idx:
            return []

        keys = data[idx]
        values = [
            numericise_all(
                row,
                empty2zero,
                default_blank,
                allow_underscores_in_numeric_literals,
            )
            for row in data[idx + 1:]
        ]

        return [dict(zip(keys, row)) for row in values]

Response: Returns a list of dictionaries containing all of the contents of the contents of the next cell in the spreadsheet.


Instruction:
Make a summary of the following Python 3 code
def row_values(self, row, value_render_option='FORMATTED_VALUE'):

        range_label = '%s!A%s:%s' % (self.title, row, row)

        data = self.spreadsheet.values_get(
            range_label,
            params={'valueRenderOption': value_render_option}
        )

        try:
            return data['values'][0]
        except KeyError:
            return []

Response: Returns a list of all values in a row.


Instruction:
Create a Python 3 function for
returning a list of all values in column col.

Response:
def col_values(self, col, value_render_option='FORMATTED_VALUE'):
        """Returns a list of all values in column `col`.

        Empty cells in this list will be rendered as :const:`None`.

        :param col: Column number.
        :type col: int
        :param value_render_option: (optional) Determines how values should be
                                    rendered in the the output. See
                                    `ValueRenderOption`_ in the Sheets API.
        :type value_render_option: str

        .. _ValueRenderOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueRenderOption

        """

        start_label = rowcol_to_a1(1, col)
        range_label = '%s!%s:%s' % (self.title, start_label, start_label[:-1])

        data = self.spreadsheet.values_get(
            range_label,
            params={
                'valueRenderOption': value_render_option,
                'majorDimension': 'COLUMNS'
            }
        )

        try:
            return data['values'][0]
        except KeyError:
            return []


Instruction:
Can you generate a brief explanation for the following Python 3 code
def update_acell(self, label, value):
        return self.update_cell(*(a1_to_rowcol(label)), value=value)

Response: Updates the value of a cell in A1 notation.


Instruction:
Create a Python 3 function for
updating the value of a cell.

Response:
def update_cell(self, row, col, value):
        """Updates the value of a cell.

        :param row: Row number.
        :type row: int
        :param col: Column number.
        :type col: int
        :param value: New value.

        Example::

            worksheet.update_cell(1, 1, '42')

        """
        range_label = '%s!%s' % (self.title, rowcol_to_a1(row, col))

        data = self.spreadsheet.values_update(
            range_label,
            params={
                'valueInputOption': 'USER_ENTERED'
            },
            body={
                'values': [[value]]
            }
        )

        return data


Instruction:
Create a Python 3 function for
updating many cells at once.

Response:
def update_cells(self, cell_list, value_input_option='RAW'):
        """Updates many cells at once.

        :param cell_list: List of :class:`Cell` objects to update.
        :param value_input_option: (optional) Determines how input data should
                                    be interpreted. See `ValueInputOption`_ in
                                    the Sheets API.
        :type value_input_option: str

        .. _ValueInputOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption

        Example::

            # Select a range
            cell_list = worksheet.range('A1:C7')

            for cell in cell_list:
                cell.value = 'O_o'

            # Update in batch
            worksheet.update_cells(cell_list)

        """

        values_rect = cell_list_to_rect(cell_list)

        start = rowcol_to_a1(min(c.row for c in cell_list), min(c.col for c in cell_list))
        end = rowcol_to_a1(max(c.row for c in cell_list), max(c.col for c in cell_list))

        range_label = '%s!%s:%s' % (self.title, start, end)

        data = self.spreadsheet.values_update(
            range_label,
            params={
                'valueInputOption': value_input_option
            },
            body={
                'values': values_rect
            }
        )

        return data


Instruction:
Can you tell what is the following Python 3 function doing
def resize(self, rows=None, cols=None):
        grid_properties = {}

        if rows is not None:
            grid_properties['rowCount'] = rows

        if cols is not None:
            grid_properties['columnCount'] = cols

        if not grid_properties:
            raise TypeError("Either 'rows' or 'cols' should be specified.")

        fields = ','.join(
            'gridProperties/%s' % p for p in grid_properties.keys()
        )

        body = {
            'requests': [{
                'updateSheetProperties': {
                    'properties': {
                        'sheetId': self.id,
                        'gridProperties': grid_properties
                    },
                    'fields': fields
                }
            }]
        }

        return self.spreadsheet.batch_update(body)

Response: Resizes the worksheet. Specify one of rows or cols.


Instruction:
Can you write a function in Python 3 where it
renames the worksheet. :param title: A new title. :type title: str

Response:
def update_title(self, title):
        """Renames the worksheet.

        :param title: A new title.
        :type title: str

        """

        body = {
            'requests': [{
                'updateSheetProperties': {
                    'properties': {
                        'sheetId': self.id,
                        'title': title
                    },
                    'fields': 'title'
                }
            }]
        }

        response = self.spreadsheet.batch_update(body)
        self._properties['title'] = title
        return response


Instruction:
Can you generate a brief explanation for the following Python 3 code
def append_row(self, values, value_input_option='RAW'):
        params = {
            'valueInputOption': value_input_option
        }

        body = {
            'values': [values]
        }

        return self.spreadsheet.values_append(self.title, params, body)

Response: Adds a row to the worksheet and populates it with values.


Instruction:
How would you explain what the following Python 3 function does
def insert_row(
        self,
        values,
        index=1,
        value_input_option='RAW'
    ):
        """Adds a row to the worksheet at the specified index
        and populates it with values.

        Widens the worksheet if there are more values than columns.

        :param values: List of values for the new row.
        :param index: (optional) Offset for the newly inserted row.
        :type index: int
        :param value_input_option: (optional) Determines how input data should
                                    be interpreted. See `ValueInputOption`_ in
                                    the Sheets API.
        :type value_input_option: str

        .. _ValueInputOption: https://developers.google.com/sheets/api/reference/rest/v4/ValueInputOption

        """

        body = {
            "requests": [{
                "insertDimension": {
                    "range": {
                      "sheetId": self.id,
                      "dimension": "ROWS",
                      "startIndex": index - 1,
                      "endIndex": index
                    }
                }
            }]
        }

        self.spreadsheet.batch_update(body)

        range_label = '%s!%s' % (self.title, 'A%s' % index)

        data = self.spreadsheet.values_update(
            range_label,
            params={
                'valueInputOption': value_input_option
            },
            body={
                'values': [values]
            }
        )

        return data

Response: Adds a row to the worksheet at the specified index and populates it with values.


Instruction:
Can you tell what is the following Python 3 function doing
def delete_row(self, index):
        body = {
            "requests": [{
                "deleteDimension": {
                    "range": {
                      "sheetId": self.id,
                      "dimension": "ROWS",
                      "startIndex": index - 1,
                      "endIndex": index
                    }
                }
            }]
        }

        return self.spreadsheet.batch_update(body)

Response: Deletes the row from the worksheet at the specified index.


Instruction:
Can you generate the documentation for the following Python 3 function
def find(self, query):
        try:
            return self._finder(finditem, query)
        except StopIteration:
            raise CellNotFound(query)

Response: Finds the first cell matching the query.


Instruction:
Given the following Python 3 function, write the documentation
def duplicate(
        self,
        insert_sheet_index=None,
        new_sheet_id=None,
        new_sheet_name=None
    ):
        """Duplicate the sheet.

        :param int insert_sheet_index: (optional) The zero-based index
                                       where the new sheet should be inserted.
                                       The index of all sheets after this are
                                       incremented.
        :param int new_sheet_id: (optional) The ID of the new sheet.
                                 If not set, an ID is chosen. If set, the ID
                                 must not conflict with any existing sheet ID.
                                 If set, it must be non-negative.
        :param str new_sheet_name: (optional) The name of the new sheet.
                                   If empty, a new name is chosen for you.

        :returns: a newly created :class:`<gspread.models.Worksheet>`.

        .. versionadded:: 3.1.0

        """
        return self.spreadsheet.duplicate_sheet(
            self.id,
            insert_sheet_index,
            new_sheet_id,
            new_sheet_name
        )

Response: Duplicate the current entry in the current worksheet.


Instruction:
Can you tell what is the following Python 3 function doing
def numericise(value, empty2zero=False, default_blank="", allow_underscores_in_numeric_literals=False):
    if value is not None:
        if "_" in value and not allow_underscores_in_numeric_literals:
            return value
        try:
            value = int(value)
        except ValueError:
            try:
                value = float(value)
            except ValueError:
                if value == "":
                    if empty2zero:
                        value = 0
                    else:
                        value = default_blank

    return value

Response: Returns a value that depends on the input string.


Instruction:
Create a Python 3 function to
return a list of numericised values from strings

Response:
def numericise_all(input, empty2zero=False, default_blank="", allow_underscores_in_numeric_literals=False):
    """Returns a list of numericised values from strings"""
    return [numericise(s, empty2zero, default_blank, allow_underscores_in_numeric_literals) for s in input]


Instruction:
How would you explain what the following Python 3 function does
def rowcol_to_a1(row, col):
    row = int(row)
    col = int(col)

    if row < 1 or col < 1:
        raise IncorrectCellLabel('(%s, %s)' % (row, col))

    div = col
    column_label = ''

    while div:
        (div, mod) = divmod(div, 26)
        if mod == 0:
            mod = 26
            div -= 1
        column_label = chr(mod + MAGIC_NUMBER) + column_label

    label = '%s%s' % (column_label, row)

    return label

Response: Translates a row and column cell address to A1 notation.


Instruction:
Create a Python 3 function for
translating a cell s address in A1 notation to a tuple of integers.

Response:
def a1_to_rowcol(label):
    """Translates a cell's address in A1 notation to a tuple of integers.

    :param label: A cell label in A1 notation, e.g. 'B1'.
                  Letter case is ignored.
    :type label: str

    :returns: a tuple containing `row` and `column` numbers. Both indexed
              from 1 (one).

    Example:

    >>> a1_to_rowcol('A1')
    (1, 1)

    """
    m = CELL_ADDR_RE.match(label)
    if m:
        column_label = m.group(1).upper()
        row = int(m.group(2))

        col = 0
        for i, c in enumerate(reversed(column_label)):
            col += (ord(c) - MAGIC_NUMBER) * (26 ** i)
    else:
        raise IncorrectCellLabel(label)

    return (row, col)