Instruction:
Write a Python 3 function for
fitting classifier clf to return probabilities close to y_proba.

Response:
def fit_proba(clf, X, y_proba, expand_factor=10, sample_weight=None,
              shuffle=True, random_state=None,
              **fit_params):
    """
    Fit classifier ``clf`` to return probabilities close to ``y_proba``.

    scikit-learn can't optimize cross-entropy directly if target
    probability values are not indicator vectors. As a workaround this function
    expands the dataset according to target probabilities.
    Use expand_factor=None to turn it off
    (e.g. if probability scores are 0/1 in a first place).
    """
    X, y, sample_weight = expanded_X_y_sample_weights(X, y_proba,
        expand_factor=expand_factor,
        sample_weight=sample_weight,
        shuffle=shuffle,
        random_state=random_state,
    )
    fit_params = with_sample_weight(clf, sample_weight, fit_params)
    clf.fit(X, y, **fit_params)
    return clf


Instruction:
Implement a function in Python 3 to
return fit_params with added sample_weight argument.

Response:
def with_sample_weight(clf, sample_weight, fit_params):
    """
    Return fit_params with added "sample_weight" argument.
    Unlike `fit_params['sample_weight'] = sample_weight` it
    handles a case where ``clf`` is a pipeline.
    """
    param_name = _get_classifier_prefix(clf) + "sample_weight"
    params = {param_name: sample_weight}
    params.update(fit_params)
    return params


Instruction:
Can you implement a function in Python 3 that
adds missing columns to predict_proba result. When a multiclass classifier is fit on a dataset which only contains a subset of possible classes its predict_proba result only has columns corresponding to seen classes. This function adds missing columns.

Response:
def fix_multiclass_predict_proba(y_proba,          # type: np.ndarray
                                 seen_classes,
                                 complete_classes
                                 ):
    # type: (...) -> np.ndarray
    """
    Add missing columns to predict_proba result.

    When a multiclass classifier is fit on a dataset which only contains
    a subset of possible classes its predict_proba result only has columns
    corresponding to seen classes. This function adds missing columns.
    """
    assert set(complete_classes) >= set(seen_classes)
    y_proba_fixed = np.zeros(
        shape=(y_proba.shape[0], len(complete_classes)),
        dtype=y_proba.dtype,
    )
    class_mapping = np.searchsorted(complete_classes, seen_classes)
    y_proba_fixed[:, class_mapping] = y_proba
    return y_proba_fixed


Instruction:
Write a Python 3 script to
expand the dataset X and y according to the target probabilities y_proba.

Response:
def expanded_X_y_sample_weights(X, y_proba, expand_factor=10,
                                sample_weight=None, shuffle=True,
                                random_state=None):
    """
    scikit-learn can't optimize cross-entropy directly if target
    probability values are not indicator vectors.
    As a workaround this function expands the dataset according to
    target probabilities. ``expand_factor=None`` means no dataset
    expansion.
    """
    rng = check_random_state(random_state)
    if expand_factor:
        if sample_weight is not None:
            X, y, sample_weight = zip(*expand_dataset(X, y_proba,
                                                      factor=expand_factor,
                                                      random_state=rng,
                                                      extra_arrays=[
                                                          sample_weight
                                                      ]))
        else:
            X, y = zip(*expand_dataset(X, y_proba,
                                       factor=expand_factor,
                                       random_state=rng))
    else:
        y = y_proba.argmax(axis=1)

    if isinstance(X, (list, tuple)) and len(X) and issparse(X[0]):
        X = vstack(X)

    if shuffle:
        if sample_weight is not None:
            X, y, sample_weight = _shuffle(X, y, sample_weight,
                                           random_state=rng)
        else:
            X, y = _shuffle(X, y, random_state=rng)
    return X, y, sample_weight


Instruction:
Can you implement a function in Python 3 that
converts a dataset with float multiclass probabilities to a dataset with indicator probabilities by duplicating X rows and sampling true labels.

Response:
def expand_dataset(X, y_proba, factor=10, random_state=None, extra_arrays=None):
    """
    Convert a dataset with float multiclass probabilities to a dataset
    with indicator probabilities by duplicating X rows and sampling
    true labels.
    """
    rng = check_random_state(random_state)
    extra_arrays = extra_arrays or []
    n_classes = y_proba.shape[1]
    classes = np.arange(n_classes, dtype=int)
    for el in zip(X, y_proba, *extra_arrays):
        x, probs = el[0:2]
        rest = el[2:]
        for label in rng.choice(classes, size=factor, p=probs):
            yield (x, label) + rest


Instruction:
Can you write a function in Python 3 where it
gets feature names for a given transformer.

Response:
def transform_feature_names(transformer, in_names=None):
    """Get feature names for transformer output as a function of input names.

    Used by :func:`explain_weights` when applied to a scikit-learn Pipeline,
    this ``singledispatch`` should be registered with custom name
    transformations for each class of transformer.

    If there is no ``singledispatch`` handler registered for a transformer
    class, ``transformer.get_feature_names()`` method is called; if there is
    no such method then feature names are not supported and
    this function raises an exception.

    Parameters
    ----------
    transformer : scikit-learn-compatible transformer
    in_names : list of str, optional
        Names for features input to transformer.transform().
        If not provided, the implementation may generate default feature names
        if the number of input features is known.

    Returns
    -------
    feature_names : list of str
    """
    if hasattr(transformer, 'get_feature_names'):
        return transformer.get_feature_names()
    raise NotImplementedError('transform_feature_names not available for '
                              '{}'.format(transformer))


Instruction:
Can you tell what is the following Python 3 function doing
def get_weighted_spans(doc, vec, feature_weights):
    # type: (Any, Any, FeatureWeights) -> Optional[WeightedSpans]
    """ If possible, return a dict with preprocessed document and a list
    of spans with weights, corresponding to features in the document.
    """
    if isinstance(vec, FeatureUnion):
        return _get_weighted_spans_from_union(doc, vec, feature_weights)
    else:
        result = _get_doc_weighted_spans(doc, vec, feature_weights)
        if result is not None:
            found_features, doc_weighted_spans = result
            return WeightedSpans(
                [doc_weighted_spans],
                other=_get_other(feature_weights, [('', found_features)]),
            )
    return None

Response: Returns a dict with preprocessed document and a list of weighted spans corresponding to features in the document.


Instruction:
Write a Python 3 function that can
compute and set target_expl. weighted_spans attribute when possible.

Response:
def add_weighted_spans(doc, vec, vectorized, target_expl):
    # type: (Any, Any, bool, TargetExplanation) -> None
    """
    Compute and set ``target_expl.weighted_spans`` attribute, when possible.
    """
    if vec is None or vectorized:
        return

    weighted_spans = get_weighted_spans(doc, vec, target_expl.feature_weights)
    if weighted_spans:
        target_expl.weighted_spans = weighted_spans


Instruction:
Explain what the following Python 3 code does
def _get_feature_weights_dict(feature_weights,  # type: FeatureWeights
                              feature_fn        # type: Optional[Callable[[str], str]]
                              ):
    # type: (...) -> Dict[str, Tuple[float, Tuple[str, int]]]
    """ Return {feat_name: (weight, (group, idx))} mapping. """
    return {
        # (group, idx) is an unique feature identifier, e.g. ('pos', 2)
        feat_name: (fw.weight, (group, idx))
        for group in ['pos', 'neg']
        for idx, fw in enumerate(getattr(feature_weights, group))
        for feat_name in _get_features(fw.feature, feature_fn)
    }

Response: Return a dictionary mapping each feature name to its weight.


Instruction:
Can you generate the documentation for the following Python 3 function
def fit(self, X, y, groups=None, **fit_params):
        # type: (...) -> PermutationImportance
        """Compute ``feature_importances_`` attribute and optionally
        fit the base estimator.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            The training input samples.

        y : array-like, shape (n_samples,)
            The target values (integers that correspond to classes in
            classification, real numbers in regression).

        groups : array-like, with shape (n_samples,), optional
            Group labels for the samples used while splitting the dataset into
            train/test set.

        **fit_params : Other estimator specific parameters

        Returns
        -------
        self : object
            Returns self.
        """
        self.scorer_ = check_scoring(self.estimator, scoring=self.scoring)

        if pandas_available and isinstance(X, pd.DataFrame):
            self.scorer_ = self._wrap_scorer(self.scorer_, X.columns)

        if self.cv != "prefit" and self.refit:
            self.estimator_ = clone(self.estimator)
            self.estimator_.fit(X, y, **fit_params)

        X = check_array(X)

        if self.cv not in (None, "prefit"):
            si = self._cv_scores_importances(X, y, groups=groups, **fit_params)
        else:
            si = self._non_cv_scores_importances(X, y)
        scores, results = si
        self.scores_ = np.array(scores)
        self.results_ = results
        self.feature_importances_ = np.mean(results, axis=0)
        self.feature_importances_std_ = np.std(results, axis=0)
        return self

Response: Fits the base estimator and returns the PermutationImportance object.


Instruction:
Can you create a Python 3 function that
returns an explanation of an estimator prediction.

Response:
def explain_prediction(estimator, doc, **kwargs):
    """
    Return an explanation of an estimator prediction.

    :func:`explain_prediction` is not doing any work itself, it dispatches
    to a concrete implementation based on estimator type.

    Parameters
    ----------
    estimator : object
        Estimator instance. This argument must be positional.

    doc : object
        Example to run estimator on. Estimator makes a prediction for this
        example, and :func:`explain_prediction` tries to show information
        about this prediction. Pass a single element, not a one-element array:
        if you fitted your estimator on ``X``, that would be ``X[i]`` for
        most containers, and ``X.iloc[i]`` for ``pandas.DataFrame``.

    top : int or (int, int) tuple, optional
        Number of features to show. When ``top`` is int, ``top`` features with
        a highest absolute values are shown. When it is (pos, neg) tuple,
        no more than ``pos`` positive features and no more than ``neg``
        negative features is shown. ``None`` value means no limit (default).

        This argument may be supported or not, depending on estimator type.

    top_targets : int, optional
        Number of targets to show. When ``top_targets`` is provided,
        only specified number of targets with highest scores are shown.
        Negative value means targets with lowest scores are shown.
        Must not be given with ``targets`` argument.
        ``None`` value means no limit: all targets are shown (default).

        This argument may be supported or not, depending on estimator type.

    target_names : list[str] or {'old_name': 'new_name'} dict, optional
        Names of targets or classes. This argument can be used to provide
        human-readable class/target names for estimators which don't expose
        clss names themselves. It can be also used to rename estimator-provided
        classes before displaying them.

        This argument may be supported or not, depending on estimator type.

    targets : list, optional
        Order of class/target names to show. This argument can be also used
        to show information only for a subset of classes. It should be a list
        of class / target names which match either names provided by
        an estimator or names defined in ``target_names`` parameter.
        Must not be given with ``top_targets`` argument.

        In case of binary classification you can use this argument to
        set the class which probability or score should be displayed, with
        an appropriate explanation. By default a result for predicted class
        is shown. For example, you can use ``targets=[True]`` to always show
        result for a positive class, even if the predicted label is False.

        This argument may be supported or not, depending on estimator type.

    feature_names : list, optional
        A list of feature names. It allows to specify feature
        names when they are not provided by an estimator object.

        This argument may be supported or not, depending on estimator type.

    feature_re : str, optional
        Only feature names which match ``feature_re`` regex are returned
        (more precisely, ``re.search(feature_re, x)`` is checked).

    feature_filter : Callable[[str, float], bool], optional
        Only feature names for which ``feature_filter`` function returns True
        are returned. It must accept feature name and feature value.
        Missing features always have a NaN value.

    **kwargs: dict
        Keyword arguments. All keyword arguments are passed to
        concrete explain_prediction... implementations.

    Returns
    -------
    Explanation
        :class:`~.Explanation` result. Use one of the formatting functions from
        :mod:`eli5.formatters` to print it in a human-readable form.

        Explanation instances have repr which works well with
        IPython notebook, but it can be a better idea to use
        :func:`eli5.show_prediction` instead of :func:`eli5.explain_prediction`
        if you work with IPython: :func:`eli5.show_prediction` allows to
        customize formatting without a need to import :mod:`eli5.formatters`
        functions.
    """
    return Explanation(
        estimator=repr(estimator),
        error="estimator %r is not supported" % estimator,
    )


Instruction:
Write a Python 3 script to
calculate the directions between two locations.

Response:
def directions(client, origin, destination,
               mode=None, waypoints=None, alternatives=False, avoid=None,
               language=None, units=None, region=None, departure_time=None,
               arrival_time=None, optimize_waypoints=False, transit_mode=None,
               transit_routing_preference=None, traffic_model=None):
    """Get directions between an origin point and a destination point.

    :param origin: The address or latitude/longitude value from which you wish
        to calculate directions.
    :type origin: string, dict, list, or tuple

    :param destination: The address or latitude/longitude value from which
        you wish to calculate directions. You can use a place_id as destination
        by putting 'place_id:' as a preffix in the passing parameter.
    :type destination: string, dict, list, or tuple

    :param mode: Specifies the mode of transport to use when calculating
        directions. One of "driving", "walking", "bicycling" or "transit"
    :type mode: string

    :param waypoints: Specifies an array of waypoints. Waypoints alter a
        route by routing it through the specified location(s).
    :type waypoints: a single location, or a list of locations, where a
        location is a string, dict, list, or tuple

    :param alternatives: If True, more than one route may be returned in the
        response.
    :type alternatives: bool

    :param avoid: Indicates that the calculated route(s) should avoid the
        indicated features.
    :type avoid: list or string

    :param language: The language in which to return results.
    :type language: string

    :param units: Specifies the unit system to use when displaying results.
        "metric" or "imperial"
    :type units: string

    :param region: The region code, specified as a ccTLD ("top-level domain"
        two-character value.
    :type region: string

    :param departure_time: Specifies the desired time of departure.
    :type departure_time: int or datetime.datetime

    :param arrival_time: Specifies the desired time of arrival for transit
        directions. Note: you can't specify both departure_time and
        arrival_time.
    :type arrival_time: int or datetime.datetime

    :param optimize_waypoints: Optimize the provided route by rearranging the
        waypoints in a more efficient order.
    :type optimize_waypoints: bool

    :param transit_mode: Specifies one or more preferred modes of transit.
        This parameter may only be specified for requests where the mode is
        transit. Valid values are "bus", "subway", "train", "tram", "rail".
        "rail" is equivalent to ["train", "tram", "subway"].
    :type transit_mode: string or list of strings

    :param transit_routing_preference: Specifies preferences for transit
        requests. Valid values are "less_walking" or "fewer_transfers"
    :type transit_routing_preference: string

    :param traffic_model: Specifies the predictive travel time model to use.
        Valid values are "best_guess" or "optimistic" or "pessimistic".
        The traffic_model parameter may only be specified for requests where
        the travel mode is driving, and where the request includes a
        departure_time.
    :type units: string

    :rtype: list of routes
    """

    params = {
        "origin": convert.latlng(origin),
        "destination": convert.latlng(destination)
    }

    if mode:
        # NOTE(broady): the mode parameter is not validated by the Maps API
        # server. Check here to prevent silent failures.
        if mode not in ["driving", "walking", "bicycling", "transit"]:
            raise ValueError("Invalid travel mode.")
        params["mode"] = mode

    if waypoints:
        waypoints = convert.location_list(waypoints)
        if optimize_waypoints:
            waypoints = "optimize:true|" + waypoints
        params["waypoints"] = waypoints

    if alternatives:
        params["alternatives"] = "true"

    if avoid:
        params["avoid"] = convert.join_list("|", avoid)

    if language:
        params["language"] = language

    if units:
        params["units"] = units

    if region:
        params["region"] = region

    if departure_time:
        params["departure_time"] = convert.time(departure_time)

    if arrival_time:
        params["arrival_time"] = convert.time(arrival_time)

    if departure_time and arrival_time:
        raise ValueError("Should not specify both departure_time and"
                         "arrival_time.")

    if transit_mode:
        params["transit_mode"] = convert.join_list("|", transit_mode)

    if transit_routing_preference:
        params["transit_routing_preference"] = transit_routing_preference

    if traffic_model:
        params["traffic_model"] = traffic_model

    return client._request("/maps/api/directions/json", params).get("routes", [])


Instruction:
Can you generate a brief explanation for the following Python 3 code
def reverse_geocode(client, latlng, result_type=None, location_type=None,
                    language=None):
    """
    Reverse geocoding is the process of converting geographic coordinates into a
    human-readable address.

    :param latlng: The latitude/longitude value or place_id for which you wish
        to obtain the closest, human-readable address.
    :type latlng: string, dict, list, or tuple

    :param result_type: One or more address types to restrict results to.
    :type result_type: string or list of strings

    :param location_type: One or more location types to restrict results to.
    :type location_type: list of strings

    :param language: The language in which to return results.
    :type language: string

    :rtype: list of reverse geocoding results.
    """

    # Check if latlng param is a place_id string.
    #  place_id strings do not contain commas; latlng strings do.
    if convert.is_string(latlng) and ',' not in latlng:
        params = {"place_id": latlng}
    else:
        params = {"latlng": convert.latlng(latlng)}

    if result_type:
        params["result_type"] = convert.join_list("|", result_type)

    if location_type:
        params["location_type"] = convert.join_list("|", location_type)

    if language:
        params["language"] = language

    return client._request("/maps/api/geocode/json", params).get("results", [])

Response: Reverse geocoding for a given location.


Instruction:
Write a Python 3 function for
providing elevation data for a single location in the order they appear.

Response:
def elevation(client, locations):
    """
    Provides elevation data for locations provided on the surface of the
    earth, including depth locations on the ocean floor (which return negative
    values)

    :param locations: List of latitude/longitude values from which you wish
        to calculate elevation data.
    :type locations: a single location, or a list of locations, where a
        location is a string, dict, list, or tuple

    :rtype: list of elevation data responses
    """
    params = {"locations": convert.shortest_path(locations)}
    return client._request("/maps/api/elevation/json", params).get("results", [])


Instruction:
How would you code a function in Python 3 to
provide elevation data sampled along a path on the surface of the earth.

Response:
def elevation_along_path(client, path, samples):
    """
    Provides elevation data sampled along a path on the surface of the earth.

    :param path: An encoded polyline string, or a list of latitude/longitude
        values from which you wish to calculate elevation data.
    :type path: string, dict, list, or tuple

    :param samples: The number of sample points along a path for which to
        return elevation data.
    :type samples: int

    :rtype: list of elevation data responses
    """

    if type(path) is str:
        path = "enc:%s" % path
    else:
        path = convert.shortest_path(path)

    params = {
        "path": path,
        "samples": samples
    }

    return client._request("/maps/api/elevation/json", params).get("results", [])


Instruction:
How would you code a function in Python 3 to
convert a lat / lon pair to a comma - separated string.

Response:
def latlng(arg):
    """Converts a lat/lon pair to a comma-separated string.

    For example:

    sydney = {
        "lat" : -33.8674869,
        "lng" : 151.2069902
    }

    convert.latlng(sydney)
    # '-33.8674869,151.2069902'

    For convenience, also accepts lat/lon pair as a string, in
    which case it's returned unchanged.

    :param arg: The lat/lon pair.
    :type arg: string or dict or list or tuple
    """
    if is_string(arg):
        return arg

    normalized = normalize_lat_lng(arg)
    return "%s,%s" % (format_float(normalized[0]), format_float(normalized[1]))


Instruction:
Make a summary of the following Python 3 code
def normalize_lat_lng(arg):
    if isinstance(arg, dict):
        if "lat" in arg and "lng" in arg:
            return arg["lat"], arg["lng"]
        if "latitude" in arg and "longitude" in arg:
            return arg["latitude"], arg["longitude"]

    # List or tuple.
    if _is_list(arg):
        return arg[0], arg[1]

    raise TypeError(
        "Expected a lat/lng dict or tuple, "
        "but got %s" % type(arg).__name__)

Response: Normalizes the various lat and lng representations and return a tuple.


Instruction:
Here you have a function in Python 3, explain what it does
def location_list(arg):
    if isinstance(arg, tuple):
        # Handle the single-tuple lat/lng case.
        return latlng(arg)
    else:
        return "|".join([latlng(location) for location in as_list(arg)])

Response: Joins a list of locations into a pipe separated string.


Instruction:
Explain what the following Python 3 code does
def _is_list(arg):
    if isinstance(arg, dict):
        return False
    if isinstance(arg, str): # Python 3-only, as str has __iter__
        return False
    return (not _has_method(arg, "strip")
            and _has_method(arg, "__getitem__")
            or _has_method(arg, "__iter__"))

Response: Checks if arg is list - like. This excludes strings and dicts.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def is_string(val):
    try:
        basestring
    except NameError:
        return isinstance(val, str)
    return isinstance(val, basestring)

Response: Determines whether the passed value is a string safe for 2 or 3.


Instruction:
Write a Python 3 script for
converting the value into a unix time.

Response:
def time(arg):
    """Converts the value into a unix time (seconds since unix epoch).

    For example:
        convert.time(datetime.now())
        # '1409810596'

    :param arg: The time.
    :type arg: datetime.datetime or int
    """
    # handle datetime instances.
    if _has_method(arg, "timetuple"):
        arg = _time.mktime(arg.timetuple())

    if isinstance(arg, float):
        arg = int(arg)

    return str(arg)


Instruction:
Create a Python 3 function to
return true if the given object has a method with the given name.

Response:
def _has_method(arg, method):
    """Returns true if the given object has a method with the given name.

    :param arg: the object

    :param method: the method name
    :type method: string

    :rtype: bool
    """
    return hasattr(arg, method) and callable(getattr(arg, method))


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

    # Components may have multiple values per type, here we
    # expand them into individual key/value items, eg:
    # {"country": ["US", "AU"], "foo": 1} -> "country:AU", "country:US", "foo:1"
    def expand(arg):
        for k, v in arg.items():
            for item in as_list(v):
                yield "%s:%s" % (k, item)

    if isinstance(arg, dict):
        return "|".join(sorted(expand(arg)))

    raise TypeError(
        "Expected a dict for components, "
        "but got %s" % type(arg).__name__)

Response:
Converts a dict of components to the format expected by the Google Maps
    server.


Instruction:
Implement a function in Python 3 to
convert a lat - lng bounds dict to a comma - separated string.

Response:
def bounds(arg):
    """Converts a lat/lon bounds to a comma- and pipe-separated string.

    Accepts two representations:
    1) string: pipe-separated pair of comma-separated lat/lon pairs.
    2) dict with two entries - "southwest" and "northeast". See convert.latlng
    for information on how these can be represented.

    For example:

    sydney_bounds = {
        "northeast" : {
            "lat" : -33.4245981,
            "lng" : 151.3426361
        },
        "southwest" : {
            "lat" : -34.1692489,
            "lng" : 150.502229
        }
    }

    convert.bounds(sydney_bounds)
    # '-34.169249,150.502229|-33.424598,151.342636'

    :param arg: The bounds.
    :type arg: dict
    """

    if is_string(arg) and arg.count("|") == 1 and arg.count(",") == 2:
        return arg
    elif isinstance(arg, dict):
        if "southwest" in arg and "northeast" in arg:
            return "%s|%s" % (latlng(arg["southwest"]),
                              latlng(arg["northeast"]))

    raise TypeError(
        "Expected a bounds (southwest/northeast) dict, "
        "but got %s" % type(arg).__name__)


Instruction:
Explain what the following Python 3 code does
def decode_polyline(polyline):
    points = []
    index = lat = lng = 0

    while index < len(polyline):
        result = 1
        shift = 0
        while True:
            b = ord(polyline[index]) - 63 - 1
            index += 1
            result += b << shift
            shift += 5
            if b < 0x1f:
                break
        lat += (~result >> 1) if (result & 1) != 0 else (result >> 1)

        result = 1
        shift = 0
        while True:
            b = ord(polyline[index]) - 63 - 1
            index += 1
            result += b << shift
            shift += 5
            if b < 0x1f:
                break
        lng += ~(result >> 1) if (result & 1) != 0 else (result >> 1)

        points.append({"lat": lat * 1e-5, "lng": lng * 1e-5})

    return points

Response: Decodes a Polyline string into a list of lat / lng dicts.


Instruction:
Can you create a Python 3 function that
encodes a list of points into a polyline string.

Response:
def encode_polyline(points):
    """Encodes a list of points into a polyline string.

    See the developer docs for a detailed description of this encoding:
    https://developers.google.com/maps/documentation/utilities/polylinealgorithm

    :param points: a list of lat/lng pairs
    :type points: list of dicts or tuples

    :rtype: string
    """
    last_lat = last_lng = 0
    result = ""

    for point in points:
        ll = normalize_lat_lng(point)
        lat = int(round(ll[0] * 1e5))
        lng = int(round(ll[1] * 1e5))
        d_lat = lat - last_lat
        d_lng = lng - last_lng

        for v in [d_lat, d_lng]:
            v = ~(v << 1) if v < 0 else v << 1
            while v >= 0x20:
                result += (chr((0x20 | (v & 0x1f)) + 63))
                v >>= 5
            result += (chr(v + 63))

        last_lat = lat
        last_lng = lng

    return result


Instruction:
Create a Python 3 function to
get time zone for a location on the earth and optionally a timestamp.

Response:
def timezone(client, location, timestamp=None, language=None):
    """Get time zone for a location on the earth, as well as that location's
    time offset from UTC.

    :param location: The latitude/longitude value representing the location to
        look up.
    :type location: string, dict, list, or tuple

    :param timestamp: Timestamp specifies the desired time as seconds since
        midnight, January 1, 1970 UTC. The Time Zone API uses the timestamp to
        determine whether or not Daylight Savings should be applied. Times
        before 1970 can be expressed as negative values. Optional. Defaults to
        ``datetime.utcnow()``.
    :type timestamp: int or datetime.datetime

    :param language: The language in which to return results.
    :type language: string

    :rtype: dict
    """

    params = {
        "location": convert.latlng(location),
        "timestamp": convert.time(timestamp or datetime.utcnow())
    }

    if language:
        params["language"] = language

    return client._request( "/maps/api/timezone/json", params)


Instruction:
Write a Python 3 script for
snapping a path to the most likely roads travelled along a route.

Response:
def snap_to_roads(client, path, interpolate=False):
    """Snaps a path to the most likely roads travelled.

    Takes up to 100 GPS points collected along a route, and returns a similar
    set of data with the points snapped to the most likely roads the vehicle
    was traveling along.

    :param path: The path to be snapped.
    :type path: a single location, or a list of locations, where a
        location is a string, dict, list, or tuple

    :param interpolate: Whether to interpolate a path to include all points
        forming the full road-geometry. When true, additional interpolated
        points will also be returned, resulting in a path that smoothly follows
        the geometry of the road, even around corners and through tunnels.
        Interpolated paths may contain more points than the original path.
    :type interpolate: bool

    :rtype: A list of snapped points.
    """

    params = {"path": convert.location_list(path)}

    if interpolate:
        params["interpolate"] = "true"

    return client._request("/v1/snapToRoads", params,
                       base_url=_ROADS_BASE_URL,
                       accepts_clientid=False,
                       extract_body=_roads_extract).get("snappedPoints", [])


Instruction:
Implement a function in Python 3 to
find the closest road segments for each point.

Response:
def nearest_roads(client, points):
    """Find the closest road segments for each point

    Takes up to 100 independent coordinates, and returns the closest road
    segment for each point. The points passed do not need to be part of a
    continuous path.

    :param points: The points for which the nearest road segments are to be
        located.
    :type points: a single location, or a list of locations, where a
        location is a string, dict, list, or tuple

    :rtype: A list of snapped points.
    """

    params = {"points": convert.location_list(points)}

    return client._request("/v1/nearestRoads", params,
                       base_url=_ROADS_BASE_URL,
                       accepts_clientid=False,
                       extract_body=_roads_extract).get("snappedPoints", [])


Instruction:
Can you tell what is the following Python 3 function doing
def speed_limits(client, place_ids):

    params = [("placeId", place_id) for place_id in convert.as_list(place_ids)]

    return client._request("/v1/speedLimits", params,
                       base_url=_ROADS_BASE_URL,
                       accepts_clientid=False,
                       extract_body=_roads_extract).get("speedLimits", [])

Response: Returns the posted speed limit for given ROAD segments.


Instruction:
How would you implement a function in Python 3 that
returns the posted speed limit for the given path.

Response:
def snapped_speed_limits(client, path):
    """Returns the posted speed limit (in km/h) for given road segments.

    The provided points will first be snapped to the most likely roads the
    vehicle was traveling along.

    :param path: The path of points to be snapped.
    :type path: a single location, or a list of locations, where a
        location is a string, dict, list, or tuple

    :rtype: dict with a list of speed limits and a list of the snapped points.
    """

    params = {"path": convert.location_list(path)}

    return client._request("/v1/speedLimits", params,
                       base_url=_ROADS_BASE_URL,
                       accepts_clientid=False,
                       extract_body=_roads_extract)


Instruction:
Write a Python 3 script for
extracting a result from a Roads API HTTP response.

Response:
def _roads_extract(resp):
    """Extracts a result from a Roads API HTTP response."""

    try:
        j = resp.json()
    except:
        if resp.status_code != 200:
            raise googlemaps.exceptions.HTTPError(resp.status_code)

        raise googlemaps.exceptions.ApiError("UNKNOWN_ERROR",
                                             "Received a malformed response.")

    if "error" in j:
        error = j["error"]
        status = error["status"]

        if status == "RESOURCE_EXHAUSTED":
            raise googlemaps.exceptions._OverQueryLimit(status,
                                                        error.get("message"))

        raise googlemaps.exceptions.ApiError(status, error.get("message"))

    if resp.status_code != 200:
        raise googlemaps.exceptions.HTTPError(resp.status_code)

    return j


Instruction:
Given the following Python 3 function, write the documentation
def places(client, query, location=None, radius=None, language=None,
           min_price=None, max_price=None, open_now=False, type=None, region=None,
           page_token=None):
    """
    Places search.

    :param query: The text string on which to search, for example: "restaurant".
    :type query: string

    :param location: The latitude/longitude value for which you wish to obtain the
        closest, human-readable address.
    :type location: string, dict, list, or tuple

    :param radius: Distance in meters within which to bias results.
    :type radius: int

    :param language: The language in which to return results.
    :type language: string

    :param min_price: Restricts results to only those places with no less than
        this price level. Valid values are in the range from 0 (most affordable)
        to 4 (most expensive).
    :type min_price: int

    :param max_price: Restricts results to only those places with no greater
        than this price level. Valid values are in the range from 0 (most
        affordable) to 4 (most expensive).
    :type max_price: int

    :param open_now: Return only those places that are open for business at
        the time the query is sent.
    :type open_now: bool

    :param type: Restricts the results to places matching the specified type.
        The full list of supported types is available here:
        https://developers.google.com/places/supported_types
    :type type: string

    :param region: The region code, optional parameter.
        See more @ https://developers.google.com/places/web-service/search
    :type region: string

    :param page_token: Token from a previous search that when provided will
        returns the next page of results for the same search.
    :type page_token: string

    :rtype: result dict with the following keys:
        results: list of places
        html_attributions: set of attributions which must be displayed
        next_page_token: token for retrieving the next page of results
    """
    return _places(client, "text", query=query, location=location,
                   radius=radius, language=language, min_price=min_price,
                   max_price=max_price, open_now=open_now, type=type, region=region,
                   page_token=page_token)

Response: Search for places in a location.


Instruction:
Write a Python 3 script for
performing nearby search for places. :param location: The latitude/longitude value for which you wish to obtain the closest, human-readable address. :type location: string, dict, list, or tuple :param radius: Distance in meters within which to bias results. :type radius: int :param region: The region code, optional parameter. See more @ https://developers.google.com/places/web-service/search :type region: string :param keyword: A term to be matched against all content that Google has indexed for this place. :type keyword: string :param language: The language in which to return results. :type language: string :param min_price: Restricts results to only those places with no less than this price level. Valid values are in the range from 0 (most affordable) to 4 (most expensive). :type min_price: int :param max_price: Restricts results to only those places with no greater than this price level. Valid values are in the range from 0 (most affordable) to 4 (most expensive). :type max_price: int :param name: One or more terms to be matched against the names of places. :type name: string or list of strings :param open_now: Return only those places that are open for business at the time the query is sent. :type open_now: bool :param rank_by: Specifies the order in which results are listed. Possible values are: prominence (default), distance :type rank_by: string :param type: Restricts the results to places matching the specified type. The full list of supported types is available here: https://developers.google.com/places/supported_types :type type: string :param page_token: Token from a previous search that when provided will returns the next page of results for the same search. :type page_token: string :rtype: result dict with the following keys: status: status code results: list of places html_attributions: set of attributions which must be displayed next_page_token: token for retrieving the next page of results

Response:
def places_nearby(client, location=None, radius=None, keyword=None,
                  language=None, min_price=None, max_price=None, name=None,
                  open_now=False, rank_by=None, type=None, page_token=None):
    """
    Performs nearby search for places.

    :param location: The latitude/longitude value for which you wish to obtain the
                     closest, human-readable address.
    :type location: string, dict, list, or tuple

    :param radius: Distance in meters within which to bias results.
    :type radius: int

    :param region: The region code, optional parameter.
        See more @ https://developers.google.com/places/web-service/search
    :type region: string

    :param keyword: A term to be matched against all content that Google has
                    indexed for this place.
    :type keyword: string

    :param language: The language in which to return results.
    :type language: string

    :param min_price: Restricts results to only those places with no less than
                      this price level. Valid values are in the range from 0
                      (most affordable) to 4 (most expensive).
    :type min_price: int

    :param max_price: Restricts results to only those places with no greater
                      than this price level. Valid values are in the range
                      from 0 (most affordable) to 4 (most expensive).
    :type max_price: int

    :param name: One or more terms to be matched against the names of places.
    :type name: string or list of strings

    :param open_now: Return only those places that are open for business at
                     the time the query is sent.
    :type open_now: bool

    :param rank_by: Specifies the order in which results are listed.
                    Possible values are: prominence (default), distance
    :type rank_by: string

    :param type: Restricts the results to places matching the specified type.
        The full list of supported types is available here:
        https://developers.google.com/places/supported_types
    :type type: string

    :param page_token: Token from a previous search that when provided will
                       returns the next page of results for the same search.
    :type page_token: string

    :rtype: result dict with the following keys:
            status: status code
            results: list of places
            html_attributions: set of attributions which must be displayed
            next_page_token: token for retrieving the next page of results

    """
    if not location and not page_token:
        raise ValueError("either a location or page_token arg is required")
    if rank_by == "distance":
        if not (keyword or name or type):
            raise ValueError("either a keyword, name, or type arg is required "
                             "when rank_by is set to distance")
        elif radius is not None:
            raise ValueError("radius cannot be specified when rank_by is set to "
                             "distance")

    return _places(client, "nearby", location=location, radius=radius,
                   keyword=keyword, language=language, min_price=min_price,
                   max_price=max_price, name=name, open_now=open_now,
                   rank_by=rank_by, type=type, page_token=page_token)


Instruction:
Given the following Python 3 function, write the documentation
def places_radar(client, location, radius, keyword=None, min_price=None,
                 max_price=None, name=None, open_now=False, type=None):
    """
    Performs radar search for places.

    :param location: The latitude/longitude value for which you wish to obtain the
                     closest, human-readable address.
    :type location: string, dict, list, or tuple

    :param radius: Distance in meters within which to bias results.
    :type radius: int

    :param keyword: A term to be matched against all content that Google has
                    indexed for this place.
    :type keyword: string

    :param min_price: Restricts results to only those places with no less than
                      this price level. Valid values are in the range from 0
                      (most affordable) to 4 (most expensive).
    :type min_price: int

    :param max_price: Restricts results to only those places with no greater
                      than this price level. Valid values are in the range
                      from 0 (most affordable) to 4 (most expensive).
    :type max_price: int

    :param name: One or more terms to be matched against the names of places.
    :type name: string or list of strings

    :param open_now: Return only those places that are open for business at
                     the time the query is sent.
    :type open_now: bool

    :param type: Restricts the results to places matching the specified type.
        The full list of supported types is available here:
        https://developers.google.com/places/supported_types
    :type type: string

    :rtype: result dict with the following keys:
            status: status code
            results: list of places
            html_attributions: set of attributions which must be displayed

    """
    if not (keyword or name or type):
        raise ValueError("either a keyword, name, or type arg is required")

    from warnings import warn
    warn("places_radar is deprecated, see http://goo.gl/BGiumE",
         DeprecationWarning)

    return _places(client, "radar", location=location, radius=radius,
                   keyword=keyword, min_price=min_price, max_price=max_price,
                   name=name, open_now=open_now, type=type)

Response: Performs a radar search for places.


Instruction:
Make a summary of the following Python 3 code
def _places(client, url_part, query=None, location=None, radius=None,
            keyword=None, language=None, min_price=0, max_price=4, name=None,
            open_now=False, rank_by=None, type=None, region=None, page_token=None):
    """
    Internal handler for ``places``, ``places_nearby``, and ``places_radar``.
    See each method's docs for arg details.
    """

    params = {"minprice": min_price, "maxprice": max_price}

    if query:
        params["query"] = query
    if location:
        params["location"] = convert.latlng(location)
    if radius:
        params["radius"] = radius
    if keyword:
        params["keyword"] = keyword
    if language:
        params["language"] = language
    if name:
        params["name"] = convert.join_list(" ", name)
    if open_now:
        params["opennow"] = "true"
    if rank_by:
        params["rankby"] = rank_by
    if type:
        params["type"] = type
    if region:
        params["region"] = region
    if page_token:
        params["pagetoken"] = page_token

    url = "/maps/api/place/%ssearch/json" % url_part
    return client._request(url, params)

Response: Internal method for places search.


Instruction:
Write a Python 3 function for
returning a list of details for a single place.

Response:
def place(client, place_id, session_token=None, fields=None, language=None):
    """
    Comprehensive details for an individual place.

    :param place_id: A textual identifier that uniquely identifies a place,
        returned from a Places search.
    :type place_id: string

    :param session_token: A random string which identifies an autocomplete
                          session for billing purposes.
    :type session_token: string

    :param fields: The fields specifying the types of place data to return,
                   separated by a comma. For full details see:
                   https://cloud.google.com/maps-platform/user-guide/product-changes/#places
    :type input: list

    :param language: The language in which to return results.
    :type language: string

    :rtype: result dict with the following keys:
        result: dict containing place details
        html_attributions: set of attributions which must be displayed
    """
    params = {"placeid": place_id}

    if fields:
        invalid_fields = set(fields) - PLACES_DETAIL_FIELDS
        if invalid_fields:
            raise ValueError("Valid values for the `fields` param for "
                             "`place` are '%s', these given field(s) "
                             "are invalid: '%s'" % (
                                "', '".join(PLACES_DETAIL_FIELDS),
                                "', '".join(invalid_fields)))
        params["fields"] = convert.join_list(",", fields)

    if language:
        params["language"] = language
    if session_token:
        params["sessiontoken"] = session_token

    return client._request("/maps/api/place/details/json", params)


Instruction:
Write a Python 3 script for
downloading a photo from the Places API and returns an iterator of the image data.

Response:
def places_photo(client, photo_reference, max_width=None, max_height=None):
    """
    Downloads a photo from the Places API.

    :param photo_reference: A string identifier that uniquely identifies a
        photo, as provided by either a Places search or Places detail request.
    :type photo_reference: string

    :param max_width: Specifies the maximum desired width, in pixels.
    :type max_width: int

    :param max_height: Specifies the maximum desired height, in pixels.
    :type max_height: int

    :rtype: iterator containing the raw image data, which typically can be
        used to save an image file locally. For example:

        ```
        f = open(local_filename, 'wb')
        for chunk in client.places_photo(photo_reference, max_width=100):
            if chunk:
                f.write(chunk)
        f.close()
        ```
    """

    if not (max_width or max_height):
        raise ValueError("a max_width or max_height arg is required")

    params = {"photoreference": photo_reference}

    if max_width:
        params["maxwidth"] = max_width
    if max_height:
        params["maxheight"] = max_height

    # "extract_body" and "stream" args here are used to return an iterable
    # response containing the image file data, rather than converting from
    # json.
    response = client._request("/maps/api/place/photo", params,
                           extract_body=lambda response: response,
                           requests_kwargs={"stream": True})
    return response.iter_content()


Instruction:
Implement a Python 3 function for
returning a Place predictions given a textual search string and optional geographic bounds.

Response:
def places_autocomplete(client, input_text, session_token, offset=None,
                        location=None, radius=None, language=None, types=None,
                        components=None, strict_bounds=False):
    """
    Returns Place predictions given a textual search string and optional
    geographic bounds.

    :param input_text: The text string on which to search.
    :type input_text: string

    :param session_token: A random string which identifies an autocomplete
                          session for billing purposes.
    :type session_token: string

    :param offset: The position, in the input term, of the last character
                   that the service uses to match predictions. For example,
                   if the input is 'Google' and the offset is 3, the
                   service will match on 'Goo'.
    :type offset: int

    :param location: The latitude/longitude value for which you wish to obtain the
                     closest, human-readable address.
    :type location: string, dict, list, or tuple

    :param radius: Distance in meters within which to bias results.
    :type radius: int

    :param language: The language in which to return results.
    :type language: string

    :param types: Restricts the results to places matching the specified type.
        The full list of supported types is available here:
        https://developers.google.com/places/web-service/autocomplete#place_types
    :type types: string

    :param components: A component filter for which you wish to obtain a geocode.
        Currently, you can use components to filter by up to 5 countries for
        example: ``{'country': ['US', 'AU']}``
    :type components: dict

    :param strict_bounds: Returns only those places that are strictly within
        the region defined by location and radius.
    :type strict_bounds: bool

    :rtype: list of predictions

    """
    return _autocomplete(client, "", input_text, session_token=session_token,
                         offset=offset, location=location, radius=radius,
                         language=language, types=types, components=components,
                         strict_bounds=strict_bounds)


Instruction:
Implement a function in Python 3 to
return Place predictions given a textual search query such as pizza near New York and optional geographic bounds.

Response:
def places_autocomplete_query(client, input_text, offset=None, location=None,
                              radius=None, language=None):
    """
    Returns Place predictions given a textual search query, such as
    "pizza near New York", and optional geographic bounds.

    :param input_text: The text query on which to search.
    :type input_text: string

    :param offset: The position, in the input term, of the last character
        that the service uses to match predictions. For example, if the input
        is 'Google' and the offset is 3, the service will match on 'Goo'.
    :type offset: int

    :param location: The latitude/longitude value for which you wish to obtain the
        closest, human-readable address.
    :type location: string, dict, list, or tuple

    :param radius: Distance in meters within which to bias results.
    :type radius: number

    :param language: The language in which to return results.
    :type language: string

    :rtype: list of predictions
    """
    return _autocomplete(client, "query", input_text, offset=offset,
                         location=location, radius=radius, language=language)


Instruction:
Explain what the following Python 3 code does
def _autocomplete(client, url_part, input_text, session_token=None,
                  offset=None, location=None, radius=None, language=None,
                  types=None, components=None, strict_bounds=False):
    """
    Internal handler for ``autocomplete`` and ``autocomplete_query``.
    See each method's docs for arg details.
    """

    params = {"input": input_text}

    if session_token:
        params["sessiontoken"] = session_token
    if offset:
        params["offset"] = offset
    if location:
        params["location"] = convert.latlng(location)
    if radius:
        params["radius"] = radius
    if language:
        params["language"] = language
    if types:
        params["types"] = types
    if components:
        if len(components) != 1 or list(components.keys())[0] != "country":
            raise ValueError("Only country components are supported")
        params["components"] = convert.components(components)
    if strict_bounds:
        params["strictbounds"] = "true"

    url = "/maps/api/place/%sautocomplete/json" % url_part
    return client._request(url, params).get("predictions", [])

Response: Internal method for autocomplete_query.


Instruction:
How would you code a function in Python 3 to
extract the data from a geolocation response.

Response:
def _geolocation_extract(response):
    """
    Mimics the exception handling logic in ``client._get_body``, but
    for geolocation which uses a different response format.
    """
    body = response.json()
    if response.status_code in (200, 404):
        return body

    try:
        error = body["error"]["errors"][0]["reason"]
    except KeyError:
        error = None

    if response.status_code == 403:
        raise exceptions._OverQueryLimit(response.status_code, error)
    else:
        raise exceptions.ApiError(response.status_code, error)


Instruction:
How would you explain what the following Python 3 function does
def geolocate(client, home_mobile_country_code=None,
              home_mobile_network_code=None, radio_type=None, carrier=None,
              consider_ip=None, cell_towers=None, wifi_access_points=None):
    """
    The Google Maps Geolocation API returns a location and accuracy
    radius based on information about cell towers and WiFi nodes given.

    See https://developers.google.com/maps/documentation/geolocation/intro
    for more info, including more detail for each parameter below.

    :param home_mobile_country_code: The mobile country code (MCC) for
        the device's home network.
    :type home_mobile_country_code: string

    :param home_mobile_network_code: The mobile network code (MCC) for
        the device's home network.
    :type home_mobile_network_code: string

    :param radio_type: The mobile radio type. Supported values are
        lte, gsm, cdma, and wcdma. While this field is optional, it
        should be included if a value is available, for more accurate
        results.
    :type radio_type: string

    :param carrier: The carrier name.
    :type carrier: string

    :param consider_ip: Specifies whether to fall back to IP geolocation
        if wifi and cell tower signals are not available. Note that the
        IP address in the request header may not be the IP of the device.
    :type consider_ip: bool

    :param cell_towers: A list of cell tower dicts. See
        https://developers.google.com/maps/documentation/geolocation/intro#cell_tower_object
        for more detail.
    :type cell_towers: list of dicts

    :param wifi_access_points: A list of WiFi access point dicts. See
        https://developers.google.com/maps/documentation/geolocation/intro#wifi_access_point_object
        for more detail.
    :type wifi_access_points: list of dicts
    """

    params = {}
    if home_mobile_country_code is not None:
        params["homeMobileCountryCode"] = home_mobile_country_code
    if home_mobile_network_code is not None:
        params["homeMobileNetworkCode"] = home_mobile_network_code
    if radio_type is not None:
        params["radioType"] = radio_type
    if carrier is not None:
        params["carrier"] = carrier
    if consider_ip is not None:
        params["considerIp"] = consider_ip
    if cell_towers is not None:
        params["cellTowers"] = cell_towers
    if wifi_access_points is not None:
        params["wifiAccessPoints"] = wifi_access_points

    return client._request("/geolocation/v1/geolocate", {},  # No GET params
                           base_url=_GEOLOCATION_BASE_URL,
                           extract_body=_geolocation_extract,
                           post_json=params)

Response: This function returns a location and accuracy of a node given a set of cell towers and WiFi nodes.


Instruction:
How would you code a function in Python 3 to
get travel distance and time for a set of origins and destinations.

Response:
def distance_matrix(client, origins, destinations,
                    mode=None, language=None, avoid=None, units=None,
                    departure_time=None, arrival_time=None, transit_mode=None,
                    transit_routing_preference=None, traffic_model=None, region=None):
    """ Gets travel distance and time for a matrix of origins and destinations.

    :param origins: One or more locations and/or latitude/longitude values,
        from which to calculate distance and time. If you pass an address as
        a string, the service will geocode the string and convert it to a
        latitude/longitude coordinate to calculate directions.
    :type origins: a single location, or a list of locations, where a
        location is a string, dict, list, or tuple

    :param destinations: One or more addresses and/or lat/lng values, to
        which to calculate distance and time. If you pass an address as a
        string, the service will geocode the string and convert it to a
        latitude/longitude coordinate to calculate directions.
    :type destinations: a single location, or a list of locations, where a
        location is a string, dict, list, or tuple

    :param mode: Specifies the mode of transport to use when calculating
        directions. Valid values are "driving", "walking", "transit" or
        "bicycling".
    :type mode: string

    :param language: The language in which to return results.
    :type language: string

    :param avoid: Indicates that the calculated route(s) should avoid the
        indicated features. Valid values are "tolls", "highways" or "ferries".
    :type avoid: string

    :param units: Specifies the unit system to use when displaying results.
        Valid values are "metric" or "imperial".
    :type units: string

    :param departure_time: Specifies the desired time of departure.
    :type departure_time: int or datetime.datetime

    :param arrival_time: Specifies the desired time of arrival for transit
        directions. Note: you can't specify both departure_time and
        arrival_time.
    :type arrival_time: int or datetime.datetime

    :param transit_mode: Specifies one or more preferred modes of transit.
        This parameter may only be specified for requests where the mode is
        transit. Valid values are "bus", "subway", "train", "tram", "rail".
        "rail" is equivalent to ["train", "tram", "subway"].
    :type transit_mode: string or list of strings

    :param transit_routing_preference: Specifies preferences for transit
        requests. Valid values are "less_walking" or "fewer_transfers".
    :type transit_routing_preference: string

    :param traffic_model: Specifies the predictive travel time model to use.
        Valid values are "best_guess" or "optimistic" or "pessimistic".
        The traffic_model parameter may only be specified for requests where
        the travel mode is driving, and where the request includes a
        departure_time.

    :param region: Specifies the prefered region the geocoder should search
        first, but it will not restrict the results to only this region. Valid
        values are a ccTLD code.
    :type region: string

    :rtype: matrix of distances. Results are returned in rows, each row
        containing one origin paired with each destination.
    """

    params = {
        "origins": convert.location_list(origins),
        "destinations": convert.location_list(destinations)
    }

    if mode:
        # NOTE(broady): the mode parameter is not validated by the Maps API
        # server. Check here to prevent silent failures.
        if mode not in ["driving", "walking", "bicycling", "transit"]:
            raise ValueError("Invalid travel mode.")
        params["mode"] = mode

    if language:
        params["language"] = language

    if avoid:
        if avoid not in ["tolls", "highways", "ferries"]:
            raise ValueError("Invalid route restriction.")
        params["avoid"] = avoid

    if units:
        params["units"] = units

    if departure_time:
        params["departure_time"] = convert.time(departure_time)

    if arrival_time:
        params["arrival_time"] = convert.time(arrival_time)

    if departure_time and arrival_time:
        raise ValueError("Should not specify both departure_time and"
                         "arrival_time.")

    if transit_mode:
        params["transit_mode"] = convert.join_list("|", transit_mode)

    if transit_routing_preference:
        params["transit_routing_preference"] = transit_routing_preference

    if traffic_model:
        params["traffic_model"] = traffic_model

    if region:
        params["region"] = region

    return client._request("/maps/api/distancematrix/json", params)


Instruction:
Can you implement a function in Python 3 that
provides a single entry point for modifying all API methods. For now this is limited to allowing the client object to be modified with an `extra_params` keyword arg to each method, that is then used as the params for each web service request. Please note that this is an unsupported feature for advanced use only. It's also currently incompatibile with multiple threads, see GH #160.

Response:
def make_api_method(func):
    """
    Provides a single entry point for modifying all API methods.
    For now this is limited to allowing the client object to be modified
    with an `extra_params` keyword arg to each method, that is then used
    as the params for each web service request.

    Please note that this is an unsupported feature for advanced use only.
    It's also currently incompatibile with multiple threads, see GH #160.
    """
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        args[0]._extra_params = kwargs.pop("extra_params", None)
        result = func(*args, **kwargs)
        try:
            del args[0]._extra_params
        except AttributeError:
            pass
        return result
    return wrapper


Instruction:
Given the following Python 3 function, write the documentation
def sign_hmac(secret, payload):
    payload = payload.encode('ascii', 'strict')
    secret = secret.encode('ascii', 'strict')
    sig = hmac.new(base64.urlsafe_b64decode(secret), payload, hashlib.sha1)
    out = base64.urlsafe_b64encode(sig.digest())
    return out.decode('utf-8')

Response: Returns a base64 - encoded HMAC - SHA1 signature of a given string.


Instruction:
Make a summary of the following Python 3 code
def urlencode_params(params):
    # urlencode does not handle unicode strings in Python 2.
    # Firstly, normalize the values so they get encoded correctly.
    params = [(key, normalize_for_urlencode(val)) for key, val in params]
    # Secondly, unquote unreserved chars which are incorrectly quoted
    # by urllib.urlencode, causing invalid auth signatures. See GH #72
    # for more info.
    return requests.utils.unquote_unreserved(urlencode(params))

Response: URL encodes the parameters.


Instruction:
Make a summary of the following Python 3 code
def _request(self, url, params, first_request_time=None, retry_counter=0,
             base_url=_DEFAULT_BASE_URL, accepts_clientid=True,
             extract_body=None, requests_kwargs=None, post_json=None):
        """Performs HTTP GET/POST with credentials, returning the body as
        JSON.

        :param url: URL path for the request. Should begin with a slash.
        :type url: string

        :param params: HTTP GET parameters.
        :type params: dict or list of key/value tuples

        :param first_request_time: The time of the first request (None if no
            retries have occurred).
        :type first_request_time: datetime.datetime

        :param retry_counter: The number of this retry, or zero for first attempt.
        :type retry_counter: int

        :param base_url: The base URL for the request. Defaults to the Maps API
            server. Should not have a trailing slash.
        :type base_url: string

        :param accepts_clientid: Whether this call supports the client/signature
            params. Some APIs require API keys (e.g. Roads).
        :type accepts_clientid: bool

        :param extract_body: A function that extracts the body from the request.
            If the request was not successful, the function should raise a
            googlemaps.HTTPError or googlemaps.ApiError as appropriate.
        :type extract_body: function

        :param requests_kwargs: Same extra keywords arg for requests as per
            __init__, but provided here to allow overriding internally on a
            per-request basis.
        :type requests_kwargs: dict

        :raises ApiError: when the API returns an error.
        :raises Timeout: if the request timed out.
        :raises TransportError: when something went wrong while trying to
            exceute a request.
        """

        if not first_request_time:
            first_request_time = datetime.now()

        elapsed = datetime.now() - first_request_time
        if elapsed > self.retry_timeout:
            raise googlemaps.exceptions.Timeout()

        if retry_counter > 0:
            # 0.5 * (1.5 ^ i) is an increased sleep time of 1.5x per iteration,
            # starting at 0.5s when retry_counter=0. The first retry will occur
            # at 1, so subtract that first.
            delay_seconds = 0.5 * 1.5 ** (retry_counter - 1)

            # Jitter this value by 50% and pause.
            time.sleep(delay_seconds * (random.random() + 0.5))

        authed_url = self._generate_auth_url(url, params, accepts_clientid)

        # Default to the client-level self.requests_kwargs, with method-level
        # requests_kwargs arg overriding.
        requests_kwargs = requests_kwargs or {}
        final_requests_kwargs = dict(self.requests_kwargs, **requests_kwargs)

        # Determine GET/POST.
        requests_method = self.session.get
        if post_json is not None:
            requests_method = self.session.post
            final_requests_kwargs["json"] = post_json

        try:
            response = requests_method(base_url + authed_url,
                                       **final_requests_kwargs)
        except requests.exceptions.Timeout:
            raise googlemaps.exceptions.Timeout()
        except Exception as e:
            raise googlemaps.exceptions.TransportError(e)

        if response.status_code in _RETRIABLE_STATUSES:
            # Retry request.
            return self._request(url, params, first_request_time,
                                 retry_counter + 1, base_url, accepts_clientid,
                                 extract_body, requests_kwargs, post_json)

        # Check if the time of the nth previous query (where n is
        # queries_per_second) is under a second ago - if so, sleep for
        # the difference.
        if self.sent_times and len(self.sent_times) == self.queries_per_second:
            elapsed_since_earliest = time.time() - self.sent_times[0]
            if elapsed_since_earliest < 1:
                time.sleep(1 - elapsed_since_earliest)

        try:
            if extract_body:
                result = extract_body(response)
            else:
                result = self._get_body(response)
            self.sent_times.append(time.time())
            return result
        except googlemaps.exceptions._RetriableRequest as e:
            if isinstance(e, googlemaps.exceptions._OverQueryLimit) and not self.retry_over_query_limit:
                raise

            # Retry request.
            return self._request(url, params, first_request_time,
                                 retry_counter + 1, base_url, accepts_clientid,
                                 extract_body, requests_kwargs, post_json)

Response: Performs a HTTP GET or POST request.


Instruction:
Write a Python 3 function for
generating the path and query string portion of the request URL.

Response:
def _generate_auth_url(self, path, params, accepts_clientid):
        """Returns the path and query string portion of the request URL, first
        adding any necessary parameters.

        :param path: The path portion of the URL.
        :type path: string

        :param params: URL parameters.
        :type params: dict or list of key/value tuples

        :rtype: string

        """
        # Deterministic ordering through sorting by key.
        # Useful for tests, and in the future, any caching.
        extra_params = getattr(self, "_extra_params", None) or {}
        if type(params) is dict:
            params = sorted(dict(extra_params, **params).items())
        else:
            params = sorted(extra_params.items()) + params[:] # Take a copy.

        if accepts_clientid and self.client_id and self.client_secret:
            if self.channel:
                params.append(("channel", self.channel))
            params.append(("client", self.client_id))

            path = "?".join([path, urlencode_params(params)])
            sig = sign_hmac(self.client_secret, path)
            return path + "&signature=" + sig

        if self.key:
            params.append(("key", self.key))
            return path + "?" + urlencode_params(params)

        raise ValueError("Must provide API key for this API. It does not accept "
                         "enterprise credentials.")


Instruction:
Create a Python 3 function for
running all jobs that are scheduled to run.

Response:
def run_pending(self):
        """
        Run all jobs that are scheduled to run.

        Please note that it is *intended behavior that run_pending()
        does not run missed jobs*. For example, if you've registered a job
        that should run every minute and you only call run_pending()
        in one hour increments then your job won't be run 60 times in
        between but only once.
        """
        runnable_jobs = (job for job in self.jobs if job.should_run)
        for job in sorted(runnable_jobs):
            self._run_job(job)


Instruction:
How would you code a function in Python 3 to
run all jobs in the system.

Response:
def run_all(self, delay_seconds=0):
        """
        Run all jobs regardless if they are scheduled to run or not.

        A delay of `delay` seconds is added between each job. This helps
        distribute system load generated by the jobs more evenly
        over time.

        :param delay_seconds: A delay added between every executed job
        """
        logger.info('Running *all* %i jobs with %is delay inbetween',
                    len(self.jobs), delay_seconds)
        for job in self.jobs[:]:
            self._run_job(job)
            time.sleep(delay_seconds)


Instruction:
Can you write a function in Python 3 where it
deletes all scheduled jobs with the given tag or all jobs with the given tag.

Response:
def clear(self, tag=None):
        """
        Deletes scheduled jobs marked with the given tag, or all jobs
        if tag is omitted.

        :param tag: An identifier used to identify a subset of
                    jobs to delete
        """
        if tag is None:
            del self.jobs[:]
        else:
            self.jobs[:] = (job for job in self.jobs if tag not in job.tags)


Instruction:
Can you implement a function in Python 3 that
tags the job with one or more unique indentifiers.

Response:
def tag(self, *tags):
        """
        Tags the job with one or more unique indentifiers.

        Tags must be hashable. Duplicate tags are discarded.

        :param tags: A unique list of ``Hashable`` tags.
        :return: The invoked job instance
        """
        if not all(isinstance(tag, collections.Hashable) for tag in tags):
            raise TypeError('Tags must be hashable')
        self.tags.update(tags)
        return self


Instruction:
Create a Python 3 function for
returning the invoked job instance that represents the time that the job should be run at.

Response:
def at(self, time_str):
        """
        Specify a particular time that the job should be run at.

        :param time_str: A string in one of the following formats: `HH:MM:SS`,
            `HH:MM`,`:MM`, `:SS`. The format must make sense given how often
            the job is repeating; for example, a job that repeats every minute
            should not be given a string in the form `HH:MM:SS`. The difference
            between `:MM` and `:SS` is inferred from the selected time-unit
            (e.g. `every().hour.at(':30')` vs. `every().minute.at(':30')`).
        :return: The invoked job instance
        """
        if (self.unit not in ('days', 'hours', 'minutes')
                and not self.start_day):
            raise ScheduleValueError('Invalid unit')
        if not isinstance(time_str, str):
            raise TypeError('at() should be passed a string')
        if self.unit == 'days' or self.start_day:
            if not re.match(r'^([0-2]\d:)?[0-5]\d:[0-5]\d$', time_str):
                raise ScheduleValueError('Invalid time format')
        if self.unit == 'hours':
            if not re.match(r'^([0-5]\d)?:[0-5]\d$', time_str):
                raise ScheduleValueError(('Invalid time format for'
                                          ' an hourly job'))
        if self.unit == 'minutes':
            if not re.match(r'^:[0-5]\d$', time_str):
                raise ScheduleValueError(('Invalid time format for'
                                          ' a minutely job'))
        time_values = time_str.split(':')
        if len(time_values) == 3:
            hour, minute, second = time_values
        elif len(time_values) == 2 and self.unit == 'minutes':
            hour = 0
            minute = 0
            _, second = time_values
        else:
            hour, minute = time_values
            second = 0
        if self.unit == 'days' or self.start_day:
            hour = int(hour)
            if not (0 <= hour <= 23):
                raise ScheduleValueError('Invalid number of hours')
        elif self.unit == 'hours':
            hour = 0
        elif self.unit == 'minutes':
            hour = 0
            minute = 0
        minute = int(minute)
        second = int(second)
        self.at_time = datetime.time(hour, minute, second)
        return self


Instruction:
Implement a Python 3 function for
specifying the job_func that should be called every time the job runs. Any additional arguments are passed on to job_func when the job runs. :param job_func: The function to be scheduled :return: The invoked job instance

Response:
def do(self, job_func, *args, **kwargs):
        """
        Specifies the job_func that should be called every time the
        job runs.

        Any additional arguments are passed on to job_func when
        the job runs.

        :param job_func: The function to be scheduled
        :return: The invoked job instance
        """
        self.job_func = functools.partial(job_func, *args, **kwargs)
        try:
            functools.update_wrapper(self.job_func, job_func)
        except AttributeError:
            # job_funcs already wrapped by functools.partial won't have
            # __name__, __module__ or __doc__ and the update_wrapper()
            # call will fail.
            pass
        self._schedule_next_run()
        self.scheduler.jobs.append(self)
        return self


Instruction:
Implement a function in Python 3 to
run the job and immediately reschedule it.

Response:
def run(self):
        """
        Run the job and immediately reschedule it.

        :return: The return value returned by the `job_func`
        """
        logger.info('Running job %s', self)
        ret = self.job_func()
        self.last_run = datetime.datetime.now()
        self._schedule_next_run()
        return ret


Instruction:
Can you generate the documentation for the following Python 3 function
def _schedule_next_run(self):
        if self.unit not in ('seconds', 'minutes', 'hours', 'days', 'weeks'):
            raise ScheduleValueError('Invalid unit')

        if self.latest is not None:
            if not (self.latest >= self.interval):
                raise ScheduleError('`latest` is greater than `interval`')
            interval = random.randint(self.interval, self.latest)
        else:
            interval = self.interval

        self.period = datetime.timedelta(**{self.unit: interval})
        self.next_run = datetime.datetime.now() + self.period
        if self.start_day is not None:
            if self.unit != 'weeks':
                raise ScheduleValueError('`unit` should be \'weeks\'')
            weekdays = (
                'monday',
                'tuesday',
                'wednesday',
                'thursday',
                'friday',
                'saturday',
                'sunday'
            )
            if self.start_day not in weekdays:
                raise ScheduleValueError('Invalid start day')
            weekday = weekdays.index(self.start_day)
            days_ahead = weekday - self.next_run.weekday()
            if days_ahead <= 0:  # Target day already happened this week
                days_ahead += 7
            self.next_run += datetime.timedelta(days_ahead) - self.period
        if self.at_time is not None:
            if (self.unit not in ('days', 'hours', 'minutes')
                    and self.start_day is None):
                raise ScheduleValueError(('Invalid unit without'
                                          ' specifying start day'))
            kwargs = {
                'second': self.at_time.second,
                'microsecond': 0
            }
            if self.unit == 'days' or self.start_day is not None:
                kwargs['hour'] = self.at_time.hour
            if self.unit in ['days', 'hours'] or self.start_day is not None:
                kwargs['minute'] = self.at_time.minute
            self.next_run = self.next_run.replace(**kwargs)
            # If we are running for the first time, make sure we run
            # at the specified time *today* (or *this hour*) as well
            if not self.last_run:
                now = datetime.datetime.now()
                if (self.unit == 'days' and self.at_time > now.time() and
                        self.interval == 1):
                    self.next_run = self.next_run - datetime.timedelta(days=1)
                elif self.unit == 'hours' \
                        and self.at_time.minute > now.minute \
                        or (self.at_time.minute == now.minute
                            and self.at_time.second > now.second):
                    self.next_run = self.next_run - datetime.timedelta(hours=1)
                elif self.unit == 'minutes' \
                        and self.at_time.second > now.second:
                    self.next_run = self.next_run - \
                                    datetime.timedelta(minutes=1)
        if self.start_day is not None and self.at_time is not None:
            # Let's see if we will still make that time we specified today
            if (self.next_run - datetime.datetime.now()).days >= 7:
                self.next_run -= self.period

Response: Compute the instant when this job should run next.


Instruction:
Implement a function in Python 3 to
create an Issuer Credential object.

Response:
async def create(source_id: str, attrs: dict, cred_def_handle: int, name: str, price: str):
        """
            Creates a Class representing an Issuer Credential
            :param source_id: Tag associated by user of sdk
            :param attrs: attributes that will form the credential
            :param cred_def_handle: Handle from previously created credential def object
            :param name: Name given to the Credential
            :param price: Price, in tokens, required as payment for the issuance of the credential.

            Example:
            source_id = '1'
            cred_def_handle = 1
            attrs = {'key': 'value', 'key2': 'value2', 'key3': 'value3'}
            name = 'Credential Name'
            issuer_did = '8XFh8yBzrpJQmNyZzgoTqB'
            phone_number = '8019119191'
            price = 1
            issuer_credential = await IssuerCredential.create(source_id, attrs, cred_def_handle, name, price)
        """
        constructor_params = (source_id, attrs, cred_def_handle, name, price)

        c_source_id = c_char_p(source_id.encode('utf-8'))
        c_cred_def_handle = c_uint32(cred_def_handle)
        c_price = c_char_p(price.encode('utf-8'))
        # default institution_did in config is used as issuer_did
        c_issuer_did = None
        c_data = c_char_p(json.dumps(attrs).encode('utf-8'))
        c_name = c_char_p(name.encode('utf-8'))
        c_params = (c_source_id, c_cred_def_handle, c_issuer_did, c_data, c_name, c_price)

        return await IssuerCredential._create("vcx_issuer_create_credential",
                                              constructor_params,
                                              c_params)


Instruction:
How would you explain what the following Python 3 function does
async def deserialize(data: dict):
        issuer_credential = await IssuerCredential._deserialize("vcx_issuer_credential_deserialize",
                                                      json.dumps(data),
                                                      data.get('data').get('source_id'),
                                                      data.get('data').get('price'),
                                                      data.get('data').get('credential_attributes'),
                                                      data.get('data').get('schema_seq_no'),
                                                      data.get('data').get('credential_request'))
        return issuer_credential

Response: Deserialize a dict representing a serialized IssuerCredential object.


Instruction:
How would you explain what the following Python 3 function does
async def send_offer(self, connection: Connection):
        if not hasattr(IssuerCredential.send_offer, "cb"):
            self.logger.debug("vcx_issuer_send_credential_offer: Creating callback")
            IssuerCredential.send_offer.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32))

        c_credential_handle = c_uint32(self.handle)
        c_connection_handle = c_uint32(connection.handle)

        await do_call('vcx_issuer_send_credential_offer',
                      c_credential_handle,
                      c_connection_handle,
                      IssuerCredential.send_offer.cb)

Response: Sends an offer to a prover.


Instruction:
Explain what the following Python 3 code does
async def revoke_credential(self):
        if not hasattr(IssuerCredential.revoke_credential, "cb"):
            self.logger.debug("vcx_issuer_revoke_credential: Creating callback")
            IssuerCredential.revoke_credential.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32))

        c_credential_handle = c_uint32(self.handle)

        await do_call('vcx_issuer_revoke_credential',
                      c_credential_handle,
                      IssuerCredential.revoke_credential.cb)

Response:
Revokes a credential.
        :return: None
            Example:
            credential.revoke_credential()


Instruction:
Can you tell what is the following Python 3 function doing
async def create_wallet(config: str,
                        credentials: str) -> None:
    """
    Creates a new secure wallet with the given unique name.

    :param config: Wallet configuration json.
     {
       "id": string, Identifier of the wallet.
             Configured storage uses this identifier to lookup exact wallet data placement.
       "storage_type": optional<string>, Type of the wallet storage. Defaults to 'default'.
                      'Default' storage type allows to store wallet data in the local file.
                      Custom storage types can be registered with indy_register_wallet_storage call.
       "storage_config": optional<object>, Storage configuration json. Storage type defines set of supported keys.
                         Can be optional if storage supports default configuration.
                          For 'default' storage type configuration is:
       {
         "path": optional<string>, Path to the directory with wallet files.
                 Defaults to $HOME/.indy_client/wallet.
                 Wallet will be stored in the file {path}/{id}/sqlite.db
       }
     }
    :param credentials: Wallet credentials json
     {
       "key": string, Key or passphrase used for wallet key derivation.
                      Look to key_derivation_method param for information about supported key derivation methods.
       "storage_credentials": optional<object> Credentials for wallet storage. Storage type defines set of supported keys.
                              Can be optional if storage supports default configuration.
                               For 'default' storage type should be empty.
       "key_derivation_method": optional<string> Algorithm to use for wallet key derivation:
                                ARGON2I_MOD - derive secured wallet master key (used by default)
                                ARGON2I_INT - derive secured wallet master key (less secured but faster)
                                RAW - raw wallet key master provided (skip derivation).
                                      RAW keys can be generated with generate_wallet_key call
     }
    :return: Error code
    """

    logger = logging.getLogger(__name__)
    logger.debug("create_wallet: >>> config: %r, credentials: %r",
                 config,
                 credentials)

    if not hasattr(create_wallet, "cb"):
        logger.debug("create_wallet: Creating callback")
        create_wallet.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32))

    c_config = c_char_p(config.encode('utf-8'))
    c_credentials = c_char_p(credentials.encode('utf-8'))

    await do_call('indy_create_wallet',
                  c_config,
                  c_credentials,
                  create_wallet.cb)

    logger.debug("create_wallet: <<<")

Response: Create secure wallet with the given unique name.


Instruction:
Here you have a function in Python 3, explain what it does
async def close_wallet(handle: int) -> None:

    logger = logging.getLogger(__name__)
    logger.debug("close_wallet: >>> handle: %i", handle)

    if not hasattr(close_wallet, "cb"):
        logger.debug("close_wallet: Creating callback")
        close_wallet.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32))

    c_handle = c_int32(handle)

    await do_call('indy_close_wallet',
                  c_handle,
                  close_wallet.cb)

    logger.debug("close_wallet: <<<")

Response: Closes opened wallet and frees allocated resources.


Instruction:
Can you generate the documentation for the following Python 3 function
async def export_wallet(handle: int,
                        export_config_json: str) -> None:
    """
    Exports opened wallet to the file.

    :param handle: wallet handle returned by indy_open_wallet.
    :param export_config_json: JSON containing settings for input operation.
       {
          "path": path of the file that contains exported wallet content
          "key": string, Key or passphrase used for wallet export key derivation.
                         Look to key_derivation_method param for information about supported key derivation methods.
          "key_derivation_method": optional<string> algorithm to use for export key derivation:
                                ARGON2I_MOD - derive secured wallet export key (used by default)
                                ARGON2I_INT - derive secured wallet export key (less secured but faster)
                                RAW - raw wallet export key provided (skip derivation).
                                      RAW keys can be generated with generate_wallet_key call
       }
    :return:
    """

    logger = logging.getLogger(__name__)
    logger.debug("export_wallet: >>> handle: %r, export_config_json: %r",
                 handle,
                 export_config_json)

    if not hasattr(export_wallet, "cb"):
        logger.debug("export_wallet: Creating callback")
        export_wallet.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32))

    c_export_config_json = c_char_p(export_config_json.encode('utf-8'))

    await do_call('indy_export_wallet',
                  handle,
                  c_export_config_json,
                  export_wallet.cb)

    logger.debug("export_wallet: <<<")

Response: Exports opened wallet to the file.


Instruction:
Implement a Python 3 function for
creating a new secure wallet with the given unique name and then imports its content according to fields provided in import_config_json.

Response:
async def import_wallet(config: str,
                        credentials: str,
                        import_config_json: str) -> None:
    """
    Creates a new secure wallet with the given unique name and then imports its content
    according to fields provided in import_config
    This can be seen as an indy_create_wallet call with additional content import

    :param config: Wallet configuration json.
     {
       "id": string, Identifier of the wallet.
             Configured storage uses this identifier to lookup exact wallet data placement.
       "storage_type": optional<string>, Type of the wallet storage. Defaults to 'default'.
                      'Default' storage type allows to store wallet data in the local file.
                      Custom storage types can be registered with indy_register_wallet_storage call.
       "storage_config": optional<object>, Storage configuration json. Storage type defines set of supported keys.
                         Can be optional if storage supports default configuration.
                         For 'default' storage type configuration is:
       {
         "path": optional<string>, Path to the directory with wallet files.
                 Defaults to $HOME/.indy_client/wallet.
                 Wallet will be stored in the file {path}/{id}/sqlite.db
       }
     }
    :param credentials: Wallet credentials json
     {
       "key": string, Key or passphrase used for wallet key derivation.
                      Look to key_derivation_method param for information about supported key derivation methods.
       "storage_credentials": optional<object> Credentials for wallet storage. Storage type defines set of supported keys.
                              Can be optional if storage supports default configuration.
                              For 'default' storage type should be empty.
       "key_derivation_method": optional<string> Algorithm to use for wallet key derivation:
                                 ARGON2I_MOD - derive secured wallet master key (used by default)
                                 ARGON2I_INT - derive secured wallet master key (less secured but faster)
                                 RAW - raw wallet key master provided (skip derivation).
                                       RAW keys can be generated with generate_wallet_key call
     }
    :param import_config_json: JSON containing settings for input operationЖ {
     "path": path of the file that contains exported wallet content
     "key": key used for export of the wallet
   }
    :return: Error code
    """

    logger = logging.getLogger(__name__)
    logger.debug("import_wallet: >>> config: %r, credentials: %r, import_config_json: %r",
                 config,
                 credentials,
                 import_config_json)

    if not hasattr(import_wallet, "cb"):
        logger.debug("import_wallet: Creating callback")
        import_wallet.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32))

    c_config = c_char_p(config.encode('utf-8'))
    c_credentials = c_char_p(credentials.encode('utf-8'))
    c_import_config_json = c_char_p(import_config_json.encode('utf-8'))

    await do_call('indy_import_wallet',
                  c_config,
                  c_credentials,
                  c_import_config_json,
                  import_wallet.cb)

    logger.debug("import_wallet: <<<")


Instruction:
Can you generate the documentation for the following Python 3 function
async def generate_wallet_key(config: Optional[str]) -> str:

    logger = logging.getLogger(__name__)
    logger.debug("generate_wallet_key: >>> config: %r",
                 config)

    if not hasattr(generate_wallet_key, "cb"):
        logger.debug("generate_wallet_key: Creating callback")
        generate_wallet_key.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_char_p))

    c_config = c_char_p(config.encode('utf-8')) if config is not None else None

    key = await do_call('indy_generate_wallet_key',
                        c_config,
                        generate_wallet_key.cb)

    res = key.decode()

    logger.debug("generate_wallet_key: <<< res: %r", res)
    return res

Response: Generate wallet master key.


Instruction:
Can you write a function in Python 3 where it
creates credential schema entity that describes credential attributes list and allows credentials and interoperability.

Response:
async def issuer_create_schema(issuer_did: str,
                               name: str,
                               version: str,
                               attrs: str) -> (str, str):
    """
    Create credential schema entity that describes credential attributes list and allows credentials
    interoperability.

    Schema is public and intended to be shared with all anoncreds workflow actors usually by publishing SCHEMA transaction
    to Indy distributed ledger.

    It is IMPORTANT for current version POST Schema in Ledger and after that GET it from Ledger
    with correct seq_no to save compatibility with Ledger.
    After that can call indy_issuer_create_and_store_credential_def to build corresponding Credential Definition.

    :param issuer_did: DID of schema issuer
    :param name: a name the schema
    :param version: a version of the schema
    :param attrs: a list of schema attributes descriptions (the number of attributes should be less or equal than 125)
    :return:
        schema_id: identifier of created schema
        schema_json: schema as json
    """

    logger = logging.getLogger(__name__)
    logger.debug("issuer_create_schema: >>> issuer_did: %r, name: %r, version: %r, attrs: %r",
                 issuer_did,
                 name,
                 version,
                 attrs)

    if not hasattr(issuer_create_schema, "cb"):
        logger.debug("issuer_create_schema: Creating callback")
        issuer_create_schema.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32, c_char_p, c_char_p))

    c_issuer_did = c_char_p(issuer_did.encode('utf-8'))
    c_name = c_char_p(name.encode('utf-8'))
    c_version = c_char_p(version.encode('utf-8'))
    c_attrs = c_char_p(attrs.encode('utf-8'))

    (schema_id, schema_json) = await do_call('indy_issuer_create_schema',
                                             c_issuer_did,
                                             c_name,
                                             c_version,
                                             c_attrs,
                                             issuer_create_schema.cb)

    res = (schema_id.decode(), schema_json.decode())
    logger.debug("issuer_create_schema: <<< res: %r", res)
    return res