Instruction:
Can you tell what is the following Python 3 function doing
def set_memory_limits(self, rss_soft=None, rss_hard=None):
        self._set('cheaper-rss-limit-soft', rss_soft)
        self._set('cheaper-rss-limit-hard', rss_hard)

        return self._section

Response: Sets worker memory limits for cheapening.


Instruction:
Write a Python 3 script to
return uWSGI version string or tuple.

Response:
def get_version(self, as_tuple=False):
        """Returns uWSGI version string or tuple.

        :param bool as_tuple:

        :rtype: str|tuple
        """
        if as_tuple:
            return uwsgi.version_info

        return decode(uwsgi.version)


Instruction:
Can you implement a function in Python 3 that
registers a routing rule.

Response:
def register_route(self, route_rules, label=None):
        """Registers a routing rule.

        :param RouteRule|list[RouteRule] route_rules:

        :param str|unicode label: Label to mark the given set of rules.
            This can be used in conjunction with ``do_goto`` rule action.

            * http://uwsgi.readthedocs.io/en/latest/InternalRouting.html#goto

        """
        route_rules = listify(route_rules)

        if route_rules and label:
            self._set(route_rules[0].command_label, label, multi=True)

        for route_rules in route_rules:
            self._set(route_rules.command, route_rules.value, multi=True)

        return self._section


Instruction:
Write a Python 3 script for
adding an error page for managed 403 404 500 response.

Response:
def set_error_page(self, status, html_fpath):
        """Add an error page (html) for managed 403, 404, 500 response.

        :param int status: HTTP status code.

        :param str|unicode html_fpath: HTML page file path.

        """
        statuses = [403, 404, 500]

        status = int(status)

        if status not in statuses:
            raise ConfigurationError(
                'Code `%s` for `routing.set_error_page()` is unsupported. Supported: %s' %
                (status, ', '.join(map(str, statuses))))

        self._set('error-page-%s' % status, html_fpath, multi=True)

        return self._section


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_error_pages(self, codes_map=None, common_prefix=None):
        statuses = [403, 404, 500]

        if common_prefix:
            if not codes_map:
                codes_map = {code: '%s.html' % code for code in statuses}

            for code, filename in codes_map.items():
                codes_map[code] = os.path.join(common_prefix, filename)

        for code, filepath in codes_map.items():
            self.set_error_page(code, filepath)

        return self._section

Response: Add an error page for all HTTP status codes.


Instruction:
Here you have a function in Python 3, explain what it does
def set_geoip_params(self, db_country=None, db_city=None):
        self._set('geoip-country', db_country, plugin='geoip')
        self._set('geoip-city', db_city, plugin='geoip')

        return self._section

Response:
Sets GeoIP parameters.

        * http://uwsgi.readthedocs.io/en/latest/GeoIP.html

        :param str|unicode db_country: Country database file path.

        :param str|unicode db_city: City database file path. Example: ``GeoLiteCity.dat``.


Instruction:
Make a summary of the following Python 3 code
def header_collect(self, name, target_var, pull=False):
        self._set(
            'pull-header' if pull else 'collect-header',
            '%s %s' % (name, target_var), multi=True)

        return self._section

Response:
Store the specified response header in a request var
       .


Instruction:
How would you implement a function in Python 3 that
allows mapping mountpoint to a static file or file.

Response:
def register_static_map(self, mountpoint, target, retain_resource_path=False, safe_target=False):
        """Allows mapping mountpoint to a static directory (or file).

        * http://uwsgi.readthedocs.io/en/latest/StaticFiles.html#mode-3-using-static-file-mount-points

        :param str|unicode mountpoint:

        :param str|unicode target:

        :param bool retain_resource_path: Append the requested resource to the docroot.

            Example: if ``/images`` maps to ``/var/www/img`` requested ``/images/logo.png`` will be served from:

            * ``True``: ``/var/www/img/images/logo.png``

            * ``False``: ``/var/www/img/logo.png``

        :param bool safe_target: Skip security checks if the file is under the specified path.

            Whether to consider resolved (real) target a safe one to serve from.

            * http://uwsgi.readthedocs.io/en/latest/StaticFiles.html#security

        """
        command = 'static-map'

        if retain_resource_path:

            command += '2'

        self._set(command, '%s=%s' % (mountpoint, target), multi=True)

        if safe_target:
            self._set('static-safe', target, multi=True)

        return self._section


Instruction:
Make a summary of the following Python 3 code
def add_expiration_rule(self, criterion, value, timeout, use_mod_time=False):
        command = 'static-expires'
        separator = ' '

        if criterion != self.expiration_criteria.FILENAME:

            command += '-%s' % criterion

        if criterion == self.expiration_criteria.MIME_TYPE:

            separator = '='

        if use_mod_time:

            command += '-mtime'

        for value in listify(value):
            self._set(command, '%s%s%s' % (value, separator, timeout), multi=True)

        return self._section

Response: Adds a statics expiration rule based on a criterion.


Instruction:
Can you generate the documentation for the following Python 3 function
def set_paths_caching_params(self, timeout=None, cache_name=None):
        self._set('static-cache-paths', timeout)
        self._set('static-cache-paths-name', cache_name)

        return self._section

Response: Sets the static - cache - paths and static - cache - paths - name parameters for the uWSGI cache.


Instruction:
How would you code a function in Python 3 to
set common socket params.

Response:
def set_socket_params(
            self, send_timeout=None, keep_alive=None, no_defer_accept=None,
            buffer_send=None, buffer_receive=None):
        """Sets common socket params.

        :param int send_timeout: Send (write) timeout in seconds.

        :param bool keep_alive: Enable TCP KEEPALIVEs.

        :param bool no_defer_accept: Disable deferred ``accept()`` on sockets
            by default (where available) uWSGI will defer the accept() of requests until some data
            is sent by the client (this is a security/performance measure).
            If you want to disable this feature for some reason, specify this option.

        :param int buffer_send: Set SO_SNDBUF (bytes).

        :param int buffer_receive: Set SO_RCVBUF (bytes).

        """
        self._set('so-send-timeout', send_timeout)
        self._set('so-keepalive', keep_alive, cast=bool)
        self._set('no-defer-accept', no_defer_accept, cast=bool)
        self._set('socket-sndbuf', buffer_send)
        self._set('socket-rcvbuf', buffer_receive)

        return self._section


Instruction:
Create a Python 3 function to
set the Unix - socket related params.

Response:
def set_unix_socket_params(self, abstract=None, permissions=None, owner=None, umask=None):
        """Sets Unix-socket related params.

        :param bool abstract: Force UNIX socket into abstract mode (Linux only).

        :param str permissions: UNIX sockets are filesystem objects that obey
            UNIX permissions like any other filesystem object.

            You can set the UNIX sockets' permissions with this option if your webserver
            would otherwise have no access to the uWSGI socket. When used without a parameter,
            the permissions will be set to 666. Otherwise the specified chmod value will be used.

        :param str|unicode owner: Chown UNIX sockets.

        :param str|unicode umask: Set UNIX socket umask.

        """
        self._set('abstract-socket', abstract, cast=bool)
        self._set('chmod-socket', permissions)
        self._set('chown-socket', owner)
        self._set('umask', umask)

        return self._section


Instruction:
Implement a Python 3 function for
setting BSD - socket related params.

Response:
def set_bsd_socket_params(self, port_reuse=None):
        """Sets BSD-sockets related params.

        :param bool port_reuse: Enable REUSE_PORT flag on socket to allow multiple
            instances binding on the same address (BSD only).

        """
        self._set('reuse-port', port_reuse, cast=bool)

        return self._section


Instruction:
Write a Python 3 script for
registering the given socket for further use.

Response:
def register_socket(self, socket):
        """Registers the given socket(s) for further use.

        :param Socket|list[Socket] socket: Socket type object. See ``.sockets``.

        """
        sockets = self._sockets

        for socket in listify(socket):

            uses_shared = isinstance(socket.address, SocketShared)

            if uses_shared:
                # Handling shared sockets involves socket index resolution.

                shared_socket = socket.address  # type: SocketShared

                if shared_socket not in sockets:
                    self.register_socket(shared_socket)

                socket.address = self._get_shared_socket_idx(shared_socket)

            socket.address = self._section.replace_placeholders(socket.address)
            self._set(socket.name, socket, multi=True)

            socket._contribute_to_opts(self)

            bound_workers = socket.bound_workers

            if bound_workers:
                self._set(
                    'map-socket', '%s:%s' % (len(sockets), ','.join(map(str, bound_workers))),
                    multi=True)

            if not uses_shared:
                sockets.append(socket)

        return self._section


Instruction:
Implement a Python 3 function for
allowing setting server name identification params.

Response:
def set_sni_params(self, name, cert, key, ciphers=None, client_ca=None, wildcard=False):
        """Allows setting Server Name Identification (virtual hosting for SSL nodes) params.

        * http://uwsgi.readthedocs.io/en/latest/SNI.html

        :param str|unicode name: Node/server/host name.

        :param str|unicode cert: Certificate file.

        :param str|unicode key: Private key file.

        :param str|unicode ciphers: Ciphers [alias] string.

            Example:
                * DEFAULT
                * HIGH
                * DHE, EDH

            * https://www.openssl.org/docs/man1.1.0/apps/ciphers.html

        :param str|unicode client_ca: Client CA file for client-based auth.

            .. note: You can prepend ! (exclamation mark) to make client certificate
                authentication mandatory.

        :param bool wildcard: Allow regular expressions in ``name`` (used for wildcard certificates).

        """
        command = 'sni'

        if wildcard:
            command += '-regexp'

        args = [item for item in (cert, key, ciphers, client_ca) if item is not None]

        self._set(command, '%s %s' % (name, ','.join(args)))

        return self._section


Instruction:
How would you code a function in Python 3 to
enable checking for cert key client ca file in the specified directory and create a sni ssl context on demand.

Response:
def set_sni_dir_params(self, dir, ciphers=None):
        """Enable checking for cert/key/client_ca file in the specified directory
        and create a sni/ssl context on demand.

        Expected filenames:
            * <sni-name>.crt
            * <sni-name>.key
            * <sni-name>.ca - this file is optional

        * http://uwsgi.readthedocs.io/en/latest/SNI.html#massive-sni-hosting

        :param str|unicode dir:

        :param str|unicode ciphers: Ciphers [alias] string.

            Example:
                * DEFAULT
                * HIGH
                * DHE, EDH

            * https://www.openssl.org/docs/man1.1.0/apps/ciphers.html

        """
        self._set('sni-dir', dir)
        self._set('sni-dir-ciphers', ciphers)

        return self._section


Instruction:
How would you implement a function in Python 3 that
enables the shared queue of the given size.

Response:
def enable(self, size, block_size=None, store=None, store_sync_interval=None):
        """Enables shared queue of the given size.

        :param int size: Queue size.

        :param int block_size: Block size in bytes. Default: 8 KiB.

        :param str|unicode store: Persist the queue into file.

        :param int store_sync_interval: Store sync interval in master cycles (usually seconds).

        """
        self._set('queue', size)
        self._set('queue-blocksize', block_size)
        self._set('queue-store', store)
        self._set('queue-store-sync', store_sync_interval)

        return self._section


Instruction:
Create a Python 3 function for
setting basic parameters for the resource store.

Response:
def set_basic_params(self, count=None, thunder_lock=None, lock_engine=None):
        """
        :param int count: Create the specified number of shared locks.

        :param bool thunder_lock: Serialize accept() usage (if possible)
            Could improve performance on Linux with robust pthread mutexes.

            http://uwsgi.readthedocs.io/en/latest/articles/SerializingAccept.html

        :param str|unicode lock_engine: Set the lock engine.

            Example:
                - ipcsem

        """
        self._set('thunder-lock', thunder_lock, cast=bool)
        self._set('lock-engine', lock_engine)
        self._set('locks', count)

        return self._section


Instruction:
Can you generate the documentation for the following Python 3 function
def set_ipcsem_params(self, ftok=None, persistent=None):
        self._set('ftok', ftok)
        self._set('persistent-ipcsem', persistent, cast=bool)

        return self._section

Response: Sets the ipcsem lock engine params.


Instruction:
How would you explain what the following Python 3 function does
def lock_file(self, fpath, after_setup=False, wait=False):
        command = 'flock-wait' if wait else 'flock'

        if after_setup:
            command = '%s2' % command

        self._set(command, fpath)

        return self._section

Response: Locks the specified file.


Instruction:
Here you have a function in Python 3, explain what it does
def register_rpc(name=None):
    def wrapper(func):
        func_name = func.__name__
        rpc_name = name or func_name

        uwsgi.register_rpc(rpc_name, func)

        _LOG.debug("Registering '%s' for RPC under '%s' alias ...", func_name, rpc_name)

        return func

    return wrapper

Response: Decorator. Allows registering a function for RPC.


Instruction:
How would you explain what the following Python 3 function does
def make_rpc_call(func_name, args=None, remote=None):
    args = args or []
    args = [encode(str(arg)) for arg in args]

    if remote:
        result = uwsgi.rpc(remote, func_name, *args)
    else:
        result = uwsgi.call(func_name, *args)

    return decode(result)

Response: Performs an RPC function call with the given arguments.


Instruction:
Here you have a function in Python 3, explain what it does
def set_emperor_command_params(
            self, command_socket=None,
            wait_for_command=None, wait_for_command_exclude=None):
        """Emperor commands related parameters.

        * http://uwsgi-docs.readthedocs.io/en/latest/tutorials/EmperorSubscriptions.html

        :param str|unicode command_socket: Enable the Emperor command socket.
            It is a channel allowing external process to govern vassals.

        :param bool wait_for_command: Always wait for a 'spawn' Emperor command before starting a vassal.

        :param str|unicode|list[str|unicode] wait_for_command_exclude: Vassals that will ignore ``wait_for_command``.

        """
        self._set('emperor-command-socket', command_socket)
        self._set('emperor-wait-for-command', wait_for_command, cast=bool)
        self._set('emperor-wait-for-command-ignore', wait_for_command_exclude, multi=True)

        return self._section

Response: Sets the Emperor command related parameters.


Instruction:
Can you implement a function in Python 3 that
sets the emperor - wrapper and emperor - wrapper - overrides parameters for vassals.

Response:
def set_vassals_wrapper_params(self, wrapper=None, overrides=None, fallbacks=None):
        """Binary wrapper for vassals parameters.

        :param str|unicode wrapper: Set a binary wrapper for vassals.

        :param str|unicode|list[str|unicode] overrides: Set a binary wrapper for vassals to try before the default one

        :param str|unicode|list[str|unicode] fallbacks: Set a binary wrapper for vassals to try as a last resort.
            Allows you to specify an alternative binary to execute when running a vassal
            and the default binary_path is not found (or returns an error).

        """
        self._set('emperor-wrapper', wrapper)
        self._set('emperor-wrapper-override', overrides, multi=True)
        self._set('emperor-wrapper-fallback', fallbacks, multi=True)

        return self._section


Instruction:
Make a summary of the following Python 3 code
def set_throttle_params(self, level=None, level_max=None):
        self._set('emperor-throttle', level)
        self._set('emperor-max-throttle', level_max)

        return self._section

Response:
Throttling options.

        * http://uwsgi-docs.readthedocs.io/en/latest/Emperor.html#throttling
        * http://uwsgi-docs.readthedocs.io/en/latest/Emperor.html#loyalty

        :param int level: Set throttling level (in milliseconds) for bad behaving vassals. Default: 1000.

        :param int level_max: Set maximum throttling level (in milliseconds)
            for bad behaving vassals. Default: 3 minutes.


Instruction:
How would you implement a function in Python 3 that
sets the emperor - tyrant - nofollow and emperor - tyrant - initgroups attributes.

Response:
def set_mode_tyrant_params(self, enable=None, links_no_follow=None, use_initgroups=None):
        """Tyrant mode (secure multi-user hosting).

        In Tyrant mode the Emperor will run the vassal using the UID/GID of the vassal
        configuration file.

        * http://uwsgi-docs.readthedocs.io/en/latest/Emperor.html#tyrant-mode-secure-multi-user-hosting

        :param enable: Puts the Emperor in Tyrant mode.

        :param bool links_no_follow: Do not follow symlinks when checking for uid/gid in Tyrant mode.

        :param bool use_initgroups: Add additional groups set via initgroups() in Tyrant mode.

        """
        self._set('emperor-tyrant', enable, cast=bool)
        self._set('emperor-tyrant-nofollow', links_no_follow, cast=bool)
        self._set('emperor-tyrant-initgroups', use_initgroups, cast=bool)

        return self._section


Instruction:
Create a Python 3 function to
set the mode to Broodlord.

Response:
def set_mode_broodlord_params(
            self, zerg_count=None,
            vassal_overload_sos_interval=None, vassal_queue_items_sos=None):
        """This mode is a way for a vassal to ask for reinforcements to the Emperor.

        Reinforcements are new vassals spawned on demand generally bound on the same socket.

        .. warning:: If you are looking for a way to dynamically adapt the number
            of workers of an instance, check the Cheaper subsystem - adaptive process spawning mode.

            *Broodlord mode is for spawning totally new instances.*

        :param int zerg_count: Maximum number of zergs to spawn.

        :param int vassal_overload_sos_interval: Ask emperor for reinforcement when overloaded.
            Accepts the number of seconds to wait between asking for a new reinforcements.

        :param int vassal_queue_items_sos: Ask emperor for sos if listen queue (backlog) has more
            items than the value specified

        """
        self._set('emperor-broodlord', zerg_count)
        self._set('vassal-sos', vassal_overload_sos_interval)
        self._set('vassal-sos-backlog', vassal_queue_items_sos)

        return self._section


Instruction:
Here you have a function in Python 3, explain what it does
def run_command_as_worker(self, command, after_post_fork_hook=False):
        self._set('worker-exec2' if after_post_fork_hook else 'worker-exec', command, multi=True)

        return self._section

Response: Run the specified command as worker.


Instruction:
Can you implement a function in Python 3 that
sets the count of available workers by default sets it to detected number of available cores.

Response:
def set_count_auto(self, count=None):
        """Sets workers count.

        By default sets it to detected number of available cores

        :param int count:
        """
        count = count or self._section.vars.CPU_CORES

        self._set('workers', count)

        return self._section


Instruction:
Implement a Python 3 function for
setting the threads related params.

Response:
def set_thread_params(
            self, enable=None, count=None, count_offload=None, stack_size=None, no_wait=None):
        """Sets threads related params.

        :param bool enable: Enable threads in the embedded languages.
            This will allow to spawn threads in your app.

            .. warning:: Threads will simply *not work* if this option is not enabled.
                There will likely be no error, just no execution of your thread code.

        :param int count: Run each worker in prethreaded mode with the specified number
            of threads per worker.

            .. warning:: Do not use with ``gevent``.

            .. note:: Enables threads automatically.

        :param int count_offload: Set the number of threads (per-worker) to spawn
            for offloading. Default: 0.

            These threads run such tasks in a non-blocking/evented way allowing
            for a huge amount of concurrency. Various components of the uWSGI stack
            are offload-friendly.

            .. note:: Try to set it to the number of CPU cores to take advantage of SMP.

            * http://uwsgi-docs.readthedocs.io/en/latest/OffloadSubsystem.html

        :param int stack_size: Set threads stacksize.

        :param bool no_wait: Do not wait for threads cancellation on quit/reload.

        """
        self._set('enable-threads', enable, cast=bool)
        self._set('no-threads-wait', no_wait, cast=bool)
        self._set('threads', count)
        self._set('offload-threads', count_offload)

        if count:
            self._section.print_out('Threads per worker: %s' % count)

        self._set('threads-stacksize', stack_size)

        return self._section


Instruction:
How would you code a function in Python 3 to
set the mules related params.

Response:
def set_mules_params(
            self, mules=None, touch_reload=None, harakiri_timeout=None, farms=None, reload_mercy=None,
            msg_buffer=None, msg_buffer_recv=None):
        """Sets mules related params.

        http://uwsgi.readthedocs.io/en/latest/Mules.html

        Mules are worker processes living in the uWSGI stack but not reachable via socket connections,
        that can be used as a generic subsystem to offload tasks.

        :param int|list mules: Add the specified mules or number of mules.

        :param str|list touch_reload: Reload mules if the specified file is modified/touched.

        :param int harakiri_timeout: Set harakiri timeout for mule tasks.

        :param list[MuleFarm] farms: Mule farms list.

            Examples:
                * cls_mule_farm('first', 2)
                * cls_mule_farm('first', [4, 5])

        :param int reload_mercy: Set the maximum time (in seconds) a mule can take
            to reload/shutdown. Default: 60.

        :param int msg_buffer: Set mule message buffer size (bytes) given
            for mule message queue.

        :param int msg_buffer: Set mule message recv buffer size (bytes).

        """
        farms = farms or []

        next_mule_number = 1
        farm_mules_count = 0

        for farm in farms:

            if isinstance(farm.mule_numbers, int):
                farm.mule_numbers = list(range(next_mule_number, next_mule_number + farm.mule_numbers))
                next_mule_number = farm.mule_numbers[-1] + 1

            farm_mules_count += len(farm.mule_numbers)

            self._set('farm', farm, multi=True)

        if mules is None and farm_mules_count:
            mules = farm_mules_count

        if isinstance(mules, int):
            self._set('mules', mules)

        elif isinstance(mules, list):

            for mule in mules:
                self._set('mule', mule, multi=True)

        self._set('touch-mules-reload', touch_reload, multi=True)

        self._set('mule-harakiri', harakiri_timeout)
        self._set('mule-reload-mercy', reload_mercy)

        self._set('mule-msg-size', msg_buffer)
        self._set('mule-msg-recv-size', msg_buffer_recv)

        return self._section


Instruction:
Implement a function in Python 3 to
set the reload parameters for the specified worker.

Response:
def set_reload_params(
            self, min_lifetime=None, max_lifetime=None,
            max_requests=None, max_requests_delta=None,
            max_addr_space=None, max_rss=None, max_uss=None, max_pss=None,
            max_addr_space_forced=None, max_rss_forced=None, watch_interval_forced=None,
            mercy=None):
        """Sets workers reload parameters.

        :param int min_lifetime: A worker cannot be destroyed/reloaded unless it has been alive
            for N seconds (default 60). This is an anti-fork-bomb measure.
            Since 1.9

        :param int max_lifetime: Reload workers after this many seconds. Disabled by default.
            Since 1.9

        :param int max_requests: Reload workers after the specified amount of managed
            requests (avoid memory leaks).
            When a worker reaches this number of requests it will get recycled (killed and restarted).
            You can use this option to "dumb fight" memory leaks.

            Also take a look at the ``reload-on-as`` and ``reload-on-rss`` options
            as they are more useful for memory leaks.

            .. warning:: The default min-worker-lifetime 60 seconds takes priority over `max-requests`.

            Do not use with benchmarking as you'll get stalls
            such as `worker respawning too fast !!! i have to sleep a bit (2 seconds)...`

        :param int max_requests_delta: Add (worker_id * delta) to the max_requests value of each worker.

        :param int max_addr_space: Reload a worker if its address space usage is higher
            than the specified value in megabytes.

        :param int max_rss: Reload a worker if its physical unshared memory (resident set size) is higher
            than the specified value (in megabytes).

        :param int max_uss: Reload a worker if Unique Set Size is higher
            than the specified value in megabytes.

            .. note:: Linux only.

        :param int max_pss: Reload a worker if Proportional Set Size is higher
            than the specified value in megabytes.

            .. note:: Linux only.

        :param int max_addr_space_forced: Force the master to reload a worker if its address space is higher
            than specified megabytes (in megabytes).

        :param int max_rss_forced: Force the master to reload a worker
            if its resident set size memory is higher than specified in megabytes.

        :param int watch_interval_forced: The memory collector [per-worker] thread memeory watch
            interval (seconds) used for forced reloads. Default: 3.

        :param int mercy: Set the maximum time (in seconds) a worker can take
            before reload/shutdown. Default: 60.

        """
        self._set('max-requests', max_requests)
        self._set('max-requests-delta', max_requests_delta)

        self._set('min-worker-lifetime', min_lifetime)
        self._set('max-worker-lifetime', max_lifetime)

        self._set('reload-on-as', max_addr_space)
        self._set('reload-on-rss', max_rss)
        self._set('reload-on-uss', max_uss)
        self._set('reload-on-pss', max_pss)

        self._set('evil-reload-on-as', max_addr_space_forced)
        self._set('evil-reload-on-rss', max_rss_forced)
        self._set('mem-collector-freq', watch_interval_forced)

        self._set('worker-reload-mercy', mercy)

        return self._section


Instruction:
Create a Python 3 function to
set the reload - on - exception parameters.

Response:
def set_reload_on_exception_params(self, do_reload=None, etype=None, evalue=None, erepr=None):
        """Sets workers reload on exceptions parameters.

        :param bool do_reload: Reload a worker when an exception is raised.

        :param str etype: Reload a worker when a specific exception type is raised.

        :param str evalue: Reload a worker when a specific exception value is raised.

        :param str erepr: Reload a worker when a specific exception type+value (language-specific) is raised.

        """
        self._set('reload-on-exception', do_reload, cast=bool)
        self._set('reload-on-exception-type', etype)
        self._set('reload-on-exception-value', evalue)
        self._set('reload-on-exception-repr', erepr)

        return self._section


Instruction:
Can you generate the documentation for the following Python 3 function
def set_harakiri_params(self, timeout=None, verbose=None, disable_for_arh=None):
        self._set('harakiri', timeout)
        self._set('harakiri-verbose', verbose, cast=bool)
        self._set('harakiri-no-arh', disable_for_arh, cast=bool)

        return self._section

Response: Sets the worker harakiri parameters.


Instruction:
Given the following Python 3 function, write the documentation
def set_zerg_server_params(self, socket, clients_socket_pool=None):
        if clients_socket_pool:
            self._set('zergpool', '%s:%s' % (socket, ','.join(listify(clients_socket_pool))), multi=True)

        else:
            self._set('zerg-server', socket)

        return self._section

Response: Sets the Zerg server params.


Instruction:
Can you create a Python 3 function that
sets the zerg client parameters.

Response:
def set_zerg_client_params(self, server_sockets, use_fallback_socket=None):
        """Zerg mode. Zergs params.

        :param str|unicode|list[str|unicode] server_sockets: Attaches zerg to a zerg server.

        :param bool use_fallback_socket: Fallback to normal sockets if the zerg server is not available

        """
        self._set('zerg', server_sockets, multi=True)

        if use_fallback_socket is not None:
            self._set('zerg-fallback', use_fallback_socket, cast=bool)

            for socket in listify(server_sockets):
                self._section.networking.register_socket(self._section.networking.sockets.default(socket))

        return self._section


Instruction:
Can you generate a brief explanation for the following Python 3 code
def format_print_text(text, color_fg=None, color_bg=None):
    from .config import Section

    color_fg = {

        'black': '30',
        'red': '31',
        'reder': '91',
        'green': '32',
        'greener': '92',
        'yellow': '33',
        'yellower': '93',
        'blue': '34',
        'bluer': '94',
        'magenta': '35',
        'magenter': '95',
        'cyan': '36',
        'cyaner': '96',
        'gray': '37',
        'grayer': '90',
        'white': '97',

    }.get(color_fg, '39')

    color_bg = {

        'black': '40',
        'red': '41',
        'reder': '101',
        'green': '42',
        'greener': '102',
        'yellow': '43',
        'yellower': '103',
        'blue': '44',
        'bluer': '104',
        'magenta': '45',
        'magenter': '105',
        'cyan': '46',
        'cyaner': '106',
        'gray': '47',
        'grayer': '100',
        'white': '107',

    }.get(color_bg, '49')

    mod = ';'.join([color_fg, color_bg])

    text = '%(esc)s[%(mod)sm%(value)s%(end)s' % {
        'esc': Section.vars.FORMAT_ESCAPE,
        'end': Section.vars.FORMAT_END,
        'mod': mod,
        'value': text,
    }

    return text

Response: Format given text using ANSI formatting escape sequences.


Instruction:
Here you have a function in Python 3, explain what it does
def iter_options(self):
        for section in self.sections:
            name = str(section)
            for key, value in section._get_options():
                yield name, key, value

Response: Iterates over the options of the configuration sections groups options.


Instruction:
Can you write a function in Python 3 where it
sets memory related parameters.

Response:
def set_memory_params(self, ksm_interval=None, no_swap=None):
        """Set memory related parameters.

        :param int ksm_interval: Kernel Samepage Merging frequency option, that can reduce memory usage.
            Accepts a number of requests (or master process cycles) to run page scanner after.

            .. note:: Linux only.

            * http://uwsgi.readthedocs.io/en/latest/KSM.html

        :param bool no_swap: Lock all memory pages avoiding swapping.

        """
        self._set('ksm', ksm_interval)
        self._set('never_swap', no_swap, cast=bool)

        return self._section


Instruction:
Write a Python 3 function that can
change the directory of the cache entry.

Response:
def change_dir(self, to, after_app_loading=False):
        """Chdir to specified directory before or after apps loading.

        :param str|unicode to: Target directory.

        :param bool after_app_loading:
                *True* - after load
                *False* - before load

        """
        self._set('chdir2' if after_app_loading else 'chdir', to)

        return self._section


Instruction:
Here you have a function in Python 3, explain what it does
def set_owner_params(self, uid=None, gid=None, add_gids=None, set_asap=False):
        prefix = 'immediate-' if set_asap else ''

        self._set(prefix + 'uid', uid)
        self._set(prefix + 'gid', gid)
        self._set('add-gid', add_gids, multi=True)

        # This may be wrong for subsequent method calls.
        self.owner = [uid, gid]

        return self._section

Response: Set process owner params.


Instruction:
How would you explain what the following Python 3 function does
def get_owner(self, default=True):
        uid, gid = self.owner

        if not uid and default:
            uid = os.getuid()

        if not gid and default:
            gid = os.getgid()

        return uid, gid

Response: Return the owner and group IDs of the current user.


Instruction:
Write a Python 3 function for
allowing setting hooks for various uWSGI phases.

Response:
def set_hook(self, phase, action):
        """Allows setting hooks (attaching actions) for various uWSGI phases.

        :param str|unicode phase: See constants in ``.phases``.

        :param str|unicode|list|HookAction|list[HookAction] action:

        """
        self._set('hook-%s' % phase, action, multi=True)

        return self._section


Instruction:
Here you have a function in Python 3, explain what it does
def set_hook_touch(self, fpath, action):
        self._set('hook-touch', '%s %s' % (fpath, action), multi=True)

        return self._section

Response: Allows running certain action when the specified file is touched.


Instruction:
Explain what the following Python 3 code does
def set_hook_after_request(self, func):
        self._set('after-request-hook', func, multi=True)

        return self._section

Response: Set the function to be run after each request.


Instruction:
Can you generate the documentation for the following Python 3 function
def set_on_exit_params(self, skip_hooks=None, skip_teardown=None):
        self._set('skip-atexit', skip_hooks, cast=bool)
        self._set('skip-atexit-teardown', skip_teardown, cast=bool)

        return self._section

Response: Sets the params related to process exit procedure.


Instruction:
How would you code a function in Python 3 to
run a given command on a given phase.

Response:
def run_command_on_event(self, command, phase=phases.ASAP):
        """Run the given command on a given phase.

        :param str|unicode command:

        :param str|unicode phase: See constants in ``Phases`` class.

        """
        self._set('exec-%s' % phase, command, multi=True)

        return self._section


Instruction:
How would you code a function in Python 3 to
run command when the specified file is modified or touched.

Response:
def run_command_on_touch(self, command, target):
        """Run command when the specified file is modified/touched.

        :param str|unicode command:

        :param str|unicode target: File path.

        """
        self._set('touch-exec', '%s %s' % (target, command), multi=True)

        return self._section


Instruction:
Write a Python 3 function for
creating a pidfile before or after privileges drop.

Response:
def set_pid_file(self, fpath, before_priv_drop=True, safe=False):
        """Creates pidfile before or after privileges drop.

        :param str|unicode fpath: File path.

        :param bool before_priv_drop: Whether to create pidfile before privileges are dropped.

            .. note:: Vacuum is made after privileges drop, so it may not be able
                to delete PID file if it was created before dropping.

        :param bool safe: The safe-pidfile works similar to pidfile
            but performs the write a little later in the loading process.
            This avoids overwriting the value when app loading fails,
            with the consequent loss of a valid PID number.

        """
        command = 'pidfile'

        if not before_priv_drop:
            command += '2'

        if safe:
            command = 'safe-' + command

        self._set(command, fpath)

        return self._section


Instruction:
Make a summary of the following Python 3 code
def set_naming_params(self, autonaming=None, prefix=None, suffix=None, name=None):
        self._set('auto-procname', autonaming, cast=bool)
        self._set('procname-prefix%s' % ('-spaced' if prefix and prefix.endswith(' ') else ''), prefix)
        self._set('procname-append', suffix)
        self._set('procname', name)

        return self._section

Response: Sets the processes naming parameters.


Instruction:
Explain what the following Python 3 code does
def errorprint():
    try:
        yield

    except ConfigurationError as e:
        click.secho('%s' % e, err=True, fg='red')
        sys.exit(1)

Response: Print out descriptions from ConfigurationError.


Instruction:
How would you explain what the following Python 3 function does
def run(conf, only):
    with errorprint():
        config = ConfModule(conf)
        spawned = config.spawn_uwsgi(only)

        for alias, pid in spawned:
            click.secho("Spawned uWSGI for configuration aliased '%s'. PID %s" % (alias, pid), fg='green')

Response: Runs uWSGI passing to it using the default or another uwsgiconf configuration module.


Instruction:
Write a Python 3 function for
compiling classic uWSGI configuration file using the default or given uwsgiconf configuration module.

Response:
def compile(conf):
    """Compiles classic uWSGI configuration file using the default
    or given `uwsgiconf` configuration module.

    """
    with errorprint():
        config = ConfModule(conf)
        for conf in config.configurations:
            conf.format(do_print=True)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def sysinit(systype, conf, project):

    click.secho(get_config(
        systype,
        conf=ConfModule(conf).configurations[0],
        conf_path=conf,
        project_name=project,
    ))

Response: Outputs configuration for system initialization subsystem.


Instruction:
Make a summary of the following Python 3 code
def probe_plugins():
    plugins = UwsgiRunner().get_plugins()

    for plugin in sorted(plugins.generic):
        click.secho(plugin)

    click.secho('')

    for plugin in sorted(plugins.request):
        click.secho(plugin)

Response: Runs uWSGI to determine what plugins are available.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add(self, work_dir, external=False):
        command = 'spooler'

        if external:
            command += '-external'

        self._set(command, self._section.replace_placeholders(work_dir), multi=True)

        return self._section

Response: Run a spooler on the specified directory.


Instruction:
Write a Python 3 function that can
configure broodlord mode and returns emperor and zerg sections.

Response:
def configure(self):
        """Configures broodlord mode and returns emperor and zerg sections.

        :rtype: tuple
        """
        section_emperor = self.section_emperor
        section_zerg = self.section_zerg

        socket = self.socket

        section_emperor.workers.set_zerg_server_params(socket=socket)
        section_emperor.empire.set_emperor_params(vassals_home=self.vassals_home)
        section_emperor.empire.set_mode_broodlord_params(**self.broodlord_params)

        section_zerg.name = 'zerg'
        section_zerg.workers.set_zerg_client_params(server_sockets=socket)

        if self.die_on_idle:
            section_zerg.master_process.set_idle_params(timeout=30, exit=True)

        return section_emperor, section_zerg


Instruction:
Explain what the following Python 3 code does
def get_log_format_default(self):
        vars = self.logging.vars

        format_default = (
            '[pid: %s|app: %s|req: %s/%s] %s (%s) {%s vars in %s bytes} [%s] %s %s => '
            'generated %s bytes in %s %s%s(%s %s) %s headers in %s bytes (%s switches on core %s)' % (

                vars.WORKER_PID,
                '-',  # app id
                '-',  # app req count
                '-',  # worker req count
                vars.REQ_REMOTE_ADDR,
                vars.REQ_REMOTE_USER,
                vars.REQ_COUNT_VARS_CGI,
                vars.SIZE_PACKET_UWSGI,
                vars.REQ_START_CTIME,
                vars.REQ_METHOD,
                vars.REQ_URI,
                vars.RESP_SIZE_BODY,
                vars.RESP_TIME_MS,  # or RESP_TIME_US,
                '-',  # tsize
                '-',  # via sendfile/route/offload
                vars.REQ_SERVER_PROTOCOL,
                vars.RESP_STATUS,
                vars.RESP_COUNT_HEADERS,
                vars.RESP_SIZE_HEADERS,
                vars.ASYNC_SWITCHES,
                vars.CORE,
        ))

        return format_default

Response: Returns default log message format.


Instruction:
Explain what the following Python 3 code does
def configure_owner(self, owner='www-data'):
        if owner is not None:
            self.main_process.set_owner_params(uid=owner, gid=owner)

        return self

Response: Shortcut to set process owner data.


Instruction:
Can you tell what is the following Python 3 function doing
def set_basic_params(self, msg_size=None, cheap=None, anti_loop_timeout=None):
        self._set('alarm-msg-size', msg_size)
        self._set('alarm-cheap', cheap, cast=bool)
        self._set('alarm-freq', anti_loop_timeout)

        return self._section

Response: Set basic alarm parameters.


Instruction:
Can you implement a function in Python 3 that
registers (create) an alarm. :param AlarmType|list[AlarmType] alarm: Alarm.

Response:
def register_alarm(self, alarm):
        """Register (create) an alarm.

        :param AlarmType|list[AlarmType] alarm: Alarm.

        """
        for alarm in listify(alarm):
            if alarm not in self._alarms:
                self._set('alarm', alarm, multi=True)
                self._alarms.append(alarm)

        return self._section


Instruction:
Explain what the following Python 3 code does
def alarm_on_log(self, alarm, matcher, skip=False):
        self.register_alarm(alarm)

        value = '%s %s' % (
            ','.join(map(attrgetter('alias'), listify(alarm))),
            matcher)

        self._set('not-alarm-log' if skip else 'alarm-log', value)

        return self._section

Response: Raise or skip the specified alarm when a log line matches the specified regexp.


Instruction:
Explain what the following Python 3 code does
def alarm_on_fd_ready(self, alarm, fd, message, byte_count=None):
        self.register_alarm(alarm)

        value = fd

        if byte_count:
            value += ':%s' % byte_count

        value += ' %s' % message

        for alarm in listify(alarm):
            self._set('alarm-fd', '%s %s' % (alarm.alias, value), multi=True)

        return self._section

Response: Triggers the alarm when the specified file descriptor is ready for read.


Instruction:
Given the following Python 3 function, write the documentation
def alarm_on_segfault(self, alarm):
        self.register_alarm(alarm)

        for alarm in listify(alarm):
            self._set('alarm-segfault', alarm.alias, multi=True)

        return self._section

Response: Raise the specified alarm when segmentation fault handler is executed.


Instruction:
How would you explain what the following Python 3 function does
def get_config(systype, conf, conf_path, runner=None, project_name=None):
    runner = runner or ('%s run' % Finder.uwsgiconf())
    conf_path = abspath(conf_path)

    if isinstance(conf, Configuration):
        conf = conf.sections[0]  # todo Maybe something more intelligent.

    tpl = dedent(TEMPLATES.get(systype)(conf=conf))

    formatted = tpl.strip().format(
        project=project_name or conf.project_name or basename(dirname(conf_path)),
        command='%s %s' % (runner, conf_path),
    )

    return formatted

Response: Returns the contents of a configuration file.


Instruction:
Given the following Python 3 function, write the documentation
def app_2(env, start_response):

    import random

    start_response('200 OK', [('Content-Type','text/html')])

    data = [
        '
uwsgiconf demo: one file second app
',

        '
Some random number for you: %s
' % random.randint(1, 99999),
    ]

    return encode(data)

Response: This is another simple WSGI application that will be served by uWSGI.


Instruction:
Given the following Python 3 function, write the documentation
def configure():
    import os
    from uwsgiconf.presets.nice import PythonSection

    FILE = os.path.abspath(__file__)
    port = 8000

    configurations = []

    for idx in range(2):

        alias = 'app_%s' % (idx + 1)

        section = PythonSection(
            # Automatically reload uWSGI if this file is changed.
            touch_reload=FILE,

            # To differentiate easily.
            process_prefix=alias,

            # Serve WSGI application (see above) from this very file.
            wsgi_module=FILE,

            # Custom WSGI callable for second app.
            wsgi_callable=alias,

            # One is just enough, no use in worker on every core
            # for this demo.
            workers=1,

        ).networking.register_socket(
            PythonSection.networking.sockets.http('127.0.0.1:%s' % port)
        )

        port += 1

        configurations.append(
            # We give alias for configuration to prevent clashes.
            section.as_configuration(alias=alias))

    return configurations

Response:
Configure uWSGI.

    This returns several configuration objects, which will be used
    to spawn several uWSGI processes.

    Applications are on 127.0.0.1 on ports starting from 8000.


Instruction:
Given the following Python 3 function, write the documentation
def headers_raw_to_dict(headers_raw):

    if headers_raw is None:
        return None
    headers = headers_raw.splitlines()
    headers_tuples = [header.split(b':', 1) for header in headers]

    result_dict = {}
    for header_item in headers_tuples:
        if not len(header_item) == 2:
            continue

        item_key = header_item[0].strip()
        item_value = header_item[1].strip()
        result_dict[item_key] = item_value

    return result_dict

Response: r Convert raw headers to a dictionary.


Instruction:
How would you code a function in Python 3 to
log the current state of the entry into the specified target.

Response:
def log_into(self, target, before_priv_drop=True):
        """Simple file or UDP logging.

        .. note:: This doesn't require any Logger plugin and can be used
            if no log routing is required.

        :param str|unicode target: Filepath or UDP address.

        :param bool before_priv_drop: Whether to log data before or after privileges drop.

        """
        command = 'logto'

        if not before_priv_drop:
            command += '2'

        self._set(command, target)

        return self._section


Instruction:
Here you have a function in Python 3, explain what it does
def set_file_params(
            self, reopen_on_reload=None, trucate_on_statup=None, max_size=None, rotation_fname=None,
            touch_reopen=None, touch_rotate=None, owner=None, mode=None):
        """Set various parameters related to file logging.

        :param bool reopen_on_reload: Reopen log after reload.

        :param bool trucate_on_statup: Truncate log on startup.

        :param int max_size: Set maximum logfile size in bytes after which log should be rotated.

        :param str|unicode rotation_fname: Set log file name after rotation.

        :param str|unicode|list touch_reopen: Trigger log reopen if the specified file
            is modified/touched.

            .. note:: This can be set to a file touched by ``postrotate`` script of ``logrotate``
                to implement rotation.

        :param str|unicode|list touch_rotate: Trigger log rotation if the specified file
            is modified/touched.

        :param str|unicode owner: Set owner chown() for logs.

        :param str|unicode mode: Set mode chmod() for logs.

        """
        self._set('log-reopen', reopen_on_reload, cast=bool)
        self._set('log-truncate', trucate_on_statup, cast=bool)
        self._set('log-maxsize', max_size)
        self._set('log-backupname', rotation_fname)

        self._set('touch-logreopen', touch_reopen, multi=True)
        self._set('touch-logrotate', touch_rotate, multi=True)

        self._set('logfile-chown', owner)
        self._set('logfile-chmod', mode)

        return self._section

Response: Set various parameters related to file logging.


Instruction:
Write a Python 3 function for
setting various log data filters.

Response:
def set_filters(self, include=None, exclude=None, write_errors=None, write_errors_tolerance=None, sigpipe=None):
        """Set various log data filters.

        :param str|unicode|list include: Show only log lines matching the specified regexp.

            .. note:: Requires enabled PCRE support.

        :param str|unicode|list exclude: Do not show log lines matching the specified regexp.

            .. note:: Requires enabled PCRE support.

        :param bool write_errors: Log (annoying) write()/writev() errors. Default: ``True``.

            .. note:: If both this and ``sigpipe`` set to ``False``, it's the same
               as setting ``write-errors-exception-only`` uWSGI option.

        :param int write_errors_tolerance: Set the maximum number of allowed write errors before exception
            is raised. Default: no tolerance.

            .. note:: Available for Python, Perl, PHP.

        :param bool sigpipe: Log (annoying) SIGPIPE. Default: ``True``.

            .. note:: If both this and ``write_errors`` set to ``False``, it's the same
               as setting ``write-errors-exception-only`` uWSGI option.

        """
        if write_errors is not None:
            self._set('ignore-write-errors', not write_errors, cast=bool)

        if sigpipe is not None:
            self._set('ignore-sigpipe', not sigpipe, cast=bool)

        self._set('write-errors-tolerance', write_errors_tolerance)

        for line in listify(include):
            self._set('log-filter', line, multi=True)

        for line in listify(exclude):
            self._set('log-drain', line, multi=True)

        return self._section


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_requests_filters(
            self, slower=None, bigger=None, status_4xx=None, status_5xx=None,
            no_body=None, sendfile=None, io_errors=None):
        """Set various log data filters.

        :param int slower: Log requests slower than the specified number of milliseconds.

        :param int bigger: Log requests bigger than the specified size in bytes.

        :param status_4xx: Log requests with a 4xx response.

        :param status_5xx: Log requests with a 5xx response.

        :param bool no_body: Log responses without body.

        :param bool sendfile: Log sendfile requests.

        :param bool io_errors: Log requests with io errors.

        """
        self._set('log-slow', slower)
        self._set('log-big', bigger)
        self._set('log-4xx', status_4xx, cast=bool)
        self._set('log-5xx', status_5xx, cast=bool)
        self._set('log-zero', no_body, cast=bool)
        self._set('log-sendfile', sendfile, cast=bool)
        self._set('log-ioerror', io_errors, cast=bool)

        return self._section

Response: Set various log data filters.


Instruction:
Write a Python 3 script for
setting logging params for delegating logging to master process.

Response:
def set_master_logging_params(
            self, enable=None, dedicate_thread=None, buffer=None,
            sock_stream=None, sock_stream_requests_only=None):
        """Sets logging params for delegating logging to master process.

        :param bool enable: Delegate logging to master process.
            Delegate the write of the logs to the master process
            (this will put all of the logging I/O to a single process).
            Useful for system with advanced I/O schedulers/elevators.

        :param bool dedicate_thread: Delegate log writing to a thread.

            As error situations could cause the master to block while writing
            a log line to a remote server, it may be a good idea to use this option and delegate
            writes to a secondary thread.

        :param int buffer: Set the buffer size for the master logger in bytes.
            Bigger log messages will be truncated.

        :param bool|tuple sock_stream: Create the master logpipe as SOCK_STREAM.

        :param bool|tuple sock_stream_requests_only: Create the master requests logpipe as SOCK_STREAM.

        """
        self._set('log-master', enable, cast=bool)
        self._set('threaded-logger', dedicate_thread, cast=bool)
        self._set('log-master-bufsize', buffer)

        self._set('log-master-stream', sock_stream, cast=bool)

        if sock_stream_requests_only:
            self._set('log-master-req-stream', sock_stream_requests_only, cast=bool)

        return self._section


Instruction:
Create a Python 3 function to
set or add a common logger or a request requests only.

Response:
def add_logger(self, logger, requests_only=False, for_single_worker=False):
        """Set/add a common logger or a request requests only.

        :param str|unicode|list|Logger|list[Logger] logger:

        :param bool requests_only: Logger used only for requests information messages.

        :param bool for_single_worker: Logger to be used in single-worker setup.

        """
        if for_single_worker:
            command = 'worker-logger-req' if requests_only else 'worker-logger'
        else:
            command = 'req-logger' if requests_only else 'logger'

        for logger in listify(logger):
            self._set(command, logger, multi=True)

        return self._section


Instruction:
Write a Python 3 function for
logging to the specified named logger if regexp applied on log item matches.

Response:
def add_logger_route(self, logger, matcher, requests_only=False):
        """Log to the specified named logger if regexp applied on log item matches.

        :param str|unicode|list|Logger|list[Logger] logger: Logger to associate route with.

        :param str|unicode matcher: Regular expression to apply to log item.

        :param bool requests_only: Matching should be used only for requests information messages.

        """
        command = 'log-req-route' if requests_only else 'log-route'

        for logger in listify(logger):
            self._set(command, '%s %s' % (logger, matcher), multi=True)

        return self._section


Instruction:
Can you generate the documentation for the following Python 3 function
def add_logger_encoder(self, encoder, logger=None, requests_only=False, for_single_worker=False):
        if for_single_worker:
            command = 'worker-log-req-encoder' if requests_only else 'worker-log-encoder'
        else:
            command = 'log-req-encoder' if requests_only else 'log-encoder'

        for encoder in listify(encoder):

            value = '%s' % encoder

            if logger:
                if isinstance(logger, Logger):
                    logger = logger.alias

                value += ':%s' % logger

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

        return self._section

Response: Add an item to the log encoder or request encoder chain.


Instruction:
Create a Python 3 function for
returning the compiler type from distutils.

Response:
def _compiler_type():
    """
    Gets the compiler type from distutils. On Windows with MSVC it will be
    "msvc". On macOS and linux it is "unix".

    Borrowed from https://github.com/pyca/cryptography/blob\
        /05b34433fccdc2fec0bb014c3668068169d769fd/src/_cffi_src/utils.py#L78
    """
    dist = distutils.dist.Distribution()
    dist.parse_config_files()
    cmd = dist.get_command_obj('build')
    cmd.ensure_finalized()
    compiler = distutils.ccompiler.new_compiler(compiler=cmd.compiler)
    return compiler.compiler_type


Instruction:
Given the following Python 3 function, write the documentation
def set_metrics_params(self, enable=None, store_dir=None, restore=None, no_cores=None):
        self._set('enable-metrics', enable, cast=bool)
        self._set('metrics-dir', self._section.replace_placeholders(store_dir))
        self._set('metrics-dir-restore', restore, cast=bool)
        self._set('metrics-no-cores', no_cores, cast=bool)

        return self._section

Response: Sets basic Metrics subsystem params.


Instruction:
Write a Python 3 script for
setting the metric threshold parameter.

Response:
def set_metrics_threshold(self, name, value, check_interval=None, reset_to=None, alarm=None, alarm_message=None):
        """Sets metric threshold parameters.

        :param str|unicode name: Metric name.

        :param int value: Threshold value.

        :param int reset_to: Reset value to when threshold is reached.

        :param int check_interval: Threshold check interval in seconds.

        :param str|unicode|AlarmType alarm: Alarm to trigger when threshold is reached.

        :param str|unicode alarm_message: Message to pass to alarm. If not set metrics name is passed.

        """
        if alarm is not None and isinstance(alarm, AlarmType):
            self._section.alarms.register_alarm(alarm)
            alarm = alarm.alias

        value = KeyValue(
            locals(),
            aliases={
                'name': 'key',
                'reset_to': 'reset',
                'check_interval': 'rate',
                'alarm_message': 'msg',
            },
        )

        self._set('metric-threshold', value, multi=True)

        return self._section


Instruction:
Make a summary of the following Python 3 code
def set_stats_params(
            self, address=None, enable_http=None,
            minify=None, no_cores=None, no_metrics=None, push_interval=None):
        """Enables stats server on the specified address.

        * http://uwsgi.readthedocs.io/en/latest/StatsServer.html

        :param str|unicode address: Address/socket to make stats available on.

            Examples:
                * 127.0.0.1:1717
                * /tmp/statsock
                * :5050

        :param bool enable_http: Server stats over HTTP.
            Prefixes stats server json output with http headers.

        :param bool minify: Minify statistics json output.

        :param bool no_cores: Disable generation of cores-related stats.

        :param bool no_metrics: Do not include metrics in stats output.

        :param int push_interval: Set the default frequency of stats pushers in seconds/

        """
        self._set('stats-server', address)
        self._set('stats-http', enable_http, cast=bool)
        self._set('stats-minified', minify, cast=bool)
        self._set('stats-no-cores', no_cores, cast=bool)
        self._set('stats-no-metrics', no_metrics, cast=bool)
        self._set('stats-pusher-default-freq', push_interval)

        return self._section

Response: Enables stats server on the specified address.


Instruction:
Can you create a Python 3 function that
registers a pusher to be used for pushing statistics to various remotes / locals.

Response:
def register_stats_pusher(self, pusher):
        """Registers a pusher to be used for pushing statistics to various remotes/locals.

        :param Pusher|list[Pusher] pusher:

        """
        for pusher in listify(pusher):
            self._set('stats-push', pusher, multi=True)

        return self._section


Instruction:
Make a summary of the following Python 3 code
def enable_snmp(self, address, community_string):
        self._set('snmp', address)
        self._set('snmp-community', community_string)

        return self._section

Response:
Enables SNMP.

        uWSGI server embeds a tiny SNMP server that you can use to integrate
        your web apps with your monitoring infrastructure.

        * http://uwsgi.readthedocs.io/en/latest/SNMP.html

        .. note:: SNMP server is started in the master process after dropping the privileges.
            If you want it to listen on a privileged port, you can either use Capabilities on Linux,
            or use the ``as-root`` option to run the master process as root.

        :param str|unicode address: UDP address to bind to.

            Examples:

                * 192.168.1.1:2222

        :param str|unicode community_string: SNMP instance identifier to address it.


Instruction:
Can you create a Python 3 function that
mounts application under mountpoint.

Response:
def mount(self, mountpoint, app, into_worker=False):
        """Load application under mountpoint.

        Example:
            * .mount('', 'app0.py') -- Root URL part
            * .mount('/app1', 'app1.py') -- URL part
            * .mount('/pinax/here', '/var/www/pinax/deploy/pinax.wsgi')
            * .mount('the_app3', 'app3.py')  -- Variable value: application alias (can be set by ``UWSGI_APPID``)
            * .mount('example.com', 'app2.py')  -- Variable value: Hostname (variable set in nginx)

        * http://uwsgi-docs.readthedocs.io/en/latest/Nginx.html#hosting-multiple-apps-in-the-same-process-aka-managing-script-name-and-path-info

        :param str|unicode mountpoint: URL part, or variable value.

            .. note:: In case of URL part you may also want to set ``manage_script_name`` basic param to ``True``.

            .. warning:: In case of URL part a trailing slash may case problems in some cases
                (e.g. with Django based projects).

        :param str|unicode app: App module/file.

        :param bool into_worker: Load application under mountpoint
            in the specified worker or after workers spawn.

        """
        # todo check worker mount -- uwsgi_init_worker_mount_app() expects worker://
        self._set('worker-mount' if into_worker else 'mount', '%s=%s' % (mountpoint, app), multi=True)

        return self._section


Instruction:
Given the following Python 3 function, write the documentation
def switch_into_lazy_mode(self, affect_master=None):
        self._set('lazy' if affect_master else 'lazy-apps', True, cast=bool)

        return self._section

Response: Switches uWSGI to lazy mode.


Instruction:
Explain what the following Python 3 code does
def set_basic_params(
            self, workers=None, zerg_server=None, fallback_node=None, concurrent_events=None,
            cheap_mode=None, stats_server=None, quiet=None, buffer_size=None,
            keepalive=None, resubscribe_addresses=None):
        """
        :param int workers: Number of worker processes to spawn.

        :param str|unicode zerg_server: Attach the router to a zerg server.

        :param str|unicode fallback_node: Fallback to the specified node in case of error.

        :param int concurrent_events: Set the maximum number of concurrent events router can manage.

            Default: system dependent.

        :param bool cheap_mode: Enables cheap mode. When the router is in cheap mode,
            it will not respond to requests until a node is available.
            This means that when there are no nodes subscribed, only your local app (if any) will respond.
            When all of the nodes go down, the router will return in cheap mode.

        :param str|unicode stats_server: Router stats server address to run at.

        :param bool quiet: Do not report failed connections to instances.

        :param int buffer_size: Set internal buffer size in bytes. Default: page size.

        :param int keepalive: Allows holding the connection open even if the request has a body.

            * http://uwsgi.readthedocs.io/en/latest/HTTP.html#http-keep-alive

            .. note:: See http11 socket type for an alternative.

        :param str|unicode|list[str|unicode] resubscribe_addresses: Forward subscriptions
            to the specified subscription server.

        """
        super(RouterHttp, self).set_basic_params(**filter_locals(locals(), drop=[
            'keepalive',
            'resubscribe_addresses',
        ]))

        self._set_aliased('keepalive', keepalive)
        self._set_aliased('resubscribe', resubscribe_addresses, multi=True)

        return self

Response: Sets basic HTTP parameters for the router.


Instruction:
Make a summary of the following Python 3 code
def set_connections_params(
            self, harakiri=None, timeout_socket=None, retry_delay=None, timeout_headers=None, timeout_backend=None):
        """Sets connection-related parameters.

        :param int harakiri: Set gateway harakiri timeout (seconds).

        :param int timeout_socket: Node socket timeout (seconds).
            Used to set the SPDY timeout. This is the maximum amount of inactivity after
            the SPDY connection is closed.

            Default: 60.

        :param int retry_delay: Retry connections to dead static nodes after the specified
            amount of seconds. Default: 30.

        :param int timeout_headers: Defines the timeout (seconds) while waiting for http headers.

            Default: `socket_timeout`.

        :param int timeout_backend: Defines the timeout (seconds) when connecting to backend instances.

            Default: `socket_timeout`.

        """

        super(RouterHttp, self).set_connections_params(
            **filter_locals(locals(), ['timeout_headers', 'timeout_backend']))

        self._set_aliased('headers-timeout', timeout_headers)
        self._set_aliased('connect-timeout', timeout_backend)

        return self

Response: Sets connection - related parameters.


Instruction:
Explain what the following Python 3 code does
def set_manage_params(
            self, chunked_input=None, chunked_output=None, gzip=None, websockets=None, source_method=None,
            rtsp=None, proxy_protocol=None):
        """Allows enabling various automatic management mechanics.

        * http://uwsgi.readthedocs.io/en/latest/Changelog-1.9.html#http-router-keepalive-auto-chunking-auto-gzip-and-transparent-websockets

        :param bool chunked_input: Automatically detect chunked input requests and put the session in raw mode.

        :param bool chunked_output: Automatically transform output to chunked encoding
            during HTTP 1.1 keepalive (if needed).

        :param bool gzip: Automatically gzip content if uWSGI-Encoding header is set to gzip,
            but content size (Content-Length/Transfer-Encoding) and Content-Encoding are not specified.

        :param bool websockets: Automatically detect websockets connections and put the session in raw mode.

        :param bool source_method: Automatically put the session in raw mode for `SOURCE` HTTP method.

            * http://uwsgi.readthedocs.io/en/latest/Changelog-2.0.5.html#icecast2-protocol-helpers

        :param bool rtsp: Allow the HTTP router to detect RTSP and chunked requests automatically.

        :param bool proxy_protocol: Allows the HTTP router to manage PROXY1 protocol requests,
            such as those made by Haproxy or Amazon Elastic Load Balancer (ELB).

        """
        self._set_aliased('chunked-input', chunked_input, cast=bool)
        self._set_aliased('auto-chunked', chunked_output, cast=bool)
        self._set_aliased('auto-gzip', gzip, cast=bool)
        self._set_aliased('websockets', websockets, cast=bool)
        self._set_aliased('manage-source', source_method, cast=bool)
        self._set_aliased('manage-rtsp', rtsp, cast=bool)
        self._set_aliased('enable-proxy-protocol', proxy_protocol, cast=bool)

        return self

Response: Allows enabling automatic management mechanics.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_owner_params(self, uid=None, gid=None):
        self._set_aliased('uid', uid)
        self._set_aliased('gid', gid)

        return self

Response: Drop http router privileges to specified user and group.


Instruction:
Given the following Python 3 function, write the documentation
def set_connections_params(self, harakiri=None, timeout_socket=None, retry_delay=None, retry_max=None):
        super(RouterSsl, self).set_connections_params(**filter_locals(locals(), ['retry_max']))

        self._set_aliased('max-retries', retry_max)

        return self

Response: Sets connection - related parameters.


Instruction:
Can you tell what is the following Python 3 function doing
def set_basic_params(
            self, workers=None, zerg_server=None, fallback_node=None, concurrent_events=None,
            cheap_mode=None, stats_server=None, quiet=None, buffer_size=None,
            fallback_nokey=None, subscription_key=None, emperor_command_socket=None):
        """
        :param int workers: Number of worker processes to spawn.

        :param str|unicode zerg_server: Attach the router to a zerg server.

        :param str|unicode fallback_node: Fallback to the specified node in case of error.

        :param int concurrent_events: Set the maximum number of concurrent events router can manage.

            Default: system dependent.

        :param bool cheap_mode: Enables cheap mode. When the router is in cheap mode,
            it will not respond to requests until a node is available.
            This means that when there are no nodes subscribed, only your local app (if any) will respond.
            When all of the nodes go down, the router will return in cheap mode.

        :param str|unicode stats_server: Router stats server address to run at.

        :param bool quiet: Do not report failed connections to instances.

        :param int buffer_size: Set internal buffer size in bytes. Default: page size.

        :param bool fallback_nokey: Move to fallback node even if a subscription key is not found.

        :param str|unicode subscription_key: Skip uwsgi parsing and directly set a key.

        :param str|unicode emperor_command_socket: Set the emperor command socket that will receive spawn commands.

            See `.empire.set_emperor_command_params()`.

        """
        super(RouterFast, self).set_basic_params(**filter_locals(locals(), [
            'fallback_nokey',
            'subscription_key',
            'emperor_command_socket',
        ]))

        self._set_aliased('fallback-on-no-key', fallback_nokey, cast=bool)
        self._set_aliased('force-key', subscription_key)
        self._set_aliased('emperor-socket', emperor_command_socket)

        return self

Response: Set basic parameters for router.


Instruction:
Given the following Python 3 function, write the documentation
def set_resubscription_params(self, addresses=None, bind_to=None):
        self._set_aliased('resubscribe', addresses, multi=True)
        self._set_aliased('resubscribe-bind', bind_to)

        return self

Response: Set the parameters for the subscription server to be forwarded to.


Instruction:
How would you explain what the following Python 3 function does
def set_connections_params(self, harakiri=None, timeout_socket=None, retry_delay=None, retry_max=None, defer=None):
        super(RouterFast, self).set_connections_params(**filter_locals(locals(), ['retry_max', 'defer']))

        self._set_aliased('max-retries', retry_max)
        self._set_aliased('defer-connect-timeout', defer)

        return self

Response: Sets connection - related parameters.


Instruction:
Create a Python 3 function for
setting the post - buffering params for the current HTTP request.

Response:
def set_postbuffering_params(self, size=None, store_dir=None):
        """Sets buffering params.

        Web-proxies like nginx are "buffered", so they wait til the whole request (and its body)
        has been read, and then it sends it to the backends.

        :param int size: The size (in bytes) of the request body after which the body will
            be stored to disk (as a temporary file) instead of memory.

        :param str|unicode store_dir: Put buffered files to the specified directory. Default: TMPDIR, /tmp/

        """
        self._set_aliased('post-buffering', size)
        self._set_aliased('post-buffering-dir', store_dir)

        return self


Instruction:
Implement a function in Python 3 to
set connection - related parameters.

Response:
def set_connections_params(
            self, harakiri=None, timeout_socket=None, retry_delay=None, retry_max=None, use_xclient=None):
        """Sets connection-related parameters.

        :param int harakiri:  Set gateway harakiri timeout (seconds).

        :param int timeout_socket: Node socket timeout (seconds). Default: 60.

        :param int retry_delay: Retry connections to dead static nodes after the specified
            amount of seconds. Default: 30.

        :param int retry_max: Maximum number of retries/fallbacks to other nodes. Default: 3.

        :param bool use_xclient: Use the xclient protocol to pass the client address.

        """
        super(RouterRaw, self).set_connections_params(**filter_locals(locals(), ['retry_max', 'use_xclient']))

        self._set_aliased('max-retries', retry_max)
        self._set_aliased('xclient', use_xclient)

        return self


Instruction:
Explain what the following Python 3 code does
def set_connections_params(self, harakiri=None, timeout_socket=None):
        self._set_aliased('harakiri', harakiri)
        self._set_aliased('timeout', timeout_socket)

        return self

Response: Sets connection - related parameters.


Instruction:
Can you write a function in Python 3 where it
sets pty window params.

Response:
def set_window_params(self, cols=None, rows=None):
        """Sets pty window params.

        :param int cols:
        :param int rows:

        """
        self._set_aliased('cols', cols)
        self._set_aliased('rows', rows)

        return self


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_basic_params(self, use_credentials=None, stats_server=None):
        self._set_aliased('use-credentials', use_credentials)
        self._set_aliased('router-stats', stats_server)

        return self

Response: Set basic parameters for the current session.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def register_route(self, src, dst, gateway):
        self._set_aliased('router-route', ' '.join((src, dst, gateway)), multi=True)

        return self

Response: Adds a routing rule to the tuntap router.


Instruction:
How would you code a function in Python 3 to
add a tuntap device rule.

Response:
def device_add_rule(self, direction, action, src, dst, target=None):
        """Adds a tuntap device rule.

        To be used in a vassal.

        :param str|unicode direction: Direction:

            * in
            * out.

        :param str|unicode action: Action:

            * allow
            * deny
            * route
            * gateway.

        :param str|unicode src: Source/mask.

        :param str|unicode dst: Destination/mask.

        :param str|unicode target: Depends on action.

            * Route / Gateway: Accept addr:port

        """
        value = [direction, src, dst, action]

        if target:
            value.append(target)

        self._set_aliased('device-rule', ' '.join(value), multi=True)

        return self


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_firewall_rule(self, direction, action, src=None, dst=None):
        value = [action]

        if src:
            value.extend((src, dst))

        self._set_aliased('router-firewall-%s' % direction.lower(), ' '.join(value), multi=True)

        return self

Response: Adds a firewall rule to the router.


Instruction:
Write a Python 3 function for
allowing configuring uWSGI using a function which returns a list of Configuration objects.

Response:
def configure_uwsgi(configurator_func):
    """Allows configuring uWSGI using Configuration objects returned
    by the given configuration function.

    .. code-block: python

        # In configuration module, e.g `uwsgicfg.py`

        from uwsgiconf.config import configure_uwsgi

        configure_uwsgi(get_configurations)

    :param callable configurator_func: Function which return a list on configurations.

    :rtype: list|None

    :returns: A list with detected configurations or
        ``None`` if called from within uWSGI (e.g. when trying to load WSGI application).

    :raises ConfigurationError:

    """
    from .settings import ENV_CONF_READY, ENV_CONF_ALIAS, CONFIGS_MODULE_ATTR

    if os.environ.get(ENV_CONF_READY):
        # This call is from uWSGI trying to load an application.

        # We prevent unnecessary configuration
        # for setups where application is located in the same
        # file as configuration.

        del os.environ[ENV_CONF_READY]  # Drop it support consecutive reconfiguration.

        return None

    configurations = configurator_func()
    registry = OrderedDict()

    if not isinstance(configurations, (list, tuple)):
        configurations = [configurations]

    for conf_candidate in configurations:
        if not isinstance(conf_candidate, (Section, Configuration)):
            continue

        if isinstance(conf_candidate, Section):
            conf_candidate = conf_candidate.as_configuration()

        alias = conf_candidate.alias

        if alias in registry:
            raise ConfigurationError(
                "Configuration alias '%s' clashes with another configuration. "
                "Please change the alias." % alias)

        registry[alias] = conf_candidate

    if not registry:
        raise ConfigurationError(
            "Callable passed into 'configure_uwsgi' must return 'Section' or 'Configuration' objects.")

    # Try to get configuration alias from env with fall back
    # to --conf argument (as passed by UwsgiRunner.spawn()).
    target_alias = os.environ.get(ENV_CONF_ALIAS)

    if not target_alias:
        last = sys.argv[-2:]
        if len(last) == 2 and last[0] == '--conf':
            target_alias = last[1]

    conf_list = list(registry.values())

    if target_alias:
        # This call is [presumably] from uWSGI configuration read procedure.
        config = registry.get(target_alias)

        if config:
            section = config.sections[0]  # type: Section
            # Set ready marker which is checked above.
            os.environ[ENV_CONF_READY] = '1'

            # Placeholder for runtime introspection.
            section.set_placeholder('config-alias', target_alias)

            # Print out
            config.print_ini()

    else:
        # This call is from module containing uWSGI configurations.
        import inspect

        # Set module attribute automatically.
        config_module = inspect.currentframe().f_back
        config_module.f_locals[CONFIGS_MODULE_ATTR] = conf_list

    return conf_list


Instruction:
Can you generate a brief explanation for the following Python 3 code
def replace_placeholders(self, value):
        if not value:
            return value

        is_list = isinstance(value, list)
        values = []

        for value in listify(value):
            runtime_dir = self.get_runtime_dir()
            project_name = self.project_name

            value = value.replace('{runtime_dir}', runtime_dir)
            value = value.replace('{project_name}', project_name)
            value = value.replace('{project_runtime_dir}', os.path.join(runtime_dir, project_name))

            values.append(value)

        value = values if is_list else values.pop()

        return value

Response: Replaces placeholders that can be used e. g. in filepaths.


Instruction:
How would you explain what the following Python 3 function does
def get_runtime_dir(self, default=True):
        dir_ = self._runtime_dir

        if not dir_ and default:
            uid = self.main_process.get_owner()[0]
            dir_ = '/run/user/%s/' % uid if uid else '/run/'

        return dir_

Response: Returns the directory where the runtime files are stored.


Instruction:
Make a summary of the following Python 3 code
def print_stamp(self):
        from . import VERSION

        print_out = partial(self.print_out, format_options='red')
        print_out('This configuration was automatically generated using')
        print_out('uwsgiconf v%s on %s' % ('.'.join(map(str, VERSION)), datetime.now().isoformat(' ')))

        return self

Response: Prints out a stamp containing useful information such as what and when has generated this configuration.


Instruction:
Can you write a function in Python 3 where it
prints out the given value.

Response:
def print_out(self, value, indent=None, format_options=None, asap=False):
        """Prints out the given value.

        :param value:

        :param str|unicode indent:

        :param dict|str|unicode format_options: text color

        :param bool asap: Print as soon as possible.

        """
        if indent is None:
            indent = '>   '

        text = indent + str(value)

        if format_options is None:
            format_options = 'gray'

        if self._style_prints and format_options:

            if not isinstance(format_options, dict):
                format_options = {'color_fg': format_options}

            text = format_print_text(text, **format_options)

        command = 'iprint' if asap else 'print'
        self._set(command, text, multi=True)

        return self


Instruction:
Can you generate a brief explanation for the following Python 3 code
def print_variables(self):
        print_out = partial(self.print_out, format_options='green')

        print_out('===== variables =====')

        for var, hint in self.vars.get_descriptions().items():
            print_out('    %' + var + ' = ' + var + ' = ' + hint.replace('%', '%%'))

        print_out('=====================')

        return self

Response:
Prints out magic variables available in config files
        alongside with their values and descriptions.


Instruction:
Write a Python 3 function for
setting plugin - related parameters.

Response:
def set_plugins_params(self, plugins=None, search_dirs=None, autoload=None, required=False):
        """Sets plugin-related parameters.

        :param list|str|unicode|OptionsGroup|list[OptionsGroup] plugins: uWSGI plugins to load

        :param list|str|unicode search_dirs: Directories to search for uWSGI plugins.

        :param bool autoload: Try to automatically load plugins when unknown options are found.

        :param bool required: Load uWSGI plugins and exit on error.

        """
        plugins = plugins or []

        command = 'need-plugin' if required else 'plugin'

        for plugin in listify(plugins):

            if plugin not in self._plugins:
                self._set(command, plugin, multi=True)
                self._plugins.append(plugin)

        self._set('plugins-dir', search_dirs, multi=True, priority=0)
        self._set('autoload', autoload, cast=bool)

        return self


Instruction:
Here you have a function in Python 3, explain what it does
def set_fallback(self, target):
        if isinstance(target, Section):
            target = ':' + target.name

        self._set('fallback-config', target)

        return self

Response: Sets a fallback configuration for section.


Instruction:
Can you implement a function in Python 3 that
sets a placeholder for the current locale.

Response:
def set_placeholder(self, key, value):
        """Placeholders are custom magic variables defined during configuration
        time.

        .. note:: These are accessible, like any uWSGI option, in your application code via
            ``.runtime.environ.uwsgi_env.config``.

        :param str|unicode key:

        :param str|unicode value:

        """
        self._set('set-placeholder', '%s=%s' % (key, value), multi=True)

        return self


Instruction:
Given the following Python 3 function, write the documentation
def env(self, key, value=None, unset=False, asap=False):
        if unset:
            self._set('unenv', key, multi=True)
        else:
            if value is None:
                value = os.environ.get(key)

            self._set('%senv' % ('i' if asap else ''), '%s=%s' % (key, value), multi=True)

        return self

Response:
Processes (sets/unsets) environment variable.

        If is not given in `set` mode value will be taken from current env.

        :param str|unicode key:

        :param value:

        :param bool unset: Whether to unset this variable.

        :param bool asap: If True env variable will be set as soon as possible.


Instruction:
Here you have a function in Python 3, explain what it does
def include(self, target):
        for target_ in listify(target):
            if isinstance(target_, Section):
                target_ = ':' + target_.name

            self._set('ini', target_, multi=True)

        return self

Response: Includes target contents into config.


Instruction:
Can you tell what is the following Python 3 function doing
def derive_from(cls, section, name=None):
        new_section = deepcopy(section)

        if name:
            new_section.name = name

        return new_section

Response: Create a new section based on the given section.


Instruction:
Write a Python 3 script to
validate sections types and uniqueness.

Response:
def _validate_sections(cls, sections):
        """Validates sections types and uniqueness."""
        names = []
        for section in sections:

            if not hasattr(section, 'name'):
                raise ConfigurationError('`sections` attribute requires a list of Section')

            name = section.name
            if name in names:
                raise ConfigurationError('`%s` section name must be unique' % name)

            names.append(name)


Instruction:
Can you create a Python 3 function that
applies formatting to configuration.

Response:
def format(self, do_print=False, stamp=True):
        """Applies formatting to configuration.

        *Currently formats to .ini*

        :param bool do_print: Whether to print out formatted config.
        :param bool stamp: Whether to add stamp data to the first configuration section.
        :rtype: str|unicode
        """
        if stamp and self.sections:
            self.sections[0].print_stamp()

        formatted = IniFormatter(self.sections).format()

        if do_print:
            print(formatted)

        return formatted


Instruction:
Here you have a function in Python 3, explain what it does
def tofile(self, filepath=None):
        if filepath is None:
            with NamedTemporaryFile(prefix='%s_' % self.alias, suffix='.ini', delete=False) as f:
                filepath = f.name

        else:
            filepath = os.path.abspath(filepath)

            if os.path.isdir(filepath):
                filepath = os.path.join(filepath, '%s.ini' % self.alias)

        with open(filepath, 'w') as target_file:
            target_file.write(self.format())
            target_file.flush()

        return filepath

Response: Saves the current configuration into a file and returns its path.


Instruction:
How would you implement a function in Python 3 that
sets the name of the object.

Response:
def _set_name(self, version=AUTO):
        """Returns plugin name."""

        name = 'python'

        if version:
            if version is AUTO:
                version = sys.version_info[0]

                if version == 2:
                    version = ''

            name = '%s%s' % (name, version)

        self.name = name


Instruction:
Write a Python 3 function for
setting sys. argv for python apps.

Response:
def set_app_args(self, *args):
        """Sets ``sys.argv`` for python apps.

        Examples:
            * pyargv="one two three" will set ``sys.argv`` to ``('one', 'two', 'three')``.

        :param args:
        """
        if args:
            self._set('pyargv', ' '.join(args))

        return self._section


Instruction:
Can you create a Python 3 function that
sets the wsgi related parameters.

Response:
def set_wsgi_params(self, module=None, callable_name=None, env_strategy=None):
        """Set wsgi related parameters.

        :param str|unicode module:
            * load .wsgi file as the Python application
            * load a WSGI module as the application.

            .. note:: The module (sans ``.py``) must be importable, ie. be in ``PYTHONPATH``.

            Examples:
                * mypackage.my_wsgi_module -- read from `application` attr of mypackage/my_wsgi_module.py
                * mypackage.my_wsgi_module:my_app -- read from `my_app` attr of mypackage/my_wsgi_module.py

        :param str|unicode callable_name: Set WSGI callable name. Default: application.

        :param str|unicode env_strategy: Strategy for allocating/deallocating
            the WSGI env, can be:

            * ``cheat`` - preallocates the env dictionary on uWSGI startup and clears it
                after each request. Default behaviour for uWSGI <= 2.0.x

            * ``holy`` - creates and destroys the environ dictionary at each request.
                Default behaviour for uWSGI >= 2.1

        """
        module = module or ''

        if '/' in module:
            self._set('wsgi-file', module, condition=module)

        else:
            self._set('wsgi', module, condition=module)

        self._set('callable', callable_name)
        self._set('wsgi-env-behaviour', env_strategy)

        return self._section


Instruction:
Make a summary of the following Python 3 code
def set_autoreload_params(self, scan_interval=None, ignore_modules=None):
        self._set('py-auto-reload', scan_interval)
        self._set('py-auto-reload-ignore', ignore_modules, multi=True)

        return self._section

Response: Sets autoreload related parameters.


Instruction:
Write a Python 3 function that can
add an alias for a module.

Response:
def register_module_alias(self, alias, module_path, after_init=False):
        """Adds an alias for a module.

        http://uwsgi-docs.readthedocs.io/en/latest/PythonModuleAlias.html

        :param str|unicode alias:
        :param str|unicode module_path:
        :param bool after_init: add a python module alias after uwsgi module initialization
        """
        command = 'post-pymodule-alias' if after_init else 'pymodule-alias'
        self._set(command, '%s=%s' % (alias, module_path), multi=True)

        return self._section


Instruction:
Given the following Python 3 function, write the documentation
def import_module(self, modules, shared=False, into_spooler=False):
        if all((shared, into_spooler)):
            raise ConfigurationError('Unable to set both `shared` and `into_spooler` flags')

        if into_spooler:
            command = 'spooler-python-import'
        else:
            command = 'shared-python-import' if shared else 'python-import'

        self._set(command, modules, multi=True)

        return self._section

Response: Imports a python module.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_server_params(
            self, client_notify_address=None, mountpoints_depth=None, require_vassal=None,
            tolerance=None, tolerance_inactive=None, key_dot_split=None):
        """Sets subscription server related params.

        :param str|unicode client_notify_address: Set the notification socket for subscriptions.
            When you subscribe to a server, you can ask it to "acknowledge" the acceptance of your request.
            pointing address (Unix socket or UDP), on which your instance will bind and
            the subscription server will send acknowledgements to.

        :param int mountpoints_depth: Enable support of mountpoints of certain depth for subscription system.

            * http://uwsgi-docs.readthedocs.io/en/latest/SubscriptionServer.html#mountpoints-uwsgi-2-1

        :param bool require_vassal: Require a vassal field (see ``subscribe``) from each subscription.

        :param int tolerance: Subscription reclaim tolerance (seconds).

        :param int tolerance_inactive: Subscription inactivity tolerance (seconds).

        :param bool key_dot_split: Try to fallback to the next part in (dot based) subscription key.
            Used, for example, in SNI.

        """
        # todo notify-socket (fallback) relation
        self._set('subscription-notify-socket', client_notify_address)
        self._set('subscription-mountpoint', mountpoints_depth)
        self._set('subscription-vassal-required', require_vassal, cast=bool)
        self._set('subscription-tolerance', tolerance)
        self._set('subscription-tolerance-inactive', tolerance_inactive)
        self._set('subscription-dotsplit', key_dot_split, cast=bool)

        return self._section

Response: Sets the server related params for the subscription server.


Instruction:
Write a Python 3 script for
setting peer verification params for subscription server.

Response:
def set_server_verification_params(
            self, digest_algo=None, dir_cert=None, tolerance=None, no_check_uid=None,
            dir_credentials=None, pass_unix_credentials=None):
        """Sets peer verification params for subscription server.

        These are for secured subscriptions.

        :param str|unicode digest_algo: Digest algorithm. Example: SHA1

            .. note:: Also requires ``dir_cert`` to be set.

        :param str|unicode dir_cert: Certificate directory.

            .. note:: Also requires ``digest_algo`` to be set.

        :param int tolerance: Maximum tolerance (in seconds) of clock skew for secured subscription system.
            Default: 24h.

        :param str|unicode|int|list[str|unicode|int] no_check_uid: Skip signature check for the specified uids
            when using unix sockets credentials.

        :param str|unicode|list[str|unicode] dir_credentials: Directories to search for subscriptions
            key credentials.

        :param bool pass_unix_credentials: Enable management of SCM_CREDENTIALS in subscriptions UNIX sockets.

        """
        if digest_algo and dir_cert:
            self._set('subscriptions-sign-check', '%s:%s' % (digest_algo, dir_cert))

        self._set('subscriptions-sign-check-tolerance', tolerance)
        self._set('subscriptions-sign-skip-uid', no_check_uid, multi=True)
        self._set('subscriptions-credentials-check', dir_credentials, multi=True)
        self._set('subscriptions-use-credentials', pass_unix_credentials, cast=bool)

        return self._section


Instruction:
Here you have a function in Python 3, explain what it does
def set_client_params(
            self, start_unsubscribed=None, clear_on_exit=None, unsubscribe_on_reload=None,
            announce_interval=None):
        """Sets subscribers related params.

        :param bool start_unsubscribed: Configure subscriptions but do not send them.
            .. note:: Useful with master FIFO.

        :param bool clear_on_exit: Force clear instead of unsubscribe during shutdown.

        :param bool unsubscribe_on_reload: Force unsubscribe request even during graceful reload.

        :param int announce_interval: Send subscription announce at the specified interval. Default: 10 master cycles.

        """
        self._set('start-unsubscribed', start_unsubscribed, cast=bool)
        self._set('subscription-clear-on-shutdown', clear_on_exit, cast=bool)
        self._set('unsubscribe-on-graceful-reload', unsubscribe_on_reload, cast=bool)
        self._set('subscribe-freq', announce_interval)

        return self._section

Response: Sets the client related params.