Instruction:
Can you create a Python 3 function that
installs the wheel into site - packages.

Response:
def install(self, force=False, overrides={}):
        """
        Install the wheel into site-packages.
        """

        # Utility to get the target directory for a particular key
        def get_path(key):
            return overrides.get(key) or self.install_paths[key]

        # The base target location is either purelib or platlib
        if self.parsed_wheel_info['Root-Is-Purelib'] == 'true':
            root = get_path('purelib')
        else:
            root = get_path('platlib')

        # Parse all the names in the archive
        name_trans = {}
        for info in self.zipfile.infolist():
            name = info.filename
            # Zip files can contain entries representing directories.
            # These end in a '/'.
            # We ignore these, as we create directories on demand.
            if name.endswith('/'):
                continue

            # Pathnames in a zipfile namelist are always /-separated.
            # In theory, paths could start with ./ or have other oddities
            # but this won't happen in practical cases of well-formed wheels.
            # We'll cover the simple case of an initial './' as it's both easy
            # to do and more common than most other oddities.
            if name.startswith('./'):
                name = name[2:]

            # Split off the base directory to identify files that are to be
            # installed in non-root locations
            basedir, sep, filename = name.partition('/')
            if sep and basedir == self.datadir_name:
                # Data file. Target destination is elsewhere
                key, sep, filename = filename.partition('/')
                if not sep:
                    raise ValueError("Invalid filename in wheel: {0}".format(name))
                target = get_path(key)
            else:
                # Normal file. Target destination is root
                key = ''
                target = root
                filename = name

            # Map the actual filename from the zipfile to its intended target
            # directory and the pathname relative to that directory.
            dest = os.path.normpath(os.path.join(target, filename))
            name_trans[info] = (key, target, filename, dest)

        # We're now ready to start processing the actual install. The process
        # is as follows:
        #   1. Prechecks - is the wheel valid, is its declared architecture
        #      OK, etc. [[Responsibility of the caller]]
        #   2. Overwrite check - do any of the files to be installed already
        #      exist?
        #   3. Actual install - put the files in their target locations.
        #   4. Update RECORD - write a suitably modified RECORD file to
        #      reflect the actual installed paths.

        if not force:
            for info, v in name_trans.items():
                k = info.filename
                key, target, filename, dest = v
                if os.path.exists(dest):
                    raise ValueError("Wheel file {0} would overwrite {1}. Use force if this is intended".format(k, dest))

        # Get the name of our executable, for use when replacing script
        # wrapper hashbang lines.
        # We encode it using getfilesystemencoding, as that is "the name of
        # the encoding used to convert Unicode filenames into system file
        # names".
        exename = sys.executable.encode(sys.getfilesystemencoding())
        record_data = []
        record_name = self.distinfo_name + '/RECORD'
        for info, (key, target, filename, dest) in name_trans.items():
            name = info.filename
            source = self.zipfile.open(info)
            # Skip the RECORD file
            if name == record_name:
                continue
            ddir = os.path.dirname(dest)
            if not os.path.isdir(ddir):
                os.makedirs(ddir)
            destination = HashingFile(open(dest, 'wb'))
            if key == 'scripts':
                hashbang = source.readline()
                if hashbang.startswith(b'#!python'):
                    hashbang = b'#!' + exename + binary(os.linesep)
                destination.write(hashbang)
            shutil.copyfileobj(source, destination)
            reldest = os.path.relpath(dest, root)
            reldest.replace(os.sep, '/')
            record_data.append((reldest, destination.digest(), destination.length))
            destination.close()
            source.close()
            # preserve attributes (especially +x bit for scripts)
            attrs = info.external_attr >> 16
            if attrs:  # tends to be 0 if Windows.
                os.chmod(dest, info.external_attr >> 16)

        record_name = os.path.join(root, self.record_name)
        writer = csv.writer(open_for_csv(record_name, 'w+'))
        for reldest, digest, length in sorted(record_data):
            writer.writerow((reldest, digest, length))
        writer.writerow((self.record_name, '', ''))


Instruction:
Write a Python 3 script for
configuring the VerifyingZipFile zipfile by verifying its signature and setting expected hashes for every hash in RECORD.

Response:
def verify(self, zipfile=None):
        """Configure the VerifyingZipFile `zipfile` by verifying its signature
        and setting expected hashes for every hash in RECORD.
        Caller must complete the verification process by completely reading
        every file in the archive (e.g. with extractall)."""
        sig = None
        if zipfile is None:
            zipfile = self.zipfile
        zipfile.strict = True

        record_name = '/'.join((self.distinfo_name, 'RECORD'))
        sig_name = '/'.join((self.distinfo_name, 'RECORD.jws'))
        # tolerate s/mime signatures:
        smime_sig_name = '/'.join((self.distinfo_name, 'RECORD.p7s'))
        zipfile.set_expected_hash(record_name, None)
        zipfile.set_expected_hash(sig_name, None)
        zipfile.set_expected_hash(smime_sig_name, None)
        record = zipfile.read(record_name)

        record_digest = urlsafe_b64encode(hashlib.sha256(record).digest())
        try:
            sig = from_json(native(zipfile.read(sig_name)))
        except KeyError:  # no signature
            pass
        if sig:
            headers, payload = signatures.verify(sig)
            if payload['hash'] != "sha256=" + native(record_digest):
                msg = "RECORD.sig claimed RECORD hash {0} != computed hash {1}."
                raise BadWheelFile(msg.format(payload['hash'],
                                              native(record_digest)))

        reader = csv.reader((native(r) for r in record.splitlines()))

        for row in reader:
            filename = row[0]
            hash = row[1]
            if not hash:
                if filename not in (record_name, sig_name):
                    sys.stderr.write("%s has no hash!\n" % filename)
                continue
            algo, data = row[1].split('=', 1)
            assert algo == "sha256", "Unsupported hash algorithm"
            zipfile.set_expected_hash(filename, urlsafe_b64decode(binary(data)))


Instruction:
Can you implement a function in Python 3 that
checks if a name is declared in this or an outer scope.

Response:
def is_declared(self, name):
        """Check if a name is declared in this or an outer scope."""
        if name in self.declared_locally or name in self.declared_parameter:
            return True
        return name in self.declared


Instruction:
Can you tell what is the following Python 3 function doing
def inspect(self, nodes):
        visitor = FrameIdentifierVisitor(self.identifiers)
        for node in nodes:
            visitor.visit(node)

Response: Walk the node and check for identifiers.


Instruction:
How would you explain what the following Python 3 function does
def visit_Name(self, node):
        if node.ctx == 'store':
            self.identifiers.declared_locally.add(node.name)
        elif node.ctx == 'param':
            self.identifiers.declared_parameter.add(node.name)
        elif node.ctx == 'load' and not \
             self.identifiers.is_declared(node.name):
            self.identifiers.undeclared.add(node.name)

Response: All assignments to names go through this function.


Instruction:
Create a Python 3 function for
creating a whl file from all the files under base_dir.

Response:
def make_wheelfile_inner(base_name, base_dir='.'):
    """Create a whl file from all the files under 'base_dir'.

    Places .dist-info at the end of the archive."""

    zip_filename = base_name + ".whl"

    log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)

    # XXX support bz2, xz when available
    zip = zipfile.ZipFile(open(zip_filename, "wb+"), "w",
                          compression=zipfile.ZIP_DEFLATED)

    score = {'WHEEL': 1, 'METADATA': 2, 'RECORD': 3}
    deferred = []

    def writefile(path):
        zip.write(path, path)
        log.info("adding '%s'" % path)

    for dirpath, dirnames, filenames in os.walk(base_dir):
        for name in filenames:
            path = os.path.normpath(os.path.join(dirpath, name))

            if os.path.isfile(path):
                if dirpath.endswith('.dist-info'):
                    deferred.append((score.get(name, 0), path))
                else:
                    writefile(path)

    deferred.sort()
    for score, path in deferred:
        writefile(path)

    zip.close()

    return zip_filename


Instruction:
Can you tell what is the following Python 3 function doing
def atomize(f, lock=None):
	lock = lock or threading.RLock()

	@functools.wraps(f)
	def exec_atomic(*args, **kwargs):
		lock.acquire()
		try:
			return f(*args, **kwargs)
		finally:
			lock.release()
	return exec_atomic

Response: Decorate a function with a reentrant lock to prevent multiple threads from calling said thread simultaneously.


Instruction:
Write a Python 3 function that can
create a service and start server.

Response:
def service_factory(app, host, port,
                    report_message='service factory port {port}',
                    provider_cls=HTTPServiceProvider):
    """Create service, start server.

    :param app: application to instantiate a service
    :param host: interface to bound provider
    :param port: port to bound provider
    :param report_message: message format to report port
    :param provider_cls: server class provide a service

    """

    service = Service(app)
    server = provider_cls(service, host, port, report_message)
    server.serve_forever()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def unicode_urlencode(obj, charset='utf-8'):
    if not isinstance(obj, string_types):
        obj = text_type(obj)
    if isinstance(obj, text_type):
        obj = obj.encode(charset)
    return text_type(url_quote(obj))

Response: URL escapes a single bytestring or unicode string with the given charset if applicable to URL safe quoting under all supported Python versions.


Instruction:
Can you tell what is the following Python 3 function doing
def matches_requirement(req, wheels):
    try:
        from pkg_resources import Distribution, Requirement
    except ImportError:
        raise RuntimeError("Cannot use requirements without pkg_resources")

    req = Requirement.parse(req)

    selected = []
    for wf in wheels:
        f = wf.parsed_filename
        dist = Distribution(project_name=f.group("name"), version=f.group("ver"))
        if dist in req:
            selected.append(wf)
    return selected

Response: Returns a list of wheels that satisfy a requirement.


Instruction:
Can you write a function in Python 3 where it
populates a requirement set with the contents of the command line args.

Response:
def populate_requirement_set(requirement_set, args, options, finder,
                                 session, name, wheel_cache):
        """
        Marshal cmd line args into a requirement set.
        """
        for req in args:
            requirement_set.add_requirement(
                InstallRequirement.from_line(
                    req, None, isolated=options.isolated_mode,
                    wheel_cache=wheel_cache
                )
            )

        for req in options.editables:
            requirement_set.add_requirement(
                InstallRequirement.from_editable(
                    req,
                    default_vcs=options.default_vcs,
                    isolated=options.isolated_mode,
                    wheel_cache=wheel_cache
                )
            )

        found_req_in_file = False
        for filename in options.requirements:
            for req in parse_requirements(
                    filename,
                    finder=finder, options=options, session=session,
                    wheel_cache=wheel_cache):
                found_req_in_file = True
                requirement_set.add_requirement(req)

        if not (args or options.editables or found_req_in_file):
            opts = {'name': name}
            if options.find_links:
                msg = ('You must give at least one requirement to '
                       '%(name)s (maybe you meant "pip %(name)s '
                       '%(links)s"?)' %
                       dict(opts, links=' '.join(options.find_links)))
            else:
                msg = ('You must give at least one requirement '
                       'to %(name)s (see "pip help %(name)s")' % opts)
            logger.warning(msg)


Instruction:
Implement a Python 3 function for
calling the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a contextfunction or environmentfunction.

Response:
def call(__self, __obj, *args, **kwargs):
        """Call the callable with the arguments and keyword arguments
        provided but inject the active context or environment as first
        argument if the callable is a :func:`contextfunction` or
        :func:`environmentfunction`.
        """
        if __debug__:
            __traceback_hide__ = True

        # Allow callable classes to take a context
        fn = __obj.__call__
        for fn_type in ('contextfunction',
                        'evalcontextfunction',
                        'environmentfunction'):
            if hasattr(fn, fn_type):
                __obj = fn
                break

        if isinstance(__obj, _context_function_types):
            if getattr(__obj, 'contextfunction', 0):
                args = (__self,) + args
            elif getattr(__obj, 'evalcontextfunction', 0):
                args = (__self.eval_ctx,) + args
            elif getattr(__obj, 'environmentfunction', 0):
                args = (__self.environment,) + args
        try:
            return __obj(*args, **kwargs)
        except StopIteration:
            return __self.environment.undefined('value was undefined because '
                                                'a callable raised a '
                                                'StopIteration exception')


Instruction:
Can you tell what is the following Python 3 function doing
def export(self, location):
        temp_dir = tempfile.mkdtemp('-export', 'pip-')
        self.unpack(temp_dir)
        if os.path.exists(location):
            # Remove the location to make sure Bazaar can export it correctly
            rmtree(location)
        try:
            self.run_command(['export', location], cwd=temp_dir,
                             show_stdout=False)
        finally:
            rmtree(temp_dir)

Response: Export the Bazaar repository at the url to the destination location


Instruction:
Can you tell what is the following Python 3 function doing
def pip_version_check(session):
    import pip  # imported here to prevent circular imports
    pypi_version = None

    try:
        state = load_selfcheck_statefile()

        current_time = datetime.datetime.utcnow()
        # Determine if we need to refresh the state
        if "last_check" in state.state and "pypi_version" in state.state:
            last_check = datetime.datetime.strptime(
                state.state["last_check"],
                SELFCHECK_DATE_FMT
            )
            if total_seconds(current_time - last_check) < 7 * 24 * 60 * 60:
                pypi_version = state.state["pypi_version"]

        # Refresh the version if we need to or just see if we need to warn
        if pypi_version is None:
            resp = session.get(
                PyPI.pip_json_url,
                headers={"Accept": "application/json"},
            )
            resp.raise_for_status()
            pypi_version = [
                v for v in sorted(
                    list(resp.json()["releases"]),
                    key=packaging_version.parse,
                )
                if not packaging_version.parse(v).is_prerelease
            ][-1]

            # save that we've performed a check
            state.save(pypi_version, current_time)

        pip_version = packaging_version.parse(pip.__version__)
        remote_version = packaging_version.parse(pypi_version)

        # Determine if our pypi_version is older
        if (pip_version < remote_version and
                pip_version.base_version != remote_version.base_version):
            # Advise "python -m pip" on Windows to avoid issues
            # with overwriting pip.exe.
            if WINDOWS:
                pip_cmd = "python -m pip"
            else:
                pip_cmd = "pip"
            logger.warning(
                "You are using pip version %s, however version %s is "
                "available.\nYou should consider upgrading via the "
                "'%s install --upgrade pip' command." % (pip.__version__,
                                                         pypi_version,
                                                         pip_cmd)
            )

    except Exception:
        logger.debug(
            "There was an error checking the latest version of pip",
            exc_info=True,
        )

Response: Checks if pip version is older than the current one.


Instruction:
Create a Python 3 function to
iterate over all pages.

Response:
def iterate_pages(self):
        """Iterate Pages.

        A generator which iterates over all pages.
        Keep in mind that Amazon limits the number of pages it makes available.

        :return:
            Yields lxml root elements.
        """
        try:
            while True:
                yield self._query(ItemPage=self.current_page, **self.kwargs)
                self.current_page += 1
        except NoMorePages:
            pass


Instruction:
Can you create a Python 3 function that
queries Amazon Search and check for errors.

Response:
def _query(self, ResponseGroup="Large", **kwargs):
        """Query.

        Query Amazon search and check for errors.

        :return:
            An lxml root element.
        """
        response = self.api.ItemSearch(ResponseGroup=ResponseGroup, **kwargs)
        root = objectify.fromstring(response)
        if root.Items.Request.IsValid == 'False':
            code = root.Items.Request.Errors.Error.Code
            msg = root.Items.Request.Errors.Error.Message
            if code == 'AWS.ParameterOutOfRange':
                raise NoMorePages(msg)
            else:
                raise SearchException(
                    "Amazon Search Error: '{0}', '{1}'".format(code, msg))
        return root


Instruction:
Can you implement a function in Python 3 that
safes Get Element. Get a child element of root (multiple levels deep) failing silently if any descendant does not exist. :param root: Lxml element. :param path: String path (i.e. 'Items.Item.Offers.Offer'). :return: Element or None.

Response:
def _safe_get_element(self, path, root=None):
        """Safe Get Element.

        Get a child element of root (multiple levels deep) failing silently
        if any descendant does not exist.

        :param root:
            Lxml element.
        :param path:
            String path (i.e. 'Items.Item.Offers.Offer').
        :return:
            Element or None.
        """
        elements = path.split('.')
        parent = root if root is not None else self.item
        for element in elements[:-1]:
            parent = getattr(parent, element, None)
            if parent is None:
                return None
        return getattr(parent, elements[-1], None)


Instruction:
Can you write a function in Python 3 where it
safes get element text.

Response:
def _safe_get_element_text(self, path, root=None):
        """Safe get element text.

        Get element as string or None,
        :param root:
            Lxml element.
        :param path:
            String path (i.e. 'Items.Item.Offers.Offer').
        :return:
            String or None.
        """
        element = self._safe_get_element(path, root)
        if element:
            return element.text
        else:
            return None


Instruction:
Here you have a function in Python 3, explain what it does
def _safe_get_element_date(self, path, root=None):
        value = self._safe_get_element_text(path=path, root=root)
        if value is not None:
            try:
                value = datetime.datetime.strptime(value, '%Y-%m-%d').date()
            except ValueError:
                value = None

        return value

Response: Safe get elemnent date.


Instruction:
Make a summary of the following Python 3 code
def price_and_currency(self):
        price = self._safe_get_element_text(
            'Offers.Offer.OfferListing.SalePrice.Amount')
        if price:
            currency = self._safe_get_element_text(
                'Offers.Offer.OfferListing.SalePrice.CurrencyCode')
        else:
            price = self._safe_get_element_text(
                'Offers.Offer.OfferListing.Price.Amount')
            if price:
                currency = self._safe_get_element_text(
                    'Offers.Offer.OfferListing.Price.CurrencyCode')
            else:
                price = self._safe_get_element_text(
                    'OfferSummary.LowestNewPrice.Amount')
                currency = self._safe_get_element_text(
                    'OfferSummary.LowestNewPrice.CurrencyCode')
        if price:
            return float(price) / 100, currency
        else:
            return None, None

Response: Get Offer Price and Currency.


Instruction:
Write a Python 3 script to
return a tuple containing the float representation of price.

Response:
def list_price(self):
        """List Price.

        :return:
            A tuple containing:

                1. Float representation of price.
                2. ISO Currency code (string).
        """
        price = self._safe_get_element_text('ItemAttributes.ListPrice.Amount')
        currency = self._safe_get_element_text(
            'ItemAttributes.ListPrice.CurrencyCode')
        if price:
            return float(price) / 100, currency
        else:
            return None, None


Instruction:
Can you write a function in Python 3 where it
sends a request to the cache.

Response:
def send(self, request, **kw):
        """
        Send a request. Use the request information to see if it
        exists in the cache and cache the response if we need to and can.
        """
        if request.method == 'GET':
            cached_response = self.controller.cached_request(request)
            if cached_response:
                return self.build_response(request, cached_response,
                                           from_cache=True)

            # check for etags and add headers if appropriate
            request.headers.update(
                self.controller.conditional_headers(request)
            )

        resp = super(CacheControlAdapter, self).send(request, **kw)

        return resp


Instruction:
Make a summary of the following Python 3 code
def build_response(self, request, response, from_cache=False):
        if not from_cache and request.method == 'GET':

            # apply any expiration heuristics
            if response.status == 304:
                # We must have sent an ETag request. This could mean
                # that we've been expired already or that we simply
                # have an etag. In either case, we want to try and
                # update the cache if that is the case.
                cached_response = self.controller.update_cached_response(
                    request, response
                )

                if cached_response is not response:
                    from_cache = True

                # We are done with the server response, read a
                # possible response body (compliant servers will
                # not return one, but we cannot be 100% sure) and
                # release the connection back to the pool.
                response.read(decode_content=False)
                response.release_conn()

                response = cached_response

            # We always cache the 301 responses
            elif response.status == 301:
                self.controller.cache_response(request, response)
            else:
                # Check for any heuristics that might update headers
                # before trying to cache.
                if self.heuristic:
                    response = self.heuristic.apply(response)

                # Wrap the response file with a wrapper that will cache the
                #   response when the stream has been consumed.
                response._fp = CallbackFileWrapper(
                    response._fp,
                    functools.partial(
                        self.controller.cache_response,
                        request,
                        response,
                    )
                )

        resp = super(CacheControlAdapter, self).build_response(
            request, response
        )

        # See if we should invalidate the cache.
        if request.method in self.invalidating_methods and resp.ok:
            cache_url = self.controller.cache_url(request.url)
            self.cache.delete(cache_url)

        # Give the request a from_cache attr to let people use it
        resp.from_cache = from_cache

        return resp

Response: Build a response by making a request or using the cache.


Instruction:
Write a Python 3 script to
return a callable that looks up the given attribute from a passed object with the rules of the environment.

Response:
def make_attrgetter(environment, attribute):
    """Returns a callable that looks up the given attribute from a
    passed object with the rules of the environment.  Dots are allowed
    to access attributes of attributes.  Integer parts in paths are
    looked up as integers.
    """
    if not isinstance(attribute, string_types) \
       or ('.' not in attribute and not attribute.isdigit()):
        return lambda x: environment.getitem(x, attribute)
    attribute = attribute.split('.')
    def attrgetter(item):
        for part in attribute:
            if part.isdigit():
                part = int(part)
            item = environment.getitem(item, part)
        return item
    return attrgetter


Instruction:
Can you generate a brief explanation for the following Python 3 code
def do_title(s):
    rv = []
    for item in re.compile(r'([-\s]+)(?u)').split(s):
        if not item:
            continue
        rv.append(item[0].upper() + item[1:].lower())
    return ''.join(rv)

Response:
Return a titlecased version of the value. I. e. words will start with
    uppercase letters all remaining characters are lowercase.


Instruction:
Write a Python 3 script for
sorting a dict and yield key value pairs.

Response:
def do_dictsort(value, case_sensitive=False, by='key'):
    """Sort a dict and yield (key, value) pairs. Because python dicts are
    unsorted you may want to use this function to order them by either
    key or value:

    .. sourcecode:: jinja

        {% for item in mydict|dictsort %}
            sort the dict by key, case insensitive

        {% for item in mydict|dictsort(true) %}
            sort the dict by key, case sensitive

        {% for item in mydict|dictsort(false, 'value') %}
            sort the dict by key, case insensitive, sorted
            normally and ordered by value.
    """
    if by == 'key':
        pos = 0
    elif by == 'value':
        pos = 1
    else:
        raise FilterArgumentError('You can only sort by either '
                                  '"key" or "value"')
    def sort_func(item):
        value = item[pos]
        if isinstance(value, string_types) and not case_sensitive:
            value = value.lower()
        return value

    return sorted(value.items(), key=sort_func)


Instruction:
Explain what the following Python 3 code does
def do_sort(environment, value, reverse=False, case_sensitive=False,
            attribute=None):
    """Sort an iterable.  Per default it sorts ascending, if you pass it
    true as first argument it will reverse the sorting.

    If the iterable is made of strings the third parameter can be used to
    control the case sensitiveness of the comparison which is disabled by
    default.

    .. sourcecode:: jinja

        {% for item in iterable|sort %}
            ...
        {% endfor %}

    It is also possible to sort by an attribute (for example to sort
    by the date of an object) by specifying the `attribute` parameter:

    .. sourcecode:: jinja

        {% for item in iterable|sort(attribute='date') %}
            ...
        {% endfor %}

    .. versionchanged:: 2.6
       The `attribute` parameter was added.
    """
    if not case_sensitive:
        def sort_func(item):
            if isinstance(item, string_types):
                item = item.lower()
            return item
    else:
        sort_func = None
    if attribute is not None:
        getter = make_attrgetter(environment, attribute)
        def sort_func(item, processor=sort_func or (lambda x: x)):
            return processor(getter(item))
    return sorted(value, key=sort_func, reverse=reverse)

Response:
Sort an iterable.  Per default it sorts ascending, if you pass it
    true as first argument it will reverse the sorting.

    If the iterable is made of strings the third parameter can be used to
    control the case sensitiveness of the comparison which is disabled by
    default.

    .. sourcecode:: jinja

        {% for item in iterable|sort %}
            ...
        {% endfor %}

    It is also possible to sort by an attribute (for example to sort
    by the date of an object) by specifying the `attribute` parameter:

    .. sourcecode:: jinja

        {% for item in iterable|sort(attribute='date') %}
            ...
        {% endfor %}

    .. versionchanged:: 2.6
       The `attribute` parameter was added.


Instruction:
Implement a Python 3 function for
grouping a sequence of objects by a common attribute.

Response:
def do_groupby(environment, value, attribute):
    """Group a sequence of objects by a common attribute.

    If you for example have a list of dicts or objects that represent persons
    with `gender`, `first_name` and `last_name` attributes and you want to
    group all users by genders you can do something like the following
    snippet:

    .. sourcecode:: html+jinja

        {% for group in persons|groupby('gender') %}

{{ group.grouper }}

            {% for person in group.list %}

{{ person.first_name }} {{ person.last_name }}

            {% endfor %}

        {% endfor %}

    Additionally it's possible to use tuple unpacking for the grouper and
    list:

    .. sourcecode:: html+jinja

        {% for grouper, list in persons|groupby('gender') %}
            ...
        {% endfor %}

    As you can see the item we're grouping by is stored in the `grouper`
    attribute and the `list` contains all the objects that have this grouper
    in common.

    .. versionchanged:: 2.6
       It's now possible to use dotted notation to group by the child
       attribute of another attribute.
    """
    expr = make_attrgetter(environment, attribute)
    return sorted(map(_GroupTuple, groupby(sorted(value, key=expr), expr)))


Instruction:
Make a summary of the following Python 3 code
def do_map(*args, **kwargs):
    context = args[0]
    seq = args[1]

    if len(args) == 2 and 'attribute' in kwargs:
        attribute = kwargs.pop('attribute')
        if kwargs:
            raise FilterArgumentError('Unexpected keyword argument %r' %
                next(iter(kwargs)))
        func = make_attrgetter(context.environment, attribute)
    else:
        try:
            name = args[2]
            args = args[3:]
        except LookupError:
            raise FilterArgumentError('map requires a filter argument')
        func = lambda item: context.environment.call_filter(
            name, item, args, kwargs, context=context)

    if seq:
        for item in seq:
            yield func(item)

Response: Applies a filter on a sequence of objects or looks up an attribute.


Instruction:
Can you tell what is the following Python 3 function doing
def create_logger(app):
    Logger = getLoggerClass()

    class DebugLogger(Logger):
        def getEffectiveLevel(x):
            if x.level == 0 and app.debug:
                return DEBUG
            return Logger.getEffectiveLevel(x)

    class DebugHandler(StreamHandler):
        def emit(x, record):
            StreamHandler.emit(x, record) if app.debug else None

    handler = DebugHandler()
    handler.setLevel(DEBUG)
    handler.setFormatter(Formatter(app.debug_log_format))
    logger = getLogger(app.logger_name)
    # just in case that was not a new logger, get rid of all the handlers
    # already attached to it.
    del logger.handlers[:]
    logger.__class__ = DebugLogger
    logger.addHandler(handler)
    return logger

Response: Creates a logger for the given application.


Instruction:
Here you have a function in Python 3, explain what it does
def constant_time_compare(val1, val2):
    if _builtin_constant_time_compare is not None:
        return _builtin_constant_time_compare(val1, val2)
    len_eq = len(val1) == len(val2)
    if len_eq:
        result = 0
        left = val1
    else:
        result = 1
        left = val2
    for x, y in izip(bytearray(left), bytearray(val2)):
        result |= x ^ y
    return result == 0

Response: Returns True if the two strings are equal False otherwise.


Instruction:
Make a summary of the following Python 3 code
def base64_decode(string):
    string = want_bytes(string, encoding='ascii', errors='ignore')
    return base64.urlsafe_b64decode(string + b'=' * (-len(string) % 4))

Response: base64 decodes a single bytestring


Instruction:
Write a Python 3 script for
verifying the given signature matches the expected signature

Response:
def verify_signature(self, key, value, sig):
        """Verifies the given signature matches the expected signature"""
        return constant_time_compare(sig, self.get_signature(key, value))


Instruction:
Implement a function in Python 3 to
return the signature for the given value

Response:
def get_signature(self, value):
        """Returns the signature for the given value"""
        value = want_bytes(value)
        key = self.derive_key()
        sig = self.algorithm.get_signature(key, value)
        return base64_encode(sig)


Instruction:
Can you write a function in Python 3 where it
signs the given string.

Response:
def sign(self, value):
        """Signs the given string."""
        return value + want_bytes(self.sep) + self.get_signature(value)


Instruction:
Given the following Python 3 function, write the documentation
def verify_signature(self, value, sig):
        key = self.derive_key()
        try:
            sig = base64_decode(sig)
        except Exception:
            return False
        return self.algorithm.verify_signature(key, value, sig)

Response: Verifies the signature for the given value.


Instruction:
Can you generate the documentation for the following Python 3 function
def sign(self, value):
        value = want_bytes(value)
        timestamp = base64_encode(int_to_bytes(self.get_timestamp()))
        sep = want_bytes(self.sep)
        value = value + sep + timestamp
        return value + sep + self.get_signature(value)

Response: Signs the given string and also attaches a time information.


Instruction:
Write a Python 3 function for
working like the regular :meth:`~Signer.unsign` but can also validate the time. See the base docstring of the class for the general behavior. If `return_timestamp` is set to `True` the timestamp of the signature will be returned as naive :class:`datetime.datetime` object in UTC.

Response:
def unsign(self, value, max_age=None, return_timestamp=False):
        """Works like the regular :meth:`~Signer.unsign` but can also
        validate the time.  See the base docstring of the class for
        the general behavior.  If `return_timestamp` is set to `True`
        the timestamp of the signature will be returned as naive
        :class:`datetime.datetime` object in UTC.
        """
        try:
            result = Signer.unsign(self, value)
            sig_error = None
        except BadSignature as e:
            sig_error = e
            result = e.payload or b''
        sep = want_bytes(self.sep)

        # If there is no timestamp in the result there is something
        # seriously wrong.  In case there was a signature error, we raise
        # that one directly, otherwise we have a weird situation in which
        # we shouldn't have come except someone uses a time-based serializer
        # on non-timestamp data, so catch that.
        if not sep in result:
            if sig_error:
                raise sig_error
            raise BadTimeSignature('timestamp missing', payload=result)

        value, timestamp = result.rsplit(sep, 1)
        try:
            timestamp = bytes_to_int(base64_decode(timestamp))
        except Exception:
            timestamp = None

        # Signature is *not* okay.  Raise a proper error now that we have
        # split the value and the timestamp.
        if sig_error is not None:
            raise BadTimeSignature(text_type(sig_error), payload=value,
                                   date_signed=timestamp)

        # Signature was okay but the timestamp is actually not there or
        # malformed.  Should not happen, but well.  We handle it nonetheless
        if timestamp is None:
            raise BadTimeSignature('Malformed timestamp', payload=value)

        # Check timestamp is not older than max_age
        if max_age is not None:
            age = self.get_timestamp() - timestamp
            if age > max_age:
                raise SignatureExpired(
                    'Signature age %s > %s seconds' % (age, max_age),
                    payload=value,
                    date_signed=self.timestamp_to_datetime(timestamp))

        if return_timestamp:
            return value, self.timestamp_to_datetime(timestamp)
        return value


Instruction:
Write a Python 3 script to
return True if the given signed value is valid False otherwise.

Response:
def validate(self, signed_value, max_age=None):
        """Just validates the given signed value.  Returns `True` if the
        signature exists and is valid, `False` otherwise."""
        try:
            self.unsign(signed_value, max_age=max_age)
            return True
        except BadSignature:
            return False


Instruction:
Implement a Python 3 function for
loading the encoded object.

Response:
def load_payload(self, payload, serializer=None):
        """Loads the encoded object.  This function raises :class:`BadPayload`
        if the payload is not valid.  The `serializer` parameter can be used to
        override the serializer stored on the class.  The encoded payload is
        always byte based.
        """
        if serializer is None:
            serializer = self.serializer
            is_text = self.is_text_serializer
        else:
            is_text = is_text_serializer(serializer)
        try:
            if is_text:
                payload = payload.decode('utf-8')
            return serializer.loads(payload)
        except Exception as e:
            raise BadPayload('Could not load the payload because an '
                'exception occurred on unserializing the data',
                original_error=e)


Instruction:
Create a Python 3 function to
return a signed string serialized with the internal serializer.

Response:
def dumps(self, obj, salt=None):
        """Returns a signed string serialized with the internal serializer.
        The return value can be either a byte or unicode string depending
        on the format of the internal serializer.
        """
        payload = want_bytes(self.dump_payload(obj))
        rv = self.make_signer(salt).sign(payload)
        if self.is_text_serializer:
            rv = rv.decode('utf-8')
        return rv


Instruction:
Can you tell what is the following Python 3 function doing
def dump(self, obj, f, salt=None):
        f.write(self.dumps(obj, salt))

Response: Like dumps but writes to a file.


Instruction:
Write a Python 3 script to
reverse of dumps raises BadSignature exception

Response:
def loads(self, s, salt=None):
        """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
        signature validation fails.
        """
        s = want_bytes(s)
        return self.load_payload(self.make_signer(salt).unsign(s))


Instruction:
Given the following Python 3 function, write the documentation
def _loads_unsafe_impl(self, s, salt, load_kwargs=None,
                           load_payload_kwargs=None):
        """Lowlevel helper function to implement :meth:`loads_unsafe` in
        serializer subclasses.
        """
        try:
            return True, self.loads(s, salt=salt, **(load_kwargs or {}))
        except BadSignature as e:
            if e.payload is None:
                return False, None
            try:
                return False, self.load_payload(e.payload,
                    **(load_payload_kwargs or {}))
            except BadPayload:
                return False, None

Response:
Lowlevel helper function to implement loads_unsafe in
            serializer subclasses.


Instruction:
Make a summary of the following Python 3 code
def load_unsafe(self, f, *args, **kwargs):
        return self.loads_unsafe(f.read(), *args, **kwargs)

Response: Like loads_unsafe but loads from a file.


Instruction:
How would you implement a function in Python 3 that
gives a string s returns a base64 - encoded payload and a timestamp.

Response:
def loads(self, s, max_age=None, return_timestamp=False, salt=None):
        """Reverse of :meth:`dumps`, raises :exc:`BadSignature` if the
        signature validation fails.  If a `max_age` is provided it will
        ensure the signature is not older than that time in seconds.  In
        case the signature is outdated, :exc:`SignatureExpired` is raised
        which is a subclass of :exc:`BadSignature`.  All arguments are
        forwarded to the signer's :meth:`~TimestampSigner.unsign` method.
        """
        base64d, timestamp = self.make_signer(salt) \
            .unsign(s, max_age, return_timestamp=True)
        payload = self.load_payload(base64d)
        if return_timestamp:
            return payload, timestamp
        return payload


Instruction:
Can you tell what is the following Python 3 function doing
def dumps(self, obj, salt=None, header_fields=None):
        header = self.make_header(header_fields)
        signer = self.make_signer(salt, self.algorithm)
        return signer.sign(self.dump_payload(header, obj))

Response: Like : meth : ~Serializer. dumps but creates a JSON Web Signature.


Instruction:
Can you write a function in Python 3 where it
reverses of :meth:`dumps`. If requested via `return_header` it will return a tuple of payload and header.

Response:
def loads(self, s, salt=None, return_header=False):
        """Reverse of :meth:`dumps`. If requested via `return_header` it will
        return a tuple of payload and header.
        """
        payload, header = self.load_payload(
            self.make_signer(salt, self.algorithm).unsign(want_bytes(s)),
            return_header=True)
        if header.get('alg') != self.algorithm_name:
            raise BadHeader('Algorithm mismatch', header=header,
                            payload=payload)
        if return_header:
            return payload, header
        return payload


Instruction:
Given the following Python 3 function, write the documentation
def server_error(request_id, error):

    response = {
        'jsonrpc': '2.0',
        'id': request_id,
        'error': {
            'code': -32000,
            'message': 'Server error',
            'data': repr(error),
        },
    }
    raise ServiceException(500, dumps(response))

Response: JSON - RPC server error.


Instruction:
Explain what the following Python 3 code does
def findall(dir = os.curdir):
    all_files = []
    for base, dirs, files in os.walk(dir, followlinks=True):
        if base==os.curdir or base.startswith(os.curdir+os.sep):
            base = base[2:]
        if base:
            files = [os.path.join(base, f) for f in files]
        all_files.extend(filter(os.path.isfile, files))
    return all_files

Response: Find all files under dir and return the list of full filenames.


Instruction:
How would you code a function in Python 3 to
return a list of Python packages found within a directory where.

Response:
def find(cls, where='.', exclude=(), include=('*',)):
        """Return a list all Python packages found within directory 'where'

        'where' should be supplied as a "cross-platform" (i.e. URL-style)
        path; it will be converted to the appropriate local path syntax.
        'exclude' is a sequence of package names to exclude; '*' can be used
        as a wildcard in the names, such that 'foo.*' will exclude all
        subpackages of 'foo' (but not 'foo' itself).

        'include' is a sequence of package names to include.  If it's
        specified, only the named packages will be included.  If it's not
        specified, all found packages will be included.  'include' can contain
        shell style wildcard patterns just like 'exclude'.

        The list of included packages is built up first and then any
        explicitly excluded packages are removed from it.
        """
        out = cls._find_packages_iter(convert_path(where))
        out = cls.require_parents(out)
        includes = cls._build_filter(*include)
        excludes = cls._build_filter('ez_setup', '*__pycache__', *exclude)
        out = filter(includes, out)
        out = filterfalse(excludes, out)
        return list(out)


Instruction:
Create a Python 3 function to
yield the packages that are not included in the list of packages.

Response:
def require_parents(packages):
        """
        Exclude any apparent package that apparently doesn't include its
        parent.

        For example, exclude 'foo.bar' if 'foo' is not present.
        """
        found = []
        for pkg in packages:
            base, sep, child = pkg.rpartition('.')
            if base and base not in found:
                continue
            found.append(pkg)
            yield pkg


Instruction:
Can you generate the documentation for the following Python 3 function
def _all_dirs(base_path):
        for root, dirs, files in os.walk(base_path, followlinks=True):
            for dir in dirs:
                yield os.path.relpath(os.path.join(root, dir), base_path)

Response: Return all dirs in base_path relative to base_path


Instruction:
Write a Python 3 script for
verifying our vary headers match and construct a real urllib3 HTTPResponse object.

Response:
def prepare_response(self, request, cached):
        """Verify our vary headers match and construct a real urllib3
        HTTPResponse object.
        """
        # Special case the '*' Vary value as it means we cannot actually
        # determine if the cached response is suitable for this request.
        if "*" in cached.get("vary", {}):
            return

        # Ensure that the Vary headers for the cached response match our
        # request
        for header, value in cached.get("vary", {}).items():
            if request.headers.get(header, None) != value:
                return

        body_raw = cached["response"].pop("body")

        try:
            body = io.BytesIO(body_raw)
        except TypeError:
            # This can happen if cachecontrol serialized to v1 format (pickle)
            # using Python 2. A Python 2 str(byte string) will be unpickled as
            # a Python 3 str (unicode string), which will cause the above to
            # fail with:
            #
            #     TypeError: 'str' does not support the buffer interface
            body = io.BytesIO(body_raw.encode('utf8'))

        return HTTPResponse(
            body=body,
            preload_content=False,
            **cached["response"]
        )


Instruction:
How would you code a function in Python 3 to
generate a public or private key pair.

Response:
def keygen(get_keyring=get_keyring):
    """Generate a public/private key pair."""
    WheelKeys, keyring = get_keyring()

    ed25519ll = signatures.get_ed25519ll()

    wk = WheelKeys().load()

    keypair = ed25519ll.crypto_sign_keypair()
    vk = native(urlsafe_b64encode(keypair.vk))
    sk = native(urlsafe_b64encode(keypair.sk))
    kr = keyring.get_keyring()
    kr.set_password("wheel", vk, sk)
    sys.stdout.write("Created Ed25519 keypair with vk={0}\n".format(vk))
    if isinstance(kr, keyring.backends.file.BaseKeyring):
        sys.stdout.write("in {0}\n".format(kr.file_path))
    else:
        sys.stdout.write("in %r\n" % kr.__class__)

    sk2 = kr.get_password('wheel', vk)
    if sk2 != sk:
        raise WheelError("Keyring is broken. Could not retrieve secret key.")

    sys.stdout.write("Trusting {0} to sign and verify all packages.\n".format(vk))
    wk.add_signer('+', vk)
    wk.trust('+', vk)
    wk.save()


Instruction:
Can you generate the documentation for the following Python 3 function
def unsign(wheelfile):
    import wheel.install
    vzf = wheel.install.VerifyingZipFile(wheelfile, "a")
    info = vzf.infolist()
    if not (len(info) and info[-1].filename.endswith('/RECORD.jws')):
        raise WheelError("RECORD.jws not found at end of archive.")
    vzf.pop()
    vzf.close()

Response: Unsign a WHEEL file.


Instruction:
Can you implement a function in Python 3 that
verifies a wheel. The signature will be verified for internal consistency ONLY and printed. Wheel's own unpack/install commands verify the manifest against the signature and file contents.

Response:
def verify(wheelfile):
    """Verify a wheel.

    The signature will be verified for internal consistency ONLY and printed.
    Wheel's own unpack/install commands verify the manifest against the
    signature and file contents.
    """
    wf = WheelFile(wheelfile)
    sig_name = wf.distinfo_name + '/RECORD.jws'
    sig = json.loads(native(wf.zipfile.open(sig_name).read()))
    verified = signatures.verify(sig)
    sys.stderr.write("Signatures are internally consistent.\n")
    sys.stdout.write(json.dumps(verified, indent=2))
    sys.stdout.write('\n')


Instruction:
Implement a function in Python 3 to
unpack a wheel. Wheel content will be unpacked to {dest}/{name}-{ver}, where {name} is the package name and {ver} its version. :param wheelfile: The path to the wheel. :param dest: Destination directory (default to current directory).

Response:
def unpack(wheelfile, dest='.'):
    """Unpack a wheel.

    Wheel content will be unpacked to {dest}/{name}-{ver}, where {name}
    is the package name and {ver} its version.

    :param wheelfile: The path to the wheel.
    :param dest: Destination directory (default to current directory).
    """
    wf = WheelFile(wheelfile)
    namever = wf.parsed_filename.group('namever')
    destination = os.path.join(dest, namever)
    sys.stderr.write("Unpacking to: %s\n" % (destination))
    wf.zipfile.extractall(destination)
    wf.zipfile.close()


Instruction:
Make a summary of the following Python 3 code
def install(requirements, requirements_file=None,
            wheel_dirs=None, force=False, list_files=False,
            dry_run=False):
    """Install wheels.

    :param requirements: A list of requirements or wheel files to install.
    :param requirements_file: A file containing requirements to install.
    :param wheel_dirs: A list of directories to search for wheels.
    :param force: Install a wheel file even if it is not compatible.
    :param list_files: Only list the files to install, don't install them.
    :param dry_run: Do everything but the actual install.
    """

    # If no wheel directories specified, use the WHEELPATH environment
    # variable, or the current directory if that is not set.
    if not wheel_dirs:
        wheelpath = os.getenv("WHEELPATH")
        if wheelpath:
            wheel_dirs = wheelpath.split(os.pathsep)
        else:
            wheel_dirs = [ os.path.curdir ]

    # Get a list of all valid wheels in wheel_dirs
    all_wheels = []
    for d in wheel_dirs:
        for w in os.listdir(d):
            if w.endswith('.whl'):
                wf = WheelFile(os.path.join(d, w))
                if wf.compatible:
                    all_wheels.append(wf)

    # If there is a requirements file, add it to the list of requirements
    if requirements_file:
        # If the file doesn't exist, search for it in wheel_dirs
        # This allows standard requirements files to be stored with the
        # wheels.
        if not os.path.exists(requirements_file):
            for d in wheel_dirs:
                name = os.path.join(d, requirements_file)
                if os.path.exists(name):
                    requirements_file = name
                    break

        with open(requirements_file) as fd:
            requirements.extend(fd)

    to_install = []
    for req in requirements:
        if req.endswith('.whl'):
            # Explicitly specified wheel filename
            if os.path.exists(req):
                wf = WheelFile(req)
                if wf.compatible or force:
                    to_install.append(wf)
                else:
                    msg = ("{0} is not compatible with this Python. "
                           "--force to install anyway.".format(req))
                    raise WheelError(msg)
            else:
                # We could search on wheel_dirs, but it's probably OK to
                # assume the user has made an error.
                raise WheelError("No such wheel file: {}".format(req))
            continue

        # We have a requirement spec
        # If we don't have pkg_resources, this will raise an exception
        matches = matches_requirement(req, all_wheels)
        if not matches:
            raise WheelError("No match for requirement {}".format(req))
        to_install.append(max(matches))

    # We now have a list of wheels to install
    if list_files:
        sys.stdout.write("Installing:\n")

    if dry_run:
        return

    for wf in to_install:
        if list_files:
            sys.stdout.write("    {0}\n".format(wf.filename))
            continue
        wf.install(force=force)
        wf.zipfile.close()

Response: Installs the given requirements or wheel files into the list of wheels.


Instruction:
Write a Python 3 script to
install the entry_points console_scripts for the named distributions.

Response:
def install_scripts(distributions):
    """
    Regenerate the entry_points console_scripts for the named distribution.
    """
    try:
        from setuptools.command import easy_install
        import pkg_resources
    except ImportError:
        raise RuntimeError("'wheel install_scripts' needs setuptools.")

    for dist in distributions:
        pkg_resources_dist = pkg_resources.get_distribution(dist)
        install = wheel.paths.get_install_command(dist)
        command = easy_install.easy_install(install.distribution)
        command.args = ['wheel'] # dummy argument
        command.finalize_options()
        command.install_egg_scripts(pkg_resources_dist)


Instruction:
How would you explain what the following Python 3 function does
def arrange_all(self):
        import godot.dot_data_parser

        parser = godot.dot_data_parser.GodotDataParser()

        xdot_data = self.create( format = "xdot" )
#        print "GRAPH DOT:\n", str( self )
#        print "XDOT DATA:\n", xdot_data

        parser.dotparser.parseWithTabs()
        ndata = xdot_data.replace( "\\\n", "" )
        tokens = parser.dotparser.parseString( ndata )[0]
        parser.build_graph( graph=self, tokens=tokens[3] )

        self.redraw_canvas()

Response:
Set for the _draw_ and _ldraw_ attributes for each of the graph
            sub - elements by processing the xdot format of the graph and building the graph.


Instruction:
Can you write a function in Python 3 where it
redraws the canvas of the current node and edge graph.

Response:
def redraw_canvas(self):
        """ Parses the Xdot attributes of all graph components and adds
            the components to a new canvas.
        """
        from xdot_parser import XdotAttrParser

        xdot_parser = XdotAttrParser()
        canvas = self._component_default()

        for node in self.nodes:
            components = xdot_parser.parse_xdot_data( node._draw_ )
            canvas.add( *components )

            components = xdot_parser.parse_xdot_data( node._ldraw_ )
            canvas.add( *components )

        for edge in self.edges:
            components = xdot_parser.parse_xdot_data( edge._draw_ )
            canvas.add( *components )
            components = xdot_parser.parse_xdot_data( edge._ldraw_ )
            canvas.add( *components )
            components = xdot_parser.parse_xdot_data( edge._hdraw_ )
            canvas.add( *components )
            components = xdot_parser.parse_xdot_data( edge._tdraw_ )
            canvas.add( *components )
            components = xdot_parser.parse_xdot_data( edge._hldraw_ )
            canvas.add( *components )
            components = xdot_parser.parse_xdot_data( edge._tldraw_ )
            canvas.add( *components )

        self.component = canvas
        self.vp.request_redraw()


Instruction:
Make a summary of the following Python 3 code
def get_node(self, ID):
        node = super(Graph, self).get_node(ID)
        if node is not None:
            return node

        for graph in self.all_graphs:
            for each_node in graph.nodes:
                if each_node.ID == ID:
                    return each_node
        else:
            return None

Response: Returns a node given an ID or None if no such node exists.


Instruction:
How would you code a function in Python 3 to
return the maximum number of nodes in the current state.

Response:
def _maxiter_default(self):
        """ Trait initialiser.
        """
        mode = self.mode
        if mode == "KK":
            return 100 * len(self.nodes)
        elif mode == "major":
            return 200
        else:
            return 600


Instruction:
How would you code a function in Python 3 to
set the connection string for all edges.

Response:
def _directed_changed(self, new):
        """ Sets the connection string for all edges.
        """
        if new:
            conn = "->"
        else:
            conn = "--"

        for edge in [e for g in self.all_graphs for e in g.edges]:
            edge.conn = conn


Instruction:
Write a Python 3 function that can
maintain each branch s list of available nodes in order that they can move themselves.

Response:
def _on_nodes(self):
        """ Maintains each branch's list of available nodes in order that they
            may move themselves (InstanceEditor values).
        """
        all_graphs = self.all_graphs
        all_nodes = [n for g in all_graphs for n in g.nodes]

        for graph in all_graphs:
            for edge in graph.edges:
                edge._nodes = all_nodes


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _on_edges(self, object, name, old, new):
        if name == "edges_items":
            edges = new.added
        elif name == "edges":
            edges = new
        else:
            edges = []

        all_nodes = [n for g in self.all_graphs for n in g.nodes]

        for each_edge in edges:
            # Ensure the edge's nodes exist in the graph.
            if each_edge.tail_node not in all_nodes:
                object.nodes.append( each_edge.tail_node )

            if each_edge.head_node not in all_nodes:
                object.nodes.append( each_edge.head_node )

            # Initialise the edge's list of available nodes.
            each_edge._nodes = all_nodes

Response: Handles the list of edges for any graph changing.


Instruction:
Explain what the following Python 3 code does
def _viewport_default(self):

        viewport = Viewport(component=self.canvas, enable_zoom=True)
        viewport.tools.append(ViewportPanTool(viewport))
        return viewport

Response: Create a default Viewport instance.


Instruction:
How would you implement a function in Python 3 that
handles the component being changed.

Response:
def _component_changed(self, old, new):
        """ Handles the component being changed.
        """
        canvas = self.canvas
        if old is not None:
            canvas.remove(old)
        if new is not None:
            canvas.add(new)


Instruction:
Make a summary of the following Python 3 code
def normal_left_dclick(self, event):
        x = event.x
        y = event.y

        # First determine what component or components we are going to hittest
        # on.  If our component is a container, then we add its non-container
        # components to the list of candidates.
#        candidates = []
        component = self.component
#        if isinstance(component, Container):
#            candidates = get_nested_components(self.component)
#        else:
#            # We don't support clicking on unrecognized components
#            return
#
#        # Hittest against all the candidate and take the first one
#        item = None
#        for candidate, offset in candidates:
#            if candidate.is_in(x-offset[0], y-offset[1]):
#                item = candidate
#                break

        if hasattr(component, "element"):
            if component.element is not None:
                component.active_tool = self
                component.element.edit_traits(kind="livemodal")
                event.handled = True
                component.active_tool = None
                component.request_redraw()
        return

Response: Handles the left mouse button being double - clicked when the tool is in the normal state.


Instruction:
How would you code a function in Python 3 to
return a default canvas for this instance.

Response:
def _diagram_canvas_default(self):
        """ Trait initialiser """

        canvas = Canvas()

        for tool in self.tools:
            canvas.tools.append(tool(canvas))

        return canvas


Instruction:
Create a Python 3 function for
creating a Viewport object with default view position and pan tools.

Response:
def _viewport_default(self):
        """ Trait initialiser """

        vp = Viewport(component=self.diagram_canvas, enable_zoom=True)
        vp.view_position = [0,0]
        vp.tools.append(ViewportPanTool(vp))
        return vp


Instruction:
Can you tell what is the following Python 3 function doing
def _diagram_canvas_changed(self, new):

        logger.debug("Diagram canvas changed!")
        canvas = self.diagram_canvas

        for tool in self.tools:
            if canvas is not None:
                print "Adding tool: %s" % tool
                canvas.tools.append(tool(canvas))

Response: Handles the diagram canvas being changed


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

        logger.debug("Clearing the diagram canvas!")
        old_canvas = self.diagram_canvas

#        logger.debug("Canvas components: %s" % canvas.components)
#        for component in canvas.components:
#            canvas.remove(component)
#        logger.debug("Canvas components: %s" % canvas.components)
#        for component in canvas.components:
#            canvas.remove(component)
#        logger.debug("Canvas components: %s" % canvas.components)
#        canvas.request_redraw()

        new_canvas = Canvas()
        new_canvas.copy_traits(old_canvas, ["bgcolor", "draw_axes"])
        self.diagram_canvas = new_canvas

        self.viewport.component=new_canvas
        self.viewport.request_redraw()

        return

Response: Removes all components from the diagram canvas


Instruction:
Write a Python 3 function for
handling the domain model changes for the diagram.

Response:
def _domain_model_changed_for_diagram(self, obj, name, old, new):
        """ Handles the domain model changing """

        if old is not None:
            self.unmap_model(old)
        if new is not None:
            self.map_model(new)


Instruction:
Implement a function in Python 3 to
map a domain model to the diagram.

Response:
def map_model(self, new):
        """ Maps a domain model to the diagram """

        logger.debug("Mapping the domain model!")
        dot = Dot()

        self.diagram.clear_canvas()

        for node_mapping in self.nodes:
            ct = node_mapping.containment_trait
            logger.debug("Mapping elements contained by the '%s' trait" % ct)
            if hasattr(new, ct):
                elements = getattr(new, ct)
                logger.debug("%d element(s) found" % len(elements))
                for element in elements:
                    pydot_node = Node(str(id(element)))
                    dot_attrs = node_mapping.dot_node
                    if dot_attrs is not None:
                        self._style_node(pydot_node, dot_attrs)
                    dot.add_node(pydot_node)

                    new.on_trait_change(self.map_element, ct+"_items")

        logger.debug("Retrieving xdot data and forming pydot graph!")
        xdot = graph_from_dot_data(dot.create(self.program, "xdot"))
        parser = XDotParser()

        for node in xdot.get_node_list():
            diagram_node = parser.parse_node(node)
            logger.debug(
                "Parsed node [%s] and received diagram node [%s]" %
                (node, diagram_node)
            )
            if diagram_node is not None:
                for node_mapping in self.nodes: # FIXME: slow
                    ct = node_mapping.containment_trait
                    for element in getattr(new, ct):
                        if str(id(element)) == diagram_node.dot_node.get_name():
                            logger.debug(
                                "Referencing element [%s] from diagram node [%s]" %
                                (element, diagram_node)
                            )
                            diagram_node.element = element
                            break

                    # Tools
                    if isinstance(diagram_node.element, node_mapping.element):
                        for tool in node_mapping.tools:
                            logger.debug(
                                "Adding tool [%s] to diagram node [%s]" %
                                (tool, diagram_node)
                            )
                            diagram_node.tools.append(tool(diagram_node))

                else:
                    if diagram_node.element is None:
                        logger.warning("Diagram node not referenced to element")

                self.diagram.diagram_canvas.add(diagram_node)

        del parser


Instruction:
Can you generate a brief explanation for the following Python 3 code
def unmap_model(self, old):

        for node_mapping in self.nodes:
            ct = node_mapping.containment_trait
            if hasattr(old, ct):
                old_elements = getattr(old, ct)
                for old_element in old_elements:
                    old.on_trait_change(
                        self.map_element, ct+"_items", remove=True
                    )

Response: Removes listeners from a domain model


Instruction:
Create a Python 3 function for
handling mapping elements to diagram components

Response:
def map_element(self, obj, name, event):
        """ Handles mapping elements to diagram components """

        canvas = self.diagram.diagram_canvas
        parser = XDotParser()

        for element in event.added:
            logger.debug("Mapping new element [%s] to diagram node" % element)
            for node_mapping in self.nodes:
                ct = name[:-6] #strip '_items'
                if node_mapping.containment_trait == ct:
                    dot_attrs = node_mapping.dot_node
                    dot = Dot()
                    graph_node = Node(str(id(element)))
                    self._style_node(graph_node, dot_attrs)
                    dot.add_node(graph_node)
                    xdot = graph_from_dot_data(dot.create(self.program,"xdot"))
                    diagram_nodes = parser.parse_nodes(xdot)#.get_node_list())
                    for dn in diagram_nodes:
                        if dn is not None:
                            dn.element = element
                            # Tools
                            for tool in node_mapping.tools:
                                dn.tools.append(tool(dn))

                            canvas.add(dn)
                            canvas.request_redraw()

        for element in event.removed:
            logger.debug("Unmapping element [%s] from diagram" % element)
            for component in canvas.components:
                if element == component.element:
                    canvas.remove(component)
                    canvas.request_redraw()
                    break


Instruction:
Write a Python 3 script to
parse xdot data and returns the associated components.

Response:
def parse_xdot_data(self, data):
        """ Parses xdot data and returns the associated components. """

        parser = self.parser
#        if pyparsing_version >= "1.2":
#            parser.parseWithTabs()
        if data:
            return parser.parseString(data)
        else:
            return []


Instruction:
How would you code a function in Python 3 to
define the parser for the internal parser.

Response:
def define_parser(self):
        """ Defines xdot grammar.

        @see: http://graphviz.org/doc/info/output.html#d:xdot """

        # Common constructs.
        point = Group(integer.setResultsName("x") +
                      integer.setResultsName("y"))
        n_points = (integer.setResultsName("n") +
            OneOrMore(point).setResultsName("points"))
        n_bytes = Suppress(integer) + Suppress(minus) + \
            Word(printables).setResultsName("b")
        justify = ToInteger(
            Literal("-1") | Literal("0") | Literal("1")
        ).setResultsName("j")

        # Attributes ----------------------------------------------------------

        # Set fill color. The color value consists of the n bytes following
        # the '-'.
        fill = (Literal("C").suppress() + Suppress(integer) + Suppress(minus) +
            colour.setResultsName("color")).setResultsName("fill")

        # Set pen color. The color value consists of the n bytes following '-'.
        stroke = (Literal("c").suppress() + Suppress(integer) +
            Suppress(minus) + colour.setResultsName("color")
        ).setResultsName("stroke")

        # Set font. The font size is s points. The font name consists of the
        # n bytes following '-'.
        font = (Literal("F").suppress() + real.setResultsName("s") +
            n_bytes).setResultsName("font")

        # Set style attribute. The style value consists of the n bytes
        # following '-'. The syntax of the value is the same as specified for
        # a styleItem in style.
        style = (Literal("S").suppress() + n_bytes).setResultsName("style")

        # Shapes --------------------------------------------------------------

        # Filled ellipse ((x-x0)/w)^2 + ((y-y0)/h)^2 = 1
        filled_ellipse = (Literal("E").suppress() +
            integer.setResultsName("x0") + integer.setResultsName("y0") +
            integer.setResultsName("w") + integer.setResultsName("h")
        ).setResultsName("filled_ellipse")

        # Unfilled ellipse ((x-x0)/w)^2 + ((y-y0)/h)^2 = 1
        ellipse = (Literal("e").suppress() +
            integer.setResultsName("x0") + integer.setResultsName("y0") +
            integer.setResultsName("w") + integer.setResultsName("h")
        ).setResultsName("ellipse")

        # Filled polygon using the given n points.
        filled_polygon = (Literal("P").suppress() +
            n_points).setResultsName("filled_polygon")

        # Unfilled polygon using the given n points.
        polygon = (Literal("p").suppress() +
            n_points).setResultsName("polygon")

        # Polyline using the given n points.
        polyline = (Literal("L").suppress() +
            n_points).setResultsName("polyline")

        # B-spline using the given n control points.
        bspline = (Literal("B").suppress() +
            n_points).setResultsName("bspline")

        # Filled B-spline using the given n control points.
        filled_bspline = (Literal("b").suppress() +
            n_points).setResultsName("filled_bspline")

        # Text drawn using the baseline point (x,y). The text consists of the
        # n bytes following '-'. The text should be left-aligned (centered,
        # right-aligned) on the point if j is -1 (0, 1), respectively. The
        # value w gives the width of the text as computed by the library.
        text = (Literal("T").suppress() + integer.setResultsName("x") +
            integer.setResultsName("y") + justify +
            integer.setResultsName("w") + n_bytes).setResultsName("text")

        # Externally-specified image drawn in the box with lower left corner
        # (x,y) and upper right corner (x+w,y+h). The name of the image
        # consists of the n bytes following '-'. This is usually a bitmap
        # image. Note that the image size, even when converted from pixels to
        # points, might be different from the required size (w,h). It is
        # assumed the renderer will perform the necessary scaling.
        image = (Literal("I").suppress() + integer.setResultsName("x") +
            integer.setResultsName("y") + integer.setResultsName("w") +
            integer.setResultsName("h") + n_bytes).setResultsName("image")

        # The value of the drawing attributes consists of the concatenation of
        # some (multi-)set of the 13 rendering or attribute operations.
        value = (Optional(quote).suppress() + OneOrMore(filled_ellipse |
            ellipse | filled_polygon | polygon | polyline | bspline |
            filled_bspline | text | fill | stroke | font | style | image) +
            Optional(quote).suppress()).setResultsName("value")

        # Drawing operation.
#        draw_ = Literal("_draw_") + Suppress(equals) + value
#        # Label drawing.
#        ldraw_ = Literal("_ldraw_") + Suppress(equals) + value
#        # Edge head arrowhead drawing.
#        hdraw_ = Literal("_hdraw_") + Suppress(equals) + value
#        # Edge tail arrowhead drawing.
#        tdraw_ = Literal("_tdraw_") + Suppress(equals) + value
#        # Edge head label drawing.
#        hldraw_ = Literal("_hldraw_") + Suppress(equals) + value
#        # Edge tail label drawing.
#        tldraw_ = Literal("_tldraw_") + Suppress(equals) + value

        # Parse actions.
#        n_points.setParseAction(self.proc_points)

        # Attribute parse actions.
        fill.setParseAction(self.proc_fill_color)
        stroke.setParseAction(self.proc_stroke_color)
        font.setParseAction(self.proc_font)
        style.setParseAction(self.proc_style)

        # Shape parse actions.
        filled_ellipse.setParseAction(self.proc_filled_ellipse)
        ellipse.setParseAction(self.proc_unfilled_ellipse)
        filled_polygon.setParseAction(self.proc_filled_polygon)
        polygon.setParseAction(self.proc_unfilled_polygon)
        polyline.setParseAction(self.proc_polyline)
        bspline.setParseAction(self.proc_unfilled_bspline)
        filled_bspline.setParseAction(self.proc_filled_bspline)
        text.setParseAction(self.proc_text)
        image.setParseAction(self.proc_image)

        return value


Instruction:
Given the following Python 3 function, write the documentation
def _proc_color(self, tokens):

        keys = tokens.keys()
        if "red" in keys: # RGB(A)
            rr, gg, bb = tokens["red"], tokens["green"], tokens["blue"]
            hex2int = lambda h: int(h, 16)
            if "alpha" in keys:
                a = tokens["alpha"]
                c = str((hex2int(rr), hex2int(gg), hex2int(bb), hex2int(a)))
            else:
                c = str((hex2int(rr), hex2int(gg), hex2int(bb)))
        elif "hue" in keys: # HSV
            r, g, b = hsv_to_rgb(tokens["hue"],
                                 tokens["saturation"],
                                 tokens["value"])
            c = str((int(r*255), int(g*255), int(b*255)))
        else:
            c = tokens["color"]

        return c

Response: Process the color traits of a Pen instance.


Instruction:
How would you implement a function in Python 3 that
returns the components of an ellipse.

Response:
def _proc_ellipse(self, tokens, filled):
        """ Returns the components of an ellipse. """

        component = Ellipse(pen=self.pen,
                            x_origin=tokens["x0"],
                            y_origin=tokens["y0"],
                            e_width=tokens["w"],
                            e_height=tokens["h"],
                            filled=filled)

        return component


Instruction:
Here you have a function in Python 3, explain what it does
def _proc_polygon(self, tokens, filled):

        pts = [(p["x"], p["y"]) for p in tokens["points"]]
        component = Polygon(pen=self.pen, points=pts, filled=filled)

        return component

Response: Returns the components of a polygon.


Instruction:
Write a Python 3 function for
returning the components of a polyline.

Response:
def proc_polyline(self, tokens):
        """ Returns the components of a polyline. """

        pts = [(p["x"], p["y"]) for p in tokens["points"]]
        component = Polyline(pen=self.pen, points=pts)

        return component


Instruction:
Explain what the following Python 3 code does
def _proc_bspline(self, tokens, filled):

        pts = [(p["x"], p["y"]) for p in tokens["points"]]
        component = BSpline(pen=self.pen, points=pts, filled=filled)

        return component

Response: Processes a B - spline.


Instruction:
How would you explain what the following Python 3 function does
def proc_image(self, tokens):

        print "IMAGE:", tokens, tokens.asList(), tokens.keys()

        raise NotImplementedError

Response: Returns the components of an image.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def render_grid_file(context, f):

	f.seek(0)  # Ensure we are reading from the beginning.
	response = context.response  # Frequently accessed, so made local.  Useless optimization on Pypy.

	if __debug__:  # We add some useful diagnostic information in development, omitting from production due to sec.
		response.headers['Grid-ID'] = str(f._id)  # The GridFS file ID.
		log.debug("Serving GridFS file.", extra=dict(
				identifier = str(f._id),
				filename = f.filename,
				length = f.length,
				mimetype = f.content_type
			))

	response.conditional_response = True
	response.accept_ranges = 'bytes'  # We allow returns of partial content, if requested.
	response.content_type = f.content_type  # Direct transfer of GridFS-stored MIME type.
	response.content_length = f.length  # The length was pre-computed when the file was uploaded.
	response.content_md5 = response.etag = f.md5  # As was the MD5, used for simple integrity testing.
	response.last_modified = f.metadata.get('modified', None)  # Optional additional metadata.
	response.content_disposition = 'attachment; filename=' + f.name  # Preserve the filename through to the client.

	# Being asked for a range or not determines the streaming style used.
	if context.request.if_range.match_response(response):
		response.body_file = f  # Support seek + limited read.
	else:
		response.app_iter = iter(f)  # Assign the body as a streaming, chunked iterator.

	return True

Response: Allow direct use of GridOut GridFS file wrappers as endpoint responses.


Instruction:
Given the following Python 3 function, write the documentation
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"):

        x_origin = self.x_origin
        y_origin = self.y_origin

        gc.save_state()
        try:
#            self._draw_bounds(gc)
            gc.begin_path()
            gc.translate_ctm(x_origin, y_origin)
            gc.scale_ctm(self.e_width, self.e_height)
            gc.arc(0.0, 0.0, 1.0, 0, 2.0*pi)
            gc.close_path()

            # Draw stroke at same scale as graphics context
#            ctm = gc.get_ctm()
#            if hasattr(ctm, "__len__") and len(ctm) == 6:
#                scale = sqrt( (ctm[0]+ctm[1]) * (ctm[0]+ctm[1]) / 2.0 + \
#                              (ctm[2]+ctm[3]) * (ctm[2]+ctm[3]) / 2.0 )
#            elif hasattr(gc, "get_ctm_scale"):
#                scale = gc.get_ctm_scale()
#            else:
#                raise RuntimeError("Unable to get scale from GC.")

            gc.set_line_width(self.pen.line_width)
            gc.set_stroke_color(self.pen.color_)

            if self.filled:
                gc.set_fill_color(self.pen.fill_color_)
                gc.draw_path(FILL_STROKE)
            else:
                gc.stroke_path()
        finally:
            gc.restore_state()

Response: Draws the mainlayer of the current object.


Instruction:
Can you write a function in Python 3 where it
tests if the point is within this ellipse

Response:
def is_in(self, point_x, point_y):
        """ Test if the point is within this ellipse """

        x = self.x_origin
        y = self.y_origin
        a = self.e_width#/2 # FIXME: Why divide by two
        b = self.e_height#/2

        return ((point_x-x)**2/(a**2)) + ((point_y-y)**2/(b**2)) < 1.0


Instruction:
Make a summary of the following Python 3 code
def _draw_bounds(self, gc):

        dx, dy = self.bounds
        x, y = self.position
        gc.rect(x, y, dx, dy)
        gc.stroke_path()

Response: Draw the component bounds for testing purposes


Instruction:
Can you tell what is the following Python 3 function doing
def polar(x, y, deg=0):        # radian if deg=0; degree if deg=1

    if deg:
        return hypot(x, y), 180.0 * atan2(y, x) / pi
    else:
        return hypot(x, y), atan2(y, x)

Response: Convert from rectangular x y to polar


Instruction:
Can you tell what is the following Python 3 function doing
def cubic(a, b, c, d=None):

    if d: # (ax^3 + bx^2 + cx + d = 0)
        a, b, c = b / float(a), c / float(a), d / float(a)

    t = a / 3.0
    p, q = b - 3 * t**2, c - b * t + 2 * t**3
    u, v = quadratic(q, -(p/3.0)**3)

    if type(u) == type(0j): # complex cubic root
        r, w = polar(u.real, u.imag)
        y1 = 2 * cbrt(r) * cos(w / 3.0)
    else: # real root
        y1 = cbrt(u) + cbrt(v)
    y2, y3 = quadratic(y1, p + y1**2)

    return y1 - t, y2 - t, y3 - t

Response: This function calculates the cubic root of a set of roots.


Instruction:
How would you explain what the following Python 3 function does
def start(self, context):

		if __debug__:
			log.info("Connecting SQLAlchemy database layer.", extra=dict(
					uri = redact_uri(self.uri),
					config = self.config,
					alias = self.alias,
				))

		# Construct the engine.
		engine = self.engine = create_engine(self.uri, **self.config)

		# Construct the session factory.
		self.Session = scoped_session(sessionmaker(bind=engine))

		# Test the connection.
		engine.connect().close()

		# Assign the engine to our database alias.
		context.db[self.alias] = engine

Response: Construct the SQLAlchemy engine and session factory.


Instruction:
Can you implement a function in Python 3 that
parses the dot_code string and replaces the existing model with the graph.

Response:
def _parse_dot_code_fired(self):
        """ Parses the dot_code string and replaces the existing model.
        """
        parser = GodotDataParser()
        graph  = parser.parse_dot_data(self.dot_code)
        if graph is not None:
            self.model = graph


Instruction:
Implement a function in Python 3 to
handle the new Graph action.

Response:
def new_model(self, info):
        """ Handles the new Graph action. """

        if info.initialized:
            retval = confirm(parent  = info.ui.control,
                             message = "Replace existing graph?",
                             title   = "New Graph",
                             default = YES)
            if retval == YES:
                self.model = Graph()


Instruction:
Can you tell what is the following Python 3 function doing
def open_file(self, info):

        if not info.initialized: return # Escape.

#        retval = self.edit_traits(parent=info.ui.control, view="file_view")

        dlg = FileDialog( action = "open",
            wildcard = "Graphviz Files (*.dot, *.xdot, *.txt)|"
                "*.dot;*.xdot;*.txt|Dot Files (*.dot)|*.dot|"
                "All Files (*.*)|*.*|")

        if dlg.open() == OK:
            parser = GodotDataParser()
            model = parser.parse_dot_file(dlg.path)
            if model is not None:
                self.model = model
            else:
                print "error parsing: %s" % dlg.path

            self.save_file = dlg.path

        del dlg

Response: Handles the open action.


Instruction:
Write a Python 3 script for
saving the current model to the last file.

Response:
def save(self, info):
        """ Handles saving the current model to the last file.
        """
        save_file = self.save_file

        if not isfile(save_file):
            self.save_as(info)
        else:
            fd = None
            try:
                fd = open(save_file, "wb")
                dot_code = str(self.model)
                fd.write(dot_code)
            finally:
                if fd is not None:
                    fd.close()


Instruction:
Create a Python 3 function to
save the current model to file.

Response:
def save_as(self, info):
        """ Handles saving the current model to file.
        """
        if not info.initialized:
            return

#        retval = self.edit_traits(parent=info.ui.control, view="file_view")

        dlg = FileDialog( action = "save as",
            wildcard = "Graphviz Files (*.dot, *.xdot, *.txt)|" \
                "*.dot;*.xdot;*.txt|Dot Files (*.dot)|*.dot|" \
                "All Files (*.*)|*.*|")

        if dlg.open() == OK:
            fd = None
            try:
                fd = open(dlg.path, "wb")
                dot_code = str(self.model)
                fd.write(dot_code)

                self.save_file = dlg.path

            except:
                error(parent=info.ui.control, title="Save Error",
                      message="An error was encountered when saving\nto %s"
                      % self.file)

            finally:
                if fd is not None:
                    fd.close()

        del dlg


Instruction:
Given the following Python 3 function, write the documentation
def configure_graph(self, info):
        if info.initialized:
            self.model.edit_traits(parent=info.ui.control,
                kind="live", view=attr_view)

Response: Configures the graph of the node.


Instruction:
Write a Python 3 script to
handle display of the nodes editor.

Response:
def configure_nodes(self, info):
        """ Handles display of the nodes editor.
        """
        if info.initialized:
            self.model.edit_traits(parent=info.ui.control,
                kind="live", view=nodes_view)


Instruction:
Write a Python 3 function for
handling display of the edges editor.

Response:
def configure_edges(self, info):
        """ Handles display of the edges editor.
        """
        if info.initialized:
            self.model.edit_traits(parent=info.ui.control,
                kind="live", view=edges_view)


Instruction:
Write a Python 3 script for
handling displaying a view about Godot.

Response:
def about_godot(self, info):
        """ Handles displaying a view about Godot.
        """
        if info.initialized:
            self.edit_traits(parent=info.ui.control,
                kind="livemodal", view=about_view)


Instruction:
Explain what the following Python 3 code does
def add_node(self, info):
        if not info.initialized:
            return

        graph = self._request_graph(info.ui.control)

        if graph is None:
            return

        IDs = [v.ID for v in graph.nodes]
        node = Node(ID=make_unique_name("node", IDs))
        graph.nodes.append(node)

        retval = node.edit_traits(parent=info.ui.control, kind="livemodal")

        if not retval.result:
            graph.nodes.remove(node)

Response: Adds a Node to the graph.


Instruction:
Given the following Python 3 function, write the documentation
def add_edge(self, info):
        if not info.initialized:
            return

        graph = self._request_graph(info.ui.control)

        if graph is None:
            return

        n_nodes = len(graph.nodes)
        IDs = [v.ID for v in graph.nodes]

        if n_nodes == 0:
            tail_node = Node(ID=make_unique_name("node", IDs))
            head_name = make_unique_name("node", IDs + [tail_node.ID])
            head_node = Node(ID=head_name)
        elif n_nodes == 1:
            tail_node = graph.nodes[0]
            head_node = Node(ID=make_unique_name("node", IDs))
        else:
            tail_node = graph.nodes[0]
            head_node = graph.nodes[1]

        edge = Edge(tail_node, head_node, _nodes=graph.nodes)

        retval = edge.edit_traits(parent=info.ui.control, kind="livemodal")

        if retval.result:
            graph.edges.append(edge)

Response: Adds an edge to the graph.


Instruction:
Explain what the following Python 3 code does
def add_subgraph(self, info):
        if not info.initialized:
            return

        graph = self._request_graph(info.ui.control)

        if graph is not None:
            subgraph = Subgraph()#root=graph, parent=graph)
            retval = subgraph.edit_traits(parent = info.ui.control,
                                          kind   = "livemodal")
            if retval.result:
                graph.subgraphs.append(subgraph)

Response: Handles adding a subgraph to the main graph.


Instruction:
Make a summary of the following Python 3 code
def add_cluster(self, info):

        if not info.initialized:
            return

        graph = self._request_graph(info.ui.control)

        if graph is not None:
            cluster = Cluster()#root=graph, parent=graph)
            retval = cluster.edit_traits(parent = info.ui.control,
                                         kind   = "livemodal")
            if retval.result:
                graph.clusters.append(cluster)

Response: Handles adding a Cluster to the main graph.


Instruction:
Implement a function in Python 3 to
display a dialog for graph selection if more than one exists. Returns None if the dialog is canceled.

Response:
def _request_graph(self, parent=None):
        """ Displays a dialog for graph selection if more than one exists.
            Returns None if the dialog is canceled.
        """

        if (len(self.all_graphs) > 1) and (self.select_graph):
            retval = self.edit_traits(parent = parent,
                                      view   = "all_graphs_view")
            if not retval.result:
                return None

        if self.selected_graph is not None:
            return self.selected_graph
        else:
            return self.model


Instruction:
Explain what the following Python 3 code does
def godot_options(self, info):

        if info.initialized:
            self.edit_traits( parent = info.ui.control,
                              kind   = "livemodal",
                              view   = "options_view" )

Response: Handles the options menu.


Instruction:
How would you explain what the following Python 3 function does
def configure_dot_code(self, info):
        if not info.initialized:
            return

        self.dot_code = str(self.model)
        retval = self.edit_traits( parent = info.ui.control,
                                   kind   = "livemodal",
                                   view   = "dot_code_view" )

Response: Configures the dot code in a text editor.


Instruction:
How would you implement a function in Python 3 that
handles the user attempting to exit Godot.

Response:
def on_exit(self, info):
        """ Handles the user attempting to exit Godot.
        """
        if self.prompt_on_exit:# and (not is_ok):
            retval = confirm(parent  = info.ui.control,
                             message = "Exit Godot?",
                             title   = "Confirm exit",
                             default = YES)
            if retval == YES:
                self._on_close( info )
        else:
            self._on_close( info )


Instruction:
Can you implement a function in Python 3 that
moves components relative to their origin.

Response:
def move_to_origin(components):
    """ Components are positioned relative to their container. Use this
        method to position the bottom-left corner of the components at
        the origin.
    """
    for component in components:
        if isinstance(component, Ellipse):
            component.x_origin = component.e_width
            component.y_origin = component.e_height

        elif isinstance(component, (Polygon, BSpline)):
            min_x = min( [t[0] for t in component.points] )
            min_y = min( [t[1] for t in component.points] )

            component.points = [
                ( p[0]-min_x, p[1]-min_y ) for p in component.points
            ]

        elif isinstance(component, Text):
            font = str_to_font( str(component.pen.font) )
            component.text_x = 0#-( component.text_w / 2 )
            component.text_y = 0


Instruction:
Can you generate the documentation for the following Python 3 function
def save_to_file_like(self, flo, format=None, **kwargs):
        format = self.format if format is None else format
        save = getattr(self, "save_%s" % format, None)
        if save is None:
            raise ValueError("Unknown format '%s'." % format)
        save(flo, **kwargs)

Response: Save the object to a given file like object in the given format.


Instruction:
Write a Python 3 function for
loading the object from a given file like object with the given protocol.

Response:
def load_from_file_like(cls, flo, format=None):
        """ Load the object to a given file like object with the given
            protocol.
        """
        format = self.format if format is None else format
        load = getattr(cls, "load_%s" % format, None)
        if load is None:
            raise ValueError("Unknown format '%s'." % format)
        return load(flo)


Instruction:
Can you generate the documentation for the following Python 3 function
def save_to_file(self, filename, format=None, **kwargs):
        if format is None:
            # try to derive protocol from file extension
            format = format_from_extension(filename)
        with file(filename, 'wb') as fp:
            self.save_to_file_like(fp, format, **kwargs)

Response: Save the object to file given by filename.


Instruction:
Explain what the following Python 3 code does
def load_from_file(cls, filename, format=None):
        if format is None:
            # try to derive protocol from file extension
            format = format_from_extension(filename)
        with file(filename,'rbU') as fp:
            obj = cls.load_from_file_like(fp, format)
            obj.filename = filename
            return obj

Response: Load an instance of the class from the given file.


Instruction:
Here you have a function in Python 3, explain what it does
def Alias(name, **metadata):

    return Property(lambda obj: getattr(obj, name),
                    lambda obj, val: setattr(obj, name, val),
                    **metadata)

Response:
Syntactically concise alias trait but creates a pair of lambda
    functions for every alias you declare.


Instruction:
Can you tell what is the following Python 3 function doing
def parse(filename, encoding=None):

    with open(filename, encoding=encoding) as source:
        for line in source:
            for word in line.split():
                yield word

Response: Simple file parsing generator


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

        if self._start_words is not None:
            return self._start_words
        else:
            self._start_words = list(filter(
                lambda x: str.isupper(x[0][0]) and x[0][-1] not in ['.', '?', '!'],
                self.content.keys()
            ))
            return self._start_words

Response: Return a list of start words for the current language.


Instruction:
Can you write a function in Python 3 where it
adds a new chain to the current shelve file.

Response:
def add_chain(self, name, order):
        """
        Add chain to current shelve file

        Args:
            name: chain name
            order: markov chain order
        """

        if name not in self.chains:
            setattr(self.chains, name, MarkovChain(order=order))
        else:
            raise ValueError("Chain with this name already exists")


Instruction:
Create a Python 3 function for
removing a chain from the current shelve file.

Response:
def remove_chain(self, name):
        """
        Remove chain from current shelve file

        Args:
            name: chain name
        """

        if name in self.chains:
            delattr(self.chains, name)
        else:
            raise ValueError("Chain with this name not found")


Instruction:
How would you code a function in Python 3 to
build a markov chain from source on top of existin chain.

Response:
def build_chain(self, source, chain):
        """
        Build markov chain from source on top of existin chain

        Args:
            source: iterable which will be used to build chain
            chain: MarkovChain in currently loaded shelve file that
                   will be extended by source
        """

        for group in WalkByGroup(source, chain.order+1):
            pre = group[:-1]
            res = group[-1]

            if pre not in chain.content:
                chain.content[pre] = {res: 1}
            else:
                if res not in chain.content[pre]:
                    chain.content[pre][res] = 1
                else:
                    chain.content[pre][res] += 1

        chain.decache()