Instruction:
How would you explain what the following Python 3 function does
def subscribe(
            self, server=None, key=None, address=None, address_vassal=None,
            balancing_weight=None, balancing_algo=None, modifier=None, signing=None, check_file=None, protocol=None,
            sni_cert=None, sni_key=None, sni_client_ca=None):
        """Registers a subscription intent.

        :param str|unicode server: Subscription server address (UDP or UNIX socket).

            Examples:
                * 127.0.0.1:7171

        :param str|unicode key: Key to subscribe. Generally the domain name (+ optional '/< mountpoint>').
            Examples:
                * mydomain.it/foo
                * mydomain.it/foo/bar (requires ``mountpoints_depth=2``)
                * mydomain.it
                * ubuntu64.local:9090

        :param str|unicode|int address: Address to subscribe (the value for the key)
            or zero-based internal socket number (integer).

        :param str|unicode address: Vassal node address.

        :param int balancing_weight: Load balancing value. Default: 1.

        :param balancing_algo: Load balancing algorithm to use. See ``balancing_algorithms``
            .. note:: Since 2.1

        :param Modifier modifier: Routing modifier object. See ``.routing.modifiers``

        :param list|tuple signing:  Signing basics, expects two elements list/tuple:
            (signing_algorithm, key).

            Examples:
                * SHA1:idlessh001

        :param str|unicode check_file: If this file exists the subscription packet is sent,
            otherwise it is skipped.

        :param str|unicode protocol: the protocol to use, by default it is ``uwsgi``.
            See ``.networking.socket_types``.

            .. note:: Since 2.1

        :param str|unicode sni_cert: Certificate file to use for SNI proxy management.
            * http://uwsgi.readthedocs.io/en/latest/SNI.html#subscription-system-and-sni

        :param str|unicode sni_key: sni_key Key file to use for SNI proxy management.
            * http://uwsgi.readthedocs.io/en/latest/SNI.html#subscription-system-and-sni

        :param str|unicode sni_client_ca: Ca file to use for SNI proxy management.
            * http://uwsgi.readthedocs.io/en/latest/SNI.html#subscription-system-and-sni

        """
        # todo params: inactive (inactive slot activation)

        if not any((server, key)):
            raise ConfigurationError('Subscription requires `server` or `key` to be set.')

        address_key = 'addr'
        if isinstance(address, int):
            address_key = 'socket'

        if balancing_algo:
            backup = getattr(balancing_algo, 'backup_level', None)

        if signing:
            signing = ':'.join(signing)

        if modifier:
            modifier1 = modifier
            if modifier.submod:
                modifier2 = modifier.submod

        rule = KeyValue(
            filter_locals(locals(), drop=['address_key', 'modifier']),
            aliases={
                'address': address_key,
                'address_vassal': 'vassal',
                'signing': 'sign',
                'check_file': 'check',
                'balancing_weight': 'weight',
                'balancing_algo': 'algo',
                'protocol': 'proto',
                'sni_cert': 'sni_crt',
                'sni_client_ca': 'sni_ca',
            },
        )

        self._set('subscribe2', rule)

        return self._section

Response: Registers a new subscription intent.


Instruction:
How would you explain what the following Python 3 function does
def find_project_dir():
    frame = inspect.currentframe()

    while True:
        frame = frame.f_back
        fname = frame.f_globals['__file__']

        if os.path.basename(fname) == 'manage.py':
            break

    return os.path.dirname(fname)

Response:
Runs up the stack to find the location of manage. py
    which will be considered a project base path.


Instruction:
Implement a Python 3 function for
running uWSGI using the given section configuration.

Response:
def run_uwsgi(config_section, compile_only=False):
    """Runs uWSGI using the given section configuration.

    :param Section config_section:
    :param bool compile_only: Do not run, only compile and output configuration file for run.

    """
    config = config_section.as_configuration()

    if compile_only:
        config.print_ini()
        return

    config_path = config.tofile()
    os.execvp('uwsgi', ['uwsgi', '--ini=%s' % config_path])


Instruction:
Given the following Python 3 function, write the documentation
def _get_section_existing(self, name_module, name_project):
        from importlib import import_module

        from uwsgiconf.settings import CONFIGS_MODULE_ATTR

        config = getattr(
            import_module(os.path.splitext(name_module)[0], package=name_project),
            CONFIGS_MODULE_ATTR)[0]

        return config.sections[0]

Response: Loads config section from existing configuration file


Instruction:
Create a Python 3 function for
creating a new section with default settings.

Response:
def _get_section_new(cls, dir_base):
        """Creates a new section with default settings.

        :param str|unicode dir_base:
        :rtype: Section

        """
        from uwsgiconf.presets.nice import PythonSection
        from django.conf import settings

        wsgi_app = settings.WSGI_APPLICATION

        path_wsgi, filename, _, = wsgi_app.split('.')
        path_wsgi = os.path.join(dir_base, path_wsgi, '%s.py' %filename)

        section = PythonSection(
            wsgi_module=path_wsgi,

        ).networking.register_socket(
            PythonSection.networking.sockets.http('127.0.0.1:8000')

        ).main_process.change_dir(dir_base)

        return section


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

        options = self.options
        if options['compile'] or not options['use_static_handler']:
            return

        from django.core.management import call_command

        settings = self.settings
        statics = self.section.statics
        statics.register_static_map(settings.STATIC_URL, settings.STATIC_ROOT)
        statics.register_static_map(settings.MEDIA_URL, settings.MEDIA_ROOT)

        call_command('collectstatic', clear=True, interactive=False)

Response: Contributes static and media file serving settings to an existing section.


Instruction:
Write a Python 3 script for
contributing generic static error massage pages to an existing section.

Response:
def contribute_error_pages(self):
        """Contributes generic static error massage pages to an existing section."""

        static_dir = self.settings.STATIC_ROOT

        if not static_dir:
            # Source static directory is not configured. Use temporary.
            import tempfile
            static_dir = os.path.join(tempfile.gettempdir(), self.project_name)
            self.settings.STATIC_ROOT = static_dir

        self.section.routing.set_error_pages(
            common_prefix=os.path.join(static_dir, 'uwsgify'))


Instruction:
Implement a Python 3 function for
mapping a specific file or directory modification event to a signal.

Response:
def register_file_monitor(filename, target=None):
    """Maps a specific file/directory modification event to a signal.

    :param str|unicode filename: File or a directory to watch for its modification.

    :param int|Signal|str|unicode target: Existing signal to raise
        or Signal Target to register signal implicitly.

        Available targets:

            * ``workers``  - run the signal handler on all the workers
            * ``workerN`` - run the signal handler only on worker N
            * ``worker``/``worker0`` - run the signal handler on the first available worker
            * ``active-workers`` - run the signal handlers on all the active [non-cheaped] workers

            * ``mules`` - run the signal handler on all of the mules
            * ``muleN`` - run the signal handler on mule N
            * ``mule``/``mule0`` - run the signal handler on the first available mule

            * ``spooler`` - run the signal on the first available spooler
            * ``farmN/farm_XXX``  - run the signal handler in the mule farm N or named XXX

    :raises ValueError: If unable to register monitor.
    """
    return _automate_signal(target, func=lambda sig: uwsgi.add_file_monitor(int(sig), filename))


Instruction:
How would you explain what the following Python 3 function does
def set(self, value, mode=None):
        if mode == 'max':
            func = uwsgi.metric_set_max

        elif mode == 'min':
            func = uwsgi.metric_set_min

        else:
            func = uwsgi.metric_set

        return func(self.name, value)

Response: Sets the value of the current metric.


Instruction:
Given the following Python 3 function, write the documentation
def get_message(cls, signals=True, farms=False, buffer_size=65536, timeout=-1):
        return decode(uwsgi.mule_get_msg(signals, farms, buffer_size, timeout))

Response: Block until a mule message is received and return it.


Instruction:
Can you implement a function in Python 3 that
regenerates header files for cmark under. generated.

Response:
def regenerate(session):
    """Regenerates header files for cmark under ./generated."""
    if platform.system() == 'Windows':
        output_dir = '../generated/windows'
    else:
        output_dir = '../generated/unix'

    session.run(shutil.rmtree, 'build', ignore_errors=True)
    session.run(os.makedirs, 'build')
    session.chdir('build')
    session.run('cmake', '../third_party/cmark')
    session.run(shutil.copy, 'src/cmark-gfm_export.h', output_dir)
    session.run(shutil.copy, 'src/cmark-gfm_version.h', output_dir)
    session.run(shutil.copy, 'src/config.h', output_dir)
    session.run(shutil.copy, 'extensions/cmark-gfm-extensions_export.h', output_dir)
    session.chdir('..')
    session.run(shutil.rmtree, 'build')


Instruction:
Explain what the following Python 3 code does
def filter_locals(locals_dict, drop=None, include=None):
    drop = drop or []
    drop.extend([
        'self',
        '__class__',  # py3
    ])

    include = include or locals_dict.keys()

    relevant_keys = [key for key in include if key not in drop]

    locals_dict = {k: v for k, v in locals_dict.items() if k in relevant_keys}

    return locals_dict

Response: Filters a dictionary produced by locals.


Instruction:
Write a Python 3 function for
running a command and returns its output.

Response:
def get_output(cmd, args):
    """Runs a command and returns its output (stdout + stderr).

    :param str|unicode cmd:
    :param str|unicode|list[str|unicode] args:

    :rtype: str|unicode

    """
    from subprocess import Popen, STDOUT, PIPE

    command = [cmd]
    command.extend(listify(args))

    process = Popen(command, stdout=PIPE, stderr=STDOUT)
    out, _ = process.communicate()

    return out.decode('utf-8')


Instruction:
Given the following Python 3 function, write the documentation
def parse_command_plugins_output(out):
    out = out.split('--- end of plugins list ---')[0]
    out = out.partition('plugins ***')[2]
    out = out.splitlines()

    current_slot = 0

    plugins = EmbeddedPlugins([], [])

    for line in out:
        line = line.strip()

        if not line:
            continue

        if line.startswith('***'):
            current_slot += 1
            continue

        if current_slot is not None:
            plugins[current_slot].append(line)

    plugins = plugins._replace(request=[plugin.partition(' ')[2] for plugin in plugins.request])

    return plugins

Response:
Parses uWSGI
    and returns object containing lists of embedded plugin names.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_uwsgi_stub_attrs_diff():

    try:
        import uwsgi

    except ImportError:
        from uwsgiconf.exceptions import UwsgiconfException

        raise UwsgiconfException(
            '`uwsgi` module is unavailable. Calling `get_attrs_diff` in such environment makes no sense.')

    from . import uwsgi_stub

    def get_attrs(src):
        return set(attr for attr in dir(src) if not attr.startswith('_'))

    attrs_uwsgi = get_attrs(uwsgi)
    attrs_stub = get_attrs(uwsgi_stub)

    from_uwsgi = sorted(attrs_uwsgi.difference(attrs_stub))
    from_stub = sorted(attrs_stub.difference(attrs_uwsgi))

    return from_uwsgi, from_stub

Response: Returns attributes difference two elements tuple between uwsgi module and uwsgi stub module.


Instruction:
Explain what the following Python 3 code does
def spawn_uwsgi(self, only=None):
        spawned = []
        configs = self.configurations

        if len(configs) == 1:

            alias = configs[0].alias
            UwsgiRunner().spawn(self.fpath, alias, replace=True)
            spawned.append((alias, os.getpid()))

        else:
            for config in configs:  # type: Configuration
                alias = config.alias

                if only is None or alias == only:
                    pid = UwsgiRunner().spawn(self.fpath, alias)
                    spawned.append((alias, pid))

        return spawned

Response: Spawns uWSGI processes which will use configuration from the module.


Instruction:
How would you code a function in Python 3 to
load a module and returns its object.

Response:
def load(cls, fpath):
        """Loads a module and returns its object.

        :param str|unicode fpath:
        :rtype: module
        """
        module_name = os.path.splitext(os.path.basename(fpath))[0]

        sys.path.insert(0, os.path.dirname(fpath))
        try:
            module = import_module(module_name)

        finally:
            sys.path = sys.path[1:]

        return module


Instruction:
Make a summary of the following Python 3 code
def cmd_log(self, reopen=False, rotate=False):
        cmd = b''

        if reopen:
            cmd += b'l'

        if rotate:
            cmd += b'L'

        return self.send_command(cmd)

Response: Allows managing of uWSGI log related stuff.


Instruction:
Implement a Python 3 function for
reloading uWSGI master process.

Response:
def cmd_reload(self, force=False, workers_only=False, workers_chain=False):
        """Reloads uWSGI master process, workers.

        :param bool force: Use forced (brutal) reload instead of a graceful one.
        :param bool workers_only: Reload only workers.
        :param bool workers_chain: Run chained workers reload (one after another,
            instead of destroying all of them in bulk).

        """
        if workers_chain:
            return self.send_command(b'c')

        if workers_only:
            return self.send_command(b'R' if force else b'r')

        return self.send_command(b'R' if force else b'r')


Instruction:
Write a Python 3 script for
sending a generic command into the FIFO.

Response:
def send_command(self, cmd):
        """Sends a generic command into FIFO.

        :param bytes cmd: Command chars to send into FIFO.

        """
        if not cmd:
            return

        with open(self.fifo, 'wb') as f:
            f.write(cmd)


Instruction:
How would you explain what the following Python 3 function does
def get_env_path(cls):
        return os.path.dirname(Finder.python()) + os.pathsep + os.environ['PATH']

Response: Returns the PATH environment variable updated to run uwsgiconf in


Instruction:
How would you explain what the following Python 3 function does
def prepare_env(cls):
        os.environ['PATH'] = cls.get_env_path()
        return os.path.basename(Finder.python())

Response: Prepares current environment and returns Python binary name.


Instruction:
How would you explain what the following Python 3 function does
def spawn(self, filepath, configuration_alias, replace=False):
        # Pass --conf as an argument to have a chance to use
        # touch reloading form .py configuration file change.
        args = ['uwsgi', '--ini', 'exec://%s %s --conf %s' % (self.binary_python, filepath, configuration_alias)]

        if replace:
            return os.execvp('uwsgi', args)

        return os.spawnvp(os.P_NOWAIT, 'uwsgi', args)

Response: Spawns uWSGI using the given configuration module.


Instruction:
How would you implement a function in Python 3 that
gets a value from the cache.

Response:
def get(self, key, default=None, as_int=False, setter=None):
        """Gets a value from the cache.

        :param str|unicode key: The cache key to get value for.

        :param default: Value to return if none found in cache.

        :param bool as_int: Return 64bit number instead of str.

        :param callable setter: Setter callable to automatically set cache
            value if not already cached. Required to accept a key and return
            a value that will be cached.

        :rtype: str|unicode|int

        """
        if as_int:
            val = uwsgi.cache_num(key, self.name)
        else:
            val = decode(uwsgi.cache_get(key, self.name))

        if val is None:

            if setter is None:
                return default

            val = setter(key)

            if val is None:
                return default

            self.set(key, val)

        return val


Instruction:
Make a summary of the following Python 3 code
def set(self, key, value):
        return uwsgi.cache_set(key, value, self.timeout, self.name)

Response: Sets the specified key value.


Instruction:
Create a Python 3 function for
incrementing the specified key value by the specified value.

Response:
def incr(self, key, delta=1):
        """Increments the specified key value by the specified value.

        :param str|unicode key:

        :param int delta:

        :rtype: bool
        """
        return uwsgi.cache_inc(key, delta, self.timeout, self.name)


Instruction:
Explain what the following Python 3 code does
def mul(self, key, value=2):
        return uwsgi.cache_mul(key, value, self.timeout, self.name)

Response: Multiplies the specified key value by the specified value.


Instruction:
Write a Python 3 function for
dividing the specified key value by the specified value.

Response:
def div(self, key, value=2):
        """Divides the specified key value by the specified value.

        :param str|unicode key:

        :param int value:

        :rtype: bool
        """
        return uwsgi.cache_mul(key, value, self.timeout, self.name)


Instruction:
How would you implement a function in Python 3 that
receives data from the websocket.

Response:
def recv(request_context=None, non_blocking=False):
    """Receives data from websocket.

    :param request_context:

    :param bool non_blocking:

    :rtype: bytes|str

    :raises IOError: If unable to receive a message.
    """

    if non_blocking:
        result = uwsgi.websocket_recv_nb(request_context)

    else:
        result = uwsgi.websocket_recv(request_context)

    return result


Instruction:
Explain what the following Python 3 code does
def send(message, request_context=None, binary=False):
    if binary:
        return uwsgi.websocket_send_binary(message, request_context)

    return uwsgi.websocket_send(message, request_context)

Response: Sends a message to the current websocket.


Instruction:
Make a summary of the following Python 3 code
def markdown_to_html(text, options=0):
    encoded_text = text.encode('utf-8')
    raw_result = _cmark.lib.cmark_markdown_to_html(
        encoded_text, len(encoded_text), options)
    return _cmark.ffi.string(raw_result).decode('utf-8')

Response: Render the given text to HTML.


Instruction:
Implement a function in Python 3 to
render the given text to HTML using the given extensions.

Response:
def markdown_to_html_with_extensions(text, options=0, extensions=None):
    """Render the given text to Markdown, using extensions.

    This is a high-level wrapper over the various functions needed to enable
    extensions, attach them to a parser, and render html.

    Args:
        text (str): The text to render to Markdown.
        options (int): The cmark options.
        extensions (Sequence[str]): The list of extension names to use.

    Returns:
        str: The rendered markdown.
    """
    if extensions is None:
        extensions = []

    core_extensions_ensure_registered()

    cmark_extensions = []
    for extension_name in extensions:
        extension = find_syntax_extension(extension_name)
        if extension is None:
            raise ValueError('Unknown extension {}'.format(extension_name))
        cmark_extensions.append(extension)

    parser = parser_new(options=options)

    try:
        for extension in cmark_extensions:
            parser_attach_syntax_extension(parser, extension)

        parser_feed(parser, text)

        root = parser_finish(parser)

        if _cmark.lib.cmark_node_get_type(root) == _cmark.lib.CMARK_NODE_NONE:
            raise ValueError('Error parsing markdown!')

        extensions_ll = parser_get_syntax_extensions(parser)

        output = render_html(root, options=options, extensions=extensions_ll)

    finally:
        parser_free(parser)

    return output


Instruction:
How would you code a function in Python 3 to
parse a text string and return the root node of the parsed syntax tree.

Response:
def parse_document(text, options=0):
    """Parse a document and return the root node.

    Args:
        text (str): The text to parse.
        options (int): The cmark options.

    Returns:
        Any: Opaque reference to the root node of the parsed syntax tree.
    """
    encoded_text = text.encode('utf-8')
    return _cmark.lib.cmark_parse_document(
        encoded_text, len(encoded_text), options)


Instruction:
Write a Python 3 script to
direct wrapper over cmark_parser_feed.

Response:
def parser_feed(parser, text):
    """Direct wrapper over cmark_parser_feed."""
    encoded_text = text.encode('utf-8')
    return _cmark.lib.cmark_parser_feed(
        parser, encoded_text, len(encoded_text))


Instruction:
Can you generate the documentation for the following Python 3 function
def render_html(root, options=0, extensions=None):
    if extensions is None:
        extensions = _cmark.ffi.NULL

    raw_result = _cmark.lib.cmark_render_html(
        root, options, extensions)

    return _cmark.ffi.string(raw_result).decode('utf-8')

Response: Render a given syntax tree as HTML.


Instruction:
Can you create a Python 3 function that
directs wrapper over cmark_find_syntax_extension.

Response:
def find_syntax_extension(name):
    """Direct wrapper over cmark_find_syntax_extension."""
    encoded_name = name.encode('utf-8')
    extension = _cmark.lib.cmark_find_syntax_extension(encoded_name)

    if extension == _cmark.ffi.NULL:
        return None
    else:
        return extension


Instruction:
Create a Python 3 function to
set basic parameters for the cache item expiration command.

Response:
def set_basic_params(self, no_expire=None, expire_scan_interval=None, report_freed=None):
        """
        :param bool no_expire: Disable auto sweep of expired items.
            Since uWSGI 1.2, cache item expiration is managed by a thread in the master process,
            to reduce the risk of deadlock. This thread can be disabled
            (making item expiry a no-op) with the this option.

        :param int expire_scan_interval: Set the frequency (in seconds) of cache sweeper scans. Default: 3.

        :param bool report_freed: Constantly report the cache item freed by the sweeper.

            .. warning:: Use only for debug.

        """
        self._set('cache-no-expire', no_expire, cast=bool)
        self._set('cache-report-freed-items', report_freed, cast=bool)
        self._set('cache-expire-freq', expire_scan_interval)

        return self._section


Instruction:
Create a Python 3 function to
add an item into the given cache.

Response:
def add_item(self, key, value, cache_name=None):
        """Add an item into the given cache.

        This is a commodity option (mainly useful for testing) allowing you
        to store an item in a uWSGI cache during startup.

        :param str|unicode key:

        :param value:

        :param str|unicode cache_name: If not set, default will be used.

        """
        cache_name = cache_name or ''
        value = '%s %s=%s' % (cache_name, key, value)

        self._set('add-cache-item', value.strip(), multi=True)

        return self._section


Instruction:
Can you tell what is the following Python 3 function doing
def add_file(self, filepath, gzip=False, cache_name=None):
        command = 'load-file-in-cache'

        if gzip:
            command += '-gzip'

        cache_name = cache_name or ''
        value = '%s %s' % (cache_name, filepath)

        self._set(command, value.strip(), multi=True)

        return self._section

Response: Add a static file to the cache.


Instruction:
Can you write a function in Python 3 where it
creates a new cache.

Response:
def add_cache(
            self, name, max_items, expires=None, store=None, store_sync_interval=None, store_delete=None,
            hash_algo=None, hash_size=None, key_size=None, udp_clients=None, udp_servers=None,
            block_size=None, block_count=None, sync_from=None, mode_bitmap=None, use_lastmod=None,
            full_silent=None, full_purge_lru=None):
        """Creates cache. Default mode: single block.

        .. note:: This uses new generation ``cache2`` option available since uWSGI 1.9.

        .. note:: When at least one cache is configured without ``full_purge_lru``
            and the master is enabled a thread named "the cache sweeper" is started.
            Its main purpose is deleting expired keys from the cache.
            If you want auto-expiring you need to enable the master.

        :param str|unicode name: Set the name of the cache. Must be unique in an instance.

        :param int max_items: Set the maximum number of cache items.

            .. note:: Effective number of items is **max_items - 1** -
                the first item of the cache is always internally used as "NULL/None/undef".

        :param int expires: The number of seconds after the object is no more valid
            (and will be removed by the cache sweeper when ``full_purge_lru`` is not set.

        :param str|unicode store: Set the filename for the persistent storage.
            If it doesn't exist, the system assumes an empty cache and the file will be created.

        :param int store_sync_interval: Set the number of seconds after which msync() is called
            to flush memory cache on disk when in persistent mode.
            By default it is disabled leaving the decision-making to the kernel.

        :param bool store_delete: uWSGI, by default, will not start if a cache file exists
            and the store file does not match the configured items/blocksize.
            Setting this option will make uWSGI delete the existing file upon mismatch
            and create a new one.

        :param str|unicode hash_algo: Set the hash algorithm used in the hash table. Current options are:

            * djb33x (default)
            * murmur2

        :param int hash_size: This is the size of the hash table in bytes.
            Generally 65536 (the default) is a good value.

            .. note:: Change it only if you know what you are doing
                or if you have a lot of collisions in your cache.

        :param int key_size: Set the maximum size of a key, in bytes. Default: 2048.

        :param str|unicode|list udp_clients: List of UDP servers which will receive UDP cache updates.

        :param str|unicode |list udp_servers: List of UDP addresses on which to bind the cache
            to wait for UDP updates.

        :param int block_size: Set the size (in bytes) of a single block.

            .. note:: It's a good idea to use a multiple of 4096 (common memory page size).

        :param int block_count: Set the number of blocks in the cache. Useful only in bitmap mode,
            otherwise the number of blocks is equal to the maximum number of items.

        :param str|unicode|list sync_from: List of uWSGI addresses which the cache subsystem will connect to
            for getting a full dump of the cache. It can be used for initial cache synchronization.
            The first node sending a valid dump will stop the procedure.

        :param bool mode_bitmap: Enable (more versatile but relatively slower) bitmap mode.

            http://uwsgi-docs.readthedocs.io/en/latest/Caching.html#single-block-faster-vs-bitmaps-slower

            .. warning:: Considered production ready only from uWSGI 2.0.2.

        :param bool use_lastmod: Enabling will update last_modified_at timestamp of each cache
            on every cache item modification. Enable it if you want to track this value
            or if other features depend on it. This value will then be accessible via the stats socket.

        :param bool full_silent: By default uWSGI will print warning message on every cache set operation
            if the cache is full. To disable this warning set this option.

            .. note:: Available since 2.0.4.

        :param bool full_purge_lru: Allows the caching framework to evict Least Recently Used (LRU)
            item when you try to add new item to cache storage that is full.

            .. note:: ``expires`` argument will be ignored.

        """
        value = KeyValue(
            locals(),
            keys=[
                'name', 'max_items', 'expires', 'store', 'store_sync_interval', 'store_delete',
                'hash_algo', 'hash_size', 'key_size', 'udp_clients', 'udp_servers',
                'block_size', 'block_count', 'sync_from', 'mode_bitmap', 'use_lastmod',
                'full_silent', 'full_purge_lru',
            ],
            aliases={
                'max_items': 'maxitems',
                'store_sync_interval': 'storesync',
                'hash_algo': 'hash',
                'udp_clients': 'nodes',
                'block_size': 'blocksize',
                'block_count': 'blocks',
                'sync_from': 'sync',
                'mode_bitmap': 'bitmap',
                'use_lastmod': 'lastmod',
                'full_silent': 'ignore_full',
                'full_purge_lru': 'purge_lru',
            },
            bool_keys=['store_delete', 'mode_bitmap', 'use_lastmod', 'full_silent', 'full_purge_lru'],
            list_keys=['udp_clients', 'udp_servers', 'sync_from'],
        )

        self._set('cache2', value, multi=True)

        return self._section


Instruction:
Make a summary of the following Python 3 code
def register_timer(period, target=None):
    return _automate_signal(target, func=lambda sig: uwsgi.add_timer(int(sig), period))

Response: Register a timer that will repeat the current time period seconds.


Instruction:
Can you create a Python 3 function that
registers a red - black timer based on black - red tree.

Response:
def register_timer_rb(period, repeat=None, target=None):
    """Add a red-black timer (based on black-red tree).

        .. code-block:: python

            @register_timer_rb(3)
            def repeat():
                do()

    :param int period: The interval (seconds) at which the signal is raised.

    :param int repeat: How many times to repeat. Default: None - infinitely.

    :param int|Signal|str|unicode target: Existing signal to raise
        or Signal Target to register signal implicitly.

        Available targets:

            * ``workers``  - run the signal handler on all the workers
            * ``workerN`` - run the signal handler only on worker N
            * ``worker``/``worker0`` - run the signal handler on the first available worker
            * ``active-workers`` - run the signal handlers on all the active [non-cheaped] workers

            * ``mules`` - run the signal handler on all of the mules
            * ``muleN`` - run the signal handler on mule N
            * ``mule``/``mule0`` - run the signal handler on the first available mule

            * ``spooler`` - run the signal on the first available spooler
            * ``farmN/farm_XXX``  - run the signal handler in the mule farm N or named XXX

    :rtype: bool|callable

    :raises ValueError: If unable to add timer.
    """
    return _automate_signal(target, func=lambda sig: uwsgi.add_rb_timer(int(sig), period, repeat or 0))


Instruction:
Make a summary of the following Python 3 code
def register_cron(weekday=None, month=None, day=None, hour=None, minute=None, target=None):
    task_args_initial = {name: val for name, val in locals().items() if val is not None and name != 'target'}
    task_args_casted = {}

    def skip_task(check_funcs):
        now = datetime.now()
        allright = all((func(now) for func in check_funcs))
        return not allright

    def check_date(now, attr, target_range):
        attr = getattr(now, attr)

        if callable(attr):  # E.g. weekday.
            attr = attr()

        return attr in target_range

    check_date_funcs = []

    for name, val in task_args_initial.items():

        # uWSGI won't accept strings, so we emulate ranges here.
        if isinstance(val, string_types):

            # Rules like 10-18/2 (from 10 till 18 every 2 hours).
            val, _, step = val.partition('/')
            step = int(step) if step else 1
            start, _, end = val.partition('-')

            if not (start and end):
                raise RuntimeConfigurationError(
                    'String cron rule without a range is not supported. Use integer notation.')

            start = int(start)
            end = int(end)

            now_attr_name = name

            period_range = set(range(start, end+1, step))

            if name == 'weekday':
                # Special case for weekday indexes: swap uWSGI Sunday 0 for ISO Sunday 7.
                now_attr_name = 'isoweekday'

                if 0 in period_range:
                    period_range.discard(0)
                    period_range.add(7)

            # Gather date checking functions in one place.
            check_date_funcs.append(partial(check_date, attr=now_attr_name, target_range=period_range))

            # Use minimal duration (-1).
            val = None

        task_args_casted[name] = val

    if not check_date_funcs:
        # No special handling of periods, quit early.
        args = [(-1 if arg is None else arg) for arg in (minute, hour, day, month, weekday)]
        return _automate_signal(target, func=lambda sig: uwsgi.add_cron(int(sig), *args))

    skip_task = partial(skip_task, check_date_funcs)

    def decor(func_action):
        """Decorator wrapping."""

        @wraps(func_action)
        def func_action_wrapper(*args, **kwargs):
            """Action function wrapper to handle periods in rules."""

            if skip_task():
                # todo Maybe allow user defined value for this return.
                return None

            return func_action(*args, **kwargs)

        args = []
        for arg_name in ['minute', 'hour', 'day', 'month', 'weekday']:
            arg = task_args_casted.get(arg_name, None)
            args.append(-1 if arg is None else arg)

        return _automate_signal(target, func=lambda sig: uwsgi.add_cron(int(sig), *args))(func_action_wrapper)

    return decor

Response: Register a cron for the current locale.


Instruction:
Can you implement a function in Python 3 that
truncates a line to the specified length followed by... unless it s shorter than length already.

Response:
def truncate_ellipsis(line, length=30):
    """Truncate a line to the specified length followed by ``...`` unless its shorter than length already."""

    l = len(line)
    return line if l < length else line[:length - 3] + "..."


Instruction:
Explain what the following Python 3 code does
def pyle_evaluate(expressions=None, modules=(), inplace=False, files=None, print_traceback=False):

    eval_globals = {}

    eval_globals.update(STANDARD_MODULES)

    for module_arg in modules or ():
        for module in module_arg.strip().split(","):
            module = module.strip()
            if module:
                eval_globals[module] = __import__(module)

    if not expressions:
        # Default 'do nothing' program
        expressions = ['line']

    files = files or ['-']
    eval_locals = {}
    for file in files:
        if file == '-':
            file = sys.stdin

        out_buf = sys.stdout if not inplace else StringIO.StringIO()

        out_line = None
        with (open(file, 'rb') if not hasattr(file, 'read') else file) as in_file:
            for num, line in enumerate(in_file.readlines()):
                was_whole_line = False
                if line[-1] == '\n':
                    was_whole_line = True
                    line = line[:-1]

                expr = ""
                try:
                    for expr in expressions:
                        words = [word.strip()
                                 for word in re.split(r'\s+', line)
                                 if word]
                        eval_locals.update({
                            'line': line, 'words': words,
                            'filename': in_file.name, 'num': num
                            })

                        out_line = eval(expr, eval_globals, eval_locals)

                        if out_line is None:
                            continue

                        # If the result is something list-like or iterable,
                        # output each item space separated.
                        if not isinstance(out_line, str) and not isinstance(out_line, unicode):
                            try:
                                out_line = u' '.join(unicode(part)
                                                     for part in out_line)
                            except:
                                # Guess it wasn't a list after all.
                                out_line = unicode(out_line)

                        line = out_line
                except Exception as e:
                    sys.stdout.flush()
                    sys.stderr.write("At %s:%d ('%s'): `%s`: %s\n" % (
                        in_file.name, num, truncate_ellipsis(line), expr, e))
                    if print_traceback:
                        traceback.print_exc(None, sys.stderr)
                else:
                    if out_line is None:
                        continue

                    out_line = out_line or u''
                    out_buf.write(out_line)
                    if was_whole_line:
                        out_buf.write('\n')
        if inplace:
            with open(file, 'wb') as out_file:
                out_file.write(out_buf.getvalue())
            out_buf.close()

Response: The main method of pyle.


Instruction:
Implement a function in Python 3 to
execute pyle with the specified arguments or sys. argv if no arguments specified.

Response:
def pyle(argv=None):
    """Execute pyle with the specified arguments, or sys.argv if no arguments specified."""

    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument("-m", "--modules", dest="modules", action='append',
        help="import MODULE before evaluation. May be specified more than once.")
    parser.add_argument("-i", "--inplace", dest="inplace", action='store_true', default=False,
        help="edit files in place. When used with file name arguments, the files will be replaced by the output of the evaluation")
    parser.add_argument("-e", "--expression", action="append",
        dest="expressions", help="an expression to evaluate for each line")
    parser.add_argument('files', nargs='*',
        help="files to read as input. If used with --inplace, the files will be replaced with the output")
    parser.add_argument("--traceback", action="store_true", default=False,
        help="print a traceback on stderr when an expression fails for a line")

    args = parser.parse_args() if not argv else parser.parse_args(argv)

    pyle_evaluate(args.expressions, args.modules, args.inplace, args.files,
                  args.traceback)


Instruction:
Write a Python 3 function that can
convert the arpabet to the international phonetic alphabet.

Response:
def convert_to_international_phonetic_alphabet(self, arpabet):
        '''
        转换成国际音标
        :param arpabet:
        :return:
        '''

        word = self._convert_to_word(arpabet=arpabet)

        if not word:
            return None

        return word.translate_to_international_phonetic_alphabet()


Instruction:
Here you have a function in Python 3, explain what it does
def convert_to_american_phonetic_alphabet(self, arpabet):
        '''
        转换成美音
        :param arpabet:
        :return:
        '''

        word = self._convert_to_word(arpabet=arpabet)

        if not word:
            return None

        return word.translate_to_american_phonetic_alphabet()

Response: Convert the arpabet to a list of american phonetic alphabets.


Instruction:
Here you have a function in Python 3, explain what it does
def convert_to_english_phonetic_alphabet(self, arpabet):
        '''
        转换成英音
        :param arpabet:
        :return:
        '''

        word = self._convert_to_word(arpabet=arpabet)

        if not word:
            return None

        return word.translate_to_english_phonetic_alphabet()

Response: Convert the arpabet to a non - English alphabet.


Instruction:
Explain what the following Python 3 code does
def translate_to_arpabet(self):
        '''
        转换成arpabet
        :return:
        '''

        translations = []

        for phoneme in self._phoneme_list:
            if phoneme.is_vowel:
                translations.append(phoneme.arpabet + self.stress.mark_arpabet())
            else:
                translations.append(phoneme.arpabet)

        return " ".join(translations)

Response: Translate the list of phonemes to the ARPabet.


Instruction:
Create a Python 3 function to
translate the list of phonemes to a list of AMerican letters.

Response:
def translate_to_american_phonetic_alphabet(self, hide_stress_mark=False):
        '''
        转换成美音音。只要一个元音的时候需要隐藏重音标识
        :param hide_stress_mark:
        :return:

        '''

        translations = self.stress.mark_ipa() if (not hide_stress_mark) and self.have_vowel else ""

        for phoneme in self._phoneme_list:
            translations += phoneme.american

        return translations


Instruction:
Explain what the following Python 3 code does
def translate_to_english_phonetic_alphabet(self, hide_stress_mark=False):
        '''
        转换成英音。只要一个元音的时候需要隐藏重音标识
        :param hide_stress_mark:
        :return:
        '''

        translations = self.stress.mark_ipa() if (not hide_stress_mark) and self.have_vowel else ""

        for phoneme in self._phoneme_list:
            translations += phoneme.english

        return translations

Response: Translate the list of phonemes to their English alphabet.


Instruction:
Can you create a Python 3 function that
translates to international phonetic alphabet.

Response:
def translate_to_international_phonetic_alphabet(self, hide_stress_mark=False):
        '''
        转换成国际音标。只要一个元音的时候需要隐藏重音标识
        :param hide_stress_mark:
        :return:
        '''

        translations = self.stress.mark_ipa() if (not hide_stress_mark) and self.have_vowel else ""

        for phoneme in self._phoneme_list:
            translations += phoneme.ipa

        return translations


Instruction:
Can you create a Python 3 function that
initializes and returns the login form component

Response:
def get_login_form_component(self):
        """Initializes and returns the login form component

        @rtype: LoginForm
        @return: Initialized component
        """
        self.dw.wait_until(
            lambda: self.dw.is_present(LoginForm.locators.form),
            failure_message='login form was never present so could not get the model '
                            'upload form component'
        )

        self.login_form = LoginForm(
            parent_page=self,
            element=self.dw.find(LoginForm.locators.form),
        )
        return self.login_form


Instruction:
Here you have a function in Python 3, explain what it does
def objectify(dictionary, name='Object'):
    o = namedtuple(name, dictionary.keys())(*dictionary.values())

    return o

Response: Converts a dictionary into a named tuple


Instruction:
Given the following Python 3 function, write the documentation
def create_directory(directory):
    try:
        os.makedirs(directory)
    except OSError, e:
        if e.errno == errno.EEXIST and os.path.isdir(directory):
            pass

    return directory

Response: Creates a directory if it does not exist.


Instruction:
Make a summary of the following Python 3 code
def __add_query_comment(sql):
        # Inspect the call stack for the originating call
        file_name = ''
        line_number = ''
        caller_frames = inspect.getouterframes(inspect.currentframe())
        for frame in caller_frames:
            if "ShapewaysDb" not in frame[1]:
                file_name = frame[1]
                line_number = str(frame[2])
                break

        comment = "/*COYOTE: Q_SRC: {file}:{line} */\n".format(file=file_name, line=line_number)
        return comment + sql,

Response:
Adds a comment line to the query to be executed containing the line number of the calling
        function.


Instruction:
Can you implement a function in Python 3 that
returns an instance of class_type populated with attributes from the DB record ; throws an error if no records are found

Response:
def get_single_instance(sql, class_type, *args, **kwargs):
        """Returns an instance of class_type populated with attributes from the DB record; throws an error if no
        records are found

        @param sql: Sql statement to execute
        @param class_type: The type of class to instantiate and populate with DB record
        @return: Return an instance with attributes set to values from DB
        """
        record = CoyoteDb.get_single_record(sql, *args, **kwargs)
        try:
            instance = CoyoteDb.get_object_from_dictionary_representation(dictionary=record, class_type=class_type)
        except AttributeError:
            raise NoRecordsFoundException('No records found for {class_type} with sql run on {host}: \n {sql}'.format(
                sql=sql,
                host=DatabaseConfig().get('mysql_host'),
                class_type=class_type
            ))
        return instance


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_all_instances(sql, class_type, *args, **kwargs):
        records = CoyoteDb.get_all_records(sql, *args, **kwargs)
        instances = [CoyoteDb.get_object_from_dictionary_representation(
            dictionary=record, class_type=class_type) for record in records]
        for instance in instances:
            instance._query = sql
        return instances

Response: Returns a list of instances of class_type populated with attributes from the DB record


Instruction:
Implement a function in Python 3 to
escape dictionary values with keys as column names and values column names and values column values

Response:
def escape_dictionary(dictionary, datetime_format='%Y-%m-%d %H:%M:%S'):
        """Escape dictionary values with keys as column names and values column values

        @type dictionary: dict
        @param dictionary: Key-values
        """
        for k, v in dictionary.iteritems():
            if isinstance(v, datetime.datetime):
                v = v.strftime(datetime_format)

            if isinstance(v, basestring):
                v = CoyoteDb.db_escape(str(v))
                v = '"{}"'.format(v)

            if v is True:
                v = 1

            if v is False:
                v = 0

            if v is None:
                v = 'NULL'

            dictionary[k] = v


Instruction:
Can you tell what is the following Python 3 function doing
def get_insert_fields_and_values_from_dict(dictionary, datetime_format='%Y-%m-%d %H:%M:%S', db_escape=True):
        if db_escape:
            CoyoteDb.escape_dictionary(dictionary, datetime_format=datetime_format)

        fields = get_delimited_string_from_list(dictionary.keys(), delimiter=',')  # keys have no quotes
        vals = get_delimited_string_from_list(dictionary.values(), delimiter=',')  # strings get quotes

        return fields, vals

Response: Formats a dictionary to strings of fields and values for insert statements


Instruction:
Here you have a function in Python 3, explain what it does
def get_kwargs(**kwargs):
        d = dict()
        for k, v in kwargs.iteritems():
            if v is not NOTSET:
                d[k] = v
        return d

Response:
This method should be used in query functions where user can query on any number of fields
            >>>


Instruction:
Explain what the following Python 3 code does
def get_update_clause_from_dict(dictionary, datetime_format='%Y-%m-%d %H:%M:%S'):
        items = []

        CoyoteDb.escape_dictionary(dictionary, datetime_format=datetime_format)
        for k,v in dictionary.iteritems():
            item = '{k} = {v}'.format(k=k, v=v)
            items.append(item)
        clause = ', '.join(item for item in items)
        return clause

Response:
Builds an update values clause based on the dictionary representation of an an
        instance


Instruction:
Can you write a function in Python 3 where it
builds a where clause from a dictionary

Response:
def get_where_clause_from_dict(dictionary, join_operator='AND'):
        """Builds a where clause from a dictionary
        """
        CoyoteDb.escape_dictionary(dictionary)
        clause = join_operator.join(
            (' {k} is {v} ' if str(v).lower() == 'null' else ' {k} = {v} ').format(k=k, v=v)  # IS should be the operator for null values
            for k, v in dictionary.iteritems())
        return clause


Instruction:
How would you explain what the following Python 3 function does
def get_dictionary_representation_of_object_attributes(obj, omit_null_fields=False):
        obj_dictionary = obj.__dict__

        obj_dictionary_temp = obj_dictionary.copy()
        for k, v in obj_dictionary.iteritems():
            if omit_null_fields:
                if v is None:
                    obj_dictionary_temp.pop(k, None)
            if k.startswith('_'):
                obj_dictionary_temp.pop(k, None)

        return obj_dictionary_temp

Response: Returns a dictionary of the object s attributes ignoring methods


Instruction:
Make a summary of the following Python 3 code
def get_object_from_dictionary_representation(dictionary, class_type):
        assert inspect.isclass(class_type), 'Cannot instantiate an object that is not a class'

        instance = class_type()

        CoyoteDb.update_object_from_dictionary_representation(dictionary, instance)

        return instance

Response: Instantiates a new class that takes a dictionary representation and populates its attributes with a dictionary


Instruction:
Can you write a function in Python 3 where it
constructs the where clause based on a dictionary of mappings

Response:
def build_where_clause(mappings, operator='AND'):
        """Constructs the where clause based on a dictionary of values

        >>> build_where_clause({'id': 456, 'name': 'myrecord'}, operator='OR')
        >>> 'WHERE id = 456 OR name = "myrecord" '

        """
        where_clause_mappings = {}
        where_clause_mappings.update(mappings)

        where_clause = 'WHERE ' + ' {} '.format(operator).join(
            '{k} = {v}'.format(k=k, v='"{}"'.format(v) if isinstance(v, basestring) else v)
            for k, v in where_clause_mappings.iteritems()
        )
        return where_clause


Instruction:
Can you create a Python 3 function that
executes the sql statement but does not commit. Returns the cursor to commit

Response:
def execute(*args, **kwargs):
        """Executes the sql statement, but does not commit. Returns the cursor to commit

        @return: DB and cursor instance following sql execution
        """

        # Inspect the call stack for the originating call
        args = CoyoteDb.__add_query_comment(args[0])
        db = CoyoteDb.__get_db_write_instance(target_database=kwargs.pop('target_database', None))
        filtered_kwargs = {k: v for k, v in kwargs.iteritems() if k != 'target_database'}

        # Execute the query
        cursor = db.cursor()
        try:
            cursor.execute(*args, **filtered_kwargs)
        except OperationalError, e:
            raise OperationalError('{} when executing: {}'.format(e.args, args[0]))
        return db, cursor


Instruction:
Write a Python 3 function that can
execute the sql statement but does not commit. Returns the cursor to commit

Response:
def execute_read_only(*args, **kwargs):
        # TODO: consolidate with execute
        """Executes the sql statement, but does not commit. Returns the cursor to commit

        @return: DB and cursor instance following sql execution
        """

        # Inspect the call stack for the originating call
        args = CoyoteDb.__add_query_comment(args[0])

        # Execute the query
        db = CoyoteDb.__get_db_read_instance()
        cursor = db.cursor()
        try:
            cursor.execute(*args, **kwargs)
        except OperationalError, e:
            raise OperationalError('{} when executing: {}'.format(e.args, args[0]))
        return db, cursor


Instruction:
Implement a function in Python 3 to
execute the sql statement and commits the sql statement

Response:
def execute_and_commit(*args, **kwargs):
        """Executes and commits the sql statement

        @return: None
        """
        db, cursor = CoyoteDb.execute(*args, **kwargs)
        db.commit()
        return cursor


Instruction:
Write a Python 3 function that can
update and commits with an insert sql statement returns the record

Response:
def update(sql, *args, **kwargs):
        """Updates and commits with an insert sql statement, returns the record, but with a small chance of a race
        condition

        @param sql: sql to execute
        @return: The last row inserted
        """
        assert "update" in sql.lower(), 'This function requires an update statement, provided: {}'.format(sql)
        cursor = CoyoteDb.execute_and_commit(sql, *args, **kwargs)

        # now get that id
        last_row_id = cursor.lastrowid

        return last_row_id


Instruction:
Implement a Python 3 function for
deleting and commits with an insert sql statement

Response:
def delete(sql, *args, **kwargs):
        """Deletes and commits with an insert sql statement"""
        assert "delete" in sql.lower(), 'This function requires a delete statement, provided: {}'.format(sql)
        CoyoteDb.execute_and_commit(sql, *args, **kwargs)


Instruction:
Create a Python 3 function to
give a dictionary and an object instance will set all object attributes equal to the dictionary s keys and values.

Response:
def update_object_from_dictionary_representation(dictionary, instance):
        """Given a dictionary and an object instance, will set all object attributes equal to the dictionary's keys and
        values. Assumes dictionary does not have any keys for which object does not have attributes

        @type dictionary: dict
        @param dictionary: Dictionary representation of the object
        @param instance: Object instance to populate
        @return: None
        """
        for key, value in dictionary.iteritems():
            if hasattr(instance, key):
                setattr(instance, key, value)

        return instance


Instruction:
Implement a function in Python 3 to
format a time to be Shapeways database - compatible with the spec.

Response:
def format_time(time):
        """Formats a time to be Shapeways database-compatible

        @param time: Datetime or string object to format
        @rtype: str
        @return: Time formatted as a string
        """
        # Handle time typing
        try:
            time = time.isoformat()
        except AttributeError:  # Not a datetime object
            time = str(time)

        time = parser.parse(time).strftime('%Y-%m-%d %H:%M:%S')
        return time


Instruction:
Implement a function in Python 3 to
format a date to be Shapeways database - compatible with the spec.

Response:
def format_date(date):
        """Formats a date to be Shapeways database-compatible

        @param date: Datetime or string object to format
        @rtype: str
        @return: Date formatted as a string
        """
        # Handle time typing
        try:
            date = date.isoformat()
        except AttributeError:  # Not a datetime object
            date = str(date)

        date = parser.parse(date).strftime('%Y-%m-%d')
        return date


Instruction:
Make a summary of the following Python 3 code
def is_alert_present(self):
        current_frame = None
        try:
            current_frame = self.driver.current_window_handle
            a = self.driver.switch_to_alert()
            a.text
        except NoAlertPresentException:
            # No alert
            return False
        except UnexpectedAlertPresentException:
            # Alert exists
            return True
        finally:
            if current_frame:
                self.driver.switch_to_window(current_frame)
        return True

Response: Tests if an alert is present


Instruction:
Make a summary of the following Python 3 code
def find(self, locator, find_all=False, search_object=None, force_find=False, exclude_invisible=False):
        search_object = self.driver if search_object is None else search_object
        attempts = 0

        while attempts < self.find_attempts + 1:
            if bool(force_find):
                js_locator = self.locator_handler.parse_locator(locator)

                if js_locator.By != 'css selector':
                    raise ValueError(
                        'You must use a css locator in order to force find an element; this was "{}"'.format(
                            js_locator))

                elements = self.js_executor.execute_template_and_return_result(
                    'getElementsTemplate.js', variables={'selector': js_locator.value})
            else:
                elements = self.locator_handler.find_by_locator(search_object, locator, True)

            # Save original elements found before applying filters to the list
            all_elements = elements

            # Check for only visible elements
            visible_elements = elements
            if exclude_invisible:
                visible_elements = [element for element in all_elements if element.is_displayed()]
                elements = visible_elements

            if len(elements) > 0:
                if find_all is True:
                    # return list of wrapped elements
                    for index in range(len(elements)):
                        elements[index] = WebElementWrapper.WebElementWrapper(self, locator, elements[index],
                                                                              search_object=search_object)

                    return elements

                elif find_all is False:
                    # return first element
                    return WebElementWrapper.WebElementWrapper(self, locator, elements[0], search_object=search_object)

            else:
                if attempts >= self.find_attempts:
                    if find_all is True:  # returns an empty list if finding all elements
                        return []
                    else:  # raise exception if attempting to find one element
                        error_message = "Unable to find element after {0} attempts with locator: {1}".format(
                            attempts,
                            locator
                        )

                        # Check if filters limited the results
                        if exclude_invisible and len(visible_elements) == 0 and len(all_elements) > 0:
                            error_message = "Elements found using locator {}, but none were visible".format(locator)

                        raise WebDriverWrapperException.WebDriverWrapperException(self, error_message)
                else:
                    attempts += 1

Response: Find an element by the given locator


Instruction:
Write a Python 3 function for
attempting to find elements on the page without waiting .

Response:
def _find_immediately(self, locator, search_object=None):
        '''
        Attempts to immediately find elements on the page without waiting

        @type locator:          webdriverwrapper.support.locator.Locator
        @param locator:         Locator object describing
        @type search_object:    webdriverwrapper.WebElementWrapper
        @param search_object:   Optional WebElement to start search with.  If null, search will be on self.driver

        @return:                Single WebElemetnWrapper if find_all is False,
                                list of WebElementWrappers if find_all is True
        '''
        search_object = self.driver if search_object is None else search_object
        elements = self.locator_handler.find_by_locator(search_object, locator, True)
        return [WebElementWrapper.WebElementWrapper(self, locator, element) for element in elements]


Instruction:
Here you have a function in Python 3, explain what it does
def find_all(self, locator, search_object=None, force_find=False):
        '''
        Find all elements matching locator

        @type locator:          webdriverwrapper.support.locator.Locator
        @param locator:         Locator object describing

        @rtype:                 list[WebElementWrapper]
        @return:                list of WebElementWrappers
        '''
        return self.find(locator=locator, find_all=True, search_object=search_object, force_find=force_find)

Response: Find all elements matching locator


Instruction:
Explain what the following Python 3 code does
def find_by_dynamic_locator(self, template_locator, variables, find_all=False, search_object=None):
        '''
        Find with dynamic locator

        @type template_locator:         webdriverwrapper.support.locator.Locator
        @param template_locator:        Template locator w/ formatting bits to insert
        @type variables:                dict
        @param variables:               Dictionary of variable substitutions
        @type find_all:                 bool
        @param find_all:                True to find all elements immediately, False for find single element only
        @type search_object:            webdriverwrapper.WebElementWrapper
        @param search_object:           Optional WebElement to start search with.
                                        If null, search will be on self.driver

        @rtype:                         webdriverwrapper.WebElementWrapper or list()
        @return:                        Single WebElemetnWrapper if find_all is False,
                                        list of WebElementWrappers if find_all is True
        '''
        template_variable_character = '%'
        # raise an exception if user passed non-dictionary variables
        if not isinstance(variables, dict):
            raise TypeError('You must use a dictionary to populate locator variables')

        # replace all variables that match the keys in 'variables' dict
        locator = ""
        for key in variables.keys():
            locator = template_locator.replace(template_variable_character + key, variables[key])

        return self.find(locator, find_all, search_object)

Response: Find with dynamic locator.


Instruction:
Can you write a function in Python 3 where it
determines if an element is present on the page retrying once if unable to locate

Response:
def is_present(self, locator, search_object=None):
        """
        Determines whether an element is present on the page, retrying once if unable to locate

        @type locator:                  webdriverwrapper.support.locator.Locator
        @param locator:                 the locator or css string used to query the element
        @type search_object:            webdriverwrapper.WebElementWrapper
        @param search_object:           Optional WebElement to start search with.
                                        If null, search will be on self.driver
        """
        all_elements = self._find_immediately(locator, search_object=search_object)

        if all_elements is not None and len(all_elements) > 0:
            return True
        else:
            return False


Instruction:
Can you create a Python 3 function that
determines whether an element is present on the page with no wait.

Response:
def is_present_no_wait(self, locator):
        """
        Determines whether an element is present on the page with no wait

        @type locator:  webdriverwrapper.support.locator.Locator
        @param locator: the locator or css string used to query the element
        """

        # first attempt to locate the element

        def execute():
            '''
            Generic function to execute wait
            '''
            return True if len(self.locator_handler.find_by_locator(self.driver, locator, True)) < 0 else False

        return self.execute_and_handle_webdriver_exceptions(
            execute, timeout=0, locator=locator, failure_message='Error running webdriver.find_all.')


Instruction:
Can you generate the documentation for the following Python 3 function
def wait_until(self, wait_function, failure_message=None, timeout=None):
        timeout = timeout if timeout is not None else self.timeout
        failure_message = failure_message if failure_message is not None else \
            'Timeout waiting for custom function to return True'

        def wait():
            '''
            Wait function passed to executor
            '''
            return WebDriverWait(self, timeout).until(lambda dw: wait_function())

        return self.execute_and_handle_webdriver_exceptions(wait, timeout, None, failure_message)

Response: Base wait method that executes wait_function and returns True


Instruction:
Can you tell what is the following Python 3 function doing
def wait_until_present(self, locator, timeout=None, failure_message='Timeout waiting for element to be present'):
        timeout = timeout if timeout is not None else self.timeout

        def wait():
            '''
            Wait function passed to executor
            '''
            element = WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(
                (self.locator_handler.parse_locator(locator).By, self.locator_handler.parse_locator(locator).value)))
            return WebElementWrapper.WebElementWrapper(self, locator, element)

        return self.execute_and_handle_webdriver_exceptions(
            wait, timeout, locator, failure_message=failure_message)

Response: Waits until an element is present


Instruction:
Here you have a function in Python 3, explain what it does
def wait_until_not_present(self, locator, timeout=None):
        # TODO: rethink about neg case with is_present and waiting too long
        timeout = timeout if timeout is not None else self.timeout
        this = self  # for passing WebDriverWrapperReference to WebDriverWait

        def wait():
            '''
            Wait function pasted to executor
            '''
            return WebDriverWait(self.driver, timeout).until(lambda d: not this.is_present(locator))

        return self.execute_and_handle_webdriver_exceptions(
            wait, timeout, locator, 'Timeout waiting for element not to be present')

Response: Wait until an element with the given locator is not present.


Instruction:
Write a Python 3 script to
wait until an element is invisible

Response:
def wait_until_invisibility_of(self, locator, timeout=None):
        """
        Waits for an element to be invisible

        @type locator:  webdriverwrapper.support.locator.Locator
        @param locator: the locator or css string to search for the element
        @type timeout:  int
        @param timeout:  the maximum number of seconds the driver will wait before timing out

        @rtype:                 webdriverwrapper.WebElementWrapper
        @return:                Returns the element found
        """
        timeout = timeout if timeout is not None else self.timeout

        def wait():
            '''
            Wait function passed to executor
            '''
            element = WebDriverWait(self.driver, timeout).until(EC.invisibility_of_element_located(
                (self.locator_handler.parse_locator(locator).By, self.locator_handler.parse_locator(locator).value)))
            return WebElementWrapper.WebElementWrapper(self, locator, element)

        return self.execute_and_handle_webdriver_exceptions(
            wait, timeout, locator, 'Timeout waiting for element to be invisible')


Instruction:
Create a Python 3 function for
waiting for an element to be clickable

Response:
def wait_until_clickable(self, locator, timeout=None):
        """
        Waits for an element to be clickable

        @type locator:  webdriverwrapper.support.locator.Locator
        @param locator: the locator or css string to search for the element
        @type timeout:  int
        @param timeout:  the maximum number of seconds the driver will wait before timing out

        @rtype:                 webdriverwrapper.WebElementWrapper
        @return:                Returns the element found
        """
        timeout = timeout if timeout is not None else self.timeout

        def wait():
            '''
            Wait function passed to executor
            '''
            element = WebDriverWait(self.driver, timeout).until(EC.element_to_be_clickable(
                (self.locator_handler.parse_locator(locator).By, self.locator_handler.parse_locator(locator).value)))

            return WebElementWrapper.WebElementWrapper(self, locator, element)

        return self.execute_and_handle_webdriver_exceptions(
            wait, timeout, locator, 'Timeout waiting for element to be clickable')


Instruction:
Given the following Python 3 function, write the documentation
def wait_until_stale(self, locator, timeout=None):
        timeout = timeout if timeout is not None else self.timeout

        def wait():
            '''
            Wait function passed to executor
            '''
            element = WebDriverWait(self.driver, timeout).until(EC.staleness_of(
                (self.locator_handler.parse_locator(locator).By, self.locator_handler.parse_locator(locator).value)))

            return WebElementWrapper.WebElementWrapper(self, locator, element)

        return self.execute_and_handle_webdriver_exceptions(
            wait, timeout, locator, 'Timeout waiting for element to become stale')

Response:
Waits until an element is found in the DOM and returns the element found
       .


Instruction:
Make a summary of the following Python 3 code
def wait_until_title_contains(self, partial_title, timeout=None):
        timeout = timeout if timeout is not None else self.timeout

        def wait():
            '''
            Wait function passed to executor
            '''
            return WebDriverWait(self.driver, timeout).until(EC.title_contains(partial_title))

        return self.execute_and_handle_webdriver_exceptions(
            wait, timeout, partial_title, 'Timeout waiting for title to contain: ' + str(partial_title))

Response: Waits until the title contains the partial_title


Instruction:
Can you generate a brief explanation for the following Python 3 code
def wait_until_title_is(self, title, timeout=None):
        timeout = timeout if timeout is not None else self.timeout

        def wait():
            '''
            Wait function passed to executor
            '''
            return WebDriverWait(self.driver, timeout).until(EC.title_is(title))

        return self.execute_and_handle_webdriver_exceptions(
            wait, timeout, title, 'Timeout waiting for title to be: ' + str(title))

Response: Waits until the title is exactly the given one.


Instruction:
Here you have a function in Python 3, explain what it does
def wait_until_alert_is_present(self, timeout=None):
        timeout = timeout if timeout is not None else self.timeout
        locator = None

        def wait():
            '''
            Wait function passed to executor
            '''
            return WebDriverWait(self.driver, timeout).until(EC.alert_is_present())

        return self.execute_and_handle_webdriver_exceptions(
            wait, timeout, locator, 'Timeout waiting for alert to be present')

Response: Waits until an alert is present in the element


Instruction:
How would you implement a function in Python 3 that
waits for an element s text to contain text

Response:
def wait_until_text_contains(self, locator, text, timeout=None):
        """
        Waits for an element's text to contain <text>

        @type locator:          webdriverwrapper.support.locator.Locator
        @param locator:         locator used to find element
        @type text:             str
        @param text:            the text to search for
        @type timeout:          int
        @param timeout:         the maximum number of seconds the driver will wait before timing out

        @rtype:                 webdriverwrapper.WebElementWrapper
        @return:                Returns the element found
        """
        timeout = timeout if timeout is not None else self.timeout
        this = self

        self.wait_for(locator) # first check that element exists

        def wait():
            '''
            Wait function passed to executor
            '''
            WebDriverWait(self.driver, timeout).until(lambda d: text in this.find(locator).text())
            return this.find(locator)

        return self.execute_and_handle_webdriver_exceptions(
            wait, timeout, locator, 'Timeout waiting for text to contain: ' + str(text))


Instruction:
Write a Python 3 function for
waiting for an element s text to not be empty

Response:
def wait_until_text_is_not_empty(self, locator, timeout=None):
        """
        Waits for an element's text to not be empty

        @type locator:          webdriverwrapper.support.locator.Locator
        @param locator:         locator used to find element
        @type timeout:          int
        @param timeout:         the maximum number of seconds the driver will wait before timing out

        @rtype:                 webdriverwrapper.WebElementWrapper
        @return:                Returns the element found
        """
        timeout = timeout if timeout is not None else self.timeout

        self.wait_for(locator) # first check that element exists

        def wait():
            '''
            Wait function passed to executor
            '''
            WebDriverWait(self.driver, timeout).until(lambda d: len(self.find(locator).text()) > 0)
            return self.find(locator)

        return self.execute_and_handle_webdriver_exceptions(
            wait, timeout, locator, 'Timeout waiting for element to contain some text')


Instruction:
How would you code a function in Python 3 to
wait until the page source contains the given text.

Response:
def wait_until_page_source_contains(self, text, timeout=None):
        """
        Waits for the page source to contain <text>

        @type text:             str
        @param text:            the text to search for
        @type timeout:          int
        @param timeout:         the maximum number of seconds the driver will wait before timing out

        @rtype:                 webdriverwrapper.WebElementWrapper
        @return:                Returns the element found
        """
        timeout = timeout if timeout is not None else self.timeout

        def wait():
            '''
            Wait function passed to executor
            '''
            WebDriverWait(self.driver, timeout).until(lambda d: text in self.page_source())
            return self.page_source()

        return self.execute_and_handle_webdriver_exceptions(
            wait, timeout, text, 'Timeout waiting for source to contain: {}'.format(text))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def wait_until_jquery_requests_are_closed(self, timeout=None):
        timeout = timeout if timeout is not None else self.timeout

        def wait():
            '''
            Wait function passed to executor
            '''
            WebDriverWait(self.driver, timeout).until(
                lambda d: self.js_executor.execute_template('isJqueryAjaxComplete', {}))
            return True

        return self.execute_and_handle_webdriver_exceptions(
            wait, timeout, None, 'Timeout waiting for all jQuery AJAX requests to close')

Response: Waits until all jQuery AJAX requests are closed


Instruction:
How would you explain what the following Python 3 function does
def execute_and_handle_webdriver_exceptions(self, function_to_execute, timeout=None, locator=None, failure_message=None):
        logger = logging.getLogger(__name__)
        try:
            val = function_to_execute()
            for cb in self.action_callbacks:
                cb.__call__(self)
            return val

        except TimeoutException:
            raise WebDriverTimeoutException.WebDriverTimeoutException(self, timeout, locator, failure_message)

        except httplib.BadStatusLine, e:
            logger.error('BadStatusLine error raised on WebDriver action (line: {}, args:{}, message: {})'.format(
                e.line,
                e.args,
                e.message
            ))
            raise

        except httplib.CannotSendRequest:
            logger.error('CannotSendRequest error raised on WebDriver action')
            raise

        except UnexpectedAlertPresentException:
            # NOTE: handling alerts in this way expects that WebDriver does not dismiss unexpected alerts. That
            # setting can be changed by modifying the unexpectedAlertBehaviour setting
            msg = '<failed to parse message from alert>'
            try:
                a = self.driver.switch_to_alert()
                msg = a.text
            except Exception, e:
                msg = '<error parsing alert due to {} (note: parsing ' \
                      'alert text expects "unexpectedAlertBehaviour" to be set to "ignore")>'.format(e)
                logger.critical(msg)
            finally:
                logger.error('Unexpected alert raised on a WebDriver action; alert message was: {}'.format(msg))
                raise UnexpectedAlertPresentException('Unexpected alert on page, alert message was: "{}"'.format(msg))

Response: Execute a function and handle any exceptions raised by the action callbacks.


Instruction:
Explain what the following Python 3 code does
def pause_and_wait_for_user(self, timeout=None, prompt_text='Click to resume (WebDriver is paused)'):
        timeout = timeout if timeout is not None else self.user_wait_timeout
        # Set the browser state paused
        self.paused = True

        def check_user_ready(driver):
            """Polls for the user to be "ready" (meaning they checked the checkbox) and the driver to be unpaused.
            If the checkbox is not displayed (e.g. user navigates the page), it will re-insert it into the page

            @type driver: WebDriverWrapper
            @param driver: Driver to execute
            @return: True if user is ready, false if not
            """
            if driver.paused:
                if driver.is_user_ready():
                    # User indicated they are ready; free the browser lock
                    driver.paused = False
                    return True
                else:
                    if not driver.is_present(Locator('css', '#webdriver-resume-radio', 'radio to unpause webdriver')):
                        # Display the prompt
                        pause_html = staticreader.read_html_file('webdriverpaused.html')\
                            .replace('\n', '')\
                            .replace('PROMPT_TEXT', prompt_text)
                        webdriver_style = staticreader.read_css_file('webdriverstyle.css').replace('\n', '')

                        # Insert the webdriver style
                        driver.js_executor.execute_template_and_return_result(
                            'injectCssTemplate.js',
                            {'css': webdriver_style})

                        # Insert the paused html
                        driver.js_executor.execute_template_and_return_result(
                            'injectHtmlTemplate.js',
                            {'selector': 'body', 'html': pause_html})
            return False

        self.wait_until(
            lambda: check_user_ready(self),
            timeout=timeout,
            failure_message='Webdriver actions were paused but did not receive the command to continue. '
                            'You must click the on-screen message to resume.'
        )

        # Remove all injected elements
        self.js_executor.execute_template_and_return_result(
            'deleteElementsTemplate.js',
            {'selector': '.webdriver-injected'}
        )

Response: Injects a radio button into the page and waits for the user to click it.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_browser_log(self, levels=None):
        logs = self.driver.get_log('browser')
        self.browser_logs += logs
        if levels is not None:
            logs = [entry for entry in logs if entry.get(u'level') in levels]
        return logs

Response: Gets the console log of the browser


Instruction:
Can you write a function in Python 3 where it
closes driver and kill all associated displays

Response:
def quit(self):
        """Close driver and kill all associated displays

        """
        # Kill the driver

        def _quit():
            try:
                self.driver.quit()
            except Exception, err_driver:
                os.kill(self.driver_pid, signal.SIGKILL)
                raise
            finally:
                # Kill the display for this driver window
                try:
                    if self.display:
                        self.display.stop()
                except Exception, err_display:
                    os.kill(self.display_pid, signal.SIGKILL)
                    raise
        return self.execute_and_handle_webdriver_exceptions(_quit)


Instruction:
How would you code a function in Python 3 to
visit the url checking for rr errors in the response

Response:
def visit(self, url=''):
        """Visit the url, checking for rr errors in the response

        @param url: URL
        @return: Visit result
        """
        result = super(CoyoteDriver, self).visit(url)
        source = self.page_source()
        return result


Instruction:
Here you have a function in Python 3, explain what it does
def load_config_vars(target_config, source_config):
    # Overwrite all attributes in config with new config
    for attr in dir(source_config):
        # skip all private class attrs
        if attr.startswith('_'):
            continue
        val = getattr(source_config, attr)
        if val is not None:
            setattr(target_config, attr, val)

Response: Loads all attributes from source config into target config


Instruction:
Write a Python 3 function that can
read all available config files and return a dict of all the config files.

Response:
def _readall(self):
        """Read configs from all available configs. It will read files in the following order:

            1.) Read all default settings:

                These are located under: `<project_root>/config/*/default.cfg`

            2.) Read the user's config settings:

                This is located on the path: `~/.aftrc`

            3.) Read all config files specified by the config string in the environment variable TEST_RUN_SETTING_CONFIG

                A config string such as "browser.headless,scripts.no_ssh" will read paths:

                    `<project_root>/config/browser/headless.cfg`
                    `<project_root>/config/scripts/no_ssh.cfg`

                OR a config string such as "<project_root>/config/browser/headless.cfg" will load that path directly
        """
        # First priority -- read all default configs
        config_path = os.path.dirname(__file__)
        config_defaults = [os.path.join(dirpath, f)
                           for dirpath, dirnames, files in os.walk(config_path)
                           for f in fnmatch.filter(files, 'default.cfg')]

        # Second priority -- read the user overrides
        user_config = os.path.expanduser('~/.aftrc')

        # Third priority -- read the environment variable overrides
        override_filenames = []
        if TEST_RUN_SETTING_CONFIG in os.environ:
            for test_config in os.environ[TEST_RUN_SETTING_CONFIG].split(','):
                if os.path.exists(test_config):             #is this a file path
                   override_filenames.append(test_config)
                elif "." in test_config and not test_config.endswith('.cfg'):                    #else it might be in xxxx.yyyy format
                    config_parts = test_config.split('.')
                    config_parts[-1]+='.cfg' #add file ext to last part, which should be file
                    filename = os.path.join(config_path, *config_parts)
                    override_filenames.append(filename)
                else:                                       #else unknown, might throw exception here
                    pass

        all_configs = config_defaults + [user_config] + override_filenames
        return self.parser.read(all_configs)


Instruction:
Given the following Python 3 function, write the documentation
def run_parallel(*functions):
    def target(fn):
        def wrapped(results_queue, error_queue, index):
            result = None
            try:
                result = fn()
            except Exception, e:  # Swallow errors or else the process will hang
                error_queue.put(e)
                warnings.warn('Exception raised in parallel threads: {}'.format(e))
            results_queue.put((index, result))
        return wrapped

    errors = Queue()
    queue = Queue()

    jobs = list()
    for i, function in enumerate(functions):
        jobs.append(Process(target=target(function), args=(queue, errors, i)))

    [job.start() for job in jobs]
    [job.join() for job in jobs]

    # Get the results in the queue and put them back in the order in which the function was specified in the args
    results = [queue.get() for _ in jobs]
    results = sorted(results, key=lambda x: x[0])

    if not errors.empty():
        error_list = list()
        while not errors.empty():
            error_list.append(errors.get())
        raise ErrorInProcessException('Exceptions raised in parallel threads: {}'.format(error_list), errors=error_list)
    return [r[1] for r in results]

Response: Runs a series of functions in parallel.


Instruction:
How would you implement a function in Python 3 that
returns an updated copy of the dictionary without modifying the original

Response:
def copy_and_update(dictionary, update):
    """Returns an updated copy of the dictionary without modifying the original"""
    newdict = dictionary.copy()
    newdict.update(update)
    return newdict


Instruction:
Here you have a function in Python 3, explain what it does
def get_static_directory():
    directory = templates_dir = os.path.join(os.path.dirname(__file__), 'static')
    return directory

Response: Retrieves the full path of the static directory


Instruction:
Can you create a Python 3 function that
reads the contents of an html file in the css directory

Response:
def read_html_file(filename):
    """Reads the contents of an html file in the css directory

    @return: Contents of the specified file
    """
    with open(os.path.join(get_static_directory(), 'html/{filename}'.format(filename=filename))) as f:
        contents = f.read()
    return contents


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

        # handle backwards compatibility to support new Locator class
        if isinstance(locator, loc.Locator):
            locator = '{by}={locator}'.format(by=locator.by, locator=locator.locator)

        locator_tuple = namedtuple('Locator', 'By value')

        if locator.count('=') > 0 and locator.count('css=') < 1:
            by = locator[:locator.find('=')].replace('_', ' ')
            value = locator[locator.find('=')+1:]
            return locator_tuple(by, value)
        else:  # assume default is css selector
            value = locator[locator.find('=')+1:]
            return locator_tuple('css selector', value)

Response: Parses a valid selenium By and value from a locator ; returns as a named tuple with properties By and Value


Instruction:
Here you have a function in Python 3, explain what it does
def find_by_locator(webdriver_or_element, locator, find_all_elements=False):
        # handle backwards compatibility to support new Locator class
        if isinstance(locator, loc.Locator):
            locator = '{by}={locator}'.format(by=locator.by, locator=locator.locator)

        # use the appropriate find method given the locator type;
        # locators should follow the convention "css=.class" or "xpath=//div"
        # if locator type is unspecified, it will default to css
        if (locator.count('css=') > 0  or locator.count('css_selector=')) and len(locator.split('=', 1)) > 1:
            if find_all_elements:
                return webdriver_or_element.find_elements_by_css_selector(locator.split('=', 1)[-1])
            else:
                return webdriver_or_element.find_element_by_css_selector(locator.split('=', 1)[-1])

        elif locator.count('id=') > 0 and len(locator.split('=')) > 1:
            if find_all_elements:
                return webdriver_or_element.find_elements_by_id(locator.split('=', 1)[-1])
            else:
                return webdriver_or_element.find_element_by_id(locator.split('=', 1)[-1])

        elif locator.count('xpath=') > 0 and len(locator.split('=')) > 1:
            if find_all_elements:
                return webdriver_or_element.find_elements_by_xpath(locator.split('=', 1)[-1])
            else:
                return webdriver_or_element.find_element_by_xpath(locator.split('=', 1)[-1])

        elif locator.count('class_name=') > 0 and len(locator.split('=')) > 1:
            if find_all_elements:
                return webdriver_or_element.find_elements_by_class_name(locator.split('=', 1)[-1])
            else:
                return webdriver_or_element.find_element_by_class_name(locator.split('=', 1)[-1])

        elif locator.count('link_text=') > 0 and len(locator.split('=')) > 1:
            if find_all_elements:
                return webdriver_or_element.find_elements_by_link_text(locator.split('=', 1)[-1])
            else:
                return webdriver_or_element.find_element_by_link_text(locator.split('=', 1)[-1])

        elif locator.count('partial_link_text=') > 0 and len(locator.split('=')) > 1:
            if find_all_elements:
                return webdriver_or_element.find_elements_by_partial_link_text(locator.split('=', 1)[-1])
            else:
                return webdriver_or_element.find_element_by_partial_link_text(locator.split('=', 1)[-1])

        elif locator.count('name=') > 0 and len(locator.split('=')) > 1:
            if find_all_elements:
                return webdriver_or_element.find_elements_by_name(locator.split('=', 1)[-1])
            else:
                return webdriver_or_element.find_element_by_name(locator.split('=', 1)[-1])

        elif locator.count('tag_name=') > 0 and len(locator.split('=')) > 1:
            if find_all_elements:
                return webdriver_or_element.find_elements_by_tag_name(locator.split('=', 1)[-1])
            else:
                return webdriver_or_element.find_element_by_tag_name(locator.split('=', 1)[-1])

        else:   # default to css
            if find_all_elements:
                return webdriver_or_element.find_elements_by_css_selector(locator)
            else:
                return webdriver_or_element.find_element_by_css_selector(locator)

Response: Locate an element using a given locator


Instruction:
Create a Python 3 function to
spin a given assertion function until it returns True.

Response:
def spin_assert(self, assertion, failure_message='Failed Assertion', timeout=None):
        """
        Asserts that assertion function passed to it will return True,
        trying every 'step' seconds until 'timeout' seconds have passed.
        """
        timeout = self.timeout if timeout is None else timeout
        time_spent = 0
        while time_spent < timeout:
            try:
                assert assertion() is True
                return True
            except AssertionError:
                pass
            sleep(self.step)
            time_spent += 1
        raise WebDriverAssertionException.WebDriverAssertionException(self.driver_wrapper, failure_message)


Instruction:
Given the following Python 3 function, write the documentation
def webdriver_assert(self, assertion, failure_message='Failed Assertion'):
        try:
            assert assertion() is True
        except AssertionError:
            raise WebDriverAssertionException.WebDriverAssertionException(self.driver_wrapper, failure_message)

        return True

Response: Assert the assertion and throw a WebDriverAssertionException


Instruction:
Implement a Python 3 function for
testing that a value is true for the current language.

Response:
def assert_true(self, value, failure_message='Expected value to be True, was: {}'):
        """
        Asserts that a value is true

        @type value:    bool
        @param value:   value to test for True
        """
        assertion = lambda: bool(value)
        self.webdriver_assert(assertion, unicode(failure_message).format(value))


Instruction:
Can you generate the documentation for the following Python 3 function
def assert_equals(self, actual_val, expected_val, failure_message='Expected values to be equal: "{}" and "{}"'):
        assertion = lambda: expected_val == actual_val
        self.webdriver_assert(assertion, unicode(failure_message).format(actual_val, expected_val))

Response: Calls smart_assert but creates a closure that calls it with the expected and provided values with the == operator.


Instruction:
Create a Python 3 function to
test that two numbers are within an allowed delta of each other.

Response:
def assert_numbers_almost_equal(self, actual_val, expected_val, allowed_delta=0.0001,
                                    failure_message='Expected numbers to be within {} of each other: "{}" and "{}"'):
        """
        Asserts that two numbers are within an allowed delta of each other
        """
        assertion = lambda: abs(expected_val - actual_val) <= allowed_delta
        self.webdriver_assert(assertion, unicode(failure_message).format(allowed_delta, actual_val, expected_val))


Instruction:
Write a Python 3 script for
calling smart_assert but creates a closure that does not compare the expected and provided values.

Response:
def assert_not_equal(self, actual_val, unexpected_val, failure_message='Expected values to differ: "{}" and "{}"'):
        """
        Calls smart_assert, but creates its own assertion closure using
        the expected and provided values with the '!=' operator
        """
        assertion = lambda: unexpected_val != actual_val
        self.webdriver_assert(assertion, unicode(failure_message).format(actual_val, unexpected_val))


Instruction:
Explain what the following Python 3 code does
def assert_is(self, actual_val, expected_type, failure_message='Expected type to be "{1}," but was "{0}"'):
        assertion = lambda: expected_type is actual_val
        self.webdriver_assert(assertion, unicode(failure_message).format(actual_val, expected_type))

Response: Calls smart_assert but creates a closure that calls it with the expected and provided values with the is operator.


Instruction:
How would you code a function in Python 3 to
call smart_assert but creates a closure that calls it with the expected and provided values with the is not operator.

Response:
def assert_is_not(self, actual_val, unexpected_type,
                      failure_message='Expected type not to be "{1}," but was "{0}"'):
        """
        Calls smart_assert, but creates its own assertion closure using
        the expected and provided values with the 'is not' operator
        """
        assertion = lambda: unexpected_type is not actual_val
        self.webdriver_assert(assertion, unicode(failure_message).format(actual_val, unexpected_type))


Instruction:
Can you tell what is the following Python 3 function doing
def assert_in(self, actual_collection_or_string, expected_value, failure_message='Expected "{1}" to be in "{0}"'):
        assertion = lambda: expected_value in actual_collection_or_string
        self.webdriver_assert(assertion, unicode(failure_message).format(actual_collection_or_string, expected_value))

Response: Calls smart_assert but creates a closure that calls smart_assert with the expected and provided values with the in operator


Instruction:
Implement a Python 3 function for
calling smart_assert but creates a closure that calls smart_assert with the expected and provided values with the not in operator

Response:
def assert_not_in(self, actual_collection_or_string, unexpected_value,
                      failure_message='Expected "{1}" not to be in "{0}"'):
        """
        Calls smart_assert, but creates its own assertion closure using
        the expected and provided values with the 'not in' operator
        """
        assertion = lambda: unexpected_value not in actual_collection_or_string
        self.webdriver_assert(assertion, unicode(failure_message).format(actual_collection_or_string, unexpected_value))


Instruction:
Implement a function in Python 3 to
test that the page source contains the string passed in expected_value

Response:
def assert_page_source_contains(self, expected_value, failure_message='Expected page source to contain: "{}"'):
        """
        Asserts that the page source contains the string passed in expected_value
        """
        assertion = lambda: expected_value in self.driver_wrapper.page_source()
        self.webdriver_assert(assertion, unicode(failure_message).format(expected_value))


Instruction:
Make a summary of the following Python 3 code
def assert_union(self, collection1, collection2,
                     failure_message='Expected overlap between collections: "{}" and "{}"'):
        """
        Asserts that the union of two sets has at least one member (collections share at least one member)
        """
        assertion = lambda: len(collection1 or collection2) > 0
        failure_message = unicode(failure_message).format(collection1, collection2)
        self.webdriver_assert(assertion, failure_message)

Response: Assert that the union of two collections is not empty