Instruction:
Can you generate the documentation for the following Python 3 function
def get_image_ancestry(self, image_id):
        return self._http_call(self.IMAGE_ANCESTRY, get, image_id=image_id)

Response: Get ancestry for an image


Instruction:
Write a Python 3 function for
getting tags for a repository.

Response:
def get_repository_tags(self, namespace, repository):
        """GET /v1/repositories/(namespace)/(repository)/tags"""
        return self._http_call(self.TAGS, get,
                               namespace=namespace, repository=repository)


Instruction:
Create a Python 3 function to
get the image id for a given tag

Response:
def get_image_id(self, namespace, respository, tag):
        """GET /v1/repositories/(namespace)/(repository)/tags/(tag*)"""
        return self._http_call(self.TAGS + '/' + tag, get,
                               namespace=namespace, repository=respository)


Instruction:
Implement a Python 3 function for
getting the JSON data for a given tag

Response:
def get_tag_json(self, namespace, repository, tag):
        """GET /v1/repositories(namespace)/(repository)tags(tag*)/json"""
        return self._http_call(self.TAGS + '/' + tag + '/json', get,
                               namespace=namespace, repository=repository)


Instruction:
Explain what the following Python 3 code does
def delete_repository_tag(self, namespace, repository, tag):
        return self._http_call(self.TAGS + '/' + tag, delete,
                               namespace=namespace, repository=repository)

Response: Delete a repository tag


Instruction:
How would you code a function in Python 3 to
set the tag for an image

Response:
def set_tag(self, namespace, repository, tag, image_id):
        """PUT /v1/repositories/(namespace)/(repository)/tags/(tag*)"""
        return self._http_call(self.TAGS + '/' + tag, put, data=image_id,
                               namespace=namespace, repository=repository)


Instruction:
Can you tell what is the following Python 3 function doing
def _http_response(self, url, method, data=None, content_type=None,
                       schema=None, **kwargs):
        """url -> full target url
           method -> method from requests
           data -> request body
           kwargs -> url formatting args
        """

        if schema is None:
            schema = self.schema_2

        header = {
            'content-type': content_type or 'application/json',
            'Accept': schema,
        }

        # Token specific part. We add the token in the header if necessary
        auth = self.auth
        token_required = auth.token_required
        token = auth.token
        desired_scope = auth.desired_scope
        scope = auth.scope

        if token_required:
            if not token or desired_scope != scope:
                logger.debug("Getting new token for scope: %s", desired_scope)
                auth.get_new_token()

            header['Authorization'] = 'Bearer %s' % self.auth.token

        if data and not content_type:
            data = json.dumps(data)

        path = url.format(**kwargs)
        logger.debug("%s %s", method.__name__.upper(), path)
        response = method(self.host + path,
                          data=data, headers=header, **self.method_kwargs)
        logger.debug("%s %s", response.status_code, response.reason)
        response.raise_for_status()

        return response

Response: Returns an HTTP response object.


Instruction:
Given the following Python 3 function, write the documentation
def begin(self):
		# Check manufacturer and device ID match expected values.
		mid = self._device.readU16BE(MCP9808_REG_MANUF_ID)
		did = self._device.readU16BE(MCP9808_REG_DEVICE_ID)
		self._logger.debug('Read manufacturer ID: {0:04X}'.format(mid))
		self._logger.debug('Read device ID: {0:04X}'.format(did))
		return mid == 0x0054 and did == 0x0400

Response:
Start taking temperature measurements. Returns True if the device is
	intialized False otherwise.


Instruction:
Write a Python 3 function that can
read sensor and return its value in degrees celsius.

Response:
def readTempC(self):
		"""Read sensor and return its value in degrees celsius."""
		# Read temperature register value.
		t = self._device.readU16BE(MCP9808_REG_AMBIENT_TEMP)
		self._logger.debug('Raw ambient temp register value: 0x{0:04X}'.format(t & 0xFFFF))
		# Scale and convert to signed value.
		temp = (t & 0x0FFF) / 16.0
		if t & 0x1000:
			temp -= 256.0
		return temp


Instruction:
Explain what the following Python 3 code does
def crud_url_name(model, action, prefix=None):
    if prefix is None:
        prefix = ""
    app_label = model._meta.app_label
    model_lower = model.__name__.lower()
    return '%s%s_%s_%s' % (prefix, app_label, model_lower, action)

Response: Returns url name for given model and action.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_fields(model, include=None):
    fields = OrderedDict()
    info = model._meta
    if include:
        selected = [info.get_field(name) for name in include]
    else:
        selected = [field for field in info.fields if field.editable]
    for field in selected:
        fields[field.name] = field.verbose_name
    return fields

Response: Returns ordered dict in format field = verbose_name


Instruction:
How would you explain what the following Python 3 function does
def crud_url(instance_or_model, action, prefix=None, additional_kwargs=None):
    if additional_kwargs is None:
        additional_kwargs = {}
    if isinstance(instance_or_model, Model):
        additional_kwargs['pk'] = instance_or_model.pk
        model_name = instance_or_model._meta.model
    else:
        model_name = instance_or_model
    return reverse(
        crud_url_name(model_name, action, prefix),
        kwargs=additional_kwargs
    )

Response: Shortcut function returns URL for instance or model and action.


Instruction:
Write a Python 3 script for
returning a permission name using Django naming convention.

Response:
def crud_permission_name(model, action, convert=True):
    """Returns permission name using Django naming convention: app_label.action_object.

    If `convert` is True, `create` and `update` actions would be renamed
    to `add` and `change`.
    """
    app_label = model._meta.app_label
    model_lower = model.__name__.lower()
    if convert:
        action = MAP_PERMISSION_ACTIONS.get(action, action)
    return '%s.%s_%s' % (
        app_label,
        action,
        model_lower
    )


Instruction:
How would you explain what the following Python 3 function does
def format_value(obj, field_name):
    display_func = getattr(obj, 'get_%s_display' % field_name, None)
    if display_func:
        return display_func()
    value = getattr(obj, field_name)

    if isinstance(value, models.fields.files.FieldFile):
        if value:
            return mark_safe('%s' % (
                value.url,
                os.path.basename(value.name),
            ))
        else:
            return ''

    if isinstance(value, models.Model):
        return format_value_instance(value)

    if isinstance(value, models.Manager):
        return mark_safe(', '.join(
            [format_value_instance(instance) for instance in value.all()]
        ))
    if value is None:
        value = ""
    return value

Response:
Simple value formatting.

    If value is model instance returns link to detail view if exists.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def crud_fields(obj, fields=None):
    if fields is None:
        fields = utils.get_fields(type(obj))
    elif isinstance(fields, six.string_types):
        field_names = [f.strip() for f in fields.split(',')]
        fields = utils.get_fields(type(obj), include=field_names)
    return {
        'object': obj,
        'fields': fields,
    }

Response:
Display object fields in table rows::
            object id fields to include


Instruction:
How would you implement a function in Python 3 that
returns a list of fields for a given model.

Response:
def get_fields(model, fields=None):
    """
    Assigns fields for model.
    """
    include = [f.strip() for f in fields.split(',')] if fields else None
    return utils.get_fields(
        model,
        include
    )


Instruction:
Create a Python 3 function for
returning a list of url patterns for a given model.

Response:
def crud_urls(model,
              list_view=None,
              create_view=None,
              update_view=None,
              detail_view=None,
              delete_view=None,
              url_prefix=None,
              name_prefix=None,
              list_views=None,
              **kwargs):
    """Returns a list of url patterns for model.

    :param list_view:
    :param create_view:
    :param update_view:
    :param detail_view:
    :param delete_view:
    :param url_prefix: prefix to prepend, default is `'$'`
    :param name_prefix: prefix to prepend to name, default is empty string
    :param list_views(dict): additional list views
    :param **kwargs: additional detail views
    :returns: urls
    """
    if url_prefix is None:
        url_prefix = r'^'
    urls = []
    if list_view:
        urls.append(url(
            url_prefix + '$',
            list_view,
            name=utils.crud_url_name(model, utils.ACTION_LIST, name_prefix)
        ))
    if create_view:
        urls.append(url(
            url_prefix + r'new/$',
            create_view,
            name=utils.crud_url_name(model, utils.ACTION_CREATE, name_prefix)
        ))
    if detail_view:
        urls.append(url(
            url_prefix + r'(?P<pk>\d+)/$',
            detail_view,
            name=utils.crud_url_name(model, utils.ACTION_DETAIL, name_prefix)
        ))
    if update_view:
        urls.append(url(
            url_prefix + r'(?P<pk>\d+)/edit/$',
            update_view,
            name=utils.crud_url_name(model, utils.ACTION_UPDATE, name_prefix)
        ))
    if delete_view:
        urls.append(url(
            url_prefix + r'(?P<pk>\d+)/remove/$',
            delete_view,
            name=utils.crud_url_name(model, utils.ACTION_DELETE, name_prefix)
        ))

    if list_views is not None:
        for name, view in list_views.items():
            urls.append(url(
                url_prefix + r'%s/$' % name,
                view,
                name=utils.crud_url_name(model, name, name_prefix)
            ))

    for name, view in kwargs.items():
        urls.append(url(
            url_prefix + r'(?P<pk>\d+)/%s/$' % name,
            view,
            name=utils.crud_url_name(model, name, name_prefix)
        ))
    return urls


Instruction:
Can you tell what is the following Python 3 function doing
def crud_for_model(model, urlprefix=None):
    model_lower = model.__name__.lower()

    if urlprefix is None:
        urlprefix = ''
    urlprefix += model_lower + '/'

    urls = crud_urls(
        model,
        list_view=CRUDListView.as_view(model=model),
        create_view=CRUDCreateView.as_view(model=model),
        detail_view=CRUDDetailView.as_view(model=model),
        update_view=CRUDUpdateView.as_view(model=model),
        delete_view=CRUDDeleteView.as_view(model=model),
        url_prefix=urlprefix,
    )
    return urls

Response: Returns list of url items to CRUD a model.


Instruction:
How would you code a function in Python 3 to
return list of url items to CRUD an app.

Response:
def crud_for_app(app_label, urlprefix=None):
    """
    Returns list of ``url`` items to CRUD an app.
    """
    if urlprefix is None:
        urlprefix = app_label + '/'
    app = apps.get_app_config(app_label)
    urls = []
    for model in app.get_models():
        urls += crud_for_model(model, urlprefix)
    return urls


Instruction:
Can you generate the documentation for the following Python 3 function
def get_context_data(self, **kwargs):
        context = super(CRUDMixin, self).get_context_data(**kwargs)
        context.update({
            'model_verbose_name': self.model._meta.verbose_name,
            'model_verbose_name_plural': self.model._meta.verbose_name_plural,
        })

        context['fields'] = utils.get_fields(self.model)

        if hasattr(self, 'object') and self.object:
            for action in utils.INSTANCE_ACTIONS:
                try:
                    url = reverse(
                        utils.crud_url_name(self.model, action),
                        kwargs={'pk': self.object.pk})
                except NoReverseMatch:  # pragma: no cover
                    url = None
                context['url_%s' % action] = url

        for action in utils.LIST_ACTIONS:
            try:
                url = reverse(utils.crud_url_name(self.model, action))
            except NoReverseMatch:  # pragma: no cover
                url = None
            context['url_%s' % action] = url

        return context

Response: Adds available urls and names.


Instruction:
Explain what the following Python 3 code does
def get_template_names(self):
        names = super(CRUDMixin, self).get_template_names()
        if self.crud_template_name:
            names.append(self.crud_template_name)
        return names

Response: Returns a list of all the template names that are available for this application.


Instruction:
Explain what the following Python 3 code does
def python_value(self, value):
        value = super(JSONField, self).python_value(value)

        if value is not None:
            return flask.json.loads(value, **self._load_kwargs)

Response: Return the JSON in the database as a dict.


Instruction:
Write a Python 3 function that can
store the value in the database.

Response:
def db_value(self, value):
        """Store the value in the database.

        If the value is a dict like object, it is converted to a string before
        storing.
        """
        # Everything is encoded being before being surfaced
        value = flask.json.dumps(value)

        return super(JSONField, self).db_value(value)


Instruction:
How would you code a function in Python 3 to
add the attribute to the field in question so this always gets deserialzed into the field name without _id.

Response:
def _add_to_schema(self, field_name, schema):
        """Set the ``attribute`` attr to the field in question so this always
        gets deserialzed into the field name without ``_id``.

        Args:
            field_name (str): The name of the field (the attribute name being
                set in the schema).
            schema (marshmallow.Schema): The actual parent schema this field
               belongs to.
        """
        super(ForeignKeyField, self)._add_to_schema(field_name, schema)

        if self.get_field_value('convert_fks', default=True):
            self.attribute = field_name.replace('_id', '')


Instruction:
How would you implement a function in Python 3 that
serializes the ID value back to the Peewee model.

Response:
def _serialize(self, value, attr, obj):
        """Grab the ID value off the Peewee model so we serialize an ID back.
        """
        # this might be an optional field
        if value:
            value = value.id

        return super(ForeignKeyField, self)._serialize(value, attr, obj)


Instruction:
Make a summary of the following Python 3 code
def _discover_ideal_backend(orm_backend):
    if orm_backend:
        return orm_backend

    if peewee is not MISSING and sqlalchemy is not MISSING:
        raise RuntimeError('Both PeeWee and SQLAlchemy detected as installed, '
                           'but no explicit backend provided! Please specify '
                           'one!')
    if peewee is not MISSING:
        return _PEEWEE_BACKEND
    elif sqlalchemy is not MISSING:
        return _SQLALCHEMY_BACKEND
    else:
        return MISSING

Response: Auto - discover the ideal backend based on what is installed.


Instruction:
Implement a Python 3 function for
initializing the PeeWee extension with the application that was created.

Response:
def _init_peewee_ext(cls, app, dummy_configuration=None,
                         dummy_configure_args=None):
        """Init the actual PeeWee extension with the app that was created.

        Since PeeWee requires the ``DATABASE`` config parameter to be present
        IMMEDIATELY upon initializing the application, we need to delay this
        construction. This is because, in standard use, we will create the app
        and attempt to init this extension BEFORE we configure the app, which
        is totally fine. To fix this, we just need to set this up to try and
        run after every call to configure. If there is not ``DATABASE`` config
        parameter present when run, this method does nothing other than
        reschedule itself to run in the future.

        In all cases, this is a Post Configure Hook that should RUN ONCE!

        Args:
            app (flask.Flask): The application you want to init the PeeWee
                Flask extension for. Hint: if you need to use this as
                a callback, use a partial to provide this.
            dummy_configuration (dict): The resulting application configuration
                that the post_configure hook provides to all of it's callbacks.
                We will NEVER use this, but since we utilize the post_configure
                system to register this for complicated apps, we gotta accept
                it.
            dummy_configure_args (list[object]): The args passed to the
                :meth:`configure` function that triggered this callback. Just
                like the above arg, we'll never use it, but we must accept it.
        """
        # the database still isn't present, go ahead and register the callback
        # again, so we can try later.
        if 'DATABASE' not in app.config:
            app.add_post_configure_callback(partial(cls._init_peewee_ext, app),
                                            run_once=True)
            return

        _PEEWEE_EXT.init_app(app)


Instruction:
Write a Python 3 function that can
configure the application through a varied number of sources of type dict - like or dict - like.

Response:
def configure(self, *args, **kwargs):
        """Configure the Application through a varied number of sources of
        different types.

        This function chains multiple possible configuration methods together
        in order to just "make it work". You can pass multiple configuration
        sources in to the method and each one will be tried in a sane fashion.
        Later sources will override earlier sources if keys collide. For
        example:

        .. code:: python

            from application import default_config
            app.configure(default_config, os.environ, '.secrets')

        In the above example, values stored in ``default_config`` will be
        loaded first, then overwritten by those in ``os.environ``, and so on.

        An endless number of configuration sources may be passed.

        Configuration sources are type checked and processed according to the
        following rules:

        * ``string`` - if the source is a ``str``, we will assume it is a file
          or module that should be loaded. If the file ends in ``.json``, then
          :meth:`flask.Config.from_json` is used; if the file ends in ``.py``
          or ``.cfg``, then :meth:`flask.Config.from_pyfile` is used; if the
          module has any other extension we assume it is an import path, import
          the module and pass that to :meth:`flask.Config.from_object`. See
          below for a few more semantics on module loading.
        * ``dict-like`` - if the source is ``dict-like``, then
          :meth:`flask.Config.from_mapping` will be used. ``dict-like`` is
          defined as anything implementing an ``items`` method that returns
          a tuple of ``key``, ``val``.
        * ``class`` or ``module`` - if the source is an uninstantiated
          ``class`` or ``module``, then :meth:`flask.Config.from_object` will
          be used.

        Just like Flask's standard configuration, only uppercased keys will be
        loaded into the config.

        If the item we are passed is a ``string`` and it is determined to be
        a possible Python module, then a leading ``.`` is relevant. If
        a leading ``.`` is provided, we assume that the module to import is
        located in the current package and operate as such; if it begins with
        anything else we assume the import path provided is absolute. This
        allows you to source configuration stored in a module in your package,
        or in another package.

        Args:
            *args (object):
                Any object you want us to try to configure from.

        Keyword Args:
            whitelist_keys_from_mappings (bool):
                Should we whitelist the keys we pull from mappings? Very useful
                if you're passing in an entire OS ``environ`` and you want to
                omit things like ``LESSPIPE``. If no whitelist is provided, we
                use the pre-existing config keys as a whitelist.
            whitelist (list[str]):
                An explicit list of keys that should be allowed. If provided
                and ``whitelist_keys`` is ``True``, we will use that as our
                whitelist instead of pre-existing app config keys.
        """
        whitelist_keys_from_mappings = kwargs.get(
            'whitelist_keys_from_mappings', False
        )
        whitelist = kwargs.get('whitelist')

        for item in args:
            if isinstance(item, string_types):
                _, ext = splitext(item)

                if ext == '.json':
                    self._configure_from_json(item)
                elif ext in ('.cfg', '.py'):
                    self._configure_from_pyfile(item)
                else:
                    self._configure_from_module(item)

            elif isinstance(item, (types.ModuleType, type)):
                self._configure_from_object(item)

            elif hasattr(item, 'items'):
                # assume everything else is a mapping like object; ``.items()``
                # is what Flask uses under the hood for this method
                # @TODO: This doesn't handle the edge case of using a tuple of
                # two element tuples to config; but Flask does that. IMO, if
                # you do that, you're a monster.
                self._configure_from_mapping(
                    item,
                    whitelist_keys=whitelist_keys_from_mappings,
                    whitelist=whitelist
                )

            else:
                raise TypeError("Could not determine a valid type for this"
                                " configuration object: `{}`!".format(item))

        # we just finished here, run the post configure callbacks
        self._run_post_configure_callbacks(args)


Instruction:
Write a Python 3 function for
configuring from a module by import path.

Response:
def _configure_from_module(self, item):
        """Configure from a module by import path.

        Effectively, you give this an absolute or relative import path, it will
        import it, and then pass the resulting object to
        ``_configure_from_object``.

        Args:
            item (str):
                A string pointing to a valid import path.

        Returns:
            fleaker.App:
                Returns itself.
        """
        package = None
        if item[0] == '.':
            package = self.import_name

        obj = importlib.import_module(item, package=package)

        self.config.from_object(obj)

        return self


Instruction:
Create a Python 3 function for
configuring from a mapping or dict like object.

Response:
def _configure_from_mapping(self, item, whitelist_keys=False,
                                whitelist=None):
        """Configure from a mapping, or dict, like object.

        Args:
            item (dict):
                A dict-like object that we can pluck values from.

        Keyword Args:
            whitelist_keys (bool):
                Should we whitelist the keys before adding them to the
                configuration? If no whitelist is provided, we use the
                pre-existing config keys as a whitelist.
            whitelist (list[str]):
                An explicit list of keys that should be allowed. If provided
                and ``whitelist_keys`` is true, we will use that as our
                whitelist instead of pre-existing app config keys.

        Returns:
            fleaker.App:
                Returns itself.
        """
        if whitelist is None:
            whitelist = self.config.keys()

        if whitelist_keys:
            item = {k: v for k, v in item.items() if k in whitelist}

        self.config.from_mapping(item)

        return self


Instruction:
Implement a Python 3 function for
configuring from the entire set of available environment variables.

Response:
def configure_from_environment(self, whitelist_keys=False, whitelist=None):
        """Configure from the entire set of available environment variables.

        This is really a shorthand for grabbing ``os.environ`` and passing to
        :meth:`_configure_from_mapping`.

        As always, only uppercase keys are loaded.

        Keyword Args:
            whitelist_keys (bool):
                Should we whitelist the keys by only pulling those that are
                already present in the config? Useful for avoiding adding
                things like ``LESSPIPE`` to your app config. If no whitelist is
                provided, we use the current config keys as our whitelist.
            whitelist (list[str]):
                An explicit list of keys that should be allowed. If provided
                and ``whitelist_keys`` is true, we will use that as our
                whitelist instead of pre-existing app config keys.

        Returns:
            fleaker.base.BaseApplication:
                Returns itself.
        """
        self._configure_from_mapping(os.environ, whitelist_keys=whitelist_keys,
                                     whitelist=whitelist)

        return self


Instruction:
Explain what the following Python 3 code does
def add_post_configure_callback(self, callback, run_once=False):
        if run_once:
            self._post_configure_callbacks['single'].append(callback)
        else:
            self._post_configure_callbacks['multiple'].append(callback)

        return self

Response: Adds a callback to be run after every application s current configuration is set.


Instruction:
How would you implement a function in Python 3 that
runs all post configure callbacks that have been set for this entry point.

Response:
def _run_post_configure_callbacks(self, configure_args):
        """Run all post configure callbacks we have stored.

        Functions are passed the configuration that resulted from the call to
        :meth:`configure` as the first argument, in an immutable form; and are
        given the arguments passed to :meth:`configure` for the second
        argument.

        Returns from callbacks are ignored in all fashion.

        Args:
            configure_args (list[object]):
                The full list of arguments passed to :meth:`configure`.

        Returns:
            None:
                Does not return anything.
        """
        resulting_configuration = ImmutableDict(self.config)

        # copy callbacks in case people edit them while running
        multiple_callbacks = copy.copy(
            self._post_configure_callbacks['multiple']
        )
        single_callbacks = copy.copy(self._post_configure_callbacks['single'])
        # clear out the singles
        self._post_configure_callbacks['single'] = []

        for callback in multiple_callbacks:
            callback(resulting_configuration, configure_args)

        # now do the single run callbacks
        for callback in single_callbacks:
            callback(resulting_configuration, configure_args)


Instruction:
How would you code a function in Python 3 to
validate the data and create a model instance from it s data.

Response:
def make_instance(cls, data):
        """Validate the data and create a model instance from the data.

        Args:
            data (dict): The unserialized data to insert into the new model
                instance through it's constructor.

        Returns:
            peewee.Model|sqlalchemy.Model: The model instance with it's data
                inserted into it.

        Raises:
            AttributeError: This is raised if ``Meta.model`` isn't set on the
                schema's definition.
        """
        schema = cls()

        if not hasattr(schema.Meta, 'model'):
            raise AttributeError("In order to make an instance, a model for "
                                 "the schema must be defined in the Meta "
                                 "class.")

        serialized_data = schema.load(data).data

        return cls.Meta.model(**serialized_data)


Instruction:
Explain what the following Python 3 code does
def invalid_fields(self, data, original_data):
        errors = []

        for field in original_data:
            # Skip nested fields because they will loop infinitely
            if isinstance(field, (set, list, tuple, dict)):
                continue

            if field not in self.fields.keys():
                errors.append(field)

        if errors:
            raise ValidationError("Invalid field", field_names=errors)

Response: Validator that checks if any keys provided aren t in the schema.


Instruction:
Implement a Python 3 function for
returning the value in the data base as an arrow object.

Response:
def python_value(self, value):
        """Return the value in the data base as an arrow object.

        Returns:
            arrow.Arrow: An instance of arrow with the field filled in.
        """
        value = super(ArrowDateTimeField, self).python_value(value)

        if (isinstance(value, (datetime.datetime, datetime.date,
                               string_types))):
            return arrow.get(value)

        return value


Instruction:
Create a Python 3 function to
convert the Arrow instance to a datetime for saving in the db.

Response:
def db_value(self, value):
        """Convert the Arrow instance to a datetime for saving in the db."""
        if isinstance(value, string_types):
            value = arrow.get(value)

        if isinstance(value, arrow.Arrow):
            value = value.datetime

        return super(ArrowDateTimeField, self).db_value(value)


Instruction:
How would you explain what the following Python 3 function does
def init_app(self, app, context=DEFAULT_DICT):
        if context is not _CONTEXT_MISSING:
            self.update_context(context, app=app)

        # do not readd callbacks if already present; and if there's no context
        # present, there's no real need to add callbacks
        if (app not in _CONTEXT_CALLBACK_MAP
                and context is not _CONTEXT_MISSING):
            key = self._get_context_name(app=app)
            self._context_callbacks(app, key, original_context=context)

Response: Lazy initialization of the Component class.


Instruction:
Explain what the following Python 3 code does
def _context_callbacks(app, key, original_context=_CONTEXT_MISSING):
        def _get_context(dummy_app):
            """Set the context proxy so that it points to a specific context.
            """
            _CONTEXT_LOCALS.context = _CONTEXT_LOCALS(key)  # pylint: disable=assigning-non-slot

        def _clear_context(dummy_app):
            """Remove the context proxy that points to a specific context and
            restore the original context, if there was one.
            """
            try:
                del _CONTEXT_LOCALS.context
            except AttributeError:
                pass

            if original_context is not _CONTEXT_MISSING:
                setattr(_CONTEXT_LOCALS, key, original_context)

        # store for later so Blinker doesn't remove these listeners and so we
        # don't add them twice
        _CONTEXT_CALLBACK_MAP[app] = (_get_context, _clear_context)

        # and listen for any app context changes
        appcontext_pushed.connect(_get_context, app)
        appcontext_popped.connect(_clear_context, app)

        return (_get_context, _clear_context)

Response: Register the callbacks we need to properly pop and push the app - local context for a component.


Instruction:
Implement a Python 3 function for
replacing the component s context with a new one.

Response:
def update_context(self, context, app=None):
        """Replace the component's context with a new one.

        Args:
            context (dict): The new context to set this component's context to.

        Keyword Args:
            app (flask.Flask, optional): The app to update this context for. If
                not provided, the result of ``Component.app`` will be used.
        """
        if (app is None and self._context is _CONTEXT_MISSING
                and not in_app_context()):
            raise RuntimeError("Attempted to update component context without"
                               " a bound app context or eager app set! Please"
                               " pass the related app you want to update the"
                               " context for!")

        if self._context is not _CONTEXT_MISSING:
            self._context = ImmutableDict(context)
        else:
            key = self._get_context_name(app=app)
            setattr(_CONTEXT_LOCALS, key, ImmutableDict(context))


Instruction:
Write a Python 3 script to
clear the component s context.

Response:
def clear_context(self, app=None):
        """Clear the component's context.

        Keyword Args:
            app (flask.Flask, optional): The app to clear this component's
                context for. If omitted, the value from ``Component.app`` is
                used.
        """
        if (app is None and self._context is _CONTEXT_MISSING
                and not in_app_context()):
            raise RuntimeError("Attempted to clear component context without"
                               " a bound app context or eager app set! Please"
                               " pass the related app you want to update the"
                               " context for!")

        if self._context is not _CONTEXT_MISSING:
            self._context = DEFAULT_DICT
        else:
            key = self._get_context_name(app=app)
            setattr(_CONTEXT_LOCALS, key, DEFAULT_DICT)


Instruction:
Given the following Python 3 function, write the documentation
def _get_context_name(self, app=None):
        elements = [
            self.__class__.__name__,
            'context',
            text_type(id(self)),
        ]

        if app:
            elements.append(text_type(id(app)))
        else:
            try:
                elements.append(text_type(id(self.app)))
            except RuntimeError:
                pass

        return '_'.join(elements)

Response: Generate the name of the context variable for this component & app.


Instruction:
How would you implement a function in Python 3 that
creates a standard Fleaker web application.

Response:
def create_app(cls, import_name, **settings):
        """Create a standard Fleaker web application.

        This is the main entrypoint for creating your Fleaker application.
        Instead of defining your own app factory function, it's preferred that
        you use :meth:`create_app`, which is responsible for automatically
        configuring extensions (such as your ORM), parsing setup code for
        mixins, and calling relevant hooks (such as to setup logging).

        Usage is easy:

        .. code:: python

            from fleaker import App

            def my_create_app():
                app = App.create_app(__name__)
                return app

        And the rest works like a normal Flask app with application factories
        setup!

        .. versionadded:: 0.1.0
           This has always been the preferred way to create Fleaker
           Applications.
        """
        settings = cls.pre_create_app(**settings)

        # now whitelist the settings
        flask_kwargs = cls._whitelist_standard_flask_kwargs(settings)

        app = cls(import_name, **flask_kwargs)
        return cls.post_create_app(app, **settings)


Instruction:
Write a Python 3 function that can
format the log record.

Response:
def format(self, record):
        """Format the log record."""
        levelname = getattr(record, 'levelname', None)
        record.levelcolor = ''
        record.endlevelcolor = ''

        if levelname:
            level_color = getattr(self.TermColors, levelname, '')
            record.levelcolor = level_color
            record.endlevelcolor = self.TermColors.ENDC if level_color else ''

        return super(FleakerLogFormatter, self).format(record)


Instruction:
Write a Python 3 function that can
register the errorhandler for the AppException to the passed in App.

Response:
def post_create_app(cls, app, **settings):
        """Register the errorhandler for the AppException to the passed in
        App.

        Args:
            app (fleaker.base.BaseApplication): A Flask application that
                extends the Fleaker Base Application, such that the hooks are
                implemented.

        Kwargs:
            register_errorhandler (bool): A boolean indicating if we want to
                automatically register an errorhandler for the
                :class:`AppException` exception class after we create this App.
                Pass ``False`` to prevent registration. Default is ``True``.

        Returns:
            fleaker.base.BaseApplication: Returns the app it was given.
        """
        register_errorhandler = settings.pop('register_errorhandler', True)

        if register_errorhandler:
            AppException.register_errorhandler(app)

        return app


Instruction:
How would you explain what the following Python 3 function does
def create_app():
    app = App.create_app(__name__)
    app.configure('.configs.settings')

    # yes, I should use blueprints; but I don't really care for such a small
    # toy app
    @app.route('/config')
    def get_config():
        """Get the current configuration of the app."""
        return jsonify(app.config)

    @app.route('/put_config', methods=['PUT'])
    def put_config():
        """Add to the current configuration of the app.

        Takes any JSON body and adds all keys to the configs with the provided
        values.
        """
        data = request.json()

        for key, val in data.items():
            app.config[key] = val

        return jsonify({'message': 'Config updated!'})

    return app

Response: Create a new app for two


Instruction:
Can you generate a brief explanation for the following Python 3 code
def update_signature(self):
        if not self._meta.signature_fields:
            raise AttributeError(
                "No fields defined in {}.Meta.signature_fields. Please define "
                "at least one.".format(type(self).__name__)
            )

        # If the field is archived, unset the signature so records in the
        # future can have this value.
        if getattr(self, 'archived', False):
            self.signature = None
            return

        # Otherwise, combine the values of the fields together and SHA1 them
        computed = [getattr(self, value) or ' '
                    for value in self._meta.signature_fields]
        computed = ''.join([text_type(value) for value in computed])

        # If computed is a falsey value, that means all the fields were
        # None or blank and that will lead to some pain.
        if computed:
            self.signature = sha1(computed.encode('utf-8')).hexdigest()

Response: Update the signature field of the current object based on the contents of the signature_fields attribute of the object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def connect(service_account, credentials_file_path, api_version='v2'):

    # Create an httplib2.Http object to handle our HTTP requests an
    # authorize it with the Credentials. Note that the first parameter,
    # service_account_name, is the Email address created for the Service
    # account. It must be the email address associated with the key that
    # was created.
    scope = 'https://www.googleapis.com/auth/androidpublisher'
    credentials = ServiceAccountCredentials.from_p12_keyfile(service_account, credentials_file_path, scopes=scope)
    http = httplib2.Http()
    http = credentials.authorize(http)

    service = build('androidpublisher', api_version, http=http, cache_discovery=False)

    return service

Response: Connect to the Google Play interface


Instruction:
Can you implement a function in Python 3 that
formats and validate a phone number.

Response:
def _format_phone_number(self, value, attr):
        """Format and validate a phone number."""
        strict_validation = self.get_field_value(
            'strict_phone_validation',
            default=False
        )
        strict_region = self.get_field_value(
            'strict_phone_region',
            default=strict_validation
        )
        region = self.get_field_value('region', 'US')
        phone_number_format = self.get_field_value(
            'phone_number_format',
            default=phonenumbers.PhoneNumberFormat.INTERNATIONAL
        )

        # Remove excess special chars, except for the plus sign
        stripped_value = re.sub(r'[^\w+]', '', value)

        try:
            if not stripped_value.startswith('+') and not strict_region:
                phone = phonenumbers.parse(stripped_value, region)
            else:
                phone = phonenumbers.parse(stripped_value)

            if (not phonenumbers.is_possible_number(phone) or
                    not phonenumbers.is_valid_number(phone) and
                    strict_validation):
                raise ValidationError(
                    "The value for {} ({}) is not a valid phone "
                    "number.".format(attr, value)
                )

            return phonenumbers.format_number(phone, phone_number_format)

        except phonenumbers.phonenumberutil.NumberParseException as exc:
            if strict_validation or strict_region:
                raise ValidationError(exc)


Instruction:
Create a Python 3 function for
formatting and validate the phone number using libphonenumber.

Response:
def _deserialize(self, value, attr, data):
        """Format and validate the phone number using libphonenumber."""
        if value:
            value = self._format_phone_number(value, attr)

        return super(PhoneNumberField, self)._deserialize(value, attr, data)


Instruction:
Can you create a Python 3 function that
formats and validate the phone number user libphonenumber.

Response:
def _serialize(self, value, attr, obj):
        """Format and validate the phone number user libphonenumber."""
        value = super(PhoneNumberField, self)._serialize(value, attr, obj)

        if value:
            value = self._format_phone_number(value, attr)

        return value


Instruction:
Here you have a function in Python 3, explain what it does
def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            obj = format(obj, 'f')
            str_digit = text_type(obj)

            return (str_digit.rstrip('0').rstrip('.')
                    if '.' in str_digit
                    else str_digit)

        elif isinstance(obj, phonenumbers.PhoneNumber):
            return phonenumbers.format_number(
                obj,
                phonenumbers.PhoneNumberFormat.E164
            )

        elif isinstance(obj, pendulum.Pendulum):
            return text_type(obj)

        elif isinstance(obj, arrow.Arrow):
            return text_type(obj)

        elif isinstance(obj, (datetime.datetime, datetime.date)):
            return obj.isoformat()

        try:
            return list(iter(obj))
        except TypeError:
            pass

        return super(FleakerJSONEncoder, self).default(obj)

Response: Encode individual objects into their JSON representation.


Instruction:
Can you tell what is the following Python 3 function doing
def _serialize(self, value, attr, obj):
        if isinstance(value, arrow.arrow.Arrow):
            value = value.datetime

        return super(ArrowField, self)._serialize(value, attr, obj)

Response: Convert the Arrow object into a string.


Instruction:
Implement a Python 3 function for
returning the value in the database as an instance of Pendulum.

Response:
def python_value(self, value):
        """Return the value in the database as an Pendulum object.

        Returns:
            pendulum.Pendulum:
                An instance of Pendulum with the field filled in.
        """
        value = super(PendulumDateTimeField, self).python_value(value)

        if isinstance(value, datetime.datetime):
            value = pendulum.instance(value)
        elif isinstance(value, datetime.date):
            value = pendulum.instance(
                datetime.datetime.combine(
                    value, datetime.datetime.min.time()
                )
            )
        elif isinstance(value, string_types):
            value = pendulum.parse(value)

        return value


Instruction:
Write a Python 3 script for
converting the Pendulum instance to a datetime for saving in the db.

Response:
def db_value(self, value):
        """Convert the Pendulum instance to a datetime for saving in the db."""
        if isinstance(value, pendulum.Pendulum):
            value = datetime.datetime(
                value.year, value.month, value.day, value.hour, value.minute,
                value.second, value.microsecond, value.tzinfo
            )

        return super(PendulumDateTimeField, self).db_value(value)


Instruction:
Write a Python 3 script to
check if package_name has a release on staged rollout for too long

Response:
def check_rollout(edits_service, package_name, days):
    """Check if package_name has a release on staged rollout for too long"""
    edit = edits_service.insert(body={}, packageName=package_name).execute()
    response = edits_service.tracks().get(editId=edit['id'], track='production', packageName=package_name).execute()
    releases = response['releases']
    for release in releases:
        if release['status'] == 'inProgress':
            url = 'https://archive.mozilla.org/pub/mobile/releases/{}/SHA512SUMS'.format(release['name'])
            resp = requests.head(url)
            if resp.status_code != 200:
                if resp.status_code != 404:  # 404 is expected for release candidates
                    logger.warning("Could not check %s: %s", url, resp.status_code)
                continue
            age = time.time() - calendar.timegm(eu.parsedate(resp.headers['Last-Modified']))
            if age >= days * DAY:
                yield release, age


Instruction:
Can you tell what is the following Python 3 function doing
def generate_json_schema(cls, schema, context=DEFAULT_DICT):
        schema = cls._get_schema(schema)

        # Generate the JSON Schema
        return cls(context=context).dump(schema).data

Response: Generate a JSON Schema from a Marshmallow schema.


Instruction:
Explain what the following Python 3 code does
def write_schema_to_file(cls, schema, file_pointer=stdout,
                             folder=MISSING, context=DEFAULT_DICT):
        """Given a Marshmallow schema, create a JSON Schema for it.

        Args:
            schema (marshmallow.Schema|str): The Marshmallow schema, or the
                Python path to one, to create the JSON schema for.

        Keyword Args:
            file_pointer (file, optional): The pointer to the file to write
                this schema to. If not provided, the schema will be dumped to
                ``sys.stdout``.
            folder (str, optional): The folder in which to save the JSON
                schema. The name of the schema file can be optionally
                controlled my the schema's ``Meta.json_schema_filename``. If
                that attribute is not set, the class's name will be used for
                the filename. If writing the schema to a specific file is
                desired, please pass in a ``file_pointer``.
            context (dict, optional): The Marshmallow context to be pushed to
                the schema generates the JSONSchema.

        Returns:
            dict: The JSON schema in dictionary form.
        """
        schema = cls._get_schema(schema)
        json_schema = cls.generate_json_schema(schema, context=context)

        if folder:
            schema_filename = getattr(
                schema.Meta,
                'json_schema_filename',
                '.'.join([schema.__class__.__name__, 'json'])
            )
            json_path = os.path.join(folder, schema_filename)
            file_pointer = open(json_path, 'w')

        json.dump(json_schema, file_pointer, indent=2)

        return json_schema

Response: Given a Marshmallow schema and a file pointer write the JSON schema to that file.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def post_save_event_listener(sender, instance, created):
    if not instance._meta.event_ready:
        return

    if created:
        instance.create_creation_event()
    else:
        instance.create_update_event()

    # Reset the original key
    instance._original = None

Response: Event listener to create creation and update events.


Instruction:
Create a Python 3 function to
verify that the Event s code is a valid one.

Response:
def validate_event_type(sender, event, created):
    """Verify that the Event's code is a valid one."""
    if event.code not in sender.event_codes():
        raise ValueError("The Event.code '{}' is not a valid Event "
                         "code.".format(event.code))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_original(self):
        pk_value = self._get_pk_value()

        if isinstance(pk_value, int) and not self._original:
            self._original = (
                self.select().where(self.__class__.id == pk_value).get()
            )

        return self._original

Response: Get the original instance of this instance before it s updated.


Instruction:
Make a summary of the following Python 3 code
def create_creation_event(self):
        event = self.create_audit_event(code='AUDIT_CREATE')

        if self._meta.create_message:
            event.body = self._meta.create_message['message']
            event.code = self._meta.create_message['code']
            event.meta = self.parse_meta(self._meta.create_message['meta'])

        self.create_event_callback(event)

        event.save()

        return event

Response: Parse the create message DSL to insert the data into the Event.


Instruction:
Create a Python 3 function for
parsing the update messages DSL to insert the data into the Event.

Response:
def create_update_event(self):
        """Parse the update messages DSL to insert the data into the Event.

        Returns:
            list[fleaker.peewee.EventStorageMixin]:
                All the events that were created for the update.
        """
        events = []

        for fields, rules in iteritems(self._meta.update_messages):
            if not isinstance(fields, (list, tuple, set)):
                fields = (fields,)

            changed = any([
                getattr(self, field) != getattr(self.get_original(), field)
                for field in fields
            ])

            if changed:
                event = self.create_audit_event(code=rules['code'])
                event.body = rules['message']
                event.meta = self.parse_meta(rules['meta'])
                events.append(event)

        self.update_event_callback(events)

        with db.database.atomic():
            for event in events:
                event.save()

        return events


Instruction:
Can you tell what is the following Python 3 function doing
def create_deletion_event(self):
        event = self.create_audit_event(code='AUDIT_DELETE')

        if self._meta.delete_message:
            event.code = self._meta.delete_message['code']
            event.body = self._meta.delete_message['message']
            event.meta = self.parse_meta(self._meta.delete_message['meta'])

        self.delete_event_callback(event)

        event.save()

        return event

Response: Parse the delete message DSL to insert data into the Event.


Instruction:
How would you explain what the following Python 3 function does
def parse_meta(self, meta):
        res = {}

        for key, val in meta.items():
            if not val:
                continue
            elif isinstance(val, dict):
                res[key] = self.parse_meta(val)
            elif val.startswith('current_user.'):
                res[key] = self.get_path_attribute(current_user, val)
            elif val.startswith('original.'):
                res[key] = self.get_path_attribute(self.get_original(), val)
            else:
                res[key] = self.get_path_attribute(self, val)

        return res

Response: Parses the meta field in the message and returns a new dict with the keys and values which should be attribute paths relative to the current user and the current value at the end of that object.


Instruction:
Here you have a function in Python 3, explain what it does
def get_path_attribute(obj, path):
        # Strip out ignored keys passed in
        path = path.replace('original.', '').replace('current_user.', '')

        attr_parts = path.split('.')
        res = obj

        try:
            for part in attr_parts:
                try:
                    res = getattr(res, part)
                except AttributeError:
                    res = getattr(res.get(), part)

        except (peewee.DoesNotExist, AttributeError):
            return None

        return res

Response: Given an object and a path return the value of the attribute that corresponds to that object.


Instruction:
How would you implement a function in Python 3 that
copies the possible foreign key values from the object into the Event instance.

Response:
def copy_foreign_keys(self, event):
        """Copies possible foreign key values from the object into the Event,
        skipping common keys like modified and created.

        Args:
            event (Event): The Event instance to copy the FKs into
            obj (fleaker.db.Model): The object to pull the values from
        """
        event_keys = set(event._meta.fields.keys())
        obj_keys = self._meta.fields.keys()
        matching_keys = event_keys.intersection(obj_keys)

        for key in matching_keys:
            # Skip created_by because that will always be the current_user
            # for the Event.
            if key == 'created_by':
                continue

            # Skip anything that isn't a FK
            if not isinstance(self._meta.fields[key], peewee.ForeignKeyField):
                continue

            setattr(event, key, getattr(self, key))

        # Attempt to set the obj's ID in the correct FK field on Event, if it
        # exists. If this conflicts with desired behavior, handle this in the
        # respective callback. This does rely on the FK matching the lower case
        # version of the class name and that the event isn't trying to delete
        # the current record, becuase that ends badly.
        possible_key = self.__class__.__name__.lower()

        if possible_key in event_keys and event.code != 'AUDIT_DELETE':
            setattr(event, possible_key, self)


Instruction:
Can you generate the documentation for the following Python 3 function
def create_audit_event(self, code='AUDIT'):
        event = self._meta.event_model(
            code=code,
            model=self.__class__.__name__,
        )

        # Use the logged in User, if possible
        if current_user:
            event.created_by = current_user.get_id()

        self.copy_foreign_keys(event)
        self.populate_audit_fields(event)

        return event

Response: Creates a generic auditing Event with relevant info inserted into it.


Instruction:
Write a Python 3 function for
populating the audit JSON fields with raw data from the model.

Response:
def populate_audit_fields(self, event):
        """Populates the the audit JSON fields with raw data from the model, so
        all changes can be tracked and diffed.

        Args:
            event (Event): The Event instance to attach the data to
            instance (fleaker.db.Model): The newly created/updated model
        """
        event.updated = self._data
        event.original = self.get_original()._data


Instruction:
How would you explain what the following Python 3 function does
def formatted_message(self):
        return render_template_string(
            self.body,
            event=self,
            meta=self.meta,
            original=self.original,
            updated=self.updated,
            version=self.version,
        )

Response: Method that returns the formatted message for the event.


Instruction:
Make a summary of the following Python 3 code
def _get_cached_time(self):
        if not self._cached_time:
            self._cached_time = self._meta.datetime.utcnow()

        return self._cached_time

Response:
Method that will allow for consistent modified and archived
        timestamps.


Instruction:
Create a Python 3 function for
getting all the translated locales supported by Google play

Response:
def _get_list_of_completed_locales(product, channel):
    """ Get all the translated locales supported by Google play
    So, locale unsupported by Google play won't be downloaded
    Idem for not translated locale
    """
    return utils.load_json_url(_ALL_LOCALES_URL.format(product=product, channel=channel))


Instruction:
Can you generate the documentation for the following Python 3 function
def get_field_value(self, key, default=MISSING):
        meta_value = self.metadata.get(key)
        context_value = self.context.get(key)

        if context_value is not None:
            return context_value
        elif meta_value is not None:
            return meta_value

        return default

Response: Method to fetch a value from either the fields metadata or the fields context.


Instruction:
Can you write a function in Python 3 where it
returns a single instance of the model queried by ID.

Response:
def get_by_id(cls, record_id, execute=True):
        """Return a single instance of the model queried by ID.

        Args:
            record_id (int): Integer representation of the ID to query on.

        Keyword Args:
            execute (bool, optional):
                Should this method execute the query or return a query object
                for further manipulation?

        Returns:
            cls | :py:class:`peewee.SelectQuery`:
                If ``execute`` is ``True``, the query is executed, otherwise
                a query is returned.

        Raises:
            :py:class:`peewee.DoesNotExist`:
                Raised if a record with that ID doesn't exist.
        """
        query = cls.base_query().where(cls.id == record_id)

        if execute:
            return query.get()

        return query


Instruction:
Can you tell what is the following Python 3 function doing
def update_instance(self, data):
        for key, val in iteritems(data):
            if not hasattr(self, key):
                raise AttributeError(
                    "No field named {key} for model {model}".format(
                        key=key,
                        model=self.__class__.__name__
                    )
                )

            setattr(self, key, val)

        self.save()

        return self

Response: Update a single record by id with the provided data.


Instruction:
How would you explain what the following Python 3 function does
def get_code(self):
        return "" if not self.is_enabled else ("""

        """.format(SITE_KEY=self.site_key, THEME=self.theme, TYPE=self.type, SIZE=self.size, TABINDEX=self.tabindex))

Response: Returns the new ReCaptcha code


Instruction:
Make a summary of the following Python 3 code
def ensure(self, name, preparefunc, restart=False):
        from subprocess import Popen, STDOUT
        info = self.getinfo(name)
        if not restart and not info.isrunning():
            restart = True

        if restart:
            if info.pid is not None:
                info.terminate()
            controldir = info.controldir.ensure(dir=1)
            #controldir.remove()
            preparefunc = CompatStarter.wrap(preparefunc)
            starter = preparefunc(controldir, self)
            args = [str(x) for x in starter.args]
            self.log.debug("%s$ %s", controldir, " ".join(args))
            stdout = open(str(info.logpath), "wb", 0)
            kwargs = {'env': starter.env}
            if sys.platform == "win32":
                kwargs["startupinfo"] = sinfo = std.subprocess.STARTUPINFO()
                if sys.version_info >= (2,7):
                    sinfo.dwFlags |= std.subprocess.STARTF_USESHOWWINDOW
                    sinfo.wShowWindow |= std.subprocess.SW_HIDE
            else:
                kwargs["close_fds"] = True
                kwargs["preexec_fn"] = os.setpgrp  # no CONTROL-C
            popen = Popen(args, cwd=str(controldir),
                          stdout=stdout, stderr=STDOUT,
                          **kwargs)
            info.pid = pid = popen.pid
            info.pidpath.write(str(pid))
            self.log.debug("process %r started pid=%s", name, pid)
            stdout.close()
        f = info.logpath.open()
        if not restart:
            f.seek(0, 2)
        else:
            if not starter.wait(f):
                raise RuntimeError("Could not start process %s" % name)
            self.log.debug("%s process startup detected", name)
        logfiles = self.config.__dict__.setdefault("_extlogfiles", {})
        logfiles[name] = f
        self.getinfo(name)
        return info.pid, info.logpath

Response: Creates a new process and returns the PID logfile if it is running.


Instruction:
Make a summary of the following Python 3 code
def wait(self, log_file):
        "Wait until the process is ready."
        lines = map(self.log_line, self.filter_lines(self.get_lines(log_file)))
        return any(
            std.re.search(self.pattern, line)
            for line in lines
        )

Response: Wait until the process is ready.


Instruction:
Can you generate the documentation for the following Python 3 function
def prep(self, wait, args, env=None):
        self.pattern = wait
        self.env = env
        self.args = args

        # wait is a function, supersedes the default behavior
        if callable(wait):
            self.wait = lambda lines: wait()

Response: Given the return value of a preparefunc prepare this CompatStarter.


Instruction:
How would you explain what the following Python 3 function does
def wrap(self, starter_cls):
        if isinstance(starter_cls, type) and issubclass(starter_cls, ProcessStarter):
            return starter_cls
        depr_msg = 'Pass a ProcessStarter for preparefunc'
        warnings.warn(depr_msg, DeprecationWarning, stacklevel=3)
        return functools.partial(CompatStarter, starter_cls)

Response: Wrap a process_class in a CompatStarter.


Instruction:
Make a summary of the following Python 3 code
def set_start_date(self, start_day: int, data_limit: str, month_threshold: int):
        return self._connection.post('monitoring/start_date', OrderedDict((
            ('StartDay', start_day),
            ('DataLimit', data_limit),
            ('MonthThreshold', month_threshold),
            ('SetMonthData', 1)
        )))

Response:
Sets the start date of the network usage alarm for LTE
       .


Instruction:
Write a Python 3 function that can
make a GET request.

Response:
def _get(self, *args, **kwargs):
        """
        Make a GET request.
        """
        return self._request(requests.get, *args, **kwargs)


Instruction:
Can you generate the documentation for the following Python 3 function
def _post(self, *args, **kwargs):
        data = self._default_data()
        data.update(kwargs.get('data') or {})
        kwargs['data'] = data
        return self._request(requests.post, *args, **kwargs)

Response: Make a POST request.


Instruction:
Create a Python 3 function for
constructing the url to use for the orderbook.

Response:
def _construct_url(self, url, base, quote):
        """
        Adds the orderbook to the url if base and quote are specified.
        """
        if not base and not quote:
            return url
        else:
            url = url + base.lower() + quote.lower() + "/"
            return url


Instruction:
Implement a function in Python 3 to
make a generic request to the Bitstamp API.

Response:
def _request(self, func, url, version=1, *args, **kwargs):
        """
        Make a generic request, adding in any proxy defined by the instance.

        Raises a ``requests.HTTPError`` if the response status isn't 200, and
        raises a :class:`BitstampError` if the response contains a json encoded
        error message.
        """
        return_json = kwargs.pop('return_json', False)
        url = self.api_url[version] + url
        response = func(url, *args, **kwargs)

        if 'proxies' not in kwargs:
            kwargs['proxies'] = self.proxydict

        # Check for error, raising an exception if appropriate.
        response.raise_for_status()

        try:
            json_response = response.json()
        except ValueError:
            json_response = None
        if isinstance(json_response, dict):
            error = json_response.get('error')
            if error:
                raise BitstampError(error)
            elif json_response.get('status') == "error":
                raise BitstampError(json_response.get('reason'))

        if return_json:
            if json_response is None:
                raise BitstampError(
                    "Could not decode json for: " + response.text)
            return json_response

        return response


Instruction:
Write a Python 3 function for
returning a dictionary of the available ticker items.

Response:
def ticker(self, base="btc", quote="usd"):
        """
        Returns dictionary.
        """
        url = self._construct_url("ticker/", base, quote)
        return self._get(url, return_json=True, version=2)


Instruction:
How would you explain what the following Python 3 function does
def order_book(self, group=True, base="btc", quote="usd"):
        params = {'group': group}
        url = self._construct_url("order_book/", base, quote)
        return self._get(url, params=params, return_json=True, version=2)

Response: Returns a dictionary with bids and asks.


Instruction:
Can you create a Python 3 function that
returns the last timedelta seconds of the last transaction in the specified base and quote.

Response:
def transactions(self, time=TransRange.HOUR, base="btc", quote="usd"):
        """
        Returns transactions for the last 'timedelta' seconds.
        Parameter time is specified by one of two values of TransRange class.
        """
        params = {'time': time}
        url = self._construct_url("transactions/", base, quote)
        return self._get(url, params=params, return_json=True, version=2)


Instruction:
Write a Python 3 script to
get a unique nonce for the bitstamp API.

Response:
def get_nonce(self):
        """
        Get a unique nonce for the bitstamp API.

        This integer must always be increasing, so use the current unix time.
        Every time this variable is requested, it automatically increments to
        allow for more than one API request per second.

        This isn't a thread-safe function however, so you should only rely on a
        single thread if you have a high level of concurrent API requests in
        your application.
        """
        nonce = getattr(self, '_nonce', 0)
        if nonce:
            nonce += 1
        # If the unix time is greater though, use that instead (helps low
        # concurrency multi-threaded apps always call with the largest nonce).
        self._nonce = max(int(time.time()), nonce)
        return self._nonce


Instruction:
Create a Python 3 function to
generate a one - time signature and other data required to send a secure POST request to Bitstamp API.

Response:
def _default_data(self, *args, **kwargs):
        """
        Generate a one-time signature and other data required to send a secure
        POST request to the Bitstamp API.
        """
        data = super(Trading, self)._default_data(*args, **kwargs)
        data['key'] = self.key
        nonce = self.get_nonce()
        msg = str(nonce) + self.username + self.key

        signature = hmac.new(
            self.secret.encode('utf-8'), msg=msg.encode('utf-8'),
            digestmod=hashlib.sha256).hexdigest().upper()
        data['signature'] = signature
        data['nonce'] = nonce
        return data


Instruction:
Write a Python 3 function that can
get the balance of the current account.

Response:
def account_balance(self, base="btc", quote="usd"):
        """
        Returns dictionary::

            {u'btc_reserved': u'0',
             u'fee': u'0.5000',
             u'btc_available': u'2.30856098',
             u'usd_reserved': u'0',
             u'btc_balance': u'2.30856098',
             u'usd_balance': u'114.64',
             u'usd_available': u'114.64',
             ---If base and quote were specified:
             u'fee': u'',
             ---If base and quote were not specified:
             u'btcusd_fee': u'0.25',
             u'btceur_fee': u'0.25',
             u'eurusd_fee': u'0.20',
             }
            There could be reasons to set base and quote to None (or False),
            because the result then will contain the fees for all currency pairs
            For backwards compatibility this can not be the default however.
        """
        url = self._construct_url("balance/", base, quote)
        return self._post(url, return_json=True, version=2)


Instruction:
Can you generate the documentation for the following Python 3 function
def user_transactions(self, offset=0, limit=100, descending=True,
                          base=None, quote=None):
        """
        Returns descending list of transactions. Every transaction (dictionary)
        contains::

            {u'usd': u'-39.25',
             u'datetime': u'2013-03-26 18:49:13',
             u'fee': u'0.20',
             u'btc': u'0.50000000',
             u'type': 2,
             u'id': 213642}

        Instead of the keys btc and usd, it can contain other currency codes
        """
        data = {
            'offset': offset,
            'limit': limit,
            'sort': 'desc' if descending else 'asc',
        }
        url = self._construct_url("user_transactions/", base, quote)
        return self._post(url, data=data, return_json=True, version=2)

Response: Returns descending list of transactions. Every transaction contains a single entry for each user.


Instruction:
Create a Python 3 function for
returning the status of the order with the given ID

Response:
def order_status(self, order_id):
        """
        Returns dictionary.
        - status: 'Finished'
          or      'In Queue'
          or      'Open'
        - transactions: list of transactions
          Each transaction is a dictionary with the following keys:
              btc, usd, price, type, fee, datetime, tid
          or  btc, eur, ....
          or  eur, usd, ....
        """
        data = {'id': order_id}
        return self._post("order_status/", data=data, return_json=True,
                          version=1)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def cancel_order(self, order_id, version=1):
        data = {'id': order_id}
        return self._post("cancel_order/", data=data, return_json=True,
                          version=version)

Response:
Cancel the order specified by order_id.

        Version 1 (default for backwards compatibility reasons):
        Returns True if order was successfully canceled, otherwise
        raise a BitstampError.

        Version 2:
        Returns dictionary of the canceled order, containing the keys:
        id, type, price, amount


Instruction:
Explain what the following Python 3 code does
def buy_limit_order(self, amount, price, base="btc", quote="usd", limit_price=None):
        data = {'amount': amount, 'price': price}
        if limit_price is not None:
            data['limit_price'] = limit_price
        url = self._construct_url("buy/", base, quote)
        return self._post(url, data=data, return_json=True, version=2)

Response: Buy amount of bitcoins for specified price.


Instruction:
Create a Python 3 function for
buying a market order.

Response:
def buy_market_order(self, amount, base="btc", quote="usd"):
        """
        Order to buy amount of bitcoins for market price.
        """
        data = {'amount': amount}
        url = self._construct_url("buy/market/", base, quote)
        return self._post(url, data=data, return_json=True, version=2)


Instruction:
How would you implement a function in Python 3 that
checks USD and BTC amount included in given bitstamp code. Returns JSON dictionary containing USD and BTC amount included in given bitstamp code.

Response:
def check_bitstamp_code(self, code):
        """
        Returns JSON dictionary containing USD and BTC amount included in given
        bitstamp code.
        """
        data = {'code': code}
        return self._post("check_code/", data=data, return_json=True,
                          version=1)


Instruction:
How would you explain what the following Python 3 function does
def redeem_bitstamp_code(self, code):
        data = {'code': code}
        return self._post("redeem_code/", data=data, return_json=True,
                          version=1)

Response: Redeem bitstamp code to user s user s set of bitstamps.


Instruction:
Can you tell what is the following Python 3 function doing
def withdrawal_requests(self, timedelta = 86400):
        data = {'timedelta': timedelta}
        return self._post("withdrawal_requests/", return_json=True, version=1, data=data)

Response: Returns a list of withdrawal requests.


Instruction:
How would you explain what the following Python 3 function does
def litecoin_withdrawal(self, amount, address):
        data = {'amount': amount, 'address': address}
        return self._post("ltc_withdrawal/", data=data, return_json=True,
                          version=2)

Response: Send litecoins to another litecoin wallet specified by address.


Instruction:
How would you explain what the following Python 3 function does
def ripple_withdrawal(self, amount, address, currency):
        data = {'amount': amount, 'address': address, 'currency': currency}
        response = self._post("ripple_withdrawal/", data=data,
                              return_json=True)
        return self._expect_true(response)

Response: Returns true if successful.


Instruction:
Make a summary of the following Python 3 code
def xrp_withdrawal(self, amount, address, destination_tag=None):
        data = {'amount': amount, 'address': address}
        if destination_tag:
            data['destination_tag'] = destination_tag

        return self._post("xrp_withdrawal/", data=data, return_json=True,
                          version=2)["id"]

Response: Sends xrps to another xrp wallet specified by address. Returns withdrawal id.


Instruction:
Can you generate the documentation for the following Python 3 function
def transfer_to_main(self, amount, currency, subaccount=None):
        data = {'amount': amount,
                'currency': currency,}
        if subaccount is not None:
            data['subAccount'] = subaccount
        return self._post("transfer-to-main/", data=data, return_json=True,
                          version=2)

Response: Transfer amount to main account


Instruction:
Can you generate the documentation for the following Python 3 function
def resample(self, target_sr):
        y_hat = librosa.core.resample(self.y, self.sr, target_sr)
        return Sound(y_hat, target_sr)

Response: Returns a new sound with a samplerate of target_sr.


Instruction:
How would you code a function in Python 3 to
provide an IPythonwidgets player that can be used in a notebook.

Response:
def as_ipywidget(self):
        """ Provides an IPywidgets player that can be used in a notebook. """
        from IPython.display import Audio

        return Audio(data=self.y, rate=self.sr)


Instruction:
Make a summary of the following Python 3 code
def from_file(cls, filename, sr=22050):
        y, sr = librosa.load(filename, sr=sr)
        return cls(y, sr)

Response: Loads an audio file into a new object.


Instruction:
Explain what the following Python 3 code does
def chunks(self):
        if not hasattr(self, '_it'):
            class ChunkIterator(object):
                def __iter__(iter):
                    return iter

                def __next__(iter):
                    try:
                        chunk = self._next_chunk()
                    except StopIteration:
                        if self.loop:
                            self._init_stretching()
                            return iter.__next__()

                        raise

                    return chunk
                next = __next__

            self._it = ChunkIterator()

        return self._it

Response: Returns an iterator over the sound.


Instruction:
Here you have a function in Python 3, explain what it does
def pitch_shifter(self, chunk, shift):
        freq = numpy.fft.rfft(chunk)

        N = len(freq)
        shifted_freq = numpy.zeros(N, freq.dtype)

        S = numpy.round(shift if shift > 0 else N + shift, 0)
        s = N - S

        shifted_freq[:S] = freq[s:]
        shifted_freq[S:] = freq[:s]

        shifted_chunk = numpy.fft.irfft(shifted_freq)

        return shifted_chunk.astype(chunk.dtype)

Response: Pitch - Shift the given chunk by shift semi - tones.


Instruction:
Here you have a function in Python 3, explain what it does
def _time_stretcher(self, stretch_factor):
        start = self._i2
        end = min(self._i2 + self._N, len(self._sy) - (self._N + self._H))

        if start >= end:
            raise StopIteration

        # The not so clean code below basically implements a phase vocoder
        out = numpy.zeros(self._N, dtype=numpy.complex)

        while self._i2 < end:
            if self._i1 + self._N + self._H > len(self.y):
                raise StopIteration

            a, b = self._i1, self._i1 + self._N
            S1 = numpy.fft.fft(self._win * self.y[a: b])
            S2 = numpy.fft.fft(self._win * self.y[a + self._H: b + self._H])

            self._phi += (numpy.angle(S2) - numpy.angle(S1))
            self._phi = self._phi - 2.0 * numpy.pi * numpy.round(self._phi / (2.0 * numpy.pi))

            out.real, out.imag = numpy.cos(self._phi), numpy.sin(self._phi)

            self._sy[self._i2: self._i2 + self._N] += self._win * numpy.fft.ifft(numpy.abs(S2) * out).real

            self._i1 += int(self._H * self.stretch_factor)
            self._i2 += self._H

        chunk = self._sy[start:end]

        if stretch_factor == 1.0:
            chunk = self.y[start:end]

        return chunk

Response: Real time - scale without pitch modification.


Instruction:
Here you have a function in Python 3, explain what it does
def make_tokenizer(specs):

    def compile_spec(spec):
        name, args = spec
        return name, re.compile(*args)

    compiled = [compile_spec(s) for s in specs]

    def match_specs(specs, str, i, position):
        line, pos = position
        for type, regexp in specs:
            m = regexp.match(str, i)
            if m is not None:
                value = m.group()
                nls = value.count(u'\n')
                n_line = line + nls
                if nls == 0:
                    n_pos = pos + len(value)
                else:
                    n_pos = len(value) - value.rfind(u'\n') - 1
                return Token(type, value, (line, pos + 1), (n_line, n_pos))
        else:
            errline = str.splitlines()[line - 1]
            raise LexerError((line, pos + 1), errline)

    def f(str):
        length = len(str)
        line, pos = 1, 0
        i = 0
        while i < length:
            t = match_specs(compiled, str, i, (line, pos))
            yield t
            line, pos = t.end
            i += len(t.value)

    return f

Response: Returns a function that returns tokens for the given list of specs.


Instruction:
Here you have a function in Python 3, explain what it does
def finished(tokens, s):
    if s.pos >= len(tokens):
        return None, s
    else:
        raise NoParseError(u'should have reached <EOF>', s)

Response: Parser returns None if no more tokens are left in the input unparsed.


Instruction:
Write a Python 3 script for
returning a parser that applies one or more times to a parser.

Response:
def oneplus(p):
    """Parser(a, b) -> Parser(a, [b])

    Returns a parser that applies the parser p one or more times.
    """
    @Parser
    def _oneplus(tokens, s):
        (v1, s2) = p.run(tokens, s)
        (v2, s3) = many(p).run(tokens, s2)
        return [v1] + v2, s3

    _oneplus.name = u'(%s , { %s })' % (p.name, p.name)
    return _oneplus


Instruction:
Make a summary of the following Python 3 code
def with_forward_decls(suspension):

    @Parser
    def f(tokens, s):
        return suspension().run(tokens, s)

    return f

Response:
Returns a parser that computes itself lazily as a result of the suspension
   .


Instruction:
How would you explain what the following Python 3 function does
def define(self, p):
        f = getattr(p, 'run', p)
        if debug:
            setattr(self, '_run', f)
        else:
            setattr(self, 'run', f)
        self.named(getattr(p, 'name', p.__doc__))

Response: Defines a parser wrapped into this object.


Instruction:
Create a Python 3 function for
running a parser wrapped into this object.

Response:
def run(self, tokens, s):
        """Sequence(a), State -> (b, State)

        Runs a parser wrapped into this object.
        """
        if debug:
            log.debug(u'trying %s' % self.name)
        return self._run(tokens, s)


Instruction:
How would you explain what the following Python 3 function does
def parse(self, tokens):
        try:
            (tree, _) = self.run(tokens, State())
            return tree
        except NoParseError, e:
            max = e.state.max
            if len(tokens) > max:
                tok = tokens[max]
            else:
                tok = u'<EOF>'
            raise NoParseError(u'%s: %s' % (e.msg, tok), e.state)

Response: Applies the parser to a sequence of tokens producing a parsing result.


Instruction:
Write a Python 3 function that can
add a new sound to the Sampler.

Response:
def play(self, sound):
        """ Adds and plays a new Sound to the Sampler.

            :param sound: sound to play

            .. note:: If the sound is already playing, it will restart from the beginning.

        """
        self.is_done.clear()  # hold is_done until the sound is played
        if self.sr != sound.sr:
            raise ValueError('You can only play sound with a samplerate of {} (here {}). Use the Sound.resample method for instance.', self.sr, sound.sr)

        if sound in self.sounds:
            self.remove(sound)

        with self.chunk_available:
            self.sounds.append(sound)
            sound.playing = True

            self.chunk_available.notify()
        self.is_done.wait()


Instruction:
Make a summary of the following Python 3 code
def remove(self, sound):
        with self.chunk_available:
            sound.playing = False
            self.sounds.remove(sound)

Response: Remove a currently played sound.


Instruction:
Given the following Python 3 function, write the documentation
def next_chunks(self):
        with self.chunk_available:
            while True:
                playing_sounds = [s for s in self.sounds if s.playing]

                chunks = []
                for s in playing_sounds:
                    try:
                        chunks.append(next(s.chunks))
                    except StopIteration:
                        s.playing = False
                        self.sounds.remove(s)
                        self.is_done.set()  # sound was played, release is_done to end the wait in play

                if chunks:
                    break

                self.chunk_available.wait()

            return numpy.mean(chunks, axis=0)

Response: Gets a new chunk from all played sound and mix them together.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def run(self):
        self.running = True

        def chunks_producer():
            while self.running:
                self.chunks.put(self.next_chunks())

        t = Thread(target=chunks_producer)
        t.start()

        with self.BackendStream(samplerate=self.sr, channels=1) as stream:
            while self.running:
                try:
                    stream.write(self.chunks.get(timeout=self.timeout))  # timeout so stream.write() thread can exit
                except Empty:
                    self.running = False

Response: Play loop i. e. send all sound chunks by chunk to the soundcard.


Instruction:
Explain what the following Python 3 code does
def xml(self):
        root = Element('UsernameToken', ns=wssens)
        u = Element('Username', ns=wssens)
        u.setText(self.username)
        root.append(u)
        p = Element('Password', ns=wssens)
        p.setText(self.password)
        if self.password_digest:
            p.set("Type", wsdigest)
            p.setText(self.password_digest)
        root.append(p)
        if self.nonce is not None:
            n = Element('Nonce', ns=wssens)
            if self.nonce_has_encoding:
                n.set("EncodingType", nonce_encoding_type)
            n.setText(self.nonce)
            root.append(n)
        if self.created is not None:
            n = Element('Created', ns=wsuns)
            n.setText(str(DateTime(self.created)))
            root.append(n)
        return root

Response: Get xml representation of the object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def skip(self, attr):
        ns = attr.namespace()
        skip = (
            Namespace.xmlns[1],
            'http://schemas.xmlsoap.org/soap/encoding/',
            'http://schemas.xmlsoap.org/soap/envelope/',
            'http://www.w3.org/2003/05/soap-envelope',
        )
        return ( Namespace.xs(ns) or ns[1] in skip )

Response: Returns whether to skip the specified attribute.


Instruction:
Can you create a Python 3 function that
sorts items dependencies first in a given dependency tree.

Response:
def dependency_sort(dependency_tree):
    """
    Sorts items 'dependencies first' in a given dependency tree.

    A dependency tree is a dictionary mapping an object to a collection its
    dependency objects.

    Result is a properly sorted list of items, where each item is a 2-tuple
    containing an object and its dependency list, as given in the input
    dependency tree.

    If B is directly or indirectly dependent on A and they are not both a part
    of the same dependency cycle (i.e. then A is neither directly nor
    indirectly dependent on B) then A needs to come before B.

    If A and B are a part of the same dependency cycle, i.e. if they are both
    directly or indirectly dependent on each other, then it does not matter
    which comes first.

    Any entries found listed as dependencies, but that do not have their own
    dependencies listed as well, are logged & ignored.

    @return: The sorted items.
    @rtype: list

    """
    sorted = []
    processed = set()
    for key, deps in dependency_tree.iteritems():
        _sort_r(sorted, processed, key, deps, dependency_tree)
    return sorted


Instruction:
Given the following Python 3 function, write the documentation
def _sort_r(sorted, processed, key, deps, dependency_tree):
    if key in processed:
        return
    processed.add(key)
    for dep_key in deps:
        dep_deps = dependency_tree.get(dep_key)
        if dep_deps is None:
            log.debug('"%s" not found, skipped', Repr(dep_key))
            continue
        _sort_r(sorted, processed, dep_key, dep_deps, dependency_tree)
    sorted.append((key, deps))

Response: Recursive topological sort implementation.


Instruction:
Implement a Python 3 function for
resolving the node s type reference and returns the referenced external node.

Response:
def resolve(self, nobuiltin=False):
        """
        Resolve the node's type reference and return the referenced type node.

        Returns self if the type is defined locally, e.g. as a <complexType>
        subnode. Otherwise returns the referenced external node.

        @param nobuiltin: Flag indicating whether resolving to XSD built-in
            types should not be allowed.
        @return: The resolved (true) type.
        @rtype: L{SchemaObject}

        """
        cached = self.resolved_cache.get(nobuiltin)
        if cached is not None:
            return cached
        resolved = self.__resolve_type(nobuiltin)
        self.resolved_cache[nobuiltin] = resolved
        return resolved


Instruction:
Write a Python 3 function that can
set the type to <xsd : any/> when implicit.

Response:
def implany(self):
        """
        Set the type to <xsd:any/> when implicit.

        An element has an implicit <xsd:any/> type when it has no body and no
        explicitly defined type.

        @return: self
        @rtype: L{Element}

        """
        if self.type is None and self.ref is None and self.root.isempty():
            self.type = self.anytype()


Instruction:
Implement a Python 3 function for
getting this schema element s target namespace.

Response:
def namespace(self, prefix=None):
        """
        Get this schema element's target namespace.

        In case of reference elements, the target namespace is defined by the
        referenced and not the referencing element node.

        @param prefix: The default prefix.
        @type prefix: str
        @return: The schema element's target namespace
        @rtype: (I{prefix},I{URI})

        """
        e = self.__deref()
        if e is not None:
            return e.namespace(prefix)
        return super(Element, self).namespace()


Instruction:
Given the following Python 3 function, write the documentation
def open(self, options, loaded_schemata):
        if self.opened:
            return
        self.opened = True
        log.debug("%s, importing ns='%s', location='%s'", self.id, self.ns[1],
            self.location)
        result = self.__locate()
        if result is None:
            if self.location is None:
                log.debug("imported schema (%s) not-found", self.ns[1])
            else:
                url = self.location
                if "://" not in url:
                    url = urljoin(self.schema.baseurl, url)
                result = (loaded_schemata.get(url) or
                    self.__download(url, loaded_schemata, options))
        log.debug("imported:\n%s", result)
        return result

Response: Open and import the referenced schema.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def __locate(self):
        if self.ns[1] != self.schema.tns[1]:
            return self.schema.locate(self.ns)

Response: Find the schema locally.


Instruction:
How would you code a function in Python 3 to
make sure included schema has the same target namespace.

Response:
def __applytns(self, root):
        """Make sure included schema has the same target namespace."""
        TNS = "targetNamespace"
        tns = root.get(TNS)
        if tns is None:
            tns = self.schema.tns[1]
            root.set(TNS, tns)
        else:
            if self.schema.tns[1] != tns:
                raise Exception, "%s mismatch" % TNS


Instruction:
Write a Python 3 function for
resolving named references to other WSDL objects.

Response:
def resolve(self, definitions):
        """
        Resolve named references to other WSDL objects.

        Can be safely called multiple times.

        @param definitions: A definitions object.
        @type definitions: L{Definitions}

        """
        if not self.__resolved:
            self.do_resolve(definitions)
            self.__resolved = True


Instruction:
Here you have a function in Python 3, explain what it does
def mktns(self, root):
        tns = root.get("targetNamespace")
        prefix = root.findPrefix(tns)
        if prefix is None:
            log.debug("warning: tns (%s), not mapped to prefix", tns)
            prefix = "tns"
        return (prefix, tns)

Response: Get the target namespace.


Instruction:
How would you code a function in Python 3 to
open the imported WSDLs.

Response:
def open_imports(self, imported_definitions):
        """Import the I{imported} WSDLs."""
        for imp in self.imports:
            imp.load(self, imported_definitions)


Instruction:
Here you have a function in Python 3, explain what it does
def add_methods(self, service):
        bindings = {
            "document/literal": Document(self),
            "rpc/literal": RPC(self),
            "rpc/encoded": Encoded(self)}
        for p in service.ports:
            binding = p.binding
            ptype = p.binding.type
            operations = p.binding.type.operations.values()
            for name in (op.name for op in operations):
                m = Facade("Method")
                m.name = name
                m.location = p.location
                m.binding = Facade("binding")
                op = binding.operation(name)
                m.soap = op.soap
                key = "/".join((op.soap.style, op.soap.input.body.use))
                m.binding.input = bindings.get(key)
                key = "/".join((op.soap.style, op.soap.output.body.use))
                m.binding.output = bindings.get(key)
                p.methods[name] = m

Response: Build method view for service.


Instruction:
Make a summary of the following Python 3 code
def import_schema(self, definitions, d):
        if not definitions.types:
            root = Element("types", ns=wsdlns)
            definitions.root.insert(root)
            types = Types(root, definitions)
            definitions.types.append(types)
        else:
            types = definitions.types[-1]
        types.root.append(d.root)
        log.debug("imported (XSD):\n%s", d.root)

Response: Import schema as <types/> content.


Instruction:
Can you tell what is the following Python 3 function doing
def soaproot(self):
        for ns in (soapns, soap12ns):
            sr = self.root.getChild("binding", ns=ns)
            if sr is not None:
                return sr

Response: Get the soap root element.


Instruction:
Explain what the following Python 3 code does
def do_resolve(self, definitions):
        self.__resolveport(definitions)
        for op in self.operations.values():
            self.__resolvesoapbody(definitions, op)
            self.__resolveheaders(definitions, op)
            self.__resolvefaults(definitions, op)

Response: Resolve named references to other WSDL objects.


Instruction:
Write a Python 3 script to
resolve a port type reference.

Response:
def __resolveport(self, definitions):
        """
        Resolve port_type reference.

        @param definitions: A definitions object.
        @type definitions: L{Definitions}

        """
        ref = qualify(self.type, self.root, definitions.tns)
        port_type = definitions.port_types.get(ref)
        if port_type is None:
            raise Exception("portType '%s', not-found" % (self.type,))
        # Later on we will require access to the message data referenced by
        # this port_type instance, and in order for those data references to be
        # available, port_type first needs to dereference its message
        # identification string. The only scenario where the port_type might
        # possibly not have already resolved its references, and where this
        # explicit resolve() call is required, is if we are dealing with a
        # recursive WSDL import chain.
        port_type.resolve(definitions)
        self.type = port_type


Instruction:
Can you generate a brief explanation for the following Python 3 code
def port(self, name):
        for p in self.ports:
            if p.name == name:
                return p

Response: Locate a port by name.


Instruction:
How would you explain what the following Python 3 function does
def do_resolve(self, definitions):
        filtered = []
        for p in self.ports:
            ref = qualify(p.binding, self.root, definitions.tns)
            binding = definitions.bindings.get(ref)
            if binding is None:
                raise Exception("binding '%s', not-found" % (p.binding,))
            if binding.soap is None:
                log.debug("binding '%s' - not a SOAP binding, discarded",
                    binding.name)
                continue
            # After we have been resolved, our caller will expect that the
            # binding we are referencing has been fully constructed, i.e.
            # resolved, as well. The only scenario where the operations binding
            # might possibly not have already resolved its references, and
            # where this explicit resolve() call is required, is if we are
            # dealing with a recursive WSDL import chain.
            binding.resolve(definitions)
            p.binding = binding
            filtered.append(p)
        self.ports = filtered

Response:
Resolve named references to other WSDL objects. Ports without SOAP
            bindings are discarded.


Instruction:
Write a Python 3 script to
create an object based on the root tag name.

Response:
def create(cls, root, definitions):
        """
        Create an object based on the root tag name.

        @param root: An XML root element.
        @type root: L{Element}
        @param definitions: A definitions object.
        @type definitions: L{Definitions}
        @return: The created object.
        @rtype: L{WObject}

        """
        fn = cls.tags.get(root.name)
        if fn is not None:
            return fn(root, definitions)