Instruction:
Write a Python 3 function that can
return a boolean from any of a range of values.

Response:
def getbool(value):
    """
    Returns a boolean from any of a range of values. Returns None for
    unrecognized values. Numbers other than 0 and 1 are considered
    unrecognized.

    >>> getbool(True)
    True
    >>> getbool(1)
    True
    >>> getbool('1')
    True
    >>> getbool('t')
    True
    >>> getbool(2)
    >>> getbool(0)
    False
    >>> getbool(False)
    False
    >>> getbool('n')
    False
    """
    value = str(value).lower()
    if value in ['1', 't', 'true', 'y', 'yes']:
        return True
    elif value in ['0', 'f', 'false', 'n', 'no']:
        return False
    return None


Instruction:
Here you have a function in Python 3, explain what it does
def require_one_of(_return=False, **kwargs):

    # Two ways to count number of non-None parameters:
    #
    # 1. sum([1 if v is not None else 0 for v in kwargs.values()])
    #
    #    Using a list comprehension instead of a generator comprehension as the
    #    parameter to `sum` is faster on both Python 2 and 3.
    #
    # 2. len(kwargs) - kwargs.values().count(None)
    #
    #    This is 2x faster than the first method under Python 2.7. Unfortunately,
    #    it doesn't work in Python 3 because `kwargs.values()` is a view that doesn't
    #    have a `count` method. It needs to be cast into a tuple/list first, but
    #    remains faster despite the cast's slowdown. Tuples are faster than lists.

    if six.PY3:  # pragma: no cover
        count = len(kwargs) - tuple(kwargs.values()).count(None)
    else:  # pragma: no cover
        count = len(kwargs) - kwargs.values().count(None)

    if count == 0:
        raise TypeError("One of these parameters is required: " + ', '.join(kwargs.keys()))
    elif count != 1:
        raise TypeError("Only one of these parameters is allowed: " + ', '.join(kwargs.keys()))

    if _return:
        keys, values = zip(*[(k, 1 if v is not None else 0) for k, v in kwargs.items()])
        k = keys[values.index(1)]
        return k, kwargs[k]

Response: Validator that raises a TypeError if one and only one parameter is not specified.


Instruction:
Here you have a function in Python 3, explain what it does
def unicode_http_header(value):
    if six.PY3:  # pragma: no cover
        # email.header.decode_header expects strings, not bytes. Your input data may be in bytes.
        # Since these bytes are almost always ASCII, calling `.decode()` on it without specifying
        # a charset should work fine.
        if isinstance(value, six.binary_type):
            value = value.decode()
    return u''.join([six.text_type(s, e or 'iso-8859-1') if not isinstance(s, six.text_type) else s
        for s, e in decode_header(value)])

Response: r Convert an ASCII HTTP header string into a unicode string with the appropriate encoding applied.


Instruction:
Implement a function in Python 3 to
return a list of timezones sorted by offset from UTC.

Response:
def sorted_timezones():
    """
    Return a list of timezones sorted by offset from UTC.
    """
    def hourmin(delta):
        if delta.days < 0:
            hours, remaining = divmod(86400 - delta.seconds, 3600)
        else:
            hours, remaining = divmod(delta.seconds, 3600)
        minutes, remaining = divmod(remaining, 60)
        return hours, minutes

    now = datetime.utcnow()
    # Make a list of country code mappings
    timezone_country = {}
    for countrycode in pytz.country_timezones:
        for timezone in pytz.country_timezones[countrycode]:
            timezone_country[timezone] = countrycode

    # Make a list of timezones, discarding the US/* and Canada/* zones since they aren't reliable for
    # DST, and discarding UTC and GMT since timezones in that zone have their own names
    timezones = [(pytz.timezone(tzname).utcoffset(now, is_dst=False), tzname) for tzname in pytz.common_timezones
        if not tzname.startswith('US/') and not tzname.startswith('Canada/') and tzname not in ('GMT', 'UTC')]
    # Sort timezones by offset from UTC and their human-readable name
    presorted = [(delta, '%s%s - %s%s (%s)' % (
        (delta.days < 0 and '-') or (delta.days == 0 and delta.seconds == 0 and ' ') or '+',
        '%02d:%02d' % hourmin(delta),
        (pytz.country_names[timezone_country[name]] + ': ') if name in timezone_country else '',
        name.replace('_', ' '),
        pytz.timezone(name).tzname(now, is_dst=False)), name) for delta, name in timezones]
    presorted.sort()
    # Return a list of (timezone, label) with the timezone offset included in the label.
    return [(name, label) for (delta, label, name) in presorted]


Instruction:
Can you tell what is the following Python 3 function doing
def namespace_from_url(url):
    parsed = urlparse(url)
    if parsed.hostname is None or parsed.hostname in ['localhost', 'localhost.localdomain'] or (
            _ipv4_re.search(parsed.hostname)):
        return None

    namespace = parsed.hostname.split('.')
    namespace.reverse()
    if namespace and not namespace[0]:
        namespace.pop(0)
    if namespace and namespace[-1] == 'www':
        namespace.pop(-1)
    return type(url)('.'.join(namespace))

Response: Construct a dotted namespace string from a URL.


Instruction:
Can you generate the documentation for the following Python 3 function
def base_domain_matches(d1, d2):
    r1 = tldextract.extract(d1)
    r2 = tldextract.extract(d2)
    # r1 and r2 contain subdomain, domain and suffix.
    # We want to confirm that domain and suffix match.
    return r1.domain == r2.domain and r1.suffix == r2.suffix

Response: Check if two domains have the same base domain.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def MarkdownColumn(name, deferred=False, group=None, **kwargs):
    return composite(MarkdownComposite,
        Column(name + '_text', UnicodeText, **kwargs),
        Column(name + '_html', UnicodeText, **kwargs),
        deferred=deferred, group=group or name
    )

Response: Create a composite column that autogenerates HTML from Markdown text and stores data in db columns named with _html and _text prefixes.


Instruction:
Write a Python 3 function for
converting plain dictionaries to MutableDict.

Response:
def coerce(cls, key, value):
        """Convert plain dictionaries to MutableDict."""

        if not isinstance(value, MutableDict):
            if isinstance(value, dict):
                return MutableDict(value)
            elif isinstance(value, six.string_types):
                # Assume JSON string
                if value:
                    return MutableDict(simplejson.loads(value, use_decimal=True))
                else:
                    return MutableDict()  # Empty value is an empty dict

            # this call will raise ValueError
            return Mutable.coerce(key, value)
        else:
            return value


Instruction:
Can you generate the documentation for the following Python 3 function
def require(self, *namespecs):
        blacklist = set([n[1:] for n in namespecs if n.startswith('!')])
        not_blacklist = [n for n in namespecs if not n.startswith('!')]
        return Bundle(*[bundle for name, version, bundle
            in self._require_recursive(*not_blacklist) if name not in blacklist])

Response: Return a bundle of the requested assets and their dependencies.


Instruction:
Can you implement a function in Python 3 that
returns the state manager current state label for the current state

Response:
def _state_invalid(self):
        """
        If the state is invalid for the transition, return details on what didn't match

        :return: Tuple of (state manager, current state, label for current state)
        """
        for statemanager, conditions in self.statetransition.transitions.items():
            current_state = getattr(self.obj, statemanager.propname)
            if conditions['from'] is None:
                state_valid = True
            else:
                mstate = conditions['from'].get(current_state)
                state_valid = mstate and mstate(self.obj)
            if state_valid and conditions['if']:
                state_valid = all(v(self.obj) for v in conditions['if'])
            if not state_valid:
                return statemanager, current_state, statemanager.lenum.get(current_state)


Instruction:
How would you code a function in Python 3 to
add a group of managed states.

Response:
def add_state_group(self, name, *states):
        """
        Add a group of managed states. Groups can be specified directly in the
        :class:`~coaster.utils.classes.LabeledEnum`. This method is only useful
        for grouping a conditional state with existing states. It cannot be
        used to form a group of groups.

        :param str name: Name of this group
        :param states: :class:`ManagedState` instances to be grouped together
        """
        # See `_add_state_internal` for explanation of the following
        if hasattr(self, name):
            raise AttributeError(
                "State group name %s conflicts with existing attribute in the state manager" % name)
        mstate = ManagedStateGroup(name, self, states)
        self.states[name] = mstate
        setattr(self, name, mstate)
        setattr(self, 'is_' + name.lower(), mstate)


Instruction:
Write a Python 3 function for
adding a conditional state that combines an existing state with a validator that must also pass.

Response:
def add_conditional_state(self, name, state, validator, class_validator=None, cache_for=None, label=None):
        """
        Add a conditional state that combines an existing state with a validator
        that must also pass. The validator receives the object on which the property
        is present as a parameter.

        :param str name: Name of the new state
        :param ManagedState state: Existing state that this is based on
        :param validator: Function that will be called with the host object as a parameter
        :param class_validator: Function that will be called when the state is queried
            on the class instead of the instance. Falls back to ``validator`` if not specified.
            Receives the class as the parameter
        :param cache_for: Integer or function that indicates how long ``validator``'s
            result can be cached (not applicable to ``class_validator``). ``None`` implies
            no cache, ``0`` implies indefinite cache (until invalidated by a transition)
            and any other integer is the number of seconds for which to cache the assertion
        :param label: Label for this state (string or 2-tuple)

        TODO: `cache_for`'s implementation is currently pending a test case demonstrating
        how it will be used.
        """
        # We'll accept a ManagedState with grouped values, but not a ManagedStateGroup
        if not isinstance(state, ManagedState):
            raise TypeError("Not a managed state: %s" % repr(state))
        elif state.statemanager != self:
            raise ValueError("State %s is not associated with this state manager" % repr(state))
        if isinstance(label, tuple) and len(label) == 2:
            label = NameTitle(*label)
        self._add_state_internal(name, state.value, label=label,
            validator=validator, class_validator=class_validator, cache_for=cache_for)


Instruction:
How would you explain what the following Python 3 function does
def transition(self, from_, to, if_=None, **data):
        def decorator(f):
            if isinstance(f, StateTransition):
                f.add_transition(self, from_, to, if_, data)
                st = f
            else:
                st = StateTransition(f, self, from_, to, if_, data)
            self.transitions.append(st.name)
            return st

        return decorator

Response: Decorator to add a transition to one state to another.


Instruction:
Create a Python 3 function to
decorate a method that may be called if the given state is currently active. Registers a transition internally, but does not change the state. :param from_: Required state to allow this call (can be a state group) :param if_: Validator(s) that, given the object, must all return True for the call to proceed :param data: Additional metadata, stored on the `StateTransition` object as a :attr:`data` attribute

Response:
def requires(self, from_, if_=None, **data):
        """
        Decorates a method that may be called if the given state is currently active.
        Registers a transition internally, but does not change the state.

        :param from_: Required state to allow this call (can be a state group)
        :param if_: Validator(s) that, given the object, must all return True for the call to proceed
        :param data: Additional metadata, stored on the `StateTransition` object as a :attr:`data` attribute
        """
        return self.transition(from_, None, if_, **data)


Instruction:
Can you write a function in Python 3 where it
returns a SQL CHECK constraint string given a column name and a LabeledEnum

Response:
def check_constraint(column, lenum, **kwargs):
        """
        Returns a SQL CHECK constraint string given a column name and a
        :class:`~coaster.utils.classes.LabeledEnum`.

        Alembic may not detect the CHECK constraint when autogenerating
        migrations, so you may need to do this manually using the Python
        console to extract the SQL string::

            from coaster.sqlalchemy import StateManager
            from your_app.models import YOUR_ENUM

            print str(StateManager.check_constraint('your_column', YOUR_ENUM).sqltext)

        :param str column: Column name
        :param LabeledEnum lenum: :class:`~coaster.utils.classes.LabeledEnum` to retrieve valid values from
        :param kwargs: Additional options passed to CheckConstraint
        """
        return CheckConstraint(
            str(column_constructor(column).in_(lenum.keys()).compile(compile_kwargs={'literal_binds': True})),
            **kwargs)


Instruction:
Implement a function in Python 3 to
return the best match for this scalar state.

Response:
def bestmatch(self):
        """
        Best matching current scalar state (direct or conditional), only
        applicable when accessed via an instance.
        """
        if self.obj is not None:
            for mstate in self.statemanager.all_states_by_value[self.value]:
                msw = mstate(self.obj, self.cls)  # This returns a wrapper
                if msw:  # If the wrapper evaluates to True, it's our best match
                    return msw


Instruction:
Make a summary of the following Python 3 code
def current(self):
        if self.obj is not None:
            return {name: mstate(self.obj, self.cls)
                for name, mstate in self.statemanager.states.items()
                if mstate(self.obj, self.cls)}

Response: Return a dictionary of all states and state groups that are currently active.


Instruction:
How would you explain what the following Python 3 function does
def transitions(self, current=True):
        if current and isinstance(self.obj, RoleMixin):
            proxy = self.obj.current_access()
        else:
            proxy = {}
            current = False  # In case the host object is not a RoleMixin
        return OrderedDict((name, transition) for name, transition in
            # Retrieve transitions from the host object to activate the descriptor.
            ((name, getattr(self.obj, name)) for name in self.statemanager.transitions)
            if transition.is_available and (name in proxy if current else True))

Response: Returns the available transitions for the current state.


Instruction:
Explain what the following Python 3 code does
def transitions_for(self, roles=None, actor=None, anchors=[]):
        proxy = self.obj.access_for(roles, actor, anchors)
        return {name: transition for name, transition in self.transitions(current=False).items()
            if name in proxy}

Response: Returns a dictionary of names of all states that are available for the specified roles actor and anchors.


Instruction:
Implement a function in Python 3 to
give an iterable of instances groups them by state using the state manager s state_by_value property as keys.

Response:
def group(self, items, keep_empty=False):
        """
        Given an iterable of instances, groups them by state using :class:`ManagedState` instances
        as dictionary keys. Returns an `OrderedDict` that preserves the order of states from
        the source :class:`~coaster.utils.classes.LabeledEnum`.

        :param bool keep_empty: If ``True``, empty states are included in the result
        """
        cls = self.cls if self.cls is not None else type(self.obj)  # Class of the item being managed
        groups = OrderedDict()
        for mstate in self.statemanager.states_by_value.values():
            # Ensure we sort groups using the order of states in the source LabeledEnum.
            # We'll discard the unused states later.
            groups[mstate] = []
        # Now process the items by state
        for item in items:
            # Use isinstance instead of `type(item) != cls` to account for subclasses
            if not isinstance(item, cls):
                raise TypeError("Item %s is not an instance of type %s" % (repr(item), repr(self.cls)))
            statevalue = self.statemanager._value(item)
            mstate = self.statemanager.states_by_value[statevalue]
            groups[mstate].append(item)
        if not keep_empty:
            for key, value in list(groups.items()):
                if not value:
                    del groups[key]
        return groups


Instruction:
Make a summary of the following Python 3 code
def gfm(text):
    def indent_code(matchobj):
        syntax = matchobj.group(1)
        code = matchobj.group(2)
        if syntax:
            result = '    :::' + syntax + '\n'
        else:
            result = ''
        # The last line will be blank since it had the closing "```". Discard it
        # when indenting the lines.
        return result + '\n'.join(['    ' + line for line in code.split('\n')[:-1]])

    use_crlf = text.find('\r') != -1
    if use_crlf:
        text = text.replace('\r\n', '\n')

    # Render GitHub-style ```code blocks``` into Markdown-style 4-space indented blocks
    text = CODEPATTERN_RE.sub(indent_code, text)

    text, code_blocks = remove_pre_blocks(text)
    text, inline_blocks = remove_inline_code_blocks(text)

    # Prevent foo_bar_baz from ending up with an italic word in the middle.
    def italic_callback(matchobj):
        s = matchobj.group(0)
        # don't mess with URLs:
        if 'http:' in s or 'https:' in s:
            return s

        return s.replace('_', r'\_')

    # fix italics for code blocks
    text = ITALICSPATTERN_RE.sub(italic_callback, text)

    # linkify naked URLs
    # wrap the URL in brackets: http://foo -> [http://foo](http://foo)
    text = NAKEDURL_RE.sub(r'\1[\2](\2)\3', text)

    # In very clear cases, let newlines become <br /> tags.
    def newline_callback(matchobj):
        if len(matchobj.group(1)) == 1:
            return matchobj.group(0).rstrip() + '  \n'
        else:
            return matchobj.group(0)

    text = NEWLINE_RE.sub(newline_callback, text)

    # now restore removed code blocks
    removed_blocks = code_blocks + inline_blocks
    for removed_block in removed_blocks:
        text = text.replace('{placeholder}', removed_block, 1)

    if use_crlf:
        text = text.replace('\n', '\r\n')

    return text

Response: Render a Markdown text into a list of nodes.


Instruction:
How would you explain what the following Python 3 function does
def markdown(text, html=False, valid_tags=GFM_TAGS):
    if text is None:
        return None
    if html:
        return Markup(sanitize_html(markdown_convert_html(gfm(text)), valid_tags=valid_tags))
    else:
        return Markup(markdown_convert_text(gfm(text)))

Response: Return Markdown rendered text using GitHub Flavoured Markdown and syntax - highlighting enabled.


Instruction:
Make a summary of the following Python 3 code
def rulejoin(class_rule, method_rule):
    if method_rule.startswith('/'):
        return method_rule
    else:
        return class_rule + ('' if class_rule.endswith('/') or not method_rule else '/') + method_rule

Response: Join class and method rules. Used internally by the class view decorators and the method view decorators.


Instruction:
Implement a Python 3 function for
viewing method decorator that checks the URL of the loaded object in ``self.obj`` against the URL in the request (using ``self.obj.url_for(__name__)``). If the URLs do not match, and the request is a ``GET``, it issues a redirect to the correct URL. Usage:: @route('/doc/<document>') class MyModelView(UrlForView, InstanceLoader, ModelView): model = MyModel route_model_map = {'document': 'url_id_name'} @route('') @url_change_check @render_with(json=True) def view(self): return self.obj.current_access() If the decorator is required for all view handlers in the class, use :class:`UrlChangeCheck`.

Response:
def url_change_check(f):
    """
    View method decorator that checks the URL of the loaded object in
    ``self.obj`` against the URL in the request (using
    ``self.obj.url_for(__name__)``). If the URLs do not match,
    and the request is a ``GET``, it issues a redirect to the correct URL.
    Usage::

        @route('/doc/<document>')
        class MyModelView(UrlForView, InstanceLoader, ModelView):
            model = MyModel
            route_model_map = {'document': 'url_id_name'}

            @route('')
            @url_change_check
            @render_with(json=True)
            def view(self):
                return self.obj.current_access()

    If the decorator is required for all view handlers in the class, use
    :class:`UrlChangeCheck`.
    """
    @wraps(f)
    def wrapper(self, *args, **kwargs):
        if request.method == 'GET' and self.obj is not None:
            correct_url = self.obj.url_for(f.__name__, _external=True)
            if correct_url != request.base_url:
                if request.query_string:
                    correct_url = correct_url + '?' + request.query_string.decode()
                return redirect(correct_url)  # TODO: Decide if this should be 302 (default) or 301
        return f(self, *args, **kwargs)
    return wrapper


Instruction:
How would you implement a function in Python 3 that
registers routes for a given app and class.

Response:
def init_app(self, app, cls, callback=None):
        """
        Register routes for a given app and :class:`ClassView` class. At the
        time of this call, we will always be in the view class even if we were
        originally defined in a base class. :meth:`ClassView.init_app`
        ensures this. :meth:`init_app` therefore takes the liberty of adding
        additional attributes to ``self``:

        * :attr:`wrapped_func`: The function wrapped with all decorators added by the class
        * :attr:`view_func`: The view function registered as a Flask view handler
        * :attr:`endpoints`: The URL endpoints registered to this view handler
        """
        def view_func(**view_args):
            # view_func does not make any reference to variables from init_app to avoid creating
            # a closure. Instead, the code further below sticks all relevant variables into
            # view_func's namespace.

            # Instantiate the view class. We depend on its __init__ requiring no parameters
            viewinst = view_func.view_class()
            # Declare ourselves (the ViewHandler) as the current view. The wrapper makes
            # equivalence tests possible, such as ``self.current_handler == self.index``
            viewinst.current_handler = ViewHandlerWrapper(view_func.view, viewinst, view_func.view_class)
            # Place view arguments in the instance, in case they are needed outside the dispatch process
            viewinst.view_args = view_args
            # Place the view instance on the request stack for :obj:`current_view` to discover
            _request_ctx_stack.top.current_view = viewinst
            # Call the view instance's dispatch method. View classes can customise this for
            # desired behaviour.
            return viewinst.dispatch_request(view_func.wrapped_func, view_args)

        # Decorate the wrapped view function with the class's desired decorators.
        # Mixin classes may provide their own decorators, and all of them will be applied.
        # The oldest defined decorators (from mixins) will be applied first, and the
        # class's own decorators last. Within the list of decorators, we reverse the list
        # again, so that a list specified like this:
        #
        #     __decorators__ = [first, second]
        #
        # Has the same effect as writing this:
        #
        #     @first
        #     @second
        #     def myview(self):
        #         pass
        wrapped_func = self.func
        for base in reversed(cls.__mro__):
            if '__decorators__' in base.__dict__:
                for decorator in reversed(base.__dict__['__decorators__']):
                    wrapped_func = decorator(wrapped_func)
                    wrapped_func.__name__ = self.name  # See below

        # Make view_func resemble the underlying view handler method...
        view_func = update_wrapper(view_func, wrapped_func)
        # ...but give view_func the name of the method in the class (self.name),
        # self.name will differ from __name__ only if the view handler method
        # was defined outside the class and then added to the class with a
        # different name.
        view_func.__name__ = self.name

        # Stick `wrapped_func` and `cls` into view_func to avoid creating a closure.
        view_func.wrapped_func = wrapped_func
        view_func.view_class = cls
        view_func.view = self

        # Keep a copy of these functions (we already have self.func)
        self.wrapped_func = wrapped_func
        self.view_func = view_func

        for class_rule, class_options in cls.__routes__:
            for method_rule, method_options in self.routes:
                use_options = dict(method_options)
                use_options.update(class_options)
                endpoint = use_options.pop('endpoint', self.endpoint)
                self.endpoints.add(endpoint)
                use_rule = rulejoin(class_rule, method_rule)
                app.add_url_rule(use_rule, endpoint, view_func, **use_options)
                if callback:
                    callback(use_rule, endpoint, view_func, **use_options)


Instruction:
Can you implement a function in Python 3 that
indicates whether this view is available in the current context

Response:
def is_available(self):
        """Indicates whether this view is available in the current context"""
        if hasattr(self._viewh.wrapped_func, 'is_available'):
            return self._viewh.wrapped_func.is_available(self._obj)
        return True


Instruction:
Given the following Python 3 function, write the documentation
def dispatch_request(self, view, view_args):
        # Call the :meth:`before_request` method
        resp = self.before_request()
        if resp:
            return self.after_request(make_response(resp))
        # Call the view handler method, then pass the response to :meth:`after_response`
        return self.after_request(make_response(view(self, **view_args)))

Response: Dispatches a request to the specified view and returns the response.


Instruction:
Implement a function in Python 3 to
return True if any view handler in the class is currently available via its is_available method.

Response:
def is_available(self):
        """
        Returns `True` if *any* view handler in the class is currently
        available via its `is_available` method.
        """
        if self.is_always_available:
            return True
        for viewname in self.__views__:
            if getattr(self, viewname).is_available():
                return True
        return False


Instruction:
Can you generate the documentation for the following Python 3 function
def add_route_for(cls, _name, rule, **options):
        setattr(cls, _name, route(rule, **options)(cls.__get_raw_attr(_name)))

Response:
Add a route for an existing method or view. Useful for modifying routes
           .


Instruction:
Implement a function in Python 3 to
register views on an app.

Response:
def init_app(cls, app, callback=None):
        """
        Register views on an app. If :attr:`callback` is specified, it will
        be called after ``app.``:meth:`~flask.Flask.add_url_rule`, with the same
        parameters.
        """
        processed = set()
        cls.__views__ = set()
        cls.is_always_available = False
        for base in cls.__mro__:
            for name, attr in base.__dict__.items():
                if name in processed:
                    continue
                processed.add(name)
                if isinstance(attr, ViewHandler):
                    if base != cls:  # Copy ViewHandler instances into subclasses
                        # TODO: Don't do this during init_app. Use a metaclass
                        # and do this when the class is defined.
                        attr = attr.copy_for_subclass()
                        setattr(cls, name, attr)
                    attr.__set_name__(cls, name)  # Required for Python < 3.6
                    cls.__views__.add(name)
                    attr.init_app(app, cls, callback=callback)
                    if not hasattr(attr.wrapped_func, 'is_available'):
                        cls.is_always_available = True


Instruction:
Can you implement a function in Python 3 that
dispatches a request to the specified view method and returns the response.

Response:
def dispatch_request(self, view, view_args):
        """
        View dispatcher that calls :meth:`before_request`, :meth:`loader`,
        :meth:`after_loader`, the view, and then :meth:`after_request`.

        :param view: View method wrapped in specified decorators.
        :param dict view_args: View arguments, to be passed on to the view method
        """
        # Call the :meth:`before_request` method
        resp = self.before_request()
        if resp:
            return self.after_request(make_response(resp))
        # Load the database model
        self.obj = self.loader(**view_args)
        # Trigger pre-view processing of the loaded object
        resp = self.after_loader()
        if resp:
            return self.after_request(make_response(resp))
        # Call the view handler method, then pass the response to :meth:`after_response`
        return self.after_request(make_response(view(self)))


Instruction:
Explain what the following Python 3 code does
def declared_attr_roles(rw=None, call=None, read=None, write=None):
    def inner(f):
        @wraps(f)
        def attr(cls):
            # Pass f(cls) as a parameter to with_roles.inner to avoid the test for
            # iterables within with_roles. We have no idea about the use cases for
            # declared_attr in downstream code. There could be a declared_attr
            # that returns a list that should be accessible via the proxy.
            return with_roles(rw=rw, call=call, read=read, write=write)(f(cls))
        return attr
    warnings.warn("declared_attr_roles is deprecated; use with_roles", stacklevel=2)
    return inner

Response: Decorator for the class that has declared_attr_roles.


Instruction:
Create a Python 3 function for
configuring the class s roles based on the base classes.

Response:
def __configure_roles(mapper, cls):
    """
    Run through attributes of the class looking for role decorations from
    :func:`with_roles` and add them to :attr:`cls.__roles__`
    """
    # Don't mutate ``__roles__`` in the base class.
    # The subclass must have its own.
    # Since classes may specify ``__roles__`` directly without
    # using :func:`with_roles`, we must preserve existing content.
    if '__roles__' not in cls.__dict__:
        # If the following line is confusing, it's because reading an
        # attribute on an object invokes the Method Resolution Order (MRO)
        # mechanism to find it on base classes, while writing always writes
        # to the current object.
        cls.__roles__ = deepcopy(cls.__roles__)

    # An attribute may be defined more than once in base classes. Only handle the first
    processed = set()

    # Loop through all attributes in this and base classes, looking for role annotations
    for base in cls.__mro__:
        for name, attr in base.__dict__.items():
            if name in processed or name.startswith('__'):
                continue

            if isinstance(attr, collections.Hashable) and attr in __cache__:
                data = __cache__[attr]
                del __cache__[attr]
            elif isinstance(attr, InstrumentedAttribute) and attr.property in __cache__:
                data = __cache__[attr.property]
                del __cache__[attr.property]
            elif hasattr(attr, '_coaster_roles'):
                data = attr._coaster_roles
            else:
                data = None
            if data is not None:
                for role in data.get('call', []):
                    cls.__roles__.setdefault(role, {}).setdefault('call', set()).add(name)
                for role in data.get('read', []):
                    cls.__roles__.setdefault(role, {}).setdefault('read', set()).add(name)
                for role in data.get('write', []):
                    cls.__roles__.setdefault(role, {}).setdefault('write', set()).add(name)
                processed.add(name)


Instruction:
Explain what the following Python 3 code does
def current_roles(self):
        return InspectableSet(self.roles_for(actor=current_auth.actor, anchors=current_auth.anchors))

Response:
Return a InspectableSet containing currently
            available roles on this object.


Instruction:
Can you generate the documentation for the following Python 3 function
def access_for(self, roles=None, actor=None, anchors=[]):
        if roles is None:
            roles = self.roles_for(actor=actor, anchors=anchors)
        elif actor is not None or anchors:
            raise TypeError('If roles are specified, actor/anchors must not be specified')
        return RoleAccessProxy(self, roles=roles)

Response:
Returns a proxy object that limits read and write access to attributes
            based on the actor s roles.


Instruction:
How would you implement a function in Python 3 that
wraps :meth:`access_for` with :obj:`~coaster.auth.current_auth` to return a proxy for the currently authenticated user.

Response:
def current_access(self):
        """
        Wraps :meth:`access_for` with :obj:`~coaster.auth.current_auth` to
        return a proxy for the currently authenticated user.
        """
        return self.access_for(actor=current_auth.actor, anchors=current_auth.anchors)


Instruction:
Here you have a function in Python 3, explain what it does
def get_current_url():
    if current_app.config.get('SERVER_NAME') and (
            # Check current hostname against server name, ignoring port numbers, if any (split on ':')
            request.environ['HTTP_HOST'].split(':', 1)[0] != current_app.config['SERVER_NAME'].split(':', 1)[0]):
        return request.url

    url = url_for(request.endpoint, **request.view_args)
    query = request.query_string
    if query:
        return url + '?' + query.decode()
    else:
        return url

Response: Return the current URL including the query string as a relative path.


Instruction:
Given the following Python 3 function, write the documentation
def get_next_url(referrer=False, external=False, session=False, default=__marker):
    if session:
        next_url = request_session.pop('next', None) or request.args.get('next', '')
    else:
        next_url = request.args.get('next', '')
    if next_url and not external:
        next_url = __clean_external_url(next_url)
    if next_url:
        return next_url

    if default is __marker:
        usedefault = False
    else:
        usedefault = True

    if referrer and request.referrer:
        if external:
            return request.referrer
        else:
            return __clean_external_url(request.referrer) or (default if usedefault else __index_url())
    else:
        return default if usedefault else __index_url()

Response: Get the next URL to redirect to. Don t return external URLs unless explicitly asked for.


Instruction:
Create a Python 3 function for
returning a JSON response with a callback wrapper if asked for.

Response:
def jsonp(*args, **kw):
    """
    Returns a JSON response with a callback wrapper, if asked for.
    Consider using CORS instead, as JSONP makes the client app insecure.
    See the :func:`~coaster.views.decorators.cors` decorator.
    """
    data = json.dumps(dict(*args, **kw), indent=2)
    callback = request.args.get('callback', request.args.get('jsonp'))
    if callback and __jsoncallback_re.search(callback) is not None:
        data = callback + u'(' + data + u');'
        mimetype = 'application/javascript'
    else:
        mimetype = 'application/json'
    return Response(data, mimetype=mimetype)


Instruction:
Write a Python 3 script for
giving an absolute URL retrieve the matching endpoint name or view arguments.

Response:
def endpoint_for(url, method=None, return_rule=False, follow_redirects=True):
    """
    Given an absolute URL, retrieve the matching endpoint name (or rule) and
    view arguments. Requires a current request context to determine runtime
    environment.

    :param str method: HTTP method to use (defaults to GET)
    :param bool return_rule: Return the URL rule instead of the endpoint name
    :param bool follow_redirects: Follow redirects to final endpoint
    :return: Tuple of endpoint name or URL rule or `None`, view arguments
    """
    parsed_url = urlsplit(url)
    if not parsed_url.netloc:
        # We require an absolute URL
        return None, {}

    # Take the current runtime environment...
    environ = dict(request.environ)
    # ...but replace the HTTP host with the URL's host...
    environ['HTTP_HOST'] = parsed_url.netloc
    # ...and the path with the URL's path (after discounting the app path, if not hosted at root).
    environ['PATH_INFO'] = parsed_url.path[len(environ.get('SCRIPT_NAME', '')):]
    # Create a new request with this environment...
    url_request = current_app.request_class(environ)
    # ...and a URL adapter with the new request.
    url_adapter = current_app.create_url_adapter(url_request)

    # Run three hostname tests, one of which must pass:

    # 1. Does the URL map have host matching enabled? If so, the URL adapter will validate the hostname.
    if current_app.url_map.host_matching:
        pass

    # 2. If not, does the domain match? url_adapter.server_name will prefer app.config['SERVER_NAME'],
    # but if that is not specified, it will take it from the environment.
    elif parsed_url.netloc == url_adapter.server_name:
        pass

    # 3. If subdomain matching is enabled, does the subdomain match?
    elif current_app.subdomain_matching and parsed_url.netloc.endswith('.' + url_adapter.server_name):
        pass

    # If no test passed, we don't have a matching endpoint.
    else:
        return None, {}

    # Now retrieve the endpoint or rule, watching for redirects or resolution failures
    try:
        return url_adapter.match(parsed_url.path, method, return_rule=return_rule)
    except RequestRedirect as r:
        # A redirect typically implies `/folder` -> `/folder/`
        # This will not be a redirect response from a view, since the view isn't being called
        if follow_redirects:
            return endpoint_for(r.new_url, method=method, return_rule=return_rule, follow_redirects=follow_redirects)
    except (NotFound, MethodNotAllowed):
        pass
    # If we got here, no endpoint was found.
    return None, {}


Instruction:
Can you implement a function in Python 3 that
returns a set of permissions for this workflow.

Response:
def permissions(self):
        """
        Permissions for this workflow. Plays nice with
        :meth:`coaster.views.load_models` and
        :class:`coaster.sqlalchemy.PermissionMixin` to determine the available
        permissions to the current user.
        """
        perms = set(super(DocumentWorkflow, self).permissions())
        if g:
            if hasattr(g, 'permissions'):
                perms.update(g.permissions or [])
            if hasattr(self.document, 'permissions'):
                perms = self.document.permissions(current_auth.actor, perms)
        return perms


Instruction:
How would you code a function in Python 3 to
configure the annotations of the class.

Response:
def __configure_annotations(mapper, cls):
    """
    Run through attributes of the class looking for annotations from
    :func:`annotation_wrapper` and add them to :attr:`cls.__annotations__`
    and :attr:`cls.__annotations_by_attr__`
    """
    annotations = {}
    annotations_by_attr = {}

    # An attribute may be defined more than once in base classes. Only handle the first
    processed = set()

    # Loop through all attributes in the class and its base classes, looking for annotations
    for base in cls.__mro__:
        for name, attr in base.__dict__.items():
            if name in processed or name.startswith('__'):
                continue

            # 'data' is a list of string annotations
            if isinstance(attr, collections.Hashable) and attr in __cache__:
                data = __cache__[attr]
                del __cache__[attr]
            elif isinstance(attr, InstrumentedAttribute) and attr.property in __cache__:
                data = __cache__[attr.property]
                del __cache__[attr.property]
            elif hasattr(attr, '_coaster_annotations'):
                data = attr._coaster_annotations
            else:
                data = None
            if data is not None:
                annotations_by_attr.setdefault(name, []).extend(data)
                for a in data:
                    annotations.setdefault(a, []).append(name)
                processed.add(name)

    # Classes specifying ``__annotations__`` directly isn't supported,
    # so we don't bother preserving existing content, if any.
    if annotations:
        cls.__annotations__ = annotations
    if annotations_by_attr:
        cls.__annotations_by_attr__ = annotations_by_attr
    annotations_configured.send(cls)


Instruction:
How would you explain what the following Python 3 function does
def annotation_wrapper(annotation, doc=None):
    def decorator(attr):
        __cache__.setdefault(attr, []).append(annotation)
        # Also mark the annotation on the object itself. This will
        # fail if the object has a restrictive __slots__, but it's
        # required for some objects like Column because SQLAlchemy copies
        # them in subclasses, changing their hash and making them
        # undiscoverable via the cache.
        try:
            if not hasattr(attr, '_coaster_annotations'):
                setattr(attr, '_coaster_annotations', [])
            attr._coaster_annotations.append(annotation)
        except AttributeError:
            pass
        return attr

    decorator.__name__ = decorator.name = annotation
    decorator.__doc__ = doc
    return decorator

Response: A decorator that adds an annotation to an attribute.


Instruction:
Given the following Python 3 function, write the documentation
def add_auth_attribute(attr, value, actor=False):
    if attr in ('actor', 'anchors', 'is_anonymous', 'not_anonymous', 'is_authenticated', 'not_authenticated'):
        raise AttributeError("Attribute name %s is reserved by current_auth" % attr)

    # Invoking current_auth will also create it on the local stack. We can
    # then proceed to set attributes on it.
    ca = current_auth._get_current_object()
    # Since :class:`CurrentAuth` overrides ``__setattr__``, we need to use :class:`object`'s.
    object.__setattr__(ca, attr, value)

    if attr == 'user':
        # Special-case 'user' for compatibility with Flask-Login
        _request_ctx_stack.top.user = value
        # A user is always an actor
        actor = True

    if actor:
        object.__setattr__(ca, 'actor', value)

Response: Helper function for login managers. Adds authorization attributes to the current_auth object.


Instruction:
How would you explain what the following Python 3 function does
def build_attributes(cls, attributes, namespace):
        config_path = attributes.get('config_path')
        tokens = {}

        def build_config_key(value_def, config_key):
            key = value_def.config_key or config_key
            return '%s.%s' % (config_path, key) if config_path else key

        def build_token(name, value_def):
            config_key = build_config_key(value_def, name)
            value_token = ValueToken.from_definition(
                                            value_def, namespace, config_key)
            getters.register_value_proxy(namespace, value_token, value_def.help)
            tokens[name] = value_token
            return name, build_property(value_token)

        def build_attr(name, attribute):
            if not isinstance(attribute, ValueTypeDefinition):
                return name, attribute
            return build_token(name, attribute)

        attributes = dict(build_attr(*item)
                          for item in six.iteritems(attributes))
        attributes['_tokens'] = tokens
        return attributes

Response:
Build a dictionary of attributes with ValueTokens replaced by a
            property which returns the config value.


Instruction:
Can you generate the documentation for the following Python 3 function
def cache_as_field(cache_name):
    def cache_wrapper(func):
        @functools.wraps(func)
        def inner_wrapper(self, *args, **kwargs):
            value = getattr(self, cache_name, UndefToken)
            if value != UndefToken:
                return value

            ret = func(self, *args, **kwargs)
            setattr(self, cache_name, ret)
            return ret
        return inner_wrapper
    return cache_wrapper

Response: Cache a functions return value as the field cache_name.


Instruction:
Can you generate the documentation for the following Python 3 function
def extract_value(proxy):
    value = proxy.namespace.get(proxy.config_key, proxy.default)
    if value is UndefToken:
        raise errors.ConfigurationError("%s is missing value for: %s" %
            (proxy.namespace, proxy.config_key))

    try:
        return proxy.validator(value)
    except errors.ValidationError as e:
        raise errors.ConfigurationError("%s failed to validate %s: %s" %
            (proxy.namespace, proxy.config_key, e))

Response: Given a value proxy type Retrieve a value from a namespace raising an exception if no value is found raising an exception if the value does not validate.


Instruction:
Explain what the following Python 3 code does
def build_reader(validator, reader_namespace=config.DEFAULT):
    def reader(config_key, default=UndefToken, namespace=None):
        config_namespace = config.get_namespace(namespace or reader_namespace)
        return validator(_read_config(config_key, config_namespace, default))
    return reader

Response:
A factory method for creating a custom config reader from a validation
    function.


Instruction:
Can you tell what is the following Python 3 function doing
def get_namespaces_from_names(name, all_names):
    names = configuration_namespaces.keys() if all_names else [name]
    for name in names:
        yield get_namespace(name)

Response: Return a generator which yields namespace objects.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_namespace(name):
    if name not in configuration_namespaces:
        configuration_namespaces[name] = ConfigNamespace(name)
    return configuration_namespaces[name]

Response: Return a ConfigNamespace by name creating it if it does not exist.


Instruction:
Create a Python 3 function to
reload one or all namespaces.

Response:
def reload(name=DEFAULT, all_names=False):
    """Reload one or all :class:`ConfigNamespace`. Reload clears the cache of
    :mod:`staticconf.schema` and :mod:`staticconf.getters`, allowing them to
    pickup the latest values in the namespace.

    Defaults to reloading just the DEFAULT namespace.

    :param name: the name of the :class:`ConfigNamespace` to reload
    :param all_names: If True, reload all namespaces, and ignore `name`
    """
    for namespace in get_namespaces_from_names(name, all_names):
        for value_proxy in namespace.get_value_proxies():
            value_proxy.reset()


Instruction:
Explain what the following Python 3 code does
def validate(name=DEFAULT, all_names=False):
    for namespace in get_namespaces_from_names(name, all_names):
        all(value_proxy.get_value() for value_proxy in namespace.get_value_proxies())

Response: Validate all registered keys or values in a given namespace.


Instruction:
Implement a function in Python 3 to
compare two dictionaries for duplicate keys.

Response:
def has_duplicate_keys(config_data, base_conf, raise_error):
    """Compare two dictionaries for duplicate keys. if raise_error is True
    then raise on exception, otherwise log return True."""
    duplicate_keys = set(base_conf) & set(config_data)
    if not duplicate_keys:
        return
    msg = "Duplicate keys in config: %s" % duplicate_keys
    if raise_error:
        raise errors.ConfigurationError(msg)
    log.info(msg)
    return True


Instruction:
Implement a Python 3 function for
building a compare_func that can be passed to MTimeComparator.

Response:
def build_compare_func(err_logger=None):
    """Returns a compare_func that can be passed to MTimeComparator.

    The returned compare_func first tries os.path.getmtime(filename),
    then calls err_logger(filename) if that fails. If err_logger is None,
    then it does nothing. err_logger is always called within the context of
    an OSError raised by os.path.getmtime(filename). Information on this
    error can be retrieved by calling sys.exc_info inside of err_logger."""
    def compare_func(filename):
        try:
            return os.path.getmtime(filename)
        except OSError:
            if err_logger is not None:
                err_logger(filename)
        return -1
    return compare_func


Instruction:
Can you create a Python 3 function that
reconstructs the nested structure of this object s configuration and return it as a dict.

Response:
def get_config_dict(self):
        """Reconstruct the nested structure of this object's configuration
        and return it as a dict.
        """
        config_dict = {}
        for dotted_key, value in self.get_config_values().items():
            subkeys = dotted_key.split('.')
            d = config_dict
            for key in subkeys:
                d = d.setdefault(key, value if key == subkeys[-1] else {})
        return config_dict


Instruction:
Can you generate a brief explanation for the following Python 3 code
def view_help(self):
        def format_desc(desc):
            return "%s (Type: %s, Default: %s)\n%s" % (
                    desc.name,
                    desc.validator.__name__.replace('validate_', ''),
                    desc.default,
                    desc.help or '')

        def format_namespace(key, desc_list):
            return "\nNamespace: %s\n%s" % (
                    key,
                    '\n'.join(sorted(format_desc(desc) for desc in desc_list)))

        def namespace_cmp(item):
            name, _ = item
            return chr(0) if name == DEFAULT else name

        return '\n'.join(format_namespace(*desc) for desc in
                         sorted(six.iteritems(self.descriptions),
                                key=namespace_cmp))

Response: Return a help message describing all the statically configured keys.


Instruction:
How would you explain what the following Python 3 function does
def reload_if_changed(self, force=False):
        if (force or self.should_check) and self.file_modified():
            return self.reload()

Response: Reloads the configuration of the object if the file has changed.


Instruction:
How would you implement a function in Python 3 that
loads a configuration file into a new namespace.

Response:
def load(
            cls,
            filename,
            namespace,
            loader_func,
            min_interval=0,
            comparators=None,
    ):
        """Create a new :class:`ConfigurationWatcher` and load the initial
        configuration by calling `loader_func`.

        :param filename: a filename or list of filenames to monitor for changes
        :param namespace: the name of a namespace to use when loading
                          configuration. All config data from `filename` will
                          end up in a :class:`ConfigNamespace` with this name
        :param loader_func: a function which accepts two arguments and uses
                            loader functions from :mod:`staticconf.loader` to
                            load configuration data into a namespace. The
                            arguments are `filename` and `namespace`
        :param min_interval: minimum number of seconds to wait between calls to
                             :func:`os.path.getmtime` to check if a file has
                             been modified.
        :param comparators: a list of classes which support the
            :class:`IComparator` interface which are used to determine if a config
            file has been modified. See ConfigurationWatcher::__init__.
        :returns: a :class:`ConfigFacade`
        """
        watcher = ConfigurationWatcher(
            build_loader_callable(loader_func, filename, namespace=namespace),
            filename,
            min_interval=min_interval,
            reloader=ReloadCallbackChain(namespace=namespace),
            comparators=comparators,
        )
        watcher.load_config()
        return cls(watcher)


Instruction:
Explain what the following Python 3 code does
def _validate_iterable(iterable_type, value):
    if isinstance(value, six.string_types):
        msg = "Invalid iterable of type(%s): %s"
        raise ValidationError(msg % (type(value), value))

    try:
        return iterable_type(value)
    except TypeError:
        raise ValidationError("Invalid iterable: %s" % (value))

Response:
Convert the iterable to iterable_type or raise a Configuration
    exception.


Instruction:
Given the following Python 3 function, write the documentation
def build_list_type_validator(item_validator):
    def validate_list_of_type(value):
        return [item_validator(item) for item in validate_list(value)]
    return validate_list_of_type

Response:
Build a function which validates that the value is a list of items
    which are validated using item_validator.


Instruction:
Given the following Python 3 function, write the documentation
def build_map_type_validator(item_validator):
    def validate_mapping(value):
        return dict(item_validator(item) for item in validate_list(value))
    return validate_mapping

Response:
Return a function which validates that the value is a mapping of
    items. The function should return pairs of items that will be
   .


Instruction:
How would you implement a function in Python 3 that
registers a value proxy with the namespace and add the help_text.

Response:
def register_value_proxy(namespace, value_proxy, help_text):
    """Register a value proxy with the namespace, and add the help_text."""
    namespace.register_proxy(value_proxy)
    config.config_help.add(
        value_proxy.config_key, value_proxy.validator, value_proxy.default,
        namespace.get_name(), help_text)


Instruction:
Here you have a function in Python 3, explain what it does
def build_getter(validator, getter_namespace=None):
    def proxy_register(key_name, default=UndefToken, help=None, namespace=None):
        name        = namespace or getter_namespace or config.DEFAULT
        namespace   = config.get_namespace(name)
        return proxy_factory.build(validator, namespace, key_name, default, help)

    return proxy_register

Response: Create a getter function for retrieving values from the config cache.


Instruction:
Can you tell what is the following Python 3 function doing
def build(self, validator, namespace, config_key, default, help):
        proxy_attrs = validator, namespace, config_key, default
        proxy_key = repr(proxy_attrs)
        if proxy_key in self.proxies:
            return self.proxies[proxy_key]

        value_proxy = proxy.ValueProxy(*proxy_attrs)
        register_value_proxy(namespace, value_proxy, help)
        return self.proxies.setdefault(proxy_key, value_proxy)

Response: Build or retrieve a ValueProxy from the attributes.


Instruction:
Here you have a function in Python 3, explain what it does
def minimizeSPSA(func, x0, args=(), bounds=None, niter=100, paired=True,
                 a=1.0, alpha=0.602, c=1.0, gamma=0.101,
                 disp=False, callback=None):
    """
    Minimization of an objective function by a simultaneous perturbation
    stochastic approximation algorithm.

    This algorithm approximates the gradient of the function by finite differences
    along stochastic directions Deltak. The elements of Deltak are drawn from
    +- 1 with probability one half. The gradient is approximated from the
    symmetric difference f(xk + ck*Deltak) - f(xk - ck*Deltak), where the evaluation
    step size ck is scaled according ck =  c/(k+1)**gamma.
    The algorithm takes a step of size ak = a/(0.01*niter+k+1)**alpha along the
    negative gradient.

    See Spall, IEEE, 1998, 34, 817-823 for guidelines about how to choose the algorithm's
    parameters (a, alpha, c, gamma).

    Parameters
    ----------
    func: callable
        objective function to be minimized:
        called as `func(x, *args)`,
        if `paired=True`, then called with keyword argument `seed` additionally
    x0: array-like
        initial guess for parameters
    args: tuple
        extra arguments to be supplied to func
    bounds: array-like
        bounds on the variables
    niter: int
        number of iterations after which to terminate the algorithm
    paired: boolean
        calculate gradient for same random seeds
    a: float
       scaling parameter for step size
    alpha: float
        scaling exponent for step size
    c: float
       scaling parameter for evaluation step size
    gamma: float
        scaling exponent for evaluation step size
    disp: boolean
        whether to output status updates during the optimization
    callback: callable
        called after each iteration, as callback(xk), where xk are the current parameters

    Returns
    -------
    `scipy.optimize.OptimizeResult` object
    """
    A = 0.01 * niter

    if bounds is not None:
        bounds = np.asarray(bounds)
        project = lambda x: np.clip(x, bounds[:, 0], bounds[:, 1])

    if args is not None:
        # freeze function arguments
        def funcf(x, **kwargs):
            return func(x, *args, **kwargs)

    N = len(x0)
    x = x0
    for k in range(niter):
        ak = a/(k+1.0+A)**alpha
        ck = c/(k+1.0)**gamma
        Deltak = np.random.choice([-1, 1], size=N)
        fkwargs = dict()
        if paired:
            fkwargs['seed'] = np.random.randint(0, np.iinfo(np.uint32).max)
        if bounds is None:
            grad = (funcf(x + ck*Deltak, **fkwargs) - funcf(x - ck*Deltak, **fkwargs)) / (2*ck*Deltak)
            x -= ak*grad
        else:
            # ensure evaluation points are feasible
            xplus = project(x + ck*Deltak)
            xminus = project(x - ck*Deltak)
            grad = (funcf(xplus, **fkwargs) - funcf(xminus, **fkwargs)) / (xplus-xminus)
            x = project(x - ak*grad)
        # print 100 status updates if disp=True
        if disp and (k % (niter//100)) == 0:
            print(x)
        if callback is not None:
            callback(x)
    message = 'terminated after reaching max number of iterations'
    return OptimizeResult(fun=funcf(x), x=x, nit=niter, nfev=2*niter, message=message, success=True)

Response: Minimization of an objective function by a simultaneous perturbation of a single object.


Instruction:
Write a Python 3 function for
finding root by bysection search.

Response:
def bisect(func, a, b, xtol=1e-6, errorcontrol=True,
           testkwargs=dict(), outside='extrapolate',
           ascending=None,
           disp=False):
    """Find root by bysection search.

    If the function evaluation is noisy then use `errorcontrol=True` for adaptive
    sampling of the function during the bisection search.

    Parameters
    ----------
    func: callable
        Function of which the root should be found. If `errorcontrol=True`
        then the function should be derived from `AverageBase`.
    a, b: float
        initial interval
    xtol: float
        target tolerance for interval size
    errorcontrol: boolean
        if true, assume that function is derived from `AverageBase`.
    testkwargs: only for `errorcontrol=True`
        see `AverageBase.test0`
    outside: ['extrapolate', 'raise']
        How to handle the case where f(a) and f(b) have same sign,
        i.e. where the root lies outside of the interval.
        If 'raise' throws a `BisectException`.
    ascending: allow passing in directly whether function is ascending or not
        if ascending=True then it is assumed without check that f(a) < 0 and f(b) > 0
        if ascending=False then it is assumed without check that f(a) > 0 and f(b) < 0

    Returns
    -------
    float, root of function
    """
    search = True
    # check whether function is ascending or not
    if ascending is None:
        if errorcontrol:
            testkwargs.update(dict(type_='smaller', force=True))
            fa = func.test0(a, **testkwargs)
            fb = func.test0(b, **testkwargs)
        else:
            fa = func(a) < 0
            fb = func(b) < 0
        if fa and not fb:
            ascending = True
        elif fb and not fa:
            ascending =  False
        else:
            if disp:
                print('Warning: func(a) and func(b) do not have opposing signs -> no search done')
            if outside == 'raise':
                raise BisectException()
            search = False

    # refine interval until it has reached size xtol, except if root outside
    while (b-a > xtol) and search:
        mid = (a+b)/2.0
        if ascending:
            if ((not errorcontrol) and (func(mid) < 0)) or \
                    (errorcontrol and func.test0(mid, **testkwargs)):
                a = mid
            else:
                b = mid
        else:
            if ((not errorcontrol) and (func(mid) < 0)) or \
                    (errorcontrol and func.test0(mid, **testkwargs)):
                b = mid
            else:
                a = mid
        if disp:
            print('bisect bounds', a, b)
    # interpolate linearly to get zero
    if errorcontrol:
        ya, yb = func(a)[0], func(b)[0]
    else:
        ya, yb = func(a), func(b)
    m = (yb-ya) / (b-a)
    res = a-ya/m
    if disp:
        print('bisect final value', res)
    return res


Instruction:
How would you code a function in Python 3 to
document : selection_set fragment_list

Response:
def p_document_shorthand_with_fragments(self, p):
        """
        document : selection_set fragment_list
        """
        p[0] = Document(definitions=[Query(selections=p[1])] + p[2])


Instruction:
How would you code a function in Python 3 to
parse an operation definition

Response:
def p_operation_definition1(self, p):
        """
        operation_definition : operation_type name variable_definitions directives selection_set
        """
        p[0] = self.operation_cls(p[1])(
            selections=p[5],
            name=p[2],
            variable_definitions=p[3],
            directives=p[4],
        )


Instruction:
How would you code a function in Python 3 to
parse the 2nd parameter of the operation definition

Response:
def p_operation_definition2(self, p):
        """
        operation_definition : operation_type name variable_definitions selection_set
        """
        p[0] = self.operation_cls(p[1])(
            selections=p[4],
            name=p[2],
            variable_definitions=p[3],
        )


Instruction:
Write a Python 3 script to
parse the 3rd party operation definition.

Response:
def p_operation_definition3(self, p):
        """
        operation_definition : operation_type name directives selection_set
        """
        p[0] = self.operation_cls(p[1])(
            selections=p[4],
            name=p[2],
            directives=p[3],
        )


Instruction:
Make a summary of the following Python 3 code
def p_operation_definition4(self, p):
        p[0] = self.operation_cls(p[1])(selections=p[3], name=p[2])

Response: P 3. 4. 2. 2.


Instruction:
Given the following Python 3 function, write the documentation
def p_operation_definition5(self, p):
        p[0] = self.operation_cls(p[1])(
            selections=p[4],
            variable_definitions=p[2],
            directives=p[3],
        )

Response: Parse the 5 part of the operation definition.


Instruction:
Given the following Python 3 function, write the documentation
def p_operation_definition6(self, p):
        p[0] = self.operation_cls(p[1])(
            selections=p[3],
            variable_definitions=p[2],
        )

Response: P 6 - level operation definition


Instruction:
Can you generate a brief explanation for the following Python 3 code
def p_operation_definition7(self, p):
        p[0] = self.operation_cls(p[1])(
            selections=p[3],
            directives=p[2],
        )

Response: Parse the 7th section of the resource definition.


Instruction:
Can you create a Python 3 function that
fields : alias name arguments directives selection_set

Response:
def p_field_all(self, p):
        """
        field : alias name arguments directives selection_set
        """
        p[0] = Field(name=p[2], alias=p[1], arguments=p[3], directives=p[4],
                     selections=p[5])


Instruction:
Create a Python 3 function for
parsing the optional 1. 0 field.

Response:
def p_field_optional1_1(self, p):
        """
        field : name arguments directives selection_set
        """
        p[0] = Field(name=p[1], arguments=p[2], directives=p[3],
                     selections=p[5])


Instruction:
Here you have a function in Python 3, explain what it does
def p_field_optional1_2(self, p):
        p[0] = Field(name=p[2], alias=p[1], directives=p[3], selections=p[5])

Response: Parse the optional 1. 2 section of the spec.


Instruction:
Can you generate the documentation for the following Python 3 function
def p_field_optional1_3(self, p):
        p[0] = Field(name=p[2], alias=p[1], arguments=p[3], selections=p[4])

Response: Parse the optional 1. 3. 1. 2 field.


Instruction:
Write a Python 3 script for
parsing the optional 1. 4 section of the log message.

Response:
def p_field_optional1_4(self, p):
        """
        field : alias name arguments directives
        """
        p[0] = Field(name=p[2], alias=p[1], arguments=p[3], directives=p[4])


Instruction:
Explain what the following Python 3 code does
def p_field_optional2_1(self, p):
        p[0] = Field(name=p[1], directives=p[2], selections=p[3])

Response: Parse the optional 2. 1 section of the spec.


Instruction:
How would you code a function in Python 3 to
field : name arguments selection_set

Response:
def p_field_optional2_2(self, p):
        """
        field : name arguments selection_set
        """
        p[0] = Field(name=p[1], arguments=p[2], selections=p[3])


Instruction:
Can you generate a brief explanation for the following Python 3 code
def p_field_optional2_3(self, p):
        p[0] = Field(name=p[1], arguments=p[2], directives=p[3])

Response: Parse the optional 2. 3. 1. 2.


Instruction:
Implement a function in Python 3 to
parse optional 2. 4. 1. 2.

Response:
def p_field_optional2_4(self, p):
        """
        field : alias name selection_set
        """
        p[0] = Field(name=p[2], alias=p[1], selections=p[3])


Instruction:
How would you code a function in Python 3 to
parse an optional 2. 5 field.

Response:
def p_field_optional2_5(self, p):
        """
        field : alias name directives
        """
        p[0] = Field(name=p[2], alias=p[1], directives=p[3])


Instruction:
Here you have a function in Python 3, explain what it does
def p_field_optional2_6(self, p):
        p[0] = Field(name=p[2], alias=p[1], arguments=p[3])

Response: Parse the optional 2. 6. 1. 1 Field.


Instruction:
Make a summary of the following Python 3 code
def p_directive(self, p):
        arguments = p[3] if len(p) == 4 else None
        p[0] = Directive(name=p[2], arguments=arguments)

Response: parse a tag directive


Instruction:
Given the following Python 3 function, write the documentation
def p_const_object_field_list(self, p):
        obj = p[1].copy()
        obj.update(p[2])
        p[0] = obj

Response: A function to update the const_object_field_list field of a class.


Instruction:
Implement a function in Python 3 to
sort a list of triples by relation name.

Response:
def alphanum_order(triples):
    """
    Sort a list of triples by relation name.

    Embedded integers are sorted numerically, but otherwise the sorting
    is alphabetic.
    """
    return sorted(
        triples,
        key=lambda t: [
            int(t) if t.isdigit() else t
            for t in re.split(r'([0-9]+)', t.relation or '')
        ]
    )


Instruction:
Create a Python 3 function to
serialize the graph g from top to PENMAN notation.

Response:
def encode(g, top=None, cls=PENMANCodec, **kwargs):
    """
    Serialize the graph *g* from *top* to PENMAN notation.

    Args:
        g: the Graph object
        top: the node identifier for the top of the serialized graph; if
            unset, the original top of *g* is used
        cls: serialization codec class
        kwargs: keyword arguments passed to the constructor of *cls*
    Returns:
        the PENMAN-serialized string of the Graph *g*
    Example:

        >>> encode(Graph([('h', 'instance', 'hi')]))
        (h / hi)
    """
    codec = cls(**kwargs)
    return codec.encode(g, top=top)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def load(source, triples=False, cls=PENMANCodec, **kwargs):
    decode = cls(**kwargs).iterdecode
    if hasattr(source, 'read'):
        return list(decode(source.read()))
    else:
        with open(source) as fh:
            return list(decode(fh.read()))

Response: Deserialize a list of PENMAN - encoded graphs from a file - like object.


Instruction:
Here you have a function in Python 3, explain what it does
def dump(graphs, file, triples=False, cls=PENMANCodec, **kwargs):
    text = dumps(graphs, triples=triples, cls=cls, **kwargs)

    if hasattr(file, 'write'):
        print(text, file=file)
    else:
        with open(file, 'w') as fh:
            print(text, file=fh)

Response: Serialize each graph in graphs to PENMAN and write to file.


Instruction:
Write a Python 3 function for
serializing graphs to the PENMAN format.

Response:
def dumps(graphs, triples=False, cls=PENMANCodec, **kwargs):
    """
    Serialize each graph in *graphs* to the PENMAN format.

    Args:
        graphs: an iterable of Graph objects
        triples: if True, write graphs as triples instead of as PENMAN
    Returns:
        the string of serialized graphs
    """
    codec = cls(**kwargs)
    strings = [codec.encode(g, triples=triples) for g in graphs]
    return '\n\n'.join(strings)


Instruction:
Can you implement a function in Python 3 that
serializes the graph g from top to PENMAN notation.

Response:
def encode(self, g, top=None, triples=False):
        """
        Serialize the graph *g* from *top* to PENMAN notation.

        Args:
            g: the Graph object
            top: the node identifier for the top of the serialized
                graph; if unset, the original top of *g* is used
            triples: if True, serialize as a conjunction of logical triples
        Returns:
            the PENMAN-serialized string of the Graph *g*
        Example:

            >>> codec = PENMANCodec()
            >>> codec.encode(Graph([('h', 'instance', 'hi')]))
            (h / hi)
            >>> codec.encode(Graph([('h', 'instance', 'hi')]),
            ...                      triples=True)
            instance(h, hi)
        """
        if len(g.triples()) == 0:
            raise EncodeError('Cannot encode empty graph.')
        if triples:
            return self._encode_triple_conjunction(g, top=top)
        else:
            return self._encode_penman(g, top=top)


Instruction:
Given the following Python 3 function, write the documentation
def handle_triple(self, lhs, relation, rhs):
        relation = relation.replace(':', '', 1)  # remove leading :

        if self.is_relation_inverted(relation):  # deinvert
            source, target, inverted = rhs, lhs, True
            relation = self.invert_relation(relation)
        else:
            source, target, inverted = lhs, rhs, False

        source = _default_cast(source)
        target = _default_cast(target)

        if relation == '':  # set empty relations to None
            relation = None

        return Triple(source, relation, target, inverted)

Response: Process a triple from lhs to rhs and return a new triple.


Instruction:
Create a Python 3 function to
create a Graph object from a list of triples.

Response:
def triples_to_graph(self, triples, top=None):
        """
        Create a Graph from *triples* considering codec configuration.

        The Graph class does not know about information in the codec,
        so if Graph instantiation depends on special `TYPE_REL` or
        `TOP_VAR` values, use this function instead of instantiating
        a Graph object directly. This is also where edge
        normalization (de-inversion) and value type conversion occur
        (via handle_triple()).

        Args:
            triples: an iterable of (lhs, relation, rhs) triples
            top: node identifier of the top node
        Returns:
            a Graph object
        """
        inferred_top = triples[0][0] if triples else None
        ts = []
        for triple in triples:
            if triple[0] == self.TOP_VAR and triple[1] == self.TOP_REL:
                inferred_top = triple[2]
            else:
                ts.append(self.handle_triple(*triple))
        top = self.handle_triple(self.TOP_VAR, self.TOP_REL, top).target
        return Graph(ts, top=top or inferred_top)


Instruction:
Can you create a Python 3 function that
returns True if the relation is inverted.

Response:
def is_relation_inverted(self, relation):
        """
        Return True if *relation* is inverted.
        """
        return (
            relation in self._deinversions or
            (relation.endswith('-of') and relation not in self._inversions)
        )


Instruction:
Implement a function in Python 3 to
invert or deinvert relation.

Response:
def invert_relation(self, relation):
        """
        Invert or deinvert *relation*.
        """
        if self.is_relation_inverted(relation):
            rel = self._deinversions.get(relation, relation[:-3])
        else:
            rel = self._inversions.get(relation, relation + '-of')
        if rel is None:
             raise PenmanError(
                'Cannot (de)invert {}; not allowed'.format(relation)
            )
        return rel


Instruction:
Can you tell what is the following Python 3 function doing
def triples(self, source=None, relation=None, target=None):
        triplematch = lambda t: (
            (source is None or source == t.source) and
            (relation is None or relation == t.relation) and
            (target is None or target == t.target)
        )
        return list(filter(triplematch, self._triples))

Response: Return a list of triples filtered by their source relation or target.


Instruction:
Given the following Python 3 function, write the documentation
def edges(self, source=None, relation=None, target=None):
        edgematch = lambda e: (
            (source is None or source == e.source) and
            (relation is None or relation == e.relation) and
            (target is None or target == e.target)
        )
        variables = self.variables()
        edges = [t for t in self._triples if t.target in variables]
        return list(filter(edgematch, edges))

Response: Return a list of edges that are in the terminal graph.


Instruction:
Can you write a function in Python 3 where it
returns a list of all attributes that are in the current context.

Response:
def attributes(self, source=None, relation=None, target=None):
        """
        Return attributes filtered by their *source*, *relation*, or *target*.

        Attributes don't include triples where the target is a nonterminal.
        """
        attrmatch = lambda a: (
            (source is None or source == a.source) and
            (relation is None or relation == a.relation) and
            (target is None or target == a.target)
        )
        variables = self.variables()
        attrs = [t for t in self.triples() if t.target not in variables]
        return list(filter(attrmatch, attrs))


Instruction:
Create a Python 3 function to
return a mapping of variables to their re - entrancy count.

Response:
def reentrancies(self):
        """
        Return a mapping of variables to their re-entrancy count.

        A re-entrancy is when more than one edge selects a node as its
        target. These graphs are rooted, so the top node always has an
        implicit entrancy. Only nodes with re-entrancies are reported,
        and the count is only for the entrant edges beyond the first.
        Also note that these counts are for the interpreted graph, not
        for the linearized form, so inverted edges are always
        re-entrant.
        """
        entrancies = defaultdict(int)
        entrancies[self.top] += 1  # implicit entrancy to top
        for t in self.edges():
            entrancies[t.target] += 1
        return dict((v, cnt - 1) for v, cnt in entrancies.items() if cnt >= 2)


Instruction:
Can you generate the documentation for the following Python 3 function
def check_1d(inp):
    if isinstance(inp, list):
        return check_1d(np.array(inp))
    if isinstance(inp, np.ndarray):
        if inp.ndim == 1: # input is a vector
            return inp

Response: Checks input to be a vector. Converts lists to np. ndarray.


Instruction:
Implement a function in Python 3 to
check input to be a matrix. Converts lists of lists to np. ndarray.

Response:
def check_2d(inp):
    """
    Check input to be a matrix. Converts lists of lists to np.ndarray.

    Also allows the input to be a scipy sparse matrix.

    Parameters
    ----------
    inp : obj
        Input matrix

    Returns
    -------
    numpy.ndarray, scipy.sparse or None
        Input matrix or None

    Examples
    --------
    >>> check_2d([[0, 1], [2, 3]])
    [[0, 1], [2, 3]]

    >>> check_2d('test')
    None

    """
    if isinstance(inp, list):
        return check_2d(np.array(inp))
    if isinstance(inp, (np.ndarray, np.matrixlib.defmatrix.matrix)):
        if inp.ndim == 2: # input is a dense matrix
            return inp
    if sps.issparse(inp):
        if inp.ndim == 2: # input is a sparse matrix
            return inp


Instruction:
Can you generate the documentation for the following Python 3 function
def graph_to_laplacian(G, normalized=True):
    try:
        import networkx as nx
        if isinstance(G, nx.Graph):
            if normalized:
                return nx.normalized_laplacian_matrix(G)
            else:
                return nx.laplacian_matrix(G)
    except ImportError:
        pass
    try:
        import graph_tool.all as gt
        if isinstance(G, gt.Graph):
            if normalized:
                return gt.laplacian_type(G, normalized=True)
            else:
                return gt.laplacian(G)
    except ImportError:
        pass
    try:
        import igraph as ig
        if isinstance(G, ig.Graph):
            if normalized:
                return np.array(G.laplacian(normalized=True))
            else:
                return np.array(G.laplacian())
    except ImportError:
        pass

Response: Converts a graph from popular Python packages to Laplacian representation.


Instruction:
Create a Python 3 function to
convert a sparse or dence adjacency matrix to Laplacian.

Response:
def mat_to_laplacian(mat, normalized):
    """
    Converts a sparse or dence adjacency matrix to Laplacian.

    Parameters
    ----------
    mat : obj
        Input adjacency matrix. If it is a Laplacian matrix already, return it.
    normalized : bool
        Whether to use normalized Laplacian.
        Normalized and unnormalized Laplacians capture different properties of graphs, e.g. normalized Laplacian spectrum can determine whether a graph is bipartite, but not the number of its edges. We recommend using normalized Laplacian.

    Returns
    -------
    obj
        Laplacian of the input adjacency matrix

    Examples
    --------
    >>> mat_to_laplacian(numpy.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]), False)
    [[ 2, -1, -1], [-1,  2, -1], [-1, -1,  2]]

    """
    if sps.issparse(mat):
        if np.all(mat.diagonal()>=0): # Check diagonal
            if np.all((mat-sps.diags(mat.diagonal())).data <= 0): # Check off-diagonal elements
                return mat
    else:
        if np.all(np.diag(mat)>=0): # Check diagonal
            if np.all(mat - np.diag(mat) <= 0): # Check off-diagonal elements
                return mat
    deg = np.squeeze(np.asarray(mat.sum(axis=1)))
    if sps.issparse(mat):
        L = sps.diags(deg) - mat
    else:
        L = np.diag(deg) - mat
    if not normalized:
        return L
    with np.errstate(divide='ignore'):
        sqrt_deg = 1.0 / np.sqrt(deg)
    sqrt_deg[sqrt_deg==np.inf] = 0
    if sps.issparse(mat):
        sqrt_deg_mat = sps.diags(sqrt_deg)
    else:
        sqrt_deg_mat = np.diag(sqrt_deg)
    return sqrt_deg_mat.dot(L).dot(sqrt_deg_mat)


Instruction:
Write a Python 3 script for
updating Laplacian spectrum using lower and upper parts of the eigenspectrum.

Response:
def updown_linear_approx(eigvals_lower, eigvals_upper, nv):
    """
    Approximates Laplacian spectrum using upper and lower parts of the eigenspectrum.

    Parameters
    ----------
    eigvals_lower : numpy.ndarray
        Lower part of the spectrum, sorted
    eigvals_upper : numpy.ndarray
        Upper part of the spectrum, sorted
    nv : int
        Total number of nodes (eigenvalues) in the graph.

    Returns
    -------
    numpy.ndarray
        Vector of approximated eigenvalues

    Examples
    --------
    >>> updown_linear_approx([1, 2, 3], [7, 8, 9], 9)
    array([1,  2,  3,  4,  5,  6,  7,  8,  9])

    """
    nal = len(eigvals_lower)
    nau = len(eigvals_upper)
    if nv < nal + nau:
        raise ValueError('Number of supplied eigenvalues ({0} lower and {1} upper) is higher than number of nodes ({2})!'.format(nal, nau, nv))
    ret = np.zeros(nv)
    ret[:nal] = eigvals_lower
    ret[-nau:] = eigvals_upper
    ret[nal-1:-nau+1] = np.linspace(eigvals_lower[-1], eigvals_upper[0], nv-nal-nau+2)
    return ret


Instruction:
How would you explain what the following Python 3 function does
def eigenvalues_auto(mat, n_eivals='auto'):
    do_full = True
    n_lower = 150
    n_upper = 150
    nv = mat.shape[0]
    if n_eivals == 'auto':
        if mat.shape[0] > 1024:
            do_full = False
    if n_eivals == 'full':
        do_full = True
    if isinstance(n_eivals, int):
        n_lower = n_upper = n_eivals
        do_full = False
    if isinstance(n_eivals, tuple):
        n_lower, n_upper = n_eivals
        do_full = False
    if do_full and sps.issparse(mat):
        mat = mat.todense()
    if sps.issparse(mat):
        if n_lower == n_upper:
            tr_eivals = spsl.eigsh(mat, 2*n_lower, which='BE', return_eigenvectors=False)
            return updown_linear_approx(tr_eivals[:n_upper], tr_eivals[n_upper:], nv)
        else:
            lo_eivals = spsl.eigsh(mat, n_lower, which='SM', return_eigenvectors=False)[::-1]
            up_eivals = spsl.eigsh(mat, n_upper, which='LM', return_eigenvectors=False)
            return updown_linear_approx(lo_eivals, up_eivals, nv)
    else:
        if do_full:
            return spl.eigvalsh(mat)
        else:
            lo_eivals = spl.eigvalsh(mat, eigvals=(0, n_lower-1))
            up_eivals = spl.eigvalsh(mat, eigvals=(nv-n_upper-1, nv-1))
            return updown_linear_approx(lo_eivals, up_eivals, nv)

Response: A function that computes the spectrum of a given Laplacian matrix and returns the vector of approximated eigenvalues.


Instruction:
Explain what the following Python 3 code does
def netlsd(inp, timescales=np.logspace(-2, 2, 250), kernel='heat', eigenvalues='auto', normalization='empty', normalized_laplacian=True):
    if kernel not in {'heat', 'wave'}:
        raise AttributeError('Unirecognized kernel type: expected one of [\'heat\', \'wave\'], got {0}'.format(kernel))
    if not isinstance(normalized_laplacian, bool):
        raise AttributeError('Unknown Laplacian type: expected bool, got {0}'.format(normalized_laplacian))
    if not isinstance(eigenvalues, (int, tuple, str)):
        raise AttributeError('Unirecognized requested eigenvalue number: expected type of [\'str\', \'tuple\', or \'int\'], got {0}'.format(type(eigenvalues)))
    if not isinstance(timescales, np.ndarray):
        raise AttributeError('Unirecognized timescales data type: expected np.ndarray, got {0}'.format(type(timescales)))
    if timescales.ndim != 1:
        raise AttributeError('Unirecognized timescales dimensionality: expected a vector, got {0}-d array'.format(timescales.ndim))
    if normalization not in {'complete', 'empty', 'none', True, False, None}:
        if not isinstance(normalization, np.ndarray):
            raise AttributeError('Unirecognized normalization type: expected one of [\'complete\', \'empty\', None or np.ndarray], got {0}'.format(normalization))
        if normalization.ndim != 1:
            raise AttributeError('Unirecognized normalization dimensionality: expected a vector, got {0}-d array'.format(normalization.ndim))
        if timescales.shape[0] != normalization.shape[0]:
            raise AttributeError('Unirecognized normalization dimensionality: expected {0}-length vector, got length {1}'.format(timescales.shape[0], normalization.shape[0]))

    eivals = check_1d(inp)
    if eivals is None:
        mat = check_2d(inp)
        if mat is None:
            mat = graph_to_laplacian(inp, normalized_laplacian)
            if mat is None:
                raise ValueError('Unirecognized input type: expected one of [\'np.ndarray\', \'scipy.sparse\', \'networkx.Graph\',\' graph_tool.Graph,\' or \'igraph.Graph\'], got {0}'.format(type(inp)))
        else:
            mat = mat_to_laplacian(inp, normalized_laplacian)
        eivals = eigenvalues_auto(mat, eigenvalues)
    if kernel == 'heat':
        return _hkt(eivals, timescales, normalization, normalized_laplacian)
    else:
        return _wkt(eivals, timescales, normalization, normalized_laplacian)

Response: This function computes the NetLSD signature from some input time series and kernels.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def heat(inp, timescales=np.logspace(-2, 2, 250), eigenvalues='auto', normalization='empty', normalized_laplacian=True):
    return netlsd(inp, timescales, 'heat', eigenvalues, normalization, normalized_laplacian)

Response: Compute the heat kernel trace from some input time series timescales and normalization.


Instruction:
How would you explain what the following Python 3 function does
def wave(inp, timescales=np.linspace(0, 2*np.pi, 250), eigenvalues='auto', normalization='empty', normalized_laplacian=True):
    return netlsd(inp, timescales, 'wave', eigenvalues, normalization, normalized_laplacian)

Response: This function computes the wave kernel trace from some input time series timescales and normalization.


Instruction:
Make a summary of the following Python 3 code
def _hkt(eivals, timescales, normalization, normalized_laplacian):
    nv = eivals.shape[0]
    hkt = np.zeros(timescales.shape)
    for idx, t in enumerate(timescales):
        hkt[idx] = np.sum(np.exp(-t * eivals))
    if isinstance(normalization, np.ndarray):
        return hkt / normalization
    if normalization == 'empty' or normalization == True:
        return hkt / nv
    if normalization == 'complete':
        if normalized_laplacian:
            return hkt / (1 + (nv - 1) * np.exp(-timescales))
        else:
            return hkt / (1 + nv * np.exp(-nv * timescales))
    return hkt

Response: Compute the heat kernel trace from given eigenvalues timescales and normalization.


Instruction:
Write a Python 3 script for
computing the wave kernel trace from given eigenvalues timescales and normalization.

Response:
def _wkt(eivals, timescales, normalization, normalized_laplacian):
    """
    Computes wave kernel trace from given eigenvalues, timescales, and normalization.

    For precise definition, please refer to "NetLSD: Hearing the Shape of a Graph" by A. Tsitsulin, D. Mottin, P. Karras, A. Bronstein, E. Müller. Published at KDD'18.

    Parameters
    ----------
    eivals : numpy.ndarray
        Eigenvalue vector
    timescales : numpy.ndarray
        Vector of discrete timesteps for the kernel computation
    normalization : str or numpy.ndarray
        Either 'empty', 'complete' or None.
        If None or any ther value, return unnormalized wave kernel trace.
        For the details how 'empty' and 'complete' are computed, please refer to the paper.
        If np.ndarray, they are treated as exact normalization constants
    normalized_laplacian: bool
        Defines whether the eigenvalues came from the normalized Laplacian. It only affects 'complete' normalization.

    Returns
    -------
    numpy.ndarray
        Wave kernel trace signature

    """
    nv = eivals.shape[0]
    wkt = np.zeros(timescales.shape)
    for idx, t in enumerate(timescales):
        wkt[idx] = np.sum(np.exp(-1j * t * eivals))
    if isinstance(normalization, np.ndarray):
        return hkt / normalization
    if normalization == 'empty' or normalization == True:
        return wkt / nv
    if normalization == 'complete':
        if normalized_laplacian:
            return wkt / (1 + (nv - 1) * np.cos(timescales))
        else:
            return wkt / (1 + (nv - 1) * np.cos(nv * timescales))
    return wkt


Instruction:
Can you implement a function in Python 3 that
removes all the elements from the list.

Response:
def clear(self):
        """Remove all the elements from the list."""
        self._len = 0
        del self._maxes[:]
        del self._lists[:]
        del self._keys[:]
        del self._index[:]


Instruction:
Implement a function in Python 3 to
remove the first occurrence of val from the internal list of the internal list of the internal list of the internal list of the internal list of the internal list.

Response:
def discard(self, val):
        """
        Remove the first occurrence of *val*.

        If *val* is not a member, does nothing.
        """
        _maxes = self._maxes

        if not _maxes:
            return

        key = self._key(val)
        pos = bisect_left(_maxes, key)

        if pos == len(_maxes):
            return

        _keys = self._keys
        _lists = self._lists
        idx = bisect_left(_keys[pos], key)

        len_keys = len(_keys)
        len_sublist = len(_keys[pos])

        while True:
            if _keys[pos][idx] != key:
                return
            if _lists[pos][idx] == val:
                self._delete(pos, idx)
                return
            idx += 1
            if idx == len_sublist:
                pos += 1
                if pos == len_keys:
                    return
                len_sublist = len(_keys[pos])
                idx = 0


Instruction:
How would you code a function in Python 3 to
remove first occurrence of val from the internal list. Raises ValueError if val is not present.

Response:
def remove(self, val):
        """
        Remove first occurrence of *val*.

        Raises ValueError if *val* is not present.
        """
        _maxes = self._maxes

        if not _maxes:
            raise ValueError('{0} not in list'.format(repr(val)))

        key = self._key(val)
        pos = bisect_left(_maxes, key)

        if pos == len(_maxes):
            raise ValueError('{0} not in list'.format(repr(val)))

        _keys = self._keys
        _lists = self._lists
        idx = bisect_left(_keys[pos], key)

        len_keys = len(_keys)
        len_sublist = len(_keys[pos])

        while True:
            if _keys[pos][idx] != key:
                raise ValueError('{0} not in list'.format(repr(val)))
            if _lists[pos][idx] == val:
                self._delete(pos, idx)
                return
            idx += 1
            if idx == len_sublist:
                pos += 1
                if pos == len_keys:
                    raise ValueError('{0} not in list'.format(repr(val)))
                len_sublist = len(_keys[pos])
                idx = 0


Instruction:
Can you generate the documentation for the following Python 3 function
def _delete(self, pos, idx):
        _maxes, _lists, _keys, _index = self._maxes, self._lists, self._keys, self._index

        keys_pos = _keys[pos]
        lists_pos = _lists[pos]

        del keys_pos[idx]
        del lists_pos[idx]
        self._len -= 1

        len_keys_pos = len(keys_pos)

        if len_keys_pos > self._half:

            _maxes[pos] = keys_pos[-1]

            if len(_index) > 0:
                child = self._offset + pos
                while child > 0:
                    _index[child] -= 1
                    child = (child - 1) >> 1
                _index[0] -= 1

        elif len(_keys) > 1:

            if not pos:
                pos += 1

            prev = pos - 1
            _keys[prev].extend(_keys[pos])
            _lists[prev].extend(_lists[pos])
            _maxes[prev] = _keys[prev][-1]

            del _keys[pos]
            del _lists[pos]
            del _maxes[pos]
            del _index[:]

            self._expand(prev)

        elif len_keys_pos:

            _maxes[pos] = keys_pos[-1]

        else:

            del _keys[pos]
            del _lists[pos]
            del _maxes[pos]
            del _index[:]

Response: Delete the item at the given position.


Instruction:
Implement a Python 3 function for
converting an index pair to a single index that corresponds to the position of the value in the sorted list at the given position.

Response:
def _loc(self, pos, idx):
        """Convert an index pair (alpha, beta) into a single index that corresponds to
        the position of the value in the sorted list.

        Most queries require the index be built. Details of the index are
        described in self._build_index.

        Indexing requires traversing the tree from a leaf node to the root. The
        parent of each node is easily computable at (pos - 1) // 2.

        Left-child nodes are always at odd indices and right-child nodes are
        always at even indices.

        When traversing up from a right-child node, increment the total by the
        left-child node.

        The final index is the sum from traversal and the index in the sublist.

        For example, using the index from self._build_index:

        _index = 14 5 9 3 2 4 5
        _offset = 3

        Tree:

                 14
              5      9
            3   2  4   5

        Converting index pair (2, 3) into a single index involves iterating like
        so:

        1. Starting at the leaf node: offset + alpha = 3 + 2 = 5. We identify
           the node as a left-child node. At such nodes, we simply traverse to
           the parent.

        2. At node 9, position 2, we recognize the node as a right-child node
           and accumulate the left-child in our total. Total is now 5 and we
           traverse to the parent at position 0.

        3. Iteration ends at the root.

        Computing the index is the sum of the total and beta: 5 + 3 = 8.
        """
        if not pos:
            return idx

        _index = self._index

        if not len(_index):
            self._build_index()

        total = 0

        # Increment pos to point in the index to len(self._lists[pos]).

        pos += self._offset

        # Iterate until reaching the root of the index tree at pos = 0.

        while pos:

            # Right-child nodes are at odd indices. At such indices
            # account the total below the left child node.

            if not (pos & 1):
                total += _index[pos - 1]

            # Advance pos to the parent node.

            pos = (pos - 1) >> 1

        return total + idx


Instruction:
Can you generate a brief explanation for the following Python 3 code
def islice(self, start=None, stop=None, reverse=False):
        _len = self._len

        if not _len:
            return iter(())

        start, stop, step = self._slice(slice(start, stop))

        if start >= stop:
            return iter(())

        _pos = self._pos

        min_pos, min_idx = _pos(start)

        if stop == _len:
            max_pos = len(self._lists) - 1
            max_idx = len(self._lists[-1])
        else:
            max_pos, max_idx = _pos(stop)

        return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)

Response: Returns an iterator that slices self from start to stop index inclusive and exclusive respectively.


Instruction:
Can you generate the documentation for the following Python 3 function
def irange(self, minimum=None, maximum=None, inclusive=(True, True),
               reverse=False):
        """
        Create an iterator of values between `minimum` and `maximum`.

        `inclusive` is a pair of booleans that indicates whether the minimum
        and maximum ought to be included in the range, respectively. The
        default is (True, True) such that the range is inclusive of both
        minimum and maximum.

        Both `minimum` and `maximum` default to `None` which is automatically
        inclusive of the start and end of the list, respectively.

        When `reverse` is `True` the values are yielded from the iterator in
        reverse order; `reverse` defaults to `False`.
        """
        minimum = self._key(minimum) if minimum is not None else None
        maximum = self._key(maximum) if maximum is not None else None
        return self.irange_key(
            min_key=minimum, max_key=maximum,
            inclusive=inclusive, reverse=reverse,
        )

Response: Create an iterator of values between minimum and maximum.